from dataclasses import dataclass from typing import ClassVar from anydi import singleton from fansifter_common.auth.account import Account from fansifter_common.auth.exceptions import PermissionDenied from fansifter_common.auth.services import AuthService from fansifter_common.auth.types import Permission from dmp.shopify.dtos import ShopifyStore from dmp.shopify.repositories import StoreAssociationRepository from dmp.shopify.types import ShopifyStoreOrderBy @dataclass(frozen=True) class GetStoresV2Request: identity_id: str vendor_id: int | None subaccount_id: int | None limit: int offset: int order_by: list[ShopifyStoreOrderBy] DEFAULT_LIMIT: ClassVar[int] = 10 DEFAULT_OFFSET: ClassVar[int] = 0 DEFAULT_ORDER_BY: ClassVar[list[ShopifyStoreOrderBy]] = [ "vendorId.asc.nullsFirst", "name.asc", ] @dataclass(frozen=True) class GetStoresV2Response: total: int items: list[ShopifyStore] @singleton class GetStoresV2Handler: permission = Permission("fan_data_channel", "view") def __init__( self, auth_service: AuthService, store_association_repository: StoreAssociationRepository, ) -> None: self.auth_service = auth_service self.store_association_repository = store_association_repository def handle(self, request: GetStoresV2Request) -> GetStoresV2Response: account_access = self.auth_service.authorize_for_permission( request.identity_id, permission=self.permission ) if request.vendor_id is not None and request.subaccount_id is not None: if not account_access.has_access( Account( vendor_id=request.vendor_id, subaccount_id=request.subaccount_id, ) ): raise PermissionDenied vendor_ids = account_access.filter_vendor_ids(request.vendor_id) subaccount_ids = account_access.filter_subaccount_ids(request.subaccount_id) total = self.store_association_repository.count_by_account_ids( vendor_ids=vendor_ids, subaccount_ids=subaccount_ids, ) if total == 0: return GetStoresV2Response(total=0, items=[]) items = self.store_association_repository.find_paginated( vendor_ids=vendor_ids, subaccount_ids=subaccount_ids, limit=request.limit, offset=request.offset, order_by=request.order_by, ) return GetStoresV2Response(total=total, items=items)