Source code for smarter.apps.account.manifest.brokers.account

# pylint: disable=W0718
"""Smarter API Account Manifest handler."""

import datetime
import traceback
from typing import TYPE_CHECKING, List, Optional, Type

from django.core import serializers
from rest_framework.serializers import ModelSerializer

from smarter.apps.account.manifest.models.account.const import MANIFEST_KIND
from smarter.apps.account.manifest.models.account.metadata import SAMAccountMetadata
from smarter.apps.account.manifest.models.account.model import SAMAccount
from smarter.apps.account.manifest.models.account.spec import (
    SAMAccountSpec,
    SAMAccountSpecConfig,
)
from smarter.apps.account.manifest.models.account.status import SAMAccountStatus
from smarter.apps.account.models import Account, User, UserProfile
from smarter.common.utils.decorators import camel_case
from smarter.lib import json, logging
from smarter.lib.django.waffle import SmarterWaffleSwitches
from smarter.lib.journal.enum import SmarterJournalCliCommands
from smarter.lib.journal.http import SmarterJournaledJsonResponse
from smarter.lib.manifest.broker import (
    AbstractBroker,
    SAMBrokerError,
    SAMBrokerErrorNotFound,
    SAMBrokerErrorNotImplemented,
    SAMBrokerErrorNotReady,
    SAMDependency,
    SAMDependents,
    memoized_dependencies,
)
from smarter.lib.manifest.enum import (
    SAMKeys,
    SAMMetadataKeys,
    SCLIResponseGet,
    SCLIResponseGetData,
)
from smarter.lib.typing import SmarterDictType, required

if TYPE_CHECKING:
    from django.http import HttpRequest


logger = logging.getSmarterLogger(
    __name__, any_switches=[SmarterWaffleSwitches.ACCOUNT_LOGGING, SmarterWaffleSwitches.MANIFEST_LOGGING]
)


MAX_RESULTS = 1000


