"""库存关账期间守卫。纯逻辑。

关账后，落在已关闭期间（含更早）的库存变动一律拒绝，只能在当前开放期间用
纠正单处理并引用原单据。期间以 YYYY-MM 表示。
"""
from fastapi import HTTPException


class PeriodClosed(HTTPException):
    def __init__(self, period: str) -> None:
        super().__init__(status_code=409,
                         detail=f"期间 {period} 已关账，请在当前开放期间用纠正单处理")


def period_of(dt) -> str:
    """把 datetime/date 映射到 YYYY-MM 期间。"""
    return f"{dt.year:04d}-{dt.month:02d}"


def is_closed(target_period: str, closed_through: str | None) -> bool:
    """target_period 是否落在已关账范围（<= closed_through）。"""
    if not closed_through:
        return False
    return target_period <= closed_through


def assert_open(target_period: str, closed_through: str | None) -> None:
    if is_closed(target_period, closed_through):
        raise PeriodClosed(target_period)
