diff --git a/sdk/billing/azure-mgmt-billing/_meta.json b/sdk/billing/azure-mgmt-billing/_meta.json index 111c7a0612e3..d186ca9a66ca 100644 --- a/sdk/billing/azure-mgmt-billing/_meta.json +++ b/sdk/billing/azure-mgmt-billing/_meta.json @@ -1,8 +1,11 @@ { - "autorest": "3.3.0", - "use": "@autorest/python@5.6.6", - "commit": "1e43e60cfb0bb2829ff8d57a9ba06a2410f0b3c0", + "autorest": "3.9.2", + "use": [ + "@autorest/python@6.1.11", + "@autorest/modelerfour@4.24.3" + ], + "commit": "82a5d57725ad9f852b8d3a9dc3c558c803ac9321", "repository_url": "https://github.com/Azure/azure-rest-api-specs", - "autorest_command": "autorest specification/billing/resource-manager/readme.md --multiapi --python --python-mode=update --python-sdks-folder=/home/vsts/work/1/s/azure-sdk-for-python/sdk --track2 --use=@autorest/python@5.6.6 --version=3.3.0", + "autorest_command": "autorest specification/billing/resource-manager/readme.md --python --python-sdks-folder=/mnt/vss/_work/1/s/azure-sdk-for-python/sdk --use=@autorest/python@6.1.11 --use=@autorest/modelerfour@4.24.3 --version=3.9.2 --version-tolerant=False", "readme": "specification/billing/resource-manager/readme.md" } \ No newline at end of file diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/__init__.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/__init__.py index bfbe5e3f54d0..8b505014ae0b 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/__init__.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/__init__.py @@ -10,10 +10,15 @@ from ._version import VERSION __version__ = VERSION -__all__ = ['BillingManagementClient'] try: - from ._patch import patch_sdk # type: ignore - patch_sdk() + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import except ImportError: - pass + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["BillingManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/_billing_management_client.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/_billing_management_client.py index a1e2d429dd3b..7e4c78732354 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/_billing_management_client.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/_billing_management_client.py @@ -6,44 +6,45 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from copy import deepcopy +from typing import Any, TYPE_CHECKING +from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient -from msrest import Deserializer, Serializer + +from . import models +from ._configuration import BillingManagementClientConfiguration +from ._serialization import Deserializer, Serializer +from .operations import ( + AddressOperations, + AgreementsOperations, + AvailableBalancesOperations, + BillingAccountsOperations, + BillingPeriodsOperations, + BillingPermissionsOperations, + BillingProfilesOperations, + BillingPropertyOperations, + BillingRoleAssignmentsOperations, + BillingRoleDefinitionsOperations, + BillingSubscriptionsOperations, + CustomersOperations, + EnrollmentAccountsOperations, + InstructionsOperations, + InvoiceSectionsOperations, + InvoicesOperations, + Operations, + PoliciesOperations, + ProductsOperations, + ReservationsOperations, + TransactionsOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Optional - from azure.core.credentials import TokenCredential - from azure.core.pipeline.transport import HttpRequest, HttpResponse - -from ._configuration import BillingManagementClientConfiguration -from .operations import BillingAccountsOperations -from .operations import AddressOperations -from .operations import AvailableBalancesOperations -from .operations import InstructionsOperations -from .operations import BillingProfilesOperations -from .operations import CustomersOperations -from .operations import InvoiceSectionsOperations -from .operations import BillingPermissionsOperations -from .operations import BillingSubscriptionsOperations -from .operations import ProductsOperations -from .operations import InvoicesOperations -from .operations import TransactionsOperations -from .operations import PoliciesOperations -from .operations import BillingPropertyOperations -from .operations import Operations -from .operations import BillingRoleDefinitionsOperations -from .operations import BillingRoleAssignmentsOperations -from .operations import AgreementsOperations -from .operations import ReservationsOperations -from .operations import EnrollmentAccountsOperations -from .operations import BillingPeriodsOperations -from . import models -class BillingManagementClient(object): +class BillingManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes """Billing client provides access to billing resources for Azure subscriptions. :ivar billing_accounts: BillingAccountsOperations operations @@ -74,12 +75,12 @@ class BillingManagementClient(object): :vartype policies: azure.mgmt.billing.operations.PoliciesOperations :ivar billing_property: BillingPropertyOperations operations :vartype billing_property: azure.mgmt.billing.operations.BillingPropertyOperations - :ivar operations: Operations operations - :vartype operations: azure.mgmt.billing.operations.Operations :ivar billing_role_definitions: BillingRoleDefinitionsOperations operations - :vartype billing_role_definitions: azure.mgmt.billing.operations.BillingRoleDefinitionsOperations + :vartype billing_role_definitions: + azure.mgmt.billing.operations.BillingRoleDefinitionsOperations :ivar billing_role_assignments: BillingRoleAssignmentsOperations operations - :vartype billing_role_assignments: azure.mgmt.billing.operations.BillingRoleAssignmentsOperations + :vartype billing_role_assignments: + azure.mgmt.billing.operations.BillingRoleAssignmentsOperations :ivar agreements: AgreementsOperations operations :vartype agreements: azure.mgmt.billing.operations.AgreementsOperations :ivar reservations: ReservationsOperations operations @@ -88,92 +89,97 @@ class BillingManagementClient(object): :vartype enrollment_accounts: azure.mgmt.billing.operations.EnrollmentAccountsOperations :ivar billing_periods: BillingPeriodsOperations operations :vartype billing_periods: azure.mgmt.billing.operations.BillingPeriodsOperations - :param credential: Credential needed for the client to connect to Azure. + :ivar operations: Operations operations + :vartype operations: azure.mgmt.billing.operations.Operations + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID that uniquely identifies an Azure subscription. + :param subscription_id: The ID that uniquely identifies an Azure subscription. Required. :type subscription_id: str - :param str base_url: Service URL - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. """ def __init__( self, - credential, # type: "TokenCredential" - subscription_id, # type: str - base_url=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> None - if not base_url: - base_url = 'https://management.azure.com' - self._config = BillingManagementClientConfiguration(credential, subscription_id, **kwargs) + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = BillingManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - + self._serialize.client_side_validation = False self.billing_accounts = BillingAccountsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.address = AddressOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) + self.address = AddressOperations(self._client, self._config, self._serialize, self._deserialize) self.available_balances = AvailableBalancesOperations( - self._client, self._config, self._serialize, self._deserialize) - self.instructions = InstructionsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) + self.instructions = InstructionsOperations(self._client, self._config, self._serialize, self._deserialize) self.billing_profiles = BillingProfilesOperations( - self._client, self._config, self._serialize, self._deserialize) - self.customers = CustomersOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) + self.customers = CustomersOperations(self._client, self._config, self._serialize, self._deserialize) self.invoice_sections = InvoiceSectionsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.billing_permissions = BillingPermissionsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.billing_subscriptions = BillingSubscriptionsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.products = ProductsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.invoices = InvoicesOperations( - self._client, self._config, self._serialize, self._deserialize) - self.transactions = TransactionsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.policies = PoliciesOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) + self.products = ProductsOperations(self._client, self._config, self._serialize, self._deserialize) + self.invoices = InvoicesOperations(self._client, self._config, self._serialize, self._deserialize) + self.transactions = TransactionsOperations(self._client, self._config, self._serialize, self._deserialize) + self.policies = PoliciesOperations(self._client, self._config, self._serialize, self._deserialize) self.billing_property = BillingPropertyOperations( - self._client, self._config, self._serialize, self._deserialize) - self.operations = Operations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.billing_role_definitions = BillingRoleDefinitionsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.billing_role_assignments = BillingRoleAssignmentsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.agreements = AgreementsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.reservations = ReservationsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) + self.agreements = AgreementsOperations(self._client, self._config, self._serialize, self._deserialize) + self.reservations = ReservationsOperations(self._client, self._config, self._serialize, self._deserialize) self.enrollment_accounts = EnrollmentAccountsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.billing_periods = BillingPeriodsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) + self.billing_periods = BillingPeriodsOperations(self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) - def _send_request(self, http_request, **kwargs): - # type: (HttpRequest, Any) -> HttpResponse + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.HttpResponse + :rtype: ~azure.core.rest.HttpResponse """ - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) def close(self): # type: () -> None diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/_configuration.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/_configuration.py index fa9ff1d038d8..98ff01383d05 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/_configuration.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/_configuration.py @@ -6,65 +6,58 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any - from azure.core.credentials import TokenCredential -class BillingManagementClientConfiguration(Configuration): +class BillingManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for BillingManagementClient. Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID that uniquely identifies an Azure subscription. + :param subscription_id: The ID that uniquely identifies an Azure subscription. Required. :type subscription_id: str """ - def __init__( - self, - credential, # type: "TokenCredential" - subscription_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(BillingManagementClientConfiguration, self).__init__(**kwargs) if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(BillingManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-billing/{}'.format(VERSION)) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-billing/{}".format(VERSION)) self._configure(**kwargs) def _configure( - self, - **kwargs # type: Any + self, **kwargs # type: Any ): # type: (...) -> None - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/_metadata.json b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/_metadata.json deleted file mode 100644 index 7a518fc45a10..000000000000 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/_metadata.json +++ /dev/null @@ -1,123 +0,0 @@ -{ - "chosen_version": "", - "total_api_version_list": ["2018-03-01-preview", "2020-05-01"], - "client": { - "name": "BillingManagementClient", - "filename": "_billing_management_client", - "description": "Billing client provides access to billing resources for Azure subscriptions.", - "base_url": "\u0027https://management.azure.com\u0027", - "custom_base_url": null, - "azure_arm": true, - "has_lro_operations": true, - "client_side_validation": false, - "sync_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"ARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"BillingManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"HttpRequest\", \"HttpResponse\"]}}}", - "async_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"AsyncARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"BillingManagementClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"AsyncHttpResponse\", \"HttpRequest\"]}}}" - }, - "global_parameters": { - "sync": { - "credential": { - "signature": "credential, # type: \"TokenCredential\"", - "description": "Credential needed for the client to connect to Azure.", - "docstring_type": "~azure.core.credentials.TokenCredential", - "required": true - }, - "subscription_id": { - "signature": "subscription_id, # type: str", - "description": "The ID that uniquely identifies an Azure subscription.", - "docstring_type": "str", - "required": true - } - }, - "async": { - "credential": { - "signature": "credential: \"AsyncTokenCredential\",", - "description": "Credential needed for the client to connect to Azure.", - "docstring_type": "~azure.core.credentials_async.AsyncTokenCredential", - "required": true - }, - "subscription_id": { - "signature": "subscription_id: str,", - "description": "The ID that uniquely identifies an Azure subscription.", - "docstring_type": "str", - "required": true - } - }, - "constant": { - }, - "call": "credential, subscription_id", - "service_client_specific": { - "sync": { - "api_version": { - "signature": "api_version=None, # type: Optional[str]", - "description": "API version to use if no profile is provided, or if missing in profile.", - "docstring_type": "str", - "required": false - }, - "base_url": { - "signature": "base_url=None, # type: Optional[str]", - "description": "Service URL", - "docstring_type": "str", - "required": false - }, - "profile": { - "signature": "profile=KnownProfiles.default, # type: KnownProfiles", - "description": "A profile definition, from KnownProfiles to dict.", - "docstring_type": "azure.profiles.KnownProfiles", - "required": false - } - }, - "async": { - "api_version": { - "signature": "api_version: Optional[str] = None,", - "description": "API version to use if no profile is provided, or if missing in profile.", - "docstring_type": "str", - "required": false - }, - "base_url": { - "signature": "base_url: Optional[str] = None,", - "description": "Service URL", - "docstring_type": "str", - "required": false - }, - "profile": { - "signature": "profile: KnownProfiles = KnownProfiles.default,", - "description": "A profile definition, from KnownProfiles to dict.", - "docstring_type": "azure.profiles.KnownProfiles", - "required": false - } - } - } - }, - "config": { - "credential": true, - "credential_scopes": ["https://management.azure.com/.default"], - "credential_default_policy_type": "BearerTokenCredentialPolicy", - "credential_default_policy_type_has_async_version": true, - "credential_key_header_name": null, - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" - }, - "operation_groups": { - "billing_accounts": "BillingAccountsOperations", - "address": "AddressOperations", - "available_balances": "AvailableBalancesOperations", - "instructions": "InstructionsOperations", - "billing_profiles": "BillingProfilesOperations", - "customers": "CustomersOperations", - "invoice_sections": "InvoiceSectionsOperations", - "billing_permissions": "BillingPermissionsOperations", - "billing_subscriptions": "BillingSubscriptionsOperations", - "products": "ProductsOperations", - "invoices": "InvoicesOperations", - "transactions": "TransactionsOperations", - "policies": "PoliciesOperations", - "billing_property": "BillingPropertyOperations", - "operations": "Operations", - "billing_role_definitions": "BillingRoleDefinitionsOperations", - "billing_role_assignments": "BillingRoleAssignmentsOperations", - "agreements": "AgreementsOperations", - "reservations": "ReservationsOperations", - "enrollment_accounts": "EnrollmentAccountsOperations", - "billing_periods": "BillingPeriodsOperations" - } -} \ No newline at end of file diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/_patch.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/_serialization.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/_serialization.py new file mode 100644 index 000000000000..7c1dedb5133d --- /dev/null +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/_serialization.py @@ -0,0 +1,1970 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- + +# pylint: skip-file + +from base64 import b64decode, b64encode +import calendar +import datetime +import decimal +import email +from enum import Enum +import json +import logging +import re +import sys +import codecs + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote # type: ignore +import xml.etree.ElementTree as ET + +import isodate + +from typing import Dict, Any, cast, TYPE_CHECKING + +from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + +if TYPE_CHECKING: + from typing import Optional, Union, AnyStr, IO, Mapping + + +class RawDeserializer: + + # Accept "text" because we're open minded people... + JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") + + # Name used in context + CONTEXT_NAME = "deserialized_data" + + @classmethod + def deserialize_from_text(cls, data, content_type=None): + # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any + """Decode data according to content-type. + + Accept a stream of data as well, but will be load at once in memory for now. + + If no content-type, will return the string version (not bytes, not stream) + + :param data: Input, could be bytes or stream (will be decoded with UTF8) or text + :type data: str or bytes or IO + :param str content_type: The content type. + """ + if hasattr(data, "read"): + # Assume a stream + data = cast(IO, data).read() + + if isinstance(data, bytes): + data_as_str = data.decode(encoding="utf-8-sig") + else: + # Explain to mypy the correct type. + data_as_str = cast(str, data) + + # Remove Byte Order Mark if present in string + data_as_str = data_as_str.lstrip(_BOM) + + if content_type is None: + return data + + if cls.JSON_REGEXP.match(content_type): + try: + return json.loads(data_as_str) + except ValueError as err: + raise DeserializationError("JSON is invalid: {}".format(err), err) + elif "xml" in (content_type or []): + try: + + try: + if isinstance(data, unicode): # type: ignore + # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string + data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore + except NameError: + pass + + return ET.fromstring(data_as_str) # nosec + except ET.ParseError: + # It might be because the server has an issue, and returned JSON with + # content-type XML.... + # So let's try a JSON load, and if it's still broken + # let's flow the initial exception + def _json_attemp(data): + try: + return True, json.loads(data) + except ValueError: + return False, None # Don't care about this one + + success, json_result = _json_attemp(data) + if success: + return json_result + # If i'm here, it's not JSON, it's not XML, let's scream + # and raise the last context in this block (the XML exception) + # The function hack is because Py2.7 messes up with exception + # context otherwise. + _LOGGER.critical("Wasn't XML not JSON, failing") + raise_with_traceback(DeserializationError, "XML is invalid") + raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes, headers): + # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any + """Deserialize from HTTP response. + + Use bytes and headers to NOT use any requests/aiohttp or whatever + specific implementation. + Headers will tested for "content-type" + """ + # Try to use content-type from headers if available + content_type = None + if "content-type" in headers: + content_type = headers["content-type"].split(";")[0].strip().lower() + # Ouch, this server did not declare what it sent... + # Let's guess it's JSON... + # Also, since Autorest was considering that an empty body was a valid JSON, + # need that test as well.... + else: + content_type = "application/json" + + if body_bytes: + return cls.deserialize_from_text(body_bytes, content_type) + return None + + +try: + basestring # type: ignore + unicode_str = unicode # type: ignore +except NameError: + basestring = str # type: ignore + unicode_str = str # type: ignore + +_LOGGER = logging.getLogger(__name__) + +try: + _long_type = long # type: ignore +except NameError: + _long_type = int + + +class UTC(datetime.tzinfo): + """Time Zone info for handling UTC""" + + def utcoffset(self, dt): + """UTF offset for UTC is 0.""" + return datetime.timedelta(0) + + def tzname(self, dt): + """Timestamp representation.""" + return "Z" + + def dst(self, dt): + """No daylight saving for UTC.""" + return datetime.timedelta(hours=1) + + +try: + from datetime import timezone as _FixedOffset +except ImportError: # Python 2.7 + + class _FixedOffset(datetime.tzinfo): # type: ignore + """Fixed offset in minutes east from UTC. + Copy/pasted from Python doc + :param datetime.timedelta offset: offset in timedelta format + """ + + def __init__(self, offset): + self.__offset = offset + + def utcoffset(self, dt): + return self.__offset + + def tzname(self, dt): + return str(self.__offset.total_seconds() / 3600) + + def __repr__(self): + return "".format(self.tzname(None)) + + def dst(self, dt): + return datetime.timedelta(0) + + def __getinitargs__(self): + return (self.__offset,) + + +try: + from datetime import timezone + + TZ_UTC = timezone.utc # type: ignore +except ImportError: + TZ_UTC = UTC() # type: ignore + +_FLATTEN = re.compile(r"(? y, + "minimum": lambda x, y: x < y, + "maximum": lambda x, y: x > y, + "minimum_ex": lambda x, y: x <= y, + "maximum_ex": lambda x, y: x >= y, + "min_items": lambda x, y: len(x) < y, + "max_items": lambda x, y: len(x) > y, + "pattern": lambda x, y: not re.match(y, x, re.UNICODE), + "unique": lambda x, y: len(x) != len(set(x)), + "multiple": lambda x, y: x % y != 0, + } + + def __init__(self, classes=None): + self.serialize_type = { + "iso-8601": Serializer.serialize_iso, + "rfc-1123": Serializer.serialize_rfc, + "unix-time": Serializer.serialize_unix, + "duration": Serializer.serialize_duration, + "date": Serializer.serialize_date, + "time": Serializer.serialize_time, + "decimal": Serializer.serialize_decimal, + "long": Serializer.serialize_long, + "bytearray": Serializer.serialize_bytearray, + "base64": Serializer.serialize_base64, + "object": self.serialize_object, + "[]": self.serialize_iter, + "{}": self.serialize_dict, + } + self.dependencies = dict(classes) if classes else {} + self.key_transformer = full_restapi_key_transformer + self.client_side_validation = True + + def _serialize(self, target_obj, data_type=None, **kwargs): + """Serialize data into a string according to type. + + :param target_obj: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, dict + :raises: SerializationError if serialization fails. + """ + key_transformer = kwargs.get("key_transformer", self.key_transformer) + keep_readonly = kwargs.get("keep_readonly", False) + if target_obj is None: + return None + + attr_name = None + class_name = target_obj.__class__.__name__ + + if data_type: + return self.serialize_data(target_obj, data_type, **kwargs) + + if not hasattr(target_obj, "_attribute_map"): + data_type = type(target_obj).__name__ + if data_type in self.basic_types.values(): + return self.serialize_data(target_obj, data_type, **kwargs) + + # Force "is_xml" kwargs if we detect a XML model + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) + + serialized = {} + if is_xml_model_serialization: + serialized = target_obj._create_xml_node() + try: + attributes = target_obj._attribute_map + for attr, attr_desc in attributes.items(): + attr_name = attr + if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): + continue + + if attr_name == "additional_properties" and attr_desc["key"] == "": + if target_obj.additional_properties is not None: + serialized.update(target_obj.additional_properties) + continue + try: + + orig_attr = getattr(target_obj, attr) + if is_xml_model_serialization: + pass # Don't provide "transformer" for XML for now. Keep "orig_attr" + else: # JSON + keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) + keys = keys if isinstance(keys, list) else [keys] + + kwargs["serialization_ctxt"] = attr_desc + new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) + + if is_xml_model_serialization: + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + xml_prefix = xml_desc.get("prefix", None) + xml_ns = xml_desc.get("ns", None) + if xml_desc.get("attr", False): + if xml_ns: + ET.register_namespace(xml_prefix, xml_ns) + xml_name = "{}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) + continue + if xml_desc.get("text", False): + serialized.text = new_attr + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) + elif isinstance(new_attr, ET.Element): + # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. + if "name" not in getattr(orig_attr, "_xml_map", {}): + splitted_tag = new_attr.tag.split("}") + if len(splitted_tag) == 2: # Namespace + new_attr.tag = "}".join([splitted_tag[0], xml_name]) + else: + new_attr.tag = xml_name + serialized.append(new_attr) + else: # That's a basic type + # Integrate namespace if necessary + local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) + local_node.text = unicode_str(new_attr) + serialized.append(local_node) + else: # JSON + for k in reversed(keys): + unflattened = {k: new_attr} + new_attr = unflattened + + _new_attr = new_attr + _serialized = serialized + for k in keys: + if k not in _serialized: + _serialized.update(_new_attr) + _new_attr = _new_attr[k] + _serialized = _serialized[k] + except ValueError: + continue + + except (AttributeError, KeyError, TypeError) as err: + msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) + raise_with_traceback(SerializationError, msg, err) + else: + return serialized + + def body(self, data, data_type, **kwargs): + """Serialize data intended for a request body. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: dict + :raises: SerializationError if serialization fails. + :raises: ValueError if data is None + """ + + # Just in case this is a dict + internal_data_type = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type, None) + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + if internal_data_type and issubclass(internal_data_type, Model): + is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) + else: + is_xml_model_serialization = False + if internal_data_type and not isinstance(internal_data_type, Enum): + try: + deserializer = Deserializer(self.dependencies) + # Since it's on serialization, it's almost sure that format is not JSON REST + # We're not able to deal with additional properties for now. + deserializer.additional_properties_detection = False + if is_xml_model_serialization: + deserializer.key_extractors = [ + attribute_key_case_insensitive_extractor, + ] + else: + deserializer.key_extractors = [ + rest_key_case_insensitive_extractor, + attribute_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + data = deserializer._deserialize(data_type, data) + except DeserializationError as err: + raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) + + return self._serialize(data, data_type, **kwargs) + + def url(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL path. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return output + + def query(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL query. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + # Treat the list aside, since we don't want to encode the div separator + if data_type.startswith("["): + internal_data_type = data_type[1:-1] + data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] + if not kwargs.get("skip_quote", False): + data = [quote(str(d), safe="") for d in data] + return str(self.serialize_iter(data, internal_data_type, **kwargs)) + + # Not a list, regular serialization + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return str(output) + + def header(self, name, data, data_type, **kwargs): + """Serialize data intended for a request header. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + if data_type in ["[str]"]: + data = ["" if d is None else d for d in data] + + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return str(output) + + def serialize_data(self, data, data_type, **kwargs): + """Serialize generic data according to supplied data type. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :param bool required: Whether it's essential that the data not be + empty or None + :raises: AttributeError if required data is None. + :raises: ValueError if data is None + :raises: SerializationError if serialization fails. + """ + if data is None: + raise ValueError("No value for given attribute") + + try: + if data_type in self.basic_types.values(): + return self.serialize_basic(data, data_type, **kwargs) + + elif data_type in self.serialize_type: + return self.serialize_type[data_type](data, **kwargs) + + # If dependencies is empty, try with current data class + # It has to be a subclass of Enum anyway + enum_type = self.dependencies.get(data_type, data.__class__) + if issubclass(enum_type, Enum): + return Serializer.serialize_enum(data, enum_obj=enum_type) + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.serialize_type: + return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) + + except (ValueError, TypeError) as err: + msg = "Unable to serialize value: {!r} as type: {!r}." + raise_with_traceback(SerializationError, msg.format(data, data_type), err) + else: + return self._serialize(data, **kwargs) + + @classmethod + def _get_custom_serializers(cls, data_type, **kwargs): + custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) + if custom_serializer: + return custom_serializer + if kwargs.get("is_xml", False): + return cls._xml_basic_types_serializers.get(data_type) + + @classmethod + def serialize_basic(cls, data, data_type, **kwargs): + """Serialize basic builting data type. + Serializes objects to str, int, float or bool. + + Possible kwargs: + - basic_types_serializers dict[str, callable] : If set, use the callable as serializer + - is_xml bool : If set, use xml_basic_types_serializers + + :param data: Object to be serialized. + :param str data_type: Type of object in the iterable. + """ + custom_serializer = cls._get_custom_serializers(data_type, **kwargs) + if custom_serializer: + return custom_serializer(data) + if data_type == "str": + return cls.serialize_unicode(data) + return eval(data_type)(data) # nosec + + @classmethod + def serialize_unicode(cls, data): + """Special handling for serializing unicode strings in Py2. + Encode to UTF-8 if unicode, otherwise handle as a str. + + :param data: Object to be serialized. + :rtype: str + """ + try: # If I received an enum, return its value + return data.value + except AttributeError: + pass + + try: + if isinstance(data, unicode): + # Don't change it, JSON and XML ElementTree are totally able + # to serialize correctly u'' strings + return data + except NameError: + return str(data) + else: + return str(data) + + def serialize_iter(self, data, iter_type, div=None, **kwargs): + """Serialize iterable. + + Supported kwargs: + - serialization_ctxt dict : The current entry of _attribute_map, or same format. + serialization_ctxt['type'] should be same as data_type. + - is_xml bool : If set, serialize as XML + + :param list attr: Object to be serialized. + :param str iter_type: Type of object in the iterable. + :param bool required: Whether the objects in the iterable must + not be None or empty. + :param str div: If set, this str will be used to combine the elements + in the iterable into a combined string. Default is 'None'. + :rtype: list, str + """ + if isinstance(data, str): + raise SerializationError("Refuse str type as a valid iter type.") + + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + is_xml = kwargs.get("is_xml", False) + + serialized = [] + for d in data: + try: + serialized.append(self.serialize_data(d, iter_type, **kwargs)) + except ValueError: + serialized.append(None) + + if div: + serialized = ["" if s is None else str(s) for s in serialized] + serialized = div.join(serialized) + + if "xml" in serialization_ctxt or is_xml: + # XML serialization is more complicated + xml_desc = serialization_ctxt.get("xml", {}) + xml_name = xml_desc.get("name") + if not xml_name: + xml_name = serialization_ctxt["key"] + + # Create a wrap node if necessary (use the fact that Element and list have "append") + is_wrapped = xml_desc.get("wrapped", False) + node_name = xml_desc.get("itemsName", xml_name) + if is_wrapped: + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + else: + final_result = [] + # All list elements to "local_node" + for el in serialized: + if isinstance(el, ET.Element): + el_node = el + else: + el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + if el is not None: # Otherwise it writes "None" :-p + el_node.text = str(el) + final_result.append(el_node) + return final_result + return serialized + + def serialize_dict(self, attr, dict_type, **kwargs): + """Serialize a dictionary of objects. + + :param dict attr: Object to be serialized. + :param str dict_type: Type of object in the dictionary. + :param bool required: Whether the objects in the dictionary must + not be None or empty. + :rtype: dict + """ + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + + if "xml" in serialization_ctxt: + # XML serialization is more complicated + xml_desc = serialization_ctxt["xml"] + xml_name = xml_desc["name"] + + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + for key, value in serialized.items(): + ET.SubElement(final_result, key).text = value + return final_result + + return serialized + + def serialize_object(self, attr, **kwargs): + """Serialize a generic object. + This will be handled as a dictionary. If object passed in is not + a basic type (str, int, float, dict, list) it will simply be + cast to str. + + :param dict attr: Object to be serialized. + :rtype: dict or str + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + return attr + obj_type = type(attr) + if obj_type in self.basic_types: + return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) + if obj_type is _long_type: + return self.serialize_long(attr) + if obj_type is unicode_str: + return self.serialize_unicode(attr) + if obj_type is datetime.datetime: + return self.serialize_iso(attr) + if obj_type is datetime.date: + return self.serialize_date(attr) + if obj_type is datetime.time: + return self.serialize_time(attr) + if obj_type is datetime.timedelta: + return self.serialize_duration(attr) + if obj_type is decimal.Decimal: + return self.serialize_decimal(attr) + + # If it's a model or I know this dependency, serialize as a Model + elif obj_type in self.dependencies.values() or isinstance(attr, Model): + return self._serialize(attr) + + if obj_type == dict: + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + return serialized + + if obj_type == list: + serialized = [] + for obj in attr: + try: + serialized.append(self.serialize_object(obj, **kwargs)) + except ValueError: + pass + return serialized + return str(attr) + + @staticmethod + def serialize_enum(attr, enum_obj=None): + try: + result = attr.value + except AttributeError: + result = attr + try: + enum_obj(result) + return result + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(attr).lower(): + return enum_value.value + error = "{!r} is not valid value for enum {!r}" + raise SerializationError(error.format(attr, enum_obj)) + + @staticmethod + def serialize_bytearray(attr, **kwargs): + """Serialize bytearray into base-64 string. + + :param attr: Object to be serialized. + :rtype: str + """ + return b64encode(attr).decode() + + @staticmethod + def serialize_base64(attr, **kwargs): + """Serialize str into base-64 string. + + :param attr: Object to be serialized. + :rtype: str + """ + encoded = b64encode(attr).decode("ascii") + return encoded.strip("=").replace("+", "-").replace("/", "_") + + @staticmethod + def serialize_decimal(attr, **kwargs): + """Serialize Decimal object to float. + + :param attr: Object to be serialized. + :rtype: float + """ + return float(attr) + + @staticmethod + def serialize_long(attr, **kwargs): + """Serialize long (Py2) or int (Py3). + + :param attr: Object to be serialized. + :rtype: int/long + """ + return _long_type(attr) + + @staticmethod + def serialize_date(attr, **kwargs): + """Serialize Date object into ISO-8601 formatted string. + + :param Date attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_date(attr) + t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) + return t + + @staticmethod + def serialize_time(attr, **kwargs): + """Serialize Time object into ISO-8601 formatted string. + + :param datetime.time attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_time(attr) + t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) + if attr.microsecond: + t += ".{:02}".format(attr.microsecond) + return t + + @staticmethod + def serialize_duration(attr, **kwargs): + """Serialize TimeDelta object into ISO-8601 formatted string. + + :param TimeDelta attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + return isodate.duration_isoformat(attr) + + @staticmethod + def serialize_rfc(attr, **kwargs): + """Serialize Datetime object into RFC-1123 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises: TypeError if format invalid. + """ + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + except AttributeError: + raise TypeError("RFC1123 object must be valid Datetime object.") + + return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( + Serializer.days[utc.tm_wday], + utc.tm_mday, + Serializer.months[utc.tm_mon], + utc.tm_year, + utc.tm_hour, + utc.tm_min, + utc.tm_sec, + ) + + @staticmethod + def serialize_iso(attr, **kwargs): + """Serialize Datetime object into ISO-8601 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises: SerializationError if format invalid. + """ + if isinstance(attr, str): + attr = isodate.parse_datetime(attr) + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + if utc.tm_year > 9999 or utc.tm_year < 1: + raise OverflowError("Hit max or min date") + + microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") + if microseconds: + microseconds = "." + microseconds + date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + ) + return date + microseconds + "Z" + except (ValueError, OverflowError) as err: + msg = "Unable to serialize datetime object." + raise_with_traceback(SerializationError, msg, err) + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise_with_traceback(TypeError, msg, err) + + @staticmethod + def serialize_unix(attr, **kwargs): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param Datetime attr: Object to be serialized. + :rtype: int + :raises: SerializationError if format invalid + """ + if isinstance(attr, int): + return attr + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + return int(calendar.timegm(attr.utctimetuple())) + except AttributeError: + raise TypeError("Unix time object must be valid Datetime object.") + + +def rest_key_extractor(attr, attr_desc, data): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = working_data.get(working_key, data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + # https://github.com/Azure/msrest-for-python/issues/197 + return None + key = ".".join(dict_keys[1:]) + + return working_data.get(key) + + +def rest_key_case_insensitive_extractor(attr, attr_desc, data): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + # https://github.com/Azure/msrest-for-python/issues/197 + return None + key = ".".join(dict_keys[1:]) + + if working_data: + return attribute_key_case_insensitive_extractor(key, None, working_data) + + +def last_rest_key_extractor(attr, attr_desc, data): + """Extract the attribute in "data" based on the last part of the JSON path key.""" + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_extractor(dict_keys[-1], None, data) + + +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): + """Extract the attribute in "data" based on the last part of the JSON path key. + + This is the case insensitive version of "last_rest_key_extractor" + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) + + +def attribute_key_extractor(attr, _, data): + return data.get(attr) + + +def attribute_key_case_insensitive_extractor(attr, _, data): + found_key = None + lower_attr = attr.lower() + for key in data: + if lower_attr == key.lower(): + found_key = key + break + + return data.get(found_key) + + +def _extract_name_from_internal_type(internal_type): + """Given an internal type XML description, extract correct XML name with namespace. + + :param dict internal_type: An model type + :rtype: tuple + :returns: A tuple XML name + namespace dict + """ + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + xml_name = internal_type_xml_map.get("name", internal_type.__name__) + xml_ns = internal_type_xml_map.get("ns", None) + if xml_ns: + xml_name = "{}{}".format(xml_ns, xml_name) + return xml_name + + +def xml_key_extractor(attr, attr_desc, data): + if isinstance(data, dict): + return None + + # Test if this model is XML ready first + if not isinstance(data, ET.Element): + return None + + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + + # Look for a children + is_iter_type = attr_desc["type"].startswith("[") + is_wrapped = xml_desc.get("wrapped", False) + internal_type = attr_desc.get("internalType", None) + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + + # Integrate namespace if necessary + xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) + if xml_ns: + xml_name = "{}{}".format(xml_ns, xml_name) + + # If it's an attribute, that's simple + if xml_desc.get("attr", False): + return data.get(xml_name) + + # If it's x-ms-text, that's simple too + if xml_desc.get("text", False): + return data.text + + # Scenario where I take the local name: + # - Wrapped node + # - Internal type is an enum (considered basic types) + # - Internal type has no XML/Name node + if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): + children = data.findall(xml_name) + # If internal type has a local name and it's not a list, I use that name + elif not is_iter_type and internal_type and "name" in internal_type_xml_map: + xml_name = _extract_name_from_internal_type(internal_type) + children = data.findall(xml_name) + # That's an array + else: + if internal_type: # Complex type, ignore itemsName and use the complex type name + items_name = _extract_name_from_internal_type(internal_type) + else: + items_name = xml_desc.get("itemsName", xml_name) + children = data.findall(items_name) + + if len(children) == 0: + if is_iter_type: + if is_wrapped: + return None # is_wrapped no node, we want None + else: + return [] # not wrapped, assume empty list + return None # Assume it's not there, maybe an optional node. + + # If is_iter_type and not wrapped, return all found children + if is_iter_type: + if not is_wrapped: + return children + else: # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name + ) + ) + return list(children[0]) # Might be empty list and that's ok. + + # Here it's not a itertype, we should have found one element only or empty + if len(children) > 1: + raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) + return children[0] + + +class Deserializer(object): + """Response object model deserializer. + + :param dict classes: Class type dictionary for deserializing complex types. + :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. + """ + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + + def __init__(self, classes=None): + self.deserialize_type = { + "iso-8601": Deserializer.deserialize_iso, + "rfc-1123": Deserializer.deserialize_rfc, + "unix-time": Deserializer.deserialize_unix, + "duration": Deserializer.deserialize_duration, + "date": Deserializer.deserialize_date, + "time": Deserializer.deserialize_time, + "decimal": Deserializer.deserialize_decimal, + "long": Deserializer.deserialize_long, + "bytearray": Deserializer.deserialize_bytearray, + "base64": Deserializer.deserialize_base64, + "object": self.deserialize_object, + "[]": self.deserialize_iter, + "{}": self.deserialize_dict, + } + self.deserialize_expected_types = { + "duration": (isodate.Duration, datetime.timedelta), + "iso-8601": (datetime.datetime), + } + self.dependencies = dict(classes) if classes else {} + self.key_extractors = [rest_key_extractor, xml_key_extractor] + # Additional properties only works if the "rest_key_extractor" is used to + # extract the keys. Making it to work whatever the key extractor is too much + # complicated, with no real scenario for now. + # So adding a flag to disable additional properties detection. This flag should be + # used if your expect the deserialization to NOT come from a JSON REST syntax. + # Otherwise, result are unexpected + self.additional_properties_detection = True + + def __call__(self, target_obj, response_data, content_type=None): + """Call the deserializer to process a REST response. + + :param str target_obj: Target data type to deserialize to. + :param requests.Response response_data: REST response object. + :param str content_type: Swagger "produces" if available. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + data = self._unpack_content(response_data, content_type) + return self._deserialize(target_obj, data) + + def _deserialize(self, target_obj, data): + """Call the deserializer on a model. + + Data needs to be already deserialized as JSON or XML ElementTree + + :param str target_obj: Target data type to deserialize to. + :param object data: Object to deserialize. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + # This is already a model, go recursive just in case + if hasattr(data, "_attribute_map"): + constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] + try: + for attr, mapconfig in data._attribute_map.items(): + if attr in constants: + continue + value = getattr(data, attr) + if value is None: + continue + local_type = mapconfig["type"] + internal_data_type = local_type.strip("[]{}") + if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): + continue + setattr(data, attr, self._deserialize(local_type, value)) + return data + except AttributeError: + return + + response, class_name = self._classify_target(target_obj, data) + + if isinstance(response, basestring): + return self.deserialize_data(data, response) + elif isinstance(response, type) and issubclass(response, Enum): + return self.deserialize_enum(data, response) + + if data is None: + return data + try: + attributes = response._attribute_map + d_attrs = {} + for attr, attr_desc in attributes.items(): + # Check empty string. If it's not empty, someone has a real "additionalProperties"... + if attr == "additional_properties" and attr_desc["key"] == "": + continue + raw_value = None + # Enhance attr_desc with some dynamic data + attr_desc = attr_desc.copy() # Do a copy, do not change the real one + internal_data_type = attr_desc["type"].strip("[]{}") + if internal_data_type in self.dependencies: + attr_desc["internalType"] = self.dependencies[internal_data_type] + + for key_extractor in self.key_extractors: + found_value = key_extractor(attr, attr_desc, data) + if found_value is not None: + if raw_value is not None and raw_value != found_value: + msg = ( + "Ignoring extracted value '%s' from %s for key '%s'" + " (duplicate extraction, follow extractors order)" + ) + _LOGGER.warning(msg, found_value, key_extractor, attr) + continue + raw_value = found_value + + value = self.deserialize_data(raw_value, attr_desc["type"]) + d_attrs[attr] = value + except (AttributeError, TypeError, KeyError) as err: + msg = "Unable to deserialize to object: " + class_name + raise_with_traceback(DeserializationError, msg, err) + else: + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) + + def _build_additional_properties(self, attribute_map, data): + if not self.additional_properties_detection: + return None + if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": + # Check empty string. If it's not empty, someone has a real "additionalProperties" + return None + if isinstance(data, ET.Element): + data = {el.tag: el.text for el in data} + + known_keys = { + _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) + for desc in attribute_map.values() + if desc["key"] != "" + } + present_keys = set(data.keys()) + missing_keys = present_keys - known_keys + return {key: data[key] for key in missing_keys} + + def _classify_target(self, target, data): + """Check to see whether the deserialization target object can + be classified into a subclass. + Once classification has been determined, initialize object. + + :param str target: The target object type to deserialize to. + :param str/dict data: The response data to deseralize. + """ + if target is None: + return None, None + + if isinstance(target, basestring): + try: + target = self.dependencies[target] + except KeyError: + return target, target + + try: + target = target._classify(data, self.dependencies) + except AttributeError: + pass # Target is not a Model, no classify + return target, target.__class__.__name__ + + def failsafe_deserialize(self, target_obj, data, content_type=None): + """Ignores any errors encountered in deserialization, + and falls back to not deserializing the object. Recommended + for use in error deserialization, as we want to return the + HttpResponseError to users, and not have them deal with + a deserialization error. + + :param str target_obj: The target object type to deserialize to. + :param str/dict data: The response data to deseralize. + :param str content_type: Swagger "produces" if available. + """ + try: + return self(target_obj, data, content_type=content_type) + except: + _LOGGER.debug( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + @staticmethod + def _unpack_content(raw_data, content_type=None): + """Extract the correct structure for deserialization. + + If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. + if we can't, raise. Your Pipeline should have a RawDeserializer. + + If not a pipeline response and raw_data is bytes or string, use content-type + to decode it. If no content-type, try JSON. + + If raw_data is something else, bypass all logic and return it directly. + + :param raw_data: Data to be processed. + :param content_type: How to parse if raw_data is a string/bytes. + :raises JSONDecodeError: If JSON is requested and parsing is impossible. + :raises UnicodeDecodeError: If bytes is not UTF8 + """ + # Assume this is enough to detect a Pipeline Response without importing it + context = getattr(raw_data, "context", {}) + if context: + if RawDeserializer.CONTEXT_NAME in context: + return context[RawDeserializer.CONTEXT_NAME] + raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") + + # Assume this is enough to recognize universal_http.ClientResponse without importing it + if hasattr(raw_data, "body"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) + + # Assume this enough to recognize requests.Response without importing it. + if hasattr(raw_data, "_content_consumed"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) + + if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) + return raw_data + + def _instantiate_model(self, response, attrs, additional_properties=None): + """Instantiate a response model passing in deserialized args. + + :param response: The response model class. + :param d_attrs: The deserialized response attributes. + """ + if callable(response): + subtype = getattr(response, "_subtype_map", {}) + try: + readonly = [k for k, v in response._validation.items() if v.get("readonly")] + const = [k for k, v in response._validation.items() if v.get("constant")] + kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} + response_obj = response(**kwargs) + for attr in readonly: + setattr(response_obj, attr, attrs.get(attr)) + if additional_properties: + response_obj.additional_properties = additional_properties + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) + raise DeserializationError(msg + str(err)) + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) + + def deserialize_data(self, data, data_type): + """Process data for deserialization according to data type. + + :param str data: The response string to be deserialized. + :param str data_type: The type to deserialize to. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + if data is None: + return data + + try: + if not data_type: + return data + if data_type in self.basic_types.values(): + return self.deserialize_basic(data, data_type) + if data_type in self.deserialize_type: + if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): + return data + + is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] + if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: + return None + data_val = self.deserialize_type[data_type](data) + return data_val + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.deserialize_type: + return self.deserialize_type[iter_type](data, data_type[1:-1]) + + obj_type = self.dependencies[data_type] + if issubclass(obj_type, Enum): + if isinstance(data, ET.Element): + data = data.text + return self.deserialize_enum(data, obj_type) + + except (ValueError, TypeError, AttributeError) as err: + msg = "Unable to deserialize response data." + msg += " Data: {}, {}".format(data, data_type) + raise_with_traceback(DeserializationError, msg, err) + else: + return self._deserialize(obj_type, data) + + def deserialize_iter(self, attr, iter_type): + """Deserialize an iterable. + + :param list attr: Iterable to be deserialized. + :param str iter_type: The type of object in the iterable. + :rtype: list + """ + if attr is None: + return None + if isinstance(attr, ET.Element): # If I receive an element here, get the children + attr = list(attr) + if not isinstance(attr, (list, set)): + raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) + return [self.deserialize_data(a, iter_type) for a in attr] + + def deserialize_dict(self, attr, dict_type): + """Deserialize a dictionary. + + :param dict/list attr: Dictionary to be deserialized. Also accepts + a list of key, value pairs. + :param str dict_type: The object type of the items in the dictionary. + :rtype: dict + """ + if isinstance(attr, list): + return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} + + if isinstance(attr, ET.Element): + # Transform value into {"Key": "value"} + attr = {el.tag: el.text for el in attr} + return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} + + def deserialize_object(self, attr, **kwargs): + """Deserialize a generic object. + This will be handled as a dictionary. + + :param dict attr: Dictionary to be deserialized. + :rtype: dict + :raises: TypeError if non-builtin datatype encountered. + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + # Do no recurse on XML, just return the tree as-is + return attr + if isinstance(attr, basestring): + return self.deserialize_basic(attr, "str") + obj_type = type(attr) + if obj_type in self.basic_types: + return self.deserialize_basic(attr, self.basic_types[obj_type]) + if obj_type is _long_type: + return self.deserialize_long(attr) + + if obj_type == dict: + deserialized = {} + for key, value in attr.items(): + try: + deserialized[key] = self.deserialize_object(value, **kwargs) + except ValueError: + deserialized[key] = None + return deserialized + + if obj_type == list: + deserialized = [] + for obj in attr: + try: + deserialized.append(self.deserialize_object(obj, **kwargs)) + except ValueError: + pass + return deserialized + + else: + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) + + def deserialize_basic(self, attr, data_type): + """Deserialize basic builtin data type from string. + Will attempt to convert to str, int, float and bool. + This function will also accept '1', '0', 'true' and 'false' as + valid bool values. + + :param str attr: response string to be deserialized. + :param str data_type: deserialization data type. + :rtype: str, int, float or bool + :raises: TypeError if string format is not valid. + """ + # If we're here, data is supposed to be a basic type. + # If it's still an XML node, take the text + if isinstance(attr, ET.Element): + attr = attr.text + if not attr: + if data_type == "str": + # None or '', node is empty string. + return "" + else: + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None + + if data_type == "bool": + if attr in [True, False, 1, 0]: + return bool(attr) + elif isinstance(attr, basestring): + if attr.lower() in ["true", "1"]: + return True + elif attr.lower() in ["false", "0"]: + return False + raise TypeError("Invalid boolean value: {}".format(attr)) + + if data_type == "str": + return self.deserialize_unicode(attr) + return eval(data_type)(attr) # nosec + + @staticmethod + def deserialize_unicode(data): + """Preserve unicode objects in Python 2, otherwise return data + as a string. + + :param str data: response string to be deserialized. + :rtype: str or unicode + """ + # We might be here because we have an enum modeled as string, + # and we try to deserialize a partial dict with enum inside + if isinstance(data, Enum): + return data + + # Consider this is real string + try: + if isinstance(data, unicode): + return data + except NameError: + return str(data) + else: + return str(data) + + @staticmethod + def deserialize_enum(data, enum_obj): + """Deserialize string into enum object. + + If the string is not a valid enum value it will be returned as-is + and a warning will be logged. + + :param str data: Response string to be deserialized. If this value is + None or invalid it will be returned as-is. + :param Enum enum_obj: Enum object to deserialize to. + :rtype: Enum + """ + if isinstance(data, enum_obj) or data is None: + return data + if isinstance(data, Enum): + data = data.value + if isinstance(data, int): + # Workaround. We might consider remove it in the future. + # https://github.com/Azure/azure-rest-api-specs/issues/141 + try: + return list(enum_obj.__members__.values())[data] + except IndexError: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) + try: + return enum_obj(str(data)) + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(data).lower(): + return enum_value + # We don't fail anymore for unknown value, we deserialize as a string + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) + return Deserializer.deserialize_unicode(data) + + @staticmethod + def deserialize_bytearray(attr): + """Deserialize string into bytearray. + + :param str attr: response string to be deserialized. + :rtype: bytearray + :raises: TypeError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return bytearray(b64decode(attr)) + + @staticmethod + def deserialize_base64(attr): + """Deserialize base64 encoded string into string. + + :param str attr: response string to be deserialized. + :rtype: bytearray + :raises: TypeError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + padding = "=" * (3 - (len(attr) + 3) % 4) + attr = attr + padding + encoded = attr.replace("-", "+").replace("_", "/") + return b64decode(encoded) + + @staticmethod + def deserialize_decimal(attr): + """Deserialize string into Decimal object. + + :param str attr: response string to be deserialized. + :rtype: Decimal + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + return decimal.Decimal(attr) + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise_with_traceback(DeserializationError, msg, err) + + @staticmethod + def deserialize_long(attr): + """Deserialize string into long (Py2) or int (Py3). + + :param str attr: response string to be deserialized. + :rtype: long or int + :raises: ValueError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return _long_type(attr) + + @staticmethod + def deserialize_duration(attr): + """Deserialize ISO-8601 formatted string into TimeDelta object. + + :param str attr: response string to be deserialized. + :rtype: TimeDelta + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = isodate.parse_duration(attr) + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize duration object." + raise_with_traceback(DeserializationError, msg, err) + else: + return duration + + @staticmethod + def deserialize_date(attr): + """Deserialize ISO-8601 formatted string into Date object. + + :param str attr: response string to be deserialized. + :rtype: Date + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + return isodate.parse_date(attr, defaultmonth=None, defaultday=None) + + @staticmethod + def deserialize_time(attr): + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :rtype: datetime.time + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + return isodate.parse_time(attr) + + @staticmethod + def deserialize_rfc(attr): + """Deserialize RFC-1123 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: Datetime + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + parsed_date = email.utils.parsedate_tz(attr) + date_obj = datetime.datetime( + *parsed_date[:6], tzinfo=_FixedOffset(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + ) + if not date_obj.tzinfo: + date_obj = date_obj.astimezone(tz=TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to rfc datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj + + @staticmethod + def deserialize_iso(attr): + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: Datetime + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + attr = attr.upper() + match = Deserializer.valid_date.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj + + @staticmethod + def deserialize_unix(attr): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param int attr: Object to be serialized. + :rtype: Datetime + :raises: DeserializationError if format invalid + """ + if isinstance(attr, ET.Element): + attr = int(attr.text) + try: + date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to unix datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/_vendor.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/_vendor.py new file mode 100644 index 000000000000..9aad73fc743e --- /dev/null +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/_vendor.py @@ -0,0 +1,27 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.core.pipeline.transport import HttpRequest + + +def _convert_request(request, files=None): + data = request.content if not files else None + request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) + if files: + request.set_formdata_body(files) + return request + + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + formatted_components = template.split("/") + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] + template = "/".join(components) diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/_version.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/_version.py index caf312bd2d0b..92721eef7dd5 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/_version.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.0" +VERSION = "0.3.0" diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/__init__.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/__init__.py index f07d4ec74555..e77cdd9d104a 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/__init__.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/__init__.py @@ -7,4 +7,15 @@ # -------------------------------------------------------------------------- from ._billing_management_client import BillingManagementClient -__all__ = ['BillingManagementClient'] + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["BillingManagementClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/_billing_management_client.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/_billing_management_client.py index dfa4bc08b5e9..7f769c44c36c 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/_billing_management_client.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/_billing_management_client.py @@ -6,42 +6,45 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Optional, TYPE_CHECKING +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient -from msrest import Deserializer, Serializer + +from .. import models +from .._serialization import Deserializer, Serializer +from ._configuration import BillingManagementClientConfiguration +from .operations import ( + AddressOperations, + AgreementsOperations, + AvailableBalancesOperations, + BillingAccountsOperations, + BillingPeriodsOperations, + BillingPermissionsOperations, + BillingProfilesOperations, + BillingPropertyOperations, + BillingRoleAssignmentsOperations, + BillingRoleDefinitionsOperations, + BillingSubscriptionsOperations, + CustomersOperations, + EnrollmentAccountsOperations, + InstructionsOperations, + InvoiceSectionsOperations, + InvoicesOperations, + Operations, + PoliciesOperations, + ProductsOperations, + ReservationsOperations, + TransactionsOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -from ._configuration import BillingManagementClientConfiguration -from .operations import BillingAccountsOperations -from .operations import AddressOperations -from .operations import AvailableBalancesOperations -from .operations import InstructionsOperations -from .operations import BillingProfilesOperations -from .operations import CustomersOperations -from .operations import InvoiceSectionsOperations -from .operations import BillingPermissionsOperations -from .operations import BillingSubscriptionsOperations -from .operations import ProductsOperations -from .operations import InvoicesOperations -from .operations import TransactionsOperations -from .operations import PoliciesOperations -from .operations import BillingPropertyOperations -from .operations import Operations -from .operations import BillingRoleDefinitionsOperations -from .operations import BillingRoleAssignmentsOperations -from .operations import AgreementsOperations -from .operations import ReservationsOperations -from .operations import EnrollmentAccountsOperations -from .operations import BillingPeriodsOperations -from .. import models - -class BillingManagementClient(object): +class BillingManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes """Billing client provides access to billing resources for Azure subscriptions. :ivar billing_accounts: BillingAccountsOperations operations @@ -61,7 +64,8 @@ class BillingManagementClient(object): :ivar billing_permissions: BillingPermissionsOperations operations :vartype billing_permissions: azure.mgmt.billing.aio.operations.BillingPermissionsOperations :ivar billing_subscriptions: BillingSubscriptionsOperations operations - :vartype billing_subscriptions: azure.mgmt.billing.aio.operations.BillingSubscriptionsOperations + :vartype billing_subscriptions: + azure.mgmt.billing.aio.operations.BillingSubscriptionsOperations :ivar products: ProductsOperations operations :vartype products: azure.mgmt.billing.aio.operations.ProductsOperations :ivar invoices: InvoicesOperations operations @@ -72,12 +76,12 @@ class BillingManagementClient(object): :vartype policies: azure.mgmt.billing.aio.operations.PoliciesOperations :ivar billing_property: BillingPropertyOperations operations :vartype billing_property: azure.mgmt.billing.aio.operations.BillingPropertyOperations - :ivar operations: Operations operations - :vartype operations: azure.mgmt.billing.aio.operations.Operations :ivar billing_role_definitions: BillingRoleDefinitionsOperations operations - :vartype billing_role_definitions: azure.mgmt.billing.aio.operations.BillingRoleDefinitionsOperations + :vartype billing_role_definitions: + azure.mgmt.billing.aio.operations.BillingRoleDefinitionsOperations :ivar billing_role_assignments: BillingRoleAssignmentsOperations operations - :vartype billing_role_assignments: azure.mgmt.billing.aio.operations.BillingRoleAssignmentsOperations + :vartype billing_role_assignments: + azure.mgmt.billing.aio.operations.BillingRoleAssignmentsOperations :ivar agreements: AgreementsOperations operations :vartype agreements: azure.mgmt.billing.aio.operations.AgreementsOperations :ivar reservations: ReservationsOperations operations @@ -86,90 +90,97 @@ class BillingManagementClient(object): :vartype enrollment_accounts: azure.mgmt.billing.aio.operations.EnrollmentAccountsOperations :ivar billing_periods: BillingPeriodsOperations operations :vartype billing_periods: azure.mgmt.billing.aio.operations.BillingPeriodsOperations - :param credential: Credential needed for the client to connect to Azure. + :ivar operations: Operations operations + :vartype operations: azure.mgmt.billing.aio.operations.Operations + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID that uniquely identifies an Azure subscription. + :param subscription_id: The ID that uniquely identifies an Azure subscription. Required. :type subscription_id: str - :param str base_url: Service URL - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. """ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, - base_url: Optional[str] = None, + base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - if not base_url: - base_url = 'https://management.azure.com' - self._config = BillingManagementClientConfiguration(credential, subscription_id, **kwargs) + self._config = BillingManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - + self._serialize.client_side_validation = False self.billing_accounts = BillingAccountsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.address = AddressOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) + self.address = AddressOperations(self._client, self._config, self._serialize, self._deserialize) self.available_balances = AvailableBalancesOperations( - self._client, self._config, self._serialize, self._deserialize) - self.instructions = InstructionsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) + self.instructions = InstructionsOperations(self._client, self._config, self._serialize, self._deserialize) self.billing_profiles = BillingProfilesOperations( - self._client, self._config, self._serialize, self._deserialize) - self.customers = CustomersOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) + self.customers = CustomersOperations(self._client, self._config, self._serialize, self._deserialize) self.invoice_sections = InvoiceSectionsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.billing_permissions = BillingPermissionsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.billing_subscriptions = BillingSubscriptionsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.products = ProductsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.invoices = InvoicesOperations( - self._client, self._config, self._serialize, self._deserialize) - self.transactions = TransactionsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.policies = PoliciesOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) + self.products = ProductsOperations(self._client, self._config, self._serialize, self._deserialize) + self.invoices = InvoicesOperations(self._client, self._config, self._serialize, self._deserialize) + self.transactions = TransactionsOperations(self._client, self._config, self._serialize, self._deserialize) + self.policies = PoliciesOperations(self._client, self._config, self._serialize, self._deserialize) self.billing_property = BillingPropertyOperations( - self._client, self._config, self._serialize, self._deserialize) - self.operations = Operations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.billing_role_definitions = BillingRoleDefinitionsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) self.billing_role_assignments = BillingRoleAssignmentsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.agreements = AgreementsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.reservations = ReservationsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) + self.agreements = AgreementsOperations(self._client, self._config, self._serialize, self._deserialize) + self.reservations = ReservationsOperations(self._client, self._config, self._serialize, self._deserialize) self.enrollment_accounts = EnrollmentAccountsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.billing_periods = BillingPeriodsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) + self.billing_periods = BillingPeriodsOperations(self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) - async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + :rtype: ~azure.core.rest.AsyncHttpResponse """ - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) async def close(self) -> None: await self._client.close() diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/_configuration.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/_configuration.py index 070bbfe02425..4e38578cb8b0 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/_configuration.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/_configuration.py @@ -10,7 +10,7 @@ from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION @@ -19,48 +19,42 @@ from azure.core.credentials_async import AsyncTokenCredential -class BillingManagementClientConfiguration(Configuration): +class BillingManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for BillingManagementClient. Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID that uniquely identifies an Azure subscription. + :param subscription_id: The ID that uniquely identifies an Azure subscription. Required. :type subscription_id: str """ - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - **kwargs: Any - ) -> None: + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(BillingManagementClientConfiguration, self).__init__(**kwargs) if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(BillingManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-billing/{}'.format(VERSION)) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-billing/{}".format(VERSION)) self._configure(**kwargs) - def _configure( - self, - **kwargs: Any - ) -> None: - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/_patch.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/__init__.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/__init__.py index 7f7bbc76fedb..0f9808051bfd 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/__init__.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/__init__.py @@ -20,34 +20,40 @@ from ._transactions_operations import TransactionsOperations from ._policies_operations import PoliciesOperations from ._billing_property_operations import BillingPropertyOperations -from ._operations import Operations from ._billing_role_definitions_operations import BillingRoleDefinitionsOperations from ._billing_role_assignments_operations import BillingRoleAssignmentsOperations from ._agreements_operations import AgreementsOperations from ._reservations_operations import ReservationsOperations from ._enrollment_accounts_operations import EnrollmentAccountsOperations from ._billing_periods_operations import BillingPeriodsOperations +from ._operations import Operations + +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'BillingAccountsOperations', - 'AddressOperations', - 'AvailableBalancesOperations', - 'InstructionsOperations', - 'BillingProfilesOperations', - 'CustomersOperations', - 'InvoiceSectionsOperations', - 'BillingPermissionsOperations', - 'BillingSubscriptionsOperations', - 'ProductsOperations', - 'InvoicesOperations', - 'TransactionsOperations', - 'PoliciesOperations', - 'BillingPropertyOperations', - 'Operations', - 'BillingRoleDefinitionsOperations', - 'BillingRoleAssignmentsOperations', - 'AgreementsOperations', - 'ReservationsOperations', - 'EnrollmentAccountsOperations', - 'BillingPeriodsOperations', + "BillingAccountsOperations", + "AddressOperations", + "AvailableBalancesOperations", + "InstructionsOperations", + "BillingProfilesOperations", + "CustomersOperations", + "InvoiceSectionsOperations", + "BillingPermissionsOperations", + "BillingSubscriptionsOperations", + "ProductsOperations", + "InvoicesOperations", + "TransactionsOperations", + "PoliciesOperations", + "BillingPropertyOperations", + "BillingRoleDefinitionsOperations", + "BillingRoleAssignmentsOperations", + "AgreementsOperations", + "ReservationsOperations", + "EnrollmentAccountsOperations", + "BillingPeriodsOperations", + "Operations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_address_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_address_operations.py index 37a5150ec00f..28bf339c5e61 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_address_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_address_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,93 +6,154 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Generic, Optional, TypeVar -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._address_operations import build_validate_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class AddressOperations: - """AddressOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class AddressOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s + :attr:`address` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @overload async def validate( - self, - address: "_models.AddressDetails", - **kwargs - ) -> "_models.ValidateAddressResponse": + self, address: _models.AddressDetails, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ValidateAddressResponse: """Validates an address. Use the operation to validate an address before using it as soldTo or a billTo address. - :param address: + :param address: Required. :type address: ~azure.mgmt.billing.models.AddressDetails + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ValidateAddressResponse or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.ValidateAddressResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def validate( + self, address: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ValidateAddressResponse: + """Validates an address. Use the operation to validate an address before using it as soldTo or a + billTo address. + + :param address: Required. + :type address: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ValidateAddressResponse, or the result of cls(response) + :return: ValidateAddressResponse or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateAddressResponse - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def validate( + self, address: Union[_models.AddressDetails, IO], **kwargs: Any + ) -> _models.ValidateAddressResponse: + """Validates an address. Use the operation to validate an address before using it as soldTo or a + billTo address. + + :param address: Is either a model type or a IO type. Required. + :type address: ~azure.mgmt.billing.models.AddressDetails or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ValidateAddressResponse or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.ValidateAddressResponse + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ValidateAddressResponse"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.validate.metadata['url'] # type: ignore - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(address, 'AddressDetails') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidateAddressResponse] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(address, (IO, bytes)): + _content = address + else: + _json = self._serialize.body(address, "AddressDetails") + + request = build_validate_request( + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.validate.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('ValidateAddressResponse', pipeline_response) + deserialized = self._deserialize("ValidateAddressResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - validate.metadata = {'url': '/providers/Microsoft.Billing/validateAddress'} # type: ignore + + validate.metadata = {"url": "/providers/Microsoft.Billing/validateAddress"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_agreements_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_agreements_operations.py index 426c9a6eae96..ca9eac6975e3 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_agreements_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_agreements_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,94 +6,104 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._agreements_operations import build_get_request, build_list_by_billing_account_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class AgreementsOperations: - """AgreementsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class AgreementsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s + :attr:`agreements` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_by_billing_account( - self, - billing_account_name: str, - expand: Optional[str] = None, - **kwargs - ) -> AsyncIterable["_models.AgreementListResult"]: + self, billing_account_name: str, expand: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.Agreement"]: """Lists the agreements for a billing account. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param expand: May be used to expand the participants. + :param expand: May be used to expand the participants. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AgreementListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.AgreementListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Agreement or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Agreement] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AgreementListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AgreementListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_account.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if expand is not None: - query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_account_request( + billing_account_name=billing_account_name, + expand=expand, + api_version=api_version, + template_url=self.list_by_billing_account.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('AgreementListResult', pipeline_response) + deserialized = self._deserialize("AgreementListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -101,80 +112,81 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_billing_account.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/agreements'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/agreements"} # type: ignore + @distributed_trace_async async def get( - self, - billing_account_name: str, - agreement_name: str, - expand: Optional[str] = None, - **kwargs - ) -> "_models.Agreement": + self, billing_account_name: str, agreement_name: str, expand: Optional[str] = None, **kwargs: Any + ) -> _models.Agreement: """Gets an agreement by ID. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param agreement_name: The ID that uniquely identifies an agreement. + :param agreement_name: The ID that uniquely identifies an agreement. Required. :type agreement_name: str - :param expand: May be used to expand the participants. + :param expand: May be used to expand the participants. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Agreement, or the result of cls(response) + :return: Agreement or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Agreement - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Agreement"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'agreementName': self._serialize.url("agreement_name", agreement_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if expand is not None: - query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Agreement] + + request = build_get_request( + billing_account_name=billing_account_name, + agreement_name=agreement_name, + expand=expand, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Agreement', pipeline_response) + deserialized = self._deserialize("Agreement", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/agreements/{agreementName}'} # type: ignore + + get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/agreements/{agreementName}"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_available_balances_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_available_balances_operations.py index 5737f68c973c..6cd2f6ad1418 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_available_balances_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_available_balances_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,97 +6,108 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Generic, Optional, TypeVar -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._available_balances_operations import build_get_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class AvailableBalancesOperations: - """AvailableBalancesOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class AvailableBalancesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s + :attr:`available_balances` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace_async async def get( - self, - billing_account_name: str, - billing_profile_name: str, - **kwargs - ) -> "_models.AvailableBalance": + self, billing_account_name: str, billing_profile_name: str, **kwargs: Any + ) -> _models.AvailableBalance: """The available credit balance for a billing profile. This is the balance that can be used for pay now to settle due or past due invoices. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AvailableBalance, or the result of cls(response) + :return: AvailableBalance or the result of cls(response) :rtype: ~azure.mgmt.billing.models.AvailableBalance - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AvailableBalance"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AvailableBalance] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AvailableBalance', pipeline_response) + deserialized = self._deserialize("AvailableBalance", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/availableBalance/default'} # type: ignore + + get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/availableBalance/default"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_billing_accounts_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_billing_accounts_operations.py index 2ec6f0568c16..2b2bae93aed1 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_billing_accounts_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_billing_accounts_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,89 +6,107 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._billing_accounts_operations import ( + build_get_request, + build_list_invoice_sections_by_create_subscription_permission_request, + build_list_request, + build_update_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class BillingAccountsOperations: - """BillingAccountsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class BillingAccountsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s + :attr:`billing_accounts` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def list( - self, - expand: Optional[str] = None, - **kwargs - ) -> AsyncIterable["_models.BillingAccountListResult"]: + @distributed_trace + def list(self, expand: Optional[str] = None, **kwargs: Any) -> AsyncIterable["_models.BillingAccount"]: """Lists the billing accounts that a user has access to. - :param expand: May be used to expand the soldTo, invoice sections and billing profiles. + :param expand: May be used to expand the soldTo, invoice sections and billing profiles. Default + value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either BillingAccountListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingAccountListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either BillingAccount or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingAccount] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingAccountListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingAccountListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if expand is not None: - query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + expand=expand, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('BillingAccountListResult', pipeline_response) + deserialized = self._deserialize("BillingAccountListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -96,250 +115,339 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts"} # type: ignore + @distributed_trace_async async def get( - self, - billing_account_name: str, - expand: Optional[str] = None, - **kwargs - ) -> "_models.BillingAccount": + self, billing_account_name: str, expand: Optional[str] = None, **kwargs: Any + ) -> _models.BillingAccount: """Gets a billing account by its ID. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param expand: May be used to expand the soldTo, invoice sections and billing profiles. + :param expand: May be used to expand the soldTo, invoice sections and billing profiles. Default + value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: BillingAccount, or the result of cls(response) + :return: BillingAccount or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingAccount - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingAccount"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if expand is not None: - query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingAccount] + + request = build_get_request( + billing_account_name=billing_account_name, + expand=expand, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('BillingAccount', pipeline_response) + deserialized = self._deserialize("BillingAccount", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}'} # type: ignore + + get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}"} # type: ignore async def _update_initial( - self, - billing_account_name: str, - parameters: "_models.BillingAccountUpdateRequest", - **kwargs - ) -> Optional["_models.BillingAccount"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.BillingAccount"]] + self, billing_account_name: str, parameters: Union[_models.BillingAccountUpdateRequest, IO], **kwargs: Any + ) -> Optional[_models.BillingAccount]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self._update_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'BillingAccountUpdateRequest') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.BillingAccount]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "BillingAccountUpdateRequest") + + request = build_update_request( + billing_account_name=billing_account_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._update_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('BillingAccount', pipeline_response) + deserialized = self._deserialize("BillingAccount", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _update_initial.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}'} # type: ignore + _update_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}"} # type: ignore + + @overload async def begin_update( self, billing_account_name: str, - parameters: "_models.BillingAccountUpdateRequest", - **kwargs - ) -> AsyncLROPoller["_models.BillingAccount"]: + parameters: _models.BillingAccountUpdateRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.BillingAccount]: """Updates the properties of a billing account. Currently, displayName and address can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the update billing account - operation. + operation. Required. :type parameters: ~azure.mgmt.billing.models.BillingAccountUpdateRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, - False for no polling, or your own initialized polling object for a personal polling strategy. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either BillingAccount or the result of cls(response) + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either BillingAccount or the result of + cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingAccount] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingAccount"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + async def begin_update( + self, billing_account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[_models.BillingAccount]: + """Updates the properties of a billing account. Currently, displayName and address can be updated. + The operation is supported only for billing accounts with agreement type Microsoft Customer + Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param parameters: Request parameters that are provided to the update billing account + operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either BillingAccount or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingAccount] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_update( + self, billing_account_name: str, parameters: Union[_models.BillingAccountUpdateRequest, IO], **kwargs: Any + ) -> AsyncLROPoller[_models.BillingAccount]: + """Updates the properties of a billing account. Currently, displayName and address can be updated. + The operation is supported only for billing accounts with agreement type Microsoft Customer + Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param parameters: Request parameters that are provided to the update billing account + operation. Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.billing.models.BillingAccountUpdateRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either BillingAccount or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingAccount] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingAccount] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._update_initial( + raw_result = await self._update_initial( # type: ignore billing_account_name=billing_account_name, parameters=parameters, - cls=lambda x,y,z: x, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('BillingAccount', pipeline_response) - + deserialized = self._deserialize("BillingAccount", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - } - - if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + AsyncPollingMethod, + AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs), + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_update.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}'} # type: ignore + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}"} # type: ignore + + @distributed_trace def list_invoice_sections_by_create_subscription_permission( - self, - billing_account_name: str, - **kwargs - ) -> AsyncIterable["_models.InvoiceSectionListWithCreateSubPermissionResult"]: + self, billing_account_name: str, **kwargs: Any + ) -> AsyncIterable["_models.InvoiceSectionWithCreateSubPermission"]: """Lists the invoice sections for which the user has permission to create Azure subscriptions. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either InvoiceSectionListWithCreateSubPermissionResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.InvoiceSectionListWithCreateSubPermissionResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either InvoiceSectionWithCreateSubPermission or the + result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.InvoiceSectionWithCreateSubPermission] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.InvoiceSectionListWithCreateSubPermissionResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceSectionListWithCreateSubPermissionResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_invoice_sections_by_create_subscription_permission.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + + request = build_list_invoice_sections_by_create_subscription_permission_request( + billing_account_name=billing_account_name, + api_version=api_version, + template_url=self.list_invoice_sections_by_create_subscription_permission.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('InvoiceSectionListWithCreateSubPermissionResult', pipeline_response) + deserialized = self._deserialize("InvoiceSectionListWithCreateSubPermissionResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -348,17 +456,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_invoice_sections_by_create_subscription_permission.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/listInvoiceSectionsWithCreateSubscriptionPermission'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_invoice_sections_by_create_subscription_permission.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/listInvoiceSectionsWithCreateSubscriptionPermission"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_billing_periods_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_billing_periods_operations.py index f3e701e6a6aa..12915598527d 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_billing_periods_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_billing_periods_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,107 +6,116 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._billing_periods_operations import build_get_request, build_list_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class BillingPeriodsOperations: - """BillingPeriodsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class BillingPeriodsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s + :attr:`billing_periods` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list( - self, - filter: Optional[str] = None, - skiptoken: Optional[str] = None, - top: Optional[int] = None, - **kwargs - ) -> AsyncIterable["_models.BillingPeriodsListResult"]: + self, filter: Optional[str] = None, skiptoken: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> AsyncIterable["_models.BillingPeriod"]: """Lists the available billing periods for a subscription in reverse chronological order. This is only supported for Azure Web-Direct subscriptions. Other subscription types which were not purchased directly through the Azure web portal are not supported through this preview API. :param filter: May be used to filter billing periods by billingPeriodEndDate. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or - 'not'. + 'not'. Default value is None. :type filter: str :param skiptoken: Skiptoken is only used if a previous operation returned a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include - a skiptoken parameter that specifies a starting point to use for subsequent calls. + a skiptoken parameter that specifies a starting point to use for subsequent calls. Default + value is None. :type skiptoken: str :param top: May be used to limit the number of results to the most recent N billing periods. + Default value is None. :type top: int :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either BillingPeriodsListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingPeriodsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either BillingPeriod or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingPeriod] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingPeriodsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPeriodsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-03-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - if skiptoken is not None: - query_parameters['$skiptoken'] = self._serialize.query("skiptoken", skiptoken, 'str') - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int', maximum=100, minimum=1) - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + skiptoken=skiptoken, + top=top, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('BillingPeriodsListResult', pipeline_response) + deserialized = self._deserialize("BillingPeriodsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -114,74 +124,76 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingPeriods'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingPeriods"} # type: ignore - async def get( - self, - billing_period_name: str, - **kwargs - ) -> "_models.BillingPeriod": + @distributed_trace_async + async def get(self, billing_period_name: str, **kwargs: Any) -> _models.BillingPeriod: """Gets a named billing period. This is only supported for Azure Web-Direct subscriptions. Other subscription types which were not purchased directly through the Azure web portal are not supported through this preview API. - :param billing_period_name: The name of a BillingPeriod resource. + :param billing_period_name: The name of a BillingPeriod resource. Required. :type billing_period_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: BillingPeriod, or the result of cls(response) + :return: BillingPeriod or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingPeriod - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingPeriod"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-03-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'billingPeriodName': self._serialize.url("billing_period_name", billing_period_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPeriod] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_request( + billing_period_name=billing_period_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('BillingPeriod', pipeline_response) + deserialized = self._deserialize("BillingPeriod", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}'} # type: ignore + + get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_billing_permissions_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_billing_permissions_operations.py index 613e0189287e..60a401b9d8b7 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_billing_permissions_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_billing_permissions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,93 +6,110 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._billing_permissions_operations import ( + build_list_by_billing_account_request, + build_list_by_billing_profile_request, + build_list_by_customer_request, + build_list_by_invoice_sections_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class BillingPermissionsOperations: - """BillingPermissionsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class BillingPermissionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s + :attr:`billing_permissions` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_by_customer( - self, - billing_account_name: str, - customer_name: str, - **kwargs - ) -> AsyncIterable["_models.BillingPermissionsListResult"]: + self, billing_account_name: str, customer_name: str, **kwargs: Any + ) -> AsyncIterable["_models.BillingPermissionsProperties"]: """Lists the billing permissions the caller has for a customer. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param customer_name: The ID that uniquely identifies a customer. + :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either BillingPermissionsListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingPermissionsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either BillingPermissionsProperties or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingPermissionsProperties] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingPermissionsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPermissionsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_customer.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'customerName': self._serialize.url("customer_name", customer_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_customer_request( + billing_account_name=billing_account_name, + customer_name=customer_name, + api_version=api_version, + template_url=self.list_by_customer.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('BillingPermissionsListResult', pipeline_response) + deserialized = self._deserialize("BillingPermissionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -100,68 +118,73 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_customer.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/billingPermissions'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list_by_customer.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/billingPermissions"} # type: ignore + + @distributed_trace def list_by_billing_account( - self, - billing_account_name: str, - **kwargs - ) -> AsyncIterable["_models.BillingPermissionsListResult"]: + self, billing_account_name: str, **kwargs: Any + ) -> AsyncIterable["_models.BillingPermissionsProperties"]: """Lists the billing permissions the caller has on a billing account. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either BillingPermissionsListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingPermissionsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either BillingPermissionsProperties or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingPermissionsProperties] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingPermissionsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPermissionsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_account.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_account_request( + billing_account_name=billing_account_name, + api_version=api_version, + template_url=self.list_by_billing_account.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('BillingPermissionsListResult', pipeline_response) + deserialized = self._deserialize("BillingPermissionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -170,76 +193,79 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_billing_account.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingPermissions'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingPermissions"} # type: ignore + @distributed_trace def list_by_invoice_sections( - self, - billing_account_name: str, - billing_profile_name: str, - invoice_section_name: str, - **kwargs - ) -> AsyncIterable["_models.BillingPermissionsListResult"]: + self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any + ) -> AsyncIterable["_models.BillingPermissionsProperties"]: """Lists the billing permissions the caller has on an invoice section. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str - :param invoice_section_name: The ID that uniquely identifies an invoice section. + :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either BillingPermissionsListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingPermissionsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either BillingPermissionsProperties or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingPermissionsProperties] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingPermissionsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPermissionsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_invoice_sections.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - 'invoiceSectionName': self._serialize.url("invoice_section_name", invoice_section_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_invoice_sections_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + invoice_section_name=invoice_section_name, + api_version=api_version, + template_url=self.list_by_invoice_sections.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('BillingPermissionsListResult', pipeline_response) + deserialized = self._deserialize("BillingPermissionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -248,72 +274,76 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_invoice_sections.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingPermissions'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list_by_invoice_sections.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingPermissions"} # type: ignore + + @distributed_trace def list_by_billing_profile( - self, - billing_account_name: str, - billing_profile_name: str, - **kwargs - ) -> AsyncIterable["_models.BillingPermissionsListResult"]: + self, billing_account_name: str, billing_profile_name: str, **kwargs: Any + ) -> AsyncIterable["_models.BillingPermissionsProperties"]: """Lists the billing permissions the caller has on a billing profile. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either BillingPermissionsListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingPermissionsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either BillingPermissionsProperties or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingPermissionsProperties] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingPermissionsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPermissionsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_profile.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_profile_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + api_version=api_version, + template_url=self.list_by_billing_profile.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('BillingPermissionsListResult', pipeline_response) + deserialized = self._deserialize("BillingPermissionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -322,17 +352,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_billing_profile.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingPermissions'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingPermissions"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_billing_profiles_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_billing_profiles_operations.py index 0c7eaffb8d05..e2b37345cffb 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_billing_profiles_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_billing_profiles_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,97 +6,111 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._billing_profiles_operations import ( + build_create_or_update_request, + build_get_request, + build_list_by_billing_account_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class BillingProfilesOperations: - """BillingProfilesOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class BillingProfilesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s + :attr:`billing_profiles` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_by_billing_account( - self, - billing_account_name: str, - expand: Optional[str] = None, - **kwargs - ) -> AsyncIterable["_models.BillingProfileListResult"]: + self, billing_account_name: str, expand: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.BillingProfile"]: """Lists the billing profiles that a user has access to. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param expand: May be used to expand the invoice sections. + :param expand: May be used to expand the invoice sections. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either BillingProfileListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingProfileListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either BillingProfile or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingProfile] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingProfileListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingProfileListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_account.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if expand is not None: - query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_account_request( + billing_account_name=billing_account_name, + expand=expand, + api_version=api_version, + template_url=self.list_by_billing_account.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('BillingProfileListResult', pipeline_response) + deserialized = self._deserialize("BillingProfileListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -104,212 +119,305 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_billing_account.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles"} # type: ignore + @distributed_trace_async async def get( - self, - billing_account_name: str, - billing_profile_name: str, - expand: Optional[str] = None, - **kwargs - ) -> "_models.BillingProfile": + self, billing_account_name: str, billing_profile_name: str, expand: Optional[str] = None, **kwargs: Any + ) -> _models.BillingProfile: """Gets a billing profile by its ID. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str - :param expand: May be used to expand the invoice sections. + :param expand: May be used to expand the invoice sections. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: BillingProfile, or the result of cls(response) + :return: BillingProfile or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingProfile - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingProfile"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if expand is not None: - query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingProfile] + + request = build_get_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + expand=expand, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('BillingProfile', pipeline_response) + deserialized = self._deserialize("BillingProfile", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}'} # type: ignore + + get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}"} # type: ignore async def _create_or_update_initial( self, billing_account_name: str, billing_profile_name: str, - parameters: "_models.BillingProfile", - **kwargs - ) -> Optional["_models.BillingProfile"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.BillingProfile"]] + parameters: Union[_models.BillingProfile, IO], + **kwargs: Any + ) -> Optional[_models.BillingProfile]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self._create_or_update_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'BillingProfile') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.BillingProfile]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "BillingProfile") + + request = build_create_or_update_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - response_headers = {} deserialized = None + response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('BillingProfile', pipeline_response) + deserialized = self._deserialize("BillingProfile", pipeline_response) if response.status_code == 202: - response_headers['Location']=self._deserialize('str', response.headers.get('Location')) - response_headers['Retry-After']=self._deserialize('int', response.headers.get('Retry-After')) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized - _create_or_update_initial.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}'} # type: ignore + _create_or_update_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}"} # type: ignore + + @overload async def begin_create_or_update( self, billing_account_name: str, billing_profile_name: str, - parameters: "_models.BillingProfile", - **kwargs - ) -> AsyncLROPoller["_models.BillingProfile"]: + parameters: _models.BillingProfile, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.BillingProfile]: """Creates or updates a billing profile. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str - :param parameters: The new or updated billing profile. + :param parameters: The new or updated billing profile. Required. :type parameters: ~azure.mgmt.billing.models.BillingProfile + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, - False for no polling, or your own initialized polling object for a personal polling strategy. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either BillingProfile or the result of cls(response) + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either BillingProfile or the result of + cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingProfile] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingProfile"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + async def begin_create_or_update( + self, + billing_account_name: str, + billing_profile_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.BillingProfile]: + """Creates or updates a billing profile. The operation is supported for billing accounts with + agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. + :type billing_profile_name: str + :param parameters: The new or updated billing profile. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either BillingProfile or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingProfile] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + billing_account_name: str, + billing_profile_name: str, + parameters: Union[_models.BillingProfile, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.BillingProfile]: + """Creates or updates a billing profile. The operation is supported for billing accounts with + agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. + :type billing_profile_name: str + :param parameters: The new or updated billing profile. Is either a model type or a IO type. + Required. + :type parameters: ~azure.mgmt.billing.models.BillingProfile or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either BillingProfile or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingProfile] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingProfile] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._create_or_update_initial( + raw_result = await self._create_or_update_initial( # type: ignore billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, parameters=parameters, - cls=lambda x,y,z: x, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('BillingProfile', pipeline_response) - + deserialized = self._deserialize("BillingProfile", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - } - - if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}'} # type: ignore + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_or_update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_billing_property_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_billing_property_operations.py index f54dfc955f5a..5d194b429594 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_billing_property_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_billing_property_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,151 +6,213 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Generic, Optional, TypeVar -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._billing_property_operations import build_get_request, build_update_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class BillingPropertyOperations: - """BillingPropertyOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class BillingPropertyOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s + :attr:`billing_property` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - async def get( - self, - **kwargs - ) -> "_models.BillingProperty": + @distributed_trace_async + async def get(self, **kwargs: Any) -> _models.BillingProperty: """Get the billing properties for a subscription. This operation is not supported for billing accounts with agreement type Enterprise Agreement. :keyword callable cls: A custom type or function that will be passed the direct response - :return: BillingProperty, or the result of cls(response) + :return: BillingProperty or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingProperty - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingProperty"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingProperty] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('BillingProperty', pipeline_response) + deserialized = self._deserialize("BillingProperty", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingProperty/default'} # type: ignore + get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingProperty/default"} # type: ignore + + @overload async def update( - self, - parameters: "_models.BillingProperty", - **kwargs - ) -> "_models.BillingProperty": + self, parameters: _models.BillingProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.BillingProperty: """Updates the billing property of a subscription. Currently, cost center can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param parameters: Request parameters that are provided to the update billing property - operation. + operation. Required. :type parameters: ~azure.mgmt.billing.models.BillingProperty + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: BillingProperty or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.BillingProperty + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.BillingProperty: + """Updates the billing property of a subscription. Currently, cost center can be updated. The + operation is supported only for billing accounts with agreement type Microsoft Customer + Agreement. + + :param parameters: Request parameters that are provided to the update billing property + operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: BillingProperty, or the result of cls(response) + :return: BillingProperty or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingProperty - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update(self, parameters: Union[_models.BillingProperty, IO], **kwargs: Any) -> _models.BillingProperty: + """Updates the billing property of a subscription. Currently, cost center can be updated. The + operation is supported only for billing accounts with agreement type Microsoft Customer + Agreement. + + :param parameters: Request parameters that are provided to the update billing property + operation. Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.billing.models.BillingProperty or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: BillingProperty or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.BillingProperty + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingProperty"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.update.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'BillingProperty') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingProperty] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "BillingProperty") + + request = build_update_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('BillingProperty', pipeline_response) + deserialized = self._deserialize("BillingProperty", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingProperty/default'} # type: ignore + + update.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingProperty/default"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_billing_role_assignments_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_billing_role_assignments_operations.py index 342d85b97e5f..a9814f4718b3 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_billing_role_assignments_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_billing_role_assignments_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,473 +6,519 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._billing_role_assignments_operations import ( + build_delete_by_billing_account_request, + build_delete_by_billing_profile_request, + build_delete_by_invoice_section_request, + build_get_by_billing_account_request, + build_get_by_billing_profile_request, + build_get_by_invoice_section_request, + build_list_by_billing_account_request, + build_list_by_billing_profile_request, + build_list_by_invoice_section_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class BillingRoleAssignmentsOperations: - """BillingRoleAssignmentsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class BillingRoleAssignmentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s + :attr:`billing_role_assignments` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace_async async def get_by_billing_account( - self, - billing_account_name: str, - billing_role_assignment_name: str, - **kwargs - ) -> "_models.BillingRoleAssignment": + self, billing_account_name: str, billing_role_assignment_name: str, **kwargs: Any + ) -> _models.BillingRoleAssignment: """Gets a role assignment for the caller on a billing account. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. + Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: BillingRoleAssignment, or the result of cls(response) + :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingRoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get_by_billing_account.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingRoleAssignmentName': self._serialize.url("billing_role_assignment_name", billing_role_assignment_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_get_by_billing_account_request( + billing_account_name=billing_account_name, + billing_role_assignment_name=billing_role_assignment_name, + api_version=api_version, + template_url=self.get_by_billing_account.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('BillingRoleAssignment', pipeline_response) + deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_billing_account.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments/{billingRoleAssignmentName}'} # type: ignore + get_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore + + @distributed_trace_async async def delete_by_billing_account( - self, - billing_account_name: str, - billing_role_assignment_name: str, - **kwargs - ) -> "_models.BillingRoleAssignment": + self, billing_account_name: str, billing_role_assignment_name: str, **kwargs: Any + ) -> _models.BillingRoleAssignment: """Deletes a role assignment for the caller on a billing account. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. + Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: BillingRoleAssignment, or the result of cls(response) + :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingRoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.delete_by_billing_account.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingRoleAssignmentName': self._serialize.url("billing_role_assignment_name", billing_role_assignment_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] + + request = build_delete_by_billing_account_request( + billing_account_name=billing_account_name, + billing_role_assignment_name=billing_role_assignment_name, + api_version=api_version, + template_url=self.delete_by_billing_account.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('BillingRoleAssignment', pipeline_response) + deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete_by_billing_account.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments/{billingRoleAssignmentName}'} # type: ignore + delete_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore + + @distributed_trace_async async def get_by_invoice_section( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, billing_role_assignment_name: str, - **kwargs - ) -> "_models.BillingRoleAssignment": + **kwargs: Any + ) -> _models.BillingRoleAssignment: """Gets a role assignment for the caller on an invoice section. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str - :param invoice_section_name: The ID that uniquely identifies an invoice section. + :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. + Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: BillingRoleAssignment, or the result of cls(response) + :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingRoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get_by_invoice_section.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - 'invoiceSectionName': self._serialize.url("invoice_section_name", invoice_section_name, 'str'), - 'billingRoleAssignmentName': self._serialize.url("billing_role_assignment_name", billing_role_assignment_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] + + request = build_get_by_invoice_section_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + invoice_section_name=invoice_section_name, + billing_role_assignment_name=billing_role_assignment_name, + api_version=api_version, + template_url=self.get_by_invoice_section.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('BillingRoleAssignment', pipeline_response) + deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_invoice_section.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments/{billingRoleAssignmentName}'} # type: ignore + get_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore + + @distributed_trace_async async def delete_by_invoice_section( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, billing_role_assignment_name: str, - **kwargs - ) -> "_models.BillingRoleAssignment": + **kwargs: Any + ) -> _models.BillingRoleAssignment: """Deletes a role assignment for the caller on an invoice section. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str - :param invoice_section_name: The ID that uniquely identifies an invoice section. + :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. + Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: BillingRoleAssignment, or the result of cls(response) + :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingRoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.delete_by_invoice_section.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - 'invoiceSectionName': self._serialize.url("invoice_section_name", invoice_section_name, 'str'), - 'billingRoleAssignmentName': self._serialize.url("billing_role_assignment_name", billing_role_assignment_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] + + request = build_delete_by_invoice_section_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + invoice_section_name=invoice_section_name, + billing_role_assignment_name=billing_role_assignment_name, + api_version=api_version, + template_url=self.delete_by_invoice_section.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('BillingRoleAssignment', pipeline_response) + deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete_by_invoice_section.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments/{billingRoleAssignmentName}'} # type: ignore + delete_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore + + @distributed_trace_async async def get_by_billing_profile( - self, - billing_account_name: str, - billing_profile_name: str, - billing_role_assignment_name: str, - **kwargs - ) -> "_models.BillingRoleAssignment": + self, billing_account_name: str, billing_profile_name: str, billing_role_assignment_name: str, **kwargs: Any + ) -> _models.BillingRoleAssignment: """Gets a role assignment for the caller on a billing profile. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. + Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: BillingRoleAssignment, or the result of cls(response) + :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingRoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get_by_billing_profile.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - 'billingRoleAssignmentName': self._serialize.url("billing_role_assignment_name", billing_role_assignment_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] + + request = build_get_by_billing_profile_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + billing_role_assignment_name=billing_role_assignment_name, + api_version=api_version, + template_url=self.get_by_billing_profile.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('BillingRoleAssignment', pipeline_response) + deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_billing_profile.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments/{billingRoleAssignmentName}'} # type: ignore + get_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore + + @distributed_trace_async async def delete_by_billing_profile( - self, - billing_account_name: str, - billing_profile_name: str, - billing_role_assignment_name: str, - **kwargs - ) -> "_models.BillingRoleAssignment": + self, billing_account_name: str, billing_profile_name: str, billing_role_assignment_name: str, **kwargs: Any + ) -> _models.BillingRoleAssignment: """Deletes a role assignment for the caller on a billing profile. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. + Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: BillingRoleAssignment, or the result of cls(response) + :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingRoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.delete_by_billing_profile.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - 'billingRoleAssignmentName': self._serialize.url("billing_role_assignment_name", billing_role_assignment_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] + + request = build_delete_by_billing_profile_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + billing_role_assignment_name=billing_role_assignment_name, + api_version=api_version, + template_url=self.delete_by_billing_profile.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('BillingRoleAssignment', pipeline_response) + deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete_by_billing_profile.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments/{billingRoleAssignmentName}'} # type: ignore + delete_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore + + @distributed_trace def list_by_billing_account( - self, - billing_account_name: str, - **kwargs - ) -> AsyncIterable["_models.BillingRoleAssignmentListResult"]: + self, billing_account_name: str, **kwargs: Any + ) -> AsyncIterable["_models.BillingRoleAssignment"]: """Lists the role assignments for the caller on a billing account. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either BillingRoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either BillingRoleAssignment or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingRoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_account.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_account_request( + billing_account_name=billing_account_name, + api_version=api_version, + template_url=self.list_by_billing_account.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('BillingRoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("BillingRoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -480,77 +527,80 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_billing_account.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments"} # type: ignore + + @distributed_trace def list_by_invoice_section( - self, - billing_account_name: str, - billing_profile_name: str, - invoice_section_name: str, - **kwargs - ) -> AsyncIterable["_models.BillingRoleAssignmentListResult"]: + self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any + ) -> AsyncIterable["_models.BillingRoleAssignment"]: """Lists the role assignments for the caller on an invoice section. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str - :param invoice_section_name: The ID that uniquely identifies an invoice section. + :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either BillingRoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either BillingRoleAssignment or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingRoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_invoice_section.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - 'invoiceSectionName': self._serialize.url("invoice_section_name", invoice_section_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_invoice_section_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + invoice_section_name=invoice_section_name, + api_version=api_version, + template_url=self.list_by_invoice_section.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('BillingRoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("BillingRoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -559,73 +609,77 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_invoice_section.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments"} # type: ignore + @distributed_trace def list_by_billing_profile( - self, - billing_account_name: str, - billing_profile_name: str, - **kwargs - ) -> AsyncIterable["_models.BillingRoleAssignmentListResult"]: + self, billing_account_name: str, billing_profile_name: str, **kwargs: Any + ) -> AsyncIterable["_models.BillingRoleAssignment"]: """Lists the role assignments for the caller on a billing profile. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either BillingRoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either BillingRoleAssignment or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingRoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_profile.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_profile_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + api_version=api_version, + template_url=self.list_by_billing_profile.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('BillingRoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("BillingRoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -634,17 +688,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_billing_profile.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_billing_role_definitions_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_billing_role_definitions_operations.py index 1ed6da928727..0de9044cf281 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_billing_role_definitions_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_billing_role_definitions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,279 +6,311 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._billing_role_definitions_operations import ( + build_get_by_billing_account_request, + build_get_by_billing_profile_request, + build_get_by_invoice_section_request, + build_list_by_billing_account_request, + build_list_by_billing_profile_request, + build_list_by_invoice_section_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class BillingRoleDefinitionsOperations: - """BillingRoleDefinitionsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class BillingRoleDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s + :attr:`billing_role_definitions` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace_async async def get_by_billing_account( - self, - billing_account_name: str, - billing_role_definition_name: str, - **kwargs - ) -> "_models.BillingRoleDefinition": + self, billing_account_name: str, billing_role_definition_name: str, **kwargs: Any + ) -> _models.BillingRoleDefinition: """Gets the definition for a role on a billing account. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_role_definition_name: The ID that uniquely identifies a role definition. + Required. :type billing_role_definition_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: BillingRoleDefinition, or the result of cls(response) + :return: BillingRoleDefinition or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleDefinition - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingRoleDefinition"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get_by_billing_account.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingRoleDefinitionName': self._serialize.url("billing_role_definition_name", billing_role_definition_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinition] + + request = build_get_by_billing_account_request( + billing_account_name=billing_account_name, + billing_role_definition_name=billing_role_definition_name, + api_version=api_version, + template_url=self.get_by_billing_account.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('BillingRoleDefinition', pipeline_response) + deserialized = self._deserialize("BillingRoleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_billing_account.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleDefinitions/{billingRoleDefinitionName}'} # type: ignore + get_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleDefinitions/{billingRoleDefinitionName}"} # type: ignore + + @distributed_trace_async async def get_by_invoice_section( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, billing_role_definition_name: str, - **kwargs - ) -> "_models.BillingRoleDefinition": + **kwargs: Any + ) -> _models.BillingRoleDefinition: """Gets the definition for a role on an invoice section. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str - :param invoice_section_name: The ID that uniquely identifies an invoice section. + :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param billing_role_definition_name: The ID that uniquely identifies a role definition. + Required. :type billing_role_definition_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: BillingRoleDefinition, or the result of cls(response) + :return: BillingRoleDefinition or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleDefinition - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingRoleDefinition"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get_by_invoice_section.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - 'invoiceSectionName': self._serialize.url("invoice_section_name", invoice_section_name, 'str'), - 'billingRoleDefinitionName': self._serialize.url("billing_role_definition_name", billing_role_definition_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinition] + + request = build_get_by_invoice_section_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + invoice_section_name=invoice_section_name, + billing_role_definition_name=billing_role_definition_name, + api_version=api_version, + template_url=self.get_by_invoice_section.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('BillingRoleDefinition', pipeline_response) + deserialized = self._deserialize("BillingRoleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_invoice_section.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleDefinitions/{billingRoleDefinitionName}'} # type: ignore + get_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleDefinitions/{billingRoleDefinitionName}"} # type: ignore + + @distributed_trace_async async def get_by_billing_profile( - self, - billing_account_name: str, - billing_profile_name: str, - billing_role_definition_name: str, - **kwargs - ) -> "_models.BillingRoleDefinition": + self, billing_account_name: str, billing_profile_name: str, billing_role_definition_name: str, **kwargs: Any + ) -> _models.BillingRoleDefinition: """Gets the definition for a role on a billing profile. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param billing_role_definition_name: The ID that uniquely identifies a role definition. + Required. :type billing_role_definition_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: BillingRoleDefinition, or the result of cls(response) + :return: BillingRoleDefinition or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleDefinition - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingRoleDefinition"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get_by_billing_profile.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - 'billingRoleDefinitionName': self._serialize.url("billing_role_definition_name", billing_role_definition_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinition] + + request = build_get_by_billing_profile_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + billing_role_definition_name=billing_role_definition_name, + api_version=api_version, + template_url=self.get_by_billing_profile.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('BillingRoleDefinition', pipeline_response) + deserialized = self._deserialize("BillingRoleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_billing_profile.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleDefinitions/{billingRoleDefinitionName}'} # type: ignore + get_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleDefinitions/{billingRoleDefinitionName}"} # type: ignore + + @distributed_trace def list_by_billing_account( - self, - billing_account_name: str, - **kwargs - ) -> AsyncIterable["_models.BillingRoleDefinitionListResult"]: + self, billing_account_name: str, **kwargs: Any + ) -> AsyncIterable["_models.BillingRoleDefinition"]: """Lists the role definitions for a billing account. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either BillingRoleDefinitionListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleDefinitionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either BillingRoleDefinition or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleDefinition] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingRoleDefinitionListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinitionListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_account.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_account_request( + billing_account_name=billing_account_name, + api_version=api_version, + template_url=self.list_by_billing_account.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('BillingRoleDefinitionListResult', pipeline_response) + deserialized = self._deserialize("BillingRoleDefinitionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -286,77 +319,80 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_billing_account.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleDefinitions'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleDefinitions"} # type: ignore + @distributed_trace def list_by_invoice_section( - self, - billing_account_name: str, - billing_profile_name: str, - invoice_section_name: str, - **kwargs - ) -> AsyncIterable["_models.BillingRoleDefinitionListResult"]: + self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any + ) -> AsyncIterable["_models.BillingRoleDefinition"]: """Lists the role definitions for an invoice section. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str - :param invoice_section_name: The ID that uniquely identifies an invoice section. + :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either BillingRoleDefinitionListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleDefinitionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either BillingRoleDefinition or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleDefinition] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingRoleDefinitionListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinitionListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_invoice_section.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - 'invoiceSectionName': self._serialize.url("invoice_section_name", invoice_section_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_invoice_section_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + invoice_section_name=invoice_section_name, + api_version=api_version, + template_url=self.list_by_invoice_section.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('BillingRoleDefinitionListResult', pipeline_response) + deserialized = self._deserialize("BillingRoleDefinitionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -365,73 +401,77 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_invoice_section.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleDefinitions'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleDefinitions"} # type: ignore + @distributed_trace def list_by_billing_profile( - self, - billing_account_name: str, - billing_profile_name: str, - **kwargs - ) -> AsyncIterable["_models.BillingRoleDefinitionListResult"]: + self, billing_account_name: str, billing_profile_name: str, **kwargs: Any + ) -> AsyncIterable["_models.BillingRoleDefinition"]: """Lists the role definitions for a billing profile. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either BillingRoleDefinitionListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleDefinitionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either BillingRoleDefinition or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingRoleDefinition] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingRoleDefinitionListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinitionListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_profile.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_profile_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + api_version=api_version, + template_url=self.list_by_billing_profile.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('BillingRoleDefinitionListResult', pipeline_response) + deserialized = self._deserialize("BillingRoleDefinitionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -440,17 +480,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_billing_profile.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleDefinitions'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleDefinitions"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_billing_subscriptions_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_billing_subscriptions_operations.py index a147b51fbca7..0fdfe53c2f67 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_billing_subscriptions_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_billing_subscriptions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,96 +6,116 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._billing_subscriptions_operations import ( + build_get_request, + build_list_by_billing_account_request, + build_list_by_billing_profile_request, + build_list_by_customer_request, + build_list_by_invoice_section_request, + build_move_request, + build_update_request, + build_validate_move_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class BillingSubscriptionsOperations: - """BillingSubscriptionsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class BillingSubscriptionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s + :attr:`billing_subscriptions` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_by_customer( - self, - billing_account_name: str, - customer_name: str, - **kwargs - ) -> AsyncIterable["_models.BillingSubscriptionsListResult"]: + self, billing_account_name: str, customer_name: str, **kwargs: Any + ) -> AsyncIterable["_models.BillingSubscription"]: """Lists the subscriptions for a customer. The operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param customer_name: The ID that uniquely identifies a customer. + :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either BillingSubscriptionsListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingSubscriptionsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either BillingSubscription or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingSubscription] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingSubscriptionsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscriptionsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_customer.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'customerName': self._serialize.url("customer_name", customer_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_customer_request( + billing_account_name=billing_account_name, + customer_name=customer_name, + api_version=api_version, + template_url=self.list_by_customer.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('BillingSubscriptionsListResult', pipeline_response) + deserialized = self._deserialize("BillingSubscriptionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -103,69 +124,72 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_customer.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/billingSubscriptions'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list_by_customer.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/billingSubscriptions"} # type: ignore + + @distributed_trace def list_by_billing_account( - self, - billing_account_name: str, - **kwargs - ) -> AsyncIterable["_models.BillingSubscriptionsListResult"]: + self, billing_account_name: str, **kwargs: Any + ) -> AsyncIterable["_models.BillingSubscription"]: """Lists the subscriptions for a billing account. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either BillingSubscriptionsListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingSubscriptionsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either BillingSubscription or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingSubscription] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingSubscriptionsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscriptionsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_account.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_account_request( + billing_account_name=billing_account_name, + api_version=api_version, + template_url=self.list_by_billing_account.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('BillingSubscriptionsListResult', pipeline_response) + deserialized = self._deserialize("BillingSubscriptionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -174,74 +198,76 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_billing_account.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions"} # type: ignore + + @distributed_trace def list_by_billing_profile( - self, - billing_account_name: str, - billing_profile_name: str, - **kwargs - ) -> AsyncIterable["_models.BillingSubscriptionsListResult"]: + self, billing_account_name: str, billing_profile_name: str, **kwargs: Any + ) -> AsyncIterable["_models.BillingSubscription"]: """Lists the subscriptions that are billed to a billing profile. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either BillingSubscriptionsListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingSubscriptionsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either BillingSubscription or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingSubscription] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingSubscriptionsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscriptionsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_profile.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_profile_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + api_version=api_version, + template_url=self.list_by_billing_profile.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('BillingSubscriptionsListResult', pipeline_response) + deserialized = self._deserialize("BillingSubscriptionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -250,77 +276,78 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_billing_profile.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingSubscriptions'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingSubscriptions"} # type: ignore + + @distributed_trace def list_by_invoice_section( - self, - billing_account_name: str, - billing_profile_name: str, - invoice_section_name: str, - **kwargs - ) -> AsyncIterable["_models.BillingSubscriptionsListResult"]: + self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any + ) -> AsyncIterable["_models.BillingSubscription"]: """Lists the subscriptions that are billed to an invoice section. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str - :param invoice_section_name: The ID that uniquely identifies an invoice section. + :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either BillingSubscriptionsListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingSubscriptionsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either BillingSubscription or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.BillingSubscription] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingSubscriptionsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscriptionsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_invoice_section.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - 'invoiceSectionName': self._serialize.url("invoice_section_name", invoice_section_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_invoice_section_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + invoice_section_name=invoice_section_name, + api_version=api_version, + template_url=self.list_by_invoice_section.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('BillingSubscriptionsListResult', pipeline_response) + deserialized = self._deserialize("BillingSubscriptionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -329,331 +356,541 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_invoice_section.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingSubscriptions'} # type: ignore + return AsyncItemPaged(get_next, extract_data) - async def get( - self, - billing_account_name: str, - **kwargs - ) -> "_models.BillingSubscription": + list_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingSubscriptions"} # type: ignore + + @distributed_trace_async + async def get(self, billing_account_name: str, **kwargs: Any) -> _models.BillingSubscription: """Gets a subscription by its ID. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement and Microsoft Partner Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: BillingSubscription, or the result of cls(response) + :return: BillingSubscription or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingSubscription - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingSubscription"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscription] + + request = build_get_request( + billing_account_name=billing_account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('BillingSubscription', pipeline_response) + deserialized = self._deserialize("BillingSubscription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}'} # type: ignore + get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}"} # type: ignore + + @overload async def update( self, billing_account_name: str, - parameters: "_models.BillingSubscription", - **kwargs - ) -> "_models.BillingSubscription": + parameters: _models.BillingSubscription, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.BillingSubscription: """Updates the properties of a billing subscription. Currently, cost center can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the update billing subscription - operation. + operation. Required. :type parameters: ~azure.mgmt.billing.models.BillingSubscription + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: BillingSubscription or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.BillingSubscription + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, billing_account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.BillingSubscription: + """Updates the properties of a billing subscription. Currently, cost center can be updated. The + operation is supported only for billing accounts with agreement type Microsoft Customer + Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param parameters: Request parameters that are provided to the update billing subscription + operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: BillingSubscription or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.BillingSubscription + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update( + self, billing_account_name: str, parameters: Union[_models.BillingSubscription, IO], **kwargs: Any + ) -> _models.BillingSubscription: + """Updates the properties of a billing subscription. Currently, cost center can be updated. The + operation is supported only for billing accounts with agreement type Microsoft Customer + Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param parameters: Request parameters that are provided to the update billing subscription + operation. Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.billing.models.BillingSubscription or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: BillingSubscription, or the result of cls(response) + :return: BillingSubscription or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingSubscription - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingSubscription"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.update.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'BillingSubscription') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscription] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "BillingSubscription") + + request = build_update_request( + billing_account_name=billing_account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('BillingSubscription', pipeline_response) + deserialized = self._deserialize("BillingSubscription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}'} # type: ignore + + update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}"} # type: ignore async def _move_initial( self, billing_account_name: str, - parameters: "_models.TransferBillingSubscriptionRequestProperties", - **kwargs - ) -> Optional["_models.BillingSubscription"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.BillingSubscription"]] + parameters: Union[_models.TransferBillingSubscriptionRequestProperties, IO], + **kwargs: Any + ) -> Optional[_models.BillingSubscription]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self._move_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'TransferBillingSubscriptionRequestProperties') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.BillingSubscription]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "TransferBillingSubscriptionRequestProperties") + + request = build_move_request( + billing_account_name=billing_account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._move_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - response_headers = {} deserialized = None + response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('BillingSubscription', pipeline_response) + deserialized = self._deserialize("BillingSubscription", pipeline_response) if response.status_code == 202: - response_headers['Location']=self._deserialize('str', response.headers.get('Location')) - response_headers['Retry-After']=self._deserialize('int', response.headers.get('Retry-After')) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized - _move_initial.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}/move'} # type: ignore + _move_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}/move"} # type: ignore + + @overload async def begin_move( self, billing_account_name: str, - parameters: "_models.TransferBillingSubscriptionRequestProperties", - **kwargs - ) -> AsyncLROPoller["_models.BillingSubscription"]: + parameters: _models.TransferBillingSubscriptionRequestProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.BillingSubscription]: """Moves a subscription's charges to a new invoice section. The new invoice section must belong to the same billing profile as the existing invoice section. This operation is supported for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the move subscription operation. + Required. :type parameters: ~azure.mgmt.billing.models.TransferBillingSubscriptionRequestProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, - False for no polling, or your own initialized polling object for a personal polling strategy. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either BillingSubscription or the result of cls(response) + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either BillingSubscription or the result of + cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingSubscription] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingSubscription"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + async def begin_move( + self, billing_account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[_models.BillingSubscription]: + """Moves a subscription's charges to a new invoice section. The new invoice section must belong to + the same billing profile as the existing invoice section. This operation is supported for + billing accounts with agreement type Microsoft Customer Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param parameters: Request parameters that are provided to the move subscription operation. + Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either BillingSubscription or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingSubscription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_move( + self, + billing_account_name: str, + parameters: Union[_models.TransferBillingSubscriptionRequestProperties, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.BillingSubscription]: + """Moves a subscription's charges to a new invoice section. The new invoice section must belong to + the same billing profile as the existing invoice section. This operation is supported for + billing accounts with agreement type Microsoft Customer Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param parameters: Request parameters that are provided to the move subscription operation. Is + either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.billing.models.TransferBillingSubscriptionRequestProperties or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either BillingSubscription or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.BillingSubscription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscription] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._move_initial( + raw_result = await self._move_initial( # type: ignore billing_account_name=billing_account_name, parameters=parameters, - cls=lambda x,y,z: x, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('BillingSubscription', pipeline_response) - + deserialized = self._deserialize("BillingSubscription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - - if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_move.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}/move'} # type: ignore + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_move.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}/move"} # type: ignore + @overload async def validate_move( self, billing_account_name: str, - parameters: "_models.TransferBillingSubscriptionRequestProperties", - **kwargs - ) -> "_models.ValidateSubscriptionTransferEligibilityResult": + parameters: _models.TransferBillingSubscriptionRequestProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ValidateSubscriptionTransferEligibilityResult: """Validates if a subscription's charges can be moved to a new invoice section. This operation is supported for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the validate move eligibility - operation. + operation. Required. :type parameters: ~azure.mgmt.billing.models.TransferBillingSubscriptionRequestProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ValidateSubscriptionTransferEligibilityResult or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.ValidateSubscriptionTransferEligibilityResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def validate_move( + self, billing_account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ValidateSubscriptionTransferEligibilityResult: + """Validates if a subscription's charges can be moved to a new invoice section. This operation is + supported for billing accounts with agreement type Microsoft Customer Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param parameters: Request parameters that are provided to the validate move eligibility + operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ValidateSubscriptionTransferEligibilityResult or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.ValidateSubscriptionTransferEligibilityResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def validate_move( + self, + billing_account_name: str, + parameters: Union[_models.TransferBillingSubscriptionRequestProperties, IO], + **kwargs: Any + ) -> _models.ValidateSubscriptionTransferEligibilityResult: + """Validates if a subscription's charges can be moved to a new invoice section. This operation is + supported for billing accounts with agreement type Microsoft Customer Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param parameters: Request parameters that are provided to the validate move eligibility + operation. Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.billing.models.TransferBillingSubscriptionRequestProperties or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ValidateSubscriptionTransferEligibilityResult, or the result of cls(response) + :return: ValidateSubscriptionTransferEligibilityResult or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateSubscriptionTransferEligibilityResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ValidateSubscriptionTransferEligibilityResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.validate_move.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'TransferBillingSubscriptionRequestProperties') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidateSubscriptionTransferEligibilityResult] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "TransferBillingSubscriptionRequestProperties") + + request = build_validate_move_request( + billing_account_name=billing_account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.validate_move.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('ValidateSubscriptionTransferEligibilityResult', pipeline_response) + deserialized = self._deserialize("ValidateSubscriptionTransferEligibilityResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - validate_move.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}/validateMoveEligibility'} # type: ignore + + validate_move.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}/validateMoveEligibility"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_customers_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_customers_operations.py index a8635fd4abb1..b2f1ed42d073 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_customers_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_customers_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,105 +6,121 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._customers_operations import ( + build_get_request, + build_list_by_billing_account_request, + build_list_by_billing_profile_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class CustomersOperations: - """CustomersOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class CustomersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s + :attr:`customers` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, search: Optional[str] = None, filter: Optional[str] = None, - **kwargs - ) -> AsyncIterable["_models.CustomerListResult"]: + **kwargs: Any + ) -> AsyncIterable["_models.Customer"]: """Lists the customers that are billed to a billing profile. The operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param search: Used for searching customers by their name. Any customer with name containing - the search text will be included in the response. + the search text will be included in the response. Default value is None. :type search: str - :param filter: May be used to filter the list of customers. + :param filter: May be used to filter the list of customers. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either CustomerListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.CustomerListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Customer or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Customer] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CustomerListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomerListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_profile.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if search is not None: - query_parameters['$search'] = self._serialize.query("search", search, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_profile_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + search=search, + filter=filter, + api_version=api_version, + template_url=self.list_by_billing_profile.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('CustomerListResult', pipeline_response) + deserialized = self._deserialize("CustomerListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -112,80 +129,79 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_billing_profile.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/customers'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/customers"} # type: ignore + + @distributed_trace def list_by_billing_account( - self, - billing_account_name: str, - search: Optional[str] = None, - filter: Optional[str] = None, - **kwargs - ) -> AsyncIterable["_models.CustomerListResult"]: + self, billing_account_name: str, search: Optional[str] = None, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.Customer"]: """Lists the customers that are billed to a billing account. The operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param search: Used for searching customers by their name. Any customer with name containing - the search text will be included in the response. + the search text will be included in the response. Default value is None. :type search: str - :param filter: May be used to filter the list of customers. + :param filter: May be used to filter the list of customers. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either CustomerListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.CustomerListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Customer or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Customer] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CustomerListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomerListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_account.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if search is not None: - query_parameters['$search'] = self._serialize.query("search", search, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_account_request( + billing_account_name=billing_account_name, + search=search, + filter=filter, + api_version=api_version, + template_url=self.list_by_billing_account.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('CustomerListResult', pipeline_response) + deserialized = self._deserialize("CustomerListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -194,81 +210,82 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_billing_account.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers"} # type: ignore + @distributed_trace_async async def get( - self, - billing_account_name: str, - customer_name: str, - expand: Optional[str] = None, - **kwargs - ) -> "_models.Customer": + self, billing_account_name: str, customer_name: str, expand: Optional[str] = None, **kwargs: Any + ) -> _models.Customer: """Gets a customer by its ID. The operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param customer_name: The ID that uniquely identifies a customer. + :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str - :param expand: May be used to expand enabledAzurePlans and resellers. + :param expand: May be used to expand enabledAzurePlans and resellers. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Customer, or the result of cls(response) + :return: Customer or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Customer - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Customer"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'customerName': self._serialize.url("customer_name", customer_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if expand is not None: - query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Customer] + + request = build_get_request( + billing_account_name=billing_account_name, + customer_name=customer_name, + expand=expand, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Customer', pipeline_response) + deserialized = self._deserialize("Customer", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}'} # type: ignore + + get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_enrollment_accounts_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_enrollment_accounts_operations.py index 6d32fb128cef..1b87fff8fbcd 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_enrollment_accounts_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_enrollment_accounts_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,82 +6,98 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._enrollment_accounts_operations import build_get_request, build_list_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class EnrollmentAccountsOperations: - """EnrollmentAccountsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class EnrollmentAccountsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s + :attr:`enrollment_accounts` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def list( - self, - **kwargs - ) -> AsyncIterable["_models.EnrollmentAccountListResult"]: + @distributed_trace + def list(self, **kwargs: Any) -> AsyncIterable["_models.EnrollmentAccountSummary"]: """Lists the enrollment accounts the caller has access to. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either EnrollmentAccountListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.EnrollmentAccountListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either EnrollmentAccountSummary or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.EnrollmentAccountSummary] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.EnrollmentAccountListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.EnrollmentAccountListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-03-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - request = self._client.get(url, query_parameters, header_parameters) + request = build_list_request( + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('EnrollmentAccountListResult', pipeline_response) + deserialized = self._deserialize("EnrollmentAccountListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -89,71 +106,73 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.Billing/enrollmentAccounts'} # type: ignore + return AsyncItemPaged(get_next, extract_data) - async def get( - self, - name: str, - **kwargs - ) -> "_models.EnrollmentAccountSummary": + list.metadata = {"url": "/providers/Microsoft.Billing/enrollmentAccounts"} # type: ignore + + @distributed_trace_async + async def get(self, name: str, **kwargs: Any) -> _models.EnrollmentAccountSummary: """Gets a enrollment account by name. - :param name: Enrollment Account name. + :param name: Enrollment Account name. Required. :type name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: EnrollmentAccountSummary, or the result of cls(response) + :return: EnrollmentAccountSummary or the result of cls(response) :rtype: ~azure.mgmt.billing.models.EnrollmentAccountSummary - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.EnrollmentAccountSummary"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-03-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'name': self._serialize.url("name", name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.EnrollmentAccountSummary] + + request = build_get_request( + name=name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('EnrollmentAccountSummary', pipeline_response) + deserialized = self._deserialize("EnrollmentAccountSummary", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/providers/Microsoft.Billing/enrollmentAccounts/{name}'} # type: ignore + + get.metadata = {"url": "/providers/Microsoft.Billing/enrollmentAccounts/{name}"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_instructions_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_instructions_operations.py index f5b457ab7aba..12e0908a6fb1 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_instructions_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_instructions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,93 +6,108 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._instructions_operations import ( + build_get_request, + build_list_by_billing_profile_request, + build_put_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class InstructionsOperations: - """InstructionsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class InstructionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s + :attr:`instructions` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_by_billing_profile( - self, - billing_account_name: str, - billing_profile_name: str, - **kwargs - ) -> AsyncIterable["_models.InstructionListResult"]: + self, billing_account_name: str, billing_profile_name: str, **kwargs: Any + ) -> AsyncIterable["_models.Instruction"]: """Lists the instructions by billing profile id. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either InstructionListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.InstructionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Instruction or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Instruction] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.InstructionListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.InstructionListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_profile.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_profile_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + api_version=api_version, + template_url=self.list_by_billing_profile.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('InstructionListResult', pipeline_response) + deserialized = self._deserialize("InstructionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -100,151 +116,230 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_billing_profile.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions"} # type: ignore + @distributed_trace_async async def get( - self, - billing_account_name: str, - billing_profile_name: str, - instruction_name: str, - **kwargs - ) -> "_models.Instruction": + self, billing_account_name: str, billing_profile_name: str, instruction_name: str, **kwargs: Any + ) -> _models.Instruction: """Get the instruction by name. These are custom billing instructions and are only applicable for certain customers. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str - :param instruction_name: Instruction Name. + :param instruction_name: Instruction Name. Required. :type instruction_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Instruction, or the result of cls(response) + :return: Instruction or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Instruction - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Instruction"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - 'instructionName': self._serialize.url("instruction_name", instruction_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Instruction] + + request = build_get_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + instruction_name=instruction_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Instruction', pipeline_response) + deserialized = self._deserialize("Instruction", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions/{instructionName}'} # type: ignore + get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions/{instructionName}"} # type: ignore + + @overload async def put( self, billing_account_name: str, billing_profile_name: str, instruction_name: str, - parameters: "_models.Instruction", - **kwargs - ) -> "_models.Instruction": + parameters: _models.Instruction, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Instruction: """Creates or updates an instruction. These are custom billing instructions and are only applicable for certain customers. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str - :param instruction_name: Instruction Name. + :param instruction_name: Instruction Name. Required. :type instruction_name: str - :param parameters: The new instruction. + :param parameters: The new instruction. Required. :type parameters: ~azure.mgmt.billing.models.Instruction + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Instruction, or the result of cls(response) + :return: Instruction or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Instruction - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def put( + self, + billing_account_name: str, + billing_profile_name: str, + instruction_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Instruction: + """Creates or updates an instruction. These are custom billing instructions and are only + applicable for certain customers. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. + :type billing_profile_name: str + :param instruction_name: Instruction Name. Required. + :type instruction_name: str + :param parameters: The new instruction. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Instruction or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.Instruction + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def put( + self, + billing_account_name: str, + billing_profile_name: str, + instruction_name: str, + parameters: Union[_models.Instruction, IO], + **kwargs: Any + ) -> _models.Instruction: + """Creates or updates an instruction. These are custom billing instructions and are only + applicable for certain customers. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. + :type billing_profile_name: str + :param instruction_name: Instruction Name. Required. + :type instruction_name: str + :param parameters: The new instruction. Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.billing.models.Instruction or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Instruction or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.Instruction + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Instruction"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.put.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - 'instructionName': self._serialize.url("instruction_name", instruction_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'Instruction') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Instruction] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Instruction") + + request = build_put_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + instruction_name=instruction_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.put.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Instruction', pipeline_response) + deserialized = self._deserialize("Instruction", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - put.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions/{instructionName}'} # type: ignore + + put.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions/{instructionName}"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_invoice_sections_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_invoice_sections_operations.py index ffca6262fe47..d09e44342e00 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_invoice_sections_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_invoice_sections_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,96 +6,111 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._invoice_sections_operations import ( + build_create_or_update_request, + build_get_request, + build_list_by_billing_profile_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class InvoiceSectionsOperations: - """InvoiceSectionsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class InvoiceSectionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s + :attr:`invoice_sections` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_by_billing_profile( - self, - billing_account_name: str, - billing_profile_name: str, - **kwargs - ) -> AsyncIterable["_models.InvoiceSectionListResult"]: + self, billing_account_name: str, billing_profile_name: str, **kwargs: Any + ) -> AsyncIterable["_models.InvoiceSection"]: """Lists the invoice sections that a user has access to. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either InvoiceSectionListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.InvoiceSectionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either InvoiceSection or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.InvoiceSection] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.InvoiceSectionListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceSectionListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_profile.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_profile_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + api_version=api_version, + template_url=self.list_by_billing_profile.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('InvoiceSectionListResult', pipeline_response) + deserialized = self._deserialize("InvoiceSectionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -103,218 +119,317 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_billing_profile.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections"} # type: ignore + @distributed_trace_async async def get( - self, - billing_account_name: str, - billing_profile_name: str, - invoice_section_name: str, - **kwargs - ) -> "_models.InvoiceSection": + self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any + ) -> _models.InvoiceSection: """Gets an invoice section by its ID. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str - :param invoice_section_name: The ID that uniquely identifies an invoice section. + :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: InvoiceSection, or the result of cls(response) + :return: InvoiceSection or the result of cls(response) :rtype: ~azure.mgmt.billing.models.InvoiceSection - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.InvoiceSection"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - 'invoiceSectionName': self._serialize.url("invoice_section_name", invoice_section_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceSection] + + request = build_get_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + invoice_section_name=invoice_section_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('InvoiceSection', pipeline_response) + deserialized = self._deserialize("InvoiceSection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}'} # type: ignore + + get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}"} # type: ignore async def _create_or_update_initial( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, - parameters: "_models.InvoiceSection", - **kwargs - ) -> Optional["_models.InvoiceSection"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.InvoiceSection"]] + parameters: Union[_models.InvoiceSection, IO], + **kwargs: Any + ) -> Optional[_models.InvoiceSection]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self._create_or_update_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - 'invoiceSectionName': self._serialize.url("invoice_section_name", invoice_section_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'InvoiceSection') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.InvoiceSection]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "InvoiceSection") + + request = build_create_or_update_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + invoice_section_name=invoice_section_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - response_headers = {} deserialized = None + response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('InvoiceSection', pipeline_response) + deserialized = self._deserialize("InvoiceSection", pipeline_response) if response.status_code == 202: - response_headers['Location']=self._deserialize('str', response.headers.get('Location')) - response_headers['Retry-After']=self._deserialize('int', response.headers.get('Retry-After')) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized - _create_or_update_initial.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}'} # type: ignore + _create_or_update_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}"} # type: ignore + + @overload async def begin_create_or_update( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, - parameters: "_models.InvoiceSection", - **kwargs - ) -> AsyncLROPoller["_models.InvoiceSection"]: + parameters: _models.InvoiceSection, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.InvoiceSection]: """Creates or updates an invoice section. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str - :param invoice_section_name: The ID that uniquely identifies an invoice section. + :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str - :param parameters: The new or updated invoice section. + :param parameters: The new or updated invoice section. Required. :type parameters: ~azure.mgmt.billing.models.InvoiceSection + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, - False for no polling, or your own initialized polling object for a personal polling strategy. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either InvoiceSection or the result of cls(response) + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either InvoiceSection or the result of + cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.InvoiceSection] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.InvoiceSection"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + async def begin_create_or_update( + self, + billing_account_name: str, + billing_profile_name: str, + invoice_section_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.InvoiceSection]: + """Creates or updates an invoice section. The operation is supported only for billing accounts + with agreement type Microsoft Customer Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. + :type billing_profile_name: str + :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. + :type invoice_section_name: str + :param parameters: The new or updated invoice section. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either InvoiceSection or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.InvoiceSection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + billing_account_name: str, + billing_profile_name: str, + invoice_section_name: str, + parameters: Union[_models.InvoiceSection, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.InvoiceSection]: + """Creates or updates an invoice section. The operation is supported only for billing accounts + with agreement type Microsoft Customer Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. + :type billing_profile_name: str + :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. + :type invoice_section_name: str + :param parameters: The new or updated invoice section. Is either a model type or a IO type. + Required. + :type parameters: ~azure.mgmt.billing.models.InvoiceSection or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either InvoiceSection or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.InvoiceSection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceSection] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._create_or_update_initial( + raw_result = await self._create_or_update_initial( # type: ignore billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, parameters=parameters, - cls=lambda x,y,z: x, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('InvoiceSection', pipeline_response) - + deserialized = self._deserialize("InvoiceSection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - 'invoiceSectionName': self._serialize.url("invoice_section_name", invoice_section_name, 'str'), - } - - if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}'} # type: ignore + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_or_update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_invoices_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_invoices_operations.py index ac7fe13b4d95..8c9023887f72 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_invoices_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_invoices_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,103 +6,124 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, List, Optional, TypeVar, Union -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, List, Optional, TypeVar, Union, cast, overload from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._invoices_operations import ( + build_download_billing_subscription_invoice_request, + build_download_invoice_request, + build_download_multiple_billing_profile_invoices_request, + build_download_multiple_billing_subscription_invoices_request, + build_get_by_id_request, + build_get_by_subscription_and_invoice_id_request, + build_get_request, + build_list_by_billing_account_request, + build_list_by_billing_profile_request, + build_list_by_billing_subscription_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class InvoicesOperations: - """InvoicesOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class InvoicesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s + :attr:`invoices` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_by_billing_account( - self, - billing_account_name: str, - period_start_date: str, - period_end_date: str, - **kwargs - ) -> AsyncIterable["_models.InvoiceListResult"]: + self, billing_account_name: str, period_start_date: str, period_end_date: str, **kwargs: Any + ) -> AsyncIterable["_models.Invoice"]: """Lists the invoices for a billing account for a given start date and end date. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param period_start_date: The start date to fetch the invoices. The date should be specified in - MM-DD-YYYY format. + MM-DD-YYYY format. Required. :type period_start_date: str :param period_end_date: The end date to fetch the invoices. The date should be specified in - MM-DD-YYYY format. + MM-DD-YYYY format. Required. :type period_end_date: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either InvoiceListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.InvoiceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Invoice or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Invoice] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.InvoiceListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_account.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - query_parameters['periodStartDate'] = self._serialize.query("period_start_date", period_start_date, 'str') - query_parameters['periodEndDate'] = self._serialize.query("period_end_date", period_end_date, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_account_request( + billing_account_name=billing_account_name, + period_start_date=period_start_date, + period_end_date=period_end_date, + api_version=api_version, + template_url=self.list_by_billing_account.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('InvoiceListResult', pipeline_response) + deserialized = self._deserialize("InvoiceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -110,84 +132,89 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_billing_account.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices"} # type: ignore + + @distributed_trace def list_by_billing_profile( self, billing_account_name: str, billing_profile_name: str, period_start_date: str, period_end_date: str, - **kwargs - ) -> AsyncIterable["_models.InvoiceListResult"]: + **kwargs: Any + ) -> AsyncIterable["_models.Invoice"]: """Lists the invoices for a billing profile for a given start date and end date. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param period_start_date: The start date to fetch the invoices. The date should be specified in - MM-DD-YYYY format. + MM-DD-YYYY format. Required. :type period_start_date: str :param period_end_date: The end date to fetch the invoices. The date should be specified in - MM-DD-YYYY format. + MM-DD-YYYY format. Required. :type period_end_date: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either InvoiceListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.InvoiceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Invoice or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Invoice] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.InvoiceListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_profile.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - query_parameters['periodStartDate'] = self._serialize.query("period_start_date", period_start_date, 'str') - query_parameters['periodEndDate'] = self._serialize.query("period_end_date", period_end_date, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_profile_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + period_start_date=period_start_date, + period_end_date=period_end_date, + api_version=api_version, + template_url=self.list_by_billing_profile.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('InvoiceListResult', pipeline_response) + deserialized = self._deserialize("InvoiceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -196,439 +223,523 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_billing_profile.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoices'} # type: ignore + return AsyncItemPaged(get_next, extract_data) - async def get( - self, - billing_account_name: str, - invoice_name: str, - **kwargs - ) -> "_models.Invoice": + list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoices"} # type: ignore + + @distributed_trace_async + async def get(self, billing_account_name: str, invoice_name: str, **kwargs: Any) -> _models.Invoice: """Gets an invoice by billing account name and ID. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param invoice_name: The ID that uniquely identifies an invoice. + :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Invoice, or the result of cls(response) + :return: Invoice or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Invoice - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Invoice"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'invoiceName': self._serialize.url("invoice_name", invoice_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Invoice] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_request( + billing_account_name=billing_account_name, + invoice_name=invoice_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Invoice', pipeline_response) + deserialized = self._deserialize("Invoice", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}'} # type: ignore - async def get_by_id( - self, - invoice_name: str, - **kwargs - ) -> "_models.Invoice": + get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}"} # type: ignore + + @distributed_trace_async + async def get_by_id(self, invoice_name: str, **kwargs: Any) -> _models.Invoice: """Gets an invoice by ID. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. - :param invoice_name: The ID that uniquely identifies an invoice. + :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Invoice, or the result of cls(response) + :return: Invoice or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Invoice - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Invoice"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'invoiceName': self._serialize.url("invoice_name", invoice_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Invoice] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_get_by_id_request( + invoice_name=invoice_name, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Invoice', pipeline_response) + deserialized = self._deserialize("Invoice", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/default/invoices/{invoiceName}'} # type: ignore + + get_by_id.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/invoices/{invoiceName}"} # type: ignore async def _download_invoice_initial( - self, - billing_account_name: str, - invoice_name: str, - download_token: str, - **kwargs - ) -> Optional["_models.DownloadUrl"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.DownloadUrl"]] + self, billing_account_name: str, invoice_name: str, download_token: str, **kwargs: Any + ) -> Optional[_models.DownloadUrl]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self._download_invoice_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'invoiceName': self._serialize.url("invoice_name", invoice_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - query_parameters['downloadToken'] = self._serialize.query("download_token", download_token, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.DownloadUrl]] + + request = build_download_invoice_request( + billing_account_name=billing_account_name, + invoice_name=invoice_name, + download_token=download_token, + api_version=api_version, + template_url=self._download_invoice_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - response_headers = {} deserialized = None + response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('DownloadUrl', pipeline_response) + deserialized = self._deserialize("DownloadUrl", pipeline_response) if response.status_code == 202: - response_headers['Location']=self._deserialize('str', response.headers.get('Location')) - response_headers['Retry-After']=self._deserialize('str', response.headers.get('Retry-After')) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("str", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized - _download_invoice_initial.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}/download'} # type: ignore + _download_invoice_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}/download"} # type: ignore + + @distributed_trace_async async def begin_download_invoice( - self, - billing_account_name: str, - invoice_name: str, - download_token: str, - **kwargs - ) -> AsyncLROPoller["_models.DownloadUrl"]: + self, billing_account_name: str, invoice_name: str, download_token: str, **kwargs: Any + ) -> AsyncLROPoller[_models.DownloadUrl]: """Gets a URL to download an invoice. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param invoice_name: The ID that uniquely identifies an invoice. + :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str - :param download_token: Download token with document source and document ID. + :param download_token: Download token with document source and document ID. Required. :type download_token: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, - False for no polling, or your own initialized polling object for a personal polling strategy. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either DownloadUrl or the result of cls(response) + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DownloadUrl or the result of + cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DownloadUrl"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DownloadUrl] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._download_invoice_initial( + raw_result = await self._download_invoice_initial( # type: ignore billing_account_name=billing_account_name, invoice_name=invoice_name, download_token=download_token, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('DownloadUrl', pipeline_response) - + deserialized = self._deserialize("DownloadUrl", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'invoiceName': self._serialize.url("invoice_name", invoice_name, 'str'), - } - - if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_download_invoice.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}/download'} # type: ignore + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_download_invoice.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}/download"} # type: ignore async def _download_multiple_billing_profile_invoices_initial( - self, - billing_account_name: str, - download_urls: List[str], - **kwargs - ) -> Optional["_models.DownloadUrl"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.DownloadUrl"]] + self, billing_account_name: str, download_urls: Union[List[str], IO], **kwargs: Any + ) -> Optional[_models.DownloadUrl]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self._download_multiple_billing_profile_invoices_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(download_urls, '[str]') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.DownloadUrl]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(download_urls, (IO, bytes)): + _content = download_urls + else: + _json = self._serialize.body(download_urls, "[str]") + + request = build_download_multiple_billing_profile_invoices_request( + billing_account_name=billing_account_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._download_multiple_billing_profile_invoices_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - response_headers = {} deserialized = None + response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('DownloadUrl', pipeline_response) + deserialized = self._deserialize("DownloadUrl", pipeline_response) if response.status_code == 202: - response_headers['Location']=self._deserialize('str', response.headers.get('Location')) - response_headers['Retry-After']=self._deserialize('str', response.headers.get('Retry-After')) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("str", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized - _download_multiple_billing_profile_invoices_initial.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/downloadDocuments'} # type: ignore + _download_multiple_billing_profile_invoices_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/downloadDocuments"} # type: ignore + + @overload async def begin_download_multiple_billing_profile_invoices( self, billing_account_name: str, download_urls: List[str], - **kwargs - ) -> AsyncLROPoller["_models.DownloadUrl"]: + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DownloadUrl]: """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as a zip file. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param download_urls: An array of download urls for individual documents. + :param download_urls: An array of download urls for individual documents. Required. :type download_urls: list[str] + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, - False for no polling, or your own initialized polling object for a personal polling strategy. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either DownloadUrl or the result of cls(response) + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DownloadUrl or the result of + cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DownloadUrl"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + async def begin_download_multiple_billing_profile_invoices( + self, billing_account_name: str, download_urls: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[_models.DownloadUrl]: + """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as + a zip file. The operation is supported for billing accounts with agreement type Microsoft + Partner Agreement or Microsoft Customer Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param download_urls: An array of download urls for individual documents. Required. + :type download_urls: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DownloadUrl or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DownloadUrl] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_download_multiple_billing_profile_invoices( + self, billing_account_name: str, download_urls: Union[List[str], IO], **kwargs: Any + ) -> AsyncLROPoller[_models.DownloadUrl]: + """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as + a zip file. The operation is supported for billing accounts with agreement type Microsoft + Partner Agreement or Microsoft Customer Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param download_urls: An array of download urls for individual documents. Is either a list type + or a IO type. Required. + :type download_urls: list[str] or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DownloadUrl or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DownloadUrl] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.DownloadUrl] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._download_multiple_billing_profile_invoices_initial( + raw_result = await self._download_multiple_billing_profile_invoices_initial( # type: ignore billing_account_name=billing_account_name, download_urls=download_urls, - cls=lambda x,y,z: x, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('DownloadUrl', pipeline_response) - + deserialized = self._deserialize("DownloadUrl", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - } - - if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_download_multiple_billing_profile_invoices.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/downloadDocuments'} # type: ignore + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_download_multiple_billing_profile_invoices.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/downloadDocuments"} # type: ignore + + @distributed_trace def list_by_billing_subscription( - self, - period_start_date: str, - period_end_date: str, - **kwargs - ) -> AsyncIterable["_models.InvoiceListResult"]: + self, period_start_date: str, period_end_date: str, **kwargs: Any + ) -> AsyncIterable["_models.Invoice"]: """Lists the invoices for a subscription. - :param period_start_date: Invoice period start date. + :param period_start_date: Invoice period start date. Required. :type period_start_date: str - :param period_end_date: Invoice period end date. + :param period_end_date: Invoice period end date. Required. :type period_end_date: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either InvoiceListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.InvoiceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Invoice or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Invoice] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.InvoiceListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['periodStartDate'] = self._serialize.query("period_start_date", period_start_date, 'str') - query_parameters['periodEndDate'] = self._serialize.query("period_end_date", period_end_date, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_subscription_request( + subscription_id=self._config.subscription_id, + period_start_date=period_start_date, + period_end_date=period_end_date, + api_version=api_version, + template_url=self.list_by_billing_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('InvoiceListResult', pipeline_response) + deserialized = self._deserialize("InvoiceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -637,312 +748,388 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_billing_subscription.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices'} # type: ignore + return AsyncItemPaged(get_next, extract_data) - async def get_by_subscription_and_invoice_id( - self, - invoice_name: str, - **kwargs - ) -> "_models.Invoice": + list_by_billing_subscription.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices"} # type: ignore + + @distributed_trace_async + async def get_by_subscription_and_invoice_id(self, invoice_name: str, **kwargs: Any) -> _models.Invoice: """Gets an invoice by subscription ID and invoice ID. - :param invoice_name: The ID that uniquely identifies an invoice. + :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Invoice, or the result of cls(response) + :return: Invoice or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Invoice - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Invoice"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get_by_subscription_and_invoice_id.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'invoiceName': self._serialize.url("invoice_name", invoice_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Invoice] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_get_by_subscription_and_invoice_id_request( + invoice_name=invoice_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_by_subscription_and_invoice_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Invoice', pipeline_response) + deserialized = self._deserialize("Invoice", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_subscription_and_invoice_id.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices/{invoiceName}'} # type: ignore + + get_by_subscription_and_invoice_id.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices/{invoiceName}"} # type: ignore async def _download_billing_subscription_invoice_initial( - self, - invoice_name: str, - download_token: str, - **kwargs - ) -> Optional["_models.DownloadUrl"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.DownloadUrl"]] + self, invoice_name: str, download_token: str, **kwargs: Any + ) -> Optional[_models.DownloadUrl]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self._download_billing_subscription_invoice_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'invoiceName': self._serialize.url("invoice_name", invoice_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - query_parameters['downloadToken'] = self._serialize.query("download_token", download_token, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.DownloadUrl]] + + request = build_download_billing_subscription_invoice_request( + invoice_name=invoice_name, + subscription_id=self._config.subscription_id, + download_token=download_token, + api_version=api_version, + template_url=self._download_billing_subscription_invoice_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - response_headers = {} deserialized = None + response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('DownloadUrl', pipeline_response) + deserialized = self._deserialize("DownloadUrl", pipeline_response) if response.status_code == 202: - response_headers['Location']=self._deserialize('str', response.headers.get('Location')) - response_headers['Retry-After']=self._deserialize('str', response.headers.get('Retry-After')) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("str", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized - _download_billing_subscription_invoice_initial.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices/{invoiceName}/download'} # type: ignore + _download_billing_subscription_invoice_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices/{invoiceName}/download"} # type: ignore + + @distributed_trace_async async def begin_download_billing_subscription_invoice( - self, - invoice_name: str, - download_token: str, - **kwargs - ) -> AsyncLROPoller["_models.DownloadUrl"]: + self, invoice_name: str, download_token: str, **kwargs: Any + ) -> AsyncLROPoller[_models.DownloadUrl]: """Gets a URL to download an invoice. - :param invoice_name: The ID that uniquely identifies an invoice. + :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str - :param download_token: Download token with document source and document ID. + :param download_token: Download token with document source and document ID. Required. :type download_token: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, - False for no polling, or your own initialized polling object for a personal polling strategy. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either DownloadUrl or the result of cls(response) + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DownloadUrl or the result of + cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DownloadUrl"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DownloadUrl] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._download_billing_subscription_invoice_initial( + raw_result = await self._download_billing_subscription_invoice_initial( # type: ignore invoice_name=invoice_name, download_token=download_token, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('DownloadUrl', pipeline_response) - + deserialized = self._deserialize("DownloadUrl", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'invoiceName': self._serialize.url("invoice_name", invoice_name, 'str'), - } - - if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_download_billing_subscription_invoice.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices/{invoiceName}/download'} # type: ignore + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_download_billing_subscription_invoice.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices/{invoiceName}/download"} # type: ignore async def _download_multiple_billing_subscription_invoices_initial( - self, - download_urls: List[str], - **kwargs - ) -> Optional["_models.DownloadUrl"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.DownloadUrl"]] + self, download_urls: Union[List[str], IO], **kwargs: Any + ) -> Optional[_models.DownloadUrl]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self._download_multiple_billing_subscription_invoices_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(download_urls, '[str]') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.DownloadUrl]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(download_urls, (IO, bytes)): + _content = download_urls + else: + _json = self._serialize.body(download_urls, "[str]") + + request = build_download_multiple_billing_subscription_invoices_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._download_multiple_billing_subscription_invoices_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - response_headers = {} deserialized = None + response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('DownloadUrl', pipeline_response) + deserialized = self._deserialize("DownloadUrl", pipeline_response) if response.status_code == 202: - response_headers['Location']=self._deserialize('str', response.headers.get('Location')) - response_headers['Retry-After']=self._deserialize('str', response.headers.get('Retry-After')) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("str", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized - _download_multiple_billing_subscription_invoices_initial.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/downloadDocuments'} # type: ignore + _download_multiple_billing_subscription_invoices_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/downloadDocuments"} # type: ignore + + @overload async def begin_download_multiple_billing_subscription_invoices( - self, - download_urls: List[str], - **kwargs - ) -> AsyncLROPoller["_models.DownloadUrl"]: + self, download_urls: List[str], *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[_models.DownloadUrl]: """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as a zip file. - :param download_urls: An array of download urls for individual documents. + :param download_urls: An array of download urls for individual documents. Required. :type download_urls: list[str] + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, - False for no polling, or your own initialized polling object for a personal polling strategy. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either DownloadUrl or the result of cls(response) + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DownloadUrl or the result of + cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DownloadUrl"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + async def begin_download_multiple_billing_subscription_invoices( + self, download_urls: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[_models.DownloadUrl]: + """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as + a zip file. + + :param download_urls: An array of download urls for individual documents. Required. + :type download_urls: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DownloadUrl or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DownloadUrl] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_download_multiple_billing_subscription_invoices( + self, download_urls: Union[List[str], IO], **kwargs: Any + ) -> AsyncLROPoller[_models.DownloadUrl]: + """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as + a zip file. + + :param download_urls: An array of download urls for individual documents. Is either a list type + or a IO type. Required. + :type download_urls: list[str] or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DownloadUrl or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.billing.models.DownloadUrl] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.DownloadUrl] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._download_multiple_billing_subscription_invoices_initial( + raw_result = await self._download_multiple_billing_subscription_invoices_initial( # type: ignore download_urls=download_urls, - cls=lambda x,y,z: x, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('DownloadUrl', pipeline_response) - + deserialized = self._deserialize("DownloadUrl", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - - if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_download_multiple_billing_subscription_invoices.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/downloadDocuments'} # type: ignore + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_download_multiple_billing_subscription_invoices.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/downloadDocuments"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_operations.py index 4ed3179d761e..276c5f7379cf 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,82 +6,95 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._operations import build_list_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class Operations: - """Operations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s + :attr:`operations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def list( - self, - **kwargs - ) -> AsyncIterable["_models.OperationListResult"]: + @distributed_trace + def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: """Lists the available billing REST API operations. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either OperationListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.OperationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - request = self._client.get(url, query_parameters, header_parameters) + request = build_list_request( + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('OperationListResult', pipeline_response) + deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -89,17 +103,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.OperationsErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.Billing/operations'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Billing/operations"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_patch.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_policies_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_policies_operations.py index 4a328375a609..566e719e56b0 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_policies_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_policies_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,289 +6,451 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Generic, Optional, TypeVar -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._policies_operations import ( + build_get_by_billing_profile_request, + build_get_by_customer_request, + build_update_customer_request, + build_update_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class PoliciesOperations: - """PoliciesOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class PoliciesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s + :attr:`policies` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace_async async def get_by_billing_profile( - self, - billing_account_name: str, - billing_profile_name: str, - **kwargs - ) -> "_models.Policy": + self, billing_account_name: str, billing_profile_name: str, **kwargs: Any + ) -> _models.Policy: """Lists the policies for a billing profile. This operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Policy, or the result of cls(response) + :return: Policy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Policy - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Policy"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get_by_billing_profile.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Policy] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_by_billing_profile_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + api_version=api_version, + template_url=self.get_by_billing_profile.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Policy', pipeline_response) + deserialized = self._deserialize("Policy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_billing_profile.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/policies/default'} # type: ignore + get_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/policies/default"} # type: ignore + + @overload async def update( self, billing_account_name: str, billing_profile_name: str, - parameters: "_models.Policy", - **kwargs - ) -> "_models.Policy": + parameters: _models.Policy, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Policy: """Updates the policies for a billing profile. This operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param parameters: Request parameters that are provided to the update policies operation. + Required. :type parameters: ~azure.mgmt.billing.models.Policy + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Policy or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.Policy + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + billing_account_name: str, + billing_profile_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Policy: + """Updates the policies for a billing profile. This operation is supported only for billing + accounts with agreement type Microsoft Customer Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. + :type billing_profile_name: str + :param parameters: Request parameters that are provided to the update policies operation. + Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Policy, or the result of cls(response) + :return: Policy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Policy - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update( + self, billing_account_name: str, billing_profile_name: str, parameters: Union[_models.Policy, IO], **kwargs: Any + ) -> _models.Policy: + """Updates the policies for a billing profile. This operation is supported only for billing + accounts with agreement type Microsoft Customer Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. + :type billing_profile_name: str + :param parameters: Request parameters that are provided to the update policies operation. Is + either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.billing.models.Policy or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Policy or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.Policy + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Policy"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.update.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'Policy') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Policy] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Policy") + + request = build_update_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Policy', pipeline_response) + deserialized = self._deserialize("Policy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/policies/default'} # type: ignore + update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/policies/default"} # type: ignore + + @distributed_trace_async async def get_by_customer( - self, - billing_account_name: str, - customer_name: str, - **kwargs - ) -> "_models.CustomerPolicy": + self, billing_account_name: str, customer_name: str, **kwargs: Any + ) -> _models.CustomerPolicy: """Lists the policies for a customer. This operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param customer_name: The ID that uniquely identifies a customer. + :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: CustomerPolicy, or the result of cls(response) + :return: CustomerPolicy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.CustomerPolicy - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CustomerPolicy"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get_by_customer.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'customerName': self._serialize.url("customer_name", customer_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomerPolicy] + + request = build_get_by_customer_request( + billing_account_name=billing_account_name, + customer_name=customer_name, + api_version=api_version, + template_url=self.get_by_customer.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('CustomerPolicy', pipeline_response) + deserialized = self._deserialize("CustomerPolicy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_customer.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/policies/default'} # type: ignore + get_by_customer.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/policies/default"} # type: ignore + + @overload async def update_customer( self, billing_account_name: str, customer_name: str, - parameters: "_models.CustomerPolicy", - **kwargs - ) -> "_models.CustomerPolicy": + parameters: _models.CustomerPolicy, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CustomerPolicy: """Updates the policies for a customer. This operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param customer_name: The ID that uniquely identifies a customer. + :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :param parameters: Request parameters that are provided to the update policies operation. + Required. :type parameters: ~azure.mgmt.billing.models.CustomerPolicy + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: CustomerPolicy or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.CustomerPolicy + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update_customer( + self, + billing_account_name: str, + customer_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CustomerPolicy: + """Updates the policies for a customer. This operation is supported only for billing accounts with + agreement type Microsoft Partner Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param customer_name: The ID that uniquely identifies a customer. Required. + :type customer_name: str + :param parameters: Request parameters that are provided to the update policies operation. + Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: CustomerPolicy, or the result of cls(response) + :return: CustomerPolicy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.CustomerPolicy - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update_customer( + self, + billing_account_name: str, + customer_name: str, + parameters: Union[_models.CustomerPolicy, IO], + **kwargs: Any + ) -> _models.CustomerPolicy: + """Updates the policies for a customer. This operation is supported only for billing accounts with + agreement type Microsoft Partner Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param customer_name: The ID that uniquely identifies a customer. Required. + :type customer_name: str + :param parameters: Request parameters that are provided to the update policies operation. Is + either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.billing.models.CustomerPolicy or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: CustomerPolicy or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.CustomerPolicy + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CustomerPolicy"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.update_customer.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'customerName': self._serialize.url("customer_name", customer_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'CustomerPolicy') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomerPolicy] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "CustomerPolicy") + + request = build_update_customer_request( + billing_account_name=billing_account_name, + customer_name=customer_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update_customer.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('CustomerPolicy', pipeline_response) + deserialized = self._deserialize("CustomerPolicy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update_customer.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/policies/default'} # type: ignore + + update_customer.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/policies/default"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_products_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_products_operations.py index 1d172ed50a34..68739b193a33 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_products_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_products_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,95 +6,115 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._products_operations import ( + build_get_request, + build_list_by_billing_account_request, + build_list_by_billing_profile_request, + build_list_by_customer_request, + build_list_by_invoice_section_request, + build_move_request, + build_update_request, + build_validate_move_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class ProductsOperations: - """ProductsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class ProductsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s + :attr:`products` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_by_customer( - self, - billing_account_name: str, - customer_name: str, - **kwargs - ) -> AsyncIterable["_models.ProductsListResult"]: + self, billing_account_name: str, customer_name: str, **kwargs: Any + ) -> AsyncIterable["_models.Product"]: """Lists the products for a customer. These don't include products billed based on usage.The operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param customer_name: The ID that uniquely identifies a customer. + :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ProductsListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.ProductsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Product or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Product] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ProductsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ProductsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_customer.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'customerName': self._serialize.url("customer_name", customer_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_customer_request( + billing_account_name=billing_account_name, + customer_name=customer_name, + api_version=api_version, + template_url=self.list_by_customer.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('ProductsListResult', pipeline_response) + deserialized = self._deserialize("ProductsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -102,77 +123,78 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_customer.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/products'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_by_customer.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/products"} # type: ignore + @distributed_trace def list_by_billing_account( - self, - billing_account_name: str, - filter: Optional[str] = None, - **kwargs - ) -> AsyncIterable["_models.ProductsListResult"]: + self, billing_account_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.Product"]: """Lists the products for a billing account. These don't include products billed based on usage. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param filter: May be used to filter by product type. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Tag filter is a key - value pair string where key and value are separated by a colon (:). + value pair string where key and value are separated by a colon (:). Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ProductsListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.ProductsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Product or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Product] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ProductsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ProductsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_account.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_account_request( + billing_account_name=billing_account_name, + filter=filter, + api_version=api_version, + template_url=self.list_by_billing_account.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('ProductsListResult', pipeline_response) + deserialized = self._deserialize("ProductsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -181,81 +203,81 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_billing_account.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products"} # type: ignore + @distributed_trace def list_by_billing_profile( - self, - billing_account_name: str, - billing_profile_name: str, - filter: Optional[str] = None, - **kwargs - ) -> AsyncIterable["_models.ProductsListResult"]: + self, billing_account_name: str, billing_profile_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.Product"]: """Lists the products for a billing profile. These don't include products billed based on usage. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param filter: May be used to filter by product type. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Tag filter is a key - value pair string where key and value are separated by a colon (:). + value pair string where key and value are separated by a colon (:). Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ProductsListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.ProductsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Product or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Product] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ProductsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ProductsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_profile.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_profile_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + filter=filter, + api_version=api_version, + template_url=self.list_by_billing_profile.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('ProductsListResult', pipeline_response) + deserialized = self._deserialize("ProductsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -264,85 +286,89 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_billing_profile.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/products'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/products"} # type: ignore + + @distributed_trace def list_by_invoice_section( self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, filter: Optional[str] = None, - **kwargs - ) -> AsyncIterable["_models.ProductsListResult"]: + **kwargs: Any + ) -> AsyncIterable["_models.Product"]: """Lists the products for an invoice section. These don't include products billed based on usage. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str - :param invoice_section_name: The ID that uniquely identifies an invoice section. + :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param filter: May be used to filter by product type. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Tag filter is a key - value pair string where key and value are separated by a colon (:). + value pair string where key and value are separated by a colon (:). Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ProductsListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.ProductsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Product or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Product] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ProductsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ProductsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_invoice_section.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - 'invoiceSectionName': self._serialize.url("invoice_section_name", invoice_section_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_invoice_section_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + invoice_section_name=invoice_section_name, + filter=filter, + api_version=api_version, + template_url=self.list_by_invoice_section.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('ProductsListResult', pipeline_response) + deserialized = self._deserialize("ProductsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -351,288 +377,512 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_invoice_section.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/products'} # type: ignore + return AsyncItemPaged(get_next, extract_data) - async def get( - self, - billing_account_name: str, - product_name: str, - **kwargs - ) -> "_models.Product": + list_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/products"} # type: ignore + + @distributed_trace_async + async def get(self, billing_account_name: str, product_name: str, **kwargs: Any) -> _models.Product: """Gets a product by ID. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param product_name: The ID that uniquely identifies a product. + :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Product, or the result of cls(response) + :return: Product or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Product - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Product"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'productName': self._serialize.url("product_name", product_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Product] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_request( + billing_account_name=billing_account_name, + product_name=product_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Product', pipeline_response) + deserialized = self._deserialize("Product", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}'} # type: ignore + get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}"} # type: ignore + + @overload async def update( self, billing_account_name: str, product_name: str, - parameters: "_models.Product", - **kwargs - ) -> "_models.Product": + parameters: _models.Product, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Product: """Updates the properties of a Product. Currently, auto renew can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param product_name: The ID that uniquely identifies a product. + :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the update product operation. + Required. :type parameters: ~azure.mgmt.billing.models.Product + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Product, or the result of cls(response) + :return: Product or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Product - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + billing_account_name: str, + product_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Product: + """Updates the properties of a Product. Currently, auto renew can be updated. The operation is + supported only for billing accounts with agreement type Microsoft Customer Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param product_name: The ID that uniquely identifies a product. Required. + :type product_name: str + :param parameters: Request parameters that are provided to the update product operation. + Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Product or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.Product + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update( + self, billing_account_name: str, product_name: str, parameters: Union[_models.Product, IO], **kwargs: Any + ) -> _models.Product: + """Updates the properties of a Product. Currently, auto renew can be updated. The operation is + supported only for billing accounts with agreement type Microsoft Customer Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param product_name: The ID that uniquely identifies a product. Required. + :type product_name: str + :param parameters: Request parameters that are provided to the update product operation. Is + either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.billing.models.Product or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Product or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.Product + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Product"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.update.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'productName': self._serialize.url("product_name", product_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'Product') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Product] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Product") + + request = build_update_request( + billing_account_name=billing_account_name, + product_name=product_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Product', pipeline_response) + deserialized = self._deserialize("Product", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}'} # type: ignore + update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}"} # type: ignore + + @overload async def move( self, billing_account_name: str, product_name: str, - parameters: "_models.TransferProductRequestProperties", - **kwargs - ) -> Optional["_models.Product"]: + parameters: _models.TransferProductRequestProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Optional[_models.Product]: """Moves a product's charges to a new invoice section. The new invoice section must belong to the same billing profile as the existing invoice section. This operation is supported only for products that are purchased with a recurring charge and for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param product_name: The ID that uniquely identifies a product. + :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the move product operation. + Required. :type parameters: ~azure.mgmt.billing.models.TransferProductRequestProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Product or None or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.Product or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def move( + self, + billing_account_name: str, + product_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Optional[_models.Product]: + """Moves a product's charges to a new invoice section. The new invoice section must belong to the + same billing profile as the existing invoice section. This operation is supported only for + products that are purchased with a recurring charge and for billing accounts with agreement + type Microsoft Customer Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param product_name: The ID that uniquely identifies a product. Required. + :type product_name: str + :param parameters: Request parameters that are provided to the move product operation. + Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Product, or the result of cls(response) + :return: Product or None or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Product or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def move( + self, + billing_account_name: str, + product_name: str, + parameters: Union[_models.TransferProductRequestProperties, IO], + **kwargs: Any + ) -> Optional[_models.Product]: + """Moves a product's charges to a new invoice section. The new invoice section must belong to the + same billing profile as the existing invoice section. This operation is supported only for + products that are purchased with a recurring charge and for billing accounts with agreement + type Microsoft Customer Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param product_name: The ID that uniquely identifies a product. Required. + :type product_name: str + :param parameters: Request parameters that are provided to the move product operation. Is + either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.billing.models.TransferProductRequestProperties or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Product or None or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.Product or None + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Product"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.move.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'productName': self._serialize.url("product_name", product_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'TransferProductRequestProperties') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.Product]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "TransferProductRequestProperties") + + request = build_move_request( + billing_account_name=billing_account_name, + product_name=product_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.move.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - response_headers = {} deserialized = None + response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('Product', pipeline_response) + deserialized = self._deserialize("Product", pipeline_response) if response.status_code == 202: - response_headers['Location']=self._deserialize('str', response.headers.get('Location')) - response_headers['Retry-After']=self._deserialize('int', response.headers.get('Retry-After')) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized - move.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}/move'} # type: ignore + move.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}/move"} # type: ignore + + @overload async def validate_move( self, billing_account_name: str, product_name: str, - parameters: "_models.TransferProductRequestProperties", - **kwargs - ) -> "_models.ValidateProductTransferEligibilityResult": + parameters: _models.TransferProductRequestProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ValidateProductTransferEligibilityResult: """Validates if a product's charges can be moved to a new invoice section. This operation is supported only for products that are purchased with a recurring charge and for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param product_name: The ID that uniquely identifies a product. + :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the validate move eligibility - operation. + operation. Required. :type parameters: ~azure.mgmt.billing.models.TransferProductRequestProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ValidateProductTransferEligibilityResult or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.ValidateProductTransferEligibilityResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def validate_move( + self, + billing_account_name: str, + product_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ValidateProductTransferEligibilityResult: + """Validates if a product's charges can be moved to a new invoice section. This operation is + supported only for products that are purchased with a recurring charge and for billing accounts + with agreement type Microsoft Customer Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param product_name: The ID that uniquely identifies a product. Required. + :type product_name: str + :param parameters: Request parameters that are provided to the validate move eligibility + operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ValidateProductTransferEligibilityResult or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.ValidateProductTransferEligibilityResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def validate_move( + self, + billing_account_name: str, + product_name: str, + parameters: Union[_models.TransferProductRequestProperties, IO], + **kwargs: Any + ) -> _models.ValidateProductTransferEligibilityResult: + """Validates if a product's charges can be moved to a new invoice section. This operation is + supported only for products that are purchased with a recurring charge and for billing accounts + with agreement type Microsoft Customer Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param product_name: The ID that uniquely identifies a product. Required. + :type product_name: str + :param parameters: Request parameters that are provided to the validate move eligibility + operation. Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.billing.models.TransferProductRequestProperties or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ValidateProductTransferEligibilityResult, or the result of cls(response) + :return: ValidateProductTransferEligibilityResult or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateProductTransferEligibilityResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ValidateProductTransferEligibilityResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.validate_move.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'productName': self._serialize.url("product_name", product_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'TransferProductRequestProperties') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidateProductTransferEligibilityResult] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "TransferProductRequestProperties") + + request = build_validate_move_request( + billing_account_name=billing_account_name, + product_name=product_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.validate_move.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('ValidateProductTransferEligibilityResult', pipeline_response) + deserialized = self._deserialize("ValidateProductTransferEligibilityResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - validate_move.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}/validateMoveEligibility'} # type: ignore + + validate_move.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}/validateMoveEligibility"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_reservations_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_reservations_operations.py index f18d918e8450..5acd0de504bf 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_reservations_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_reservations_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,42 +6,55 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._reservations_operations import ( + build_list_by_billing_account_request, + build_list_by_billing_profile_request, +) -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class ReservationsOperations: - """ReservationsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class ReservationsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s + :attr:`reservations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_by_billing_account( self, billing_account_name: str, @@ -48,69 +62,69 @@ def list_by_billing_account( orderby: Optional[str] = None, refresh_summary: Optional[str] = None, selected_state: Optional[str] = None, - **kwargs - ) -> AsyncIterable["_models.ReservationsListResult"]: + **kwargs: Any + ) -> AsyncIterable["_models.Reservation"]: """Lists the reservations for a billing account and the roll up counts of reservations group by provisioning states. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param filter: May be used to filter by reservation properties. The filter supports 'eq', 'or', - and 'and'. It does not currently support 'ne', 'gt', 'le', 'ge', or 'not'. + and 'and'. It does not currently support 'ne', 'gt', 'le', 'ge', or 'not'. Default value is + None. :type filter: str - :param orderby: May be used to sort order by reservation properties. + :param orderby: May be used to sort order by reservation properties. Default value is None. :type orderby: str :param refresh_summary: To indicate whether to refresh the roll up counts of the reservations - group by provisioning states. + group by provisioning states. Default value is None. :type refresh_summary: str - :param selected_state: The selected provisioning state. + :param selected_state: The selected provisioning state. Default value is None. :type selected_state: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ReservationsListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.ReservationsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Reservation or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Reservation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ReservationsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ReservationsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_account.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - if orderby is not None: - query_parameters['$orderby'] = self._serialize.query("orderby", orderby, 'str') - if refresh_summary is not None: - query_parameters['refreshSummary'] = self._serialize.query("refresh_summary", refresh_summary, 'str') - if selected_state is not None: - query_parameters['selectedState'] = self._serialize.query("selected_state", selected_state, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_account_request( + billing_account_name=billing_account_name, + filter=filter, + orderby=orderby, + refresh_summary=refresh_summary, + selected_state=selected_state, + api_version=api_version, + template_url=self.list_by_billing_account.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('ReservationsListResult', pipeline_response) + deserialized = self._deserialize("ReservationsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -119,21 +133,23 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_billing_account.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/reservations'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/reservations"} # type: ignore + + @distributed_trace def list_by_billing_profile( self, billing_account_name: str, @@ -142,72 +158,72 @@ def list_by_billing_profile( orderby: Optional[str] = None, refresh_summary: Optional[str] = None, selected_state: Optional[str] = None, - **kwargs - ) -> AsyncIterable["_models.ReservationsListResult"]: + **kwargs: Any + ) -> AsyncIterable["_models.Reservation"]: """Lists the reservations for a billing profile and the roll up counts of reservations group by provisioning state. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param filter: May be used to filter by reservation properties. The filter supports 'eq', 'or', - and 'and'. It does not currently support 'ne', 'gt', 'le', 'ge', or 'not'. + and 'and'. It does not currently support 'ne', 'gt', 'le', 'ge', or 'not'. Default value is + None. :type filter: str - :param orderby: May be used to sort order by reservation properties. + :param orderby: May be used to sort order by reservation properties. Default value is None. :type orderby: str :param refresh_summary: To indicate whether to refresh the roll up counts of the reservations - group by provisioning state. + group by provisioning state. Default value is None. :type refresh_summary: str - :param selected_state: The selected provisioning state. + :param selected_state: The selected provisioning state. Default value is None. :type selected_state: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ReservationsListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.ReservationsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Reservation or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Reservation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ReservationsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ReservationsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_profile.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - if orderby is not None: - query_parameters['$orderby'] = self._serialize.query("orderby", orderby, 'str') - if refresh_summary is not None: - query_parameters['refreshSummary'] = self._serialize.query("refresh_summary", refresh_summary, 'str') - if selected_state is not None: - query_parameters['selectedState'] = self._serialize.query("selected_state", selected_state, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_profile_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + filter=filter, + orderby=orderby, + refresh_summary=refresh_summary, + selected_state=selected_state, + api_version=api_version, + template_url=self.list_by_billing_profile.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('ReservationsListResult', pipeline_response) + deserialized = self._deserialize("ReservationsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -216,17 +232,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_billing_profile.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/reservations'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/reservations"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_transactions_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_transactions_operations.py index 0d7a9a582c6d..c5926524bc65 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_transactions_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/aio/operations/_transactions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,94 +6,104 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._transactions_operations import build_list_by_invoice_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class TransactionsOperations: - """TransactionsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class TransactionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.aio.BillingManagementClient`'s + :attr:`transactions` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_by_invoice( - self, - billing_account_name: str, - invoice_name: str, - **kwargs - ) -> AsyncIterable["_models.TransactionListResult"]: + self, billing_account_name: str, invoice_name: str, **kwargs: Any + ) -> AsyncIterable["_models.Transaction"]: """Lists the transactions for an invoice. Transactions include purchases, refunds and Azure usage charges. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param invoice_name: The ID that uniquely identifies an invoice. + :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either TransactionListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.TransactionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Transaction or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.billing.models.Transaction] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.TransactionListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.TransactionListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_invoice.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'invoiceName': self._serialize.url("invoice_name", invoice_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_invoice_request( + billing_account_name=billing_account_name, + invoice_name=invoice_name, + api_version=api_version, + template_url=self.list_by_invoice.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('TransactionListResult', pipeline_response) + deserialized = self._deserialize("TransactionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -101,17 +112,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_by_invoice.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}/transactions'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_by_invoice.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}/transactions"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/models/__init__.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/models/__init__.py index 6f8996b88ee9..eb8dd8aac687 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/models/__init__.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/models/__init__.py @@ -6,307 +6,238 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -try: - from ._models_py3 import AddressDetails - from ._models_py3 import Agreement - from ._models_py3 import AgreementListResult - from ._models_py3 import Amount - from ._models_py3 import AvailableBalance - from ._models_py3 import AzurePlan - from ._models_py3 import BillingAccount - from ._models_py3 import BillingAccountListResult - from ._models_py3 import BillingAccountUpdateRequest - from ._models_py3 import BillingPeriod - from ._models_py3 import BillingPeriodsListResult - from ._models_py3 import BillingPermissionsListResult - from ._models_py3 import BillingPermissionsProperties - from ._models_py3 import BillingProfile - from ._models_py3 import BillingProfileCreationRequest - from ._models_py3 import BillingProfileListResult - from ._models_py3 import BillingProfilesOnExpand - from ._models_py3 import BillingProperty - from ._models_py3 import BillingRoleAssignment - from ._models_py3 import BillingRoleAssignmentListResult - from ._models_py3 import BillingRoleDefinition - from ._models_py3 import BillingRoleDefinitionListResult - from ._models_py3 import BillingSubscription - from ._models_py3 import BillingSubscriptionsListResult - from ._models_py3 import Customer - from ._models_py3 import CustomerListResult - from ._models_py3 import CustomerPolicy - from ._models_py3 import Department - from ._models_py3 import Document - from ._models_py3 import DownloadUrl - from ._models_py3 import Enrollment - from ._models_py3 import EnrollmentAccount - from ._models_py3 import EnrollmentAccountContext - from ._models_py3 import EnrollmentAccountListResult - from ._models_py3 import EnrollmentAccountSummary - from ._models_py3 import EnrollmentPolicies - from ._models_py3 import ErrorDetails - from ._models_py3 import ErrorResponse - from ._models_py3 import ErrorSubDetailsItem - from ._models_py3 import IndirectRelationshipInfo - from ._models_py3 import Instruction - from ._models_py3 import InstructionListResult - from ._models_py3 import Invoice - from ._models_py3 import InvoiceListResult - from ._models_py3 import InvoiceSection - from ._models_py3 import InvoiceSectionCreationRequest - from ._models_py3 import InvoiceSectionListResult - from ._models_py3 import InvoiceSectionListWithCreateSubPermissionResult - from ._models_py3 import InvoiceSectionWithCreateSubPermission - from ._models_py3 import InvoiceSectionsOnExpand - from ._models_py3 import Operation - from ._models_py3 import OperationDisplay - from ._models_py3 import OperationListResult - from ._models_py3 import Participants - from ._models_py3 import PaymentProperties - from ._models_py3 import Policy - from ._models_py3 import Product - from ._models_py3 import ProductsListResult - from ._models_py3 import RebillDetails - from ._models_py3 import Reseller - from ._models_py3 import Reservation - from ._models_py3 import ReservationPropertyUtilization - from ._models_py3 import ReservationSkuProperty - from ._models_py3 import ReservationSummary - from ._models_py3 import ReservationUtilizationAggregates - from ._models_py3 import ReservationsListResult - from ._models_py3 import Resource - from ._models_py3 import Transaction - from ._models_py3 import TransactionListResult - from ._models_py3 import TransferBillingSubscriptionRequestProperties - from ._models_py3 import TransferProductRequestProperties - from ._models_py3 import ValidateAddressResponse - from ._models_py3 import ValidateProductTransferEligibilityError - from ._models_py3 import ValidateProductTransferEligibilityResult - from ._models_py3 import ValidateSubscriptionTransferEligibilityError - from ._models_py3 import ValidateSubscriptionTransferEligibilityResult -except (SyntaxError, ImportError): - from ._models import AddressDetails # type: ignore - from ._models import Agreement # type: ignore - from ._models import AgreementListResult # type: ignore - from ._models import Amount # type: ignore - from ._models import AvailableBalance # type: ignore - from ._models import AzurePlan # type: ignore - from ._models import BillingAccount # type: ignore - from ._models import BillingAccountListResult # type: ignore - from ._models import BillingAccountUpdateRequest # type: ignore - from ._models import BillingPeriod # type: ignore - from ._models import BillingPeriodsListResult # type: ignore - from ._models import BillingPermissionsListResult # type: ignore - from ._models import BillingPermissionsProperties # type: ignore - from ._models import BillingProfile # type: ignore - from ._models import BillingProfileCreationRequest # type: ignore - from ._models import BillingProfileListResult # type: ignore - from ._models import BillingProfilesOnExpand # type: ignore - from ._models import BillingProperty # type: ignore - from ._models import BillingRoleAssignment # type: ignore - from ._models import BillingRoleAssignmentListResult # type: ignore - from ._models import BillingRoleDefinition # type: ignore - from ._models import BillingRoleDefinitionListResult # type: ignore - from ._models import BillingSubscription # type: ignore - from ._models import BillingSubscriptionsListResult # type: ignore - from ._models import Customer # type: ignore - from ._models import CustomerListResult # type: ignore - from ._models import CustomerPolicy # type: ignore - from ._models import Department # type: ignore - from ._models import Document # type: ignore - from ._models import DownloadUrl # type: ignore - from ._models import Enrollment # type: ignore - from ._models import EnrollmentAccount # type: ignore - from ._models import EnrollmentAccountContext # type: ignore - from ._models import EnrollmentAccountListResult # type: ignore - from ._models import EnrollmentAccountSummary # type: ignore - from ._models import EnrollmentPolicies # type: ignore - from ._models import ErrorDetails # type: ignore - from ._models import ErrorResponse # type: ignore - from ._models import ErrorSubDetailsItem # type: ignore - from ._models import IndirectRelationshipInfo # type: ignore - from ._models import Instruction # type: ignore - from ._models import InstructionListResult # type: ignore - from ._models import Invoice # type: ignore - from ._models import InvoiceListResult # type: ignore - from ._models import InvoiceSection # type: ignore - from ._models import InvoiceSectionCreationRequest # type: ignore - from ._models import InvoiceSectionListResult # type: ignore - from ._models import InvoiceSectionListWithCreateSubPermissionResult # type: ignore - from ._models import InvoiceSectionWithCreateSubPermission # type: ignore - from ._models import InvoiceSectionsOnExpand # type: ignore - from ._models import Operation # type: ignore - from ._models import OperationDisplay # type: ignore - from ._models import OperationListResult # type: ignore - from ._models import Participants # type: ignore - from ._models import PaymentProperties # type: ignore - from ._models import Policy # type: ignore - from ._models import Product # type: ignore - from ._models import ProductsListResult # type: ignore - from ._models import RebillDetails # type: ignore - from ._models import Reseller # type: ignore - from ._models import Reservation # type: ignore - from ._models import ReservationPropertyUtilization # type: ignore - from ._models import ReservationSkuProperty # type: ignore - from ._models import ReservationSummary # type: ignore - from ._models import ReservationUtilizationAggregates # type: ignore - from ._models import ReservationsListResult # type: ignore - from ._models import Resource # type: ignore - from ._models import Transaction # type: ignore - from ._models import TransactionListResult # type: ignore - from ._models import TransferBillingSubscriptionRequestProperties # type: ignore - from ._models import TransferProductRequestProperties # type: ignore - from ._models import ValidateAddressResponse # type: ignore - from ._models import ValidateProductTransferEligibilityError # type: ignore - from ._models import ValidateProductTransferEligibilityResult # type: ignore - from ._models import ValidateSubscriptionTransferEligibilityError # type: ignore - from ._models import ValidateSubscriptionTransferEligibilityResult # type: ignore +from ._models_py3 import AddressDetails +from ._models_py3 import Agreement +from ._models_py3 import AgreementListResult +from ._models_py3 import Amount +from ._models_py3 import AvailableBalance +from ._models_py3 import AzurePlan +from ._models_py3 import BillingAccount +from ._models_py3 import BillingAccountListResult +from ._models_py3 import BillingAccountUpdateRequest +from ._models_py3 import BillingPeriod +from ._models_py3 import BillingPeriodsListResult +from ._models_py3 import BillingPermissionsListResult +from ._models_py3 import BillingPermissionsProperties +from ._models_py3 import BillingProfile +from ._models_py3 import BillingProfileCreationRequest +from ._models_py3 import BillingProfileInfo +from ._models_py3 import BillingProfileListResult +from ._models_py3 import BillingProfilesOnExpand +from ._models_py3 import BillingProperty +from ._models_py3 import BillingRoleAssignment +from ._models_py3 import BillingRoleAssignmentListResult +from ._models_py3 import BillingRoleDefinition +from ._models_py3 import BillingRoleDefinitionListResult +from ._models_py3 import BillingSubscription +from ._models_py3 import BillingSubscriptionsListResult +from ._models_py3 import Customer +from ._models_py3 import CustomerListResult +from ._models_py3 import CustomerPolicy +from ._models_py3 import Department +from ._models_py3 import Document +from ._models_py3 import DownloadUrl +from ._models_py3 import Enrollment +from ._models_py3 import EnrollmentAccount +from ._models_py3 import EnrollmentAccountContext +from ._models_py3 import EnrollmentAccountListResult +from ._models_py3 import EnrollmentAccountSummary +from ._models_py3 import EnrollmentPolicies +from ._models_py3 import ErrorDetails +from ._models_py3 import ErrorResponse +from ._models_py3 import ErrorSubDetailsItem +from ._models_py3 import IndirectRelationshipInfo +from ._models_py3 import Instruction +from ._models_py3 import InstructionListResult +from ._models_py3 import Invoice +from ._models_py3 import InvoiceListResult +from ._models_py3 import InvoiceSection +from ._models_py3 import InvoiceSectionCreationRequest +from ._models_py3 import InvoiceSectionListResult +from ._models_py3 import InvoiceSectionListWithCreateSubPermissionResult +from ._models_py3 import InvoiceSectionWithCreateSubPermission +from ._models_py3 import InvoiceSectionsOnExpand +from ._models_py3 import Operation +from ._models_py3 import OperationDisplay +from ._models_py3 import OperationListResult +from ._models_py3 import OperationsErrorDetails +from ._models_py3 import OperationsErrorResponse +from ._models_py3 import Participants +from ._models_py3 import PaymentProperties +from ._models_py3 import Policy +from ._models_py3 import Product +from ._models_py3 import ProductsListResult +from ._models_py3 import RebillDetails +from ._models_py3 import Reseller +from ._models_py3 import Reservation +from ._models_py3 import ReservationPropertyUtilization +from ._models_py3 import ReservationSkuProperty +from ._models_py3 import ReservationSummary +from ._models_py3 import ReservationUtilizationAggregates +from ._models_py3 import ReservationsListResult +from ._models_py3 import Resource +from ._models_py3 import Transaction +from ._models_py3 import TransactionListResult +from ._models_py3 import TransferBillingSubscriptionRequestProperties +from ._models_py3 import TransferProductRequestProperties +from ._models_py3 import ValidateAddressResponse +from ._models_py3 import ValidateProductTransferEligibilityError +from ._models_py3 import ValidateProductTransferEligibilityResult +from ._models_py3 import ValidateSubscriptionTransferEligibilityError +from ._models_py3 import ValidateSubscriptionTransferEligibilityResult -from ._billing_management_client_enums import ( - AcceptanceMode, - AccountStatus, - AccountType, - AddressValidationStatus, - AgreementType, - AutoRenew, - BillingFrequency, - BillingProfileSpendingLimit, - BillingProfileStatus, - BillingProfileStatusReasonCode, - BillingRelationshipType, - BillingSubscriptionStatusType, - Category, - DocumentSource, - DocumentType, - InvoiceDocumentType, - InvoiceSectionState, - InvoiceStatus, - InvoiceType, - MarketplacePurchasesPolicy, - PaymentMethodFamily, - ProductStatusType, - ProductTransferValidationErrorCode, - ReservationPurchasesPolicy, - ReservationType, - SpendingLimit, - SpendingLimitForBillingProfile, - StatusReasonCode, - StatusReasonCodeForBillingProfile, - SubscriptionTransferValidationErrorCode, - TargetCloud, - TransactionTypeKind, - ViewCharges, - ViewChargesPolicy, -) +from ._billing_management_client_enums import AcceptanceMode +from ._billing_management_client_enums import AccountStatus +from ._billing_management_client_enums import AccountType +from ._billing_management_client_enums import AddressValidationStatus +from ._billing_management_client_enums import AgreementType +from ._billing_management_client_enums import AutoRenew +from ._billing_management_client_enums import BillingFrequency +from ._billing_management_client_enums import BillingProfileSpendingLimit +from ._billing_management_client_enums import BillingProfileStatus +from ._billing_management_client_enums import BillingProfileStatusReasonCode +from ._billing_management_client_enums import BillingRelationshipType +from ._billing_management_client_enums import BillingSubscriptionStatusType +from ._billing_management_client_enums import Category +from ._billing_management_client_enums import DocumentSource +from ._billing_management_client_enums import DocumentType +from ._billing_management_client_enums import InvoiceDocumentType +from ._billing_management_client_enums import InvoiceSectionState +from ._billing_management_client_enums import InvoiceStatus +from ._billing_management_client_enums import InvoiceType +from ._billing_management_client_enums import MarketplacePurchasesPolicy +from ._billing_management_client_enums import PaymentMethodFamily +from ._billing_management_client_enums import ProductStatusType +from ._billing_management_client_enums import ProductTransferValidationErrorCode +from ._billing_management_client_enums import ReservationPurchasesPolicy +from ._billing_management_client_enums import ReservationType +from ._billing_management_client_enums import SpendingLimit +from ._billing_management_client_enums import SpendingLimitForBillingProfile +from ._billing_management_client_enums import StatusReasonCode +from ._billing_management_client_enums import StatusReasonCodeForBillingProfile +from ._billing_management_client_enums import SubscriptionTransferValidationErrorCode +from ._billing_management_client_enums import TargetCloud +from ._billing_management_client_enums import TransactionTypeKind +from ._billing_management_client_enums import ViewCharges +from ._billing_management_client_enums import ViewChargesPolicy +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'AddressDetails', - 'Agreement', - 'AgreementListResult', - 'Amount', - 'AvailableBalance', - 'AzurePlan', - 'BillingAccount', - 'BillingAccountListResult', - 'BillingAccountUpdateRequest', - 'BillingPeriod', - 'BillingPeriodsListResult', - 'BillingPermissionsListResult', - 'BillingPermissionsProperties', - 'BillingProfile', - 'BillingProfileCreationRequest', - 'BillingProfileListResult', - 'BillingProfilesOnExpand', - 'BillingProperty', - 'BillingRoleAssignment', - 'BillingRoleAssignmentListResult', - 'BillingRoleDefinition', - 'BillingRoleDefinitionListResult', - 'BillingSubscription', - 'BillingSubscriptionsListResult', - 'Customer', - 'CustomerListResult', - 'CustomerPolicy', - 'Department', - 'Document', - 'DownloadUrl', - 'Enrollment', - 'EnrollmentAccount', - 'EnrollmentAccountContext', - 'EnrollmentAccountListResult', - 'EnrollmentAccountSummary', - 'EnrollmentPolicies', - 'ErrorDetails', - 'ErrorResponse', - 'ErrorSubDetailsItem', - 'IndirectRelationshipInfo', - 'Instruction', - 'InstructionListResult', - 'Invoice', - 'InvoiceListResult', - 'InvoiceSection', - 'InvoiceSectionCreationRequest', - 'InvoiceSectionListResult', - 'InvoiceSectionListWithCreateSubPermissionResult', - 'InvoiceSectionWithCreateSubPermission', - 'InvoiceSectionsOnExpand', - 'Operation', - 'OperationDisplay', - 'OperationListResult', - 'Participants', - 'PaymentProperties', - 'Policy', - 'Product', - 'ProductsListResult', - 'RebillDetails', - 'Reseller', - 'Reservation', - 'ReservationPropertyUtilization', - 'ReservationSkuProperty', - 'ReservationSummary', - 'ReservationUtilizationAggregates', - 'ReservationsListResult', - 'Resource', - 'Transaction', - 'TransactionListResult', - 'TransferBillingSubscriptionRequestProperties', - 'TransferProductRequestProperties', - 'ValidateAddressResponse', - 'ValidateProductTransferEligibilityError', - 'ValidateProductTransferEligibilityResult', - 'ValidateSubscriptionTransferEligibilityError', - 'ValidateSubscriptionTransferEligibilityResult', - 'AcceptanceMode', - 'AccountStatus', - 'AccountType', - 'AddressValidationStatus', - 'AgreementType', - 'AutoRenew', - 'BillingFrequency', - 'BillingProfileSpendingLimit', - 'BillingProfileStatus', - 'BillingProfileStatusReasonCode', - 'BillingRelationshipType', - 'BillingSubscriptionStatusType', - 'Category', - 'DocumentSource', - 'DocumentType', - 'InvoiceDocumentType', - 'InvoiceSectionState', - 'InvoiceStatus', - 'InvoiceType', - 'MarketplacePurchasesPolicy', - 'PaymentMethodFamily', - 'ProductStatusType', - 'ProductTransferValidationErrorCode', - 'ReservationPurchasesPolicy', - 'ReservationType', - 'SpendingLimit', - 'SpendingLimitForBillingProfile', - 'StatusReasonCode', - 'StatusReasonCodeForBillingProfile', - 'SubscriptionTransferValidationErrorCode', - 'TargetCloud', - 'TransactionTypeKind', - 'ViewCharges', - 'ViewChargesPolicy', + "AddressDetails", + "Agreement", + "AgreementListResult", + "Amount", + "AvailableBalance", + "AzurePlan", + "BillingAccount", + "BillingAccountListResult", + "BillingAccountUpdateRequest", + "BillingPeriod", + "BillingPeriodsListResult", + "BillingPermissionsListResult", + "BillingPermissionsProperties", + "BillingProfile", + "BillingProfileCreationRequest", + "BillingProfileInfo", + "BillingProfileListResult", + "BillingProfilesOnExpand", + "BillingProperty", + "BillingRoleAssignment", + "BillingRoleAssignmentListResult", + "BillingRoleDefinition", + "BillingRoleDefinitionListResult", + "BillingSubscription", + "BillingSubscriptionsListResult", + "Customer", + "CustomerListResult", + "CustomerPolicy", + "Department", + "Document", + "DownloadUrl", + "Enrollment", + "EnrollmentAccount", + "EnrollmentAccountContext", + "EnrollmentAccountListResult", + "EnrollmentAccountSummary", + "EnrollmentPolicies", + "ErrorDetails", + "ErrorResponse", + "ErrorSubDetailsItem", + "IndirectRelationshipInfo", + "Instruction", + "InstructionListResult", + "Invoice", + "InvoiceListResult", + "InvoiceSection", + "InvoiceSectionCreationRequest", + "InvoiceSectionListResult", + "InvoiceSectionListWithCreateSubPermissionResult", + "InvoiceSectionWithCreateSubPermission", + "InvoiceSectionsOnExpand", + "Operation", + "OperationDisplay", + "OperationListResult", + "OperationsErrorDetails", + "OperationsErrorResponse", + "Participants", + "PaymentProperties", + "Policy", + "Product", + "ProductsListResult", + "RebillDetails", + "Reseller", + "Reservation", + "ReservationPropertyUtilization", + "ReservationSkuProperty", + "ReservationSummary", + "ReservationUtilizationAggregates", + "ReservationsListResult", + "Resource", + "Transaction", + "TransactionListResult", + "TransferBillingSubscriptionRequestProperties", + "TransferProductRequestProperties", + "ValidateAddressResponse", + "ValidateProductTransferEligibilityError", + "ValidateProductTransferEligibilityResult", + "ValidateSubscriptionTransferEligibilityError", + "ValidateSubscriptionTransferEligibilityResult", + "AcceptanceMode", + "AccountStatus", + "AccountType", + "AddressValidationStatus", + "AgreementType", + "AutoRenew", + "BillingFrequency", + "BillingProfileSpendingLimit", + "BillingProfileStatus", + "BillingProfileStatusReasonCode", + "BillingRelationshipType", + "BillingSubscriptionStatusType", + "Category", + "DocumentSource", + "DocumentType", + "InvoiceDocumentType", + "InvoiceSectionState", + "InvoiceStatus", + "InvoiceType", + "MarketplacePurchasesPolicy", + "PaymentMethodFamily", + "ProductStatusType", + "ProductTransferValidationErrorCode", + "ReservationPurchasesPolicy", + "ReservationType", + "SpendingLimit", + "SpendingLimitForBillingProfile", + "StatusReasonCode", + "StatusReasonCodeForBillingProfile", + "SubscriptionTransferValidationErrorCode", + "TargetCloud", + "TransactionTypeKind", + "ViewCharges", + "ViewChargesPolicy", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/models/_billing_management_client_enums.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/models/_billing_management_client_enums.py index 336add87266a..7d53211c2d69 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/models/_billing_management_client_enums.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/models/_billing_management_client_enums.py @@ -6,37 +6,20 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from enum import Enum, EnumMeta -from six import with_metaclass - -class _CaseInsensitiveEnumMeta(EnumMeta): - def __getitem__(self, name): - return super().__getitem__(name.upper()) - - def __getattr__(cls, name): - """Return the enum member matching `name` - We use __getattr__ instead of descriptors or inserting into the enum - class' __dict__ in order to support `name` and `value` being both - properties for enum members (which live in the class' __dict__) and - enum members themselves. - """ - try: - return cls._member_map_[name.upper()] - except KeyError: - raise AttributeError(name) - - -class AcceptanceMode(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The mode of acceptance for an agreement. - """ +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class AcceptanceMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The mode of acceptance for an agreement.""" CLICK_TO_ACCEPT = "ClickToAccept" E_SIGN_EMBEDDED = "ESignEmbedded" E_SIGN_OFFLINE = "ESignOffline" -class AccountStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The current status of the billing account. - """ + +class AccountStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The current status of the billing account.""" ACTIVE = "Active" DELETED = "Deleted" @@ -46,80 +29,80 @@ class AccountStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): EXTENDED = "Extended" TERMINATED = "Terminated" -class AccountType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of customer. - """ + +class AccountType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of customer.""" ENTERPRISE = "Enterprise" INDIVIDUAL = "Individual" PARTNER = "Partner" -class AddressValidationStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Status of the address validation. - """ + +class AddressValidationStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Status of the address validation.""" VALID = "Valid" INVALID = "Invalid" -class AgreementType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of agreement. - """ + +class AgreementType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of agreement.""" MICROSOFT_CUSTOMER_AGREEMENT = "MicrosoftCustomerAgreement" ENTERPRISE_AGREEMENT = "EnterpriseAgreement" MICROSOFT_ONLINE_SERVICES_PROGRAM = "MicrosoftOnlineServicesProgram" MICROSOFT_PARTNER_AGREEMENT = "MicrosoftPartnerAgreement" -class AutoRenew(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Indicates whether auto renewal is turned on or off for a product. - """ + +class AutoRenew(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Indicates whether auto renewal is turned on or off for a product.""" OFF = "Off" ON = "On" -class BillingFrequency(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The frequency at which the product will be billed. - """ + +class BillingFrequency(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The frequency at which the product will be billed.""" ONE_TIME = "OneTime" MONTHLY = "Monthly" USAGE_BASED = "UsageBased" -class BillingProfileSpendingLimit(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The billing profile spending limit. - """ + +class BillingProfileSpendingLimit(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The billing profile spending limit.""" OFF = "Off" ON = "On" -class BillingProfileStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The status of the billing profile. - """ + +class BillingProfileStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The status of the billing profile.""" ACTIVE = "Active" DISABLED = "Disabled" WARNED = "Warned" -class BillingProfileStatusReasonCode(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Reason for the specified billing profile status. - """ + +class BillingProfileStatusReasonCode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Reason for the specified billing profile status.""" PAST_DUE = "PastDue" SPENDING_LIMIT_REACHED = "SpendingLimitReached" SPENDING_LIMIT_EXPIRED = "SpendingLimitExpired" -class BillingRelationshipType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Identifies which services and purchases are paid by a billing profile. - """ + +class BillingRelationshipType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Identifies which services and purchases are paid by a billing profile.""" DIRECT = "Direct" INDIRECT_CUSTOMER = "IndirectCustomer" INDIRECT_PARTNER = "IndirectPartner" CSP_PARTNER = "CSPPartner" -class BillingSubscriptionStatusType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The current billing status of the subscription. - """ + +class BillingSubscriptionStatusType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The current billing status of the subscription.""" ACTIVE = "Active" INACTIVE = "Inactive" @@ -127,81 +110,81 @@ class BillingSubscriptionStatusType(with_metaclass(_CaseInsensitiveEnumMeta, str DELETED = "Deleted" WARNING = "Warning" -class Category(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The category of the agreement signed by a customer. - """ + +class Category(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The category of the agreement signed by a customer.""" MICROSOFT_CUSTOMER_AGREEMENT = "MicrosoftCustomerAgreement" AFFILIATE_PURCHASE_TERMS = "AffiliatePurchaseTerms" OTHER = "Other" -class DocumentSource(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The source of the document. ENF for Brazil and DRS for rest of the world. - """ + +class DocumentSource(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The source of the document. ENF for Brazil and DRS for rest of the world.""" DRS = "DRS" ENF = "ENF" -class DocumentType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of the document. - """ + +class DocumentType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of the document.""" INVOICE = "Invoice" VOID_NOTE = "VoidNote" TAX_RECEIPT = "TaxReceipt" CREDIT_NOTE = "CreditNote" -class InvoiceDocumentType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of the document. - """ + +class InvoiceDocumentType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of the document.""" INVOICE = "Invoice" CREDIT_NOTE = "CreditNote" -class InvoiceSectionState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Identifies the state of an invoice section. - """ + +class InvoiceSectionState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Identifies the state of an invoice section.""" ACTIVE = "Active" RESTRICTED = "Restricted" -class InvoiceStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The current status of the invoice. - """ + +class InvoiceStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The current status of the invoice.""" DUE = "Due" OVER_DUE = "OverDue" PAID = "Paid" VOID = "Void" -class InvoiceType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Invoice type. - """ + +class InvoiceType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Invoice type.""" AZURE_SERVICE = "AzureService" AZURE_MARKETPLACE = "AzureMarketplace" AZURE_SUPPORT = "AzureSupport" -class MarketplacePurchasesPolicy(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The policy that controls whether Azure marketplace purchases are allowed for a billing profile. - """ + +class MarketplacePurchasesPolicy(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The policy that controls whether Azure marketplace purchases are allowed for a billing profile.""" ALL_ALLOWED = "AllAllowed" ONLY_FREE_ALLOWED = "OnlyFreeAllowed" NOT_ALLOWED = "NotAllowed" -class PaymentMethodFamily(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The family of payment method. - """ + +class PaymentMethodFamily(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The family of payment method.""" CREDITS = "Credits" CHECK_WIRE = "CheckWire" CREDIT_CARD = "CreditCard" NONE = "None" -class ProductStatusType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The current status of the product. - """ + +class ProductStatusType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The current status of the product.""" ACTIVE = "Active" INACTIVE = "Inactive" @@ -212,9 +195,9 @@ class ProductStatusType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): CANCELLED = "Cancelled" AUTO_RENEW = "AutoRenew" -class ProductTransferValidationErrorCode(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Error code of the transfer validation response. - """ + +class ProductTransferValidationErrorCode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Error code of the transfer validation response.""" INVALID_SOURCE = "InvalidSource" PRODUCT_NOT_ACTIVE = "ProductNotActive" @@ -226,53 +209,53 @@ class ProductTransferValidationErrorCode(with_metaclass(_CaseInsensitiveEnumMeta NOT_AVAILABLE_FOR_DESTINATION_MARKET = "NotAvailableForDestinationMarket" ONE_TIME_PURCHASE_PRODUCT_TRANSFER_NOT_ALLOWED = "OneTimePurchaseProductTransferNotAllowed" -class ReservationPurchasesPolicy(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The policy that controls whether Azure reservation purchases are allowed for a billing profile. - """ + +class ReservationPurchasesPolicy(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The policy that controls whether Azure reservation purchases are allowed for a billing profile.""" ALLOWED = "Allowed" NOT_ALLOWED = "NotAllowed" -class ReservationType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of transaction. - """ + +class ReservationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of transaction.""" PURCHASE = "Purchase" USAGE_CHARGE = "Usage Charge" -class SpendingLimit(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The billing profile spending limit. - """ + +class SpendingLimit(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The billing profile spending limit.""" OFF = "Off" ON = "On" -class SpendingLimitForBillingProfile(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The billing profile spending limit. - """ + +class SpendingLimitForBillingProfile(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The billing profile spending limit.""" OFF = "Off" ON = "On" -class StatusReasonCode(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Reason for the specified billing profile status. - """ + +class StatusReasonCode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Reason for the specified billing profile status.""" PAST_DUE = "PastDue" SPENDING_LIMIT_REACHED = "SpendingLimitReached" SPENDING_LIMIT_EXPIRED = "SpendingLimitExpired" -class StatusReasonCodeForBillingProfile(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Reason for the specified billing profile status. - """ + +class StatusReasonCodeForBillingProfile(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Reason for the specified billing profile status.""" PAST_DUE = "PastDue" SPENDING_LIMIT_REACHED = "SpendingLimitReached" SPENDING_LIMIT_EXPIRED = "SpendingLimitExpired" -class SubscriptionTransferValidationErrorCode(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Error code of the transfer validation response. - """ + +class SubscriptionTransferValidationErrorCode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Error code of the transfer validation response.""" BILLING_ACCOUNT_INACTIVE = "BillingAccountInactive" CROSS_BILLING_ACCOUNT_NOT_ALLOWED = "CrossBillingAccountNotAllowed" @@ -295,22 +278,23 @@ class SubscriptionTransferValidationErrorCode(with_metaclass(_CaseInsensitiveEnu SUBSCRIPTION_NOT_ACTIVE = "SubscriptionNotActive" SUBSCRIPTION_TYPE_NOT_SUPPORTED = "SubscriptionTypeNotSupported" -class TargetCloud(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Possible cloud environments. - """ + +class TargetCloud(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Possible cloud environments.""" US_GOV = "USGov" US_NAT = "USNat" US_SEC = "USSec" -class TransactionTypeKind(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The kind of transaction. Options are all or reservation. - """ + +class TransactionTypeKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The kind of transaction. Options are all or reservation.""" ALL = "all" RESERVATION = "reservation" -class ViewCharges(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + +class ViewCharges(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The policy that controls whether the users in customer's organization can view charges at pay-as-you-go prices. """ @@ -318,7 +302,8 @@ class ViewCharges(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): ALLOWED = "Allowed" NOT_ALLOWED = "NotAllowed" -class ViewChargesPolicy(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + +class ViewChargesPolicy(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The policy that controls whether users with Azure RBAC access to a subscription can view its charges. """ diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/models/_models.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/models/_models.py deleted file mode 100644 index 993bca9cbfaa..000000000000 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/models/_models.py +++ /dev/null @@ -1,3722 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.core.exceptions import HttpResponseError -import msrest.serialization - - -class AddressDetails(msrest.serialization.Model): - """Address details. - - All required parameters must be populated in order to send to Azure. - - :param first_name: First name. - :type first_name: str - :param middle_name: Middle name. - :type middle_name: str - :param last_name: Last name. - :type last_name: str - :param company_name: Company name. - :type company_name: str - :param address_line1: Required. Address line 1. - :type address_line1: str - :param address_line2: Address line 2. - :type address_line2: str - :param address_line3: Address line 3. - :type address_line3: str - :param city: Address city. - :type city: str - :param district: Address district. - :type district: str - :param region: Address region. - :type region: str - :param country: Required. Country code uses ISO2, 2-digit format. - :type country: str - :param postal_code: Postal code. - :type postal_code: str - :param email: Email address. - :type email: str - :param phone_number: Phone number. - :type phone_number: str - """ - - _validation = { - 'address_line1': {'required': True}, - 'country': {'required': True}, - } - - _attribute_map = { - 'first_name': {'key': 'firstName', 'type': 'str'}, - 'middle_name': {'key': 'middleName', 'type': 'str'}, - 'last_name': {'key': 'lastName', 'type': 'str'}, - 'company_name': {'key': 'companyName', 'type': 'str'}, - 'address_line1': {'key': 'addressLine1', 'type': 'str'}, - 'address_line2': {'key': 'addressLine2', 'type': 'str'}, - 'address_line3': {'key': 'addressLine3', 'type': 'str'}, - 'city': {'key': 'city', 'type': 'str'}, - 'district': {'key': 'district', 'type': 'str'}, - 'region': {'key': 'region', 'type': 'str'}, - 'country': {'key': 'country', 'type': 'str'}, - 'postal_code': {'key': 'postalCode', 'type': 'str'}, - 'email': {'key': 'email', 'type': 'str'}, - 'phone_number': {'key': 'phoneNumber', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(AddressDetails, self).__init__(**kwargs) - self.first_name = kwargs.get('first_name', None) - self.middle_name = kwargs.get('middle_name', None) - self.last_name = kwargs.get('last_name', None) - self.company_name = kwargs.get('company_name', None) - self.address_line1 = kwargs['address_line1'] - self.address_line2 = kwargs.get('address_line2', None) - self.address_line3 = kwargs.get('address_line3', None) - self.city = kwargs.get('city', None) - self.district = kwargs.get('district', None) - self.region = kwargs.get('region', None) - self.country = kwargs['country'] - self.postal_code = kwargs.get('postal_code', None) - self.email = kwargs.get('email', None) - self.phone_number = kwargs.get('phone_number', None) - - -class Resource(msrest.serialization.Model): - """The Resource model definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(Resource, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - - -class Agreement(Resource): - """An agreement. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar agreement_link: The URL to download the agreement. - :vartype agreement_link: str - :ivar category: The category of the agreement signed by a customer. Possible values include: - "MicrosoftCustomerAgreement", "AffiliatePurchaseTerms", "Other". - :vartype category: str or ~azure.mgmt.billing.models.Category - :ivar acceptance_mode: The mode of acceptance for an agreement. Possible values include: - "ClickToAccept", "ESignEmbedded", "ESignOffline". - :vartype acceptance_mode: str or ~azure.mgmt.billing.models.AcceptanceMode - :ivar effective_date: The date from which the agreement is effective. - :vartype effective_date: ~datetime.datetime - :ivar expiration_date: The date when the agreement expires. - :vartype expiration_date: ~datetime.datetime - :param participants: The list of participants that participates in acceptance of an agreement. - :type participants: list[~azure.mgmt.billing.models.Participants] - :ivar status: The current status of the agreement. - :vartype status: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'agreement_link': {'readonly': True}, - 'category': {'readonly': True}, - 'acceptance_mode': {'readonly': True}, - 'effective_date': {'readonly': True}, - 'expiration_date': {'readonly': True}, - 'status': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'agreement_link': {'key': 'properties.agreementLink', 'type': 'str'}, - 'category': {'key': 'properties.category', 'type': 'str'}, - 'acceptance_mode': {'key': 'properties.acceptanceMode', 'type': 'str'}, - 'effective_date': {'key': 'properties.effectiveDate', 'type': 'iso-8601'}, - 'expiration_date': {'key': 'properties.expirationDate', 'type': 'iso-8601'}, - 'participants': {'key': 'properties.participants', 'type': '[Participants]'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(Agreement, self).__init__(**kwargs) - self.agreement_link = None - self.category = None - self.acceptance_mode = None - self.effective_date = None - self.expiration_date = None - self.participants = kwargs.get('participants', None) - self.status = None - - -class AgreementListResult(msrest.serialization.Model): - """Result of listing agreements. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of agreements. - :vartype value: list[~azure.mgmt.billing.models.Agreement] - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - """ - - _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[Agreement]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(AgreementListResult, self).__init__(**kwargs) - self.value = None - self.next_link = None - - -class Amount(msrest.serialization.Model): - """The amount. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar currency: The currency for the amount value. - :vartype currency: str - :param value: Amount value. - :type value: float - """ - - _validation = { - 'currency': {'readonly': True}, - } - - _attribute_map = { - 'currency': {'key': 'currency', 'type': 'str'}, - 'value': {'key': 'value', 'type': 'float'}, - } - - def __init__( - self, - **kwargs - ): - super(Amount, self).__init__(**kwargs) - self.currency = None - self.value = kwargs.get('value', None) - - -class AvailableBalance(Resource): - """The latest Azure credit balance. This is the balance available for pay now. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar amount: Balance amount. - :vartype amount: ~azure.mgmt.billing.models.Amount - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'amount': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'amount': {'key': 'properties.amount', 'type': 'Amount'}, - } - - def __init__( - self, - **kwargs - ): - super(AvailableBalance, self).__init__(**kwargs) - self.amount = None - - -class AzurePlan(msrest.serialization.Model): - """Details of the Azure plan. - - Variables are only populated by the server, and will be ignored when sending a request. - - :param sku_id: The sku id. - :type sku_id: str - :ivar sku_description: The sku description. - :vartype sku_description: str - """ - - _validation = { - 'sku_description': {'readonly': True}, - } - - _attribute_map = { - 'sku_id': {'key': 'skuId', 'type': 'str'}, - 'sku_description': {'key': 'skuDescription', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(AzurePlan, self).__init__(**kwargs) - self.sku_id = kwargs.get('sku_id', None) - self.sku_description = None - - -class BillingAccount(Resource): - """A billing account. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :param display_name: The billing account name. - :type display_name: str - :param sold_to: The address of the individual or organization that is responsible for the - billing account. - :type sold_to: ~azure.mgmt.billing.models.AddressDetails - :ivar agreement_type: The type of agreement. Possible values include: - "MicrosoftCustomerAgreement", "EnterpriseAgreement", "MicrosoftOnlineServicesProgram", - "MicrosoftPartnerAgreement". - :vartype agreement_type: str or ~azure.mgmt.billing.models.AgreementType - :ivar account_type: The type of customer. Possible values include: "Enterprise", "Individual", - "Partner". - :vartype account_type: str or ~azure.mgmt.billing.models.AccountType - :ivar account_status: The current status of the billing account. Possible values include: - "Active", "Deleted", "Disabled", "Expired", "Transferred", "Extended", "Terminated". - :vartype account_status: str or ~azure.mgmt.billing.models.AccountStatus - :param billing_profiles: The billing profiles associated with the billing account. By default - this is not populated, unless it's specified in $expand. - :type billing_profiles: ~azure.mgmt.billing.models.BillingProfilesOnExpand - :ivar enrollment_details: The details about the associated legacy enrollment. By default this - is not populated, unless it's specified in $expand. - :vartype enrollment_details: ~azure.mgmt.billing.models.Enrollment - :param departments: The departments associated to the enrollment. - :type departments: list[~azure.mgmt.billing.models.Department] - :param enrollment_accounts: The accounts associated to the enrollment. - :type enrollment_accounts: list[~azure.mgmt.billing.models.EnrollmentAccount] - :ivar has_read_access: Indicates whether user has read access to the billing account. - :vartype has_read_access: bool - :param notification_email_address: Notification email address, only for legacy accounts. - :type notification_email_address: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'agreement_type': {'readonly': True}, - 'account_type': {'readonly': True}, - 'account_status': {'readonly': True}, - 'enrollment_details': {'readonly': True}, - 'has_read_access': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'display_name': {'key': 'properties.displayName', 'type': 'str'}, - 'sold_to': {'key': 'properties.soldTo', 'type': 'AddressDetails'}, - 'agreement_type': {'key': 'properties.agreementType', 'type': 'str'}, - 'account_type': {'key': 'properties.accountType', 'type': 'str'}, - 'account_status': {'key': 'properties.accountStatus', 'type': 'str'}, - 'billing_profiles': {'key': 'properties.billingProfiles', 'type': 'BillingProfilesOnExpand'}, - 'enrollment_details': {'key': 'properties.enrollmentDetails', 'type': 'Enrollment'}, - 'departments': {'key': 'properties.departments', 'type': '[Department]'}, - 'enrollment_accounts': {'key': 'properties.enrollmentAccounts', 'type': '[EnrollmentAccount]'}, - 'has_read_access': {'key': 'properties.hasReadAccess', 'type': 'bool'}, - 'notification_email_address': {'key': 'properties.notificationEmailAddress', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(BillingAccount, self).__init__(**kwargs) - self.display_name = kwargs.get('display_name', None) - self.sold_to = kwargs.get('sold_to', None) - self.agreement_type = None - self.account_type = None - self.account_status = None - self.billing_profiles = kwargs.get('billing_profiles', None) - self.enrollment_details = None - self.departments = kwargs.get('departments', None) - self.enrollment_accounts = kwargs.get('enrollment_accounts', None) - self.has_read_access = None - self.notification_email_address = kwargs.get('notification_email_address', None) - - -class BillingAccountListResult(msrest.serialization.Model): - """The list of billing accounts. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of billing accounts. - :vartype value: list[~azure.mgmt.billing.models.BillingAccount] - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - """ - - _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[BillingAccount]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(BillingAccountListResult, self).__init__(**kwargs) - self.value = None - self.next_link = None - - -class BillingAccountUpdateRequest(msrest.serialization.Model): - """The request properties of the billing account that can be updated. - - Variables are only populated by the server, and will be ignored when sending a request. - - :param display_name: The billing account name. - :type display_name: str - :param sold_to: The address of the individual or organization that is responsible for the - billing account. - :type sold_to: ~azure.mgmt.billing.models.AddressDetails - :ivar agreement_type: The type of agreement. Possible values include: - "MicrosoftCustomerAgreement", "EnterpriseAgreement", "MicrosoftOnlineServicesProgram", - "MicrosoftPartnerAgreement". - :vartype agreement_type: str or ~azure.mgmt.billing.models.AgreementType - :ivar account_type: The type of customer. Possible values include: "Enterprise", "Individual", - "Partner". - :vartype account_type: str or ~azure.mgmt.billing.models.AccountType - :ivar account_status: The current status of the billing account. Possible values include: - "Active", "Deleted", "Disabled", "Expired", "Transferred", "Extended", "Terminated". - :vartype account_status: str or ~azure.mgmt.billing.models.AccountStatus - :param billing_profiles: The billing profiles associated with the billing account. By default - this is not populated, unless it's specified in $expand. - :type billing_profiles: ~azure.mgmt.billing.models.BillingProfilesOnExpand - :ivar enrollment_details: The details about the associated legacy enrollment. By default this - is not populated, unless it's specified in $expand. - :vartype enrollment_details: ~azure.mgmt.billing.models.Enrollment - :param departments: The departments associated to the enrollment. - :type departments: list[~azure.mgmt.billing.models.Department] - :param enrollment_accounts: The accounts associated to the enrollment. - :type enrollment_accounts: list[~azure.mgmt.billing.models.EnrollmentAccount] - :ivar has_read_access: Indicates whether user has read access to the billing account. - :vartype has_read_access: bool - :param notification_email_address: Notification email address, only for legacy accounts. - :type notification_email_address: str - """ - - _validation = { - 'agreement_type': {'readonly': True}, - 'account_type': {'readonly': True}, - 'account_status': {'readonly': True}, - 'enrollment_details': {'readonly': True}, - 'has_read_access': {'readonly': True}, - } - - _attribute_map = { - 'display_name': {'key': 'properties.displayName', 'type': 'str'}, - 'sold_to': {'key': 'properties.soldTo', 'type': 'AddressDetails'}, - 'agreement_type': {'key': 'properties.agreementType', 'type': 'str'}, - 'account_type': {'key': 'properties.accountType', 'type': 'str'}, - 'account_status': {'key': 'properties.accountStatus', 'type': 'str'}, - 'billing_profiles': {'key': 'properties.billingProfiles', 'type': 'BillingProfilesOnExpand'}, - 'enrollment_details': {'key': 'properties.enrollmentDetails', 'type': 'Enrollment'}, - 'departments': {'key': 'properties.departments', 'type': '[Department]'}, - 'enrollment_accounts': {'key': 'properties.enrollmentAccounts', 'type': '[EnrollmentAccount]'}, - 'has_read_access': {'key': 'properties.hasReadAccess', 'type': 'bool'}, - 'notification_email_address': {'key': 'properties.notificationEmailAddress', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(BillingAccountUpdateRequest, self).__init__(**kwargs) - self.display_name = kwargs.get('display_name', None) - self.sold_to = kwargs.get('sold_to', None) - self.agreement_type = None - self.account_type = None - self.account_status = None - self.billing_profiles = kwargs.get('billing_profiles', None) - self.enrollment_details = None - self.departments = kwargs.get('departments', None) - self.enrollment_accounts = kwargs.get('enrollment_accounts', None) - self.has_read_access = None - self.notification_email_address = kwargs.get('notification_email_address', None) - - -class BillingPeriod(Resource): - """A billing period resource. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar billing_period_start_date: The start of the date range covered by the billing period. - :vartype billing_period_start_date: ~datetime.date - :ivar billing_period_end_date: The end of the date range covered by the billing period. - :vartype billing_period_end_date: ~datetime.date - :ivar invoice_ids: Array of invoice ids that associated with. - :vartype invoice_ids: list[str] - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'billing_period_start_date': {'readonly': True}, - 'billing_period_end_date': {'readonly': True}, - 'invoice_ids': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'billing_period_start_date': {'key': 'properties.billingPeriodStartDate', 'type': 'date'}, - 'billing_period_end_date': {'key': 'properties.billingPeriodEndDate', 'type': 'date'}, - 'invoice_ids': {'key': 'properties.invoiceIds', 'type': '[str]'}, - } - - def __init__( - self, - **kwargs - ): - super(BillingPeriod, self).__init__(**kwargs) - self.billing_period_start_date = None - self.billing_period_end_date = None - self.invoice_ids = None - - -class BillingPeriodsListResult(msrest.serialization.Model): - """Result of listing billing periods. It contains a list of available billing periods in reverse chronological order. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of billing periods. - :vartype value: list[~azure.mgmt.billing.models.BillingPeriod] - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - """ - - _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[BillingPeriod]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(BillingPeriodsListResult, self).__init__(**kwargs) - self.value = None - self.next_link = None - - -class BillingPermissionsListResult(msrest.serialization.Model): - """Result of list billingPermissions a caller has on a billing account. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of billingPermissions a caller has on a billing account. - :vartype value: list[~azure.mgmt.billing.models.BillingPermissionsProperties] - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - """ - - _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[BillingPermissionsProperties]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(BillingPermissionsListResult, self).__init__(**kwargs) - self.value = None - self.next_link = None - - -class BillingPermissionsProperties(msrest.serialization.Model): - """The set of allowed action and not allowed actions a caller has on a billing account. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar actions: The set of actions that the caller is allowed to perform. - :vartype actions: list[str] - :ivar not_actions: The set of actions that the caller is not allowed to perform. - :vartype not_actions: list[str] - """ - - _validation = { - 'actions': {'readonly': True}, - 'not_actions': {'readonly': True}, - } - - _attribute_map = { - 'actions': {'key': 'actions', 'type': '[str]'}, - 'not_actions': {'key': 'notActions', 'type': '[str]'}, - } - - def __init__( - self, - **kwargs - ): - super(BillingPermissionsProperties, self).__init__(**kwargs) - self.actions = None - self.not_actions = None - - -class BillingProfile(Resource): - """A billing profile. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :param display_name: The name of the billing profile. - :type display_name: str - :param po_number: The purchase order name that will appear on the invoices generated for the - billing profile. - :type po_number: str - :ivar billing_relationship_type: Identifies which services and purchases are paid by a billing - profile. Possible values include: "Direct", "IndirectCustomer", "IndirectPartner", - "CSPPartner". - :vartype billing_relationship_type: str or ~azure.mgmt.billing.models.BillingRelationshipType - :param bill_to: Billing address. - :type bill_to: ~azure.mgmt.billing.models.AddressDetails - :ivar indirect_relationship_info: Identifies the billing profile that is linked to another - billing profile in indirect purchase motion. - :vartype indirect_relationship_info: ~azure.mgmt.billing.models.IndirectRelationshipInfo - :param invoice_email_opt_in: Flag controlling whether the invoices for the billing profile are - sent through email. - :type invoice_email_opt_in: bool - :ivar invoice_day: The day of the month when the invoice for the billing profile is generated. - :vartype invoice_day: int - :ivar currency: The currency in which the charges for the billing profile are billed. - :vartype currency: str - :param enabled_azure_plans: Information about the enabled azure plans. - :type enabled_azure_plans: list[~azure.mgmt.billing.models.AzurePlan] - :param invoice_sections: The invoice sections associated to the billing profile. By default - this is not populated, unless it's specified in $expand. - :type invoice_sections: ~azure.mgmt.billing.models.InvoiceSectionsOnExpand - :ivar has_read_access: Indicates whether user has read access to the billing profile. - :vartype has_read_access: bool - :ivar system_id: The system generated unique identifier for a billing profile. - :vartype system_id: str - :ivar status: The status of the billing profile. Possible values include: "Active", "Disabled", - "Warned". - :vartype status: str or ~azure.mgmt.billing.models.BillingProfileStatus - :ivar status_reason_code: Reason for the specified billing profile status. Possible values - include: "PastDue", "SpendingLimitReached", "SpendingLimitExpired". - :vartype status_reason_code: str or ~azure.mgmt.billing.models.StatusReasonCode - :ivar spending_limit: The billing profile spending limit. Possible values include: "Off", "On". - :vartype spending_limit: str or ~azure.mgmt.billing.models.SpendingLimit - :ivar target_clouds: Identifies the cloud environments that are associated with a billing - profile. This is a system managed optional field and gets updated as the billing profile gets - associated with accounts in various clouds. - :vartype target_clouds: list[str or ~azure.mgmt.billing.models.TargetCloud] - :param tags: A set of tags. Tags of billing profiles. - :type tags: dict[str, str] - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'billing_relationship_type': {'readonly': True}, - 'indirect_relationship_info': {'readonly': True}, - 'invoice_day': {'readonly': True}, - 'currency': {'readonly': True}, - 'has_read_access': {'readonly': True}, - 'system_id': {'readonly': True}, - 'status': {'readonly': True}, - 'status_reason_code': {'readonly': True}, - 'spending_limit': {'readonly': True}, - 'target_clouds': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'display_name': {'key': 'properties.displayName', 'type': 'str'}, - 'po_number': {'key': 'properties.poNumber', 'type': 'str'}, - 'billing_relationship_type': {'key': 'properties.billingRelationshipType', 'type': 'str'}, - 'bill_to': {'key': 'properties.billTo', 'type': 'AddressDetails'}, - 'indirect_relationship_info': {'key': 'properties.indirectRelationshipInfo', 'type': 'IndirectRelationshipInfo'}, - 'invoice_email_opt_in': {'key': 'properties.invoiceEmailOptIn', 'type': 'bool'}, - 'invoice_day': {'key': 'properties.invoiceDay', 'type': 'int'}, - 'currency': {'key': 'properties.currency', 'type': 'str'}, - 'enabled_azure_plans': {'key': 'properties.enabledAzurePlans', 'type': '[AzurePlan]'}, - 'invoice_sections': {'key': 'properties.invoiceSections', 'type': 'InvoiceSectionsOnExpand'}, - 'has_read_access': {'key': 'properties.hasReadAccess', 'type': 'bool'}, - 'system_id': {'key': 'properties.systemId', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'status_reason_code': {'key': 'properties.statusReasonCode', 'type': 'str'}, - 'spending_limit': {'key': 'properties.spendingLimit', 'type': 'str'}, - 'target_clouds': {'key': 'properties.targetClouds', 'type': '[str]'}, - 'tags': {'key': 'properties.tags', 'type': '{str}'}, - } - - def __init__( - self, - **kwargs - ): - super(BillingProfile, self).__init__(**kwargs) - self.display_name = kwargs.get('display_name', None) - self.po_number = kwargs.get('po_number', None) - self.billing_relationship_type = None - self.bill_to = kwargs.get('bill_to', None) - self.indirect_relationship_info = None - self.invoice_email_opt_in = kwargs.get('invoice_email_opt_in', None) - self.invoice_day = None - self.currency = None - self.enabled_azure_plans = kwargs.get('enabled_azure_plans', None) - self.invoice_sections = kwargs.get('invoice_sections', None) - self.has_read_access = None - self.system_id = None - self.status = None - self.status_reason_code = None - self.spending_limit = None - self.target_clouds = None - self.tags = kwargs.get('tags', None) - - -class BillingProfileCreationRequest(msrest.serialization.Model): - """The request parameters for creating a new billing profile. - - :param display_name: The name of the billing profile. - :type display_name: str - :param po_number: The purchase order name that will appear on the invoices generated for the - billing profile. - :type po_number: str - :param bill_to: The address of the individual or organization that is responsible for the - billing profile. - :type bill_to: ~azure.mgmt.billing.models.AddressDetails - :param invoice_email_opt_in: Flag controlling whether the invoices for the billing profile are - sent through email. - :type invoice_email_opt_in: bool - :param enabled_azure_plans: Enabled azure plans for the billing profile. - :type enabled_azure_plans: list[~azure.mgmt.billing.models.AzurePlan] - """ - - _attribute_map = { - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'po_number': {'key': 'poNumber', 'type': 'str'}, - 'bill_to': {'key': 'billTo', 'type': 'AddressDetails'}, - 'invoice_email_opt_in': {'key': 'invoiceEmailOptIn', 'type': 'bool'}, - 'enabled_azure_plans': {'key': 'enabledAzurePlans', 'type': '[AzurePlan]'}, - } - - def __init__( - self, - **kwargs - ): - super(BillingProfileCreationRequest, self).__init__(**kwargs) - self.display_name = kwargs.get('display_name', None) - self.po_number = kwargs.get('po_number', None) - self.bill_to = kwargs.get('bill_to', None) - self.invoice_email_opt_in = kwargs.get('invoice_email_opt_in', None) - self.enabled_azure_plans = kwargs.get('enabled_azure_plans', None) - - -class BillingProfileListResult(msrest.serialization.Model): - """The list of billing profiles. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of billing profiles. - :vartype value: list[~azure.mgmt.billing.models.BillingProfile] - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - """ - - _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[BillingProfile]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(BillingProfileListResult, self).__init__(**kwargs) - self.value = None - self.next_link = None - - -class BillingProfilesOnExpand(msrest.serialization.Model): - """The billing profiles associated with the billing account. By default this is not populated, unless it's specified in $expand. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar has_more_results: Indicates whether there are more billing profiles than the ones listed - in this collection. The collection lists a maximum of 50 billing profiles. To get all billing - profiles, use the list billing profiles API. - :vartype has_more_results: bool - :param value: The billing profiles associated with the billing account. - :type value: list[~azure.mgmt.billing.models.BillingProfile] - """ - - _validation = { - 'has_more_results': {'readonly': True}, - } - - _attribute_map = { - 'has_more_results': {'key': 'hasMoreResults', 'type': 'bool'}, - 'value': {'key': 'value', 'type': '[BillingProfile]'}, - } - - def __init__( - self, - **kwargs - ): - super(BillingProfilesOnExpand, self).__init__(**kwargs) - self.has_more_results = None - self.value = kwargs.get('value', None) - - -class BillingProperty(Resource): - """A billing property. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar account_admin_notification_email_address: The email address on which the account admin - gets all Azure notifications. - :vartype account_admin_notification_email_address: str - :ivar billing_tenant_id: The Azure AD tenant ID of the billing account for the subscription. - :vartype billing_tenant_id: str - :ivar billing_account_id: The ID of the billing account to which the subscription is billed. - :vartype billing_account_id: str - :ivar billing_account_display_name: The name of the billing account to which the subscription - is billed. - :vartype billing_account_display_name: str - :ivar billing_profile_id: The ID of the billing profile to which the subscription is billed. - :vartype billing_profile_id: str - :ivar billing_profile_display_name: The name of the billing profile to which the subscription - is billed. - :vartype billing_profile_display_name: str - :ivar billing_profile_status: The status of the billing profile. Possible values include: - "Active", "Disabled", "Warned". - :vartype billing_profile_status: str or ~azure.mgmt.billing.models.BillingProfileStatus - :ivar billing_profile_status_reason_code: Reason for the specified billing profile status. - Possible values include: "PastDue", "SpendingLimitReached", "SpendingLimitExpired". - :vartype billing_profile_status_reason_code: str or - ~azure.mgmt.billing.models.BillingProfileStatusReasonCode - :ivar billing_profile_spending_limit: The billing profile spending limit. Possible values - include: "Off", "On". - :vartype billing_profile_spending_limit: str or - ~azure.mgmt.billing.models.BillingProfileSpendingLimit - :param cost_center: The cost center applied to the subscription. - :type cost_center: str - :ivar invoice_section_id: The ID of the invoice section to which the subscription is billed. - :vartype invoice_section_id: str - :ivar invoice_section_display_name: The name of the invoice section to which the subscription - is billed. - :vartype invoice_section_display_name: str - :ivar is_account_admin: Indicates whether user is the account admin. - :vartype is_account_admin: bool - :ivar product_id: The product ID of the Azure plan. - :vartype product_id: str - :ivar product_name: The product name of the Azure plan. - :vartype product_name: str - :ivar sku_id: The sku ID of the Azure plan for the subscription. - :vartype sku_id: str - :ivar sku_description: The sku description of the Azure plan for the subscription. - :vartype sku_description: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'account_admin_notification_email_address': {'readonly': True}, - 'billing_tenant_id': {'readonly': True}, - 'billing_account_id': {'readonly': True}, - 'billing_account_display_name': {'readonly': True}, - 'billing_profile_id': {'readonly': True}, - 'billing_profile_display_name': {'readonly': True}, - 'billing_profile_status': {'readonly': True}, - 'billing_profile_status_reason_code': {'readonly': True}, - 'billing_profile_spending_limit': {'readonly': True}, - 'invoice_section_id': {'readonly': True}, - 'invoice_section_display_name': {'readonly': True}, - 'is_account_admin': {'readonly': True}, - 'product_id': {'readonly': True}, - 'product_name': {'readonly': True}, - 'sku_id': {'readonly': True}, - 'sku_description': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'account_admin_notification_email_address': {'key': 'properties.accountAdminNotificationEmailAddress', 'type': 'str'}, - 'billing_tenant_id': {'key': 'properties.billingTenantId', 'type': 'str'}, - 'billing_account_id': {'key': 'properties.billingAccountId', 'type': 'str'}, - 'billing_account_display_name': {'key': 'properties.billingAccountDisplayName', 'type': 'str'}, - 'billing_profile_id': {'key': 'properties.billingProfileId', 'type': 'str'}, - 'billing_profile_display_name': {'key': 'properties.billingProfileDisplayName', 'type': 'str'}, - 'billing_profile_status': {'key': 'properties.billingProfileStatus', 'type': 'str'}, - 'billing_profile_status_reason_code': {'key': 'properties.billingProfileStatusReasonCode', 'type': 'str'}, - 'billing_profile_spending_limit': {'key': 'properties.billingProfileSpendingLimit', 'type': 'str'}, - 'cost_center': {'key': 'properties.costCenter', 'type': 'str'}, - 'invoice_section_id': {'key': 'properties.invoiceSectionId', 'type': 'str'}, - 'invoice_section_display_name': {'key': 'properties.invoiceSectionDisplayName', 'type': 'str'}, - 'is_account_admin': {'key': 'properties.isAccountAdmin', 'type': 'bool'}, - 'product_id': {'key': 'properties.productId', 'type': 'str'}, - 'product_name': {'key': 'properties.productName', 'type': 'str'}, - 'sku_id': {'key': 'properties.skuId', 'type': 'str'}, - 'sku_description': {'key': 'properties.skuDescription', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(BillingProperty, self).__init__(**kwargs) - self.account_admin_notification_email_address = None - self.billing_tenant_id = None - self.billing_account_id = None - self.billing_account_display_name = None - self.billing_profile_id = None - self.billing_profile_display_name = None - self.billing_profile_status = None - self.billing_profile_status_reason_code = None - self.billing_profile_spending_limit = None - self.cost_center = kwargs.get('cost_center', None) - self.invoice_section_id = None - self.invoice_section_display_name = None - self.is_account_admin = None - self.product_id = None - self.product_name = None - self.sku_id = None - self.sku_description = None - - -class BillingRoleAssignment(Resource): - """The role assignment. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar created_on: The date the role assignment was created. - :vartype created_on: str - :ivar created_by_principal_tenant_id: The tenant Id of the user who created the role - assignment. - :vartype created_by_principal_tenant_id: str - :ivar created_by_principal_id: The principal Id of the user who created the role assignment. - :vartype created_by_principal_id: str - :ivar created_by_user_email_address: The email address of the user who created the role - assignment. - :vartype created_by_user_email_address: str - :param principal_id: The principal id of the user to whom the role was assigned. - :type principal_id: str - :param principal_tenant_id: The principal tenant id of the user to whom the role was assigned. - :type principal_tenant_id: str - :param role_definition_id: The ID of the role definition. - :type role_definition_id: str - :ivar scope: The scope at which the role was assigned. - :vartype scope: str - :param user_authentication_type: The authentication type. - :type user_authentication_type: str - :param user_email_address: The email address of the user. - :type user_email_address: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'created_on': {'readonly': True}, - 'created_by_principal_tenant_id': {'readonly': True}, - 'created_by_principal_id': {'readonly': True}, - 'created_by_user_email_address': {'readonly': True}, - 'scope': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'created_on': {'key': 'properties.createdOn', 'type': 'str'}, - 'created_by_principal_tenant_id': {'key': 'properties.createdByPrincipalTenantId', 'type': 'str'}, - 'created_by_principal_id': {'key': 'properties.createdByPrincipalId', 'type': 'str'}, - 'created_by_user_email_address': {'key': 'properties.createdByUserEmailAddress', 'type': 'str'}, - 'principal_id': {'key': 'properties.principalId', 'type': 'str'}, - 'principal_tenant_id': {'key': 'properties.principalTenantId', 'type': 'str'}, - 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'user_authentication_type': {'key': 'properties.userAuthenticationType', 'type': 'str'}, - 'user_email_address': {'key': 'properties.userEmailAddress', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(BillingRoleAssignment, self).__init__(**kwargs) - self.created_on = None - self.created_by_principal_tenant_id = None - self.created_by_principal_id = None - self.created_by_user_email_address = None - self.principal_id = kwargs.get('principal_id', None) - self.principal_tenant_id = kwargs.get('principal_tenant_id', None) - self.role_definition_id = kwargs.get('role_definition_id', None) - self.scope = None - self.user_authentication_type = kwargs.get('user_authentication_type', None) - self.user_email_address = kwargs.get('user_email_address', None) - - -class BillingRoleAssignmentListResult(msrest.serialization.Model): - """The list of role assignments. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of role assignments. - :vartype value: list[~azure.mgmt.billing.models.BillingRoleAssignment] - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - """ - - _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[BillingRoleAssignment]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(BillingRoleAssignmentListResult, self).__init__(**kwargs) - self.value = None - self.next_link = None - - -class BillingRoleDefinition(Resource): - """The properties of a role definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar description: The role description. - :vartype description: str - :param permissions: The billingPermissions the role has. - :type permissions: list[~azure.mgmt.billing.models.BillingPermissionsProperties] - :ivar role_name: The name of the role. - :vartype role_name: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'description': {'readonly': True}, - 'role_name': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'permissions': {'key': 'properties.permissions', 'type': '[BillingPermissionsProperties]'}, - 'role_name': {'key': 'properties.roleName', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(BillingRoleDefinition, self).__init__(**kwargs) - self.description = None - self.permissions = kwargs.get('permissions', None) - self.role_name = None - - -class BillingRoleDefinitionListResult(msrest.serialization.Model): - """The list of role definitions. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The role definitions. - :vartype value: list[~azure.mgmt.billing.models.BillingRoleDefinition] - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - """ - - _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[BillingRoleDefinition]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(BillingRoleDefinitionListResult, self).__init__(**kwargs) - self.value = None - self.next_link = None - - -class BillingSubscription(Resource): - """A billing subscription. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar display_name: The name of the subscription. - :vartype display_name: str - :ivar subscription_id: The ID of the subscription. - :vartype subscription_id: str - :param subscription_billing_status: The current billing status of the subscription. Possible - values include: "Active", "Inactive", "Abandoned", "Deleted", "Warning". - :type subscription_billing_status: str or - ~azure.mgmt.billing.models.BillingSubscriptionStatusType - :ivar last_month_charges: The last month charges. - :vartype last_month_charges: ~azure.mgmt.billing.models.Amount - :ivar month_to_date_charges: The current month to date charges. - :vartype month_to_date_charges: ~azure.mgmt.billing.models.Amount - :ivar billing_profile_id: The ID of the billing profile to which the subscription is billed. - :vartype billing_profile_id: str - :ivar billing_profile_display_name: The name of the billing profile to which the subscription - is billed. - :vartype billing_profile_display_name: str - :param cost_center: The cost center applied to the subscription. - :type cost_center: str - :ivar customer_id: The ID of the customer for whom the subscription was created. The field is - applicable only for Microsoft Partner Agreement billing account. - :vartype customer_id: str - :ivar customer_display_name: The name of the customer for whom the subscription was created. - The field is applicable only for Microsoft Partner Agreement billing account. - :vartype customer_display_name: str - :ivar invoice_section_id: The ID of the invoice section to which the subscription is billed. - :vartype invoice_section_id: str - :ivar invoice_section_display_name: The name of the invoice section to which the subscription - is billed. - :vartype invoice_section_display_name: str - :ivar reseller: Reseller for this subscription. - :vartype reseller: ~azure.mgmt.billing.models.Reseller - :param sku_id: The sku ID of the Azure plan for the subscription. - :type sku_id: str - :ivar sku_description: The sku description of the Azure plan for the subscription. - :vartype sku_description: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'display_name': {'readonly': True}, - 'subscription_id': {'readonly': True}, - 'last_month_charges': {'readonly': True}, - 'month_to_date_charges': {'readonly': True}, - 'billing_profile_id': {'readonly': True}, - 'billing_profile_display_name': {'readonly': True}, - 'customer_id': {'readonly': True}, - 'customer_display_name': {'readonly': True}, - 'invoice_section_id': {'readonly': True}, - 'invoice_section_display_name': {'readonly': True}, - 'reseller': {'readonly': True}, - 'sku_description': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'display_name': {'key': 'properties.displayName', 'type': 'str'}, - 'subscription_id': {'key': 'properties.subscriptionId', 'type': 'str'}, - 'subscription_billing_status': {'key': 'properties.subscriptionBillingStatus', 'type': 'str'}, - 'last_month_charges': {'key': 'properties.lastMonthCharges', 'type': 'Amount'}, - 'month_to_date_charges': {'key': 'properties.monthToDateCharges', 'type': 'Amount'}, - 'billing_profile_id': {'key': 'properties.billingProfileId', 'type': 'str'}, - 'billing_profile_display_name': {'key': 'properties.billingProfileDisplayName', 'type': 'str'}, - 'cost_center': {'key': 'properties.costCenter', 'type': 'str'}, - 'customer_id': {'key': 'properties.customerId', 'type': 'str'}, - 'customer_display_name': {'key': 'properties.customerDisplayName', 'type': 'str'}, - 'invoice_section_id': {'key': 'properties.invoiceSectionId', 'type': 'str'}, - 'invoice_section_display_name': {'key': 'properties.invoiceSectionDisplayName', 'type': 'str'}, - 'reseller': {'key': 'properties.reseller', 'type': 'Reseller'}, - 'sku_id': {'key': 'properties.skuId', 'type': 'str'}, - 'sku_description': {'key': 'properties.skuDescription', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(BillingSubscription, self).__init__(**kwargs) - self.display_name = None - self.subscription_id = None - self.subscription_billing_status = kwargs.get('subscription_billing_status', None) - self.last_month_charges = None - self.month_to_date_charges = None - self.billing_profile_id = None - self.billing_profile_display_name = None - self.cost_center = kwargs.get('cost_center', None) - self.customer_id = None - self.customer_display_name = None - self.invoice_section_id = None - self.invoice_section_display_name = None - self.reseller = None - self.sku_id = kwargs.get('sku_id', None) - self.sku_description = None - - -class BillingSubscriptionsListResult(msrest.serialization.Model): - """The list of billing subscriptions. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of billing subscriptions. - :vartype value: list[~azure.mgmt.billing.models.BillingSubscription] - :ivar total_count: Total number of records. - :vartype total_count: int - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - """ - - _validation = { - 'value': {'readonly': True}, - 'total_count': {'readonly': True}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[BillingSubscription]'}, - 'total_count': {'key': 'totalCount', 'type': 'int'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(BillingSubscriptionsListResult, self).__init__(**kwargs) - self.value = None - self.total_count = None - self.next_link = None - - -class Customer(Resource): - """A partner's customer. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar billing_profile_id: The ID of the billing profile for the invoice section. - :vartype billing_profile_id: str - :ivar billing_profile_display_name: The name of the billing profile for the invoice section. - :vartype billing_profile_display_name: str - :param display_name: The name of the customer. - :type display_name: str - :param enabled_azure_plans: Azure plans enabled for the customer. - :type enabled_azure_plans: list[~azure.mgmt.billing.models.AzurePlan] - :param resellers: The list of resellers for which an Azure plan is enabled for the customer. - :type resellers: list[~azure.mgmt.billing.models.Reseller] - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'billing_profile_id': {'readonly': True}, - 'billing_profile_display_name': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'billing_profile_id': {'key': 'properties.billingProfileId', 'type': 'str'}, - 'billing_profile_display_name': {'key': 'properties.billingProfileDisplayName', 'type': 'str'}, - 'display_name': {'key': 'properties.displayName', 'type': 'str'}, - 'enabled_azure_plans': {'key': 'properties.enabledAzurePlans', 'type': '[AzurePlan]'}, - 'resellers': {'key': 'properties.resellers', 'type': '[Reseller]'}, - } - - def __init__( - self, - **kwargs - ): - super(Customer, self).__init__(**kwargs) - self.billing_profile_id = None - self.billing_profile_display_name = None - self.display_name = kwargs.get('display_name', None) - self.enabled_azure_plans = kwargs.get('enabled_azure_plans', None) - self.resellers = kwargs.get('resellers', None) - - -class CustomerListResult(msrest.serialization.Model): - """The list of customers. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of customers. - :vartype value: list[~azure.mgmt.billing.models.Customer] - :ivar total_count: Total number of records. - :vartype total_count: int - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - """ - - _validation = { - 'value': {'readonly': True}, - 'total_count': {'readonly': True}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[Customer]'}, - 'total_count': {'key': 'totalCount', 'type': 'int'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(CustomerListResult, self).__init__(**kwargs) - self.value = None - self.total_count = None - self.next_link = None - - -class CustomerPolicy(Resource): - """The customer's Policy. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :param view_charges: The policy that controls whether the users in customer's organization can - view charges at pay-as-you-go prices. Possible values include: "Allowed", "NotAllowed". - :type view_charges: str or ~azure.mgmt.billing.models.ViewCharges - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'view_charges': {'key': 'properties.viewCharges', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(CustomerPolicy, self).__init__(**kwargs) - self.view_charges = kwargs.get('view_charges', None) - - -class Department(Resource): - """A department. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :param department_name: The name of the department. - :type department_name: str - :param cost_center: The cost center associated with the department. - :type cost_center: str - :param status: The status of the department. - :type status: str - :param enrollment_accounts: Associated enrollment accounts. By default this is not populated, - unless it's specified in $expand. - :type enrollment_accounts: list[~azure.mgmt.billing.models.EnrollmentAccount] - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'department_name': {'key': 'properties.departmentName', 'type': 'str'}, - 'cost_center': {'key': 'properties.costCenter', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'enrollment_accounts': {'key': 'properties.enrollmentAccounts', 'type': '[EnrollmentAccount]'}, - } - - def __init__( - self, - **kwargs - ): - super(Department, self).__init__(**kwargs) - self.department_name = kwargs.get('department_name', None) - self.cost_center = kwargs.get('cost_center', None) - self.status = kwargs.get('status', None) - self.enrollment_accounts = kwargs.get('enrollment_accounts', None) - - -class Document(msrest.serialization.Model): - """The properties of a document. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar kind: The type of the document. Possible values include: "Invoice", "VoidNote", - "TaxReceipt", "CreditNote". - :vartype kind: str or ~azure.mgmt.billing.models.DocumentType - :ivar url: Document URL. - :vartype url: str - :ivar source: The source of the document. ENF for Brazil and DRS for rest of the world. - Possible values include: "DRS", "ENF". - :vartype source: str or ~azure.mgmt.billing.models.DocumentSource - """ - - _validation = { - 'kind': {'readonly': True}, - 'url': {'readonly': True}, - 'source': {'readonly': True}, - } - - _attribute_map = { - 'kind': {'key': 'kind', 'type': 'str'}, - 'url': {'key': 'url', 'type': 'str'}, - 'source': {'key': 'source', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(Document, self).__init__(**kwargs) - self.kind = None - self.url = None - self.source = None - - -class DownloadUrl(msrest.serialization.Model): - """A secure URL that can be used to download a an entity until the URL expires. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar expiry_time: The time in UTC when the download URL will expire. - :vartype expiry_time: ~datetime.datetime - :ivar url: The URL to the PDF file. - :vartype url: str - """ - - _validation = { - 'expiry_time': {'readonly': True}, - 'url': {'readonly': True}, - } - - _attribute_map = { - 'expiry_time': {'key': 'expiryTime', 'type': 'iso-8601'}, - 'url': {'key': 'url', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(DownloadUrl, self).__init__(**kwargs) - self.expiry_time = None - self.url = None - - -class Enrollment(msrest.serialization.Model): - """The properties of an enrollment. - - Variables are only populated by the server, and will be ignored when sending a request. - - :param start_date: The start date of the enrollment. - :type start_date: ~datetime.datetime - :param end_date: The end date of the enrollment. - :type end_date: ~datetime.datetime - :ivar currency: The billing currency for the enrollment. - :vartype currency: str - :ivar channel: The channel type of the enrollment. - :vartype channel: str - :ivar policies: The policies for Enterprise Agreement enrollments. - :vartype policies: ~azure.mgmt.billing.models.EnrollmentPolicies - :ivar language: The language for the enrollment. - :vartype language: str - :ivar country_code: The country code of the enrollment. - :vartype country_code: str - :ivar status: The current status of the enrollment. - :vartype status: str - :ivar billing_cycle: The billing cycle for the enrollment. - :vartype billing_cycle: str - """ - - _validation = { - 'currency': {'readonly': True}, - 'channel': {'readonly': True}, - 'policies': {'readonly': True}, - 'language': {'readonly': True}, - 'country_code': {'readonly': True}, - 'status': {'readonly': True}, - 'billing_cycle': {'readonly': True}, - } - - _attribute_map = { - 'start_date': {'key': 'startDate', 'type': 'iso-8601'}, - 'end_date': {'key': 'endDate', 'type': 'iso-8601'}, - 'currency': {'key': 'currency', 'type': 'str'}, - 'channel': {'key': 'channel', 'type': 'str'}, - 'policies': {'key': 'policies', 'type': 'EnrollmentPolicies'}, - 'language': {'key': 'language', 'type': 'str'}, - 'country_code': {'key': 'countryCode', 'type': 'str'}, - 'status': {'key': 'status', 'type': 'str'}, - 'billing_cycle': {'key': 'billingCycle', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(Enrollment, self).__init__(**kwargs) - self.start_date = kwargs.get('start_date', None) - self.end_date = kwargs.get('end_date', None) - self.currency = None - self.channel = None - self.policies = None - self.language = None - self.country_code = None - self.status = None - self.billing_cycle = None - - -class EnrollmentAccount(Resource): - """An enrollment account. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :param account_name: The name of the enrollment account. - :type account_name: str - :param cost_center: The cost center associated with the enrollment account. - :type cost_center: str - :param account_owner: The owner of the enrollment account. - :type account_owner: str - :param account_owner_email: The enrollment account owner email address. - :type account_owner_email: str - :param status: The status of the enrollment account. - :type status: str - :param start_date: The start date of the enrollment account. - :type start_date: ~datetime.datetime - :param end_date: The end date of the enrollment account. - :type end_date: ~datetime.datetime - :param department: Associated department. By default this is not populated, unless it's - specified in $expand. - :type department: ~azure.mgmt.billing.models.Department - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'account_name': {'key': 'properties.accountName', 'type': 'str'}, - 'cost_center': {'key': 'properties.costCenter', 'type': 'str'}, - 'account_owner': {'key': 'properties.accountOwner', 'type': 'str'}, - 'account_owner_email': {'key': 'properties.accountOwnerEmail', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'start_date': {'key': 'properties.startDate', 'type': 'iso-8601'}, - 'end_date': {'key': 'properties.endDate', 'type': 'iso-8601'}, - 'department': {'key': 'properties.department', 'type': 'Department'}, - } - - def __init__( - self, - **kwargs - ): - super(EnrollmentAccount, self).__init__(**kwargs) - self.account_name = kwargs.get('account_name', None) - self.cost_center = kwargs.get('cost_center', None) - self.account_owner = kwargs.get('account_owner', None) - self.account_owner_email = kwargs.get('account_owner_email', None) - self.status = kwargs.get('status', None) - self.start_date = kwargs.get('start_date', None) - self.end_date = kwargs.get('end_date', None) - self.department = kwargs.get('department', None) - - -class EnrollmentAccountContext(msrest.serialization.Model): - """The enrollment account context. - - :param cost_center: The cost center associated with the enrollment account. - :type cost_center: str - :param start_date: The start date of the enrollment account. - :type start_date: ~datetime.datetime - :param end_date: The end date of the enrollment account. - :type end_date: ~datetime.datetime - :param enrollment_account_name: The ID of the enrollment account. - :type enrollment_account_name: str - """ - - _attribute_map = { - 'cost_center': {'key': 'costCenter', 'type': 'str'}, - 'start_date': {'key': 'startDate', 'type': 'iso-8601'}, - 'end_date': {'key': 'endDate', 'type': 'iso-8601'}, - 'enrollment_account_name': {'key': 'enrollmentAccountName', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(EnrollmentAccountContext, self).__init__(**kwargs) - self.cost_center = kwargs.get('cost_center', None) - self.start_date = kwargs.get('start_date', None) - self.end_date = kwargs.get('end_date', None) - self.enrollment_account_name = kwargs.get('enrollment_account_name', None) - - -class EnrollmentAccountListResult(msrest.serialization.Model): - """Result of listing enrollment accounts. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of enrollment accounts. - :vartype value: list[~azure.mgmt.billing.models.EnrollmentAccountSummary] - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - """ - - _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[EnrollmentAccountSummary]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(EnrollmentAccountListResult, self).__init__(**kwargs) - self.value = None - self.next_link = None - - -class EnrollmentAccountSummary(Resource): - """An enrollment account resource. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar principal_name: The account owner's principal name. - :vartype principal_name: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'principal_name': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'principal_name': {'key': 'properties.principalName', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(EnrollmentAccountSummary, self).__init__(**kwargs) - self.principal_name = None - - -class EnrollmentPolicies(msrest.serialization.Model): - """The policies for Enterprise Agreement enrollments. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar account_owner_view_charges: The policy that controls whether Account Owners can view - charges. - :vartype account_owner_view_charges: bool - :ivar department_admin_view_charges: The policy that controls whether Department Administrators - can view charges. - :vartype department_admin_view_charges: bool - :ivar marketplace_enabled: The policy that controls whether Azure marketplace purchases are - allowed in the enrollment. - :vartype marketplace_enabled: bool - :ivar reserved_instances_enabled: The policy that controls whether Azure reservation purchases - are allowed in the enrollment. - :vartype reserved_instances_enabled: bool - """ - - _validation = { - 'account_owner_view_charges': {'readonly': True}, - 'department_admin_view_charges': {'readonly': True}, - 'marketplace_enabled': {'readonly': True}, - 'reserved_instances_enabled': {'readonly': True}, - } - - _attribute_map = { - 'account_owner_view_charges': {'key': 'accountOwnerViewCharges', 'type': 'bool'}, - 'department_admin_view_charges': {'key': 'departmentAdminViewCharges', 'type': 'bool'}, - 'marketplace_enabled': {'key': 'marketplaceEnabled', 'type': 'bool'}, - 'reserved_instances_enabled': {'key': 'reservedInstancesEnabled', 'type': 'bool'}, - } - - def __init__( - self, - **kwargs - ): - super(EnrollmentPolicies, self).__init__(**kwargs) - self.account_owner_view_charges = None - self.department_admin_view_charges = None - self.marketplace_enabled = None - self.reserved_instances_enabled = None - - -class ErrorDetails(msrest.serialization.Model): - """The details of the error. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: Error code. - :vartype code: str - :ivar message: Error message indicating why the operation failed. - :vartype message: str - :ivar target: The target of the particular error. - :vartype target: str - :ivar details: The sub details of the error. - :vartype details: list[~azure.mgmt.billing.models.ErrorSubDetailsItem] - """ - - _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, - 'target': {'readonly': True}, - 'details': {'readonly': True}, - } - - _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'str'}, - 'details': {'key': 'details', 'type': '[ErrorSubDetailsItem]'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorDetails, self).__init__(**kwargs) - self.code = None - self.message = None - self.target = None - self.details = None - - -class ErrorResponse(msrest.serialization.Model): - """Error response indicates that the service is not able to process the incoming request. The reason is provided in the error message. - - :param error: The details of the error. - :type error: ~azure.mgmt.billing.models.ErrorDetails - """ - - _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDetails'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorResponse, self).__init__(**kwargs) - self.error = kwargs.get('error', None) - - -class ErrorSubDetailsItem(msrest.serialization.Model): - """ErrorSubDetailsItem. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: Error code. - :vartype code: str - :ivar message: Error message indicating why the operation failed. - :vartype message: str - :ivar target: The target of the particular error. - :vartype target: str - """ - - _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, - 'target': {'readonly': True}, - } - - _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorSubDetailsItem, self).__init__(**kwargs) - self.code = None - self.message = None - self.target = None - - -class IndirectRelationshipInfo(msrest.serialization.Model): - """The billing profile details of the partner of the customer for an indirect motion. - - :param billing_account_name: The billing account name of the partner or the customer for an - indirect motion. - :type billing_account_name: str - :param billing_profile_name: The billing profile name of the partner or the customer for an - indirect motion. - :type billing_profile_name: str - :param display_name: The display name of the partner or customer for an indirect motion. - :type display_name: str - """ - - _attribute_map = { - 'billing_account_name': {'key': 'billingAccountName', 'type': 'str'}, - 'billing_profile_name': {'key': 'billingProfileName', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(IndirectRelationshipInfo, self).__init__(**kwargs) - self.billing_account_name = kwargs.get('billing_account_name', None) - self.billing_profile_name = kwargs.get('billing_profile_name', None) - self.display_name = kwargs.get('display_name', None) - - -class Instruction(Resource): - """An instruction. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :param amount: The amount budgeted for this billing instruction. - :type amount: float - :param start_date: The date this billing instruction goes into effect. - :type start_date: ~datetime.datetime - :param end_date: The date this billing instruction is no longer in effect. - :type end_date: ~datetime.datetime - :param creation_date: The date this billing instruction was created. - :type creation_date: ~datetime.datetime - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'amount': {'key': 'properties.amount', 'type': 'float'}, - 'start_date': {'key': 'properties.startDate', 'type': 'iso-8601'}, - 'end_date': {'key': 'properties.endDate', 'type': 'iso-8601'}, - 'creation_date': {'key': 'properties.creationDate', 'type': 'iso-8601'}, - } - - def __init__( - self, - **kwargs - ): - super(Instruction, self).__init__(**kwargs) - self.amount = kwargs.get('amount', None) - self.start_date = kwargs.get('start_date', None) - self.end_date = kwargs.get('end_date', None) - self.creation_date = kwargs.get('creation_date', None) - - -class InstructionListResult(msrest.serialization.Model): - """The list of billing instructions used during invoice generation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of billing instructions used during invoice generation. - :vartype value: list[~azure.mgmt.billing.models.Instruction] - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - """ - - _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[Instruction]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(InstructionListResult, self).__init__(**kwargs) - self.value = None - self.next_link = None - - -class Invoice(Resource): - """An invoice. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar due_date: The due date for the invoice. - :vartype due_date: ~datetime.datetime - :ivar invoice_date: The date when the invoice was generated. - :vartype invoice_date: ~datetime.datetime - :ivar status: The current status of the invoice. Possible values include: "Due", "OverDue", - "Paid", "Void". - :vartype status: str or ~azure.mgmt.billing.models.InvoiceStatus - :ivar amount_due: The amount due as of now. - :vartype amount_due: ~azure.mgmt.billing.models.Amount - :ivar azure_prepayment_applied: The amount of Azure prepayment applied to the charges. This - field is applicable to billing accounts with agreement type Microsoft Customer Agreement. - :vartype azure_prepayment_applied: ~azure.mgmt.billing.models.Amount - :ivar billed_amount: The total charges for the invoice billing period. - :vartype billed_amount: ~azure.mgmt.billing.models.Amount - :ivar credit_amount: The total refund for returns and cancellations during the invoice billing - period. This field is applicable to billing accounts with agreement type Microsoft Customer - Agreement. - :vartype credit_amount: ~azure.mgmt.billing.models.Amount - :ivar free_azure_credit_applied: The amount of free Azure credits applied to the charges. This - field is applicable to billing accounts with agreement type Microsoft Customer Agreement. - :vartype free_azure_credit_applied: ~azure.mgmt.billing.models.Amount - :ivar sub_total: The pre-tax amount due. This field is applicable to billing accounts with - agreement type Microsoft Customer Agreement. - :vartype sub_total: ~azure.mgmt.billing.models.Amount - :ivar tax_amount: The amount of tax charged for the billing period. This field is applicable to - billing accounts with agreement type Microsoft Customer Agreement. - :vartype tax_amount: ~azure.mgmt.billing.models.Amount - :ivar total_amount: The amount due when the invoice was generated. This field is applicable to - billing accounts with agreement type Microsoft Customer Agreement. - :vartype total_amount: ~azure.mgmt.billing.models.Amount - :ivar invoice_period_start_date: The start date of the billing period for which the invoice is - generated. - :vartype invoice_period_start_date: ~datetime.datetime - :ivar invoice_period_end_date: The end date of the billing period for which the invoice is - generated. - :vartype invoice_period_end_date: ~datetime.datetime - :ivar invoice_type: Invoice type. Possible values include: "AzureService", "AzureMarketplace", - "AzureSupport". - :vartype invoice_type: str or ~azure.mgmt.billing.models.InvoiceType - :ivar is_monthly_invoice: Specifies if the invoice is generated as part of monthly invoicing - cycle or not. This field is applicable to billing accounts with agreement type Microsoft - Customer Agreement. - :vartype is_monthly_invoice: bool - :ivar billing_profile_id: The ID of the billing profile for which the invoice is generated. - :vartype billing_profile_id: str - :ivar billing_profile_display_name: The name of the billing profile for which the invoice is - generated. - :vartype billing_profile_display_name: str - :ivar purchase_order_number: An optional purchase order number for the invoice. - :vartype purchase_order_number: str - :ivar documents: List of documents available to download such as invoice and tax receipt. - :vartype documents: list[~azure.mgmt.billing.models.Document] - :ivar payments: List of payments. - :vartype payments: list[~azure.mgmt.billing.models.PaymentProperties] - :ivar rebill_details: Rebill details for an invoice. - :vartype rebill_details: dict[str, ~azure.mgmt.billing.models.RebillDetails] - :ivar document_type: The type of the document. Possible values include: "Invoice", - "CreditNote". - :vartype document_type: str or ~azure.mgmt.billing.models.InvoiceDocumentType - :ivar billed_document_id: The Id of the active invoice which is originally billed after this - invoice was voided. This field is applicable to the void invoices only. - :vartype billed_document_id: str - :ivar credit_for_document_id: The Id of the invoice which got voided and this credit note was - issued as a result. This field is applicable to the credit notes only. - :vartype credit_for_document_id: str - :ivar subscription_id: The ID of the subscription for which the invoice is generated. - :vartype subscription_id: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'due_date': {'readonly': True}, - 'invoice_date': {'readonly': True}, - 'status': {'readonly': True}, - 'amount_due': {'readonly': True}, - 'azure_prepayment_applied': {'readonly': True}, - 'billed_amount': {'readonly': True}, - 'credit_amount': {'readonly': True}, - 'free_azure_credit_applied': {'readonly': True}, - 'sub_total': {'readonly': True}, - 'tax_amount': {'readonly': True}, - 'total_amount': {'readonly': True}, - 'invoice_period_start_date': {'readonly': True}, - 'invoice_period_end_date': {'readonly': True}, - 'invoice_type': {'readonly': True}, - 'is_monthly_invoice': {'readonly': True}, - 'billing_profile_id': {'readonly': True}, - 'billing_profile_display_name': {'readonly': True}, - 'purchase_order_number': {'readonly': True}, - 'documents': {'readonly': True}, - 'payments': {'readonly': True}, - 'rebill_details': {'readonly': True}, - 'document_type': {'readonly': True}, - 'billed_document_id': {'readonly': True}, - 'credit_for_document_id': {'readonly': True}, - 'subscription_id': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'due_date': {'key': 'properties.dueDate', 'type': 'iso-8601'}, - 'invoice_date': {'key': 'properties.invoiceDate', 'type': 'iso-8601'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'amount_due': {'key': 'properties.amountDue', 'type': 'Amount'}, - 'azure_prepayment_applied': {'key': 'properties.azurePrepaymentApplied', 'type': 'Amount'}, - 'billed_amount': {'key': 'properties.billedAmount', 'type': 'Amount'}, - 'credit_amount': {'key': 'properties.creditAmount', 'type': 'Amount'}, - 'free_azure_credit_applied': {'key': 'properties.freeAzureCreditApplied', 'type': 'Amount'}, - 'sub_total': {'key': 'properties.subTotal', 'type': 'Amount'}, - 'tax_amount': {'key': 'properties.taxAmount', 'type': 'Amount'}, - 'total_amount': {'key': 'properties.totalAmount', 'type': 'Amount'}, - 'invoice_period_start_date': {'key': 'properties.invoicePeriodStartDate', 'type': 'iso-8601'}, - 'invoice_period_end_date': {'key': 'properties.invoicePeriodEndDate', 'type': 'iso-8601'}, - 'invoice_type': {'key': 'properties.invoiceType', 'type': 'str'}, - 'is_monthly_invoice': {'key': 'properties.isMonthlyInvoice', 'type': 'bool'}, - 'billing_profile_id': {'key': 'properties.billingProfileId', 'type': 'str'}, - 'billing_profile_display_name': {'key': 'properties.billingProfileDisplayName', 'type': 'str'}, - 'purchase_order_number': {'key': 'properties.purchaseOrderNumber', 'type': 'str'}, - 'documents': {'key': 'properties.documents', 'type': '[Document]'}, - 'payments': {'key': 'properties.payments', 'type': '[PaymentProperties]'}, - 'rebill_details': {'key': 'properties.rebillDetails', 'type': '{RebillDetails}'}, - 'document_type': {'key': 'properties.documentType', 'type': 'str'}, - 'billed_document_id': {'key': 'properties.billedDocumentId', 'type': 'str'}, - 'credit_for_document_id': {'key': 'properties.creditForDocumentId', 'type': 'str'}, - 'subscription_id': {'key': 'properties.subscriptionId', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(Invoice, self).__init__(**kwargs) - self.due_date = None - self.invoice_date = None - self.status = None - self.amount_due = None - self.azure_prepayment_applied = None - self.billed_amount = None - self.credit_amount = None - self.free_azure_credit_applied = None - self.sub_total = None - self.tax_amount = None - self.total_amount = None - self.invoice_period_start_date = None - self.invoice_period_end_date = None - self.invoice_type = None - self.is_monthly_invoice = None - self.billing_profile_id = None - self.billing_profile_display_name = None - self.purchase_order_number = None - self.documents = None - self.payments = None - self.rebill_details = None - self.document_type = None - self.billed_document_id = None - self.credit_for_document_id = None - self.subscription_id = None - - -class InvoiceListResult(msrest.serialization.Model): - """The list of invoices. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of invoices. - :vartype value: list[~azure.mgmt.billing.models.Invoice] - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - """ - - _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[Invoice]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(InvoiceListResult, self).__init__(**kwargs) - self.value = None - self.next_link = None - - -class InvoiceSection(Resource): - """An invoice section. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :param display_name: The name of the invoice section. - :type display_name: str - :param labels: Dictionary of metadata associated with the invoice section. - :type labels: dict[str, str] - :ivar state: Identifies the state of an invoice section. Possible values include: "Active", - "Restricted". - :vartype state: str or ~azure.mgmt.billing.models.InvoiceSectionState - :ivar system_id: The system generated unique identifier for an invoice section. - :vartype system_id: str - :ivar target_cloud: Identifies the cloud environments that are associated with an invoice - section. This is a system managed optional field and gets updated as the invoice section gets - associated with accounts in various clouds. Possible values include: "USGov", "USNat", "USSec". - :vartype target_cloud: str or ~azure.mgmt.billing.models.TargetCloud - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'state': {'readonly': True}, - 'system_id': {'readonly': True}, - 'target_cloud': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'display_name': {'key': 'properties.displayName', 'type': 'str'}, - 'labels': {'key': 'properties.labels', 'type': '{str}'}, - 'state': {'key': 'properties.state', 'type': 'str'}, - 'system_id': {'key': 'properties.systemId', 'type': 'str'}, - 'target_cloud': {'key': 'properties.targetCloud', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(InvoiceSection, self).__init__(**kwargs) - self.display_name = kwargs.get('display_name', None) - self.labels = kwargs.get('labels', None) - self.state = None - self.system_id = None - self.target_cloud = None - - -class InvoiceSectionCreationRequest(msrest.serialization.Model): - """The properties of the invoice section. - - :param display_name: The name of the invoice section. - :type display_name: str - """ - - _attribute_map = { - 'display_name': {'key': 'displayName', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(InvoiceSectionCreationRequest, self).__init__(**kwargs) - self.display_name = kwargs.get('display_name', None) - - -class InvoiceSectionListResult(msrest.serialization.Model): - """The list of invoice sections. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of invoice sections. - :vartype value: list[~azure.mgmt.billing.models.InvoiceSection] - :ivar total_count: Total number of records. - :vartype total_count: int - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - """ - - _validation = { - 'value': {'readonly': True}, - 'total_count': {'readonly': True}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[InvoiceSection]'}, - 'total_count': {'key': 'totalCount', 'type': 'int'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(InvoiceSectionListResult, self).__init__(**kwargs) - self.value = None - self.total_count = None - self.next_link = None - - -class InvoiceSectionListWithCreateSubPermissionResult(msrest.serialization.Model): - """The list of invoice section properties with create subscription permission. - - Variables are only populated by the server, and will be ignored when sending a request. - - :param value: The list of invoice section properties with create subscription permission. - :type value: list[~azure.mgmt.billing.models.InvoiceSectionWithCreateSubPermission] - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - """ - - _validation = { - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[InvoiceSectionWithCreateSubPermission]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(InvoiceSectionListWithCreateSubPermissionResult, self).__init__(**kwargs) - self.value = kwargs.get('value', None) - self.next_link = None - - -class InvoiceSectionsOnExpand(msrest.serialization.Model): - """The invoice sections associated to the billing profile. By default this is not populated, unless it's specified in $expand. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar has_more_results: Indicates whether there are more invoice sections than the ones listed - in this collection. The collection lists a maximum of 50 invoice sections. To get all invoice - sections, use the list invoice sections API. - :vartype has_more_results: bool - :param value: The invoice sections associated to the billing profile. - :type value: list[~azure.mgmt.billing.models.InvoiceSection] - """ - - _validation = { - 'has_more_results': {'readonly': True}, - } - - _attribute_map = { - 'has_more_results': {'key': 'hasMoreResults', 'type': 'bool'}, - 'value': {'key': 'value', 'type': '[InvoiceSection]'}, - } - - def __init__( - self, - **kwargs - ): - super(InvoiceSectionsOnExpand, self).__init__(**kwargs) - self.has_more_results = None - self.value = kwargs.get('value', None) - - -class InvoiceSectionWithCreateSubPermission(msrest.serialization.Model): - """Invoice section properties with create subscription permission. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar invoice_section_id: The ID of the invoice section. - :vartype invoice_section_id: str - :ivar invoice_section_display_name: The name of the invoice section. - :vartype invoice_section_display_name: str - :ivar invoice_section_system_id: The system generated unique identifier for an invoice section. - :vartype invoice_section_system_id: str - :ivar billing_profile_id: The ID of the billing profile for the invoice section. - :vartype billing_profile_id: str - :ivar billing_profile_display_name: The name of the billing profile for the invoice section. - :vartype billing_profile_display_name: str - :ivar billing_profile_status: The status of the billing profile. Possible values include: - "Active", "Disabled", "Warned". - :vartype billing_profile_status: str or ~azure.mgmt.billing.models.BillingProfileStatus - :ivar billing_profile_status_reason_code: Reason for the specified billing profile status. - Possible values include: "PastDue", "SpendingLimitReached", "SpendingLimitExpired". - :vartype billing_profile_status_reason_code: str or - ~azure.mgmt.billing.models.StatusReasonCodeForBillingProfile - :ivar billing_profile_spending_limit: The billing profile spending limit. Possible values - include: "Off", "On". - :vartype billing_profile_spending_limit: str or - ~azure.mgmt.billing.models.SpendingLimitForBillingProfile - :ivar billing_profile_system_id: The system generated unique identifier for a billing profile. - :vartype billing_profile_system_id: str - :param enabled_azure_plans: Enabled azure plans for the associated billing profile. - :type enabled_azure_plans: list[~azure.mgmt.billing.models.AzurePlan] - """ - - _validation = { - 'invoice_section_id': {'readonly': True}, - 'invoice_section_display_name': {'readonly': True}, - 'invoice_section_system_id': {'readonly': True}, - 'billing_profile_id': {'readonly': True}, - 'billing_profile_display_name': {'readonly': True}, - 'billing_profile_status': {'readonly': True}, - 'billing_profile_status_reason_code': {'readonly': True}, - 'billing_profile_spending_limit': {'readonly': True}, - 'billing_profile_system_id': {'readonly': True}, - } - - _attribute_map = { - 'invoice_section_id': {'key': 'invoiceSectionId', 'type': 'str'}, - 'invoice_section_display_name': {'key': 'invoiceSectionDisplayName', 'type': 'str'}, - 'invoice_section_system_id': {'key': 'invoiceSectionSystemId', 'type': 'str'}, - 'billing_profile_id': {'key': 'billingProfileId', 'type': 'str'}, - 'billing_profile_display_name': {'key': 'billingProfileDisplayName', 'type': 'str'}, - 'billing_profile_status': {'key': 'billingProfileStatus', 'type': 'str'}, - 'billing_profile_status_reason_code': {'key': 'billingProfileStatusReasonCode', 'type': 'str'}, - 'billing_profile_spending_limit': {'key': 'billingProfileSpendingLimit', 'type': 'str'}, - 'billing_profile_system_id': {'key': 'billingProfileSystemId', 'type': 'str'}, - 'enabled_azure_plans': {'key': 'enabledAzurePlans', 'type': '[AzurePlan]'}, - } - - def __init__( - self, - **kwargs - ): - super(InvoiceSectionWithCreateSubPermission, self).__init__(**kwargs) - self.invoice_section_id = None - self.invoice_section_display_name = None - self.invoice_section_system_id = None - self.billing_profile_id = None - self.billing_profile_display_name = None - self.billing_profile_status = None - self.billing_profile_status_reason_code = None - self.billing_profile_spending_limit = None - self.billing_profile_system_id = None - self.enabled_azure_plans = kwargs.get('enabled_azure_plans', None) - - -class Operation(msrest.serialization.Model): - """A Billing REST API operation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar name: Operation name: {provider}/{resource}/{operation}. - :vartype name: str - :ivar is_data_action: Identifies if the operation is a data operation. - :vartype is_data_action: bool - :param display: The object that represents the operation. - :type display: ~azure.mgmt.billing.models.OperationDisplay - """ - - _validation = { - 'name': {'readonly': True}, - 'is_data_action': {'readonly': True}, - } - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, - 'display': {'key': 'display', 'type': 'OperationDisplay'}, - } - - def __init__( - self, - **kwargs - ): - super(Operation, self).__init__(**kwargs) - self.name = None - self.is_data_action = None - self.display = kwargs.get('display', None) - - -class OperationDisplay(msrest.serialization.Model): - """The object that represents the operation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar provider: Service provider: Microsoft.Billing. - :vartype provider: str - :ivar resource: Resource on which the operation is performed such as invoice and billing - subscription. - :vartype resource: str - :ivar operation: Operation type such as read, write and delete. - :vartype operation: str - :ivar description: Description of operation. - :vartype description: str - """ - - _validation = { - 'provider': {'readonly': True}, - 'resource': {'readonly': True}, - 'operation': {'readonly': True}, - 'description': {'readonly': True}, - } - - _attribute_map = { - 'provider': {'key': 'provider', 'type': 'str'}, - 'resource': {'key': 'resource', 'type': 'str'}, - 'operation': {'key': 'operation', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(OperationDisplay, self).__init__(**kwargs) - self.provider = None - self.resource = None - self.operation = None - self.description = None - - -class OperationListResult(msrest.serialization.Model): - """The list of billing operations and a URL link to get the next set of results. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of billing operations supported by the Microsoft.Billing resource - provider. - :vartype value: list[~azure.mgmt.billing.models.Operation] - :ivar next_link: URL to get the next set of operation list results if there are any. - :vartype next_link: str - """ - - _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[Operation]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(OperationListResult, self).__init__(**kwargs) - self.value = None - self.next_link = None - - -class Participants(msrest.serialization.Model): - """The details about a participant. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar status: The acceptance status of the participant. - :vartype status: str - :ivar status_date: The date when the status got changed. - :vartype status_date: ~datetime.datetime - :ivar email: The email address of the participant. - :vartype email: str - """ - - _validation = { - 'status': {'readonly': True}, - 'status_date': {'readonly': True}, - 'email': {'readonly': True}, - } - - _attribute_map = { - 'status': {'key': 'status', 'type': 'str'}, - 'status_date': {'key': 'statusDate', 'type': 'iso-8601'}, - 'email': {'key': 'email', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(Participants, self).__init__(**kwargs) - self.status = None - self.status_date = None - self.email = None - - -class PaymentProperties(msrest.serialization.Model): - """The properties of a payment. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar payment_type: The type of payment. - :vartype payment_type: str - :ivar amount: The paid amount. - :vartype amount: ~azure.mgmt.billing.models.Amount - :ivar date: The date when the payment was made. - :vartype date: ~datetime.datetime - :param payment_method_family: The family of payment method. Possible values include: "Credits", - "CheckWire", "CreditCard", "None". - :type payment_method_family: str or ~azure.mgmt.billing.models.PaymentMethodFamily - :ivar payment_method_type: The type of payment method. - :vartype payment_method_type: str - """ - - _validation = { - 'payment_type': {'readonly': True}, - 'amount': {'readonly': True}, - 'date': {'readonly': True}, - 'payment_method_type': {'readonly': True}, - } - - _attribute_map = { - 'payment_type': {'key': 'paymentType', 'type': 'str'}, - 'amount': {'key': 'amount', 'type': 'Amount'}, - 'date': {'key': 'date', 'type': 'iso-8601'}, - 'payment_method_family': {'key': 'paymentMethodFamily', 'type': 'str'}, - 'payment_method_type': {'key': 'paymentMethodType', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PaymentProperties, self).__init__(**kwargs) - self.payment_type = None - self.amount = None - self.date = None - self.payment_method_family = kwargs.get('payment_method_family', None) - self.payment_method_type = None - - -class Policy(Resource): - """A policy. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :param marketplace_purchases: The policy that controls whether Azure marketplace purchases are - allowed for a billing profile. Possible values include: "AllAllowed", "OnlyFreeAllowed", - "NotAllowed". - :type marketplace_purchases: str or ~azure.mgmt.billing.models.MarketplacePurchasesPolicy - :param reservation_purchases: The policy that controls whether Azure reservation purchases are - allowed for a billing profile. Possible values include: "Allowed", "NotAllowed". - :type reservation_purchases: str or ~azure.mgmt.billing.models.ReservationPurchasesPolicy - :param view_charges: The policy that controls whether users with Azure RBAC access to a - subscription can view its charges. Possible values include: "Allowed", "NotAllowed". - :type view_charges: str or ~azure.mgmt.billing.models.ViewChargesPolicy - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'marketplace_purchases': {'key': 'properties.marketplacePurchases', 'type': 'str'}, - 'reservation_purchases': {'key': 'properties.reservationPurchases', 'type': 'str'}, - 'view_charges': {'key': 'properties.viewCharges', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(Policy, self).__init__(**kwargs) - self.marketplace_purchases = kwargs.get('marketplace_purchases', None) - self.reservation_purchases = kwargs.get('reservation_purchases', None) - self.view_charges = kwargs.get('view_charges', None) - - -class Product(Resource): - """A product. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :param auto_renew: Indicates whether auto renewal is turned on or off for a product. Possible - values include: "Off", "On". - :type auto_renew: str or ~azure.mgmt.billing.models.AutoRenew - :ivar display_name: The display name of the product. - :vartype display_name: str - :ivar purchase_date: The date when the product was purchased. - :vartype purchase_date: ~datetime.datetime - :ivar product_type_id: The ID of the type of product. - :vartype product_type_id: str - :ivar product_type: The description of the type of product. - :vartype product_type: str - :param status: The current status of the product. Possible values include: "Active", - "Inactive", "PastDue", "Expiring", "Expired", "Disabled", "Cancelled", "AutoRenew". - :type status: str or ~azure.mgmt.billing.models.ProductStatusType - :ivar end_date: The date when the product will be renewed or canceled. - :vartype end_date: ~datetime.datetime - :param billing_frequency: The frequency at which the product will be billed. Possible values - include: "OneTime", "Monthly", "UsageBased". - :type billing_frequency: str or ~azure.mgmt.billing.models.BillingFrequency - :ivar last_charge: The last month charges. - :vartype last_charge: ~azure.mgmt.billing.models.Amount - :ivar last_charge_date: The date of the last charge. - :vartype last_charge_date: ~datetime.datetime - :ivar quantity: The quantity purchased for the product. - :vartype quantity: float - :ivar sku_id: The sku ID of the product. - :vartype sku_id: str - :ivar sku_description: The sku description of the product. - :vartype sku_description: str - :ivar tenant_id: The id of the tenant in which the product is used. - :vartype tenant_id: str - :ivar availability_id: The availability of the product. - :vartype availability_id: str - :ivar invoice_section_id: The ID of the invoice section to which the product is billed. - :vartype invoice_section_id: str - :ivar invoice_section_display_name: The name of the invoice section to which the product is - billed. - :vartype invoice_section_display_name: str - :ivar billing_profile_id: The ID of the billing profile to which the product is billed. - :vartype billing_profile_id: str - :ivar billing_profile_display_name: The name of the billing profile to which the product is - billed. - :vartype billing_profile_display_name: str - :ivar customer_id: The ID of the customer for whom the product was purchased. The field is - applicable only for Microsoft Partner Agreement billing account. - :vartype customer_id: str - :ivar customer_display_name: The name of the customer for whom the product was purchased. The - field is applicable only for Microsoft Partner Agreement billing account. - :vartype customer_display_name: str - :ivar reseller: Reseller for this product. - :vartype reseller: ~azure.mgmt.billing.models.Reseller - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'display_name': {'readonly': True}, - 'purchase_date': {'readonly': True}, - 'product_type_id': {'readonly': True}, - 'product_type': {'readonly': True}, - 'end_date': {'readonly': True}, - 'last_charge': {'readonly': True}, - 'last_charge_date': {'readonly': True}, - 'quantity': {'readonly': True}, - 'sku_id': {'readonly': True}, - 'sku_description': {'readonly': True}, - 'tenant_id': {'readonly': True}, - 'availability_id': {'readonly': True}, - 'invoice_section_id': {'readonly': True}, - 'invoice_section_display_name': {'readonly': True}, - 'billing_profile_id': {'readonly': True}, - 'billing_profile_display_name': {'readonly': True}, - 'customer_id': {'readonly': True}, - 'customer_display_name': {'readonly': True}, - 'reseller': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'auto_renew': {'key': 'properties.autoRenew', 'type': 'str'}, - 'display_name': {'key': 'properties.displayName', 'type': 'str'}, - 'purchase_date': {'key': 'properties.purchaseDate', 'type': 'iso-8601'}, - 'product_type_id': {'key': 'properties.productTypeId', 'type': 'str'}, - 'product_type': {'key': 'properties.productType', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'end_date': {'key': 'properties.endDate', 'type': 'iso-8601'}, - 'billing_frequency': {'key': 'properties.billingFrequency', 'type': 'str'}, - 'last_charge': {'key': 'properties.lastCharge', 'type': 'Amount'}, - 'last_charge_date': {'key': 'properties.lastChargeDate', 'type': 'iso-8601'}, - 'quantity': {'key': 'properties.quantity', 'type': 'float'}, - 'sku_id': {'key': 'properties.skuId', 'type': 'str'}, - 'sku_description': {'key': 'properties.skuDescription', 'type': 'str'}, - 'tenant_id': {'key': 'properties.tenantId', 'type': 'str'}, - 'availability_id': {'key': 'properties.availabilityId', 'type': 'str'}, - 'invoice_section_id': {'key': 'properties.invoiceSectionId', 'type': 'str'}, - 'invoice_section_display_name': {'key': 'properties.invoiceSectionDisplayName', 'type': 'str'}, - 'billing_profile_id': {'key': 'properties.billingProfileId', 'type': 'str'}, - 'billing_profile_display_name': {'key': 'properties.billingProfileDisplayName', 'type': 'str'}, - 'customer_id': {'key': 'properties.customerId', 'type': 'str'}, - 'customer_display_name': {'key': 'properties.customerDisplayName', 'type': 'str'}, - 'reseller': {'key': 'properties.reseller', 'type': 'Reseller'}, - } - - def __init__( - self, - **kwargs - ): - super(Product, self).__init__(**kwargs) - self.auto_renew = kwargs.get('auto_renew', None) - self.display_name = None - self.purchase_date = None - self.product_type_id = None - self.product_type = None - self.status = kwargs.get('status', None) - self.end_date = None - self.billing_frequency = kwargs.get('billing_frequency', None) - self.last_charge = None - self.last_charge_date = None - self.quantity = None - self.sku_id = None - self.sku_description = None - self.tenant_id = None - self.availability_id = None - self.invoice_section_id = None - self.invoice_section_display_name = None - self.billing_profile_id = None - self.billing_profile_display_name = None - self.customer_id = None - self.customer_display_name = None - self.reseller = None - - -class ProductsListResult(msrest.serialization.Model): - """The list of products. It contains a list of available product summaries in reverse chronological order by purchase date. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of products. - :vartype value: list[~azure.mgmt.billing.models.Product] - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - """ - - _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[Product]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ProductsListResult, self).__init__(**kwargs) - self.value = None - self.next_link = None - - -class RebillDetails(msrest.serialization.Model): - """The rebill details of an invoice. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar credit_note_document_id: The ID of credit note. - :vartype credit_note_document_id: str - :ivar invoice_document_id: The ID of invoice. - :vartype invoice_document_id: str - :ivar rebill_details: Rebill details for an invoice. - :vartype rebill_details: dict[str, ~azure.mgmt.billing.models.RebillDetails] - """ - - _validation = { - 'credit_note_document_id': {'readonly': True}, - 'invoice_document_id': {'readonly': True}, - 'rebill_details': {'readonly': True}, - } - - _attribute_map = { - 'credit_note_document_id': {'key': 'creditNoteDocumentId', 'type': 'str'}, - 'invoice_document_id': {'key': 'invoiceDocumentId', 'type': 'str'}, - 'rebill_details': {'key': 'rebillDetails', 'type': '{RebillDetails}'}, - } - - def __init__( - self, - **kwargs - ): - super(RebillDetails, self).__init__(**kwargs) - self.credit_note_document_id = None - self.invoice_document_id = None - self.rebill_details = None - - -class Reseller(msrest.serialization.Model): - """Details of the reseller. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar reseller_id: The MPN ID of the reseller. - :vartype reseller_id: str - :ivar description: The name of the reseller. - :vartype description: str - """ - - _validation = { - 'reseller_id': {'readonly': True}, - 'description': {'readonly': True}, - } - - _attribute_map = { - 'reseller_id': {'key': 'resellerId', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(Reseller, self).__init__(**kwargs) - self.reseller_id = None - self.description = None - - -class Reservation(msrest.serialization.Model): - """The definition of the reservation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The id of the reservation. - :vartype id: str - :ivar name: The name of the reservation. - :vartype name: str - :ivar type: The type of the reservation. - :vartype type: str - :ivar location: The location of the reservation. - :vartype location: str - :param sku: The sku information associated to this reservation. - :type sku: ~azure.mgmt.billing.models.ReservationSkuProperty - :param applied_scopes: The array of applied scopes of a reservation. Will be null if the - reservation is in Shared scope. - :type applied_scopes: list[str] - :ivar applied_scope_type: The applied scope type of the reservation. - :vartype applied_scope_type: str - :ivar reserved_resource_type: The reserved source type of the reservation, e.g. virtual - machine. - :vartype reserved_resource_type: str - :ivar quantity: The number of the reservation. - :vartype quantity: float - :ivar provisioning_state: The provisioning state of the reservation, e.g. Succeeded. - :vartype provisioning_state: str - :ivar expiry_date: The expiry date of the reservation. - :vartype expiry_date: str - :ivar provisioning_sub_state: The provisioning state of the reservation, e.g. Succeeded. - :vartype provisioning_sub_state: str - :ivar display_name: The display name of the reservation. - :vartype display_name: str - :ivar display_provisioning_state: The provisioning state of the reservation for display, e.g. - Succeeded. - :vartype display_provisioning_state: str - :ivar user_friendly_renew_state: The renew state of the reservation for display, e.g. On. - :vartype user_friendly_renew_state: str - :ivar user_friendly_applied_scope_type: The applied scope type of the reservation for display, - e.g. Shared. - :vartype user_friendly_applied_scope_type: str - :ivar effective_date_time: The effective date time of the reservation. - :vartype effective_date_time: str - :ivar sku_description: The sku description of the reservation. - :vartype sku_description: str - :ivar term: The term of the reservation, e.g. P1Y. - :vartype term: str - :ivar renew: The renew state of the reservation. - :vartype renew: bool - :ivar renew_source: The renew source of the reservation. - :vartype renew_source: str - :ivar utilization: Reservation utilization. - :vartype utilization: ~azure.mgmt.billing.models.ReservationPropertyUtilization - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'location': {'readonly': True}, - 'applied_scope_type': {'readonly': True}, - 'reserved_resource_type': {'readonly': True}, - 'quantity': {'readonly': True}, - 'provisioning_state': {'readonly': True}, - 'expiry_date': {'readonly': True}, - 'provisioning_sub_state': {'readonly': True}, - 'display_name': {'readonly': True}, - 'display_provisioning_state': {'readonly': True}, - 'user_friendly_renew_state': {'readonly': True}, - 'user_friendly_applied_scope_type': {'readonly': True}, - 'effective_date_time': {'readonly': True}, - 'sku_description': {'readonly': True}, - 'term': {'readonly': True}, - 'renew': {'readonly': True}, - 'renew_source': {'readonly': True}, - 'utilization': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'location': {'key': 'location', 'type': 'str'}, - 'sku': {'key': 'sku', 'type': 'ReservationSkuProperty'}, - 'applied_scopes': {'key': 'properties.appliedScopes', 'type': '[str]'}, - 'applied_scope_type': {'key': 'properties.appliedScopeType', 'type': 'str'}, - 'reserved_resource_type': {'key': 'properties.reservedResourceType', 'type': 'str'}, - 'quantity': {'key': 'properties.quantity', 'type': 'float'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, - 'expiry_date': {'key': 'properties.expiryDate', 'type': 'str'}, - 'provisioning_sub_state': {'key': 'properties.provisioningSubState', 'type': 'str'}, - 'display_name': {'key': 'properties.displayName', 'type': 'str'}, - 'display_provisioning_state': {'key': 'properties.displayProvisioningState', 'type': 'str'}, - 'user_friendly_renew_state': {'key': 'properties.userFriendlyRenewState', 'type': 'str'}, - 'user_friendly_applied_scope_type': {'key': 'properties.userFriendlyAppliedScopeType', 'type': 'str'}, - 'effective_date_time': {'key': 'properties.effectiveDateTime', 'type': 'str'}, - 'sku_description': {'key': 'properties.skuDescription', 'type': 'str'}, - 'term': {'key': 'properties.term', 'type': 'str'}, - 'renew': {'key': 'properties.renew', 'type': 'bool'}, - 'renew_source': {'key': 'properties.renewSource', 'type': 'str'}, - 'utilization': {'key': 'properties.utilization', 'type': 'ReservationPropertyUtilization'}, - } - - def __init__( - self, - **kwargs - ): - super(Reservation, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.location = None - self.sku = kwargs.get('sku', None) - self.applied_scopes = kwargs.get('applied_scopes', None) - self.applied_scope_type = None - self.reserved_resource_type = None - self.quantity = None - self.provisioning_state = None - self.expiry_date = None - self.provisioning_sub_state = None - self.display_name = None - self.display_provisioning_state = None - self.user_friendly_renew_state = None - self.user_friendly_applied_scope_type = None - self.effective_date_time = None - self.sku_description = None - self.term = None - self.renew = None - self.renew_source = None - self.utilization = None - - -class ReservationPropertyUtilization(msrest.serialization.Model): - """Reservation utilization. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar trend: The number of days trend for a reservation. - :vartype trend: str - :param aggregates: The array of aggregates of a reservation's utilization. - :type aggregates: list[~azure.mgmt.billing.models.ReservationUtilizationAggregates] - """ - - _validation = { - 'trend': {'readonly': True}, - } - - _attribute_map = { - 'trend': {'key': 'trend', 'type': 'str'}, - 'aggregates': {'key': 'aggregates', 'type': '[ReservationUtilizationAggregates]'}, - } - - def __init__( - self, - **kwargs - ): - super(ReservationPropertyUtilization, self).__init__(**kwargs) - self.trend = None - self.aggregates = kwargs.get('aggregates', None) - - -class ReservationSkuProperty(msrest.serialization.Model): - """The property of reservation sku object. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar name: The name of the reservation sku. - :vartype name: str - """ - - _validation = { - 'name': {'readonly': True}, - } - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ReservationSkuProperty, self).__init__(**kwargs) - self.name = None - - -class ReservationsListResult(msrest.serialization.Model): - """The list of reservations and summary of roll out count of reservations in each state. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of reservations. - :vartype value: list[~azure.mgmt.billing.models.Reservation] - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - :param summary: The roll out count summary of the reservations. - :type summary: ~azure.mgmt.billing.models.ReservationSummary - """ - - _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[Reservation]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - 'summary': {'key': 'summary', 'type': 'ReservationSummary'}, - } - - def __init__( - self, - **kwargs - ): - super(ReservationsListResult, self).__init__(**kwargs) - self.value = None - self.next_link = None - self.summary = kwargs.get('summary', None) - - -class ReservationSummary(msrest.serialization.Model): - """The roll up count summary of reservations in each state. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar succeeded_count: The number of reservation in Succeeded state. - :vartype succeeded_count: float - :ivar failed_count: The number of reservation in Failed state. - :vartype failed_count: float - :ivar expiring_count: The number of reservation in Expiring state. - :vartype expiring_count: float - :ivar expired_count: The number of reservation in Expired state. - :vartype expired_count: float - :ivar pending_count: The number of reservation in Pending state. - :vartype pending_count: float - :ivar cancelled_count: The number of reservation in Cancelled state. - :vartype cancelled_count: float - """ - - _validation = { - 'succeeded_count': {'readonly': True}, - 'failed_count': {'readonly': True}, - 'expiring_count': {'readonly': True}, - 'expired_count': {'readonly': True}, - 'pending_count': {'readonly': True}, - 'cancelled_count': {'readonly': True}, - } - - _attribute_map = { - 'succeeded_count': {'key': 'succeededCount', 'type': 'float'}, - 'failed_count': {'key': 'failedCount', 'type': 'float'}, - 'expiring_count': {'key': 'expiringCount', 'type': 'float'}, - 'expired_count': {'key': 'expiredCount', 'type': 'float'}, - 'pending_count': {'key': 'pendingCount', 'type': 'float'}, - 'cancelled_count': {'key': 'cancelledCount', 'type': 'float'}, - } - - def __init__( - self, - **kwargs - ): - super(ReservationSummary, self).__init__(**kwargs) - self.succeeded_count = None - self.failed_count = None - self.expiring_count = None - self.expired_count = None - self.pending_count = None - self.cancelled_count = None - - -class ReservationUtilizationAggregates(msrest.serialization.Model): - """The aggregate values of reservation utilization. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar grain: The grain of the aggregate. - :vartype grain: float - :ivar grain_unit: The grain unit of the aggregate. - :vartype grain_unit: str - :ivar value: The aggregate value. - :vartype value: float - :ivar value_unit: The aggregate value unit. - :vartype value_unit: str - """ - - _validation = { - 'grain': {'readonly': True}, - 'grain_unit': {'readonly': True}, - 'value': {'readonly': True}, - 'value_unit': {'readonly': True}, - } - - _attribute_map = { - 'grain': {'key': 'grain', 'type': 'float'}, - 'grain_unit': {'key': 'grainUnit', 'type': 'str'}, - 'value': {'key': 'value', 'type': 'float'}, - 'value_unit': {'key': 'valueUnit', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ReservationUtilizationAggregates, self).__init__(**kwargs) - self.grain = None - self.grain_unit = None - self.value = None - self.value_unit = None - - -class Transaction(Resource): - """A transaction. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource Id. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :param kind: The kind of transaction. Options are all or reservation. Possible values include: - "all", "reservation". - :type kind: str or ~azure.mgmt.billing.models.TransactionTypeKind - :ivar date: The date of transaction. - :vartype date: ~datetime.datetime - :ivar invoice: Invoice on which the transaction was billed or 'pending' if the transaction is - not billed. - :vartype invoice: str - :ivar invoice_id: The ID of the invoice on which the transaction was billed. This field is only - applicable for transactions which are billed. - :vartype invoice_id: str - :ivar order_id: The order ID of the reservation. The field is only applicable for transaction - of kind reservation. - :vartype order_id: str - :ivar order_name: The name of the reservation order. The field is only applicable for - transactions of kind reservation. - :vartype order_name: str - :ivar product_family: The family of the product for which the transaction took place. - :vartype product_family: str - :ivar product_type_id: The ID of the product type for which the transaction took place. - :vartype product_type_id: str - :ivar product_type: The type of the product for which the transaction took place. - :vartype product_type: str - :ivar product_description: The description of the product for which the transaction took place. - :vartype product_description: str - :param transaction_type: The type of transaction. Possible values include: "Purchase", "Usage - Charge". - :type transaction_type: str or ~azure.mgmt.billing.models.ReservationType - :ivar transaction_amount: The charge associated with the transaction. - :vartype transaction_amount: ~azure.mgmt.billing.models.Amount - :ivar quantity: The quantity purchased in the transaction. - :vartype quantity: int - :ivar invoice_section_id: The ID of the invoice section which will be billed for the - transaction. - :vartype invoice_section_id: str - :ivar invoice_section_display_name: The name of the invoice section which will be billed for - the transaction. - :vartype invoice_section_display_name: str - :ivar billing_profile_id: The ID of the billing profile which will be billed for the - transaction. - :vartype billing_profile_id: str - :ivar billing_profile_display_name: The name of the billing profile which will be billed for - the transaction. - :vartype billing_profile_display_name: str - :ivar customer_id: The ID of the customer for which the transaction took place. The field is - applicable only for Microsoft Partner Agreement billing account. - :vartype customer_id: str - :ivar customer_display_name: The name of the customer for which the transaction took place. The - field is applicable only for Microsoft Partner Agreement billing account. - :vartype customer_display_name: str - :ivar subscription_id: The ID of the subscription that was used for the transaction. The field - is only applicable for transaction of kind reservation. - :vartype subscription_id: str - :ivar subscription_name: The name of the subscription that was used for the transaction. The - field is only applicable for transaction of kind reservation. - :vartype subscription_name: str - :ivar azure_plan: The type of azure plan of the subscription that was used for the transaction. - :vartype azure_plan: str - :ivar azure_credit_applied: The amount of any Azure credits automatically applied to this - transaction. - :vartype azure_credit_applied: ~azure.mgmt.billing.models.Amount - :ivar billing_currency: The ISO 4217 code for the currency in which this transaction is billed. - :vartype billing_currency: str - :ivar discount: The percentage discount, if any, applied to this transaction. - :vartype discount: float - :ivar effective_price: The price of the product after applying any discounts. - :vartype effective_price: ~azure.mgmt.billing.models.Amount - :ivar exchange_rate: The exchange rate used to convert charged amount to billing currency, if - applicable. - :vartype exchange_rate: float - :ivar market_price: The retail price of the product. - :vartype market_price: ~azure.mgmt.billing.models.Amount - :ivar pricing_currency: The ISO 4217 code for the currency in which the product is priced. - :vartype pricing_currency: str - :ivar service_period_start_date: The date of the purchase of the product, or the start date of - the month in which usage started. - :vartype service_period_start_date: ~datetime.datetime - :ivar service_period_end_date: The end date of the product term, or the end date of the month - in which usage ended. - :vartype service_period_end_date: ~datetime.datetime - :ivar sub_total: The pre-tax charged amount for the transaction. - :vartype sub_total: ~azure.mgmt.billing.models.Amount - :ivar tax: The tax amount applied to the transaction. - :vartype tax: ~azure.mgmt.billing.models.Amount - :ivar unit_of_measure: The unit of measure used to bill for the product. For example, compute - services are billed per hour. - :vartype unit_of_measure: str - :ivar units: The number of units used for a given product. - :vartype units: float - :ivar unit_type: The description for the unit of measure for a given product. - :vartype unit_type: str - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'date': {'readonly': True}, - 'invoice': {'readonly': True}, - 'invoice_id': {'readonly': True}, - 'order_id': {'readonly': True}, - 'order_name': {'readonly': True}, - 'product_family': {'readonly': True}, - 'product_type_id': {'readonly': True}, - 'product_type': {'readonly': True}, - 'product_description': {'readonly': True}, - 'transaction_amount': {'readonly': True}, - 'quantity': {'readonly': True}, - 'invoice_section_id': {'readonly': True}, - 'invoice_section_display_name': {'readonly': True}, - 'billing_profile_id': {'readonly': True}, - 'billing_profile_display_name': {'readonly': True}, - 'customer_id': {'readonly': True}, - 'customer_display_name': {'readonly': True}, - 'subscription_id': {'readonly': True}, - 'subscription_name': {'readonly': True}, - 'azure_plan': {'readonly': True}, - 'azure_credit_applied': {'readonly': True}, - 'billing_currency': {'readonly': True}, - 'discount': {'readonly': True}, - 'effective_price': {'readonly': True}, - 'exchange_rate': {'readonly': True}, - 'market_price': {'readonly': True}, - 'pricing_currency': {'readonly': True}, - 'service_period_start_date': {'readonly': True}, - 'service_period_end_date': {'readonly': True}, - 'sub_total': {'readonly': True}, - 'tax': {'readonly': True}, - 'unit_of_measure': {'readonly': True}, - 'units': {'readonly': True}, - 'unit_type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'kind': {'key': 'properties.kind', 'type': 'str'}, - 'date': {'key': 'properties.date', 'type': 'iso-8601'}, - 'invoice': {'key': 'properties.invoice', 'type': 'str'}, - 'invoice_id': {'key': 'properties.invoiceId', 'type': 'str'}, - 'order_id': {'key': 'properties.orderId', 'type': 'str'}, - 'order_name': {'key': 'properties.orderName', 'type': 'str'}, - 'product_family': {'key': 'properties.productFamily', 'type': 'str'}, - 'product_type_id': {'key': 'properties.productTypeId', 'type': 'str'}, - 'product_type': {'key': 'properties.productType', 'type': 'str'}, - 'product_description': {'key': 'properties.productDescription', 'type': 'str'}, - 'transaction_type': {'key': 'properties.transactionType', 'type': 'str'}, - 'transaction_amount': {'key': 'properties.transactionAmount', 'type': 'Amount'}, - 'quantity': {'key': 'properties.quantity', 'type': 'int'}, - 'invoice_section_id': {'key': 'properties.invoiceSectionId', 'type': 'str'}, - 'invoice_section_display_name': {'key': 'properties.invoiceSectionDisplayName', 'type': 'str'}, - 'billing_profile_id': {'key': 'properties.billingProfileId', 'type': 'str'}, - 'billing_profile_display_name': {'key': 'properties.billingProfileDisplayName', 'type': 'str'}, - 'customer_id': {'key': 'properties.customerId', 'type': 'str'}, - 'customer_display_name': {'key': 'properties.customerDisplayName', 'type': 'str'}, - 'subscription_id': {'key': 'properties.subscriptionId', 'type': 'str'}, - 'subscription_name': {'key': 'properties.subscriptionName', 'type': 'str'}, - 'azure_plan': {'key': 'properties.azurePlan', 'type': 'str'}, - 'azure_credit_applied': {'key': 'properties.azureCreditApplied', 'type': 'Amount'}, - 'billing_currency': {'key': 'properties.billingCurrency', 'type': 'str'}, - 'discount': {'key': 'properties.discount', 'type': 'float'}, - 'effective_price': {'key': 'properties.effectivePrice', 'type': 'Amount'}, - 'exchange_rate': {'key': 'properties.exchangeRate', 'type': 'float'}, - 'market_price': {'key': 'properties.marketPrice', 'type': 'Amount'}, - 'pricing_currency': {'key': 'properties.pricingCurrency', 'type': 'str'}, - 'service_period_start_date': {'key': 'properties.servicePeriodStartDate', 'type': 'iso-8601'}, - 'service_period_end_date': {'key': 'properties.servicePeriodEndDate', 'type': 'iso-8601'}, - 'sub_total': {'key': 'properties.subTotal', 'type': 'Amount'}, - 'tax': {'key': 'properties.tax', 'type': 'Amount'}, - 'unit_of_measure': {'key': 'properties.unitOfMeasure', 'type': 'str'}, - 'units': {'key': 'properties.units', 'type': 'float'}, - 'unit_type': {'key': 'properties.unitType', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(Transaction, self).__init__(**kwargs) - self.kind = kwargs.get('kind', None) - self.date = None - self.invoice = None - self.invoice_id = None - self.order_id = None - self.order_name = None - self.product_family = None - self.product_type_id = None - self.product_type = None - self.product_description = None - self.transaction_type = kwargs.get('transaction_type', None) - self.transaction_amount = None - self.quantity = None - self.invoice_section_id = None - self.invoice_section_display_name = None - self.billing_profile_id = None - self.billing_profile_display_name = None - self.customer_id = None - self.customer_display_name = None - self.subscription_id = None - self.subscription_name = None - self.azure_plan = None - self.azure_credit_applied = None - self.billing_currency = None - self.discount = None - self.effective_price = None - self.exchange_rate = None - self.market_price = None - self.pricing_currency = None - self.service_period_start_date = None - self.service_period_end_date = None - self.sub_total = None - self.tax = None - self.unit_of_measure = None - self.units = None - self.unit_type = None - - -class TransactionListResult(msrest.serialization.Model): - """The list of transactions. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: The list of transactions. - :vartype value: list[~azure.mgmt.billing.models.Transaction] - :ivar next_link: The link (url) to the next page of results. - :vartype next_link: str - """ - - _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[Transaction]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(TransactionListResult, self).__init__(**kwargs) - self.value = None - self.next_link = None - - -class TransferBillingSubscriptionRequestProperties(msrest.serialization.Model): - """Request parameters to transfer billing subscription. - - All required parameters must be populated in order to send to Azure. - - :param destination_invoice_section_id: Required. The destination invoice section id. - :type destination_invoice_section_id: str - """ - - _validation = { - 'destination_invoice_section_id': {'required': True}, - } - - _attribute_map = { - 'destination_invoice_section_id': {'key': 'destinationInvoiceSectionId', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(TransferBillingSubscriptionRequestProperties, self).__init__(**kwargs) - self.destination_invoice_section_id = kwargs['destination_invoice_section_id'] - - -class TransferProductRequestProperties(msrest.serialization.Model): - """The properties of the product to initiate a transfer. - - :param destination_invoice_section_id: The destination invoice section id. - :type destination_invoice_section_id: str - """ - - _attribute_map = { - 'destination_invoice_section_id': {'key': 'destinationInvoiceSectionId', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(TransferProductRequestProperties, self).__init__(**kwargs) - self.destination_invoice_section_id = kwargs.get('destination_invoice_section_id', None) - - -class ValidateAddressResponse(msrest.serialization.Model): - """Result of the address validation. - - :param status: status of the address validation. Possible values include: "Valid", "Invalid". - :type status: str or ~azure.mgmt.billing.models.AddressValidationStatus - :param suggested_addresses: The list of suggested addresses. - :type suggested_addresses: list[~azure.mgmt.billing.models.AddressDetails] - :param validation_message: Validation error message. - :type validation_message: str - """ - - _attribute_map = { - 'status': {'key': 'status', 'type': 'str'}, - 'suggested_addresses': {'key': 'suggestedAddresses', 'type': '[AddressDetails]'}, - 'validation_message': {'key': 'validationMessage', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ValidateAddressResponse, self).__init__(**kwargs) - self.status = kwargs.get('status', None) - self.suggested_addresses = kwargs.get('suggested_addresses', None) - self.validation_message = kwargs.get('validation_message', None) - - -class ValidateProductTransferEligibilityError(msrest.serialization.Model): - """Error details of the product transfer eligibility validation. - - :param code: Error code for the product transfer validation. Possible values include: - "InvalidSource", "ProductNotActive", "InsufficientPermissionOnSource", - "InsufficientPermissionOnDestination", "DestinationBillingProfilePastDue", - "ProductTypeNotSupported", "CrossBillingAccountNotAllowed", "NotAvailableForDestinationMarket", - "OneTimePurchaseProductTransferNotAllowed". - :type code: str or ~azure.mgmt.billing.models.ProductTransferValidationErrorCode - :param message: The error message. - :type message: str - :param details: Detailed error message explaining the error. - :type details: str - """ - - _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'details': {'key': 'details', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ValidateProductTransferEligibilityError, self).__init__(**kwargs) - self.code = kwargs.get('code', None) - self.message = kwargs.get('message', None) - self.details = kwargs.get('details', None) - - -class ValidateProductTransferEligibilityResult(msrest.serialization.Model): - """Result of the product transfer eligibility validation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar is_move_eligible: Specifies whether the transfer is eligible or not. - :vartype is_move_eligible: bool - :param error_details: Validation error details. - :type error_details: ~azure.mgmt.billing.models.ValidateProductTransferEligibilityError - """ - - _validation = { - 'is_move_eligible': {'readonly': True}, - } - - _attribute_map = { - 'is_move_eligible': {'key': 'isMoveEligible', 'type': 'bool'}, - 'error_details': {'key': 'errorDetails', 'type': 'ValidateProductTransferEligibilityError'}, - } - - def __init__( - self, - **kwargs - ): - super(ValidateProductTransferEligibilityResult, self).__init__(**kwargs) - self.is_move_eligible = None - self.error_details = kwargs.get('error_details', None) - - -class ValidateSubscriptionTransferEligibilityError(msrest.serialization.Model): - """Error details of the transfer eligibility validation. - - :param code: Error code for the product transfer validation. Possible values include: - "BillingAccountInactive", "CrossBillingAccountNotAllowed", "DestinationBillingProfileInactive", - "DestinationBillingProfileNotFound", "DestinationBillingProfilePastDue", - "DestinationInvoiceSectionInactive", "DestinationInvoiceSectionNotFound", - "InsufficientPermissionOnDestination", "InsufficientPermissionOnSource", "InvalidDestination", - "InvalidSource", "MarketplaceNotEnabledOnDestination", "NotAvailableForDestinationMarket", - "ProductInactive", "ProductNotFound", "ProductTypeNotSupported", "SourceBillingProfilePastDue", - "SourceInvoiceSectionInactive", "SubscriptionNotActive", "SubscriptionTypeNotSupported". - :type code: str or ~azure.mgmt.billing.models.SubscriptionTransferValidationErrorCode - :param message: The error message. - :type message: str - :param details: Detailed error message explaining the error. - :type details: str - """ - - _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'details': {'key': 'details', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ValidateSubscriptionTransferEligibilityError, self).__init__(**kwargs) - self.code = kwargs.get('code', None) - self.message = kwargs.get('message', None) - self.details = kwargs.get('details', None) - - -class ValidateSubscriptionTransferEligibilityResult(msrest.serialization.Model): - """Result of the transfer eligibility validation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar is_move_eligible: Specifies whether the subscription is eligible to be transferred. - :vartype is_move_eligible: bool - :param error_details: Validation error details. - :type error_details: ~azure.mgmt.billing.models.ValidateSubscriptionTransferEligibilityError - """ - - _validation = { - 'is_move_eligible': {'readonly': True}, - } - - _attribute_map = { - 'is_move_eligible': {'key': 'isMoveEligible', 'type': 'bool'}, - 'error_details': {'key': 'errorDetails', 'type': 'ValidateSubscriptionTransferEligibilityError'}, - } - - def __init__( - self, - **kwargs - ): - super(ValidateSubscriptionTransferEligibilityResult, self).__init__(**kwargs) - self.is_move_eligible = None - self.error_details = kwargs.get('error_details', None) diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/models/_models_py3.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/models/_models_py3.py index 945556626fdb..0e18b58b1f8f 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/models/_models_py3.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/models/_models_py3.py @@ -1,4 +1,5 @@ # coding=utf-8 +# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. @@ -7,69 +8,70 @@ # -------------------------------------------------------------------------- import datetime -from typing import Dict, List, Optional, Union +from typing import Dict, List, Optional, TYPE_CHECKING, Union -from azure.core.exceptions import HttpResponseError -import msrest.serialization +from .. import _serialization -from ._billing_management_client_enums import * +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models -class AddressDetails(msrest.serialization.Model): +class AddressDetails(_serialization.Model): # pylint: disable=too-many-instance-attributes """Address details. All required parameters must be populated in order to send to Azure. - :param first_name: First name. - :type first_name: str - :param middle_name: Middle name. - :type middle_name: str - :param last_name: Last name. - :type last_name: str - :param company_name: Company name. - :type company_name: str - :param address_line1: Required. Address line 1. - :type address_line1: str - :param address_line2: Address line 2. - :type address_line2: str - :param address_line3: Address line 3. - :type address_line3: str - :param city: Address city. - :type city: str - :param district: Address district. - :type district: str - :param region: Address region. - :type region: str - :param country: Required. Country code uses ISO2, 2-digit format. - :type country: str - :param postal_code: Postal code. - :type postal_code: str - :param email: Email address. - :type email: str - :param phone_number: Phone number. - :type phone_number: str - """ - - _validation = { - 'address_line1': {'required': True}, - 'country': {'required': True}, - } - - _attribute_map = { - 'first_name': {'key': 'firstName', 'type': 'str'}, - 'middle_name': {'key': 'middleName', 'type': 'str'}, - 'last_name': {'key': 'lastName', 'type': 'str'}, - 'company_name': {'key': 'companyName', 'type': 'str'}, - 'address_line1': {'key': 'addressLine1', 'type': 'str'}, - 'address_line2': {'key': 'addressLine2', 'type': 'str'}, - 'address_line3': {'key': 'addressLine3', 'type': 'str'}, - 'city': {'key': 'city', 'type': 'str'}, - 'district': {'key': 'district', 'type': 'str'}, - 'region': {'key': 'region', 'type': 'str'}, - 'country': {'key': 'country', 'type': 'str'}, - 'postal_code': {'key': 'postalCode', 'type': 'str'}, - 'email': {'key': 'email', 'type': 'str'}, - 'phone_number': {'key': 'phoneNumber', 'type': 'str'}, + :ivar first_name: First name. + :vartype first_name: str + :ivar middle_name: Middle name. + :vartype middle_name: str + :ivar last_name: Last name. + :vartype last_name: str + :ivar company_name: Company name. + :vartype company_name: str + :ivar address_line1: Address line 1. Required. + :vartype address_line1: str + :ivar address_line2: Address line 2. + :vartype address_line2: str + :ivar address_line3: Address line 3. + :vartype address_line3: str + :ivar city: Address city. + :vartype city: str + :ivar district: Address district. + :vartype district: str + :ivar region: Address region. + :vartype region: str + :ivar country: Country code uses ISO2, 2-digit format. Required. + :vartype country: str + :ivar postal_code: Postal code. + :vartype postal_code: str + :ivar email: Email address. + :vartype email: str + :ivar phone_number: Phone number. + :vartype phone_number: str + """ + + _validation = { + "address_line1": {"required": True}, + "country": {"required": True}, + } + + _attribute_map = { + "first_name": {"key": "firstName", "type": "str"}, + "middle_name": {"key": "middleName", "type": "str"}, + "last_name": {"key": "lastName", "type": "str"}, + "company_name": {"key": "companyName", "type": "str"}, + "address_line1": {"key": "addressLine1", "type": "str"}, + "address_line2": {"key": "addressLine2", "type": "str"}, + "address_line3": {"key": "addressLine3", "type": "str"}, + "city": {"key": "city", "type": "str"}, + "district": {"key": "district", "type": "str"}, + "region": {"key": "region", "type": "str"}, + "country": {"key": "country", "type": "str"}, + "postal_code": {"key": "postalCode", "type": "str"}, + "email": {"key": "email", "type": "str"}, + "phone_number": {"key": "phoneNumber", "type": "str"}, } def __init__( @@ -91,7 +93,37 @@ def __init__( phone_number: Optional[str] = None, **kwargs ): - super(AddressDetails, self).__init__(**kwargs) + """ + :keyword first_name: First name. + :paramtype first_name: str + :keyword middle_name: Middle name. + :paramtype middle_name: str + :keyword last_name: Last name. + :paramtype last_name: str + :keyword company_name: Company name. + :paramtype company_name: str + :keyword address_line1: Address line 1. Required. + :paramtype address_line1: str + :keyword address_line2: Address line 2. + :paramtype address_line2: str + :keyword address_line3: Address line 3. + :paramtype address_line3: str + :keyword city: Address city. + :paramtype city: str + :keyword district: Address district. + :paramtype district: str + :keyword region: Address region. + :paramtype region: str + :keyword country: Country code uses ISO2, 2-digit format. Required. + :paramtype country: str + :keyword postal_code: Postal code. + :paramtype postal_code: str + :keyword email: Email address. + :paramtype email: str + :keyword phone_number: Phone number. + :paramtype phone_number: str + """ + super().__init__(**kwargs) self.first_name = first_name self.middle_name = middle_name self.last_name = last_name @@ -108,7 +140,7 @@ def __init__( self.phone_number = phone_number -class Resource(msrest.serialization.Model): +class Resource(_serialization.Model): """The Resource model definition. Variables are only populated by the server, and will be ignored when sending a request. @@ -122,28 +154,26 @@ class Resource(msrest.serialization.Model): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(Resource, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None -class Agreement(Resource): +class Agreement(Resource): # pylint: disable=too-many-instance-attributes """An agreement. Variables are only populated by the server, and will be ignored when sending a request. @@ -156,64 +186,70 @@ class Agreement(Resource): :vartype type: str :ivar agreement_link: The URL to download the agreement. :vartype agreement_link: str - :ivar category: The category of the agreement signed by a customer. Possible values include: - "MicrosoftCustomerAgreement", "AffiliatePurchaseTerms", "Other". + :ivar category: The category of the agreement signed by a customer. Known values are: + "MicrosoftCustomerAgreement", "AffiliatePurchaseTerms", and "Other". :vartype category: str or ~azure.mgmt.billing.models.Category - :ivar acceptance_mode: The mode of acceptance for an agreement. Possible values include: - "ClickToAccept", "ESignEmbedded", "ESignOffline". + :ivar acceptance_mode: The mode of acceptance for an agreement. Known values are: + "ClickToAccept", "ESignEmbedded", and "ESignOffline". :vartype acceptance_mode: str or ~azure.mgmt.billing.models.AcceptanceMode + :ivar billing_profile_info: The list of billing profiles associated with agreement and present + only for specific agreements. + :vartype billing_profile_info: ~azure.mgmt.billing.models.BillingProfileInfo :ivar effective_date: The date from which the agreement is effective. :vartype effective_date: ~datetime.datetime :ivar expiration_date: The date when the agreement expires. :vartype expiration_date: ~datetime.datetime - :param participants: The list of participants that participates in acceptance of an agreement. - :type participants: list[~azure.mgmt.billing.models.Participants] + :ivar participants: The list of participants that participates in acceptance of an agreement. + :vartype participants: list[~azure.mgmt.billing.models.Participants] :ivar status: The current status of the agreement. :vartype status: str """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'agreement_link': {'readonly': True}, - 'category': {'readonly': True}, - 'acceptance_mode': {'readonly': True}, - 'effective_date': {'readonly': True}, - 'expiration_date': {'readonly': True}, - 'status': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "agreement_link": {"readonly": True}, + "category": {"readonly": True}, + "acceptance_mode": {"readonly": True}, + "billing_profile_info": {"readonly": True}, + "effective_date": {"readonly": True}, + "expiration_date": {"readonly": True}, + "status": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'agreement_link': {'key': 'properties.agreementLink', 'type': 'str'}, - 'category': {'key': 'properties.category', 'type': 'str'}, - 'acceptance_mode': {'key': 'properties.acceptanceMode', 'type': 'str'}, - 'effective_date': {'key': 'properties.effectiveDate', 'type': 'iso-8601'}, - 'expiration_date': {'key': 'properties.expirationDate', 'type': 'iso-8601'}, - 'participants': {'key': 'properties.participants', 'type': '[Participants]'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - } - - def __init__( - self, - *, - participants: Optional[List["Participants"]] = None, - **kwargs - ): - super(Agreement, self).__init__(**kwargs) + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "agreement_link": {"key": "properties.agreementLink", "type": "str"}, + "category": {"key": "properties.category", "type": "str"}, + "acceptance_mode": {"key": "properties.acceptanceMode", "type": "str"}, + "billing_profile_info": {"key": "properties.billingProfileInfo", "type": "BillingProfileInfo"}, + "effective_date": {"key": "properties.effectiveDate", "type": "iso-8601"}, + "expiration_date": {"key": "properties.expirationDate", "type": "iso-8601"}, + "participants": {"key": "properties.participants", "type": "[Participants]"}, + "status": {"key": "properties.status", "type": "str"}, + } + + def __init__(self, *, participants: Optional[List["_models.Participants"]] = None, **kwargs): + """ + :keyword participants: The list of participants that participates in acceptance of an + agreement. + :paramtype participants: list[~azure.mgmt.billing.models.Participants] + """ + super().__init__(**kwargs) self.agreement_link = None self.category = None self.acceptance_mode = None + self.billing_profile_info = None self.effective_date = None self.expiration_date = None self.participants = participants self.status = None -class AgreementListResult(msrest.serialization.Model): +class AgreementListResult(_serialization.Model): """Result of listing agreements. Variables are only populated by the server, and will be ignored when sending a request. @@ -225,51 +261,48 @@ class AgreementListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[Agreement]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Agreement]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(AgreementListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class Amount(msrest.serialization.Model): +class Amount(_serialization.Model): """The amount. Variables are only populated by the server, and will be ignored when sending a request. :ivar currency: The currency for the amount value. :vartype currency: str - :param value: Amount value. - :type value: float + :ivar value: Amount value. + :vartype value: float """ _validation = { - 'currency': {'readonly': True}, + "currency": {"readonly": True}, } _attribute_map = { - 'currency': {'key': 'currency', 'type': 'str'}, - 'value': {'key': 'value', 'type': 'float'}, + "currency": {"key": "currency", "type": "str"}, + "value": {"key": "value", "type": "float"}, } - def __init__( - self, - *, - value: Optional[float] = None, - **kwargs - ): - super(Amount, self).__init__(**kwargs) + def __init__(self, *, value: Optional[float] = None, **kwargs): + """ + :keyword value: Amount value. + :paramtype value: float + """ + super().__init__(**kwargs) self.currency = None self.value = value @@ -290,59 +323,56 @@ class AvailableBalance(Resource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'amount': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "amount": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'amount': {'key': 'properties.amount', 'type': 'Amount'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "amount": {"key": "properties.amount", "type": "Amount"}, } - def __init__( - self, - **kwargs - ): - super(AvailableBalance, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.amount = None -class AzurePlan(msrest.serialization.Model): +class AzurePlan(_serialization.Model): """Details of the Azure plan. Variables are only populated by the server, and will be ignored when sending a request. - :param sku_id: The sku id. - :type sku_id: str + :ivar sku_id: The sku id. + :vartype sku_id: str :ivar sku_description: The sku description. :vartype sku_description: str """ _validation = { - 'sku_description': {'readonly': True}, + "sku_description": {"readonly": True}, } _attribute_map = { - 'sku_id': {'key': 'skuId', 'type': 'str'}, - 'sku_description': {'key': 'skuDescription', 'type': 'str'}, + "sku_id": {"key": "skuId", "type": "str"}, + "sku_description": {"key": "skuDescription", "type": "str"}, } - def __init__( - self, - *, - sku_id: Optional[str] = None, - **kwargs - ): - super(AzurePlan, self).__init__(**kwargs) + def __init__(self, *, sku_id: Optional[str] = None, **kwargs): + """ + :keyword sku_id: The sku id. + :paramtype sku_id: str + """ + super().__init__(**kwargs) self.sku_id = sku_id self.sku_description = None -class BillingAccount(Resource): +class BillingAccount(Resource): # pylint: disable=too-many-instance-attributes """A billing account. Variables are only populated by the server, and will be ignored when sending a request. @@ -353,77 +383,92 @@ class BillingAccount(Resource): :vartype name: str :ivar type: Resource type. :vartype type: str - :param display_name: The billing account name. - :type display_name: str - :param sold_to: The address of the individual or organization that is responsible for the + :ivar display_name: The billing account name. + :vartype display_name: str + :ivar sold_to: The address of the individual or organization that is responsible for the billing account. - :type sold_to: ~azure.mgmt.billing.models.AddressDetails - :ivar agreement_type: The type of agreement. Possible values include: - "MicrosoftCustomerAgreement", "EnterpriseAgreement", "MicrosoftOnlineServicesProgram", - "MicrosoftPartnerAgreement". + :vartype sold_to: ~azure.mgmt.billing.models.AddressDetails + :ivar agreement_type: The type of agreement. Known values are: "MicrosoftCustomerAgreement", + "EnterpriseAgreement", "MicrosoftOnlineServicesProgram", and "MicrosoftPartnerAgreement". :vartype agreement_type: str or ~azure.mgmt.billing.models.AgreementType - :ivar account_type: The type of customer. Possible values include: "Enterprise", "Individual", + :ivar account_type: The type of customer. Known values are: "Enterprise", "Individual", and "Partner". :vartype account_type: str or ~azure.mgmt.billing.models.AccountType - :ivar account_status: The current status of the billing account. Possible values include: - "Active", "Deleted", "Disabled", "Expired", "Transferred", "Extended", "Terminated". + :ivar account_status: The current status of the billing account. Known values are: "Active", + "Deleted", "Disabled", "Expired", "Transferred", "Extended", and "Terminated". :vartype account_status: str or ~azure.mgmt.billing.models.AccountStatus - :param billing_profiles: The billing profiles associated with the billing account. By default + :ivar billing_profiles: The billing profiles associated with the billing account. By default this is not populated, unless it's specified in $expand. - :type billing_profiles: ~azure.mgmt.billing.models.BillingProfilesOnExpand + :vartype billing_profiles: ~azure.mgmt.billing.models.BillingProfilesOnExpand :ivar enrollment_details: The details about the associated legacy enrollment. By default this is not populated, unless it's specified in $expand. :vartype enrollment_details: ~azure.mgmt.billing.models.Enrollment - :param departments: The departments associated to the enrollment. - :type departments: list[~azure.mgmt.billing.models.Department] - :param enrollment_accounts: The accounts associated to the enrollment. - :type enrollment_accounts: list[~azure.mgmt.billing.models.EnrollmentAccount] + :ivar departments: The departments associated to the enrollment. + :vartype departments: list[~azure.mgmt.billing.models.Department] + :ivar enrollment_accounts: The accounts associated to the enrollment. + :vartype enrollment_accounts: list[~azure.mgmt.billing.models.EnrollmentAccount] :ivar has_read_access: Indicates whether user has read access to the billing account. :vartype has_read_access: bool - :param notification_email_address: Notification email address, only for legacy accounts. - :type notification_email_address: str + :ivar notification_email_address: Notification email address, only for legacy accounts. + :vartype notification_email_address: str """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'agreement_type': {'readonly': True}, - 'account_type': {'readonly': True}, - 'account_status': {'readonly': True}, - 'enrollment_details': {'readonly': True}, - 'has_read_access': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "agreement_type": {"readonly": True}, + "account_type": {"readonly": True}, + "account_status": {"readonly": True}, + "enrollment_details": {"readonly": True}, + "has_read_access": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'display_name': {'key': 'properties.displayName', 'type': 'str'}, - 'sold_to': {'key': 'properties.soldTo', 'type': 'AddressDetails'}, - 'agreement_type': {'key': 'properties.agreementType', 'type': 'str'}, - 'account_type': {'key': 'properties.accountType', 'type': 'str'}, - 'account_status': {'key': 'properties.accountStatus', 'type': 'str'}, - 'billing_profiles': {'key': 'properties.billingProfiles', 'type': 'BillingProfilesOnExpand'}, - 'enrollment_details': {'key': 'properties.enrollmentDetails', 'type': 'Enrollment'}, - 'departments': {'key': 'properties.departments', 'type': '[Department]'}, - 'enrollment_accounts': {'key': 'properties.enrollmentAccounts', 'type': '[EnrollmentAccount]'}, - 'has_read_access': {'key': 'properties.hasReadAccess', 'type': 'bool'}, - 'notification_email_address': {'key': 'properties.notificationEmailAddress', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "sold_to": {"key": "properties.soldTo", "type": "AddressDetails"}, + "agreement_type": {"key": "properties.agreementType", "type": "str"}, + "account_type": {"key": "properties.accountType", "type": "str"}, + "account_status": {"key": "properties.accountStatus", "type": "str"}, + "billing_profiles": {"key": "properties.billingProfiles", "type": "BillingProfilesOnExpand"}, + "enrollment_details": {"key": "properties.enrollmentDetails", "type": "Enrollment"}, + "departments": {"key": "properties.departments", "type": "[Department]"}, + "enrollment_accounts": {"key": "properties.enrollmentAccounts", "type": "[EnrollmentAccount]"}, + "has_read_access": {"key": "properties.hasReadAccess", "type": "bool"}, + "notification_email_address": {"key": "properties.notificationEmailAddress", "type": "str"}, } def __init__( self, *, display_name: Optional[str] = None, - sold_to: Optional["AddressDetails"] = None, - billing_profiles: Optional["BillingProfilesOnExpand"] = None, - departments: Optional[List["Department"]] = None, - enrollment_accounts: Optional[List["EnrollmentAccount"]] = None, + sold_to: Optional["_models.AddressDetails"] = None, + billing_profiles: Optional["_models.BillingProfilesOnExpand"] = None, + departments: Optional[List["_models.Department"]] = None, + enrollment_accounts: Optional[List["_models.EnrollmentAccount"]] = None, notification_email_address: Optional[str] = None, **kwargs ): - super(BillingAccount, self).__init__(**kwargs) + """ + :keyword display_name: The billing account name. + :paramtype display_name: str + :keyword sold_to: The address of the individual or organization that is responsible for the + billing account. + :paramtype sold_to: ~azure.mgmt.billing.models.AddressDetails + :keyword billing_profiles: The billing profiles associated with the billing account. By default + this is not populated, unless it's specified in $expand. + :paramtype billing_profiles: ~azure.mgmt.billing.models.BillingProfilesOnExpand + :keyword departments: The departments associated to the enrollment. + :paramtype departments: list[~azure.mgmt.billing.models.Department] + :keyword enrollment_accounts: The accounts associated to the enrollment. + :paramtype enrollment_accounts: list[~azure.mgmt.billing.models.EnrollmentAccount] + :keyword notification_email_address: Notification email address, only for legacy accounts. + :paramtype notification_email_address: str + """ + super().__init__(**kwargs) self.display_name = display_name self.sold_to = sold_to self.agreement_type = None @@ -437,7 +482,7 @@ def __init__( self.notification_email_address = notification_email_address -class BillingAccountListResult(msrest.serialization.Model): +class BillingAccountListResult(_serialization.Model): """The list of billing accounts. Variables are only populated by the server, and will be ignored when sending a request. @@ -449,94 +494,107 @@ class BillingAccountListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[BillingAccount]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[BillingAccount]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(BillingAccountListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class BillingAccountUpdateRequest(msrest.serialization.Model): +class BillingAccountUpdateRequest(_serialization.Model): # pylint: disable=too-many-instance-attributes """The request properties of the billing account that can be updated. Variables are only populated by the server, and will be ignored when sending a request. - :param display_name: The billing account name. - :type display_name: str - :param sold_to: The address of the individual or organization that is responsible for the + :ivar display_name: The billing account name. + :vartype display_name: str + :ivar sold_to: The address of the individual or organization that is responsible for the billing account. - :type sold_to: ~azure.mgmt.billing.models.AddressDetails - :ivar agreement_type: The type of agreement. Possible values include: - "MicrosoftCustomerAgreement", "EnterpriseAgreement", "MicrosoftOnlineServicesProgram", - "MicrosoftPartnerAgreement". + :vartype sold_to: ~azure.mgmt.billing.models.AddressDetails + :ivar agreement_type: The type of agreement. Known values are: "MicrosoftCustomerAgreement", + "EnterpriseAgreement", "MicrosoftOnlineServicesProgram", and "MicrosoftPartnerAgreement". :vartype agreement_type: str or ~azure.mgmt.billing.models.AgreementType - :ivar account_type: The type of customer. Possible values include: "Enterprise", "Individual", + :ivar account_type: The type of customer. Known values are: "Enterprise", "Individual", and "Partner". :vartype account_type: str or ~azure.mgmt.billing.models.AccountType - :ivar account_status: The current status of the billing account. Possible values include: - "Active", "Deleted", "Disabled", "Expired", "Transferred", "Extended", "Terminated". + :ivar account_status: The current status of the billing account. Known values are: "Active", + "Deleted", "Disabled", "Expired", "Transferred", "Extended", and "Terminated". :vartype account_status: str or ~azure.mgmt.billing.models.AccountStatus - :param billing_profiles: The billing profiles associated with the billing account. By default + :ivar billing_profiles: The billing profiles associated with the billing account. By default this is not populated, unless it's specified in $expand. - :type billing_profiles: ~azure.mgmt.billing.models.BillingProfilesOnExpand + :vartype billing_profiles: ~azure.mgmt.billing.models.BillingProfilesOnExpand :ivar enrollment_details: The details about the associated legacy enrollment. By default this is not populated, unless it's specified in $expand. :vartype enrollment_details: ~azure.mgmt.billing.models.Enrollment - :param departments: The departments associated to the enrollment. - :type departments: list[~azure.mgmt.billing.models.Department] - :param enrollment_accounts: The accounts associated to the enrollment. - :type enrollment_accounts: list[~azure.mgmt.billing.models.EnrollmentAccount] + :ivar departments: The departments associated to the enrollment. + :vartype departments: list[~azure.mgmt.billing.models.Department] + :ivar enrollment_accounts: The accounts associated to the enrollment. + :vartype enrollment_accounts: list[~azure.mgmt.billing.models.EnrollmentAccount] :ivar has_read_access: Indicates whether user has read access to the billing account. :vartype has_read_access: bool - :param notification_email_address: Notification email address, only for legacy accounts. - :type notification_email_address: str + :ivar notification_email_address: Notification email address, only for legacy accounts. + :vartype notification_email_address: str """ _validation = { - 'agreement_type': {'readonly': True}, - 'account_type': {'readonly': True}, - 'account_status': {'readonly': True}, - 'enrollment_details': {'readonly': True}, - 'has_read_access': {'readonly': True}, + "agreement_type": {"readonly": True}, + "account_type": {"readonly": True}, + "account_status": {"readonly": True}, + "enrollment_details": {"readonly": True}, + "has_read_access": {"readonly": True}, } _attribute_map = { - 'display_name': {'key': 'properties.displayName', 'type': 'str'}, - 'sold_to': {'key': 'properties.soldTo', 'type': 'AddressDetails'}, - 'agreement_type': {'key': 'properties.agreementType', 'type': 'str'}, - 'account_type': {'key': 'properties.accountType', 'type': 'str'}, - 'account_status': {'key': 'properties.accountStatus', 'type': 'str'}, - 'billing_profiles': {'key': 'properties.billingProfiles', 'type': 'BillingProfilesOnExpand'}, - 'enrollment_details': {'key': 'properties.enrollmentDetails', 'type': 'Enrollment'}, - 'departments': {'key': 'properties.departments', 'type': '[Department]'}, - 'enrollment_accounts': {'key': 'properties.enrollmentAccounts', 'type': '[EnrollmentAccount]'}, - 'has_read_access': {'key': 'properties.hasReadAccess', 'type': 'bool'}, - 'notification_email_address': {'key': 'properties.notificationEmailAddress', 'type': 'str'}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "sold_to": {"key": "properties.soldTo", "type": "AddressDetails"}, + "agreement_type": {"key": "properties.agreementType", "type": "str"}, + "account_type": {"key": "properties.accountType", "type": "str"}, + "account_status": {"key": "properties.accountStatus", "type": "str"}, + "billing_profiles": {"key": "properties.billingProfiles", "type": "BillingProfilesOnExpand"}, + "enrollment_details": {"key": "properties.enrollmentDetails", "type": "Enrollment"}, + "departments": {"key": "properties.departments", "type": "[Department]"}, + "enrollment_accounts": {"key": "properties.enrollmentAccounts", "type": "[EnrollmentAccount]"}, + "has_read_access": {"key": "properties.hasReadAccess", "type": "bool"}, + "notification_email_address": {"key": "properties.notificationEmailAddress", "type": "str"}, } def __init__( self, *, display_name: Optional[str] = None, - sold_to: Optional["AddressDetails"] = None, - billing_profiles: Optional["BillingProfilesOnExpand"] = None, - departments: Optional[List["Department"]] = None, - enrollment_accounts: Optional[List["EnrollmentAccount"]] = None, + sold_to: Optional["_models.AddressDetails"] = None, + billing_profiles: Optional["_models.BillingProfilesOnExpand"] = None, + departments: Optional[List["_models.Department"]] = None, + enrollment_accounts: Optional[List["_models.EnrollmentAccount"]] = None, notification_email_address: Optional[str] = None, **kwargs ): - super(BillingAccountUpdateRequest, self).__init__(**kwargs) + """ + :keyword display_name: The billing account name. + :paramtype display_name: str + :keyword sold_to: The address of the individual or organization that is responsible for the + billing account. + :paramtype sold_to: ~azure.mgmt.billing.models.AddressDetails + :keyword billing_profiles: The billing profiles associated with the billing account. By default + this is not populated, unless it's specified in $expand. + :paramtype billing_profiles: ~azure.mgmt.billing.models.BillingProfilesOnExpand + :keyword departments: The departments associated to the enrollment. + :paramtype departments: list[~azure.mgmt.billing.models.Department] + :keyword enrollment_accounts: The accounts associated to the enrollment. + :paramtype enrollment_accounts: list[~azure.mgmt.billing.models.EnrollmentAccount] + :keyword notification_email_address: Notification email address, only for legacy accounts. + :paramtype notification_email_address: str + """ + super().__init__(**kwargs) self.display_name = display_name self.sold_to = sold_to self.agreement_type = None @@ -570,34 +628,32 @@ class BillingPeriod(Resource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'billing_period_start_date': {'readonly': True}, - 'billing_period_end_date': {'readonly': True}, - 'invoice_ids': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "billing_period_start_date": {"readonly": True}, + "billing_period_end_date": {"readonly": True}, + "invoice_ids": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'billing_period_start_date': {'key': 'properties.billingPeriodStartDate', 'type': 'date'}, - 'billing_period_end_date': {'key': 'properties.billingPeriodEndDate', 'type': 'date'}, - 'invoice_ids': {'key': 'properties.invoiceIds', 'type': '[str]'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "billing_period_start_date": {"key": "properties.billingPeriodStartDate", "type": "date"}, + "billing_period_end_date": {"key": "properties.billingPeriodEndDate", "type": "date"}, + "invoice_ids": {"key": "properties.invoiceIds", "type": "[str]"}, } - def __init__( - self, - **kwargs - ): - super(BillingPeriod, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.billing_period_start_date = None self.billing_period_end_date = None self.invoice_ids = None -class BillingPeriodsListResult(msrest.serialization.Model): +class BillingPeriodsListResult(_serialization.Model): """Result of listing billing periods. It contains a list of available billing periods in reverse chronological order. Variables are only populated by the server, and will be ignored when sending a request. @@ -609,25 +665,23 @@ class BillingPeriodsListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[BillingPeriod]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[BillingPeriod]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(BillingPeriodsListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class BillingPermissionsListResult(msrest.serialization.Model): +class BillingPermissionsListResult(_serialization.Model): """Result of list billingPermissions a caller has on a billing account. Variables are only populated by the server, and will be ignored when sending a request. @@ -639,25 +693,23 @@ class BillingPermissionsListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[BillingPermissionsProperties]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[BillingPermissionsProperties]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(BillingPermissionsListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class BillingPermissionsProperties(msrest.serialization.Model): +class BillingPermissionsProperties(_serialization.Model): """The set of allowed action and not allowed actions a caller has on a billing account. Variables are only populated by the server, and will be ignored when sending a request. @@ -669,25 +721,23 @@ class BillingPermissionsProperties(msrest.serialization.Model): """ _validation = { - 'actions': {'readonly': True}, - 'not_actions': {'readonly': True}, + "actions": {"readonly": True}, + "not_actions": {"readonly": True}, } _attribute_map = { - 'actions': {'key': 'actions', 'type': '[str]'}, - 'not_actions': {'key': 'notActions', 'type': '[str]'}, + "actions": {"key": "actions", "type": "[str]"}, + "not_actions": {"key": "notActions", "type": "[str]"}, } - def __init__( - self, - **kwargs - ): - super(BillingPermissionsProperties, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.actions = None self.not_actions = None -class BillingProfile(Resource): +class BillingProfile(Resource): # pylint: disable=too-many-instance-attributes """A billing profile. Variables are only populated by the server, and will be ignored when sending a request. @@ -698,89 +748,91 @@ class BillingProfile(Resource): :vartype name: str :ivar type: Resource type. :vartype type: str - :param display_name: The name of the billing profile. - :type display_name: str - :param po_number: The purchase order name that will appear on the invoices generated for the + :ivar display_name: The name of the billing profile. + :vartype display_name: str + :ivar po_number: The purchase order name that will appear on the invoices generated for the billing profile. - :type po_number: str + :vartype po_number: str :ivar billing_relationship_type: Identifies which services and purchases are paid by a billing - profile. Possible values include: "Direct", "IndirectCustomer", "IndirectPartner", - "CSPPartner". + profile. Known values are: "Direct", "IndirectCustomer", "IndirectPartner", and "CSPPartner". :vartype billing_relationship_type: str or ~azure.mgmt.billing.models.BillingRelationshipType - :param bill_to: Billing address. - :type bill_to: ~azure.mgmt.billing.models.AddressDetails + :ivar bill_to: Billing address. + :vartype bill_to: ~azure.mgmt.billing.models.AddressDetails :ivar indirect_relationship_info: Identifies the billing profile that is linked to another billing profile in indirect purchase motion. :vartype indirect_relationship_info: ~azure.mgmt.billing.models.IndirectRelationshipInfo - :param invoice_email_opt_in: Flag controlling whether the invoices for the billing profile are + :ivar invoice_email_opt_in: Flag controlling whether the invoices for the billing profile are sent through email. - :type invoice_email_opt_in: bool + :vartype invoice_email_opt_in: bool :ivar invoice_day: The day of the month when the invoice for the billing profile is generated. :vartype invoice_day: int :ivar currency: The currency in which the charges for the billing profile are billed. :vartype currency: str - :param enabled_azure_plans: Information about the enabled azure plans. - :type enabled_azure_plans: list[~azure.mgmt.billing.models.AzurePlan] - :param invoice_sections: The invoice sections associated to the billing profile. By default - this is not populated, unless it's specified in $expand. - :type invoice_sections: ~azure.mgmt.billing.models.InvoiceSectionsOnExpand + :ivar enabled_azure_plans: Information about the enabled azure plans. + :vartype enabled_azure_plans: list[~azure.mgmt.billing.models.AzurePlan] + :ivar invoice_sections: The invoice sections associated to the billing profile. By default this + is not populated, unless it's specified in $expand. + :vartype invoice_sections: ~azure.mgmt.billing.models.InvoiceSectionsOnExpand :ivar has_read_access: Indicates whether user has read access to the billing profile. :vartype has_read_access: bool :ivar system_id: The system generated unique identifier for a billing profile. :vartype system_id: str - :ivar status: The status of the billing profile. Possible values include: "Active", "Disabled", + :ivar status: The status of the billing profile. Known values are: "Active", "Disabled", and "Warned". :vartype status: str or ~azure.mgmt.billing.models.BillingProfileStatus - :ivar status_reason_code: Reason for the specified billing profile status. Possible values - include: "PastDue", "SpendingLimitReached", "SpendingLimitExpired". + :ivar status_reason_code: Reason for the specified billing profile status. Known values are: + "PastDue", "SpendingLimitReached", and "SpendingLimitExpired". :vartype status_reason_code: str or ~azure.mgmt.billing.models.StatusReasonCode - :ivar spending_limit: The billing profile spending limit. Possible values include: "Off", "On". + :ivar spending_limit: The billing profile spending limit. Known values are: "Off" and "On". :vartype spending_limit: str or ~azure.mgmt.billing.models.SpendingLimit :ivar target_clouds: Identifies the cloud environments that are associated with a billing profile. This is a system managed optional field and gets updated as the billing profile gets associated with accounts in various clouds. :vartype target_clouds: list[str or ~azure.mgmt.billing.models.TargetCloud] - :param tags: A set of tags. Tags of billing profiles. - :type tags: dict[str, str] - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'billing_relationship_type': {'readonly': True}, - 'indirect_relationship_info': {'readonly': True}, - 'invoice_day': {'readonly': True}, - 'currency': {'readonly': True}, - 'has_read_access': {'readonly': True}, - 'system_id': {'readonly': True}, - 'status': {'readonly': True}, - 'status_reason_code': {'readonly': True}, - 'spending_limit': {'readonly': True}, - 'target_clouds': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'display_name': {'key': 'properties.displayName', 'type': 'str'}, - 'po_number': {'key': 'properties.poNumber', 'type': 'str'}, - 'billing_relationship_type': {'key': 'properties.billingRelationshipType', 'type': 'str'}, - 'bill_to': {'key': 'properties.billTo', 'type': 'AddressDetails'}, - 'indirect_relationship_info': {'key': 'properties.indirectRelationshipInfo', 'type': 'IndirectRelationshipInfo'}, - 'invoice_email_opt_in': {'key': 'properties.invoiceEmailOptIn', 'type': 'bool'}, - 'invoice_day': {'key': 'properties.invoiceDay', 'type': 'int'}, - 'currency': {'key': 'properties.currency', 'type': 'str'}, - 'enabled_azure_plans': {'key': 'properties.enabledAzurePlans', 'type': '[AzurePlan]'}, - 'invoice_sections': {'key': 'properties.invoiceSections', 'type': 'InvoiceSectionsOnExpand'}, - 'has_read_access': {'key': 'properties.hasReadAccess', 'type': 'bool'}, - 'system_id': {'key': 'properties.systemId', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'status_reason_code': {'key': 'properties.statusReasonCode', 'type': 'str'}, - 'spending_limit': {'key': 'properties.spendingLimit', 'type': 'str'}, - 'target_clouds': {'key': 'properties.targetClouds', 'type': '[str]'}, - 'tags': {'key': 'properties.tags', 'type': '{str}'}, + :ivar tags: Tags of billing profiles. + :vartype tags: dict[str, str] + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "billing_relationship_type": {"readonly": True}, + "indirect_relationship_info": {"readonly": True}, + "invoice_day": {"readonly": True}, + "currency": {"readonly": True}, + "has_read_access": {"readonly": True}, + "system_id": {"readonly": True}, + "status": {"readonly": True}, + "status_reason_code": {"readonly": True}, + "spending_limit": {"readonly": True}, + "target_clouds": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "po_number": {"key": "properties.poNumber", "type": "str"}, + "billing_relationship_type": {"key": "properties.billingRelationshipType", "type": "str"}, + "bill_to": {"key": "properties.billTo", "type": "AddressDetails"}, + "indirect_relationship_info": { + "key": "properties.indirectRelationshipInfo", + "type": "IndirectRelationshipInfo", + }, + "invoice_email_opt_in": {"key": "properties.invoiceEmailOptIn", "type": "bool"}, + "invoice_day": {"key": "properties.invoiceDay", "type": "int"}, + "currency": {"key": "properties.currency", "type": "str"}, + "enabled_azure_plans": {"key": "properties.enabledAzurePlans", "type": "[AzurePlan]"}, + "invoice_sections": {"key": "properties.invoiceSections", "type": "InvoiceSectionsOnExpand"}, + "has_read_access": {"key": "properties.hasReadAccess", "type": "bool"}, + "system_id": {"key": "properties.systemId", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, + "status_reason_code": {"key": "properties.statusReasonCode", "type": "str"}, + "spending_limit": {"key": "properties.spendingLimit", "type": "str"}, + "target_clouds": {"key": "properties.targetClouds", "type": "[str]"}, + "tags": {"key": "properties.tags", "type": "{str}"}, } def __init__( @@ -788,14 +840,33 @@ def __init__( *, display_name: Optional[str] = None, po_number: Optional[str] = None, - bill_to: Optional["AddressDetails"] = None, + bill_to: Optional["_models.AddressDetails"] = None, invoice_email_opt_in: Optional[bool] = None, - enabled_azure_plans: Optional[List["AzurePlan"]] = None, - invoice_sections: Optional["InvoiceSectionsOnExpand"] = None, + enabled_azure_plans: Optional[List["_models.AzurePlan"]] = None, + invoice_sections: Optional["_models.InvoiceSectionsOnExpand"] = None, tags: Optional[Dict[str, str]] = None, **kwargs ): - super(BillingProfile, self).__init__(**kwargs) + """ + :keyword display_name: The name of the billing profile. + :paramtype display_name: str + :keyword po_number: The purchase order name that will appear on the invoices generated for the + billing profile. + :paramtype po_number: str + :keyword bill_to: Billing address. + :paramtype bill_to: ~azure.mgmt.billing.models.AddressDetails + :keyword invoice_email_opt_in: Flag controlling whether the invoices for the billing profile + are sent through email. + :paramtype invoice_email_opt_in: bool + :keyword enabled_azure_plans: Information about the enabled azure plans. + :paramtype enabled_azure_plans: list[~azure.mgmt.billing.models.AzurePlan] + :keyword invoice_sections: The invoice sections associated to the billing profile. By default + this is not populated, unless it's specified in $expand. + :paramtype invoice_sections: ~azure.mgmt.billing.models.InvoiceSectionsOnExpand + :keyword tags: Tags of billing profiles. + :paramtype tags: dict[str, str] + """ + super().__init__(**kwargs) self.display_name = display_name self.po_number = po_number self.billing_relationship_type = None @@ -815,30 +886,30 @@ def __init__( self.tags = tags -class BillingProfileCreationRequest(msrest.serialization.Model): +class BillingProfileCreationRequest(_serialization.Model): """The request parameters for creating a new billing profile. - :param display_name: The name of the billing profile. - :type display_name: str - :param po_number: The purchase order name that will appear on the invoices generated for the + :ivar display_name: The name of the billing profile. + :vartype display_name: str + :ivar po_number: The purchase order name that will appear on the invoices generated for the billing profile. - :type po_number: str - :param bill_to: The address of the individual or organization that is responsible for the + :vartype po_number: str + :ivar bill_to: The address of the individual or organization that is responsible for the billing profile. - :type bill_to: ~azure.mgmt.billing.models.AddressDetails - :param invoice_email_opt_in: Flag controlling whether the invoices for the billing profile are + :vartype bill_to: ~azure.mgmt.billing.models.AddressDetails + :ivar invoice_email_opt_in: Flag controlling whether the invoices for the billing profile are sent through email. - :type invoice_email_opt_in: bool - :param enabled_azure_plans: Enabled azure plans for the billing profile. - :type enabled_azure_plans: list[~azure.mgmt.billing.models.AzurePlan] + :vartype invoice_email_opt_in: bool + :ivar enabled_azure_plans: Enabled azure plans for the billing profile. + :vartype enabled_azure_plans: list[~azure.mgmt.billing.models.AzurePlan] """ _attribute_map = { - 'display_name': {'key': 'displayName', 'type': 'str'}, - 'po_number': {'key': 'poNumber', 'type': 'str'}, - 'bill_to': {'key': 'billTo', 'type': 'AddressDetails'}, - 'invoice_email_opt_in': {'key': 'invoiceEmailOptIn', 'type': 'bool'}, - 'enabled_azure_plans': {'key': 'enabledAzurePlans', 'type': '[AzurePlan]'}, + "display_name": {"key": "displayName", "type": "str"}, + "po_number": {"key": "poNumber", "type": "str"}, + "bill_to": {"key": "billTo", "type": "AddressDetails"}, + "invoice_email_opt_in": {"key": "invoiceEmailOptIn", "type": "bool"}, + "enabled_azure_plans": {"key": "enabledAzurePlans", "type": "[AzurePlan]"}, } def __init__( @@ -846,12 +917,27 @@ def __init__( *, display_name: Optional[str] = None, po_number: Optional[str] = None, - bill_to: Optional["AddressDetails"] = None, + bill_to: Optional["_models.AddressDetails"] = None, invoice_email_opt_in: Optional[bool] = None, - enabled_azure_plans: Optional[List["AzurePlan"]] = None, + enabled_azure_plans: Optional[List["_models.AzurePlan"]] = None, **kwargs ): - super(BillingProfileCreationRequest, self).__init__(**kwargs) + """ + :keyword display_name: The name of the billing profile. + :paramtype display_name: str + :keyword po_number: The purchase order name that will appear on the invoices generated for the + billing profile. + :paramtype po_number: str + :keyword bill_to: The address of the individual or organization that is responsible for the + billing profile. + :paramtype bill_to: ~azure.mgmt.billing.models.AddressDetails + :keyword invoice_email_opt_in: Flag controlling whether the invoices for the billing profile + are sent through email. + :paramtype invoice_email_opt_in: bool + :keyword enabled_azure_plans: Enabled azure plans for the billing profile. + :paramtype enabled_azure_plans: list[~azure.mgmt.billing.models.AzurePlan] + """ + super().__init__(**kwargs) self.display_name = display_name self.po_number = po_number self.bill_to = bill_to @@ -859,37 +945,81 @@ def __init__( self.enabled_azure_plans = enabled_azure_plans -class BillingProfileListResult(msrest.serialization.Model): +class BillingProfileInfo(_serialization.Model): + """Details about billing profile associated with agreement and available only for specific agreements. + + :ivar billing_profile_id: The unique identifier for the billing profile. + :vartype billing_profile_id: str + :ivar billing_profile_display_name: The name of the billing profile. + :vartype billing_profile_display_name: str + :ivar indirect_relationship_organization_name: Billing account name. This property is available + for a specific type of agreement. + :vartype indirect_relationship_organization_name: str + """ + + _attribute_map = { + "billing_profile_id": {"key": "billingProfileId", "type": "str"}, + "billing_profile_display_name": {"key": "billingProfileDisplayName", "type": "str"}, + "indirect_relationship_organization_name": {"key": "indirectRelationshipOrganizationName", "type": "str"}, + } + + def __init__( + self, + *, + billing_profile_id: Optional[str] = None, + billing_profile_display_name: Optional[str] = None, + indirect_relationship_organization_name: Optional[str] = None, + **kwargs + ): + """ + :keyword billing_profile_id: The unique identifier for the billing profile. + :paramtype billing_profile_id: str + :keyword billing_profile_display_name: The name of the billing profile. + :paramtype billing_profile_display_name: str + :keyword indirect_relationship_organization_name: Billing account name. This property is + available for a specific type of agreement. + :paramtype indirect_relationship_organization_name: str + """ + super().__init__(**kwargs) + self.billing_profile_id = billing_profile_id + self.billing_profile_display_name = billing_profile_display_name + self.indirect_relationship_organization_name = indirect_relationship_organization_name + + +class BillingProfileListResult(_serialization.Model): """The list of billing profiles. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of billing profiles. :vartype value: list[~azure.mgmt.billing.models.BillingProfile] + :ivar total_count: Total number of records. + :vartype total_count: int :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "total_count": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[BillingProfile]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[BillingProfile]"}, + "total_count": {"key": "totalCount", "type": "int"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(BillingProfileListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None + self.total_count = None self.next_link = None -class BillingProfilesOnExpand(msrest.serialization.Model): +class BillingProfilesOnExpand(_serialization.Model): """The billing profiles associated with the billing account. By default this is not populated, unless it's specified in $expand. Variables are only populated by the server, and will be ignored when sending a request. @@ -898,31 +1028,30 @@ class BillingProfilesOnExpand(msrest.serialization.Model): in this collection. The collection lists a maximum of 50 billing profiles. To get all billing profiles, use the list billing profiles API. :vartype has_more_results: bool - :param value: The billing profiles associated with the billing account. - :type value: list[~azure.mgmt.billing.models.BillingProfile] + :ivar value: The billing profiles associated with the billing account. + :vartype value: list[~azure.mgmt.billing.models.BillingProfile] """ _validation = { - 'has_more_results': {'readonly': True}, + "has_more_results": {"readonly": True}, } _attribute_map = { - 'has_more_results': {'key': 'hasMoreResults', 'type': 'bool'}, - 'value': {'key': 'value', 'type': '[BillingProfile]'}, + "has_more_results": {"key": "hasMoreResults", "type": "bool"}, + "value": {"key": "value", "type": "[BillingProfile]"}, } - def __init__( - self, - *, - value: Optional[List["BillingProfile"]] = None, - **kwargs - ): - super(BillingProfilesOnExpand, self).__init__(**kwargs) + def __init__(self, *, value: Optional[List["_models.BillingProfile"]] = None, **kwargs): + """ + :keyword value: The billing profiles associated with the billing account. + :paramtype value: list[~azure.mgmt.billing.models.BillingProfile] + """ + super().__init__(**kwargs) self.has_more_results = None self.value = value -class BillingProperty(Resource): +class BillingProperty(Resource): # pylint: disable=too-many-instance-attributes """A billing property. Variables are only populated by the server, and will be ignored when sending a request. @@ -948,19 +1077,19 @@ class BillingProperty(Resource): :ivar billing_profile_display_name: The name of the billing profile to which the subscription is billed. :vartype billing_profile_display_name: str - :ivar billing_profile_status: The status of the billing profile. Possible values include: - "Active", "Disabled", "Warned". + :ivar billing_profile_status: The status of the billing profile. Known values are: "Active", + "Disabled", and "Warned". :vartype billing_profile_status: str or ~azure.mgmt.billing.models.BillingProfileStatus :ivar billing_profile_status_reason_code: Reason for the specified billing profile status. - Possible values include: "PastDue", "SpendingLimitReached", "SpendingLimitExpired". + Known values are: "PastDue", "SpendingLimitReached", and "SpendingLimitExpired". :vartype billing_profile_status_reason_code: str or ~azure.mgmt.billing.models.BillingProfileStatusReasonCode - :ivar billing_profile_spending_limit: The billing profile spending limit. Possible values - include: "Off", "On". + :ivar billing_profile_spending_limit: The billing profile spending limit. Known values are: + "Off" and "On". :vartype billing_profile_spending_limit: str or ~azure.mgmt.billing.models.BillingProfileSpendingLimit - :param cost_center: The cost center applied to the subscription. - :type cost_center: str + :ivar cost_center: The cost center applied to the subscription. + :vartype cost_center: str :ivar invoice_section_id: The ID of the invoice section to which the subscription is billed. :vartype invoice_section_id: str :ivar invoice_section_display_name: The name of the invoice section to which the subscription @@ -979,57 +1108,59 @@ class BillingProperty(Resource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'account_admin_notification_email_address': {'readonly': True}, - 'billing_tenant_id': {'readonly': True}, - 'billing_account_id': {'readonly': True}, - 'billing_account_display_name': {'readonly': True}, - 'billing_profile_id': {'readonly': True}, - 'billing_profile_display_name': {'readonly': True}, - 'billing_profile_status': {'readonly': True}, - 'billing_profile_status_reason_code': {'readonly': True}, - 'billing_profile_spending_limit': {'readonly': True}, - 'invoice_section_id': {'readonly': True}, - 'invoice_section_display_name': {'readonly': True}, - 'is_account_admin': {'readonly': True}, - 'product_id': {'readonly': True}, - 'product_name': {'readonly': True}, - 'sku_id': {'readonly': True}, - 'sku_description': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'account_admin_notification_email_address': {'key': 'properties.accountAdminNotificationEmailAddress', 'type': 'str'}, - 'billing_tenant_id': {'key': 'properties.billingTenantId', 'type': 'str'}, - 'billing_account_id': {'key': 'properties.billingAccountId', 'type': 'str'}, - 'billing_account_display_name': {'key': 'properties.billingAccountDisplayName', 'type': 'str'}, - 'billing_profile_id': {'key': 'properties.billingProfileId', 'type': 'str'}, - 'billing_profile_display_name': {'key': 'properties.billingProfileDisplayName', 'type': 'str'}, - 'billing_profile_status': {'key': 'properties.billingProfileStatus', 'type': 'str'}, - 'billing_profile_status_reason_code': {'key': 'properties.billingProfileStatusReasonCode', 'type': 'str'}, - 'billing_profile_spending_limit': {'key': 'properties.billingProfileSpendingLimit', 'type': 'str'}, - 'cost_center': {'key': 'properties.costCenter', 'type': 'str'}, - 'invoice_section_id': {'key': 'properties.invoiceSectionId', 'type': 'str'}, - 'invoice_section_display_name': {'key': 'properties.invoiceSectionDisplayName', 'type': 'str'}, - 'is_account_admin': {'key': 'properties.isAccountAdmin', 'type': 'bool'}, - 'product_id': {'key': 'properties.productId', 'type': 'str'}, - 'product_name': {'key': 'properties.productName', 'type': 'str'}, - 'sku_id': {'key': 'properties.skuId', 'type': 'str'}, - 'sku_description': {'key': 'properties.skuDescription', 'type': 'str'}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "account_admin_notification_email_address": {"readonly": True}, + "billing_tenant_id": {"readonly": True}, + "billing_account_id": {"readonly": True}, + "billing_account_display_name": {"readonly": True}, + "billing_profile_id": {"readonly": True}, + "billing_profile_display_name": {"readonly": True}, + "billing_profile_status": {"readonly": True}, + "billing_profile_status_reason_code": {"readonly": True}, + "billing_profile_spending_limit": {"readonly": True}, + "invoice_section_id": {"readonly": True}, + "invoice_section_display_name": {"readonly": True}, + "is_account_admin": {"readonly": True}, + "product_id": {"readonly": True}, + "product_name": {"readonly": True}, + "sku_id": {"readonly": True}, + "sku_description": {"readonly": True}, } - def __init__( - self, - *, - cost_center: Optional[str] = None, - **kwargs - ): - super(BillingProperty, self).__init__(**kwargs) + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "account_admin_notification_email_address": { + "key": "properties.accountAdminNotificationEmailAddress", + "type": "str", + }, + "billing_tenant_id": {"key": "properties.billingTenantId", "type": "str"}, + "billing_account_id": {"key": "properties.billingAccountId", "type": "str"}, + "billing_account_display_name": {"key": "properties.billingAccountDisplayName", "type": "str"}, + "billing_profile_id": {"key": "properties.billingProfileId", "type": "str"}, + "billing_profile_display_name": {"key": "properties.billingProfileDisplayName", "type": "str"}, + "billing_profile_status": {"key": "properties.billingProfileStatus", "type": "str"}, + "billing_profile_status_reason_code": {"key": "properties.billingProfileStatusReasonCode", "type": "str"}, + "billing_profile_spending_limit": {"key": "properties.billingProfileSpendingLimit", "type": "str"}, + "cost_center": {"key": "properties.costCenter", "type": "str"}, + "invoice_section_id": {"key": "properties.invoiceSectionId", "type": "str"}, + "invoice_section_display_name": {"key": "properties.invoiceSectionDisplayName", "type": "str"}, + "is_account_admin": {"key": "properties.isAccountAdmin", "type": "bool"}, + "product_id": {"key": "properties.productId", "type": "str"}, + "product_name": {"key": "properties.productName", "type": "str"}, + "sku_id": {"key": "properties.skuId", "type": "str"}, + "sku_description": {"key": "properties.skuDescription", "type": "str"}, + } + + def __init__(self, *, cost_center: Optional[str] = None, **kwargs): + """ + :keyword cost_center: The cost center applied to the subscription. + :paramtype cost_center: str + """ + super().__init__(**kwargs) self.account_admin_notification_email_address = None self.billing_tenant_id = None self.billing_account_id = None @@ -1049,7 +1180,7 @@ def __init__( self.sku_description = None -class BillingRoleAssignment(Resource): +class BillingRoleAssignment(Resource): # pylint: disable=too-many-instance-attributes """The role assignment. Variables are only populated by the server, and will be ignored when sending a request. @@ -1070,45 +1201,45 @@ class BillingRoleAssignment(Resource): :ivar created_by_user_email_address: The email address of the user who created the role assignment. :vartype created_by_user_email_address: str - :param principal_id: The principal id of the user to whom the role was assigned. - :type principal_id: str - :param principal_tenant_id: The principal tenant id of the user to whom the role was assigned. - :type principal_tenant_id: str - :param role_definition_id: The ID of the role definition. - :type role_definition_id: str + :ivar principal_id: The principal id of the user to whom the role was assigned. + :vartype principal_id: str + :ivar principal_tenant_id: The principal tenant id of the user to whom the role was assigned. + :vartype principal_tenant_id: str + :ivar role_definition_id: The ID of the role definition. + :vartype role_definition_id: str :ivar scope: The scope at which the role was assigned. :vartype scope: str - :param user_authentication_type: The authentication type. - :type user_authentication_type: str - :param user_email_address: The email address of the user. - :type user_email_address: str + :ivar user_authentication_type: The authentication type. + :vartype user_authentication_type: str + :ivar user_email_address: The email address of the user. + :vartype user_email_address: str """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'created_on': {'readonly': True}, - 'created_by_principal_tenant_id': {'readonly': True}, - 'created_by_principal_id': {'readonly': True}, - 'created_by_user_email_address': {'readonly': True}, - 'scope': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "created_on": {"readonly": True}, + "created_by_principal_tenant_id": {"readonly": True}, + "created_by_principal_id": {"readonly": True}, + "created_by_user_email_address": {"readonly": True}, + "scope": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'created_on': {'key': 'properties.createdOn', 'type': 'str'}, - 'created_by_principal_tenant_id': {'key': 'properties.createdByPrincipalTenantId', 'type': 'str'}, - 'created_by_principal_id': {'key': 'properties.createdByPrincipalId', 'type': 'str'}, - 'created_by_user_email_address': {'key': 'properties.createdByUserEmailAddress', 'type': 'str'}, - 'principal_id': {'key': 'properties.principalId', 'type': 'str'}, - 'principal_tenant_id': {'key': 'properties.principalTenantId', 'type': 'str'}, - 'role_definition_id': {'key': 'properties.roleDefinitionId', 'type': 'str'}, - 'scope': {'key': 'properties.scope', 'type': 'str'}, - 'user_authentication_type': {'key': 'properties.userAuthenticationType', 'type': 'str'}, - 'user_email_address': {'key': 'properties.userEmailAddress', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "created_on": {"key": "properties.createdOn", "type": "str"}, + "created_by_principal_tenant_id": {"key": "properties.createdByPrincipalTenantId", "type": "str"}, + "created_by_principal_id": {"key": "properties.createdByPrincipalId", "type": "str"}, + "created_by_user_email_address": {"key": "properties.createdByUserEmailAddress", "type": "str"}, + "principal_id": {"key": "properties.principalId", "type": "str"}, + "principal_tenant_id": {"key": "properties.principalTenantId", "type": "str"}, + "role_definition_id": {"key": "properties.roleDefinitionId", "type": "str"}, + "scope": {"key": "properties.scope", "type": "str"}, + "user_authentication_type": {"key": "properties.userAuthenticationType", "type": "str"}, + "user_email_address": {"key": "properties.userEmailAddress", "type": "str"}, } def __init__( @@ -1121,7 +1252,20 @@ def __init__( user_email_address: Optional[str] = None, **kwargs ): - super(BillingRoleAssignment, self).__init__(**kwargs) + """ + :keyword principal_id: The principal id of the user to whom the role was assigned. + :paramtype principal_id: str + :keyword principal_tenant_id: The principal tenant id of the user to whom the role was + assigned. + :paramtype principal_tenant_id: str + :keyword role_definition_id: The ID of the role definition. + :paramtype role_definition_id: str + :keyword user_authentication_type: The authentication type. + :paramtype user_authentication_type: str + :keyword user_email_address: The email address of the user. + :paramtype user_email_address: str + """ + super().__init__(**kwargs) self.created_on = None self.created_by_principal_tenant_id = None self.created_by_principal_id = None @@ -1134,7 +1278,7 @@ def __init__( self.user_email_address = user_email_address -class BillingRoleAssignmentListResult(msrest.serialization.Model): +class BillingRoleAssignmentListResult(_serialization.Model): """The list of role assignments. Variables are only populated by the server, and will be ignored when sending a request. @@ -1146,20 +1290,18 @@ class BillingRoleAssignmentListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[BillingRoleAssignment]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[BillingRoleAssignment]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(BillingRoleAssignmentListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None @@ -1177,42 +1319,41 @@ class BillingRoleDefinition(Resource): :vartype type: str :ivar description: The role description. :vartype description: str - :param permissions: The billingPermissions the role has. - :type permissions: list[~azure.mgmt.billing.models.BillingPermissionsProperties] + :ivar permissions: The billingPermissions the role has. + :vartype permissions: list[~azure.mgmt.billing.models.BillingPermissionsProperties] :ivar role_name: The name of the role. :vartype role_name: str """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'description': {'readonly': True}, - 'role_name': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "description": {"readonly": True}, + "role_name": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'permissions': {'key': 'properties.permissions', 'type': '[BillingPermissionsProperties]'}, - 'role_name': {'key': 'properties.roleName', 'type': 'str'}, - } - - def __init__( - self, - *, - permissions: Optional[List["BillingPermissionsProperties"]] = None, - **kwargs - ): - super(BillingRoleDefinition, self).__init__(**kwargs) + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "permissions": {"key": "properties.permissions", "type": "[BillingPermissionsProperties]"}, + "role_name": {"key": "properties.roleName", "type": "str"}, + } + + def __init__(self, *, permissions: Optional[List["_models.BillingPermissionsProperties"]] = None, **kwargs): + """ + :keyword permissions: The billingPermissions the role has. + :paramtype permissions: list[~azure.mgmt.billing.models.BillingPermissionsProperties] + """ + super().__init__(**kwargs) self.description = None self.permissions = permissions self.role_name = None -class BillingRoleDefinitionListResult(msrest.serialization.Model): +class BillingRoleDefinitionListResult(_serialization.Model): """The list of role definitions. Variables are only populated by the server, and will be ignored when sending a request. @@ -1224,25 +1365,23 @@ class BillingRoleDefinitionListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[BillingRoleDefinition]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[BillingRoleDefinition]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(BillingRoleDefinitionListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class BillingSubscription(Resource): +class BillingSubscription(Resource): # pylint: disable=too-many-instance-attributes """A billing subscription. Variables are only populated by the server, and will be ignored when sending a request. @@ -1257,9 +1396,9 @@ class BillingSubscription(Resource): :vartype display_name: str :ivar subscription_id: The ID of the subscription. :vartype subscription_id: str - :param subscription_billing_status: The current billing status of the subscription. Possible - values include: "Active", "Inactive", "Abandoned", "Deleted", "Warning". - :type subscription_billing_status: str or + :ivar subscription_billing_status: The current billing status of the subscription. Known values + are: "Active", "Inactive", "Abandoned", "Deleted", and "Warning". + :vartype subscription_billing_status: str or ~azure.mgmt.billing.models.BillingSubscriptionStatusType :ivar last_month_charges: The last month charges. :vartype last_month_charges: ~azure.mgmt.billing.models.Amount @@ -1270,8 +1409,8 @@ class BillingSubscription(Resource): :ivar billing_profile_display_name: The name of the billing profile to which the subscription is billed. :vartype billing_profile_display_name: str - :param cost_center: The cost center applied to the subscription. - :type cost_center: str + :ivar cost_center: The cost center applied to the subscription. + :vartype cost_center: str :ivar customer_id: The ID of the customer for whom the subscription was created. The field is applicable only for Microsoft Partner Agreement billing account. :vartype customer_id: str @@ -1285,60 +1424,75 @@ class BillingSubscription(Resource): :vartype invoice_section_display_name: str :ivar reseller: Reseller for this subscription. :vartype reseller: ~azure.mgmt.billing.models.Reseller - :param sku_id: The sku ID of the Azure plan for the subscription. - :type sku_id: str + :ivar sku_id: The sku ID of the Azure plan for the subscription. + :vartype sku_id: str :ivar sku_description: The sku description of the Azure plan for the subscription. :vartype sku_description: str + :ivar suspension_reasons: The suspension reason for a subscription. Applies only to + subscriptions in Microsoft Online Services Program billing accounts. + :vartype suspension_reasons: list[str] """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'display_name': {'readonly': True}, - 'subscription_id': {'readonly': True}, - 'last_month_charges': {'readonly': True}, - 'month_to_date_charges': {'readonly': True}, - 'billing_profile_id': {'readonly': True}, - 'billing_profile_display_name': {'readonly': True}, - 'customer_id': {'readonly': True}, - 'customer_display_name': {'readonly': True}, - 'invoice_section_id': {'readonly': True}, - 'invoice_section_display_name': {'readonly': True}, - 'reseller': {'readonly': True}, - 'sku_description': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'display_name': {'key': 'properties.displayName', 'type': 'str'}, - 'subscription_id': {'key': 'properties.subscriptionId', 'type': 'str'}, - 'subscription_billing_status': {'key': 'properties.subscriptionBillingStatus', 'type': 'str'}, - 'last_month_charges': {'key': 'properties.lastMonthCharges', 'type': 'Amount'}, - 'month_to_date_charges': {'key': 'properties.monthToDateCharges', 'type': 'Amount'}, - 'billing_profile_id': {'key': 'properties.billingProfileId', 'type': 'str'}, - 'billing_profile_display_name': {'key': 'properties.billingProfileDisplayName', 'type': 'str'}, - 'cost_center': {'key': 'properties.costCenter', 'type': 'str'}, - 'customer_id': {'key': 'properties.customerId', 'type': 'str'}, - 'customer_display_name': {'key': 'properties.customerDisplayName', 'type': 'str'}, - 'invoice_section_id': {'key': 'properties.invoiceSectionId', 'type': 'str'}, - 'invoice_section_display_name': {'key': 'properties.invoiceSectionDisplayName', 'type': 'str'}, - 'reseller': {'key': 'properties.reseller', 'type': 'Reseller'}, - 'sku_id': {'key': 'properties.skuId', 'type': 'str'}, - 'sku_description': {'key': 'properties.skuDescription', 'type': 'str'}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "display_name": {"readonly": True}, + "subscription_id": {"readonly": True}, + "last_month_charges": {"readonly": True}, + "month_to_date_charges": {"readonly": True}, + "billing_profile_id": {"readonly": True}, + "billing_profile_display_name": {"readonly": True}, + "customer_id": {"readonly": True}, + "customer_display_name": {"readonly": True}, + "invoice_section_id": {"readonly": True}, + "invoice_section_display_name": {"readonly": True}, + "reseller": {"readonly": True}, + "sku_description": {"readonly": True}, + "suspension_reasons": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "subscription_id": {"key": "properties.subscriptionId", "type": "str"}, + "subscription_billing_status": {"key": "properties.subscriptionBillingStatus", "type": "str"}, + "last_month_charges": {"key": "properties.lastMonthCharges", "type": "Amount"}, + "month_to_date_charges": {"key": "properties.monthToDateCharges", "type": "Amount"}, + "billing_profile_id": {"key": "properties.billingProfileId", "type": "str"}, + "billing_profile_display_name": {"key": "properties.billingProfileDisplayName", "type": "str"}, + "cost_center": {"key": "properties.costCenter", "type": "str"}, + "customer_id": {"key": "properties.customerId", "type": "str"}, + "customer_display_name": {"key": "properties.customerDisplayName", "type": "str"}, + "invoice_section_id": {"key": "properties.invoiceSectionId", "type": "str"}, + "invoice_section_display_name": {"key": "properties.invoiceSectionDisplayName", "type": "str"}, + "reseller": {"key": "properties.reseller", "type": "Reseller"}, + "sku_id": {"key": "properties.skuId", "type": "str"}, + "sku_description": {"key": "properties.skuDescription", "type": "str"}, + "suspension_reasons": {"key": "properties.suspensionReasons", "type": "[str]"}, } def __init__( self, *, - subscription_billing_status: Optional[Union[str, "BillingSubscriptionStatusType"]] = None, + subscription_billing_status: Optional[Union[str, "_models.BillingSubscriptionStatusType"]] = None, cost_center: Optional[str] = None, sku_id: Optional[str] = None, **kwargs ): - super(BillingSubscription, self).__init__(**kwargs) + """ + :keyword subscription_billing_status: The current billing status of the subscription. Known + values are: "Active", "Inactive", "Abandoned", "Deleted", and "Warning". + :paramtype subscription_billing_status: str or + ~azure.mgmt.billing.models.BillingSubscriptionStatusType + :keyword cost_center: The cost center applied to the subscription. + :paramtype cost_center: str + :keyword sku_id: The sku ID of the Azure plan for the subscription. + :paramtype sku_id: str + """ + super().__init__(**kwargs) self.display_name = None self.subscription_id = None self.subscription_billing_status = subscription_billing_status @@ -1354,9 +1508,10 @@ def __init__( self.reseller = None self.sku_id = sku_id self.sku_description = None + self.suspension_reasons = None -class BillingSubscriptionsListResult(msrest.serialization.Model): +class BillingSubscriptionsListResult(_serialization.Model): """The list of billing subscriptions. Variables are only populated by the server, and will be ignored when sending a request. @@ -1370,22 +1525,20 @@ class BillingSubscriptionsListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'total_count': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "total_count": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[BillingSubscription]'}, - 'total_count': {'key': 'totalCount', 'type': 'int'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[BillingSubscription]"}, + "total_count": {"key": "totalCount", "type": "int"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(BillingSubscriptionsListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.total_count = None self.next_link = None @@ -1406,42 +1559,50 @@ class Customer(Resource): :vartype billing_profile_id: str :ivar billing_profile_display_name: The name of the billing profile for the invoice section. :vartype billing_profile_display_name: str - :param display_name: The name of the customer. - :type display_name: str - :param enabled_azure_plans: Azure plans enabled for the customer. - :type enabled_azure_plans: list[~azure.mgmt.billing.models.AzurePlan] - :param resellers: The list of resellers for which an Azure plan is enabled for the customer. - :type resellers: list[~azure.mgmt.billing.models.Reseller] + :ivar display_name: The name of the customer. + :vartype display_name: str + :ivar enabled_azure_plans: Azure plans enabled for the customer. + :vartype enabled_azure_plans: list[~azure.mgmt.billing.models.AzurePlan] + :ivar resellers: The list of resellers for which an Azure plan is enabled for the customer. + :vartype resellers: list[~azure.mgmt.billing.models.Reseller] """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'billing_profile_id': {'readonly': True}, - 'billing_profile_display_name': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "billing_profile_id": {"readonly": True}, + "billing_profile_display_name": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'billing_profile_id': {'key': 'properties.billingProfileId', 'type': 'str'}, - 'billing_profile_display_name': {'key': 'properties.billingProfileDisplayName', 'type': 'str'}, - 'display_name': {'key': 'properties.displayName', 'type': 'str'}, - 'enabled_azure_plans': {'key': 'properties.enabledAzurePlans', 'type': '[AzurePlan]'}, - 'resellers': {'key': 'properties.resellers', 'type': '[Reseller]'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "billing_profile_id": {"key": "properties.billingProfileId", "type": "str"}, + "billing_profile_display_name": {"key": "properties.billingProfileDisplayName", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "enabled_azure_plans": {"key": "properties.enabledAzurePlans", "type": "[AzurePlan]"}, + "resellers": {"key": "properties.resellers", "type": "[Reseller]"}, } def __init__( self, *, display_name: Optional[str] = None, - enabled_azure_plans: Optional[List["AzurePlan"]] = None, - resellers: Optional[List["Reseller"]] = None, + enabled_azure_plans: Optional[List["_models.AzurePlan"]] = None, + resellers: Optional[List["_models.Reseller"]] = None, **kwargs ): - super(Customer, self).__init__(**kwargs) + """ + :keyword display_name: The name of the customer. + :paramtype display_name: str + :keyword enabled_azure_plans: Azure plans enabled for the customer. + :paramtype enabled_azure_plans: list[~azure.mgmt.billing.models.AzurePlan] + :keyword resellers: The list of resellers for which an Azure plan is enabled for the customer. + :paramtype resellers: list[~azure.mgmt.billing.models.Reseller] + """ + super().__init__(**kwargs) self.billing_profile_id = None self.billing_profile_display_name = None self.display_name = display_name @@ -1449,7 +1610,7 @@ def __init__( self.resellers = resellers -class CustomerListResult(msrest.serialization.Model): +class CustomerListResult(_serialization.Model): """The list of customers. Variables are only populated by the server, and will be ignored when sending a request. @@ -1463,22 +1624,20 @@ class CustomerListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'total_count': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "total_count": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[Customer]'}, - 'total_count': {'key': 'totalCount', 'type': 'int'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Customer]"}, + "total_count": {"key": "totalCount", "type": "int"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(CustomerListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.total_count = None self.next_link = None @@ -1495,31 +1654,31 @@ class CustomerPolicy(Resource): :vartype name: str :ivar type: Resource type. :vartype type: str - :param view_charges: The policy that controls whether the users in customer's organization can - view charges at pay-as-you-go prices. Possible values include: "Allowed", "NotAllowed". - :type view_charges: str or ~azure.mgmt.billing.models.ViewCharges + :ivar view_charges: The policy that controls whether the users in customer's organization can + view charges at pay-as-you-go prices. Known values are: "Allowed" and "NotAllowed". + :vartype view_charges: str or ~azure.mgmt.billing.models.ViewCharges """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'view_charges': {'key': 'properties.viewCharges', 'type': 'str'}, - } - - def __init__( - self, - *, - view_charges: Optional[Union[str, "ViewCharges"]] = None, - **kwargs - ): - super(CustomerPolicy, self).__init__(**kwargs) + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "view_charges": {"key": "properties.viewCharges", "type": "str"}, + } + + def __init__(self, *, view_charges: Optional[Union[str, "_models.ViewCharges"]] = None, **kwargs): + """ + :keyword view_charges: The policy that controls whether the users in customer's organization + can view charges at pay-as-you-go prices. Known values are: "Allowed" and "NotAllowed". + :paramtype view_charges: str or ~azure.mgmt.billing.models.ViewCharges + """ + super().__init__(**kwargs) self.view_charges = view_charges @@ -1534,31 +1693,31 @@ class Department(Resource): :vartype name: str :ivar type: Resource type. :vartype type: str - :param department_name: The name of the department. - :type department_name: str - :param cost_center: The cost center associated with the department. - :type cost_center: str - :param status: The status of the department. - :type status: str - :param enrollment_accounts: Associated enrollment accounts. By default this is not populated, + :ivar department_name: The name of the department. + :vartype department_name: str + :ivar cost_center: The cost center associated with the department. + :vartype cost_center: str + :ivar status: The status of the department. + :vartype status: str + :ivar enrollment_accounts: Associated enrollment accounts. By default this is not populated, unless it's specified in $expand. - :type enrollment_accounts: list[~azure.mgmt.billing.models.EnrollmentAccount] + :vartype enrollment_accounts: list[~azure.mgmt.billing.models.EnrollmentAccount] """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'department_name': {'key': 'properties.departmentName', 'type': 'str'}, - 'cost_center': {'key': 'properties.costCenter', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'enrollment_accounts': {'key': 'properties.enrollmentAccounts', 'type': '[EnrollmentAccount]'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "department_name": {"key": "properties.departmentName", "type": "str"}, + "cost_center": {"key": "properties.costCenter", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, + "enrollment_accounts": {"key": "properties.enrollmentAccounts", "type": "[EnrollmentAccount]"}, } def __init__( @@ -1567,54 +1726,63 @@ def __init__( department_name: Optional[str] = None, cost_center: Optional[str] = None, status: Optional[str] = None, - enrollment_accounts: Optional[List["EnrollmentAccount"]] = None, + enrollment_accounts: Optional[List["_models.EnrollmentAccount"]] = None, **kwargs ): - super(Department, self).__init__(**kwargs) + """ + :keyword department_name: The name of the department. + :paramtype department_name: str + :keyword cost_center: The cost center associated with the department. + :paramtype cost_center: str + :keyword status: The status of the department. + :paramtype status: str + :keyword enrollment_accounts: Associated enrollment accounts. By default this is not populated, + unless it's specified in $expand. + :paramtype enrollment_accounts: list[~azure.mgmt.billing.models.EnrollmentAccount] + """ + super().__init__(**kwargs) self.department_name = department_name self.cost_center = cost_center self.status = status self.enrollment_accounts = enrollment_accounts -class Document(msrest.serialization.Model): +class Document(_serialization.Model): """The properties of a document. Variables are only populated by the server, and will be ignored when sending a request. - :ivar kind: The type of the document. Possible values include: "Invoice", "VoidNote", - "TaxReceipt", "CreditNote". + :ivar kind: The type of the document. Known values are: "Invoice", "VoidNote", "TaxReceipt", + and "CreditNote". :vartype kind: str or ~azure.mgmt.billing.models.DocumentType :ivar url: Document URL. :vartype url: str - :ivar source: The source of the document. ENF for Brazil and DRS for rest of the world. - Possible values include: "DRS", "ENF". + :ivar source: The source of the document. ENF for Brazil and DRS for rest of the world. Known + values are: "DRS" and "ENF". :vartype source: str or ~azure.mgmt.billing.models.DocumentSource """ _validation = { - 'kind': {'readonly': True}, - 'url': {'readonly': True}, - 'source': {'readonly': True}, + "kind": {"readonly": True}, + "url": {"readonly": True}, + "source": {"readonly": True}, } _attribute_map = { - 'kind': {'key': 'kind', 'type': 'str'}, - 'url': {'key': 'url', 'type': 'str'}, - 'source': {'key': 'source', 'type': 'str'}, + "kind": {"key": "kind", "type": "str"}, + "url": {"key": "url", "type": "str"}, + "source": {"key": "source", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(Document, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.kind = None self.url = None self.source = None -class DownloadUrl(msrest.serialization.Model): +class DownloadUrl(_serialization.Model): """A secure URL that can be used to download a an entity until the URL expires. Variables are only populated by the server, and will be ignored when sending a request. @@ -1626,33 +1794,31 @@ class DownloadUrl(msrest.serialization.Model): """ _validation = { - 'expiry_time': {'readonly': True}, - 'url': {'readonly': True}, + "expiry_time": {"readonly": True}, + "url": {"readonly": True}, } _attribute_map = { - 'expiry_time': {'key': 'expiryTime', 'type': 'iso-8601'}, - 'url': {'key': 'url', 'type': 'str'}, + "expiry_time": {"key": "expiryTime", "type": "iso-8601"}, + "url": {"key": "url", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(DownloadUrl, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.expiry_time = None self.url = None -class Enrollment(msrest.serialization.Model): +class Enrollment(_serialization.Model): """The properties of an enrollment. Variables are only populated by the server, and will be ignored when sending a request. - :param start_date: The start date of the enrollment. - :type start_date: ~datetime.datetime - :param end_date: The end date of the enrollment. - :type end_date: ~datetime.datetime + :ivar start_date: The start date of the enrollment. + :vartype start_date: ~datetime.datetime + :ivar end_date: The end date of the enrollment. + :vartype end_date: ~datetime.datetime :ivar currency: The billing currency for the enrollment. :vartype currency: str :ivar channel: The channel type of the enrollment. @@ -1670,35 +1836,37 @@ class Enrollment(msrest.serialization.Model): """ _validation = { - 'currency': {'readonly': True}, - 'channel': {'readonly': True}, - 'policies': {'readonly': True}, - 'language': {'readonly': True}, - 'country_code': {'readonly': True}, - 'status': {'readonly': True}, - 'billing_cycle': {'readonly': True}, + "currency": {"readonly": True}, + "channel": {"readonly": True}, + "policies": {"readonly": True}, + "language": {"readonly": True}, + "country_code": {"readonly": True}, + "status": {"readonly": True}, + "billing_cycle": {"readonly": True}, } _attribute_map = { - 'start_date': {'key': 'startDate', 'type': 'iso-8601'}, - 'end_date': {'key': 'endDate', 'type': 'iso-8601'}, - 'currency': {'key': 'currency', 'type': 'str'}, - 'channel': {'key': 'channel', 'type': 'str'}, - 'policies': {'key': 'policies', 'type': 'EnrollmentPolicies'}, - 'language': {'key': 'language', 'type': 'str'}, - 'country_code': {'key': 'countryCode', 'type': 'str'}, - 'status': {'key': 'status', 'type': 'str'}, - 'billing_cycle': {'key': 'billingCycle', 'type': 'str'}, + "start_date": {"key": "startDate", "type": "iso-8601"}, + "end_date": {"key": "endDate", "type": "iso-8601"}, + "currency": {"key": "currency", "type": "str"}, + "channel": {"key": "channel", "type": "str"}, + "policies": {"key": "policies", "type": "EnrollmentPolicies"}, + "language": {"key": "language", "type": "str"}, + "country_code": {"key": "countryCode", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "billing_cycle": {"key": "billingCycle", "type": "str"}, } def __init__( - self, - *, - start_date: Optional[datetime.datetime] = None, - end_date: Optional[datetime.datetime] = None, - **kwargs + self, *, start_date: Optional[datetime.datetime] = None, end_date: Optional[datetime.datetime] = None, **kwargs ): - super(Enrollment, self).__init__(**kwargs) + """ + :keyword start_date: The start date of the enrollment. + :paramtype start_date: ~datetime.datetime + :keyword end_date: The end date of the enrollment. + :paramtype end_date: ~datetime.datetime + """ + super().__init__(**kwargs) self.start_date = start_date self.end_date = end_date self.currency = None @@ -1710,7 +1878,7 @@ def __init__( self.billing_cycle = None -class EnrollmentAccount(Resource): +class EnrollmentAccount(Resource): # pylint: disable=too-many-instance-attributes """An enrollment account. Variables are only populated by the server, and will be ignored when sending a request. @@ -1721,43 +1889,43 @@ class EnrollmentAccount(Resource): :vartype name: str :ivar type: Resource type. :vartype type: str - :param account_name: The name of the enrollment account. - :type account_name: str - :param cost_center: The cost center associated with the enrollment account. - :type cost_center: str - :param account_owner: The owner of the enrollment account. - :type account_owner: str - :param account_owner_email: The enrollment account owner email address. - :type account_owner_email: str - :param status: The status of the enrollment account. - :type status: str - :param start_date: The start date of the enrollment account. - :type start_date: ~datetime.datetime - :param end_date: The end date of the enrollment account. - :type end_date: ~datetime.datetime - :param department: Associated department. By default this is not populated, unless it's + :ivar account_name: The name of the enrollment account. + :vartype account_name: str + :ivar cost_center: The cost center associated with the enrollment account. + :vartype cost_center: str + :ivar account_owner: The owner of the enrollment account. + :vartype account_owner: str + :ivar account_owner_email: The enrollment account owner email address. + :vartype account_owner_email: str + :ivar status: The status of the enrollment account. + :vartype status: str + :ivar start_date: The start date of the enrollment account. + :vartype start_date: ~datetime.datetime + :ivar end_date: The end date of the enrollment account. + :vartype end_date: ~datetime.datetime + :ivar department: Associated department. By default this is not populated, unless it's specified in $expand. - :type department: ~azure.mgmt.billing.models.Department + :vartype department: ~azure.mgmt.billing.models.Department """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'account_name': {'key': 'properties.accountName', 'type': 'str'}, - 'cost_center': {'key': 'properties.costCenter', 'type': 'str'}, - 'account_owner': {'key': 'properties.accountOwner', 'type': 'str'}, - 'account_owner_email': {'key': 'properties.accountOwnerEmail', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'start_date': {'key': 'properties.startDate', 'type': 'iso-8601'}, - 'end_date': {'key': 'properties.endDate', 'type': 'iso-8601'}, - 'department': {'key': 'properties.department', 'type': 'Department'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "account_name": {"key": "properties.accountName", "type": "str"}, + "cost_center": {"key": "properties.costCenter", "type": "str"}, + "account_owner": {"key": "properties.accountOwner", "type": "str"}, + "account_owner_email": {"key": "properties.accountOwnerEmail", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, + "start_date": {"key": "properties.startDate", "type": "iso-8601"}, + "end_date": {"key": "properties.endDate", "type": "iso-8601"}, + "department": {"key": "properties.department", "type": "Department"}, } def __init__( @@ -1770,10 +1938,29 @@ def __init__( status: Optional[str] = None, start_date: Optional[datetime.datetime] = None, end_date: Optional[datetime.datetime] = None, - department: Optional["Department"] = None, + department: Optional["_models.Department"] = None, **kwargs ): - super(EnrollmentAccount, self).__init__(**kwargs) + """ + :keyword account_name: The name of the enrollment account. + :paramtype account_name: str + :keyword cost_center: The cost center associated with the enrollment account. + :paramtype cost_center: str + :keyword account_owner: The owner of the enrollment account. + :paramtype account_owner: str + :keyword account_owner_email: The enrollment account owner email address. + :paramtype account_owner_email: str + :keyword status: The status of the enrollment account. + :paramtype status: str + :keyword start_date: The start date of the enrollment account. + :paramtype start_date: ~datetime.datetime + :keyword end_date: The end date of the enrollment account. + :paramtype end_date: ~datetime.datetime + :keyword department: Associated department. By default this is not populated, unless it's + specified in $expand. + :paramtype department: ~azure.mgmt.billing.models.Department + """ + super().__init__(**kwargs) self.account_name = account_name self.cost_center = cost_center self.account_owner = account_owner @@ -1784,24 +1971,24 @@ def __init__( self.department = department -class EnrollmentAccountContext(msrest.serialization.Model): +class EnrollmentAccountContext(_serialization.Model): """The enrollment account context. - :param cost_center: The cost center associated with the enrollment account. - :type cost_center: str - :param start_date: The start date of the enrollment account. - :type start_date: ~datetime.datetime - :param end_date: The end date of the enrollment account. - :type end_date: ~datetime.datetime - :param enrollment_account_name: The ID of the enrollment account. - :type enrollment_account_name: str + :ivar cost_center: The cost center associated with the enrollment account. + :vartype cost_center: str + :ivar start_date: The start date of the enrollment account. + :vartype start_date: ~datetime.datetime + :ivar end_date: The end date of the enrollment account. + :vartype end_date: ~datetime.datetime + :ivar enrollment_account_name: The ID of the enrollment account. + :vartype enrollment_account_name: str """ _attribute_map = { - 'cost_center': {'key': 'costCenter', 'type': 'str'}, - 'start_date': {'key': 'startDate', 'type': 'iso-8601'}, - 'end_date': {'key': 'endDate', 'type': 'iso-8601'}, - 'enrollment_account_name': {'key': 'enrollmentAccountName', 'type': 'str'}, + "cost_center": {"key": "costCenter", "type": "str"}, + "start_date": {"key": "startDate", "type": "iso-8601"}, + "end_date": {"key": "endDate", "type": "iso-8601"}, + "enrollment_account_name": {"key": "enrollmentAccountName", "type": "str"}, } def __init__( @@ -1813,14 +2000,24 @@ def __init__( enrollment_account_name: Optional[str] = None, **kwargs ): - super(EnrollmentAccountContext, self).__init__(**kwargs) + """ + :keyword cost_center: The cost center associated with the enrollment account. + :paramtype cost_center: str + :keyword start_date: The start date of the enrollment account. + :paramtype start_date: ~datetime.datetime + :keyword end_date: The end date of the enrollment account. + :paramtype end_date: ~datetime.datetime + :keyword enrollment_account_name: The ID of the enrollment account. + :paramtype enrollment_account_name: str + """ + super().__init__(**kwargs) self.cost_center = cost_center self.start_date = start_date self.end_date = end_date self.enrollment_account_name = enrollment_account_name -class EnrollmentAccountListResult(msrest.serialization.Model): +class EnrollmentAccountListResult(_serialization.Model): """Result of listing enrollment accounts. Variables are only populated by the server, and will be ignored when sending a request. @@ -1832,20 +2029,18 @@ class EnrollmentAccountListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[EnrollmentAccountSummary]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[EnrollmentAccountSummary]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(EnrollmentAccountListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None @@ -1866,28 +2061,26 @@ class EnrollmentAccountSummary(Resource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'principal_name': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "principal_name": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'principal_name': {'key': 'properties.principalName', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "principal_name": {"key": "properties.principalName", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(EnrollmentAccountSummary, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.principal_name = None -class EnrollmentPolicies(msrest.serialization.Model): +class EnrollmentPolicies(_serialization.Model): """The policies for Enterprise Agreement enrollments. Variables are only populated by the server, and will be ignored when sending a request. @@ -1907,31 +2100,29 @@ class EnrollmentPolicies(msrest.serialization.Model): """ _validation = { - 'account_owner_view_charges': {'readonly': True}, - 'department_admin_view_charges': {'readonly': True}, - 'marketplace_enabled': {'readonly': True}, - 'reserved_instances_enabled': {'readonly': True}, + "account_owner_view_charges": {"readonly": True}, + "department_admin_view_charges": {"readonly": True}, + "marketplace_enabled": {"readonly": True}, + "reserved_instances_enabled": {"readonly": True}, } _attribute_map = { - 'account_owner_view_charges': {'key': 'accountOwnerViewCharges', 'type': 'bool'}, - 'department_admin_view_charges': {'key': 'departmentAdminViewCharges', 'type': 'bool'}, - 'marketplace_enabled': {'key': 'marketplaceEnabled', 'type': 'bool'}, - 'reserved_instances_enabled': {'key': 'reservedInstancesEnabled', 'type': 'bool'}, + "account_owner_view_charges": {"key": "accountOwnerViewCharges", "type": "bool"}, + "department_admin_view_charges": {"key": "departmentAdminViewCharges", "type": "bool"}, + "marketplace_enabled": {"key": "marketplaceEnabled", "type": "bool"}, + "reserved_instances_enabled": {"key": "reservedInstancesEnabled", "type": "bool"}, } - def __init__( - self, - **kwargs - ): - super(EnrollmentPolicies, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.account_owner_view_charges = None self.department_admin_view_charges = None self.marketplace_enabled = None self.reserved_instances_enabled = None -class ErrorDetails(msrest.serialization.Model): +class ErrorDetails(_serialization.Model): """The details of the error. Variables are only populated by the server, and will be ignored when sending a request. @@ -1947,52 +2138,49 @@ class ErrorDetails(msrest.serialization.Model): """ _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, - 'target': {'readonly': True}, - 'details': {'readonly': True}, + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, + "details": {"readonly": True}, } _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'str'}, - 'details': {'key': 'details', 'type': '[ErrorSubDetailsItem]'}, + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorSubDetailsItem]"}, } - def __init__( - self, - **kwargs - ): - super(ErrorDetails, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.code = None self.message = None self.target = None self.details = None -class ErrorResponse(msrest.serialization.Model): +class ErrorResponse(_serialization.Model): """Error response indicates that the service is not able to process the incoming request. The reason is provided in the error message. - :param error: The details of the error. - :type error: ~azure.mgmt.billing.models.ErrorDetails + :ivar error: The details of the error. + :vartype error: ~azure.mgmt.billing.models.ErrorDetails """ _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDetails'}, + "error": {"key": "error", "type": "ErrorDetails"}, } - def __init__( - self, - *, - error: Optional["ErrorDetails"] = None, - **kwargs - ): - super(ErrorResponse, self).__init__(**kwargs) + def __init__(self, *, error: Optional["_models.ErrorDetails"] = None, **kwargs): + """ + :keyword error: The details of the error. + :paramtype error: ~azure.mgmt.billing.models.ErrorDetails + """ + super().__init__(**kwargs) self.error = error -class ErrorSubDetailsItem(msrest.serialization.Model): +class ErrorSubDetailsItem(_serialization.Model): """ErrorSubDetailsItem. Variables are only populated by the server, and will be ignored when sending a request. @@ -2006,44 +2194,42 @@ class ErrorSubDetailsItem(msrest.serialization.Model): """ _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, - 'target': {'readonly': True}, + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, } _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'str'}, + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(ErrorSubDetailsItem, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.code = None self.message = None self.target = None -class IndirectRelationshipInfo(msrest.serialization.Model): +class IndirectRelationshipInfo(_serialization.Model): """The billing profile details of the partner of the customer for an indirect motion. - :param billing_account_name: The billing account name of the partner or the customer for an + :ivar billing_account_name: The billing account name of the partner or the customer for an indirect motion. - :type billing_account_name: str - :param billing_profile_name: The billing profile name of the partner or the customer for an + :vartype billing_account_name: str + :ivar billing_profile_name: The billing profile name of the partner or the customer for an indirect motion. - :type billing_profile_name: str - :param display_name: The display name of the partner or customer for an indirect motion. - :type display_name: str + :vartype billing_profile_name: str + :ivar display_name: The display name of the partner or customer for an indirect motion. + :vartype display_name: str """ _attribute_map = { - 'billing_account_name': {'key': 'billingAccountName', 'type': 'str'}, - 'billing_profile_name': {'key': 'billingProfileName', 'type': 'str'}, - 'display_name': {'key': 'displayName', 'type': 'str'}, + "billing_account_name": {"key": "billingAccountName", "type": "str"}, + "billing_profile_name": {"key": "billingProfileName", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, } def __init__( @@ -2054,7 +2240,17 @@ def __init__( display_name: Optional[str] = None, **kwargs ): - super(IndirectRelationshipInfo, self).__init__(**kwargs) + """ + :keyword billing_account_name: The billing account name of the partner or the customer for an + indirect motion. + :paramtype billing_account_name: str + :keyword billing_profile_name: The billing profile name of the partner or the customer for an + indirect motion. + :paramtype billing_profile_name: str + :keyword display_name: The display name of the partner or customer for an indirect motion. + :paramtype display_name: str + """ + super().__init__(**kwargs) self.billing_account_name = billing_account_name self.billing_profile_name = billing_profile_name self.display_name = display_name @@ -2071,30 +2267,30 @@ class Instruction(Resource): :vartype name: str :ivar type: Resource type. :vartype type: str - :param amount: The amount budgeted for this billing instruction. - :type amount: float - :param start_date: The date this billing instruction goes into effect. - :type start_date: ~datetime.datetime - :param end_date: The date this billing instruction is no longer in effect. - :type end_date: ~datetime.datetime - :param creation_date: The date this billing instruction was created. - :type creation_date: ~datetime.datetime + :ivar amount: The amount budgeted for this billing instruction. + :vartype amount: float + :ivar start_date: The date this billing instruction goes into effect. + :vartype start_date: ~datetime.datetime + :ivar end_date: The date this billing instruction is no longer in effect. + :vartype end_date: ~datetime.datetime + :ivar creation_date: The date this billing instruction was created. + :vartype creation_date: ~datetime.datetime """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'amount': {'key': 'properties.amount', 'type': 'float'}, - 'start_date': {'key': 'properties.startDate', 'type': 'iso-8601'}, - 'end_date': {'key': 'properties.endDate', 'type': 'iso-8601'}, - 'creation_date': {'key': 'properties.creationDate', 'type': 'iso-8601'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "amount": {"key": "properties.amount", "type": "float"}, + "start_date": {"key": "properties.startDate", "type": "iso-8601"}, + "end_date": {"key": "properties.endDate", "type": "iso-8601"}, + "creation_date": {"key": "properties.creationDate", "type": "iso-8601"}, } def __init__( @@ -2106,14 +2302,24 @@ def __init__( creation_date: Optional[datetime.datetime] = None, **kwargs ): - super(Instruction, self).__init__(**kwargs) + """ + :keyword amount: The amount budgeted for this billing instruction. + :paramtype amount: float + :keyword start_date: The date this billing instruction goes into effect. + :paramtype start_date: ~datetime.datetime + :keyword end_date: The date this billing instruction is no longer in effect. + :paramtype end_date: ~datetime.datetime + :keyword creation_date: The date this billing instruction was created. + :paramtype creation_date: ~datetime.datetime + """ + super().__init__(**kwargs) self.amount = amount self.start_date = start_date self.end_date = end_date self.creation_date = creation_date -class InstructionListResult(msrest.serialization.Model): +class InstructionListResult(_serialization.Model): """The list of billing instructions used during invoice generation. Variables are only populated by the server, and will be ignored when sending a request. @@ -2125,25 +2331,23 @@ class InstructionListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[Instruction]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Instruction]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(InstructionListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class Invoice(Resource): +class Invoice(Resource): # pylint: disable=too-many-instance-attributes """An invoice. Variables are only populated by the server, and will be ignored when sending a request. @@ -2158,8 +2362,8 @@ class Invoice(Resource): :vartype due_date: ~datetime.datetime :ivar invoice_date: The date when the invoice was generated. :vartype invoice_date: ~datetime.datetime - :ivar status: The current status of the invoice. Possible values include: "Due", "OverDue", - "Paid", "Void". + :ivar status: The current status of the invoice. Known values are: "Due", "OverDue", "Paid", + and "Void". :vartype status: str or ~azure.mgmt.billing.models.InvoiceStatus :ivar amount_due: The amount due as of now. :vartype amount_due: ~azure.mgmt.billing.models.Amount @@ -2190,7 +2394,7 @@ class Invoice(Resource): :ivar invoice_period_end_date: The end date of the billing period for which the invoice is generated. :vartype invoice_period_end_date: ~datetime.datetime - :ivar invoice_type: Invoice type. Possible values include: "AzureService", "AzureMarketplace", + :ivar invoice_type: Invoice type. Known values are: "AzureService", "AzureMarketplace", and "AzureSupport". :vartype invoice_type: str or ~azure.mgmt.billing.models.InvoiceType :ivar is_monthly_invoice: Specifies if the invoice is generated as part of monthly invoicing @@ -2210,8 +2414,7 @@ class Invoice(Resource): :vartype payments: list[~azure.mgmt.billing.models.PaymentProperties] :ivar rebill_details: Rebill details for an invoice. :vartype rebill_details: dict[str, ~azure.mgmt.billing.models.RebillDetails] - :ivar document_type: The type of the document. Possible values include: "Invoice", - "CreditNote". + :ivar document_type: The type of the document. Known values are: "Invoice" and "CreditNote". :vartype document_type: str or ~azure.mgmt.billing.models.InvoiceDocumentType :ivar billed_document_id: The Id of the active invoice which is originally billed after this invoice was voided. This field is applicable to the void invoices only. @@ -2224,72 +2427,70 @@ class Invoice(Resource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'due_date': {'readonly': True}, - 'invoice_date': {'readonly': True}, - 'status': {'readonly': True}, - 'amount_due': {'readonly': True}, - 'azure_prepayment_applied': {'readonly': True}, - 'billed_amount': {'readonly': True}, - 'credit_amount': {'readonly': True}, - 'free_azure_credit_applied': {'readonly': True}, - 'sub_total': {'readonly': True}, - 'tax_amount': {'readonly': True}, - 'total_amount': {'readonly': True}, - 'invoice_period_start_date': {'readonly': True}, - 'invoice_period_end_date': {'readonly': True}, - 'invoice_type': {'readonly': True}, - 'is_monthly_invoice': {'readonly': True}, - 'billing_profile_id': {'readonly': True}, - 'billing_profile_display_name': {'readonly': True}, - 'purchase_order_number': {'readonly': True}, - 'documents': {'readonly': True}, - 'payments': {'readonly': True}, - 'rebill_details': {'readonly': True}, - 'document_type': {'readonly': True}, - 'billed_document_id': {'readonly': True}, - 'credit_for_document_id': {'readonly': True}, - 'subscription_id': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'due_date': {'key': 'properties.dueDate', 'type': 'iso-8601'}, - 'invoice_date': {'key': 'properties.invoiceDate', 'type': 'iso-8601'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'amount_due': {'key': 'properties.amountDue', 'type': 'Amount'}, - 'azure_prepayment_applied': {'key': 'properties.azurePrepaymentApplied', 'type': 'Amount'}, - 'billed_amount': {'key': 'properties.billedAmount', 'type': 'Amount'}, - 'credit_amount': {'key': 'properties.creditAmount', 'type': 'Amount'}, - 'free_azure_credit_applied': {'key': 'properties.freeAzureCreditApplied', 'type': 'Amount'}, - 'sub_total': {'key': 'properties.subTotal', 'type': 'Amount'}, - 'tax_amount': {'key': 'properties.taxAmount', 'type': 'Amount'}, - 'total_amount': {'key': 'properties.totalAmount', 'type': 'Amount'}, - 'invoice_period_start_date': {'key': 'properties.invoicePeriodStartDate', 'type': 'iso-8601'}, - 'invoice_period_end_date': {'key': 'properties.invoicePeriodEndDate', 'type': 'iso-8601'}, - 'invoice_type': {'key': 'properties.invoiceType', 'type': 'str'}, - 'is_monthly_invoice': {'key': 'properties.isMonthlyInvoice', 'type': 'bool'}, - 'billing_profile_id': {'key': 'properties.billingProfileId', 'type': 'str'}, - 'billing_profile_display_name': {'key': 'properties.billingProfileDisplayName', 'type': 'str'}, - 'purchase_order_number': {'key': 'properties.purchaseOrderNumber', 'type': 'str'}, - 'documents': {'key': 'properties.documents', 'type': '[Document]'}, - 'payments': {'key': 'properties.payments', 'type': '[PaymentProperties]'}, - 'rebill_details': {'key': 'properties.rebillDetails', 'type': '{RebillDetails}'}, - 'document_type': {'key': 'properties.documentType', 'type': 'str'}, - 'billed_document_id': {'key': 'properties.billedDocumentId', 'type': 'str'}, - 'credit_for_document_id': {'key': 'properties.creditForDocumentId', 'type': 'str'}, - 'subscription_id': {'key': 'properties.subscriptionId', 'type': 'str'}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "due_date": {"readonly": True}, + "invoice_date": {"readonly": True}, + "status": {"readonly": True}, + "amount_due": {"readonly": True}, + "azure_prepayment_applied": {"readonly": True}, + "billed_amount": {"readonly": True}, + "credit_amount": {"readonly": True}, + "free_azure_credit_applied": {"readonly": True}, + "sub_total": {"readonly": True}, + "tax_amount": {"readonly": True}, + "total_amount": {"readonly": True}, + "invoice_period_start_date": {"readonly": True}, + "invoice_period_end_date": {"readonly": True}, + "invoice_type": {"readonly": True}, + "is_monthly_invoice": {"readonly": True}, + "billing_profile_id": {"readonly": True}, + "billing_profile_display_name": {"readonly": True}, + "purchase_order_number": {"readonly": True}, + "documents": {"readonly": True}, + "payments": {"readonly": True}, + "rebill_details": {"readonly": True}, + "document_type": {"readonly": True}, + "billed_document_id": {"readonly": True}, + "credit_for_document_id": {"readonly": True}, + "subscription_id": {"readonly": True}, } - def __init__( - self, - **kwargs - ): - super(Invoice, self).__init__(**kwargs) + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "due_date": {"key": "properties.dueDate", "type": "iso-8601"}, + "invoice_date": {"key": "properties.invoiceDate", "type": "iso-8601"}, + "status": {"key": "properties.status", "type": "str"}, + "amount_due": {"key": "properties.amountDue", "type": "Amount"}, + "azure_prepayment_applied": {"key": "properties.azurePrepaymentApplied", "type": "Amount"}, + "billed_amount": {"key": "properties.billedAmount", "type": "Amount"}, + "credit_amount": {"key": "properties.creditAmount", "type": "Amount"}, + "free_azure_credit_applied": {"key": "properties.freeAzureCreditApplied", "type": "Amount"}, + "sub_total": {"key": "properties.subTotal", "type": "Amount"}, + "tax_amount": {"key": "properties.taxAmount", "type": "Amount"}, + "total_amount": {"key": "properties.totalAmount", "type": "Amount"}, + "invoice_period_start_date": {"key": "properties.invoicePeriodStartDate", "type": "iso-8601"}, + "invoice_period_end_date": {"key": "properties.invoicePeriodEndDate", "type": "iso-8601"}, + "invoice_type": {"key": "properties.invoiceType", "type": "str"}, + "is_monthly_invoice": {"key": "properties.isMonthlyInvoice", "type": "bool"}, + "billing_profile_id": {"key": "properties.billingProfileId", "type": "str"}, + "billing_profile_display_name": {"key": "properties.billingProfileDisplayName", "type": "str"}, + "purchase_order_number": {"key": "properties.purchaseOrderNumber", "type": "str"}, + "documents": {"key": "properties.documents", "type": "[Document]"}, + "payments": {"key": "properties.payments", "type": "[PaymentProperties]"}, + "rebill_details": {"key": "properties.rebillDetails", "type": "{RebillDetails}"}, + "document_type": {"key": "properties.documentType", "type": "str"}, + "billed_document_id": {"key": "properties.billedDocumentId", "type": "str"}, + "credit_for_document_id": {"key": "properties.creditForDocumentId", "type": "str"}, + "subscription_id": {"key": "properties.subscriptionId", "type": "str"}, + } + + def __init__(self, **kwargs): # pylint: disable=too-many-locals + """ """ + super().__init__(**kwargs) self.due_date = None self.invoice_date = None self.status = None @@ -2317,7 +2518,7 @@ def __init__( self.subscription_id = None -class InvoiceListResult(msrest.serialization.Model): +class InvoiceListResult(_serialization.Model): """The list of invoices. Variables are only populated by the server, and will be ignored when sending a request. @@ -2326,25 +2527,28 @@ class InvoiceListResult(msrest.serialization.Model): :vartype value: list[~azure.mgmt.billing.models.Invoice] :ivar next_link: The link (url) to the next page of results. :vartype next_link: str + :ivar total_count: Total number of records. + :vartype total_count: int """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, + "total_count": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[Invoice]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Invoice]"}, + "next_link": {"key": "nextLink", "type": "str"}, + "total_count": {"key": "totalCount", "type": "int"}, } - def __init__( - self, - **kwargs - ): - super(InvoiceListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None + self.total_count = None class InvoiceSection(Resource): @@ -2358,39 +2562,44 @@ class InvoiceSection(Resource): :vartype name: str :ivar type: Resource type. :vartype type: str - :param display_name: The name of the invoice section. - :type display_name: str - :param labels: Dictionary of metadata associated with the invoice section. - :type labels: dict[str, str] - :ivar state: Identifies the state of an invoice section. Possible values include: "Active", + :ivar display_name: The name of the invoice section. + :vartype display_name: str + :ivar labels: Dictionary of metadata associated with the invoice section. + :vartype labels: dict[str, str] + :ivar state: Identifies the state of an invoice section. Known values are: "Active" and "Restricted". :vartype state: str or ~azure.mgmt.billing.models.InvoiceSectionState :ivar system_id: The system generated unique identifier for an invoice section. :vartype system_id: str + :ivar tags: Dictionary of metadata associated with the invoice section. Maximum key/value + length supported of 256 characters. Keys/value should not empty value nor null. Keys can not + contain < > % & ? /. + :vartype tags: dict[str, str] :ivar target_cloud: Identifies the cloud environments that are associated with an invoice section. This is a system managed optional field and gets updated as the invoice section gets - associated with accounts in various clouds. Possible values include: "USGov", "USNat", "USSec". + associated with accounts in various clouds. Known values are: "USGov", "USNat", and "USSec". :vartype target_cloud: str or ~azure.mgmt.billing.models.TargetCloud """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'state': {'readonly': True}, - 'system_id': {'readonly': True}, - 'target_cloud': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "state": {"readonly": True}, + "system_id": {"readonly": True}, + "target_cloud": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'display_name': {'key': 'properties.displayName', 'type': 'str'}, - 'labels': {'key': 'properties.labels', 'type': '{str}'}, - 'state': {'key': 'properties.state', 'type': 'str'}, - 'system_id': {'key': 'properties.systemId', 'type': 'str'}, - 'target_cloud': {'key': 'properties.targetCloud', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "labels": {"key": "properties.labels", "type": "{str}"}, + "state": {"key": "properties.state", "type": "str"}, + "system_id": {"key": "properties.systemId", "type": "str"}, + "tags": {"key": "properties.tags", "type": "{str}"}, + "target_cloud": {"key": "properties.targetCloud", "type": "str"}, } def __init__( @@ -2398,38 +2607,49 @@ def __init__( *, display_name: Optional[str] = None, labels: Optional[Dict[str, str]] = None, + tags: Optional[Dict[str, str]] = None, **kwargs ): - super(InvoiceSection, self).__init__(**kwargs) + """ + :keyword display_name: The name of the invoice section. + :paramtype display_name: str + :keyword labels: Dictionary of metadata associated with the invoice section. + :paramtype labels: dict[str, str] + :keyword tags: Dictionary of metadata associated with the invoice section. Maximum key/value + length supported of 256 characters. Keys/value should not empty value nor null. Keys can not + contain < > % & ? /. + :paramtype tags: dict[str, str] + """ + super().__init__(**kwargs) self.display_name = display_name self.labels = labels self.state = None self.system_id = None + self.tags = tags self.target_cloud = None -class InvoiceSectionCreationRequest(msrest.serialization.Model): +class InvoiceSectionCreationRequest(_serialization.Model): """The properties of the invoice section. - :param display_name: The name of the invoice section. - :type display_name: str + :ivar display_name: The name of the invoice section. + :vartype display_name: str """ _attribute_map = { - 'display_name': {'key': 'displayName', 'type': 'str'}, + "display_name": {"key": "displayName", "type": "str"}, } - def __init__( - self, - *, - display_name: Optional[str] = None, - **kwargs - ): - super(InvoiceSectionCreationRequest, self).__init__(**kwargs) + def __init__(self, *, display_name: Optional[str] = None, **kwargs): + """ + :keyword display_name: The name of the invoice section. + :paramtype display_name: str + """ + super().__init__(**kwargs) self.display_name = display_name -class InvoiceSectionListResult(msrest.serialization.Model): +class InvoiceSectionListResult(_serialization.Model): """The list of invoice sections. Variables are only populated by the server, and will be ignored when sending a request. @@ -2443,59 +2663,56 @@ class InvoiceSectionListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'total_count': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "total_count": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[InvoiceSection]'}, - 'total_count': {'key': 'totalCount', 'type': 'int'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[InvoiceSection]"}, + "total_count": {"key": "totalCount", "type": "int"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(InvoiceSectionListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.total_count = None self.next_link = None -class InvoiceSectionListWithCreateSubPermissionResult(msrest.serialization.Model): +class InvoiceSectionListWithCreateSubPermissionResult(_serialization.Model): """The list of invoice section properties with create subscription permission. Variables are only populated by the server, and will be ignored when sending a request. - :param value: The list of invoice section properties with create subscription permission. - :type value: list[~azure.mgmt.billing.models.InvoiceSectionWithCreateSubPermission] + :ivar value: The list of invoice section properties with create subscription permission. + :vartype value: list[~azure.mgmt.billing.models.InvoiceSectionWithCreateSubPermission] :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { - 'next_link': {'readonly': True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[InvoiceSectionWithCreateSubPermission]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[InvoiceSectionWithCreateSubPermission]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - *, - value: Optional[List["InvoiceSectionWithCreateSubPermission"]] = None, - **kwargs - ): - super(InvoiceSectionListWithCreateSubPermissionResult, self).__init__(**kwargs) + def __init__(self, *, value: Optional[List["_models.InvoiceSectionWithCreateSubPermission"]] = None, **kwargs): + """ + :keyword value: The list of invoice section properties with create subscription permission. + :paramtype value: list[~azure.mgmt.billing.models.InvoiceSectionWithCreateSubPermission] + """ + super().__init__(**kwargs) self.value = value self.next_link = None -class InvoiceSectionsOnExpand(msrest.serialization.Model): +class InvoiceSectionsOnExpand(_serialization.Model): """The invoice sections associated to the billing profile. By default this is not populated, unless it's specified in $expand. Variables are only populated by the server, and will be ignored when sending a request. @@ -2504,31 +2721,30 @@ class InvoiceSectionsOnExpand(msrest.serialization.Model): in this collection. The collection lists a maximum of 50 invoice sections. To get all invoice sections, use the list invoice sections API. :vartype has_more_results: bool - :param value: The invoice sections associated to the billing profile. - :type value: list[~azure.mgmt.billing.models.InvoiceSection] + :ivar value: The invoice sections associated to the billing profile. + :vartype value: list[~azure.mgmt.billing.models.InvoiceSection] """ _validation = { - 'has_more_results': {'readonly': True}, + "has_more_results": {"readonly": True}, } _attribute_map = { - 'has_more_results': {'key': 'hasMoreResults', 'type': 'bool'}, - 'value': {'key': 'value', 'type': '[InvoiceSection]'}, + "has_more_results": {"key": "hasMoreResults", "type": "bool"}, + "value": {"key": "value", "type": "[InvoiceSection]"}, } - def __init__( - self, - *, - value: Optional[List["InvoiceSection"]] = None, - **kwargs - ): - super(InvoiceSectionsOnExpand, self).__init__(**kwargs) + def __init__(self, *, value: Optional[List["_models.InvoiceSection"]] = None, **kwargs): + """ + :keyword value: The invoice sections associated to the billing profile. + :paramtype value: list[~azure.mgmt.billing.models.InvoiceSection] + """ + super().__init__(**kwargs) self.has_more_results = None self.value = value -class InvoiceSectionWithCreateSubPermission(msrest.serialization.Model): +class InvoiceSectionWithCreateSubPermission(_serialization.Model): """Invoice section properties with create subscription permission. Variables are only populated by the server, and will be ignored when sending a request. @@ -2543,55 +2759,54 @@ class InvoiceSectionWithCreateSubPermission(msrest.serialization.Model): :vartype billing_profile_id: str :ivar billing_profile_display_name: The name of the billing profile for the invoice section. :vartype billing_profile_display_name: str - :ivar billing_profile_status: The status of the billing profile. Possible values include: - "Active", "Disabled", "Warned". + :ivar billing_profile_status: The status of the billing profile. Known values are: "Active", + "Disabled", and "Warned". :vartype billing_profile_status: str or ~azure.mgmt.billing.models.BillingProfileStatus :ivar billing_profile_status_reason_code: Reason for the specified billing profile status. - Possible values include: "PastDue", "SpendingLimitReached", "SpendingLimitExpired". + Known values are: "PastDue", "SpendingLimitReached", and "SpendingLimitExpired". :vartype billing_profile_status_reason_code: str or ~azure.mgmt.billing.models.StatusReasonCodeForBillingProfile - :ivar billing_profile_spending_limit: The billing profile spending limit. Possible values - include: "Off", "On". + :ivar billing_profile_spending_limit: The billing profile spending limit. Known values are: + "Off" and "On". :vartype billing_profile_spending_limit: str or ~azure.mgmt.billing.models.SpendingLimitForBillingProfile :ivar billing_profile_system_id: The system generated unique identifier for a billing profile. :vartype billing_profile_system_id: str - :param enabled_azure_plans: Enabled azure plans for the associated billing profile. - :type enabled_azure_plans: list[~azure.mgmt.billing.models.AzurePlan] + :ivar enabled_azure_plans: Enabled azure plans for the associated billing profile. + :vartype enabled_azure_plans: list[~azure.mgmt.billing.models.AzurePlan] """ _validation = { - 'invoice_section_id': {'readonly': True}, - 'invoice_section_display_name': {'readonly': True}, - 'invoice_section_system_id': {'readonly': True}, - 'billing_profile_id': {'readonly': True}, - 'billing_profile_display_name': {'readonly': True}, - 'billing_profile_status': {'readonly': True}, - 'billing_profile_status_reason_code': {'readonly': True}, - 'billing_profile_spending_limit': {'readonly': True}, - 'billing_profile_system_id': {'readonly': True}, + "invoice_section_id": {"readonly": True}, + "invoice_section_display_name": {"readonly": True}, + "invoice_section_system_id": {"readonly": True}, + "billing_profile_id": {"readonly": True}, + "billing_profile_display_name": {"readonly": True}, + "billing_profile_status": {"readonly": True}, + "billing_profile_status_reason_code": {"readonly": True}, + "billing_profile_spending_limit": {"readonly": True}, + "billing_profile_system_id": {"readonly": True}, } _attribute_map = { - 'invoice_section_id': {'key': 'invoiceSectionId', 'type': 'str'}, - 'invoice_section_display_name': {'key': 'invoiceSectionDisplayName', 'type': 'str'}, - 'invoice_section_system_id': {'key': 'invoiceSectionSystemId', 'type': 'str'}, - 'billing_profile_id': {'key': 'billingProfileId', 'type': 'str'}, - 'billing_profile_display_name': {'key': 'billingProfileDisplayName', 'type': 'str'}, - 'billing_profile_status': {'key': 'billingProfileStatus', 'type': 'str'}, - 'billing_profile_status_reason_code': {'key': 'billingProfileStatusReasonCode', 'type': 'str'}, - 'billing_profile_spending_limit': {'key': 'billingProfileSpendingLimit', 'type': 'str'}, - 'billing_profile_system_id': {'key': 'billingProfileSystemId', 'type': 'str'}, - 'enabled_azure_plans': {'key': 'enabledAzurePlans', 'type': '[AzurePlan]'}, - } - - def __init__( - self, - *, - enabled_azure_plans: Optional[List["AzurePlan"]] = None, - **kwargs - ): - super(InvoiceSectionWithCreateSubPermission, self).__init__(**kwargs) + "invoice_section_id": {"key": "invoiceSectionId", "type": "str"}, + "invoice_section_display_name": {"key": "invoiceSectionDisplayName", "type": "str"}, + "invoice_section_system_id": {"key": "invoiceSectionSystemId", "type": "str"}, + "billing_profile_id": {"key": "billingProfileId", "type": "str"}, + "billing_profile_display_name": {"key": "billingProfileDisplayName", "type": "str"}, + "billing_profile_status": {"key": "billingProfileStatus", "type": "str"}, + "billing_profile_status_reason_code": {"key": "billingProfileStatusReasonCode", "type": "str"}, + "billing_profile_spending_limit": {"key": "billingProfileSpendingLimit", "type": "str"}, + "billing_profile_system_id": {"key": "billingProfileSystemId", "type": "str"}, + "enabled_azure_plans": {"key": "enabledAzurePlans", "type": "[AzurePlan]"}, + } + + def __init__(self, *, enabled_azure_plans: Optional[List["_models.AzurePlan"]] = None, **kwargs): + """ + :keyword enabled_azure_plans: Enabled azure plans for the associated billing profile. + :paramtype enabled_azure_plans: list[~azure.mgmt.billing.models.AzurePlan] + """ + super().__init__(**kwargs) self.invoice_section_id = None self.invoice_section_display_name = None self.invoice_section_system_id = None @@ -2604,7 +2819,7 @@ def __init__( self.enabled_azure_plans = enabled_azure_plans -class Operation(msrest.serialization.Model): +class Operation(_serialization.Model): """A Billing REST API operation. Variables are only populated by the server, and will be ignored when sending a request. @@ -2613,34 +2828,33 @@ class Operation(msrest.serialization.Model): :vartype name: str :ivar is_data_action: Identifies if the operation is a data operation. :vartype is_data_action: bool - :param display: The object that represents the operation. - :type display: ~azure.mgmt.billing.models.OperationDisplay + :ivar display: The object that represents the operation. + :vartype display: ~azure.mgmt.billing.models.OperationDisplay """ _validation = { - 'name': {'readonly': True}, - 'is_data_action': {'readonly': True}, + "name": {"readonly": True}, + "is_data_action": {"readonly": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, - 'display': {'key': 'display', 'type': 'OperationDisplay'}, + "name": {"key": "name", "type": "str"}, + "is_data_action": {"key": "isDataAction", "type": "bool"}, + "display": {"key": "display", "type": "OperationDisplay"}, } - def __init__( - self, - *, - display: Optional["OperationDisplay"] = None, - **kwargs - ): - super(Operation, self).__init__(**kwargs) + def __init__(self, *, display: Optional["_models.OperationDisplay"] = None, **kwargs): + """ + :keyword display: The object that represents the operation. + :paramtype display: ~azure.mgmt.billing.models.OperationDisplay + """ + super().__init__(**kwargs) self.name = None self.is_data_action = None self.display = display -class OperationDisplay(msrest.serialization.Model): +class OperationDisplay(_serialization.Model): """The object that represents the operation. Variables are only populated by the server, and will be ignored when sending a request. @@ -2657,31 +2871,29 @@ class OperationDisplay(msrest.serialization.Model): """ _validation = { - 'provider': {'readonly': True}, - 'resource': {'readonly': True}, - 'operation': {'readonly': True}, - 'description': {'readonly': True}, + "provider": {"readonly": True}, + "resource": {"readonly": True}, + "operation": {"readonly": True}, + "description": {"readonly": True}, } _attribute_map = { - 'provider': {'key': 'provider', 'type': 'str'}, - 'resource': {'key': 'resource', 'type': 'str'}, - 'operation': {'key': 'operation', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, + "provider": {"key": "provider", "type": "str"}, + "resource": {"key": "resource", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + "description": {"key": "description", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(OperationDisplay, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.provider = None self.resource = None self.operation = None self.description = None -class OperationListResult(msrest.serialization.Model): +class OperationListResult(_serialization.Model): """The list of billing operations and a URL link to get the next set of results. Variables are only populated by the server, and will be ignored when sending a request. @@ -2694,25 +2906,76 @@ class OperationListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[Operation]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Operation]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(OperationListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class Participants(msrest.serialization.Model): +class OperationsErrorDetails(_serialization.Model): + """The details of the error. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: Error code. + :vartype code: str + :ivar message: Error message indicating why the operation failed. + :vartype message: str + :ivar target: The target of the particular error. + :vartype target: str + """ + + _validation = { + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, + } + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.code = None + self.message = None + self.target = None + + +class OperationsErrorResponse(_serialization.Model): + """Error response indicates that the service is not able to process the incoming request. The reason is provided in the error message. + + :ivar error: The details of the error. + :vartype error: ~azure.mgmt.billing.models.OperationsErrorDetails + """ + + _attribute_map = { + "error": {"key": "error", "type": "OperationsErrorDetails"}, + } + + def __init__(self, *, error: Optional["_models.OperationsErrorDetails"] = None, **kwargs): + """ + :keyword error: The details of the error. + :paramtype error: ~azure.mgmt.billing.models.OperationsErrorDetails + """ + super().__init__(**kwargs) + self.error = error + + +class Participants(_serialization.Model): """The details about a participant. Variables are only populated by the server, and will be ignored when sending a request. @@ -2726,28 +2989,26 @@ class Participants(msrest.serialization.Model): """ _validation = { - 'status': {'readonly': True}, - 'status_date': {'readonly': True}, - 'email': {'readonly': True}, + "status": {"readonly": True}, + "status_date": {"readonly": True}, + "email": {"readonly": True}, } _attribute_map = { - 'status': {'key': 'status', 'type': 'str'}, - 'status_date': {'key': 'statusDate', 'type': 'iso-8601'}, - 'email': {'key': 'email', 'type': 'str'}, + "status": {"key": "status", "type": "str"}, + "status_date": {"key": "statusDate", "type": "iso-8601"}, + "email": {"key": "email", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(Participants, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.status = None self.status_date = None self.email = None -class PaymentProperties(msrest.serialization.Model): +class PaymentProperties(_serialization.Model): """The properties of a payment. Variables are only populated by the server, and will be ignored when sending a request. @@ -2758,35 +3019,35 @@ class PaymentProperties(msrest.serialization.Model): :vartype amount: ~azure.mgmt.billing.models.Amount :ivar date: The date when the payment was made. :vartype date: ~datetime.datetime - :param payment_method_family: The family of payment method. Possible values include: "Credits", - "CheckWire", "CreditCard", "None". - :type payment_method_family: str or ~azure.mgmt.billing.models.PaymentMethodFamily + :ivar payment_method_family: The family of payment method. Known values are: "Credits", + "CheckWire", "CreditCard", and "None". + :vartype payment_method_family: str or ~azure.mgmt.billing.models.PaymentMethodFamily :ivar payment_method_type: The type of payment method. :vartype payment_method_type: str """ _validation = { - 'payment_type': {'readonly': True}, - 'amount': {'readonly': True}, - 'date': {'readonly': True}, - 'payment_method_type': {'readonly': True}, + "payment_type": {"readonly": True}, + "amount": {"readonly": True}, + "date": {"readonly": True}, + "payment_method_type": {"readonly": True}, } _attribute_map = { - 'payment_type': {'key': 'paymentType', 'type': 'str'}, - 'amount': {'key': 'amount', 'type': 'Amount'}, - 'date': {'key': 'date', 'type': 'iso-8601'}, - 'payment_method_family': {'key': 'paymentMethodFamily', 'type': 'str'}, - 'payment_method_type': {'key': 'paymentMethodType', 'type': 'str'}, - } - - def __init__( - self, - *, - payment_method_family: Optional[Union[str, "PaymentMethodFamily"]] = None, - **kwargs - ): - super(PaymentProperties, self).__init__(**kwargs) + "payment_type": {"key": "paymentType", "type": "str"}, + "amount": {"key": "amount", "type": "Amount"}, + "date": {"key": "date", "type": "iso-8601"}, + "payment_method_family": {"key": "paymentMethodFamily", "type": "str"}, + "payment_method_type": {"key": "paymentMethodType", "type": "str"}, + } + + def __init__(self, *, payment_method_family: Optional[Union[str, "_models.PaymentMethodFamily"]] = None, **kwargs): + """ + :keyword payment_method_family: The family of payment method. Known values are: "Credits", + "CheckWire", "CreditCard", and "None". + :paramtype payment_method_family: str or ~azure.mgmt.billing.models.PaymentMethodFamily + """ + super().__init__(**kwargs) self.payment_type = None self.amount = None self.date = None @@ -2805,48 +3066,60 @@ class Policy(Resource): :vartype name: str :ivar type: Resource type. :vartype type: str - :param marketplace_purchases: The policy that controls whether Azure marketplace purchases are - allowed for a billing profile. Possible values include: "AllAllowed", "OnlyFreeAllowed", + :ivar marketplace_purchases: The policy that controls whether Azure marketplace purchases are + allowed for a billing profile. Known values are: "AllAllowed", "OnlyFreeAllowed", and "NotAllowed". - :type marketplace_purchases: str or ~azure.mgmt.billing.models.MarketplacePurchasesPolicy - :param reservation_purchases: The policy that controls whether Azure reservation purchases are - allowed for a billing profile. Possible values include: "Allowed", "NotAllowed". - :type reservation_purchases: str or ~azure.mgmt.billing.models.ReservationPurchasesPolicy - :param view_charges: The policy that controls whether users with Azure RBAC access to a - subscription can view its charges. Possible values include: "Allowed", "NotAllowed". - :type view_charges: str or ~azure.mgmt.billing.models.ViewChargesPolicy + :vartype marketplace_purchases: str or ~azure.mgmt.billing.models.MarketplacePurchasesPolicy + :ivar reservation_purchases: The policy that controls whether Azure reservation purchases are + allowed for a billing profile. Known values are: "Allowed" and "NotAllowed". + :vartype reservation_purchases: str or ~azure.mgmt.billing.models.ReservationPurchasesPolicy + :ivar view_charges: The policy that controls whether users with Azure RBAC access to a + subscription can view its charges. Known values are: "Allowed" and "NotAllowed". + :vartype view_charges: str or ~azure.mgmt.billing.models.ViewChargesPolicy """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'marketplace_purchases': {'key': 'properties.marketplacePurchases', 'type': 'str'}, - 'reservation_purchases': {'key': 'properties.reservationPurchases', 'type': 'str'}, - 'view_charges': {'key': 'properties.viewCharges', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "marketplace_purchases": {"key": "properties.marketplacePurchases", "type": "str"}, + "reservation_purchases": {"key": "properties.reservationPurchases", "type": "str"}, + "view_charges": {"key": "properties.viewCharges", "type": "str"}, } def __init__( self, *, - marketplace_purchases: Optional[Union[str, "MarketplacePurchasesPolicy"]] = None, - reservation_purchases: Optional[Union[str, "ReservationPurchasesPolicy"]] = None, - view_charges: Optional[Union[str, "ViewChargesPolicy"]] = None, + marketplace_purchases: Optional[Union[str, "_models.MarketplacePurchasesPolicy"]] = None, + reservation_purchases: Optional[Union[str, "_models.ReservationPurchasesPolicy"]] = None, + view_charges: Optional[Union[str, "_models.ViewChargesPolicy"]] = None, **kwargs ): - super(Policy, self).__init__(**kwargs) + """ + :keyword marketplace_purchases: The policy that controls whether Azure marketplace purchases + are allowed for a billing profile. Known values are: "AllAllowed", "OnlyFreeAllowed", and + "NotAllowed". + :paramtype marketplace_purchases: str or ~azure.mgmt.billing.models.MarketplacePurchasesPolicy + :keyword reservation_purchases: The policy that controls whether Azure reservation purchases + are allowed for a billing profile. Known values are: "Allowed" and "NotAllowed". + :paramtype reservation_purchases: str or ~azure.mgmt.billing.models.ReservationPurchasesPolicy + :keyword view_charges: The policy that controls whether users with Azure RBAC access to a + subscription can view its charges. Known values are: "Allowed" and "NotAllowed". + :paramtype view_charges: str or ~azure.mgmt.billing.models.ViewChargesPolicy + """ + super().__init__(**kwargs) self.marketplace_purchases = marketplace_purchases self.reservation_purchases = reservation_purchases self.view_charges = view_charges -class Product(Resource): +class Product(Resource): # pylint: disable=too-many-instance-attributes """A product. Variables are only populated by the server, and will be ignored when sending a request. @@ -2857,9 +3130,9 @@ class Product(Resource): :vartype name: str :ivar type: Resource type. :vartype type: str - :param auto_renew: Indicates whether auto renewal is turned on or off for a product. Possible - values include: "Off", "On". - :type auto_renew: str or ~azure.mgmt.billing.models.AutoRenew + :ivar auto_renew: Indicates whether auto renewal is turned on or off for a product. Known + values are: "Off" and "On". + :vartype auto_renew: str or ~azure.mgmt.billing.models.AutoRenew :ivar display_name: The display name of the product. :vartype display_name: str :ivar purchase_date: The date when the product was purchased. @@ -2868,14 +3141,14 @@ class Product(Resource): :vartype product_type_id: str :ivar product_type: The description of the type of product. :vartype product_type: str - :param status: The current status of the product. Possible values include: "Active", - "Inactive", "PastDue", "Expiring", "Expired", "Disabled", "Cancelled", "AutoRenew". - :type status: str or ~azure.mgmt.billing.models.ProductStatusType + :ivar status: The current status of the product. Known values are: "Active", "Inactive", + "PastDue", "Expiring", "Expired", "Disabled", "Cancelled", and "AutoRenew". + :vartype status: str or ~azure.mgmt.billing.models.ProductStatusType :ivar end_date: The date when the product will be renewed or canceled. :vartype end_date: ~datetime.datetime - :param billing_frequency: The frequency at which the product will be billed. Possible values - include: "OneTime", "Monthly", "UsageBased". - :type billing_frequency: str or ~azure.mgmt.billing.models.BillingFrequency + :ivar billing_frequency: The frequency at which the product will be billed. Known values are: + "OneTime", "Monthly", and "UsageBased". + :vartype billing_frequency: str or ~azure.mgmt.billing.models.BillingFrequency :ivar last_charge: The last month charges. :vartype last_charge: ~azure.mgmt.billing.models.Amount :ivar last_charge_date: The date of the last charge. @@ -2911,67 +3184,78 @@ class Product(Resource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'display_name': {'readonly': True}, - 'purchase_date': {'readonly': True}, - 'product_type_id': {'readonly': True}, - 'product_type': {'readonly': True}, - 'end_date': {'readonly': True}, - 'last_charge': {'readonly': True}, - 'last_charge_date': {'readonly': True}, - 'quantity': {'readonly': True}, - 'sku_id': {'readonly': True}, - 'sku_description': {'readonly': True}, - 'tenant_id': {'readonly': True}, - 'availability_id': {'readonly': True}, - 'invoice_section_id': {'readonly': True}, - 'invoice_section_display_name': {'readonly': True}, - 'billing_profile_id': {'readonly': True}, - 'billing_profile_display_name': {'readonly': True}, - 'customer_id': {'readonly': True}, - 'customer_display_name': {'readonly': True}, - 'reseller': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'auto_renew': {'key': 'properties.autoRenew', 'type': 'str'}, - 'display_name': {'key': 'properties.displayName', 'type': 'str'}, - 'purchase_date': {'key': 'properties.purchaseDate', 'type': 'iso-8601'}, - 'product_type_id': {'key': 'properties.productTypeId', 'type': 'str'}, - 'product_type': {'key': 'properties.productType', 'type': 'str'}, - 'status': {'key': 'properties.status', 'type': 'str'}, - 'end_date': {'key': 'properties.endDate', 'type': 'iso-8601'}, - 'billing_frequency': {'key': 'properties.billingFrequency', 'type': 'str'}, - 'last_charge': {'key': 'properties.lastCharge', 'type': 'Amount'}, - 'last_charge_date': {'key': 'properties.lastChargeDate', 'type': 'iso-8601'}, - 'quantity': {'key': 'properties.quantity', 'type': 'float'}, - 'sku_id': {'key': 'properties.skuId', 'type': 'str'}, - 'sku_description': {'key': 'properties.skuDescription', 'type': 'str'}, - 'tenant_id': {'key': 'properties.tenantId', 'type': 'str'}, - 'availability_id': {'key': 'properties.availabilityId', 'type': 'str'}, - 'invoice_section_id': {'key': 'properties.invoiceSectionId', 'type': 'str'}, - 'invoice_section_display_name': {'key': 'properties.invoiceSectionDisplayName', 'type': 'str'}, - 'billing_profile_id': {'key': 'properties.billingProfileId', 'type': 'str'}, - 'billing_profile_display_name': {'key': 'properties.billingProfileDisplayName', 'type': 'str'}, - 'customer_id': {'key': 'properties.customerId', 'type': 'str'}, - 'customer_display_name': {'key': 'properties.customerDisplayName', 'type': 'str'}, - 'reseller': {'key': 'properties.reseller', 'type': 'Reseller'}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "display_name": {"readonly": True}, + "purchase_date": {"readonly": True}, + "product_type_id": {"readonly": True}, + "product_type": {"readonly": True}, + "end_date": {"readonly": True}, + "last_charge": {"readonly": True}, + "last_charge_date": {"readonly": True}, + "quantity": {"readonly": True}, + "sku_id": {"readonly": True}, + "sku_description": {"readonly": True}, + "tenant_id": {"readonly": True}, + "availability_id": {"readonly": True}, + "invoice_section_id": {"readonly": True}, + "invoice_section_display_name": {"readonly": True}, + "billing_profile_id": {"readonly": True}, + "billing_profile_display_name": {"readonly": True}, + "customer_id": {"readonly": True}, + "customer_display_name": {"readonly": True}, + "reseller": {"readonly": True}, } - def __init__( + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "auto_renew": {"key": "properties.autoRenew", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "purchase_date": {"key": "properties.purchaseDate", "type": "iso-8601"}, + "product_type_id": {"key": "properties.productTypeId", "type": "str"}, + "product_type": {"key": "properties.productType", "type": "str"}, + "status": {"key": "properties.status", "type": "str"}, + "end_date": {"key": "properties.endDate", "type": "iso-8601"}, + "billing_frequency": {"key": "properties.billingFrequency", "type": "str"}, + "last_charge": {"key": "properties.lastCharge", "type": "Amount"}, + "last_charge_date": {"key": "properties.lastChargeDate", "type": "iso-8601"}, + "quantity": {"key": "properties.quantity", "type": "float"}, + "sku_id": {"key": "properties.skuId", "type": "str"}, + "sku_description": {"key": "properties.skuDescription", "type": "str"}, + "tenant_id": {"key": "properties.tenantId", "type": "str"}, + "availability_id": {"key": "properties.availabilityId", "type": "str"}, + "invoice_section_id": {"key": "properties.invoiceSectionId", "type": "str"}, + "invoice_section_display_name": {"key": "properties.invoiceSectionDisplayName", "type": "str"}, + "billing_profile_id": {"key": "properties.billingProfileId", "type": "str"}, + "billing_profile_display_name": {"key": "properties.billingProfileDisplayName", "type": "str"}, + "customer_id": {"key": "properties.customerId", "type": "str"}, + "customer_display_name": {"key": "properties.customerDisplayName", "type": "str"}, + "reseller": {"key": "properties.reseller", "type": "Reseller"}, + } + + def __init__( # pylint: disable=too-many-locals self, *, - auto_renew: Optional[Union[str, "AutoRenew"]] = None, - status: Optional[Union[str, "ProductStatusType"]] = None, - billing_frequency: Optional[Union[str, "BillingFrequency"]] = None, + auto_renew: Optional[Union[str, "_models.AutoRenew"]] = None, + status: Optional[Union[str, "_models.ProductStatusType"]] = None, + billing_frequency: Optional[Union[str, "_models.BillingFrequency"]] = None, **kwargs ): - super(Product, self).__init__(**kwargs) + """ + :keyword auto_renew: Indicates whether auto renewal is turned on or off for a product. Known + values are: "Off" and "On". + :paramtype auto_renew: str or ~azure.mgmt.billing.models.AutoRenew + :keyword status: The current status of the product. Known values are: "Active", "Inactive", + "PastDue", "Expiring", "Expired", "Disabled", "Cancelled", and "AutoRenew". + :paramtype status: str or ~azure.mgmt.billing.models.ProductStatusType + :keyword billing_frequency: The frequency at which the product will be billed. Known values + are: "OneTime", "Monthly", and "UsageBased". + :paramtype billing_frequency: str or ~azure.mgmt.billing.models.BillingFrequency + """ + super().__init__(**kwargs) self.auto_renew = auto_renew self.display_name = None self.purchase_date = None @@ -2996,37 +3280,40 @@ def __init__( self.reseller = None -class ProductsListResult(msrest.serialization.Model): +class ProductsListResult(_serialization.Model): """The list of products. It contains a list of available product summaries in reverse chronological order by purchase date. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of products. :vartype value: list[~azure.mgmt.billing.models.Product] + :ivar total_count: Total number of records. + :vartype total_count: int :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "total_count": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[Product]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Product]"}, + "total_count": {"key": "totalCount", "type": "int"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(ProductsListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None + self.total_count = None self.next_link = None -class RebillDetails(msrest.serialization.Model): +class RebillDetails(_serialization.Model): """The rebill details of an invoice. Variables are only populated by the server, and will be ignored when sending a request. @@ -3040,28 +3327,26 @@ class RebillDetails(msrest.serialization.Model): """ _validation = { - 'credit_note_document_id': {'readonly': True}, - 'invoice_document_id': {'readonly': True}, - 'rebill_details': {'readonly': True}, + "credit_note_document_id": {"readonly": True}, + "invoice_document_id": {"readonly": True}, + "rebill_details": {"readonly": True}, } _attribute_map = { - 'credit_note_document_id': {'key': 'creditNoteDocumentId', 'type': 'str'}, - 'invoice_document_id': {'key': 'invoiceDocumentId', 'type': 'str'}, - 'rebill_details': {'key': 'rebillDetails', 'type': '{RebillDetails}'}, + "credit_note_document_id": {"key": "creditNoteDocumentId", "type": "str"}, + "invoice_document_id": {"key": "invoiceDocumentId", "type": "str"}, + "rebill_details": {"key": "rebillDetails", "type": "{RebillDetails}"}, } - def __init__( - self, - **kwargs - ): - super(RebillDetails, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.credit_note_document_id = None self.invoice_document_id = None self.rebill_details = None -class Reseller(msrest.serialization.Model): +class Reseller(_serialization.Model): """Details of the reseller. Variables are only populated by the server, and will be ignored when sending a request. @@ -3073,25 +3358,23 @@ class Reseller(msrest.serialization.Model): """ _validation = { - 'reseller_id': {'readonly': True}, - 'description': {'readonly': True}, + "reseller_id": {"readonly": True}, + "description": {"readonly": True}, } _attribute_map = { - 'reseller_id': {'key': 'resellerId', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, + "reseller_id": {"key": "resellerId", "type": "str"}, + "description": {"key": "description", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(Reseller, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.reseller_id = None self.description = None -class Reservation(msrest.serialization.Model): +class Reservation(_serialization.Model): # pylint: disable=too-many-instance-attributes """The definition of the reservation. Variables are only populated by the server, and will be ignored when sending a request. @@ -3104,11 +3387,11 @@ class Reservation(msrest.serialization.Model): :vartype type: str :ivar location: The location of the reservation. :vartype location: str - :param sku: The sku information associated to this reservation. - :type sku: ~azure.mgmt.billing.models.ReservationSkuProperty - :param applied_scopes: The array of applied scopes of a reservation. Will be null if the + :ivar sku: The sku information associated to this reservation. + :vartype sku: ~azure.mgmt.billing.models.ReservationSkuProperty + :ivar applied_scopes: The array of applied scopes of a reservation. Will be null if the reservation is in Shared scope. - :type applied_scopes: list[str] + :vartype applied_scopes: list[str] :ivar applied_scope_type: The applied scope type of the reservation. :vartype applied_scope_type: str :ivar reserved_resource_type: The reserved source type of the reservation, e.g. virtual @@ -3147,61 +3430,68 @@ class Reservation(msrest.serialization.Model): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'location': {'readonly': True}, - 'applied_scope_type': {'readonly': True}, - 'reserved_resource_type': {'readonly': True}, - 'quantity': {'readonly': True}, - 'provisioning_state': {'readonly': True}, - 'expiry_date': {'readonly': True}, - 'provisioning_sub_state': {'readonly': True}, - 'display_name': {'readonly': True}, - 'display_provisioning_state': {'readonly': True}, - 'user_friendly_renew_state': {'readonly': True}, - 'user_friendly_applied_scope_type': {'readonly': True}, - 'effective_date_time': {'readonly': True}, - 'sku_description': {'readonly': True}, - 'term': {'readonly': True}, - 'renew': {'readonly': True}, - 'renew_source': {'readonly': True}, - 'utilization': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'location': {'key': 'location', 'type': 'str'}, - 'sku': {'key': 'sku', 'type': 'ReservationSkuProperty'}, - 'applied_scopes': {'key': 'properties.appliedScopes', 'type': '[str]'}, - 'applied_scope_type': {'key': 'properties.appliedScopeType', 'type': 'str'}, - 'reserved_resource_type': {'key': 'properties.reservedResourceType', 'type': 'str'}, - 'quantity': {'key': 'properties.quantity', 'type': 'float'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, - 'expiry_date': {'key': 'properties.expiryDate', 'type': 'str'}, - 'provisioning_sub_state': {'key': 'properties.provisioningSubState', 'type': 'str'}, - 'display_name': {'key': 'properties.displayName', 'type': 'str'}, - 'display_provisioning_state': {'key': 'properties.displayProvisioningState', 'type': 'str'}, - 'user_friendly_renew_state': {'key': 'properties.userFriendlyRenewState', 'type': 'str'}, - 'user_friendly_applied_scope_type': {'key': 'properties.userFriendlyAppliedScopeType', 'type': 'str'}, - 'effective_date_time': {'key': 'properties.effectiveDateTime', 'type': 'str'}, - 'sku_description': {'key': 'properties.skuDescription', 'type': 'str'}, - 'term': {'key': 'properties.term', 'type': 'str'}, - 'renew': {'key': 'properties.renew', 'type': 'bool'}, - 'renew_source': {'key': 'properties.renewSource', 'type': 'str'}, - 'utilization': {'key': 'properties.utilization', 'type': 'ReservationPropertyUtilization'}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "location": {"readonly": True}, + "applied_scope_type": {"readonly": True}, + "reserved_resource_type": {"readonly": True}, + "quantity": {"readonly": True}, + "provisioning_state": {"readonly": True}, + "expiry_date": {"readonly": True}, + "provisioning_sub_state": {"readonly": True}, + "display_name": {"readonly": True}, + "display_provisioning_state": {"readonly": True}, + "user_friendly_renew_state": {"readonly": True}, + "user_friendly_applied_scope_type": {"readonly": True}, + "effective_date_time": {"readonly": True}, + "sku_description": {"readonly": True}, + "term": {"readonly": True}, + "renew": {"readonly": True}, + "renew_source": {"readonly": True}, + "utilization": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "sku": {"key": "sku", "type": "ReservationSkuProperty"}, + "applied_scopes": {"key": "properties.appliedScopes", "type": "[str]"}, + "applied_scope_type": {"key": "properties.appliedScopeType", "type": "str"}, + "reserved_resource_type": {"key": "properties.reservedResourceType", "type": "str"}, + "quantity": {"key": "properties.quantity", "type": "float"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "expiry_date": {"key": "properties.expiryDate", "type": "str"}, + "provisioning_sub_state": {"key": "properties.provisioningSubState", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "display_provisioning_state": {"key": "properties.displayProvisioningState", "type": "str"}, + "user_friendly_renew_state": {"key": "properties.userFriendlyRenewState", "type": "str"}, + "user_friendly_applied_scope_type": {"key": "properties.userFriendlyAppliedScopeType", "type": "str"}, + "effective_date_time": {"key": "properties.effectiveDateTime", "type": "str"}, + "sku_description": {"key": "properties.skuDescription", "type": "str"}, + "term": {"key": "properties.term", "type": "str"}, + "renew": {"key": "properties.renew", "type": "bool"}, + "renew_source": {"key": "properties.renewSource", "type": "str"}, + "utilization": {"key": "properties.utilization", "type": "ReservationPropertyUtilization"}, } def __init__( self, *, - sku: Optional["ReservationSkuProperty"] = None, + sku: Optional["_models.ReservationSkuProperty"] = None, applied_scopes: Optional[List[str]] = None, **kwargs ): - super(Reservation, self).__init__(**kwargs) + """ + :keyword sku: The sku information associated to this reservation. + :paramtype sku: ~azure.mgmt.billing.models.ReservationSkuProperty + :keyword applied_scopes: The array of applied scopes of a reservation. Will be null if the + reservation is in Shared scope. + :paramtype applied_scopes: list[str] + """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -3226,38 +3516,37 @@ def __init__( self.utilization = None -class ReservationPropertyUtilization(msrest.serialization.Model): +class ReservationPropertyUtilization(_serialization.Model): """Reservation utilization. Variables are only populated by the server, and will be ignored when sending a request. :ivar trend: The number of days trend for a reservation. :vartype trend: str - :param aggregates: The array of aggregates of a reservation's utilization. - :type aggregates: list[~azure.mgmt.billing.models.ReservationUtilizationAggregates] + :ivar aggregates: The array of aggregates of a reservation's utilization. + :vartype aggregates: list[~azure.mgmt.billing.models.ReservationUtilizationAggregates] """ _validation = { - 'trend': {'readonly': True}, + "trend": {"readonly": True}, } _attribute_map = { - 'trend': {'key': 'trend', 'type': 'str'}, - 'aggregates': {'key': 'aggregates', 'type': '[ReservationUtilizationAggregates]'}, + "trend": {"key": "trend", "type": "str"}, + "aggregates": {"key": "aggregates", "type": "[ReservationUtilizationAggregates]"}, } - def __init__( - self, - *, - aggregates: Optional[List["ReservationUtilizationAggregates"]] = None, - **kwargs - ): - super(ReservationPropertyUtilization, self).__init__(**kwargs) + def __init__(self, *, aggregates: Optional[List["_models.ReservationUtilizationAggregates"]] = None, **kwargs): + """ + :keyword aggregates: The array of aggregates of a reservation's utilization. + :paramtype aggregates: list[~azure.mgmt.billing.models.ReservationUtilizationAggregates] + """ + super().__init__(**kwargs) self.trend = None self.aggregates = aggregates -class ReservationSkuProperty(msrest.serialization.Model): +class ReservationSkuProperty(_serialization.Model): """The property of reservation sku object. Variables are only populated by the server, and will be ignored when sending a request. @@ -3267,22 +3556,20 @@ class ReservationSkuProperty(msrest.serialization.Model): """ _validation = { - 'name': {'readonly': True}, + "name": {"readonly": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(ReservationSkuProperty, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.name = None -class ReservationsListResult(msrest.serialization.Model): +class ReservationsListResult(_serialization.Model): """The list of reservations and summary of roll out count of reservations in each state. Variables are only populated by the server, and will be ignored when sending a request. @@ -3291,34 +3578,33 @@ class ReservationsListResult(msrest.serialization.Model): :vartype value: list[~azure.mgmt.billing.models.Reservation] :ivar next_link: The link (url) to the next page of results. :vartype next_link: str - :param summary: The roll out count summary of the reservations. - :type summary: ~azure.mgmt.billing.models.ReservationSummary + :ivar summary: The roll out count summary of the reservations. + :vartype summary: ~azure.mgmt.billing.models.ReservationSummary """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[Reservation]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - 'summary': {'key': 'summary', 'type': 'ReservationSummary'}, + "value": {"key": "value", "type": "[Reservation]"}, + "next_link": {"key": "nextLink", "type": "str"}, + "summary": {"key": "summary", "type": "ReservationSummary"}, } - def __init__( - self, - *, - summary: Optional["ReservationSummary"] = None, - **kwargs - ): - super(ReservationsListResult, self).__init__(**kwargs) + def __init__(self, *, summary: Optional["_models.ReservationSummary"] = None, **kwargs): + """ + :keyword summary: The roll out count summary of the reservations. + :paramtype summary: ~azure.mgmt.billing.models.ReservationSummary + """ + super().__init__(**kwargs) self.value = None self.next_link = None self.summary = summary -class ReservationSummary(msrest.serialization.Model): +class ReservationSummary(_serialization.Model): """The roll up count summary of reservations in each state. Variables are only populated by the server, and will be ignored when sending a request. @@ -3338,28 +3624,26 @@ class ReservationSummary(msrest.serialization.Model): """ _validation = { - 'succeeded_count': {'readonly': True}, - 'failed_count': {'readonly': True}, - 'expiring_count': {'readonly': True}, - 'expired_count': {'readonly': True}, - 'pending_count': {'readonly': True}, - 'cancelled_count': {'readonly': True}, + "succeeded_count": {"readonly": True}, + "failed_count": {"readonly": True}, + "expiring_count": {"readonly": True}, + "expired_count": {"readonly": True}, + "pending_count": {"readonly": True}, + "cancelled_count": {"readonly": True}, } _attribute_map = { - 'succeeded_count': {'key': 'succeededCount', 'type': 'float'}, - 'failed_count': {'key': 'failedCount', 'type': 'float'}, - 'expiring_count': {'key': 'expiringCount', 'type': 'float'}, - 'expired_count': {'key': 'expiredCount', 'type': 'float'}, - 'pending_count': {'key': 'pendingCount', 'type': 'float'}, - 'cancelled_count': {'key': 'cancelledCount', 'type': 'float'}, + "succeeded_count": {"key": "succeededCount", "type": "float"}, + "failed_count": {"key": "failedCount", "type": "float"}, + "expiring_count": {"key": "expiringCount", "type": "float"}, + "expired_count": {"key": "expiredCount", "type": "float"}, + "pending_count": {"key": "pendingCount", "type": "float"}, + "cancelled_count": {"key": "cancelledCount", "type": "float"}, } - def __init__( - self, - **kwargs - ): - super(ReservationSummary, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.succeeded_count = None self.failed_count = None self.expiring_count = None @@ -3368,7 +3652,7 @@ def __init__( self.cancelled_count = None -class ReservationUtilizationAggregates(msrest.serialization.Model): +class ReservationUtilizationAggregates(_serialization.Model): """The aggregate values of reservation utilization. Variables are only populated by the server, and will be ignored when sending a request. @@ -3384,31 +3668,29 @@ class ReservationUtilizationAggregates(msrest.serialization.Model): """ _validation = { - 'grain': {'readonly': True}, - 'grain_unit': {'readonly': True}, - 'value': {'readonly': True}, - 'value_unit': {'readonly': True}, + "grain": {"readonly": True}, + "grain_unit": {"readonly": True}, + "value": {"readonly": True}, + "value_unit": {"readonly": True}, } _attribute_map = { - 'grain': {'key': 'grain', 'type': 'float'}, - 'grain_unit': {'key': 'grainUnit', 'type': 'str'}, - 'value': {'key': 'value', 'type': 'float'}, - 'value_unit': {'key': 'valueUnit', 'type': 'str'}, + "grain": {"key": "grain", "type": "float"}, + "grain_unit": {"key": "grainUnit", "type": "str"}, + "value": {"key": "value", "type": "float"}, + "value_unit": {"key": "valueUnit", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(ReservationUtilizationAggregates, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.grain = None self.grain_unit = None self.value = None self.value_unit = None -class Transaction(Resource): +class Transaction(Resource): # pylint: disable=too-many-instance-attributes """A transaction. Variables are only populated by the server, and will be ignored when sending a request. @@ -3419,9 +3701,9 @@ class Transaction(Resource): :vartype name: str :ivar type: Resource type. :vartype type: str - :param kind: The kind of transaction. Options are all or reservation. Possible values include: - "all", "reservation". - :type kind: str or ~azure.mgmt.billing.models.TransactionTypeKind + :ivar kind: The kind of transaction. Options are all or reservation. Known values are: "all" + and "reservation". + :vartype kind: str or ~azure.mgmt.billing.models.TransactionTypeKind :ivar date: The date of transaction. :vartype date: ~datetime.datetime :ivar invoice: Invoice on which the transaction was billed or 'pending' if the transaction is @@ -3444,9 +3726,9 @@ class Transaction(Resource): :vartype product_type: str :ivar product_description: The description of the product for which the transaction took place. :vartype product_description: str - :param transaction_type: The type of transaction. Possible values include: "Purchase", "Usage + :ivar transaction_type: The type of transaction. Known values are: "Purchase" and "Usage Charge". - :type transaction_type: str or ~azure.mgmt.billing.models.ReservationType + :vartype transaction_type: str or ~azure.mgmt.billing.models.ReservationType :ivar transaction_amount: The charge associated with the transaction. :vartype transaction_amount: ~azure.mgmt.billing.models.Amount :ivar quantity: The quantity purchased in the transaction. @@ -3513,95 +3795,103 @@ class Transaction(Resource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'date': {'readonly': True}, - 'invoice': {'readonly': True}, - 'invoice_id': {'readonly': True}, - 'order_id': {'readonly': True}, - 'order_name': {'readonly': True}, - 'product_family': {'readonly': True}, - 'product_type_id': {'readonly': True}, - 'product_type': {'readonly': True}, - 'product_description': {'readonly': True}, - 'transaction_amount': {'readonly': True}, - 'quantity': {'readonly': True}, - 'invoice_section_id': {'readonly': True}, - 'invoice_section_display_name': {'readonly': True}, - 'billing_profile_id': {'readonly': True}, - 'billing_profile_display_name': {'readonly': True}, - 'customer_id': {'readonly': True}, - 'customer_display_name': {'readonly': True}, - 'subscription_id': {'readonly': True}, - 'subscription_name': {'readonly': True}, - 'azure_plan': {'readonly': True}, - 'azure_credit_applied': {'readonly': True}, - 'billing_currency': {'readonly': True}, - 'discount': {'readonly': True}, - 'effective_price': {'readonly': True}, - 'exchange_rate': {'readonly': True}, - 'market_price': {'readonly': True}, - 'pricing_currency': {'readonly': True}, - 'service_period_start_date': {'readonly': True}, - 'service_period_end_date': {'readonly': True}, - 'sub_total': {'readonly': True}, - 'tax': {'readonly': True}, - 'unit_of_measure': {'readonly': True}, - 'units': {'readonly': True}, - 'unit_type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'kind': {'key': 'properties.kind', 'type': 'str'}, - 'date': {'key': 'properties.date', 'type': 'iso-8601'}, - 'invoice': {'key': 'properties.invoice', 'type': 'str'}, - 'invoice_id': {'key': 'properties.invoiceId', 'type': 'str'}, - 'order_id': {'key': 'properties.orderId', 'type': 'str'}, - 'order_name': {'key': 'properties.orderName', 'type': 'str'}, - 'product_family': {'key': 'properties.productFamily', 'type': 'str'}, - 'product_type_id': {'key': 'properties.productTypeId', 'type': 'str'}, - 'product_type': {'key': 'properties.productType', 'type': 'str'}, - 'product_description': {'key': 'properties.productDescription', 'type': 'str'}, - 'transaction_type': {'key': 'properties.transactionType', 'type': 'str'}, - 'transaction_amount': {'key': 'properties.transactionAmount', 'type': 'Amount'}, - 'quantity': {'key': 'properties.quantity', 'type': 'int'}, - 'invoice_section_id': {'key': 'properties.invoiceSectionId', 'type': 'str'}, - 'invoice_section_display_name': {'key': 'properties.invoiceSectionDisplayName', 'type': 'str'}, - 'billing_profile_id': {'key': 'properties.billingProfileId', 'type': 'str'}, - 'billing_profile_display_name': {'key': 'properties.billingProfileDisplayName', 'type': 'str'}, - 'customer_id': {'key': 'properties.customerId', 'type': 'str'}, - 'customer_display_name': {'key': 'properties.customerDisplayName', 'type': 'str'}, - 'subscription_id': {'key': 'properties.subscriptionId', 'type': 'str'}, - 'subscription_name': {'key': 'properties.subscriptionName', 'type': 'str'}, - 'azure_plan': {'key': 'properties.azurePlan', 'type': 'str'}, - 'azure_credit_applied': {'key': 'properties.azureCreditApplied', 'type': 'Amount'}, - 'billing_currency': {'key': 'properties.billingCurrency', 'type': 'str'}, - 'discount': {'key': 'properties.discount', 'type': 'float'}, - 'effective_price': {'key': 'properties.effectivePrice', 'type': 'Amount'}, - 'exchange_rate': {'key': 'properties.exchangeRate', 'type': 'float'}, - 'market_price': {'key': 'properties.marketPrice', 'type': 'Amount'}, - 'pricing_currency': {'key': 'properties.pricingCurrency', 'type': 'str'}, - 'service_period_start_date': {'key': 'properties.servicePeriodStartDate', 'type': 'iso-8601'}, - 'service_period_end_date': {'key': 'properties.servicePeriodEndDate', 'type': 'iso-8601'}, - 'sub_total': {'key': 'properties.subTotal', 'type': 'Amount'}, - 'tax': {'key': 'properties.tax', 'type': 'Amount'}, - 'unit_of_measure': {'key': 'properties.unitOfMeasure', 'type': 'str'}, - 'units': {'key': 'properties.units', 'type': 'float'}, - 'unit_type': {'key': 'properties.unitType', 'type': 'str'}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "date": {"readonly": True}, + "invoice": {"readonly": True}, + "invoice_id": {"readonly": True}, + "order_id": {"readonly": True}, + "order_name": {"readonly": True}, + "product_family": {"readonly": True}, + "product_type_id": {"readonly": True}, + "product_type": {"readonly": True}, + "product_description": {"readonly": True}, + "transaction_amount": {"readonly": True}, + "quantity": {"readonly": True}, + "invoice_section_id": {"readonly": True}, + "invoice_section_display_name": {"readonly": True}, + "billing_profile_id": {"readonly": True}, + "billing_profile_display_name": {"readonly": True}, + "customer_id": {"readonly": True}, + "customer_display_name": {"readonly": True}, + "subscription_id": {"readonly": True}, + "subscription_name": {"readonly": True}, + "azure_plan": {"readonly": True}, + "azure_credit_applied": {"readonly": True}, + "billing_currency": {"readonly": True}, + "discount": {"readonly": True}, + "effective_price": {"readonly": True}, + "exchange_rate": {"readonly": True}, + "market_price": {"readonly": True}, + "pricing_currency": {"readonly": True}, + "service_period_start_date": {"readonly": True}, + "service_period_end_date": {"readonly": True}, + "sub_total": {"readonly": True}, + "tax": {"readonly": True}, + "unit_of_measure": {"readonly": True}, + "units": {"readonly": True}, + "unit_type": {"readonly": True}, } - def __init__( + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "kind": {"key": "properties.kind", "type": "str"}, + "date": {"key": "properties.date", "type": "iso-8601"}, + "invoice": {"key": "properties.invoice", "type": "str"}, + "invoice_id": {"key": "properties.invoiceId", "type": "str"}, + "order_id": {"key": "properties.orderId", "type": "str"}, + "order_name": {"key": "properties.orderName", "type": "str"}, + "product_family": {"key": "properties.productFamily", "type": "str"}, + "product_type_id": {"key": "properties.productTypeId", "type": "str"}, + "product_type": {"key": "properties.productType", "type": "str"}, + "product_description": {"key": "properties.productDescription", "type": "str"}, + "transaction_type": {"key": "properties.transactionType", "type": "str"}, + "transaction_amount": {"key": "properties.transactionAmount", "type": "Amount"}, + "quantity": {"key": "properties.quantity", "type": "int"}, + "invoice_section_id": {"key": "properties.invoiceSectionId", "type": "str"}, + "invoice_section_display_name": {"key": "properties.invoiceSectionDisplayName", "type": "str"}, + "billing_profile_id": {"key": "properties.billingProfileId", "type": "str"}, + "billing_profile_display_name": {"key": "properties.billingProfileDisplayName", "type": "str"}, + "customer_id": {"key": "properties.customerId", "type": "str"}, + "customer_display_name": {"key": "properties.customerDisplayName", "type": "str"}, + "subscription_id": {"key": "properties.subscriptionId", "type": "str"}, + "subscription_name": {"key": "properties.subscriptionName", "type": "str"}, + "azure_plan": {"key": "properties.azurePlan", "type": "str"}, + "azure_credit_applied": {"key": "properties.azureCreditApplied", "type": "Amount"}, + "billing_currency": {"key": "properties.billingCurrency", "type": "str"}, + "discount": {"key": "properties.discount", "type": "float"}, + "effective_price": {"key": "properties.effectivePrice", "type": "Amount"}, + "exchange_rate": {"key": "properties.exchangeRate", "type": "float"}, + "market_price": {"key": "properties.marketPrice", "type": "Amount"}, + "pricing_currency": {"key": "properties.pricingCurrency", "type": "str"}, + "service_period_start_date": {"key": "properties.servicePeriodStartDate", "type": "iso-8601"}, + "service_period_end_date": {"key": "properties.servicePeriodEndDate", "type": "iso-8601"}, + "sub_total": {"key": "properties.subTotal", "type": "Amount"}, + "tax": {"key": "properties.tax", "type": "Amount"}, + "unit_of_measure": {"key": "properties.unitOfMeasure", "type": "str"}, + "units": {"key": "properties.units", "type": "float"}, + "unit_type": {"key": "properties.unitType", "type": "str"}, + } + + def __init__( # pylint: disable=too-many-locals self, *, - kind: Optional[Union[str, "TransactionTypeKind"]] = None, - transaction_type: Optional[Union[str, "ReservationType"]] = None, + kind: Optional[Union[str, "_models.TransactionTypeKind"]] = None, + transaction_type: Optional[Union[str, "_models.ReservationType"]] = None, **kwargs ): - super(Transaction, self).__init__(**kwargs) + """ + :keyword kind: The kind of transaction. Options are all or reservation. Known values are: "all" + and "reservation". + :paramtype kind: str or ~azure.mgmt.billing.models.TransactionTypeKind + :keyword transaction_type: The type of transaction. Known values are: "Purchase" and "Usage + Charge". + :paramtype transaction_type: str or ~azure.mgmt.billing.models.ReservationType + """ + super().__init__(**kwargs) self.kind = kind self.date = None self.invoice = None @@ -3640,245 +3930,281 @@ def __init__( self.unit_type = None -class TransactionListResult(msrest.serialization.Model): +class TransactionListResult(_serialization.Model): """The list of transactions. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of transactions. :vartype value: list[~azure.mgmt.billing.models.Transaction] + :ivar total_count: Total number of records. + :vartype total_count: int :ivar next_link: The link (url) to the next page of results. :vartype next_link: str """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "total_count": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[Transaction]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Transaction]"}, + "total_count": {"key": "totalCount", "type": "int"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(TransactionListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None + self.total_count = None self.next_link = None -class TransferBillingSubscriptionRequestProperties(msrest.serialization.Model): +class TransferBillingSubscriptionRequestProperties(_serialization.Model): """Request parameters to transfer billing subscription. All required parameters must be populated in order to send to Azure. - :param destination_invoice_section_id: Required. The destination invoice section id. - :type destination_invoice_section_id: str + :ivar destination_invoice_section_id: The destination invoice section id. Required. + :vartype destination_invoice_section_id: str """ _validation = { - 'destination_invoice_section_id': {'required': True}, + "destination_invoice_section_id": {"required": True}, } _attribute_map = { - 'destination_invoice_section_id': {'key': 'destinationInvoiceSectionId', 'type': 'str'}, + "destination_invoice_section_id": {"key": "destinationInvoiceSectionId", "type": "str"}, } - def __init__( - self, - *, - destination_invoice_section_id: str, - **kwargs - ): - super(TransferBillingSubscriptionRequestProperties, self).__init__(**kwargs) + def __init__(self, *, destination_invoice_section_id: str, **kwargs): + """ + :keyword destination_invoice_section_id: The destination invoice section id. Required. + :paramtype destination_invoice_section_id: str + """ + super().__init__(**kwargs) self.destination_invoice_section_id = destination_invoice_section_id -class TransferProductRequestProperties(msrest.serialization.Model): +class TransferProductRequestProperties(_serialization.Model): """The properties of the product to initiate a transfer. - :param destination_invoice_section_id: The destination invoice section id. - :type destination_invoice_section_id: str + :ivar destination_invoice_section_id: The destination invoice section id. + :vartype destination_invoice_section_id: str """ _attribute_map = { - 'destination_invoice_section_id': {'key': 'destinationInvoiceSectionId', 'type': 'str'}, + "destination_invoice_section_id": {"key": "destinationInvoiceSectionId", "type": "str"}, } - def __init__( - self, - *, - destination_invoice_section_id: Optional[str] = None, - **kwargs - ): - super(TransferProductRequestProperties, self).__init__(**kwargs) + def __init__(self, *, destination_invoice_section_id: Optional[str] = None, **kwargs): + """ + :keyword destination_invoice_section_id: The destination invoice section id. + :paramtype destination_invoice_section_id: str + """ + super().__init__(**kwargs) self.destination_invoice_section_id = destination_invoice_section_id -class ValidateAddressResponse(msrest.serialization.Model): +class ValidateAddressResponse(_serialization.Model): """Result of the address validation. - :param status: status of the address validation. Possible values include: "Valid", "Invalid". - :type status: str or ~azure.mgmt.billing.models.AddressValidationStatus - :param suggested_addresses: The list of suggested addresses. - :type suggested_addresses: list[~azure.mgmt.billing.models.AddressDetails] - :param validation_message: Validation error message. - :type validation_message: str + :ivar status: status of the address validation. Known values are: "Valid" and "Invalid". + :vartype status: str or ~azure.mgmt.billing.models.AddressValidationStatus + :ivar suggested_addresses: The list of suggested addresses. + :vartype suggested_addresses: list[~azure.mgmt.billing.models.AddressDetails] + :ivar validation_message: Validation error message. + :vartype validation_message: str """ _attribute_map = { - 'status': {'key': 'status', 'type': 'str'}, - 'suggested_addresses': {'key': 'suggestedAddresses', 'type': '[AddressDetails]'}, - 'validation_message': {'key': 'validationMessage', 'type': 'str'}, + "status": {"key": "status", "type": "str"}, + "suggested_addresses": {"key": "suggestedAddresses", "type": "[AddressDetails]"}, + "validation_message": {"key": "validationMessage", "type": "str"}, } def __init__( self, *, - status: Optional[Union[str, "AddressValidationStatus"]] = None, - suggested_addresses: Optional[List["AddressDetails"]] = None, + status: Optional[Union[str, "_models.AddressValidationStatus"]] = None, + suggested_addresses: Optional[List["_models.AddressDetails"]] = None, validation_message: Optional[str] = None, **kwargs ): - super(ValidateAddressResponse, self).__init__(**kwargs) + """ + :keyword status: status of the address validation. Known values are: "Valid" and "Invalid". + :paramtype status: str or ~azure.mgmt.billing.models.AddressValidationStatus + :keyword suggested_addresses: The list of suggested addresses. + :paramtype suggested_addresses: list[~azure.mgmt.billing.models.AddressDetails] + :keyword validation_message: Validation error message. + :paramtype validation_message: str + """ + super().__init__(**kwargs) self.status = status self.suggested_addresses = suggested_addresses self.validation_message = validation_message -class ValidateProductTransferEligibilityError(msrest.serialization.Model): +class ValidateProductTransferEligibilityError(_serialization.Model): """Error details of the product transfer eligibility validation. - :param code: Error code for the product transfer validation. Possible values include: - "InvalidSource", "ProductNotActive", "InsufficientPermissionOnSource", - "InsufficientPermissionOnDestination", "DestinationBillingProfilePastDue", - "ProductTypeNotSupported", "CrossBillingAccountNotAllowed", "NotAvailableForDestinationMarket", - "OneTimePurchaseProductTransferNotAllowed". - :type code: str or ~azure.mgmt.billing.models.ProductTransferValidationErrorCode - :param message: The error message. - :type message: str - :param details: Detailed error message explaining the error. - :type details: str + :ivar code: Error code for the product transfer validation. Known values are: "InvalidSource", + "ProductNotActive", "InsufficientPermissionOnSource", "InsufficientPermissionOnDestination", + "DestinationBillingProfilePastDue", "ProductTypeNotSupported", "CrossBillingAccountNotAllowed", + "NotAvailableForDestinationMarket", and "OneTimePurchaseProductTransferNotAllowed". + :vartype code: str or ~azure.mgmt.billing.models.ProductTransferValidationErrorCode + :ivar message: The error message. + :vartype message: str + :ivar details: Detailed error message explaining the error. + :vartype details: str """ _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'details': {'key': 'details', 'type': 'str'}, + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "details": {"key": "details", "type": "str"}, } def __init__( self, *, - code: Optional[Union[str, "ProductTransferValidationErrorCode"]] = None, + code: Optional[Union[str, "_models.ProductTransferValidationErrorCode"]] = None, message: Optional[str] = None, details: Optional[str] = None, **kwargs ): - super(ValidateProductTransferEligibilityError, self).__init__(**kwargs) + """ + :keyword code: Error code for the product transfer validation. Known values are: + "InvalidSource", "ProductNotActive", "InsufficientPermissionOnSource", + "InsufficientPermissionOnDestination", "DestinationBillingProfilePastDue", + "ProductTypeNotSupported", "CrossBillingAccountNotAllowed", "NotAvailableForDestinationMarket", + and "OneTimePurchaseProductTransferNotAllowed". + :paramtype code: str or ~azure.mgmt.billing.models.ProductTransferValidationErrorCode + :keyword message: The error message. + :paramtype message: str + :keyword details: Detailed error message explaining the error. + :paramtype details: str + """ + super().__init__(**kwargs) self.code = code self.message = message self.details = details -class ValidateProductTransferEligibilityResult(msrest.serialization.Model): +class ValidateProductTransferEligibilityResult(_serialization.Model): """Result of the product transfer eligibility validation. Variables are only populated by the server, and will be ignored when sending a request. :ivar is_move_eligible: Specifies whether the transfer is eligible or not. :vartype is_move_eligible: bool - :param error_details: Validation error details. - :type error_details: ~azure.mgmt.billing.models.ValidateProductTransferEligibilityError + :ivar error_details: Validation error details. + :vartype error_details: ~azure.mgmt.billing.models.ValidateProductTransferEligibilityError """ _validation = { - 'is_move_eligible': {'readonly': True}, + "is_move_eligible": {"readonly": True}, } _attribute_map = { - 'is_move_eligible': {'key': 'isMoveEligible', 'type': 'bool'}, - 'error_details': {'key': 'errorDetails', 'type': 'ValidateProductTransferEligibilityError'}, + "is_move_eligible": {"key": "isMoveEligible", "type": "bool"}, + "error_details": {"key": "errorDetails", "type": "ValidateProductTransferEligibilityError"}, } - def __init__( - self, - *, - error_details: Optional["ValidateProductTransferEligibilityError"] = None, - **kwargs - ): - super(ValidateProductTransferEligibilityResult, self).__init__(**kwargs) + def __init__(self, *, error_details: Optional["_models.ValidateProductTransferEligibilityError"] = None, **kwargs): + """ + :keyword error_details: Validation error details. + :paramtype error_details: ~azure.mgmt.billing.models.ValidateProductTransferEligibilityError + """ + super().__init__(**kwargs) self.is_move_eligible = None self.error_details = error_details -class ValidateSubscriptionTransferEligibilityError(msrest.serialization.Model): +class ValidateSubscriptionTransferEligibilityError(_serialization.Model): """Error details of the transfer eligibility validation. - :param code: Error code for the product transfer validation. Possible values include: + :ivar code: Error code for the product transfer validation. Known values are: "BillingAccountInactive", "CrossBillingAccountNotAllowed", "DestinationBillingProfileInactive", "DestinationBillingProfileNotFound", "DestinationBillingProfilePastDue", "DestinationInvoiceSectionInactive", "DestinationInvoiceSectionNotFound", "InsufficientPermissionOnDestination", "InsufficientPermissionOnSource", "InvalidDestination", "InvalidSource", "MarketplaceNotEnabledOnDestination", "NotAvailableForDestinationMarket", "ProductInactive", "ProductNotFound", "ProductTypeNotSupported", "SourceBillingProfilePastDue", - "SourceInvoiceSectionInactive", "SubscriptionNotActive", "SubscriptionTypeNotSupported". - :type code: str or ~azure.mgmt.billing.models.SubscriptionTransferValidationErrorCode - :param message: The error message. - :type message: str - :param details: Detailed error message explaining the error. - :type details: str + "SourceInvoiceSectionInactive", "SubscriptionNotActive", and "SubscriptionTypeNotSupported". + :vartype code: str or ~azure.mgmt.billing.models.SubscriptionTransferValidationErrorCode + :ivar message: The error message. + :vartype message: str + :ivar details: Detailed error message explaining the error. + :vartype details: str """ _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'details': {'key': 'details', 'type': 'str'}, + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "details": {"key": "details", "type": "str"}, } def __init__( self, *, - code: Optional[Union[str, "SubscriptionTransferValidationErrorCode"]] = None, + code: Optional[Union[str, "_models.SubscriptionTransferValidationErrorCode"]] = None, message: Optional[str] = None, details: Optional[str] = None, **kwargs ): - super(ValidateSubscriptionTransferEligibilityError, self).__init__(**kwargs) + """ + :keyword code: Error code for the product transfer validation. Known values are: + "BillingAccountInactive", "CrossBillingAccountNotAllowed", "DestinationBillingProfileInactive", + "DestinationBillingProfileNotFound", "DestinationBillingProfilePastDue", + "DestinationInvoiceSectionInactive", "DestinationInvoiceSectionNotFound", + "InsufficientPermissionOnDestination", "InsufficientPermissionOnSource", "InvalidDestination", + "InvalidSource", "MarketplaceNotEnabledOnDestination", "NotAvailableForDestinationMarket", + "ProductInactive", "ProductNotFound", "ProductTypeNotSupported", "SourceBillingProfilePastDue", + "SourceInvoiceSectionInactive", "SubscriptionNotActive", and "SubscriptionTypeNotSupported". + :paramtype code: str or ~azure.mgmt.billing.models.SubscriptionTransferValidationErrorCode + :keyword message: The error message. + :paramtype message: str + :keyword details: Detailed error message explaining the error. + :paramtype details: str + """ + super().__init__(**kwargs) self.code = code self.message = message self.details = details -class ValidateSubscriptionTransferEligibilityResult(msrest.serialization.Model): +class ValidateSubscriptionTransferEligibilityResult(_serialization.Model): """Result of the transfer eligibility validation. Variables are only populated by the server, and will be ignored when sending a request. :ivar is_move_eligible: Specifies whether the subscription is eligible to be transferred. :vartype is_move_eligible: bool - :param error_details: Validation error details. - :type error_details: ~azure.mgmt.billing.models.ValidateSubscriptionTransferEligibilityError + :ivar error_details: Validation error details. + :vartype error_details: ~azure.mgmt.billing.models.ValidateSubscriptionTransferEligibilityError """ _validation = { - 'is_move_eligible': {'readonly': True}, + "is_move_eligible": {"readonly": True}, } _attribute_map = { - 'is_move_eligible': {'key': 'isMoveEligible', 'type': 'bool'}, - 'error_details': {'key': 'errorDetails', 'type': 'ValidateSubscriptionTransferEligibilityError'}, + "is_move_eligible": {"key": "isMoveEligible", "type": "bool"}, + "error_details": {"key": "errorDetails", "type": "ValidateSubscriptionTransferEligibilityError"}, } def __init__( - self, - *, - error_details: Optional["ValidateSubscriptionTransferEligibilityError"] = None, - **kwargs + self, *, error_details: Optional["_models.ValidateSubscriptionTransferEligibilityError"] = None, **kwargs ): - super(ValidateSubscriptionTransferEligibilityResult, self).__init__(**kwargs) + """ + :keyword error_details: Validation error details. + :paramtype error_details: + ~azure.mgmt.billing.models.ValidateSubscriptionTransferEligibilityError + """ + super().__init__(**kwargs) self.is_move_eligible = None self.error_details = error_details diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/models/_patch.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/models/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/__init__.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/__init__.py index 7f7bbc76fedb..0f9808051bfd 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/__init__.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/__init__.py @@ -20,34 +20,40 @@ from ._transactions_operations import TransactionsOperations from ._policies_operations import PoliciesOperations from ._billing_property_operations import BillingPropertyOperations -from ._operations import Operations from ._billing_role_definitions_operations import BillingRoleDefinitionsOperations from ._billing_role_assignments_operations import BillingRoleAssignmentsOperations from ._agreements_operations import AgreementsOperations from ._reservations_operations import ReservationsOperations from ._enrollment_accounts_operations import EnrollmentAccountsOperations from ._billing_periods_operations import BillingPeriodsOperations +from ._operations import Operations + +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'BillingAccountsOperations', - 'AddressOperations', - 'AvailableBalancesOperations', - 'InstructionsOperations', - 'BillingProfilesOperations', - 'CustomersOperations', - 'InvoiceSectionsOperations', - 'BillingPermissionsOperations', - 'BillingSubscriptionsOperations', - 'ProductsOperations', - 'InvoicesOperations', - 'TransactionsOperations', - 'PoliciesOperations', - 'BillingPropertyOperations', - 'Operations', - 'BillingRoleDefinitionsOperations', - 'BillingRoleAssignmentsOperations', - 'AgreementsOperations', - 'ReservationsOperations', - 'EnrollmentAccountsOperations', - 'BillingPeriodsOperations', + "BillingAccountsOperations", + "AddressOperations", + "AvailableBalancesOperations", + "InstructionsOperations", + "BillingProfilesOperations", + "CustomersOperations", + "InvoiceSectionsOperations", + "BillingPermissionsOperations", + "BillingSubscriptionsOperations", + "ProductsOperations", + "InvoicesOperations", + "TransactionsOperations", + "PoliciesOperations", + "BillingPropertyOperations", + "BillingRoleDefinitionsOperations", + "BillingRoleAssignmentsOperations", + "AgreementsOperations", + "ReservationsOperations", + "EnrollmentAccountsOperations", + "BillingPeriodsOperations", + "Operations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_address_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_address_operations.py index 57bc172decfd..4c0fb9ab4531 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_address_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_address_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,98 +6,177 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_validate_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/validateAddress") -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Optional, TypeVar + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") -class AddressOperations(object): - """AddressOperations operations. + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. +class AddressOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.BillingManagementClient`'s + :attr:`address` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @overload def validate( - self, - address, # type: "_models.AddressDetails" - **kwargs # type: Any - ): - # type: (...) -> "_models.ValidateAddressResponse" + self, address: _models.AddressDetails, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ValidateAddressResponse: """Validates an address. Use the operation to validate an address before using it as soldTo or a billTo address. - :param address: + :param address: Required. :type address: ~azure.mgmt.billing.models.AddressDetails + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ValidateAddressResponse or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.ValidateAddressResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def validate( + self, address: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ValidateAddressResponse: + """Validates an address. Use the operation to validate an address before using it as soldTo or a + billTo address. + + :param address: Required. + :type address: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ValidateAddressResponse, or the result of cls(response) + :return: ValidateAddressResponse or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateAddressResponse - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def validate(self, address: Union[_models.AddressDetails, IO], **kwargs: Any) -> _models.ValidateAddressResponse: + """Validates an address. Use the operation to validate an address before using it as soldTo or a + billTo address. + + :param address: Is either a model type or a IO type. Required. + :type address: ~azure.mgmt.billing.models.AddressDetails or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ValidateAddressResponse or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.ValidateAddressResponse + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ValidateAddressResponse"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.validate.metadata['url'] # type: ignore - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(address, 'AddressDetails') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidateAddressResponse] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(address, (IO, bytes)): + _content = address + else: + _json = self._serialize.body(address, "AddressDetails") + + request = build_validate_request( + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.validate.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('ValidateAddressResponse', pipeline_response) + deserialized = self._deserialize("ValidateAddressResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - validate.metadata = {'url': '/providers/Microsoft.Billing/validateAddress'} # type: ignore + + validate.metadata = {"url": "/providers/Microsoft.Billing/validateAddress"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_agreements_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_agreements_operations.py index 50c0ee838512..d8ec2a6b920c 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_agreements_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_agreements_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,99 +6,165 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_by_billing_account_request( + billing_account_name: str, *, expand: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/agreements") + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request( + billing_account_name: str, agreement_name: str, *, expand: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/agreements/{agreementName}" + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "agreementName": _SERIALIZER.url("agreement_name", agreement_name, "str"), + } -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + _url = _format_url_section(_url, **path_format_arguments) - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") -class AgreementsOperations(object): - """AgreementsOperations operations. + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + +class AgreementsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.BillingManagementClient`'s + :attr:`agreements` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_by_billing_account( - self, - billing_account_name, # type: str - expand=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.AgreementListResult"] + self, billing_account_name: str, expand: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.Agreement"]: """Lists the agreements for a billing account. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param expand: May be used to expand the participants. + :param expand: May be used to expand the participants. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AgreementListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.AgreementListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Agreement or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Agreement] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AgreementListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AgreementListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_account.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if expand is not None: - query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_account_request( + billing_account_name=billing_account_name, + expand=expand, + api_version=api_version, + template_url=self.list_by_billing_account.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('AgreementListResult', pipeline_response) + deserialized = self._deserialize("AgreementListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -106,81 +173,81 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_billing_account.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/agreements'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/agreements"} # type: ignore + @distributed_trace def get( - self, - billing_account_name, # type: str - agreement_name, # type: str - expand=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> "_models.Agreement" + self, billing_account_name: str, agreement_name: str, expand: Optional[str] = None, **kwargs: Any + ) -> _models.Agreement: """Gets an agreement by ID. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param agreement_name: The ID that uniquely identifies an agreement. + :param agreement_name: The ID that uniquely identifies an agreement. Required. :type agreement_name: str - :param expand: May be used to expand the participants. + :param expand: May be used to expand the participants. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Agreement, or the result of cls(response) + :return: Agreement or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Agreement - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Agreement"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'agreementName': self._serialize.url("agreement_name", agreement_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if expand is not None: - query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Agreement] + + request = build_get_request( + billing_account_name=billing_account_name, + agreement_name=agreement_name, + expand=expand, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Agreement', pipeline_response) + deserialized = self._deserialize("Agreement", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/agreements/{agreementName}'} # type: ignore + + get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/agreements/{agreementName}"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_available_balances_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_available_balances_operations.py index 6c812855a098..fc2e13233686 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_available_balances_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_available_balances_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,102 +6,137 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_request(billing_account_name: str, billing_profile_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/availableBalance/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Optional, TypeVar + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") -class AvailableBalancesOperations(object): - """AvailableBalancesOperations operations. + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. +class AvailableBalancesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.BillingManagementClient`'s + :attr:`available_balances` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def get( - self, - billing_account_name, # type: str - billing_profile_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.AvailableBalance" + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, billing_account_name: str, billing_profile_name: str, **kwargs: Any) -> _models.AvailableBalance: """The available credit balance for a billing profile. This is the balance that can be used for pay now to settle due or past due invoices. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: AvailableBalance, or the result of cls(response) + :return: AvailableBalance or the result of cls(response) :rtype: ~azure.mgmt.billing.models.AvailableBalance - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AvailableBalance"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AvailableBalance] + + request = build_get_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('AvailableBalance', pipeline_response) + deserialized = self._deserialize("AvailableBalance", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/availableBalance/default'} # type: ignore + + get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/availableBalance/default"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_billing_accounts_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_billing_accounts_operations.py index f16bab94220e..b69514371bd7 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_billing_accounts_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_billing_accounts_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,94 +6,207 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(*, expand: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(billing_account_name: str, *, expand: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}") + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_request(billing_account_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}") + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union +def build_list_invoice_sections_by_create_subscription_permission_request( + billing_account_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") -class BillingAccountsOperations(object): - """BillingAccountsOperations operations. + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/listInvoiceSectionsWithCreateSubscriptionPermission", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + } - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + _url = _format_url_section(_url, **path_format_arguments) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class BillingAccountsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.BillingManagementClient`'s + :attr:`billing_accounts` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - def list( - self, - expand=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.BillingAccountListResult"] + @distributed_trace + def list(self, expand: Optional[str] = None, **kwargs: Any) -> Iterable["_models.BillingAccount"]: """Lists the billing accounts that a user has access to. - :param expand: May be used to expand the soldTo, invoice sections and billing profiles. + :param expand: May be used to expand the soldTo, invoice sections and billing profiles. Default + value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either BillingAccountListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingAccountListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either BillingAccount or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingAccount] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingAccountListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingAccountListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if expand is not None: - query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + expand=expand, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('BillingAccountListResult', pipeline_response) + deserialized = self._deserialize("BillingAccountListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -101,254 +215,336 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts'} # type: ignore + return ItemPaged(get_next, extract_data) - def get( - self, - billing_account_name, # type: str - expand=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> "_models.BillingAccount" + list.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts"} # type: ignore + + @distributed_trace + def get(self, billing_account_name: str, expand: Optional[str] = None, **kwargs: Any) -> _models.BillingAccount: """Gets a billing account by its ID. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param expand: May be used to expand the soldTo, invoice sections and billing profiles. + :param expand: May be used to expand the soldTo, invoice sections and billing profiles. Default + value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: BillingAccount, or the result of cls(response) + :return: BillingAccount or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingAccount - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingAccount"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if expand is not None: - query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingAccount] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_request( + billing_account_name=billing_account_name, + expand=expand, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('BillingAccount', pipeline_response) + deserialized = self._deserialize("BillingAccount", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}'} # type: ignore + + get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}"} # type: ignore def _update_initial( - self, - billing_account_name, # type: str - parameters, # type: "_models.BillingAccountUpdateRequest" - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.BillingAccount"] - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.BillingAccount"]] + self, billing_account_name: str, parameters: Union[_models.BillingAccountUpdateRequest, IO], **kwargs: Any + ) -> Optional[_models.BillingAccount]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self._update_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'BillingAccountUpdateRequest') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.BillingAccount]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "BillingAccountUpdateRequest") + + request = build_update_request( + billing_account_name=billing_account_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._update_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('BillingAccount', pipeline_response) + deserialized = self._deserialize("BillingAccount", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _update_initial.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}'} # type: ignore + _update_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}"} # type: ignore + + @overload def begin_update( self, - billing_account_name, # type: str - parameters, # type: "_models.BillingAccountUpdateRequest" - **kwargs # type: Any - ): - # type: (...) -> LROPoller["_models.BillingAccount"] + billing_account_name: str, + parameters: _models.BillingAccountUpdateRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.BillingAccount]: """Updates the properties of a billing account. Currently, displayName and address can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the update billing account - operation. + operation. Required. :type parameters: ~azure.mgmt.billing.models.BillingAccountUpdateRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: Pass in True if you'd like the ARMPolling polling method, - False for no polling, or your own initialized polling object for a personal polling strategy. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - :return: An instance of LROPoller that returns either BillingAccount or the result of cls(response) + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either BillingAccount or the result of + cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.BillingAccount] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingAccount"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + def begin_update( + self, billing_account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[_models.BillingAccount]: + """Updates the properties of a billing account. Currently, displayName and address can be updated. + The operation is supported only for billing accounts with agreement type Microsoft Customer + Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param parameters: Request parameters that are provided to the update billing account + operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either BillingAccount or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.BillingAccount] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update( + self, billing_account_name: str, parameters: Union[_models.BillingAccountUpdateRequest, IO], **kwargs: Any + ) -> LROPoller[_models.BillingAccount]: + """Updates the properties of a billing account. Currently, displayName and address can be updated. + The operation is supported only for billing accounts with agreement type Microsoft Customer + Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param parameters: Request parameters that are provided to the update billing account + operation. Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.billing.models.BillingAccountUpdateRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either BillingAccount or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.BillingAccount] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingAccount] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._update_initial( + raw_result = self._update_initial( # type: ignore billing_account_name=billing_account_name, parameters=parameters, - cls=lambda x,y,z: x, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('BillingAccount', pipeline_response) - + deserialized = self._deserialize("BillingAccount", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - } - - if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_update.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}'} # type: ignore + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}"} # type: ignore + + @distributed_trace def list_invoice_sections_by_create_subscription_permission( - self, - billing_account_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.InvoiceSectionListWithCreateSubPermissionResult"] + self, billing_account_name: str, **kwargs: Any + ) -> Iterable["_models.InvoiceSectionWithCreateSubPermission"]: """Lists the invoice sections for which the user has permission to create Azure subscriptions. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either InvoiceSectionListWithCreateSubPermissionResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.InvoiceSectionListWithCreateSubPermissionResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either InvoiceSectionWithCreateSubPermission or the + result of cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.InvoiceSectionWithCreateSubPermission] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.InvoiceSectionListWithCreateSubPermissionResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceSectionListWithCreateSubPermissionResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_invoice_sections_by_create_subscription_permission.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + + request = build_list_invoice_sections_by_create_subscription_permission_request( + billing_account_name=billing_account_name, + api_version=api_version, + template_url=self.list_invoice_sections_by_create_subscription_permission.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('InvoiceSectionListWithCreateSubPermissionResult', pipeline_response) + deserialized = self._deserialize("InvoiceSectionListWithCreateSubPermissionResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -357,17 +553,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_invoice_sections_by_create_subscription_permission.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/listInvoiceSectionsWithCreateSubscriptionPermission'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_invoice_sections_by_create_subscription_permission.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/listInvoiceSectionsWithCreateSubscriptionPermission"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_billing_periods_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_billing_periods_operations.py index f14d0fb7b717..b42d5cdc42b0 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_billing_periods_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_billing_periods_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,112 +6,182 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False -class BillingPeriodsOperations(object): - """BillingPeriodsOperations operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +def build_list_request( + subscription_id: str, + *, + filter: Optional[str] = None, + skiptoken: Optional[str] = None, + top: Optional[int] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingPeriods") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if skiptoken is not None: + _params["$skiptoken"] = _SERIALIZER.query("skiptoken", skiptoken, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", maximum=100, minimum=1) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(billing_period_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}" + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "billingPeriodName": _SERIALIZER.url("billing_period_name", billing_period_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class BillingPeriodsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.BillingManagementClient`'s + :attr:`billing_periods` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list( - self, - filter=None, # type: Optional[str] - skiptoken=None, # type: Optional[str] - top=None, # type: Optional[int] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.BillingPeriodsListResult"] + self, filter: Optional[str] = None, skiptoken: Optional[str] = None, top: Optional[int] = None, **kwargs: Any + ) -> Iterable["_models.BillingPeriod"]: """Lists the available billing periods for a subscription in reverse chronological order. This is only supported for Azure Web-Direct subscriptions. Other subscription types which were not purchased directly through the Azure web portal are not supported through this preview API. :param filter: May be used to filter billing periods by billingPeriodEndDate. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or - 'not'. + 'not'. Default value is None. :type filter: str :param skiptoken: Skiptoken is only used if a previous operation returned a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include - a skiptoken parameter that specifies a starting point to use for subsequent calls. + a skiptoken parameter that specifies a starting point to use for subsequent calls. Default + value is None. :type skiptoken: str :param top: May be used to limit the number of results to the most recent N billing periods. + Default value is None. :type top: int :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either BillingPeriodsListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingPeriodsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either BillingPeriod or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingPeriod] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingPeriodsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPeriodsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-03-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - if skiptoken is not None: - query_parameters['$skiptoken'] = self._serialize.query("skiptoken", skiptoken, 'str') - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int', maximum=100, minimum=1) - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_request( + subscription_id=self._config.subscription_id, + filter=filter, + skiptoken=skiptoken, + top=top, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('BillingPeriodsListResult', pipeline_response) + deserialized = self._deserialize("BillingPeriodsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -119,75 +190,76 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingPeriods'} # type: ignore - - def get( - self, - billing_period_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.BillingPeriod" + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingPeriods"} # type: ignore + + @distributed_trace + def get(self, billing_period_name: str, **kwargs: Any) -> _models.BillingPeriod: """Gets a named billing period. This is only supported for Azure Web-Direct subscriptions. Other subscription types which were not purchased directly through the Azure web portal are not supported through this preview API. - :param billing_period_name: The name of a BillingPeriod resource. + :param billing_period_name: The name of a BillingPeriod resource. Required. :type billing_period_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: BillingPeriod, or the result of cls(response) + :return: BillingPeriod or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingPeriod - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingPeriod"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-03-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'billingPeriodName': self._serialize.url("billing_period_name", billing_period_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPeriod] + + request = build_get_request( + billing_period_name=billing_period_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('BillingPeriod', pipeline_response) + deserialized = self._deserialize("BillingPeriod", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}'} # type: ignore + + get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingPeriods/{billingPeriodName}"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_billing_permissions_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_billing_permissions_operations.py index aed9a76bc326..46c4037380a2 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_billing_permissions_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_billing_permissions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,98 +6,222 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_by_customer_request(billing_account_name: str, customer_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/billingPermissions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "customerName": _SERIALIZER.url("customer_name", customer_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_billing_account_request(billing_account_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingPermissions" + ) + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_invoice_sections_request( + billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingPermissions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), + "invoiceSectionName": _SERIALIZER.url("invoice_section_name", invoice_section_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_billing_profile_request( + billing_account_name: str, billing_profile_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingPermissions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), + } -class BillingPermissionsOperations(object): - """BillingPermissionsOperations operations. + _url = _format_url_section(_url, **path_format_arguments) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class BillingPermissionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.BillingManagementClient`'s + :attr:`billing_permissions` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_by_customer( - self, - billing_account_name, # type: str - customer_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.BillingPermissionsListResult"] + self, billing_account_name: str, customer_name: str, **kwargs: Any + ) -> Iterable["_models.BillingPermissionsProperties"]: """Lists the billing permissions the caller has for a customer. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param customer_name: The ID that uniquely identifies a customer. + :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either BillingPermissionsListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingPermissionsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either BillingPermissionsProperties or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingPermissionsProperties] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingPermissionsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPermissionsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_customer.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'customerName': self._serialize.url("customer_name", customer_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_customer_request( + billing_account_name=billing_account_name, + customer_name=customer_name, + api_version=api_version, + template_url=self.list_by_customer.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('BillingPermissionsListResult', pipeline_response) + deserialized = self._deserialize("BillingPermissionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -105,69 +230,72 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_customer.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/billingPermissions'} # type: ignore + return ItemPaged(get_next, extract_data) + list_by_customer.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/billingPermissions"} # type: ignore + + @distributed_trace def list_by_billing_account( - self, - billing_account_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.BillingPermissionsListResult"] + self, billing_account_name: str, **kwargs: Any + ) -> Iterable["_models.BillingPermissionsProperties"]: """Lists the billing permissions the caller has on a billing account. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either BillingPermissionsListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingPermissionsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either BillingPermissionsProperties or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingPermissionsProperties] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingPermissionsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPermissionsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_account.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_account_request( + billing_account_name=billing_account_name, + api_version=api_version, + template_url=self.list_by_billing_account.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('BillingPermissionsListResult', pipeline_response) + deserialized = self._deserialize("BillingPermissionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -176,77 +304,78 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_billing_account.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingPermissions'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingPermissions"} # type: ignore + @distributed_trace def list_by_invoice_sections( - self, - billing_account_name, # type: str - billing_profile_name, # type: str - invoice_section_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.BillingPermissionsListResult"] + self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any + ) -> Iterable["_models.BillingPermissionsProperties"]: """Lists the billing permissions the caller has on an invoice section. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str - :param invoice_section_name: The ID that uniquely identifies an invoice section. + :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either BillingPermissionsListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingPermissionsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either BillingPermissionsProperties or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingPermissionsProperties] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingPermissionsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPermissionsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_invoice_sections.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - 'invoiceSectionName': self._serialize.url("invoice_section_name", invoice_section_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_invoice_sections_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + invoice_section_name=invoice_section_name, + api_version=api_version, + template_url=self.list_by_invoice_sections.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('BillingPermissionsListResult', pipeline_response) + deserialized = self._deserialize("BillingPermissionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -255,73 +384,75 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_invoice_sections.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingPermissions'} # type: ignore + return ItemPaged(get_next, extract_data) + list_by_invoice_sections.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingPermissions"} # type: ignore + + @distributed_trace def list_by_billing_profile( - self, - billing_account_name, # type: str - billing_profile_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.BillingPermissionsListResult"] + self, billing_account_name: str, billing_profile_name: str, **kwargs: Any + ) -> Iterable["_models.BillingPermissionsProperties"]: """Lists the billing permissions the caller has on a billing profile. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either BillingPermissionsListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingPermissionsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either BillingPermissionsProperties or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingPermissionsProperties] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingPermissionsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingPermissionsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_profile.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_profile_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + api_version=api_version, + template_url=self.list_by_billing_profile.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('BillingPermissionsListResult', pipeline_response) + deserialized = self._deserialize("BillingPermissionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -330,17 +461,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_billing_profile.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingPermissions'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingPermissions"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_billing_profiles_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_billing_profiles_operations.py index 355606d61b54..10ff90655b36 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_billing_profiles_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_billing_profiles_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,102 +6,202 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_by_billing_account_request( + billing_account_name: str, *, expand: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles" + ) + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request( + billing_account_name: str, billing_profile_name: str, *, expand: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request(billing_account_name: str, billing_profile_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), + } -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + _url = _format_url_section(_url, **path_format_arguments) - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") -class BillingProfilesOperations(object): - """BillingProfilesOperations operations. + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + +class BillingProfilesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.BillingManagementClient`'s + :attr:`billing_profiles` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_by_billing_account( - self, - billing_account_name, # type: str - expand=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.BillingProfileListResult"] + self, billing_account_name: str, expand: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.BillingProfile"]: """Lists the billing profiles that a user has access to. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param expand: May be used to expand the invoice sections. + :param expand: May be used to expand the invoice sections. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either BillingProfileListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingProfileListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either BillingProfile or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingProfile] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingProfileListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingProfileListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_account.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if expand is not None: - query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_account_request( + billing_account_name=billing_account_name, + expand=expand, + api_version=api_version, + template_url=self.list_by_billing_account.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('BillingProfileListResult', pipeline_response) + deserialized = self._deserialize("BillingProfileListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -109,215 +210,305 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_billing_account.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles'} # type: ignore + return ItemPaged(get_next, extract_data) + list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles"} # type: ignore + + @distributed_trace def get( - self, - billing_account_name, # type: str - billing_profile_name, # type: str - expand=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> "_models.BillingProfile" + self, billing_account_name: str, billing_profile_name: str, expand: Optional[str] = None, **kwargs: Any + ) -> _models.BillingProfile: """Gets a billing profile by its ID. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str - :param expand: May be used to expand the invoice sections. + :param expand: May be used to expand the invoice sections. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: BillingProfile, or the result of cls(response) + :return: BillingProfile or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingProfile - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingProfile"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if expand is not None: - query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingProfile] + + request = build_get_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + expand=expand, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('BillingProfile', pipeline_response) + deserialized = self._deserialize("BillingProfile", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}'} # type: ignore + + get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}"} # type: ignore def _create_or_update_initial( self, - billing_account_name, # type: str - billing_profile_name, # type: str - parameters, # type: "_models.BillingProfile" - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.BillingProfile"] - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.BillingProfile"]] + billing_account_name: str, + billing_profile_name: str, + parameters: Union[_models.BillingProfile, IO], + **kwargs: Any + ) -> Optional[_models.BillingProfile]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self._create_or_update_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'BillingProfile') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.BillingProfile]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "BillingProfile") + + request = build_create_or_update_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - response_headers = {} deserialized = None + response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('BillingProfile', pipeline_response) + deserialized = self._deserialize("BillingProfile", pipeline_response) if response.status_code == 202: - response_headers['Location']=self._deserialize('str', response.headers.get('Location')) - response_headers['Retry-After']=self._deserialize('int', response.headers.get('Retry-After')) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized - _create_or_update_initial.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}'} # type: ignore + _create_or_update_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}"} # type: ignore + + @overload def begin_create_or_update( self, - billing_account_name, # type: str - billing_profile_name, # type: str - parameters, # type: "_models.BillingProfile" - **kwargs # type: Any - ): - # type: (...) -> LROPoller["_models.BillingProfile"] + billing_account_name: str, + billing_profile_name: str, + parameters: _models.BillingProfile, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.BillingProfile]: """Creates or updates a billing profile. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str - :param parameters: The new or updated billing profile. + :param parameters: The new or updated billing profile. Required. :type parameters: ~azure.mgmt.billing.models.BillingProfile + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: Pass in True if you'd like the ARMPolling polling method, - False for no polling, or your own initialized polling object for a personal polling strategy. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - :return: An instance of LROPoller that returns either BillingProfile or the result of cls(response) + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either BillingProfile or the result of + cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.BillingProfile] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingProfile"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + def begin_create_or_update( + self, + billing_account_name: str, + billing_profile_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.BillingProfile]: + """Creates or updates a billing profile. The operation is supported for billing accounts with + agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. + :type billing_profile_name: str + :param parameters: The new or updated billing profile. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either BillingProfile or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.BillingProfile] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + billing_account_name: str, + billing_profile_name: str, + parameters: Union[_models.BillingProfile, IO], + **kwargs: Any + ) -> LROPoller[_models.BillingProfile]: + """Creates or updates a billing profile. The operation is supported for billing accounts with + agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. + :type billing_profile_name: str + :param parameters: The new or updated billing profile. Is either a model type or a IO type. + Required. + :type parameters: ~azure.mgmt.billing.models.BillingProfile or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either BillingProfile or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.BillingProfile] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingProfile] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._create_or_update_initial( + raw_result = self._create_or_update_initial( # type: ignore billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, parameters=parameters, - cls=lambda x,y,z: x, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('BillingProfile', pipeline_response) - + deserialized = self._deserialize("BillingProfile", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - } - - if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}'} # type: ignore + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_or_update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_billing_property_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_billing_property_operations.py index 27b207d37848..1ac4cc46a6a7 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_billing_property_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_billing_property_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,157 +6,271 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Optional, TypeVar +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False -class BillingPropertyOperations(object): - """BillingPropertyOperations operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +def build_get_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingProperty/default" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingProperty/default" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +class BillingPropertyOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.BillingManagementClient`'s + :attr:`billing_property` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def get( - self, - **kwargs # type: Any - ): - # type: (...) -> "_models.BillingProperty" + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, **kwargs: Any) -> _models.BillingProperty: """Get the billing properties for a subscription. This operation is not supported for billing accounts with agreement type Enterprise Agreement. :keyword callable cls: A custom type or function that will be passed the direct response - :return: BillingProperty, or the result of cls(response) + :return: BillingProperty or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingProperty - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingProperty"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingProperty] + + request = build_get_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('BillingProperty', pipeline_response) + deserialized = self._deserialize("BillingProperty", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingProperty/default'} # type: ignore + get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingProperty/default"} # type: ignore + + @overload def update( - self, - parameters, # type: "_models.BillingProperty" - **kwargs # type: Any - ): - # type: (...) -> "_models.BillingProperty" + self, parameters: _models.BillingProperty, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.BillingProperty: """Updates the billing property of a subscription. Currently, cost center can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. :param parameters: Request parameters that are provided to the update billing property - operation. + operation. Required. :type parameters: ~azure.mgmt.billing.models.BillingProperty + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: BillingProperty, or the result of cls(response) + :return: BillingProperty or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingProperty - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update( + self, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.BillingProperty: + """Updates the billing property of a subscription. Currently, cost center can be updated. The + operation is supported only for billing accounts with agreement type Microsoft Customer + Agreement. + + :param parameters: Request parameters that are provided to the update billing property + operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: BillingProperty or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.BillingProperty + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update(self, parameters: Union[_models.BillingProperty, IO], **kwargs: Any) -> _models.BillingProperty: + """Updates the billing property of a subscription. Currently, cost center can be updated. The + operation is supported only for billing accounts with agreement type Microsoft Customer + Agreement. + + :param parameters: Request parameters that are provided to the update billing property + operation. Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.billing.models.BillingProperty or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: BillingProperty or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.BillingProperty + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingProperty"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.update.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'BillingProperty') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingProperty] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "BillingProperty") + + request = build_update_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('BillingProperty', pipeline_response) + deserialized = self._deserialize("BillingProperty", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingProperty/default'} # type: ignore + + update.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Billing/billingProperty/default"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_billing_role_assignments_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_billing_role_assignments_operations.py index 3ab2113a6808..4fef173c0617 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_billing_role_assignments_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_billing_role_assignments_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,484 +6,803 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_by_billing_account_request( + billing_account_name: str, billing_role_assignment_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments/{billingRoleAssignmentName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "billingRoleAssignmentName": _SERIALIZER.url( + "billing_role_assignment_name", billing_role_assignment_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_by_billing_account_request( + billing_account_name: str, billing_role_assignment_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments/{billingRoleAssignmentName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "billingRoleAssignmentName": _SERIALIZER.url( + "billing_role_assignment_name", billing_role_assignment_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_invoice_section_request( + billing_account_name: str, + billing_profile_name: str, + invoice_section_name: str, + billing_role_assignment_name: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments/{billingRoleAssignmentName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), + "invoiceSectionName": _SERIALIZER.url("invoice_section_name", invoice_section_name, "str"), + "billingRoleAssignmentName": _SERIALIZER.url( + "billing_role_assignment_name", billing_role_assignment_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_by_invoice_section_request( + billing_account_name: str, + billing_profile_name: str, + invoice_section_name: str, + billing_role_assignment_name: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments/{billingRoleAssignmentName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), + "invoiceSectionName": _SERIALIZER.url("invoice_section_name", invoice_section_name, "str"), + "billingRoleAssignmentName": _SERIALIZER.url( + "billing_role_assignment_name", billing_role_assignment_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_billing_profile_request( + billing_account_name: str, billing_profile_name: str, billing_role_assignment_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments/{billingRoleAssignmentName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), + "billingRoleAssignmentName": _SERIALIZER.url( + "billing_role_assignment_name", billing_role_assignment_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_by_billing_profile_request( + billing_account_name: str, billing_profile_name: str, billing_role_assignment_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments/{billingRoleAssignmentName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), + "billingRoleAssignmentName": _SERIALIZER.url( + "billing_role_assignment_name", billing_role_assignment_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_billing_account_request(billing_account_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments" + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_invoice_section_request( + billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), + "invoiceSectionName": _SERIALIZER.url("invoice_section_name", invoice_section_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +def build_list_by_billing_profile_request( + billing_account_name: str, billing_profile_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) -class BillingRoleAssignmentsOperations(object): - """BillingRoleAssignmentsOperations operations. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), + } - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class BillingRoleAssignmentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.BillingManagementClient`'s + :attr:`billing_role_assignments` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def get_by_billing_account( - self, - billing_account_name, # type: str - billing_role_assignment_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.BillingRoleAssignment" + self, billing_account_name: str, billing_role_assignment_name: str, **kwargs: Any + ) -> _models.BillingRoleAssignment: """Gets a role assignment for the caller on a billing account. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. + Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: BillingRoleAssignment, or the result of cls(response) + :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingRoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get_by_billing_account.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingRoleAssignmentName': self._serialize.url("billing_role_assignment_name", billing_role_assignment_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_get_by_billing_account_request( + billing_account_name=billing_account_name, + billing_role_assignment_name=billing_role_assignment_name, + api_version=api_version, + template_url=self.get_by_billing_account.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('BillingRoleAssignment', pipeline_response) + deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_billing_account.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments/{billingRoleAssignmentName}'} # type: ignore + get_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore + + @distributed_trace def delete_by_billing_account( - self, - billing_account_name, # type: str - billing_role_assignment_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.BillingRoleAssignment" + self, billing_account_name: str, billing_role_assignment_name: str, **kwargs: Any + ) -> _models.BillingRoleAssignment: """Deletes a role assignment for the caller on a billing account. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. + Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: BillingRoleAssignment, or the result of cls(response) + :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingRoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.delete_by_billing_account.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingRoleAssignmentName': self._serialize.url("billing_role_assignment_name", billing_role_assignment_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] + + request = build_delete_by_billing_account_request( + billing_account_name=billing_account_name, + billing_role_assignment_name=billing_role_assignment_name, + api_version=api_version, + template_url=self.delete_by_billing_account.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('BillingRoleAssignment', pipeline_response) + deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete_by_billing_account.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments/{billingRoleAssignmentName}'} # type: ignore + delete_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore + + @distributed_trace def get_by_invoice_section( self, - billing_account_name, # type: str - billing_profile_name, # type: str - invoice_section_name, # type: str - billing_role_assignment_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.BillingRoleAssignment" + billing_account_name: str, + billing_profile_name: str, + invoice_section_name: str, + billing_role_assignment_name: str, + **kwargs: Any + ) -> _models.BillingRoleAssignment: """Gets a role assignment for the caller on an invoice section. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str - :param invoice_section_name: The ID that uniquely identifies an invoice section. + :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. + Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: BillingRoleAssignment, or the result of cls(response) + :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingRoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get_by_invoice_section.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - 'invoiceSectionName': self._serialize.url("invoice_section_name", invoice_section_name, 'str'), - 'billingRoleAssignmentName': self._serialize.url("billing_role_assignment_name", billing_role_assignment_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] + + request = build_get_by_invoice_section_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + invoice_section_name=invoice_section_name, + billing_role_assignment_name=billing_role_assignment_name, + api_version=api_version, + template_url=self.get_by_invoice_section.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('BillingRoleAssignment', pipeline_response) + deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_invoice_section.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments/{billingRoleAssignmentName}'} # type: ignore + get_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore + + @distributed_trace def delete_by_invoice_section( self, - billing_account_name, # type: str - billing_profile_name, # type: str - invoice_section_name, # type: str - billing_role_assignment_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.BillingRoleAssignment" + billing_account_name: str, + billing_profile_name: str, + invoice_section_name: str, + billing_role_assignment_name: str, + **kwargs: Any + ) -> _models.BillingRoleAssignment: """Deletes a role assignment for the caller on an invoice section. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str - :param invoice_section_name: The ID that uniquely identifies an invoice section. + :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. + Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: BillingRoleAssignment, or the result of cls(response) + :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingRoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.delete_by_invoice_section.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - 'invoiceSectionName': self._serialize.url("invoice_section_name", invoice_section_name, 'str'), - 'billingRoleAssignmentName': self._serialize.url("billing_role_assignment_name", billing_role_assignment_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] + + request = build_delete_by_invoice_section_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + invoice_section_name=invoice_section_name, + billing_role_assignment_name=billing_role_assignment_name, + api_version=api_version, + template_url=self.delete_by_invoice_section.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('BillingRoleAssignment', pipeline_response) + deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete_by_invoice_section.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments/{billingRoleAssignmentName}'} # type: ignore + delete_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore + + @distributed_trace def get_by_billing_profile( - self, - billing_account_name, # type: str - billing_profile_name, # type: str - billing_role_assignment_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.BillingRoleAssignment" + self, billing_account_name: str, billing_profile_name: str, billing_role_assignment_name: str, **kwargs: Any + ) -> _models.BillingRoleAssignment: """Gets a role assignment for the caller on a billing profile. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. + Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: BillingRoleAssignment, or the result of cls(response) + :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingRoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get_by_billing_profile.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - 'billingRoleAssignmentName': self._serialize.url("billing_role_assignment_name", billing_role_assignment_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] + + request = build_get_by_billing_profile_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + billing_role_assignment_name=billing_role_assignment_name, + api_version=api_version, + template_url=self.get_by_billing_profile.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('BillingRoleAssignment', pipeline_response) + deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_billing_profile.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments/{billingRoleAssignmentName}'} # type: ignore + get_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore + + @distributed_trace def delete_by_billing_profile( - self, - billing_account_name, # type: str - billing_profile_name, # type: str - billing_role_assignment_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.BillingRoleAssignment" + self, billing_account_name: str, billing_profile_name: str, billing_role_assignment_name: str, **kwargs: Any + ) -> _models.BillingRoleAssignment: """Deletes a role assignment for the caller on a billing profile. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param billing_role_assignment_name: The ID that uniquely identifies a role assignment. + Required. :type billing_role_assignment_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: BillingRoleAssignment, or the result of cls(response) + :return: BillingRoleAssignment or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleAssignment - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingRoleAssignment"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.delete_by_billing_profile.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - 'billingRoleAssignmentName': self._serialize.url("billing_role_assignment_name", billing_role_assignment_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignment] + + request = build_delete_by_billing_profile_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + billing_role_assignment_name=billing_role_assignment_name, + api_version=api_version, + template_url=self.delete_by_billing_profile.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('BillingRoleAssignment', pipeline_response) + deserialized = self._deserialize("BillingRoleAssignment", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete_by_billing_profile.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments/{billingRoleAssignmentName}'} # type: ignore + delete_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments/{billingRoleAssignmentName}"} # type: ignore + + @distributed_trace def list_by_billing_account( - self, - billing_account_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.BillingRoleAssignmentListResult"] + self, billing_account_name: str, **kwargs: Any + ) -> Iterable["_models.BillingRoleAssignment"]: """Lists the role assignments for the caller on a billing account. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either BillingRoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingRoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either BillingRoleAssignment or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingRoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingRoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_account.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_account_request( + billing_account_name=billing_account_name, + api_version=api_version, + template_url=self.list_by_billing_account.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('BillingRoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("BillingRoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -491,78 +811,79 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_billing_account.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments"} # type: ignore + @distributed_trace def list_by_invoice_section( - self, - billing_account_name, # type: str - billing_profile_name, # type: str - invoice_section_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.BillingRoleAssignmentListResult"] + self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any + ) -> Iterable["_models.BillingRoleAssignment"]: """Lists the role assignments for the caller on an invoice section. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str - :param invoice_section_name: The ID that uniquely identifies an invoice section. + :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either BillingRoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingRoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either BillingRoleAssignment or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingRoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingRoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_invoice_section.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - 'invoiceSectionName': self._serialize.url("invoice_section_name", invoice_section_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_invoice_section_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + invoice_section_name=invoice_section_name, + api_version=api_version, + template_url=self.list_by_invoice_section.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('BillingRoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("BillingRoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -571,74 +892,76 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_invoice_section.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleAssignments"} # type: ignore + @distributed_trace def list_by_billing_profile( - self, - billing_account_name, # type: str - billing_profile_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.BillingRoleAssignmentListResult"] + self, billing_account_name: str, billing_profile_name: str, **kwargs: Any + ) -> Iterable["_models.BillingRoleAssignment"]: """Lists the role assignments for the caller on a billing profile. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either BillingRoleAssignmentListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingRoleAssignmentListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either BillingRoleAssignment or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingRoleAssignment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingRoleAssignmentListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleAssignmentListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_profile.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_profile_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + api_version=api_version, + template_url=self.list_by_billing_profile.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('BillingRoleAssignmentListResult', pipeline_response) + deserialized = self._deserialize("BillingRoleAssignmentListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -647,17 +970,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_billing_profile.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_billing_role_definitions_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_billing_role_definitions_operations.py index 1c6ebe650d73..cf6ea4f72f64 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_billing_role_definitions_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_billing_role_definitions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,287 +6,495 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_by_billing_account_request( + billing_account_name: str, billing_role_definition_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleDefinitions/{billingRoleDefinitionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "billingRoleDefinitionName": _SERIALIZER.url( + "billing_role_definition_name", billing_role_definition_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_invoice_section_request( + billing_account_name: str, + billing_profile_name: str, + invoice_section_name: str, + billing_role_definition_name: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleDefinitions/{billingRoleDefinitionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), + "invoiceSectionName": _SERIALIZER.url("invoice_section_name", invoice_section_name, "str"), + "billingRoleDefinitionName": _SERIALIZER.url( + "billing_role_definition_name", billing_role_definition_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_billing_profile_request( + billing_account_name: str, billing_profile_name: str, billing_role_definition_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleDefinitions/{billingRoleDefinitionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), + "billingRoleDefinitionName": _SERIALIZER.url( + "billing_role_definition_name", billing_role_definition_name, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +def build_list_by_billing_account_request(billing_account_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) -class BillingRoleDefinitionsOperations(object): - """BillingRoleDefinitionsOperations operations. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + # Construct URL + _url = kwargs.pop( + "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleDefinitions" + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + } - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_invoice_section_request( + billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleDefinitions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), + "invoiceSectionName": _SERIALIZER.url("invoice_section_name", invoice_section_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_billing_profile_request( + billing_account_name: str, billing_profile_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleDefinitions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class BillingRoleDefinitionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.BillingManagementClient`'s + :attr:`billing_role_definitions` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def get_by_billing_account( - self, - billing_account_name, # type: str - billing_role_definition_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.BillingRoleDefinition" + self, billing_account_name: str, billing_role_definition_name: str, **kwargs: Any + ) -> _models.BillingRoleDefinition: """Gets the definition for a role on a billing account. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param billing_role_definition_name: The ID that uniquely identifies a role definition. + Required. :type billing_role_definition_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: BillingRoleDefinition, or the result of cls(response) + :return: BillingRoleDefinition or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleDefinition - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingRoleDefinition"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get_by_billing_account.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingRoleDefinitionName': self._serialize.url("billing_role_definition_name", billing_role_definition_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinition] + + request = build_get_by_billing_account_request( + billing_account_name=billing_account_name, + billing_role_definition_name=billing_role_definition_name, + api_version=api_version, + template_url=self.get_by_billing_account.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('BillingRoleDefinition', pipeline_response) + deserialized = self._deserialize("BillingRoleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_billing_account.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleDefinitions/{billingRoleDefinitionName}'} # type: ignore + get_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleDefinitions/{billingRoleDefinitionName}"} # type: ignore + + @distributed_trace def get_by_invoice_section( self, - billing_account_name, # type: str - billing_profile_name, # type: str - invoice_section_name, # type: str - billing_role_definition_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.BillingRoleDefinition" + billing_account_name: str, + billing_profile_name: str, + invoice_section_name: str, + billing_role_definition_name: str, + **kwargs: Any + ) -> _models.BillingRoleDefinition: """Gets the definition for a role on an invoice section. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str - :param invoice_section_name: The ID that uniquely identifies an invoice section. + :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param billing_role_definition_name: The ID that uniquely identifies a role definition. + Required. :type billing_role_definition_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: BillingRoleDefinition, or the result of cls(response) + :return: BillingRoleDefinition or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleDefinition - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingRoleDefinition"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get_by_invoice_section.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - 'invoiceSectionName': self._serialize.url("invoice_section_name", invoice_section_name, 'str'), - 'billingRoleDefinitionName': self._serialize.url("billing_role_definition_name", billing_role_definition_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinition] + + request = build_get_by_invoice_section_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + invoice_section_name=invoice_section_name, + billing_role_definition_name=billing_role_definition_name, + api_version=api_version, + template_url=self.get_by_invoice_section.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('BillingRoleDefinition', pipeline_response) + deserialized = self._deserialize("BillingRoleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_invoice_section.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleDefinitions/{billingRoleDefinitionName}'} # type: ignore + get_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleDefinitions/{billingRoleDefinitionName}"} # type: ignore + + @distributed_trace def get_by_billing_profile( - self, - billing_account_name, # type: str - billing_profile_name, # type: str - billing_role_definition_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.BillingRoleDefinition" + self, billing_account_name: str, billing_profile_name: str, billing_role_definition_name: str, **kwargs: Any + ) -> _models.BillingRoleDefinition: """Gets the definition for a role on a billing profile. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param billing_role_definition_name: The ID that uniquely identifies a role definition. + Required. :type billing_role_definition_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: BillingRoleDefinition, or the result of cls(response) + :return: BillingRoleDefinition or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingRoleDefinition - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingRoleDefinition"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get_by_billing_profile.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - 'billingRoleDefinitionName': self._serialize.url("billing_role_definition_name", billing_role_definition_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinition] + + request = build_get_by_billing_profile_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + billing_role_definition_name=billing_role_definition_name, + api_version=api_version, + template_url=self.get_by_billing_profile.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('BillingRoleDefinition', pipeline_response) + deserialized = self._deserialize("BillingRoleDefinition", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_billing_profile.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleDefinitions/{billingRoleDefinitionName}'} # type: ignore + get_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleDefinitions/{billingRoleDefinitionName}"} # type: ignore + + @distributed_trace def list_by_billing_account( - self, - billing_account_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.BillingRoleDefinitionListResult"] + self, billing_account_name: str, **kwargs: Any + ) -> Iterable["_models.BillingRoleDefinition"]: """Lists the role definitions for a billing account. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either BillingRoleDefinitionListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingRoleDefinitionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either BillingRoleDefinition or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingRoleDefinition] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingRoleDefinitionListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinitionListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_account.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_account_request( + billing_account_name=billing_account_name, + api_version=api_version, + template_url=self.list_by_billing_account.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('BillingRoleDefinitionListResult', pipeline_response) + deserialized = self._deserialize("BillingRoleDefinitionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -294,78 +503,79 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_billing_account.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleDefinitions'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleDefinitions"} # type: ignore + @distributed_trace def list_by_invoice_section( - self, - billing_account_name, # type: str - billing_profile_name, # type: str - invoice_section_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.BillingRoleDefinitionListResult"] + self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any + ) -> Iterable["_models.BillingRoleDefinition"]: """Lists the role definitions for an invoice section. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str - :param invoice_section_name: The ID that uniquely identifies an invoice section. + :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either BillingRoleDefinitionListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingRoleDefinitionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either BillingRoleDefinition or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingRoleDefinition] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingRoleDefinitionListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinitionListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_invoice_section.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - 'invoiceSectionName': self._serialize.url("invoice_section_name", invoice_section_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_invoice_section_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + invoice_section_name=invoice_section_name, + api_version=api_version, + template_url=self.list_by_invoice_section.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('BillingRoleDefinitionListResult', pipeline_response) + deserialized = self._deserialize("BillingRoleDefinitionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -374,74 +584,76 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_invoice_section.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleDefinitions'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingRoleDefinitions"} # type: ignore + @distributed_trace def list_by_billing_profile( - self, - billing_account_name, # type: str - billing_profile_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.BillingRoleDefinitionListResult"] + self, billing_account_name: str, billing_profile_name: str, **kwargs: Any + ) -> Iterable["_models.BillingRoleDefinition"]: """Lists the role definitions for a billing profile. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either BillingRoleDefinitionListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingRoleDefinitionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either BillingRoleDefinition or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingRoleDefinition] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingRoleDefinitionListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingRoleDefinitionListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_profile.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_profile_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + api_version=api_version, + template_url=self.list_by_billing_profile.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('BillingRoleDefinitionListResult', pipeline_response) + deserialized = self._deserialize("BillingRoleDefinitionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -450,17 +662,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_billing_profile.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleDefinitions'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleDefinitions"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_billing_subscriptions_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_billing_subscriptions_operations.py index 1e437388e858..cfd43c6d2174 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_billing_subscriptions_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_billing_subscriptions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,101 +6,345 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_by_customer_request(billing_account_name: str, customer_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/billingSubscriptions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "customerName": _SERIALIZER.url("customer_name", customer_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_billing_account_request(billing_account_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions" + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_billing_profile_request( + billing_account_name: str, billing_profile_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingSubscriptions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_invoice_section_request( + billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingSubscriptions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), + "invoiceSectionName": _SERIALIZER.url("invoice_section_name", invoice_section_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(billing_account_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_request(billing_account_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_move_request(billing_account_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}/move", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] -class BillingSubscriptionsOperations(object): - """BillingSubscriptionsOperations operations. +def build_validate_move_request(billing_account_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}/validateMoveEligibility", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class BillingSubscriptionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.BillingManagementClient`'s + :attr:`billing_subscriptions` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_by_customer( - self, - billing_account_name, # type: str - customer_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.BillingSubscriptionsListResult"] + self, billing_account_name: str, customer_name: str, **kwargs: Any + ) -> Iterable["_models.BillingSubscription"]: """Lists the subscriptions for a customer. The operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param customer_name: The ID that uniquely identifies a customer. + :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either BillingSubscriptionsListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingSubscriptionsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either BillingSubscription or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingSubscription] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingSubscriptionsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscriptionsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_customer.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'customerName': self._serialize.url("customer_name", customer_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_customer_request( + billing_account_name=billing_account_name, + customer_name=customer_name, + api_version=api_version, + template_url=self.list_by_customer.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('BillingSubscriptionsListResult', pipeline_response) + deserialized = self._deserialize("BillingSubscriptionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -108,70 +353,72 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_customer.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/billingSubscriptions'} # type: ignore + return ItemPaged(get_next, extract_data) + list_by_customer.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/billingSubscriptions"} # type: ignore + + @distributed_trace def list_by_billing_account( - self, - billing_account_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.BillingSubscriptionsListResult"] + self, billing_account_name: str, **kwargs: Any + ) -> Iterable["_models.BillingSubscription"]: """Lists the subscriptions for a billing account. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either BillingSubscriptionsListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingSubscriptionsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either BillingSubscription or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingSubscription] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingSubscriptionsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscriptionsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_account.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_account_request( + billing_account_name=billing_account_name, + api_version=api_version, + template_url=self.list_by_billing_account.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('BillingSubscriptionsListResult', pipeline_response) + deserialized = self._deserialize("BillingSubscriptionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -180,75 +427,76 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_billing_account.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions"} # type: ignore + @distributed_trace def list_by_billing_profile( - self, - billing_account_name, # type: str - billing_profile_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.BillingSubscriptionsListResult"] + self, billing_account_name: str, billing_profile_name: str, **kwargs: Any + ) -> Iterable["_models.BillingSubscription"]: """Lists the subscriptions that are billed to a billing profile. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either BillingSubscriptionsListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingSubscriptionsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either BillingSubscription or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingSubscription] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingSubscriptionsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscriptionsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_profile.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_profile_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + api_version=api_version, + template_url=self.list_by_billing_profile.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('BillingSubscriptionsListResult', pipeline_response) + deserialized = self._deserialize("BillingSubscriptionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -257,78 +505,78 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_billing_profile.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingSubscriptions'} # type: ignore + return ItemPaged(get_next, extract_data) + list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingSubscriptions"} # type: ignore + + @distributed_trace def list_by_invoice_section( - self, - billing_account_name, # type: str - billing_profile_name, # type: str - invoice_section_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.BillingSubscriptionsListResult"] + self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any + ) -> Iterable["_models.BillingSubscription"]: """Lists the subscriptions that are billed to an invoice section. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str - :param invoice_section_name: The ID that uniquely identifies an invoice section. + :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either BillingSubscriptionsListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingSubscriptionsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either BillingSubscription or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.BillingSubscription] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingSubscriptionsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscriptionsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_invoice_section.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - 'invoiceSectionName': self._serialize.url("invoice_section_name", invoice_section_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_invoice_section_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + invoice_section_name=invoice_section_name, + api_version=api_version, + template_url=self.list_by_invoice_section.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('BillingSubscriptionsListResult', pipeline_response) + deserialized = self._deserialize("BillingSubscriptionsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -337,336 +585,541 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_invoice_section.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingSubscriptions'} # type: ignore + return ItemPaged(get_next, extract_data) - def get( - self, - billing_account_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.BillingSubscription" + list_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingSubscriptions"} # type: ignore + + @distributed_trace + def get(self, billing_account_name: str, **kwargs: Any) -> _models.BillingSubscription: """Gets a subscription by its ID. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement and Microsoft Partner Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: BillingSubscription, or the result of cls(response) + :return: BillingSubscription or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingSubscription - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingSubscription"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscription] + + request = build_get_request( + billing_account_name=billing_account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('BillingSubscription', pipeline_response) + deserialized = self._deserialize("BillingSubscription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}'} # type: ignore + get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}"} # type: ignore + + @overload def update( self, - billing_account_name, # type: str - parameters, # type: "_models.BillingSubscription" - **kwargs # type: Any - ): - # type: (...) -> "_models.BillingSubscription" + billing_account_name: str, + parameters: _models.BillingSubscription, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.BillingSubscription: """Updates the properties of a billing subscription. Currently, cost center can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the update billing subscription - operation. + operation. Required. :type parameters: ~azure.mgmt.billing.models.BillingSubscription + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: BillingSubscription, or the result of cls(response) + :return: BillingSubscription or the result of cls(response) :rtype: ~azure.mgmt.billing.models.BillingSubscription - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update( + self, billing_account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.BillingSubscription: + """Updates the properties of a billing subscription. Currently, cost center can be updated. The + operation is supported only for billing accounts with agreement type Microsoft Customer + Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param parameters: Request parameters that are provided to the update billing subscription + operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: BillingSubscription or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.BillingSubscription + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update( + self, billing_account_name: str, parameters: Union[_models.BillingSubscription, IO], **kwargs: Any + ) -> _models.BillingSubscription: + """Updates the properties of a billing subscription. Currently, cost center can be updated. The + operation is supported only for billing accounts with agreement type Microsoft Customer + Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param parameters: Request parameters that are provided to the update billing subscription + operation. Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.billing.models.BillingSubscription or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: BillingSubscription or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.BillingSubscription + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingSubscription"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.update.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'BillingSubscription') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscription] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "BillingSubscription") + + request = build_update_request( + billing_account_name=billing_account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('BillingSubscription', pipeline_response) + deserialized = self._deserialize("BillingSubscription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}'} # type: ignore + + update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}"} # type: ignore def _move_initial( self, - billing_account_name, # type: str - parameters, # type: "_models.TransferBillingSubscriptionRequestProperties" - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.BillingSubscription"] - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.BillingSubscription"]] + billing_account_name: str, + parameters: Union[_models.TransferBillingSubscriptionRequestProperties, IO], + **kwargs: Any + ) -> Optional[_models.BillingSubscription]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self._move_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'TransferBillingSubscriptionRequestProperties') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.BillingSubscription]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "TransferBillingSubscriptionRequestProperties") + + request = build_move_request( + billing_account_name=billing_account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._move_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - response_headers = {} deserialized = None + response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('BillingSubscription', pipeline_response) + deserialized = self._deserialize("BillingSubscription", pipeline_response) if response.status_code == 202: - response_headers['Location']=self._deserialize('str', response.headers.get('Location')) - response_headers['Retry-After']=self._deserialize('int', response.headers.get('Retry-After')) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized - _move_initial.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}/move'} # type: ignore + _move_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}/move"} # type: ignore + + @overload def begin_move( self, - billing_account_name, # type: str - parameters, # type: "_models.TransferBillingSubscriptionRequestProperties" - **kwargs # type: Any - ): - # type: (...) -> LROPoller["_models.BillingSubscription"] + billing_account_name: str, + parameters: _models.TransferBillingSubscriptionRequestProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.BillingSubscription]: """Moves a subscription's charges to a new invoice section. The new invoice section must belong to the same billing profile as the existing invoice section. This operation is supported for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the move subscription operation. + Required. :type parameters: ~azure.mgmt.billing.models.TransferBillingSubscriptionRequestProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: Pass in True if you'd like the ARMPolling polling method, - False for no polling, or your own initialized polling object for a personal polling strategy. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - :return: An instance of LROPoller that returns either BillingSubscription or the result of cls(response) + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either BillingSubscription or the result of + cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.BillingSubscription] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.BillingSubscription"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + def begin_move( + self, billing_account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[_models.BillingSubscription]: + """Moves a subscription's charges to a new invoice section. The new invoice section must belong to + the same billing profile as the existing invoice section. This operation is supported for + billing accounts with agreement type Microsoft Customer Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param parameters: Request parameters that are provided to the move subscription operation. + Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either BillingSubscription or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.BillingSubscription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_move( + self, + billing_account_name: str, + parameters: Union[_models.TransferBillingSubscriptionRequestProperties, IO], + **kwargs: Any + ) -> LROPoller[_models.BillingSubscription]: + """Moves a subscription's charges to a new invoice section. The new invoice section must belong to + the same billing profile as the existing invoice section. This operation is supported for + billing accounts with agreement type Microsoft Customer Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param parameters: Request parameters that are provided to the move subscription operation. Is + either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.billing.models.TransferBillingSubscriptionRequestProperties or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either BillingSubscription or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.BillingSubscription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.BillingSubscription] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._move_initial( + raw_result = self._move_initial( # type: ignore billing_account_name=billing_account_name, parameters=parameters, - cls=lambda x,y,z: x, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('BillingSubscription', pipeline_response) - + deserialized = self._deserialize("BillingSubscription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - - if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_move.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}/move'} # type: ignore + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_move.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}/move"} # type: ignore + + @overload def validate_move( self, - billing_account_name, # type: str - parameters, # type: "_models.TransferBillingSubscriptionRequestProperties" - **kwargs # type: Any - ): - # type: (...) -> "_models.ValidateSubscriptionTransferEligibilityResult" + billing_account_name: str, + parameters: _models.TransferBillingSubscriptionRequestProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ValidateSubscriptionTransferEligibilityResult: """Validates if a subscription's charges can be moved to a new invoice section. This operation is supported for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param parameters: Request parameters that are provided to the validate move eligibility - operation. + operation. Required. :type parameters: ~azure.mgmt.billing.models.TransferBillingSubscriptionRequestProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ValidateSubscriptionTransferEligibilityResult, or the result of cls(response) + :return: ValidateSubscriptionTransferEligibilityResult or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateSubscriptionTransferEligibilityResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def validate_move( + self, billing_account_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ValidateSubscriptionTransferEligibilityResult: + """Validates if a subscription's charges can be moved to a new invoice section. This operation is + supported for billing accounts with agreement type Microsoft Customer Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param parameters: Request parameters that are provided to the validate move eligibility + operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ValidateSubscriptionTransferEligibilityResult or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.ValidateSubscriptionTransferEligibilityResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def validate_move( + self, + billing_account_name: str, + parameters: Union[_models.TransferBillingSubscriptionRequestProperties, IO], + **kwargs: Any + ) -> _models.ValidateSubscriptionTransferEligibilityResult: + """Validates if a subscription's charges can be moved to a new invoice section. This operation is + supported for billing accounts with agreement type Microsoft Customer Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param parameters: Request parameters that are provided to the validate move eligibility + operation. Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.billing.models.TransferBillingSubscriptionRequestProperties or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ValidateSubscriptionTransferEligibilityResult or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.ValidateSubscriptionTransferEligibilityResult + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ValidateSubscriptionTransferEligibilityResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.validate_move.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'TransferBillingSubscriptionRequestProperties') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidateSubscriptionTransferEligibilityResult] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "TransferBillingSubscriptionRequestProperties") + + request = build_validate_move_request( + billing_account_name=billing_account_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.validate_move.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('ValidateSubscriptionTransferEligibilityResult', pipeline_response) + deserialized = self._deserialize("ValidateSubscriptionTransferEligibilityResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - validate_move.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}/validateMoveEligibility'} # type: ignore + + validate_move.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}/validateMoveEligibility"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_customers_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_customers_operations.py index 5e112bddbaec..e26ced385771 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_customers_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_customers_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,110 +6,219 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_by_billing_profile_request( + billing_account_name: str, + billing_profile_name: str, + *, + search: Optional[str] = None, + filter: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/customers", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if search is not None: + _params["$search"] = _SERIALIZER.query("search", search, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_billing_account_request( + billing_account_name: str, *, search: Optional[str] = None, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers") + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + } - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + _url = _format_url_section(_url, **path_format_arguments) -class CustomersOperations(object): - """CustomersOperations operations. + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if search is not None: + _params["$search"] = _SERIALIZER.query("search", search, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request( + billing_account_name: str, customer_name: str, *, expand: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}" + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "customerName": _SERIALIZER.url("customer_name", customer_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class CustomersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.BillingManagementClient`'s + :attr:`customers` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_by_billing_profile( self, - billing_account_name, # type: str - billing_profile_name, # type: str - search=None, # type: Optional[str] - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.CustomerListResult"] + billing_account_name: str, + billing_profile_name: str, + search: Optional[str] = None, + filter: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.Customer"]: """Lists the customers that are billed to a billing profile. The operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param search: Used for searching customers by their name. Any customer with name containing - the search text will be included in the response. + the search text will be included in the response. Default value is None. :type search: str - :param filter: May be used to filter the list of customers. + :param filter: May be used to filter the list of customers. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either CustomerListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.CustomerListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Customer or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Customer] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CustomerListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomerListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_profile.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if search is not None: - query_parameters['$search'] = self._serialize.query("search", search, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_profile_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + search=search, + filter=filter, + api_version=api_version, + template_url=self.list_by_billing_profile.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('CustomerListResult', pipeline_response) + deserialized = self._deserialize("CustomerListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -117,81 +227,79 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_billing_profile.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/customers'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/customers"} # type: ignore + @distributed_trace def list_by_billing_account( - self, - billing_account_name, # type: str - search=None, # type: Optional[str] - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.CustomerListResult"] + self, billing_account_name: str, search: Optional[str] = None, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.Customer"]: """Lists the customers that are billed to a billing account. The operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param search: Used for searching customers by their name. Any customer with name containing - the search text will be included in the response. + the search text will be included in the response. Default value is None. :type search: str - :param filter: May be used to filter the list of customers. + :param filter: May be used to filter the list of customers. Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either CustomerListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.CustomerListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Customer or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Customer] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CustomerListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomerListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_account.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if search is not None: - query_parameters['$search'] = self._serialize.query("search", search, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_account_request( + billing_account_name=billing_account_name, + search=search, + filter=filter, + api_version=api_version, + template_url=self.list_by_billing_account.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('CustomerListResult', pipeline_response) + deserialized = self._deserialize("CustomerListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -200,82 +308,82 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_billing_account.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers"} # type: ignore + @distributed_trace def get( - self, - billing_account_name, # type: str - customer_name, # type: str - expand=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> "_models.Customer" + self, billing_account_name: str, customer_name: str, expand: Optional[str] = None, **kwargs: Any + ) -> _models.Customer: """Gets a customer by its ID. The operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param customer_name: The ID that uniquely identifies a customer. + :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str - :param expand: May be used to expand enabledAzurePlans and resellers. + :param expand: May be used to expand enabledAzurePlans and resellers. Default value is None. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Customer, or the result of cls(response) + :return: Customer or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Customer - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Customer"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'customerName': self._serialize.url("customer_name", customer_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if expand is not None: - query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Customer] + + request = build_get_request( + billing_account_name=billing_account_name, + customer_name=customer_name, + expand=expand, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Customer', pipeline_response) + deserialized = self._deserialize("Customer", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}'} # type: ignore + + get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_enrollment_accounts_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_enrollment_accounts_operations.py index 36a5e9836b06..7a5243bde97d 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_enrollment_accounts_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_enrollment_accounts_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,87 +6,142 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/enrollmentAccounts") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -class EnrollmentAccountsOperations(object): - """EnrollmentAccountsOperations operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +def build_get_request(name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-03-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/enrollmentAccounts/{name}") + path_format_arguments = { + "name": _SERIALIZER.url("name", name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class EnrollmentAccountsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.BillingManagementClient`'s + :attr:`enrollment_accounts` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def list( - self, - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.EnrollmentAccountListResult"] + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> Iterable["_models.EnrollmentAccountSummary"]: """Lists the enrollment accounts the caller has access to. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either EnrollmentAccountListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.EnrollmentAccountListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either EnrollmentAccountSummary or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.EnrollmentAccountSummary] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.EnrollmentAccountListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.EnrollmentAccountListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-03-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - request = self._client.get(url, query_parameters, header_parameters) + request = build_list_request( + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('EnrollmentAccountListResult', pipeline_response) + deserialized = self._deserialize("EnrollmentAccountListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -94,72 +150,73 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.Billing/enrollmentAccounts'} # type: ignore - - def get( - self, - name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.EnrollmentAccountSummary" + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Billing/enrollmentAccounts"} # type: ignore + + @distributed_trace + def get(self, name: str, **kwargs: Any) -> _models.EnrollmentAccountSummary: """Gets a enrollment account by name. - :param name: Enrollment Account name. + :param name: Enrollment Account name. Required. :type name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: EnrollmentAccountSummary, or the result of cls(response) + :return: EnrollmentAccountSummary or the result of cls(response) :rtype: ~azure.mgmt.billing.models.EnrollmentAccountSummary - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.EnrollmentAccountSummary"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2018-03-01-preview" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'name': self._serialize.url("name", name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-03-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.EnrollmentAccountSummary] + + request = build_get_request( + name=name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('EnrollmentAccountSummary', pipeline_response) + deserialized = self._deserialize("EnrollmentAccountSummary", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/providers/Microsoft.Billing/enrollmentAccounts/{name}'} # type: ignore + + get.metadata = {"url": "/providers/Microsoft.Billing/enrollmentAccounts/{name}"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_instructions_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_instructions_operations.py index 3b7a277eb67a..1327d47c3293 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_instructions_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_instructions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,98 +6,201 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_by_billing_profile_request( + billing_account_name: str, billing_profile_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request( + billing_account_name: str, billing_profile_name: str, instruction_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions/{instructionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), + "instructionName": _SERIALIZER.url("instruction_name", instruction_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] -class InstructionsOperations(object): - """InstructionsOperations operations. +def build_put_request( + billing_account_name: str, billing_profile_name: str, instruction_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions/{instructionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), + "instructionName": _SERIALIZER.url("instruction_name", instruction_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +class InstructionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.BillingManagementClient`'s + :attr:`instructions` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_by_billing_profile( - self, - billing_account_name, # type: str - billing_profile_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.InstructionListResult"] + self, billing_account_name: str, billing_profile_name: str, **kwargs: Any + ) -> Iterable["_models.Instruction"]: """Lists the instructions by billing profile id. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either InstructionListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.InstructionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Instruction or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Instruction] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.InstructionListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.InstructionListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_profile.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_profile_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + api_version=api_version, + template_url=self.list_by_billing_profile.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('InstructionListResult', pipeline_response) + deserialized = self._deserialize("InstructionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -105,153 +209,230 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_billing_profile.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions'} # type: ignore + return ItemPaged(get_next, extract_data) + list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions"} # type: ignore + + @distributed_trace def get( - self, - billing_account_name, # type: str - billing_profile_name, # type: str - instruction_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.Instruction" + self, billing_account_name: str, billing_profile_name: str, instruction_name: str, **kwargs: Any + ) -> _models.Instruction: """Get the instruction by name. These are custom billing instructions and are only applicable for certain customers. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str - :param instruction_name: Instruction Name. + :param instruction_name: Instruction Name. Required. :type instruction_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Instruction, or the result of cls(response) + :return: Instruction or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Instruction - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Instruction"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - 'instructionName': self._serialize.url("instruction_name", instruction_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Instruction] + + request = build_get_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + instruction_name=instruction_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Instruction', pipeline_response) + deserialized = self._deserialize("Instruction", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions/{instructionName}'} # type: ignore + get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions/{instructionName}"} # type: ignore + + @overload def put( self, - billing_account_name, # type: str - billing_profile_name, # type: str - instruction_name, # type: str - parameters, # type: "_models.Instruction" - **kwargs # type: Any - ): - # type: (...) -> "_models.Instruction" + billing_account_name: str, + billing_profile_name: str, + instruction_name: str, + parameters: _models.Instruction, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Instruction: """Creates or updates an instruction. These are custom billing instructions and are only applicable for certain customers. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str - :param instruction_name: Instruction Name. + :param instruction_name: Instruction Name. Required. :type instruction_name: str - :param parameters: The new instruction. + :param parameters: The new instruction. Required. :type parameters: ~azure.mgmt.billing.models.Instruction + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Instruction or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.Instruction + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def put( + self, + billing_account_name: str, + billing_profile_name: str, + instruction_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Instruction: + """Creates or updates an instruction. These are custom billing instructions and are only + applicable for certain customers. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. + :type billing_profile_name: str + :param instruction_name: Instruction Name. Required. + :type instruction_name: str + :param parameters: The new instruction. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Instruction, or the result of cls(response) + :return: Instruction or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Instruction - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def put( + self, + billing_account_name: str, + billing_profile_name: str, + instruction_name: str, + parameters: Union[_models.Instruction, IO], + **kwargs: Any + ) -> _models.Instruction: + """Creates or updates an instruction. These are custom billing instructions and are only + applicable for certain customers. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. + :type billing_profile_name: str + :param instruction_name: Instruction Name. Required. + :type instruction_name: str + :param parameters: The new instruction. Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.billing.models.Instruction or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Instruction or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.Instruction + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Instruction"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.put.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - 'instructionName': self._serialize.url("instruction_name", instruction_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'Instruction') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Instruction] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Instruction") + + request = build_put_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + instruction_name=instruction_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.put.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Instruction', pipeline_response) + deserialized = self._deserialize("Instruction", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - put.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions/{instructionName}'} # type: ignore + + put.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions/{instructionName}"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_invoice_sections_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_invoice_sections_operations.py index 5a5af73619bd..4f24fe5a8654 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_invoice_sections_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_invoice_sections_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,101 +6,204 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_by_billing_profile_request( + billing_account_name: str, billing_profile_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request( + billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), + "invoiceSectionName": _SERIALIZER.url("invoice_section_name", invoice_section_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request( + billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), + "invoiceSectionName": _SERIALIZER.url("invoice_section_name", invoice_section_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") -class InvoiceSectionsOperations(object): - """InvoiceSectionsOperations operations. + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. +class InvoiceSectionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.BillingManagementClient`'s + :attr:`invoice_sections` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_by_billing_profile( - self, - billing_account_name, # type: str - billing_profile_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.InvoiceSectionListResult"] + self, billing_account_name: str, billing_profile_name: str, **kwargs: Any + ) -> Iterable["_models.InvoiceSection"]: """Lists the invoice sections that a user has access to. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either InvoiceSectionListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.InvoiceSectionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either InvoiceSection or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.InvoiceSection] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.InvoiceSectionListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceSectionListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_profile.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_profile_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + api_version=api_version, + template_url=self.list_by_billing_profile.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('InvoiceSectionListResult', pipeline_response) + deserialized = self._deserialize("InvoiceSectionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -108,221 +212,317 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_billing_profile.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections"} # type: ignore + @distributed_trace def get( - self, - billing_account_name, # type: str - billing_profile_name, # type: str - invoice_section_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.InvoiceSection" + self, billing_account_name: str, billing_profile_name: str, invoice_section_name: str, **kwargs: Any + ) -> _models.InvoiceSection: """Gets an invoice section by its ID. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str - :param invoice_section_name: The ID that uniquely identifies an invoice section. + :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: InvoiceSection, or the result of cls(response) + :return: InvoiceSection or the result of cls(response) :rtype: ~azure.mgmt.billing.models.InvoiceSection - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.InvoiceSection"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - 'invoiceSectionName': self._serialize.url("invoice_section_name", invoice_section_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceSection] + + request = build_get_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + invoice_section_name=invoice_section_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('InvoiceSection', pipeline_response) + deserialized = self._deserialize("InvoiceSection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}'} # type: ignore + + get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}"} # type: ignore def _create_or_update_initial( self, - billing_account_name, # type: str - billing_profile_name, # type: str - invoice_section_name, # type: str - parameters, # type: "_models.InvoiceSection" - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.InvoiceSection"] - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.InvoiceSection"]] + billing_account_name: str, + billing_profile_name: str, + invoice_section_name: str, + parameters: Union[_models.InvoiceSection, IO], + **kwargs: Any + ) -> Optional[_models.InvoiceSection]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self._create_or_update_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - 'invoiceSectionName': self._serialize.url("invoice_section_name", invoice_section_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'InvoiceSection') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.InvoiceSection]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "InvoiceSection") + + request = build_create_or_update_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + invoice_section_name=invoice_section_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - response_headers = {} deserialized = None + response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('InvoiceSection', pipeline_response) + deserialized = self._deserialize("InvoiceSection", pipeline_response) if response.status_code == 202: - response_headers['Location']=self._deserialize('str', response.headers.get('Location')) - response_headers['Retry-After']=self._deserialize('int', response.headers.get('Retry-After')) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized - _create_or_update_initial.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}'} # type: ignore + _create_or_update_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}"} # type: ignore + + @overload def begin_create_or_update( self, - billing_account_name, # type: str - billing_profile_name, # type: str - invoice_section_name, # type: str - parameters, # type: "_models.InvoiceSection" - **kwargs # type: Any - ): - # type: (...) -> LROPoller["_models.InvoiceSection"] + billing_account_name: str, + billing_profile_name: str, + invoice_section_name: str, + parameters: _models.InvoiceSection, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.InvoiceSection]: """Creates or updates an invoice section. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str - :param invoice_section_name: The ID that uniquely identifies an invoice section. + :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str - :param parameters: The new or updated invoice section. + :param parameters: The new or updated invoice section. Required. :type parameters: ~azure.mgmt.billing.models.InvoiceSection + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: Pass in True if you'd like the ARMPolling polling method, - False for no polling, or your own initialized polling object for a personal polling strategy. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - :return: An instance of LROPoller that returns either InvoiceSection or the result of cls(response) + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either InvoiceSection or the result of + cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.InvoiceSection] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.InvoiceSection"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + def begin_create_or_update( + self, + billing_account_name: str, + billing_profile_name: str, + invoice_section_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.InvoiceSection]: + """Creates or updates an invoice section. The operation is supported only for billing accounts + with agreement type Microsoft Customer Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. + :type billing_profile_name: str + :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. + :type invoice_section_name: str + :param parameters: The new or updated invoice section. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either InvoiceSection or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.InvoiceSection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + billing_account_name: str, + billing_profile_name: str, + invoice_section_name: str, + parameters: Union[_models.InvoiceSection, IO], + **kwargs: Any + ) -> LROPoller[_models.InvoiceSection]: + """Creates or updates an invoice section. The operation is supported only for billing accounts + with agreement type Microsoft Customer Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. + :type billing_profile_name: str + :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. + :type invoice_section_name: str + :param parameters: The new or updated invoice section. Is either a model type or a IO type. + Required. + :type parameters: ~azure.mgmt.billing.models.InvoiceSection or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either InvoiceSection or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.InvoiceSection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceSection] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._create_or_update_initial( + raw_result = self._create_or_update_initial( # type: ignore billing_account_name=billing_account_name, billing_profile_name=billing_profile_name, invoice_section_name=invoice_section_name, parameters=parameters, - cls=lambda x,y,z: x, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('InvoiceSection', pipeline_response) - + deserialized = self._deserialize("InvoiceSection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - 'invoiceSectionName': self._serialize.url("invoice_section_name", invoice_section_name, 'str'), - } - - if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}'} # type: ignore + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_or_update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_invoices_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_invoices_operations.py index 4949075cee12..c2d5b0a104a7 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_invoices_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_invoices_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,108 +6,408 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, List, Optional, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_by_billing_account_request( + billing_account_name: str, *, period_start_date: str, period_end_date: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices") + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["periodStartDate"] = _SERIALIZER.query("period_start_date", period_start_date, "str") + _params["periodEndDate"] = _SERIALIZER.query("period_end_date", period_end_date, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_billing_profile_request( + billing_account_name: str, billing_profile_name: str, *, period_start_date: str, period_end_date: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoices", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["periodStartDate"] = _SERIALIZER.query("period_start_date", period_start_date, "str") + _params["periodEndDate"] = _SERIALIZER.query("period_end_date", period_end_date, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(billing_account_name: str, invoice_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}" + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "invoiceName": _SERIALIZER.url("invoice_name", invoice_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_id_request(invoice_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts/default/invoices/{invoiceName}") + path_format_arguments = { + "invoiceName": _SERIALIZER.url("invoice_name", invoice_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_download_invoice_request( + billing_account_name: str, invoice_name: str, *, download_token: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}/download", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "invoiceName": _SERIALIZER.url("invoice_name", invoice_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["downloadToken"] = _SERIALIZER.query("download_token", download_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_download_multiple_billing_profile_invoices_request(billing_account_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/downloadDocuments" + ) + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_billing_subscription_request( + subscription_id: str, *, period_start_date: str, period_end_date: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["periodStartDate"] = _SERIALIZER.query("period_start_date", period_start_date, "str") + _params["periodEndDate"] = _SERIALIZER.query("period_end_date", period_end_date, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_subscription_and_invoice_id_request( + invoice_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices/{invoiceName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "invoiceName": _SERIALIZER.url("invoice_name", invoice_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, List, Optional, TypeVar, Union + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -class InvoicesOperations(object): - """InvoicesOperations operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +def build_download_billing_subscription_invoice_request( + invoice_name: str, subscription_id: str, *, download_token: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices/{invoiceName}/download", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "invoiceName": _SERIALIZER.url("invoice_name", invoice_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["downloadToken"] = _SERIALIZER.query("download_token", download_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_download_multiple_billing_subscription_invoices_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/downloadDocuments", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class InvoicesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.BillingManagementClient`'s + :attr:`invoices` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_by_billing_account( - self, - billing_account_name, # type: str - period_start_date, # type: str - period_end_date, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.InvoiceListResult"] + self, billing_account_name: str, period_start_date: str, period_end_date: str, **kwargs: Any + ) -> Iterable["_models.Invoice"]: """Lists the invoices for a billing account for a given start date and end date. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param period_start_date: The start date to fetch the invoices. The date should be specified in - MM-DD-YYYY format. + MM-DD-YYYY format. Required. :type period_start_date: str :param period_end_date: The end date to fetch the invoices. The date should be specified in - MM-DD-YYYY format. + MM-DD-YYYY format. Required. :type period_end_date: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either InvoiceListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.InvoiceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Invoice or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Invoice] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.InvoiceListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_account.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - query_parameters['periodStartDate'] = self._serialize.query("period_start_date", period_start_date, 'str') - query_parameters['periodEndDate'] = self._serialize.query("period_end_date", period_end_date, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_account_request( + billing_account_name=billing_account_name, + period_start_date=period_start_date, + period_end_date=period_end_date, + api_version=api_version, + template_url=self.list_by_billing_account.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('InvoiceListResult', pipeline_response) + deserialized = self._deserialize("InvoiceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -115,85 +416,89 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_billing_account.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices"} # type: ignore + @distributed_trace def list_by_billing_profile( self, - billing_account_name, # type: str - billing_profile_name, # type: str - period_start_date, # type: str - period_end_date, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.InvoiceListResult"] + billing_account_name: str, + billing_profile_name: str, + period_start_date: str, + period_end_date: str, + **kwargs: Any + ) -> Iterable["_models.Invoice"]: """Lists the invoices for a billing profile for a given start date and end date. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param period_start_date: The start date to fetch the invoices. The date should be specified in - MM-DD-YYYY format. + MM-DD-YYYY format. Required. :type period_start_date: str :param period_end_date: The end date to fetch the invoices. The date should be specified in - MM-DD-YYYY format. + MM-DD-YYYY format. Required. :type period_end_date: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either InvoiceListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.InvoiceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Invoice or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Invoice] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.InvoiceListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_profile.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - query_parameters['periodStartDate'] = self._serialize.query("period_start_date", period_start_date, 'str') - query_parameters['periodEndDate'] = self._serialize.query("period_end_date", period_end_date, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_profile_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + period_start_date=period_start_date, + period_end_date=period_end_date, + api_version=api_version, + template_url=self.list_by_billing_profile.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('InvoiceListResult', pipeline_response) + deserialized = self._deserialize("InvoiceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -202,446 +507,523 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_billing_profile.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoices'} # type: ignore + return ItemPaged(get_next, extract_data) - def get( - self, - billing_account_name, # type: str - invoice_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.Invoice" + list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoices"} # type: ignore + + @distributed_trace + def get(self, billing_account_name: str, invoice_name: str, **kwargs: Any) -> _models.Invoice: """Gets an invoice by billing account name and ID. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param invoice_name: The ID that uniquely identifies an invoice. + :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Invoice, or the result of cls(response) + :return: Invoice or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Invoice - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Invoice"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'invoiceName': self._serialize.url("invoice_name", invoice_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Invoice] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_get_request( + billing_account_name=billing_account_name, + invoice_name=invoice_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Invoice', pipeline_response) + deserialized = self._deserialize("Invoice", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}'} # type: ignore - def get_by_id( - self, - invoice_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.Invoice" + get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}"} # type: ignore + + @distributed_trace + def get_by_id(self, invoice_name: str, **kwargs: Any) -> _models.Invoice: """Gets an invoice by ID. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. - :param invoice_name: The ID that uniquely identifies an invoice. + :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Invoice, or the result of cls(response) + :return: Invoice or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Invoice - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Invoice"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get_by_id.metadata['url'] # type: ignore - path_format_arguments = { - 'invoiceName': self._serialize.url("invoice_name", invoice_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Invoice] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_get_by_id_request( + invoice_name=invoice_name, + api_version=api_version, + template_url=self.get_by_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Invoice', pipeline_response) + deserialized = self._deserialize("Invoice", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_id.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/default/invoices/{invoiceName}'} # type: ignore + + get_by_id.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/invoices/{invoiceName}"} # type: ignore def _download_invoice_initial( - self, - billing_account_name, # type: str - invoice_name, # type: str - download_token, # type: str - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.DownloadUrl"] - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.DownloadUrl"]] + self, billing_account_name: str, invoice_name: str, download_token: str, **kwargs: Any + ) -> Optional[_models.DownloadUrl]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self._download_invoice_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'invoiceName': self._serialize.url("invoice_name", invoice_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - query_parameters['downloadToken'] = self._serialize.query("download_token", download_token, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.DownloadUrl]] + + request = build_download_invoice_request( + billing_account_name=billing_account_name, + invoice_name=invoice_name, + download_token=download_token, + api_version=api_version, + template_url=self._download_invoice_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - response_headers = {} deserialized = None + response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('DownloadUrl', pipeline_response) + deserialized = self._deserialize("DownloadUrl", pipeline_response) if response.status_code == 202: - response_headers['Location']=self._deserialize('str', response.headers.get('Location')) - response_headers['Retry-After']=self._deserialize('str', response.headers.get('Retry-After')) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("str", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized - _download_invoice_initial.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}/download'} # type: ignore + _download_invoice_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}/download"} # type: ignore + + @distributed_trace def begin_download_invoice( - self, - billing_account_name, # type: str - invoice_name, # type: str - download_token, # type: str - **kwargs # type: Any - ): - # type: (...) -> LROPoller["_models.DownloadUrl"] + self, billing_account_name: str, invoice_name: str, download_token: str, **kwargs: Any + ) -> LROPoller[_models.DownloadUrl]: """Gets a URL to download an invoice. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param invoice_name: The ID that uniquely identifies an invoice. + :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str - :param download_token: Download token with document source and document ID. + :param download_token: Download token with document source and document ID. Required. :type download_token: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: Pass in True if you'd like the ARMPolling polling method, - False for no polling, or your own initialized polling object for a personal polling strategy. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - :return: An instance of LROPoller that returns either DownloadUrl or the result of cls(response) + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DownloadUrl or the result of + cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DownloadUrl"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DownloadUrl] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._download_invoice_initial( + raw_result = self._download_invoice_initial( # type: ignore billing_account_name=billing_account_name, invoice_name=invoice_name, download_token=download_token, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('DownloadUrl', pipeline_response) - + deserialized = self._deserialize("DownloadUrl", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'invoiceName': self._serialize.url("invoice_name", invoice_name, 'str'), - } - - if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_download_invoice.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}/download'} # type: ignore + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_download_invoice.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}/download"} # type: ignore def _download_multiple_billing_profile_invoices_initial( - self, - billing_account_name, # type: str - download_urls, # type: List[str] - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.DownloadUrl"] - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.DownloadUrl"]] + self, billing_account_name: str, download_urls: Union[List[str], IO], **kwargs: Any + ) -> Optional[_models.DownloadUrl]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self._download_multiple_billing_profile_invoices_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(download_urls, '[str]') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.DownloadUrl]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(download_urls, (IO, bytes)): + _content = download_urls + else: + _json = self._serialize.body(download_urls, "[str]") + + request = build_download_multiple_billing_profile_invoices_request( + billing_account_name=billing_account_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._download_multiple_billing_profile_invoices_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - response_headers = {} deserialized = None + response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('DownloadUrl', pipeline_response) + deserialized = self._deserialize("DownloadUrl", pipeline_response) if response.status_code == 202: - response_headers['Location']=self._deserialize('str', response.headers.get('Location')) - response_headers['Retry-After']=self._deserialize('str', response.headers.get('Retry-After')) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("str", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized - _download_multiple_billing_profile_invoices_initial.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/downloadDocuments'} # type: ignore + _download_multiple_billing_profile_invoices_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/downloadDocuments"} # type: ignore + + @overload def begin_download_multiple_billing_profile_invoices( self, - billing_account_name, # type: str - download_urls, # type: List[str] - **kwargs # type: Any - ): - # type: (...) -> LROPoller["_models.DownloadUrl"] + billing_account_name: str, + download_urls: List[str], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DownloadUrl]: """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as a zip file. The operation is supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param download_urls: An array of download urls for individual documents. + :param download_urls: An array of download urls for individual documents. Required. :type download_urls: list[str] + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: Pass in True if you'd like the ARMPolling polling method, - False for no polling, or your own initialized polling object for a personal polling strategy. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - :return: An instance of LROPoller that returns either DownloadUrl or the result of cls(response) + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DownloadUrl or the result of + cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DownloadUrl"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + def begin_download_multiple_billing_profile_invoices( + self, billing_account_name: str, download_urls: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[_models.DownloadUrl]: + """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as + a zip file. The operation is supported for billing accounts with agreement type Microsoft + Partner Agreement or Microsoft Customer Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param download_urls: An array of download urls for individual documents. Required. + :type download_urls: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DownloadUrl or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.DownloadUrl] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_download_multiple_billing_profile_invoices( + self, billing_account_name: str, download_urls: Union[List[str], IO], **kwargs: Any + ) -> LROPoller[_models.DownloadUrl]: + """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as + a zip file. The operation is supported for billing accounts with agreement type Microsoft + Partner Agreement or Microsoft Customer Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param download_urls: An array of download urls for individual documents. Is either a list type + or a IO type. Required. + :type download_urls: list[str] or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DownloadUrl or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.DownloadUrl] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.DownloadUrl] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._download_multiple_billing_profile_invoices_initial( + raw_result = self._download_multiple_billing_profile_invoices_initial( # type: ignore billing_account_name=billing_account_name, download_urls=download_urls, - cls=lambda x,y,z: x, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('DownloadUrl', pipeline_response) - + deserialized = self._deserialize("DownloadUrl", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - } - - if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_download_multiple_billing_profile_invoices.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/downloadDocuments'} # type: ignore + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_download_multiple_billing_profile_invoices.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/downloadDocuments"} # type: ignore + @distributed_trace def list_by_billing_subscription( - self, - period_start_date, # type: str - period_end_date, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.InvoiceListResult"] + self, period_start_date: str, period_end_date: str, **kwargs: Any + ) -> Iterable["_models.Invoice"]: """Lists the invoices for a subscription. - :param period_start_date: Invoice period start date. + :param period_start_date: Invoice period start date. Required. :type period_start_date: str - :param period_end_date: Invoice period end date. + :param period_end_date: Invoice period end date. Required. :type period_end_date: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either InvoiceListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.InvoiceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Invoice or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Invoice] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.InvoiceListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.InvoiceListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['periodStartDate'] = self._serialize.query("period_start_date", period_start_date, 'str') - query_parameters['periodEndDate'] = self._serialize.query("period_end_date", period_end_date, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_subscription_request( + subscription_id=self._config.subscription_id, + period_start_date=period_start_date, + period_end_date=period_end_date, + api_version=api_version, + template_url=self.list_by_billing_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('InvoiceListResult', pipeline_response) + deserialized = self._deserialize("InvoiceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -650,317 +1032,388 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_billing_subscription.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices'} # type: ignore + return ItemPaged(get_next, extract_data) - def get_by_subscription_and_invoice_id( - self, - invoice_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.Invoice" + list_by_billing_subscription.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices"} # type: ignore + + @distributed_trace + def get_by_subscription_and_invoice_id(self, invoice_name: str, **kwargs: Any) -> _models.Invoice: """Gets an invoice by subscription ID and invoice ID. - :param invoice_name: The ID that uniquely identifies an invoice. + :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Invoice, or the result of cls(response) + :return: Invoice or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Invoice - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Invoice"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get_by_subscription_and_invoice_id.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'invoiceName': self._serialize.url("invoice_name", invoice_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Invoice] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_by_subscription_and_invoice_id_request( + invoice_name=invoice_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_by_subscription_and_invoice_id.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Invoice', pipeline_response) + deserialized = self._deserialize("Invoice", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_subscription_and_invoice_id.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices/{invoiceName}'} # type: ignore + + get_by_subscription_and_invoice_id.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices/{invoiceName}"} # type: ignore def _download_billing_subscription_invoice_initial( - self, - invoice_name, # type: str - download_token, # type: str - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.DownloadUrl"] - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.DownloadUrl"]] + self, invoice_name: str, download_token: str, **kwargs: Any + ) -> Optional[_models.DownloadUrl]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self._download_billing_subscription_invoice_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'invoiceName': self._serialize.url("invoice_name", invoice_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - query_parameters['downloadToken'] = self._serialize.query("download_token", download_token, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.DownloadUrl]] + + request = build_download_billing_subscription_invoice_request( + invoice_name=invoice_name, + subscription_id=self._config.subscription_id, + download_token=download_token, + api_version=api_version, + template_url=self._download_billing_subscription_invoice_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - response_headers = {} deserialized = None + response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('DownloadUrl', pipeline_response) + deserialized = self._deserialize("DownloadUrl", pipeline_response) if response.status_code == 202: - response_headers['Location']=self._deserialize('str', response.headers.get('Location')) - response_headers['Retry-After']=self._deserialize('str', response.headers.get('Retry-After')) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("str", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized - _download_billing_subscription_invoice_initial.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices/{invoiceName}/download'} # type: ignore + _download_billing_subscription_invoice_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices/{invoiceName}/download"} # type: ignore + + @distributed_trace def begin_download_billing_subscription_invoice( - self, - invoice_name, # type: str - download_token, # type: str - **kwargs # type: Any - ): - # type: (...) -> LROPoller["_models.DownloadUrl"] + self, invoice_name: str, download_token: str, **kwargs: Any + ) -> LROPoller[_models.DownloadUrl]: """Gets a URL to download an invoice. - :param invoice_name: The ID that uniquely identifies an invoice. + :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str - :param download_token: Download token with document source and document ID. + :param download_token: Download token with document source and document ID. Required. :type download_token: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: Pass in True if you'd like the ARMPolling polling method, - False for no polling, or your own initialized polling object for a personal polling strategy. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - :return: An instance of LROPoller that returns either DownloadUrl or the result of cls(response) + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DownloadUrl or the result of + cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DownloadUrl"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DownloadUrl] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._download_billing_subscription_invoice_initial( + raw_result = self._download_billing_subscription_invoice_initial( # type: ignore invoice_name=invoice_name, download_token=download_token, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('DownloadUrl', pipeline_response) - + deserialized = self._deserialize("DownloadUrl", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'invoiceName': self._serialize.url("invoice_name", invoice_name, 'str'), - } - - if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_download_billing_subscription_invoice.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices/{invoiceName}/download'} # type: ignore + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_download_billing_subscription_invoice.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/invoices/{invoiceName}/download"} # type: ignore def _download_multiple_billing_subscription_invoices_initial( - self, - download_urls, # type: List[str] - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.DownloadUrl"] - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.DownloadUrl"]] + self, download_urls: Union[List[str], IO], **kwargs: Any + ) -> Optional[_models.DownloadUrl]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self._download_multiple_billing_subscription_invoices_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(download_urls, '[str]') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.DownloadUrl]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(download_urls, (IO, bytes)): + _content = download_urls + else: + _json = self._serialize.body(download_urls, "[str]") + + request = build_download_multiple_billing_subscription_invoices_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._download_multiple_billing_subscription_invoices_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - response_headers = {} deserialized = None + response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('DownloadUrl', pipeline_response) + deserialized = self._deserialize("DownloadUrl", pipeline_response) if response.status_code == 202: - response_headers['Location']=self._deserialize('str', response.headers.get('Location')) - response_headers['Retry-After']=self._deserialize('str', response.headers.get('Retry-After')) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("str", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized - _download_multiple_billing_subscription_invoices_initial.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/downloadDocuments'} # type: ignore + _download_multiple_billing_subscription_invoices_initial.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/downloadDocuments"} # type: ignore + + @overload def begin_download_multiple_billing_subscription_invoices( - self, - download_urls, # type: List[str] - **kwargs # type: Any - ): - # type: (...) -> LROPoller["_models.DownloadUrl"] + self, download_urls: List[str], *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[_models.DownloadUrl]: """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as a zip file. - :param download_urls: An array of download urls for individual documents. + :param download_urls: An array of download urls for individual documents. Required. :type download_urls: list[str] + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: Pass in True if you'd like the ARMPolling polling method, - False for no polling, or your own initialized polling object for a personal polling strategy. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - :return: An instance of LROPoller that returns either DownloadUrl or the result of cls(response) + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DownloadUrl or the result of + cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.DownloadUrl] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DownloadUrl"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + def begin_download_multiple_billing_subscription_invoices( + self, download_urls: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[_models.DownloadUrl]: + """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as + a zip file. + + :param download_urls: An array of download urls for individual documents. Required. + :type download_urls: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DownloadUrl or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.DownloadUrl] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_download_multiple_billing_subscription_invoices( + self, download_urls: Union[List[str], IO], **kwargs: Any + ) -> LROPoller[_models.DownloadUrl]: + """Gets a URL to download multiple invoice documents (invoice pdf, tax receipts, credit notes) as + a zip file. + + :param download_urls: An array of download urls for individual documents. Is either a list type + or a IO type. Required. + :type download_urls: list[str] or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DownloadUrl or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.billing.models.DownloadUrl] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.DownloadUrl] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._download_multiple_billing_subscription_invoices_initial( + raw_result = self._download_multiple_billing_subscription_invoices_initial( # type: ignore download_urls=download_urls, - cls=lambda x,y,z: x, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('DownloadUrl', pipeline_response) - + deserialized = self._deserialize("DownloadUrl", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - - if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_download_multiple_billing_subscription_invoices.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/downloadDocuments'} # type: ignore + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_download_multiple_billing_subscription_invoices.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/default/billingSubscriptions/{subscriptionId}/downloadDocuments"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_operations.py index 643a38021450..7a767b340156 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,87 +6,117 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar +def build_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") -class Operations(object): - """Operations operations. + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/operations") - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.BillingManagementClient`'s + :attr:`operations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def list( - self, - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.OperationListResult"] + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: """Lists the available billing REST API operations. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either OperationListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.OperationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - request = self._client.get(url, query_parameters, header_parameters) + request = build_list_request( + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('OperationListResult', pipeline_response) + deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -94,17 +125,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.OperationsErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': '/providers/Microsoft.Billing/operations'} # type: ignore + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.Billing/operations"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_patch.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_policies_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_policies_operations.py index d347885b4814..b4d4709dfe1c 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_policies_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_policies_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,297 +6,567 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_by_billing_profile_request( + billing_account_name: str, billing_profile_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/policies/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_request(billing_account_name: str, billing_profile_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/policies/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_by_customer_request(billing_account_name: str, customer_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/policies/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "customerName": _SERIALIZER.url("customer_name", customer_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Optional, TypeVar + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") -class PoliciesOperations(object): - """PoliciesOperations operations. + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. +def build_update_customer_request(billing_account_name: str, customer_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/policies/default", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "customerName": _SERIALIZER.url("customer_name", customer_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +class PoliciesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.BillingManagementClient`'s + :attr:`policies` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def get_by_billing_profile( - self, - billing_account_name, # type: str - billing_profile_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.Policy" + self, billing_account_name: str, billing_profile_name: str, **kwargs: Any + ) -> _models.Policy: """Lists the policies for a billing profile. This operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Policy, or the result of cls(response) + :return: Policy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Policy - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Policy"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get_by_billing_profile.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Policy] + + request = build_get_by_billing_profile_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + api_version=api_version, + template_url=self.get_by_billing_profile.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Policy', pipeline_response) + deserialized = self._deserialize("Policy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_billing_profile.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/policies/default'} # type: ignore + get_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/policies/default"} # type: ignore + + @overload def update( self, - billing_account_name, # type: str - billing_profile_name, # type: str - parameters, # type: "_models.Policy" - **kwargs # type: Any - ): - # type: (...) -> "_models.Policy" + billing_account_name: str, + billing_profile_name: str, + parameters: _models.Policy, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Policy: """Updates the policies for a billing profile. This operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param parameters: Request parameters that are provided to the update policies operation. + Required. :type parameters: ~azure.mgmt.billing.models.Policy + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Policy, or the result of cls(response) + :return: Policy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Policy - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + billing_account_name: str, + billing_profile_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Policy: + """Updates the policies for a billing profile. This operation is supported only for billing + accounts with agreement type Microsoft Customer Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. + :type billing_profile_name: str + :param parameters: Request parameters that are provided to the update policies operation. + Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Policy or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.Policy + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update( + self, billing_account_name: str, billing_profile_name: str, parameters: Union[_models.Policy, IO], **kwargs: Any + ) -> _models.Policy: + """Updates the policies for a billing profile. This operation is supported only for billing + accounts with agreement type Microsoft Customer Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. + :type billing_profile_name: str + :param parameters: Request parameters that are provided to the update policies operation. Is + either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.billing.models.Policy or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Policy or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.Policy + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Policy"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.update.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'Policy') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Policy] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Policy") + + request = build_update_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Policy', pipeline_response) + deserialized = self._deserialize("Policy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/policies/default'} # type: ignore - def get_by_customer( - self, - billing_account_name, # type: str - customer_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.CustomerPolicy" + update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/policies/default"} # type: ignore + + @distributed_trace + def get_by_customer(self, billing_account_name: str, customer_name: str, **kwargs: Any) -> _models.CustomerPolicy: """Lists the policies for a customer. This operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param customer_name: The ID that uniquely identifies a customer. + :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: CustomerPolicy, or the result of cls(response) + :return: CustomerPolicy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.CustomerPolicy - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CustomerPolicy"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get_by_customer.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'customerName': self._serialize.url("customer_name", customer_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomerPolicy] + + request = build_get_by_customer_request( + billing_account_name=billing_account_name, + customer_name=customer_name, + api_version=api_version, + template_url=self.get_by_customer.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('CustomerPolicy', pipeline_response) + deserialized = self._deserialize("CustomerPolicy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_by_customer.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/policies/default'} # type: ignore + get_by_customer.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/policies/default"} # type: ignore + + @overload def update_customer( self, - billing_account_name, # type: str - customer_name, # type: str - parameters, # type: "_models.CustomerPolicy" - **kwargs # type: Any - ): - # type: (...) -> "_models.CustomerPolicy" + billing_account_name: str, + customer_name: str, + parameters: _models.CustomerPolicy, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CustomerPolicy: """Updates the policies for a customer. This operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param customer_name: The ID that uniquely identifies a customer. + :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :param parameters: Request parameters that are provided to the update policies operation. + Required. :type parameters: ~azure.mgmt.billing.models.CustomerPolicy + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: CustomerPolicy, or the result of cls(response) + :return: CustomerPolicy or the result of cls(response) :rtype: ~azure.mgmt.billing.models.CustomerPolicy - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update_customer( + self, + billing_account_name: str, + customer_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CustomerPolicy: + """Updates the policies for a customer. This operation is supported only for billing accounts with + agreement type Microsoft Partner Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param customer_name: The ID that uniquely identifies a customer. Required. + :type customer_name: str + :param parameters: Request parameters that are provided to the update policies operation. + Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: CustomerPolicy or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.CustomerPolicy + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update_customer( + self, + billing_account_name: str, + customer_name: str, + parameters: Union[_models.CustomerPolicy, IO], + **kwargs: Any + ) -> _models.CustomerPolicy: + """Updates the policies for a customer. This operation is supported only for billing accounts with + agreement type Microsoft Partner Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param customer_name: The ID that uniquely identifies a customer. Required. + :type customer_name: str + :param parameters: Request parameters that are provided to the update policies operation. Is + either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.billing.models.CustomerPolicy or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: CustomerPolicy or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.CustomerPolicy + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CustomerPolicy"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.update_customer.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'customerName': self._serialize.url("customer_name", customer_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'CustomerPolicy') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CustomerPolicy] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "CustomerPolicy") + + request = build_update_customer_request( + billing_account_name=billing_account_name, + customer_name=customer_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update_customer.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('CustomerPolicy', pipeline_response) + deserialized = self._deserialize("CustomerPolicy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update_customer.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/policies/default'} # type: ignore + + update_customer.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/policies/default"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_products_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_products_operations.py index 6b08ee6d89a3..e64014ddb272 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_products_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_products_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,100 +6,352 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_by_customer_request(billing_account_name: str, customer_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/products", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "customerName": _SERIALIZER.url("customer_name", customer_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_billing_account_request( + billing_account_name: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products") + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_billing_profile_request( + billing_account_name: str, billing_profile_name: str, *, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/products", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_invoice_section_request( + billing_account_name: str, + billing_profile_name: str, + invoice_section_name: str, + *, + filter: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/products", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), + "invoiceSectionName": _SERIALIZER.url("invoice_section_name", invoice_section_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(billing_account_name: str, product_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}" + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "productName": _SERIALIZER.url("product_name", product_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_request(billing_account_name: str, product_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}" + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "productName": _SERIALIZER.url("product_name", product_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] -class ProductsOperations(object): - """ProductsOperations operations. +def build_move_request(billing_account_name: str, product_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + # Construct URL + _url = kwargs.pop( + "template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}/move" + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "productName": _SERIALIZER.url("product_name", product_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_validate_move_request(billing_account_name: str, product_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}/validateMoveEligibility", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "productName": _SERIALIZER.url("product_name", product_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class ProductsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.BillingManagementClient`'s + :attr:`products` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_by_customer( - self, - billing_account_name, # type: str - customer_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.ProductsListResult"] + self, billing_account_name: str, customer_name: str, **kwargs: Any + ) -> Iterable["_models.Product"]: """Lists the products for a customer. These don't include products billed based on usage.The operation is supported only for billing accounts with agreement type Microsoft Partner Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param customer_name: The ID that uniquely identifies a customer. + :param customer_name: The ID that uniquely identifies a customer. Required. :type customer_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ProductsListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.ProductsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Product or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Product] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ProductsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ProductsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_customer.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'customerName': self._serialize.url("customer_name", customer_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_customer_request( + billing_account_name=billing_account_name, + customer_name=customer_name, + api_version=api_version, + template_url=self.list_by_customer.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('ProductsListResult', pipeline_response) + deserialized = self._deserialize("ProductsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -107,78 +360,78 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_customer.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/products'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_by_customer.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/products"} # type: ignore + @distributed_trace def list_by_billing_account( - self, - billing_account_name, # type: str - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.ProductsListResult"] + self, billing_account_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.Product"]: """Lists the products for a billing account. These don't include products billed based on usage. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param filter: May be used to filter by product type. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Tag filter is a key - value pair string where key and value are separated by a colon (:). + value pair string where key and value are separated by a colon (:). Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ProductsListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.ProductsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Product or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Product] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ProductsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ProductsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_account.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_account_request( + billing_account_name=billing_account_name, + filter=filter, + api_version=api_version, + template_url=self.list_by_billing_account.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('ProductsListResult', pipeline_response) + deserialized = self._deserialize("ProductsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -187,82 +440,81 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_billing_account.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products"} # type: ignore + @distributed_trace def list_by_billing_profile( - self, - billing_account_name, # type: str - billing_profile_name, # type: str - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.ProductsListResult"] + self, billing_account_name: str, billing_profile_name: str, filter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.Product"]: """Lists the products for a billing profile. These don't include products billed based on usage. The operation is supported for billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param filter: May be used to filter by product type. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Tag filter is a key - value pair string where key and value are separated by a colon (:). + value pair string where key and value are separated by a colon (:). Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ProductsListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.ProductsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Product or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Product] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ProductsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ProductsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_profile.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_profile_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + filter=filter, + api_version=api_version, + template_url=self.list_by_billing_profile.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('ProductsListResult', pipeline_response) + deserialized = self._deserialize("ProductsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -271,86 +523,89 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_billing_profile.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/products'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/products"} # type: ignore + @distributed_trace def list_by_invoice_section( self, - billing_account_name, # type: str - billing_profile_name, # type: str - invoice_section_name, # type: str - filter=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.ProductsListResult"] + billing_account_name: str, + billing_profile_name: str, + invoice_section_name: str, + filter: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.Product"]: """Lists the products for an invoice section. These don't include products billed based on usage. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str - :param invoice_section_name: The ID that uniquely identifies an invoice section. + :param invoice_section_name: The ID that uniquely identifies an invoice section. Required. :type invoice_section_name: str :param filter: May be used to filter by product type. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support 'ne', 'or', or 'not'. Tag filter is a key - value pair string where key and value are separated by a colon (:). + value pair string where key and value are separated by a colon (:). Default value is None. :type filter: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ProductsListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.ProductsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Product or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Product] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ProductsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ProductsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_invoice_section.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - 'invoiceSectionName': self._serialize.url("invoice_section_name", invoice_section_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_invoice_section_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + invoice_section_name=invoice_section_name, + filter=filter, + api_version=api_version, + template_url=self.list_by_invoice_section.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('ProductsListResult', pipeline_response) + deserialized = self._deserialize("ProductsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -359,292 +614,512 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_invoice_section.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/products'} # type: ignore + return ItemPaged(get_next, extract_data) - def get( - self, - billing_account_name, # type: str - product_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.Product" + list_by_invoice_section.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/products"} # type: ignore + + @distributed_trace + def get(self, billing_account_name: str, product_name: str, **kwargs: Any) -> _models.Product: """Gets a product by ID. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param product_name: The ID that uniquely identifies a product. + :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Product, or the result of cls(response) + :return: Product or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Product - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Product"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" - - # Construct URL - url = self.get.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'productName': self._serialize.url("product_name", product_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Product] + + request = build_get_request( + billing_account_name=billing_account_name, + product_name=product_name, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Product', pipeline_response) + deserialized = self._deserialize("Product", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}'} # type: ignore + get.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}"} # type: ignore + + @overload def update( self, - billing_account_name, # type: str - product_name, # type: str - parameters, # type: "_models.Product" - **kwargs # type: Any - ): - # type: (...) -> "_models.Product" + billing_account_name: str, + product_name: str, + parameters: _models.Product, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Product: """Updates the properties of a Product. Currently, auto renew can be updated. The operation is supported only for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param product_name: The ID that uniquely identifies a product. + :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the update product operation. + Required. :type parameters: ~azure.mgmt.billing.models.Product + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Product or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.Product + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + billing_account_name: str, + product_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Product: + """Updates the properties of a Product. Currently, auto renew can be updated. The operation is + supported only for billing accounts with agreement type Microsoft Customer Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param product_name: The ID that uniquely identifies a product. Required. + :type product_name: str + :param parameters: Request parameters that are provided to the update product operation. + Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Product or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.Product + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update( + self, billing_account_name: str, product_name: str, parameters: Union[_models.Product, IO], **kwargs: Any + ) -> _models.Product: + """Updates the properties of a Product. Currently, auto renew can be updated. The operation is + supported only for billing accounts with agreement type Microsoft Customer Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param product_name: The ID that uniquely identifies a product. Required. + :type product_name: str + :param parameters: Request parameters that are provided to the update product operation. Is + either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.billing.models.Product or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Product, or the result of cls(response) + :return: Product or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Product - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Product"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.update.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'productName': self._serialize.url("product_name", product_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'Product') - body_content_kwargs['content'] = body_content - request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Product] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Product") + + request = build_update_request( + billing_account_name=billing_account_name, + product_name=product_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.update.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Product', pipeline_response) + deserialized = self._deserialize("Product", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}'} # type: ignore + update.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}"} # type: ignore + + @overload def move( self, - billing_account_name, # type: str - product_name, # type: str - parameters, # type: "_models.TransferProductRequestProperties" - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.Product"] + billing_account_name: str, + product_name: str, + parameters: _models.TransferProductRequestProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Optional[_models.Product]: """Moves a product's charges to a new invoice section. The new invoice section must belong to the same billing profile as the existing invoice section. This operation is supported only for products that are purchased with a recurring charge and for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param product_name: The ID that uniquely identifies a product. + :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the move product operation. + Required. :type parameters: ~azure.mgmt.billing.models.TransferProductRequestProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Product, or the result of cls(response) + :return: Product or None or the result of cls(response) :rtype: ~azure.mgmt.billing.models.Product or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def move( + self, + billing_account_name: str, + product_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Optional[_models.Product]: + """Moves a product's charges to a new invoice section. The new invoice section must belong to the + same billing profile as the existing invoice section. This operation is supported only for + products that are purchased with a recurring charge and for billing accounts with agreement + type Microsoft Customer Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param product_name: The ID that uniquely identifies a product. Required. + :type product_name: str + :param parameters: Request parameters that are provided to the move product operation. + Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Product or None or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.Product or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def move( + self, + billing_account_name: str, + product_name: str, + parameters: Union[_models.TransferProductRequestProperties, IO], + **kwargs: Any + ) -> Optional[_models.Product]: + """Moves a product's charges to a new invoice section. The new invoice section must belong to the + same billing profile as the existing invoice section. This operation is supported only for + products that are purchased with a recurring charge and for billing accounts with agreement + type Microsoft Customer Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param product_name: The ID that uniquely identifies a product. Required. + :type product_name: str + :param parameters: Request parameters that are provided to the move product operation. Is + either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.billing.models.TransferProductRequestProperties or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Product or None or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.Product or None + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Product"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.move.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'productName': self._serialize.url("product_name", product_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'TransferProductRequestProperties') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.Product]] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "TransferProductRequestProperties") + + request = build_move_request( + billing_account_name=billing_account_name, + product_name=product_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.move.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - response_headers = {} deserialized = None + response_headers = {} if response.status_code == 200: - deserialized = self._deserialize('Product', pipeline_response) + deserialized = self._deserialize("Product", pipeline_response) if response.status_code == 202: - response_headers['Location']=self._deserialize('str', response.headers.get('Location')) - response_headers['Retry-After']=self._deserialize('int', response.headers.get('Retry-After')) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized - move.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}/move'} # type: ignore + move.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}/move"} # type: ignore + + @overload def validate_move( self, - billing_account_name, # type: str - product_name, # type: str - parameters, # type: "_models.TransferProductRequestProperties" - **kwargs # type: Any - ): - # type: (...) -> "_models.ValidateProductTransferEligibilityResult" + billing_account_name: str, + product_name: str, + parameters: _models.TransferProductRequestProperties, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ValidateProductTransferEligibilityResult: """Validates if a product's charges can be moved to a new invoice section. This operation is supported only for products that are purchased with a recurring charge and for billing accounts with agreement type Microsoft Customer Agreement. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param product_name: The ID that uniquely identifies a product. + :param product_name: The ID that uniquely identifies a product. Required. :type product_name: str :param parameters: Request parameters that are provided to the validate move eligibility - operation. + operation. Required. :type parameters: ~azure.mgmt.billing.models.TransferProductRequestProperties + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ValidateProductTransferEligibilityResult, or the result of cls(response) + :return: ValidateProductTransferEligibilityResult or the result of cls(response) :rtype: ~azure.mgmt.billing.models.ValidateProductTransferEligibilityResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def validate_move( + self, + billing_account_name: str, + product_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ValidateProductTransferEligibilityResult: + """Validates if a product's charges can be moved to a new invoice section. This operation is + supported only for products that are purchased with a recurring charge and for billing accounts + with agreement type Microsoft Customer Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param product_name: The ID that uniquely identifies a product. Required. + :type product_name: str + :param parameters: Request parameters that are provided to the validate move eligibility + operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ValidateProductTransferEligibilityResult or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.ValidateProductTransferEligibilityResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def validate_move( + self, + billing_account_name: str, + product_name: str, + parameters: Union[_models.TransferProductRequestProperties, IO], + **kwargs: Any + ) -> _models.ValidateProductTransferEligibilityResult: + """Validates if a product's charges can be moved to a new invoice section. This operation is + supported only for products that are purchased with a recurring charge and for billing accounts + with agreement type Microsoft Customer Agreement. + + :param billing_account_name: The ID that uniquely identifies a billing account. Required. + :type billing_account_name: str + :param product_name: The ID that uniquely identifies a product. Required. + :type product_name: str + :param parameters: Request parameters that are provided to the validate move eligibility + operation. Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.billing.models.TransferProductRequestProperties or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: ValidateProductTransferEligibilityResult or the result of cls(response) + :rtype: ~azure.mgmt.billing.models.ValidateProductTransferEligibilityResult + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ValidateProductTransferEligibilityResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.validate_move.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'productName': self._serialize.url("product_name", product_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'TransferProductRequestProperties') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ValidateProductTransferEligibilityResult] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "TransferProductRequestProperties") + + request = build_validate_move_request( + billing_account_name=billing_account_name, + product_name=product_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.validate_move.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('ValidateProductTransferEligibilityResult', pipeline_response) + deserialized = self._deserialize("ValidateProductTransferEligibilityResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - validate_move.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}/validateMoveEligibility'} # type: ignore + + validate_move.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}/validateMoveEligibility"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_reservations_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_reservations_operations.py index 3bb4d1c96b1e..ff999aba44b9 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_reservations_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_reservations_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,117 +6,210 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False -class ReservationsOperations(object): - """ReservationsOperations operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +def build_list_by_billing_account_request( + billing_account_name: str, + *, + filter: Optional[str] = None, + orderby: Optional[str] = None, + refresh_summary: Optional[str] = None, + selected_state: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/reservations") + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if orderby is not None: + _params["$orderby"] = _SERIALIZER.query("orderby", orderby, "str") + if refresh_summary is not None: + _params["refreshSummary"] = _SERIALIZER.query("refresh_summary", refresh_summary, "str") + if selected_state is not None: + _params["selectedState"] = _SERIALIZER.query("selected_state", selected_state, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_billing_profile_request( + billing_account_name: str, + billing_profile_name: str, + *, + filter: Optional[str] = None, + orderby: Optional[str] = None, + refresh_summary: Optional[str] = None, + selected_state: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/reservations", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "billingProfileName": _SERIALIZER.url("billing_profile_name", billing_profile_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if orderby is not None: + _params["$orderby"] = _SERIALIZER.query("orderby", orderby, "str") + if refresh_summary is not None: + _params["refreshSummary"] = _SERIALIZER.query("refresh_summary", refresh_summary, "str") + if selected_state is not None: + _params["selectedState"] = _SERIALIZER.query("selected_state", selected_state, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class ReservationsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.BillingManagementClient`'s + :attr:`reservations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_by_billing_account( self, - billing_account_name, # type: str - filter=None, # type: Optional[str] - orderby=None, # type: Optional[str] - refresh_summary=None, # type: Optional[str] - selected_state=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.ReservationsListResult"] + billing_account_name: str, + filter: Optional[str] = None, + orderby: Optional[str] = None, + refresh_summary: Optional[str] = None, + selected_state: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.Reservation"]: """Lists the reservations for a billing account and the roll up counts of reservations group by provisioning states. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str :param filter: May be used to filter by reservation properties. The filter supports 'eq', 'or', - and 'and'. It does not currently support 'ne', 'gt', 'le', 'ge', or 'not'. + and 'and'. It does not currently support 'ne', 'gt', 'le', 'ge', or 'not'. Default value is + None. :type filter: str - :param orderby: May be used to sort order by reservation properties. + :param orderby: May be used to sort order by reservation properties. Default value is None. :type orderby: str :param refresh_summary: To indicate whether to refresh the roll up counts of the reservations - group by provisioning states. + group by provisioning states. Default value is None. :type refresh_summary: str - :param selected_state: The selected provisioning state. + :param selected_state: The selected provisioning state. Default value is None. :type selected_state: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ReservationsListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.ReservationsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Reservation or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Reservation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ReservationsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ReservationsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_account.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - if orderby is not None: - query_parameters['$orderby'] = self._serialize.query("orderby", orderby, 'str') - if refresh_summary is not None: - query_parameters['refreshSummary'] = self._serialize.query("refresh_summary", refresh_summary, 'str') - if selected_state is not None: - query_parameters['selectedState'] = self._serialize.query("selected_state", selected_state, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_account_request( + billing_account_name=billing_account_name, + filter=filter, + orderby=orderby, + refresh_summary=refresh_summary, + selected_state=selected_state, + api_version=api_version, + template_url=self.list_by_billing_account.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('ReservationsListResult', pipeline_response) + deserialized = self._deserialize("ReservationsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -124,96 +218,97 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_billing_account.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/reservations'} # type: ignore + return ItemPaged(get_next, extract_data) + list_by_billing_account.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/reservations"} # type: ignore + + @distributed_trace def list_by_billing_profile( self, - billing_account_name, # type: str - billing_profile_name, # type: str - filter=None, # type: Optional[str] - orderby=None, # type: Optional[str] - refresh_summary=None, # type: Optional[str] - selected_state=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.ReservationsListResult"] + billing_account_name: str, + billing_profile_name: str, + filter: Optional[str] = None, + orderby: Optional[str] = None, + refresh_summary: Optional[str] = None, + selected_state: Optional[str] = None, + **kwargs: Any + ) -> Iterable["_models.Reservation"]: """Lists the reservations for a billing profile and the roll up counts of reservations group by provisioning state. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param billing_profile_name: The ID that uniquely identifies a billing profile. + :param billing_profile_name: The ID that uniquely identifies a billing profile. Required. :type billing_profile_name: str :param filter: May be used to filter by reservation properties. The filter supports 'eq', 'or', - and 'and'. It does not currently support 'ne', 'gt', 'le', 'ge', or 'not'. + and 'and'. It does not currently support 'ne', 'gt', 'le', 'ge', or 'not'. Default value is + None. :type filter: str - :param orderby: May be used to sort order by reservation properties. + :param orderby: May be used to sort order by reservation properties. Default value is None. :type orderby: str :param refresh_summary: To indicate whether to refresh the roll up counts of the reservations - group by provisioning state. + group by provisioning state. Default value is None. :type refresh_summary: str - :param selected_state: The selected provisioning state. + :param selected_state: The selected provisioning state. Default value is None. :type selected_state: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ReservationsListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.ReservationsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Reservation or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Reservation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ReservationsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ReservationsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_billing_profile.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'billingProfileName': self._serialize.url("billing_profile_name", billing_profile_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') - if orderby is not None: - query_parameters['$orderby'] = self._serialize.query("orderby", orderby, 'str') - if refresh_summary is not None: - query_parameters['refreshSummary'] = self._serialize.query("refresh_summary", refresh_summary, 'str') - if selected_state is not None: - query_parameters['selectedState'] = self._serialize.query("selected_state", selected_state, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_billing_profile_request( + billing_account_name=billing_account_name, + billing_profile_name=billing_profile_name, + filter=filter, + orderby=orderby, + refresh_summary=refresh_summary, + selected_state=selected_state, + api_version=api_version, + template_url=self.list_by_billing_profile.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('ReservationsListResult', pipeline_response) + deserialized = self._deserialize("ReservationsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -222,17 +317,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_billing_profile.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/reservations'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_by_billing_profile.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/reservations"} # type: ignore diff --git a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_transactions_operations.py b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_transactions_operations.py index 4eb99fe2bdb8..a6bc3881d308 100644 --- a/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_transactions_operations.py +++ b/sdk/billing/azure-mgmt-billing/azure/mgmt/billing/operations/_transactions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,99 +6,135 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_by_invoice_request(billing_account_name: str, invoice_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}/transactions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "billingAccountName": _SERIALIZER.url("billing_account_name", billing_account_name, "str"), + "invoiceName": _SERIALIZER.url("invoice_name", invoice_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") -class TransactionsOperations(object): - """TransactionsOperations operations. + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.billing.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. +class TransactionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.billing.BillingManagementClient`'s + :attr:`transactions` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + @distributed_trace def list_by_invoice( - self, - billing_account_name, # type: str - invoice_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.TransactionListResult"] + self, billing_account_name: str, invoice_name: str, **kwargs: Any + ) -> Iterable["_models.Transaction"]: """Lists the transactions for an invoice. Transactions include purchases, refunds and Azure usage charges. - :param billing_account_name: The ID that uniquely identifies a billing account. + :param billing_account_name: The ID that uniquely identifies a billing account. Required. :type billing_account_name: str - :param invoice_name: The ID that uniquely identifies an invoice. + :param invoice_name: The ID that uniquely identifies an invoice. Required. :type invoice_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either TransactionListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.TransactionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Transaction or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.billing.models.Transaction] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.TransactionListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.TransactionListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-05-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_by_invoice.metadata['url'] # type: ignore - path_format_arguments = { - 'billingAccountName': self._serialize.url("billing_account_name", billing_account_name, 'str'), - 'invoiceName': self._serialize.url("invoice_name", invoice_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + + request = build_list_by_invoice_request( + billing_account_name=billing_account_name, + invoice_name=invoice_name, + api_version=api_version, + template_url=self.list_by_invoice.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('TransactionListResult', pipeline_response) + deserialized = self._deserialize("TransactionListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -106,17 +143,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_by_invoice.metadata = {'url': '/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}/transactions'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_by_invoice.metadata = {"url": "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoices/{invoiceName}/transactions"} # type: ignore