"""Settlement API mixins.

客户可见性绕过逻辑与 printing 模块的 CustomerVisibilityFilterMixin 对齐：
- superuser → 无过滤
- 持有 view_all_permission → 无过滤
- 其余普通员工 → settlement service 按 created_by / visible_employees 过滤

settlement.services._get_plate_order_queryset 已通过 ``user=None`` 判断来
决定是否施加可见性过滤，故基类只需控制向 service 传入的 user 参数即可。
"""

from __future__ import annotations


class SettlementVisibilityMixin:
    """
    Settlement API 客户可见性绕过基类。

    使用方式：
        class MySettlementView(SettlementVisibilityMixin, APIView):
            view_all_permission = 'printing.view_all_plateorders'

    绕过规则（与 CustomerVisibilityFilterMixin 保持一致）：
    - user.is_superuser → 绕过
    - user.has_perm(view_all_permission) → 绕过
    - 其余 → 透传原始 user，service 自行应用 visible_employees 过滤
    """

    # 子类可覆盖为自定义权限名
    view_all_permission: str | None = 'printing.view_all_plateorders'

    def can_bypass_settlement_visibility(self, user) -> bool:
        """判断该用户是否应跳过 settlement 客户可见性过滤。"""
        if user is None:
            return False
        if user.is_superuser:
            return True
        if self.view_all_permission and user.has_perm(self.view_all_permission):
            return True
        return False

    def get_service_user(self, user):
        """
        返回传递给 settlement service 函数的 ``user`` 参数。

        - 可绕过时返回 ``None``：service 不施加客户可见性过滤。
        - 否则返回原始 user：service 按员工可见性过滤。
        """
        if self.can_bypass_settlement_visibility(user):
            return None
        return user