[docs] class AccountSerializer(ModelSerializer): """Account serializer for smarter api.""" # pylint: disable=missing-class-docstring class Meta: model = Account fields = ["account_number", "company_name", "created_at", "updated_at"]
[docs] class SAMAccountBrokerError(SAMBrokerError): """Base exception for Smarter API Account Broker handling.""" @property def get_formatted_err_message(self): """The label of this error, used in its string form.""" return "Smarter API Account Manifest Broker Error"
[docs] class SAMAccountBroker(AbstractBroker[Account, Account]): """ Handles Smarter API Account Manifest operations, including loading, validating, and parsing YAML manifests, and mapping them to Django ORM and Pydantic models. This broker transforms between Django ORM and Pydantic models, ensuring data consistency for serialization and API responses. This broker is responsible for: - Loading and validating Smarter API Account manifests. - Initializing the corresponding Pydantic model from manifest data. - Creating, updating, deleting, and querying Django ORM models representing account manifests. - Transforming Django ORM models into Pydantic models for serialization and deserialization. :param _manifest: The current manifest instance (`SAMAccount`), if loaded. :type _manifest: Optional[SAMAccount] :param _pydantic_model: The Pydantic model class used for manifests. :type _pydantic_model: Type[SAMAccount] :param _account: The Django ORM `Account` instance associated with the manifest. :type _account: Optional[Account] .. note:: The manifest must be explicitly initialized with manifest data, typically using ``**data`` from the client's manifest data. .. warning:: If the manifest data or its metadata is missing, or if the account is not set, the manifest will not be initialized and may return ``None`` or raise an exception. **Example usage**:: broker = SAMAccountBroker() manifest = broker.manifest if manifest: print(manifest.apiVersion, manifest.kind) .. seealso:: - :class:`SAMAccount` - :class:`Account` - :class:`SAMAccountMetadata` - :class:`SAMAccountSpec` .. versionadded:: 1.0.0 Initial implementation of the Smarter API Account Manifest Broker. """ # override the base abstract manifest model with the Account model _manifest: Optional[SAMAccount] = None _pydantic_model: Type[SAMAccount] = SAMAccount _brokered_account: Optional[Account] = None _orm_instance: Optional[Account] = None _orm_meta_instance: Optional[Account] = None
[docs] def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) logger.debug( "broker for %s %s is %s.", self.kind, self.name, self.ready_state, )
########################################################################### # Smarter abstract property implementations ########################################################################### @property def brokered_account(self) -> Optional[Account]: """ In order to disambiguate between the AccountMixin.account. (the authenticated account making the request) and the Account resource being brokered, we use the term "brokered_account". Get the Django ORM `Account` instance associated with this broker. :returns: The `Account` instance if set, otherwise None. :rtype: Optional[Account] """ if self._brokered_account: return self._brokered_account if not self.name: logger.debug("no name provided, cannot retrieve Account.") return None try: self._brokered_account = Account.get_cached_object(name=self.name) logger.debug( "initialized existing Account: %s", self._brokered_account, ) except Account.DoesNotExist: logger.debug("no existing Account found with name: %s", self.name) self._brokered_account = None return self._brokered_account @brokered_account.setter def brokered_account(self, value: Account) -> None: """ Set the Django ORM `Account` instance associated with this broker. :param value: The `Account` instance to set. :type value: Account """ self._brokered_account = value logger.debug("set to Account: %s", self._brokered_account) @property def formatted_class_name(self) -> str: """ Returns a formatted class name string for use in logging, providing a more readable identifier for this broker class. :returns: The formatted class name, including the parent class and `SAMAccountBroker()`. :rtype: str **Example usage**:: logger.info(broker.formatted_class_name) """ parent_class = super().formatted_class_name this_class = f".{SAMAccountBroker.__name__}[{id(self)}]" return f"{parent_class}{self.formatted_text(this_class)}" @property def kind(self) -> str: """ Get the manifest kind for the Smarter API Account. :returns: The manifest kind string for the Smarter API Account. :rtype: str """ return MANIFEST_KIND @property def name(self) -> Optional[str]: """ Get the name of the Smarter API Account. :returns: The name of the Smarter API Account, or None if not set. :rtype: Optional[str] """ retval = super().name if retval: return retval if self._brokered_account: return str(self._brokered_account.name) return None @property def manifest(self) -> Optional[SAMAccount]: """ Get the manifest for the Smarter API Account as a Pydantic model. :returns: A `SAMAccount` Pydantic model instance representing the Smarter API Account manifest, or None if not initialized. .. note:: The top-level manifest model (`SAMAccount`) must be explicitly initialized with manifest data, typically using ``**data`` from the client's manifest data. .. tip:: Child models within the manifest are automatically cascade-initialized by Pydantic, passing ``**data`` to each child's constructor. .. warning:: If the manifest data or its metadata is missing, or if the account is not set, the manifest will not be initialized and None may be returned or an exception raised. **Example usage**:: # Access the manifest property manifest = broker.manifest if manifest: print(manifest.apiVersion, manifest.kind) """ if self._manifest: if not isinstance(self._manifest, SAMAccount): raise SAMAccountBrokerError( message=f"Invalid manifest type for {self.kind} broker: {type(self._manifest)}", thing=self.kind, command=SmarterJournalCliCommands.APPLY, ) return self._manifest # 1.) prioritize the client's manifest data if available. if it was provided # in the request body then this is the authoritative source. if self.manifest_data is not None: self._manifest = SAMAccount.model_validate(self.manifest_sections) logger.debug( "initialized %s from manifest data: %s", type(self._manifest).__name__, json.dumps(self._manifest.model_dump(), indent=4), ) return self._manifest # 2.) next, (and only if there is no manifest data) try to initialize # from existing Account model if available elif self.brokered_account: account_number = str(self.brokered_account.account_number) status = SAMAccountStatus( adminAccount=account_number, recordLocator=self.brokered_account.record_locator, created=required(self.brokered_account.created_at, "account.created_at"), modified=required(self.brokered_account.updated_at, "account.updated_at"), ) metadata = SAMAccountMetadata( name=str(self.brokered_account.name) or account_number.replace(" ", "_"), description=self.brokered_account.company_name, version=self.brokered_account.version, tags=self.brokered_account.tags_list, accountNumber=self.brokered_account.account_number, annotations=self.brokered_account.annotations, ) config = SAMAccountSpecConfig( companyName=self.brokered_account.company_name or "missing company name", phoneNumber=self.brokered_account.phone_number or "missing phone number", address1=self.brokered_account.address1 or "missing address1", address2=self.brokered_account.address2 or "missing address2", city=self.brokered_account.city or "missing city", state=self.brokered_account.state or "missing state", postalCode=self.brokered_account.postal_code or "missing postal code", country=self.brokered_account.country or "US", language=self.brokered_account.language or "en-US", timezone=self.brokered_account.timezone or "America/New_York", currency=self.brokered_account.currency or "USD", parent=self.related_account_number(self.brokered_account.parent_id), # type: ignore[attr-defined] shareScope=self.related_account_number(self.brokered_account.share_scope_id), # type: ignore[attr-defined] ) self._manifest = SAMAccount( apiVersion=self.api_version, kind=self.kind, metadata=metadata, spec=SAMAccountSpec(config=config), status=status, ) logger.debug( "initialized %s from Account ORM model %s: %s", type(self._manifest).__name__, self.brokered_account, serializers.serialize("json", [self.brokered_account]), ) return self._manifest else: logger.debug("could not be initialized") return self._manifest @property def SerializerClass(self) -> Type[AccountSerializer]: """ Get the Django REST Framework serializer class for the Smarter API Account. :returns: The `AccountSerializer` class. :rtype: Type[ModelSerializer] """ return AccountSerializer ########################################################################### # Transformation methods ###########################################################################
[docs] def manifest_to_django_orm(self) -> SmarterDictType: """Transform the Smarter API Account manifest into a Django ORM model.""" if not isinstance(self.manifest, SAMAccount): raise SAMAccountBrokerError( message=f"Invalid manifest type for {self.kind} broker: {type(self.manifest)}", thing=self.kind, command=SmarterJournalCliCommands.APPLY, ) metadata = super().manifest_to_django_orm() config_dump = self.manifest.spec.config.model_dump() config_dump = self.to_snake_case(config_dump) if not isinstance(config_dump, dict): raise SAMAccountBrokerError( message=f"Invalid config dump for {self.kind} manifest: {config_dump}", thing=self.kind, command=SmarterJournalCliCommands.APPLY, ) if self.brokered_account is None: raise SAMBrokerErrorNotReady( f"Account not set for {self.kind} broker. Cannot apply.", thing=self.thing, command=SmarterJournalCliCommands.APPLY, ) if self.manifest is None: raise SAMBrokerErrorNotReady( f"Manifest not set for {self.kind} broker. Cannot apply.", thing=self.thing, command=SmarterJournalCliCommands.APPLY, ) # the account tree's fields are account numbers in the manifest, and accounts in the model. parent_account_number = config_dump.pop("parent", None) share_scope_account_number = config_dump.pop("share_scope", None) parent = self.account_by_number(parent_account_number, "parent") share_scope = self.account_by_number(share_scope_account_number, "shareScope") # Convert tags (list[str]) to set for TaggableManager compatibility return { **metadata, "account": self.brokered_account, **config_dump, "parent": parent, "share_scope": share_scope, }
[docs] def account_by_number(self, account_number: Optional[str], field_name: str) -> Optional[Account]: """ The account that ``parent`` or ``shareScope`` names. :param account_number: The account number from the manifest, or None. :param field_name: The manifest field, for the error message. :returns: The account, or None if the manifest omits the field. :raises SAMAccountBrokerError: if no account has that number. """ if account_number is None: return None account = Account.objects.filter(account_number=account_number).first() if account is None: raise SAMAccountBrokerError( message=f"{field_name}: no account has the number {account_number}.", thing=self.kind, command=SmarterJournalCliCommands.APPLY, ) return account
[docs] @staticmethod def related_account_number(account_id: Optional[int]) -> Optional[str]: """ The account number of ``parent`` or ``share_scope``, for a manifest. :param account_id: The related account's id, or None. :returns: Its account number, or None. """ if account_id is None: return None account = Account.get_cached_object(pk=account_id) if account is None: return None return account.account_number
[docs] @camel_case() def django_orm_to_manifest_dict(self) -> SmarterDictType: """ Converts a Django ORM `Account` model instance into a Pydantic-compatible Smarter API Account manifest dictionary. :returns: Dictionary formatted for Pydantic model consumption, suitable for serialization and API responses. :rtype: dict :raises SAMBrokerErrorNotReady: If the broker's account is not set. :raises SAMAccountBrokerError: If the account data is invalid or cannot be converted. .. note:: The output uses camelCase keys for compatibility with Pydantic models and API consumers. **Example usage**:: manifest_dict = broker.django_orm_to_manifest_dict() print(manifest_dict["apiVersion"], manifest_dict["kind"]) .. seealso:: - :meth:`manifest_to_django_orm` - :class:`SAMAccount` - :class:`Account` .. versionchanged:: 1.0.0 Method now ensures camelCase conversion and excludes the primary key field. """ if self.brokered_account is None: raise SAMBrokerErrorNotFound( f"Account not set for {self.kind} broker. Cannot describe.", thing=self.thing, command=SmarterJournalCliCommands.DESCRIBE, ) if self.manifest is None: raise SAMBrokerErrorNotFound( f"Manifest not set for {self.kind} broker. Cannot describe.", thing=self.thing, command=SmarterJournalCliCommands.DESCRIBE, ) return self.manifest.model_dump()
########################################################################### # Smarter manifest abstract method implementations ########################################################################### @property def ORMMetaModelClass(self) -> Type[Account]: """ Return the Django ORM meta model class for the broker. :return: The Django ORM meta model class definition for the broker. :rtype: Type[Account] """ return Account @property def ORMModelClass(self) -> Type[Account]: """ Get the Django ORM model class for the Smarter API Account. :returns: The Django ORM `Account` model class. :rtype: Type[Account] """ return Account @property def orm_instance(self) -> Optional[Account]: """ Return the Django ORM model instance for the broker. :return: The Django ORM model instance for the broker. :rtype: Optional[TimestampedModel] """ if self._orm_instance: return self._orm_instance if self.orm_meta_instance: self._orm_instance = self.orm_meta_instance # type: ignore return self._orm_instance # DEBUG: commands such as example-manifest and json-schema need no name. The # commands that do need one fail with their own error. if not self.name: logger.debug( "no name, so there is no %s instance to retrieve", Account.__name__, ) return None try: logger.debug( "attempting to retrieve %s instance for user=%s, name=%s", Account.__name__, self.user, self.name, ) self._orm_instance = Account.get_cached_object(name=self.name) if self._orm_instance: logger.debug( "retrieved %s instance: %s", Account.__name__, serializers.serialize("json", [self._orm_instance]), # type: ignore[list-item] ) else: logger.debug( "no %s instance found for name: %s", Account.__name__, self.name, ) return self._orm_instance except Account.DoesNotExist: # DEBUG: the caller decides whether a missing Account is an error, e.g. describe # answers 404. logger.debug( "%s instance does not exist for account=%s, name=%s", Account.__name__, self.account, self.name, ) return None
[docs] def orm_meta_instance_setter(self) -> None: """Override of parent method to initialize the Django ORM meta model instance for the broker.""" if self._orm_instance: logger.debug( "ORM instance is already set. Setting ORM meta instance to ORM instance.", ) self._orm_meta_instance = self._orm_instance # type: ignore return if not self.name: logger.debug( "name is not set. Cannot retrieve ORM meta instance for %s.", Account.__name__, ) return self._orm_meta_instance = None try: self._orm_meta_instance = Account.get_cached_object(name=self.name) except Account.DoesNotExist: logger.warning( "ORM meta instance does not exist for account=%s, name=%s", self.account, self.name, ) except Exception as e: logger.error( "unexpected error retrieving ORM meta instance for account=%s, name=%s: %s", self.account, self.name, e, )
@property def SAMModelClass(self) -> Type[SAMAccount]: """ Return the Pydantic model class for the broker. :return: The Pydantic model class definition for the broker. :rtype: Type[SAMAccount] """ return SAMAccount
[docs] def cache_invalidations(self) -> None: """ Handle broker specific cache invalidation logic. Invalidates the cache for the `Account` and `UserProfile` models. """ logger.debug("called.", prefix_format=logging.SmarterFormattedText.BOLD_DARK_BLUE) Account.get_cached_object(invalidate=True, pk=self.brokered_account.id) # type: ignore # brokered_account is retrieved by name, which is cached separately from pk. Account.get_cached_object(invalidate=True, name=self.brokered_account.name) # type: ignore Account.get_cached_object(invalidate=True, account_number=self.brokered_account.account_number) # type: ignore # only an account with members has a cached profile. get_cached_object() would otherwise find an # administrator for a new, empty account, and create one. if UserProfile.objects.filter(account=self.brokered_account).exists(): UserProfile.get_cached_object(invalidate=True, account=self.brokered_account) return super().cache_invalidations()
[docs] def example_manifest(self, request: "HttpRequest", *args, **kwargs) -> SmarterJournaledJsonResponse: """ Return an example manifest for the Smarter API Account. :returns: A JSON response containing an example Smarter API Account manifest. :rtype: SmarterJournaledJsonResponse See Also: - :class:`SAMAccount` - :class:`SAMAccountMetadata` - :class:`SAMAccountSpec` - :class:`SAMKeys` - :class:`SAMMetadataKeys` - :class:`SAMAccountSpecKeys` """ command = SmarterJournalCliCommands(self.example_manifest.__name__) logger.debug("called") metadata = SAMAccountMetadata( name="example_account", description="An example Smarter API manifest for an Account", version="0.1.0", tags=["example"], annotations={}, accountNumber="123456789", ) spec = SAMAccountSpec( config=SAMAccountSpecConfig( companyName="Example Company Inc.", parent=None, shareScope=None, phoneNumber="555-123-4567", address1="123 Example St.", address2="Suite 100", city="Exampleville", state="EX", postalCode="12345", country="US", language="en-US", timezone="America/New_York", currency="USD", ) ) status = SAMAccountStatus( adminAccount="123456789", recordLocator="abc123", created=datetime.datetime(2024, 1, 1, 0, 0, 0, tzinfo=datetime.timezone.utc), modified=datetime.datetime(2024, 1, 2, 0, 0, 0, tzinfo=datetime.timezone.utc), ) manifest = SAMAccount( apiVersion=self.api_version, kind=self.kind, metadata=metadata, spec=spec, status=status, ) return self.json_response_ok(command=command, data=manifest.model_dump())
[docs] def get(self, request: "HttpRequest", *args, **kwargs) -> SmarterJournaledJsonResponse: """ Get the manifest(s) for the Smarter API Account. :param request: The HTTP request object. :type request: "HttpRequest" :param args: Additional positional arguments. :param kwargs: Additional keyword arguments. :returns: A JSON response containing the Smarter API Account manifest(s). :rtype: SmarterJournaledJsonResponse :raises SAMBrokerErrorNotReady: If the broker's account is not set. :raises SAMAccountBrokerError: If there is an error retrieving or serializing the account data. """ # name: str = None, all_objects: bool = False, tags: str = None command = SmarterJournalCliCommands(self.get.__name__) logger.debug("called") items: list[SmarterDictType] = [] if not isinstance(self.user, User): raise SAMAccountBrokerError( message="User not set for broker. Cannot get.", thing=self.kind, command=command, ) if not self.user.is_superuser: raise SAMAccountBrokerError( message="Only superusers can view accounts.", thing=self.kind, command=command, ) name = self.clean_cli_param( param=kwargs.get(SAMMetadataKeys.NAME.value, None), param_name="name", url=self.smarter_build_absolute_uri(request), ) # returns Optional[list[dict[str, str]]]: # [ # {"name": "accountNumber", "type": "CharField"}, # {"name": "companyName", "type": "CharField"}, # {"name": "createdAt", "type": "DateTimeField"}, # {"name": "updatedAt", "type": "DateTimeField"}, # ] model_titles = self.get_model_titles(serializer=AccountSerializer()) accounts = Account.objects.all() if name: accounts = accounts.filter(name=name) accounts = self.filter_by_annotation_selector(accounts, kwargs) for account in accounts.order_by("name")[:MAX_RESULTS]: try: logger.debug("processing Account: %s", account) model_dump = AccountSerializer(account).data camel_cased_model_dump = self.to_camel_case(model_dump) items.append(camel_cased_model_dump) except Exception as e: logger.error("Error in %s: %s", command, e) return self.json_response_err(command=command, e=e) data = { SAMKeys.APIVERSION.value: self.api_version, SAMKeys.KIND.value: self.kind, SAMMetadataKeys.NAME.value: name, SAMKeys.METADATA.value: {"count": len(items)}, SCLIResponseGet.KWARGS.value: kwargs, SCLIResponseGet.DATA.value: { SCLIResponseGetData.TITLES.value: model_titles, SCLIResponseGetData.ITEMS.value: items, }, } return self.json_response_ok(command=command, data=data)
[docs] def apply_account_number(self, brokered_account: Account, command: SmarterJournalCliCommands) -> None: """ Give a new account the number that the manifest's ``metadata.accountNumber`` names, if it names one. An organization's manifests refer to its accounts by number, e.g. a User manifest's ``spec.accounts`` or a repository's ``owners.yaml``, so its accounts must have the same numbers on every platform that applies them. Only a superuser applies an Account manifest. An account's number never changes, so a manifest whose number differs from an existing account's is refused, as is a number that another account already has. :param brokered_account: The account, saved or new. :param command: The command, for the error. :raises SAMAccountBrokerError: if the number belongs to another account, or differs from the account's own. """ manifest = self.manifest if manifest is None or not manifest.metadata.accountNumber: return account_number = str(manifest.metadata.accountNumber) if brokered_account.pk is not None: if brokered_account.account_number != account_number: raise SAMAccountBrokerError( message=f"Account {brokered_account.account_number}'s number can't change to {account_number}.", thing=self.kind, command=command, ) return if Account.objects.filter(account_number=account_number).exists(): raise SAMAccountBrokerError( message=f"Another account already has the number {account_number}.", thing=self.kind, command=command ) brokered_account.account_number = account_number
[docs] def apply(self, request: "HttpRequest", *args, **kwargs) -> SmarterJournaledJsonResponse: """ Applies the manifest by copying its data to the Django ORM `Account` model and saving the model to the database. .. note:: tags are handled separately because they are of type TaggableManager and require a different method to set them. :param request: The HTTP request object. :type request: "HttpRequest" :param args: Additional positional arguments. :param kwargs: Additional keyword arguments. :returns: A JSON response indicating the result of the apply operation. :rtype: SmarterJournaledJsonResponse :raises SAMBrokerErrorNotReady: If the broker's account is not set. :raises SAMBrokerError: If an error occurs during the apply process. .. caution:: Fields that are not editable (such as ``id``, ``created_at``, ``updated_at``, and ``account_number``) are removed from the data before saving. **Example usage**:: response = broker.apply(request) print(response.status_code, response.data) .. seealso:: - :meth:`manifest_to_django_orm` - :meth:`django_orm_to_manifest_dict` """ logger.debug("called") command = SmarterJournalCliCommands(self.apply.__name__) if not isinstance(self.user, User): raise SAMAccountBrokerError( message="User not set for broker. Cannot apply.", thing=self.kind, command=command, ) if not self.user.is_superuser: raise SAMAccountBrokerError( message="Only superusers can apply account manifests.", thing=self.kind, command=command, ) readonly_fields = ["id", "created_at", "updated_at", "account_number", "tags"] if not self.manifest: raise SAMBrokerErrorNotReady( f"Manifest not set for {self.kind} broker. Cannot apply.", thing=self.thing, command=command, ) brokered_account = self.brokered_account if brokered_account is None: brokered_account = Account() self.brokered_account = brokered_account self.apply_account_number(brokered_account, command) try: data = self.manifest_to_django_orm() tags = data.get("tags", []) for field in readonly_fields: logger.debug( "Removing readonly field %s from data for %s", field, self.kind, ) data.pop(field, None) for key, value in data.items(): setattr(brokered_account, key, value) logger.debug("Setting %s to %s", key, value) logger.debug( "Saving %s: %s", brokered_account, serializers.serialize("json", [brokered_account]), ) brokered_account.save() brokered_account.tags.set(tags) tags = set(self.manifest.metadata.tags) if self.manifest.metadata.tags else set() brokered_account.tags.set(tags) brokered_account.refresh_from_db() logger.debug( "Saved %s with ID %s: %s", brokered_account, brokered_account.id, serializers.serialize("json", [brokered_account]), ) except Exception as e: tb = traceback.format_exc() raise SAMBrokerError(message=f"Error in {command}: {e}\n{tb}", thing=self.kind, command=command) from e self.cache_invalidations() return self.json_response_ok(command=command, data=self.command_result())
[docs] def prompt(self, request: "HttpRequest", *args, **kwargs) -> SmarterJournaledJsonResponse: """ Prompt functionality is not implemented for the Smarter API Account. :param request: The HTTP request object. :type request: "HttpRequest" :param args: Additional positional arguments. :param kwargs: Additional keyword arguments. :raises SAMBrokerErrorNotImplemented: Always raised to indicate that prompt is not implemented. :returns: A JSON response indicating that prompt is not implemented. :rtype: SmarterJournaledJsonResponse """ logger.debug("called") command = SmarterJournalCliCommands(self.prompt.__name__) raise SAMBrokerErrorNotImplemented(message="Prompt not implemented", thing=self.kind, command=command)
[docs] def describe(self, request: "HttpRequest", *args, **kwargs) -> SmarterJournaledJsonResponse: """ Describe the manifest for the Smarter API Account. :param request: The HTTP request object. :type request: "HttpRequest" :param args: Additional positional arguments. :param kwargs: Additional keyword arguments. :raises SAMBrokerErrorNotReady: Raised when no account is found. :returns: A JSON response with the manifest description. :rtype: SmarterJournaledJsonResponse """ command = SmarterJournalCliCommands(self.describe.__name__) logger.debug("called for %s", self.name) if not isinstance(self.user, User): raise SAMAccountBrokerError( message="User not set for broker. Cannot describe.", thing=self.kind, command=command, ) if not self.user.is_superuser: raise SAMAccountBrokerError( message="Only superusers can view accounts.", thing=self.kind, command=command, ) if not self.brokered_account: raise SAMBrokerErrorNotFound(message="No account found", thing=self.kind, command=command) try: data = self.django_orm_to_manifest_dict() logger.debug( "returning manifest for %s: %s", self.name, json.dumps(data, indent=4), ) return self.json_response_ok(command=command, data=data) except Exception as e: raise SAMBrokerError(message=f"Error in {command}: {str(e)}", thing=self.kind, command=command) from e
[docs] @classmethod def dependents(cls, instance: Account) -> SAMDependents: """Return the users that belong to an Account, as their UserProfiles. A User has no ``name`` field, so :meth:`dependencies` builds the User brokers itself, from these UserProfiles, with each user's username. Don't pass these rows to :meth:`dependency_brokers`. :param instance: The Account. :type instance: Account :return: The UserProfiles of the Account's users. :rtype: SAMDependents """ # pylint: disable=import-outside-toplevel from smarter.apps.api.v1.manifests.enum import SAMKinds return [(SAMKinds.USER.value, UserProfile.objects.filter(account=instance).select_related("user"))]
[docs] @classmethod def references(cls, instance: Account) -> SAMDependents: """Return the resources that an Account uses: none. :param instance: The Account. :type instance: Account :return: An empty list. :rtype: SAMDependents """ return []
[docs] @memoized_dependencies def dependencies(self) -> List[SAMDependency]: """Return brokers for the Users that belong to this Account. :return: A User broker for each of the Account's users. :rtype: List[SAMDependency] """ account = self.brokered_account if not account: return [] retval: List[SAMDependency] = [] for kind, user_profiles in self.dependents(account): for user_profile in user_profiles: # dependents() returns only UserProfiles, typed as plain Models. if not isinstance(user_profile, UserProfile): continue user = user_profile.user broker = self.dependency_broker(kind, user, name=user.username, user_profile=user_profile) # type: ignore[arg-type] retval.append(broker) return retval
[docs] def delete(self, request: "HttpRequest", *args, **kwargs) -> SmarterJournaledJsonResponse: """ .. attention:: Delete functionality is not implemented for the Smarter API Account. :param request: The HTTP request object. :type request: "HttpRequest" :param args: Additional positional arguments. :param kwargs: Additional keyword arguments. :raises SAMBrokerErrorNotImplemented: Always raised to indicate that delete is not implemented. :returns: A JSON response indicating that delete is not implemented. :rtype: SmarterJournaledJsonResponse """ logger.debug("called") command = SmarterJournalCliCommands(self.delete.__name__) raise SAMBrokerErrorNotImplemented(message="Delete not implemented", thing=self.kind, command=command)
[docs] def deploy(self, request: "HttpRequest", *args, **kwargs) -> SmarterJournaledJsonResponse: """ .. attention:: Deploy functionality is not implemented for the Smarter API Account. :param request: The HTTP request object. :type request: "HttpRequest" :param args: Additional positional arguments. :param kwargs: Additional keyword arguments. :raises SAMBrokerErrorNotImplemented: Always raised to indicate that deploy is not implemented. :returns: A JSON response indicating that deploy is not implemented. :rtype: SmarterJournaledJsonResponse """ logger.debug("called") command = SmarterJournalCliCommands(self.deploy.__name__) raise SAMBrokerErrorNotImplemented(message="Deploy not implemented", thing=self.kind, command=command)
[docs] def undeploy(self, request: "HttpRequest", *args, **kwargs) -> SmarterJournaledJsonResponse: """ .. attention:: Undeploy functionality is not implemented for the Smarter API Account. :param request: The HTTP request object. :type request: "HttpRequest" :param args: Additional positional arguments. :param kwargs: Additional keyword arguments. :raises SAMBrokerErrorNotImplemented: Always raised to indicate that undeploy is not implemented. :returns: A JSON response indicating that undeploy is not implemented. :rtype: SmarterJournaledJsonResponse """ logger.debug("called") command = SmarterJournalCliCommands(self.undeploy.__name__) raise SAMBrokerErrorNotImplemented(message="Undeploy not implemented", thing=self.kind, command=command)
[docs] def logs(self, request: "HttpRequest", *args, **kwargs) -> SmarterJournaledJsonResponse: """ .. attention:: Logs functionality is not implemented for the Smarter API Account. :param request: The HTTP request object. :type request: "HttpRequest" :param args: Additional positional arguments. :param kwargs: Additional keyword arguments. :returns: A JSON response indicating that logs is not implemented. :rtype: SmarterJournaledJsonResponse """ logger.debug("called") command = SmarterJournalCliCommands(self.logs.__name__) data: SmarterDictType = {} return self.json_response_ok(command=command, data=data)