"""Shared canonical period handling for NAO evidence, planning, and tools.""" from __future__ import annotations PERIOD_KEYS = ('year', 'month', 'quarter', 'monthStart', 'monthEnd') def normalize_period(value): """Return a canonical supported period, None, or raise ``ValueError``. Supported shapes are year, one month, one quarter, and an inclusive monthStart/monthEnd range. Range endpoints must both be present. """ if value is None: return None if not isinstance(value, dict) or set(value) - set(PERIOD_KEYS): raise ValueError('期间必须只包含受支持的字段') year = value.get('year') if type(year) is not int or not 1900 <= year <= 2200: raise ValueError('年份必须为1900至2200之间的整数') has_month = 'month' in value has_quarter = 'quarter' in value has_start = 'monthStart' in value has_end = 'monthEnd' in value if has_start != has_end: raise ValueError('monthStart与monthEnd必须成对提供') if has_start: if has_month or has_quarter: raise ValueError('月份区间不能与month或quarter同时提供') start, end = value['monthStart'], value['monthEnd'] if type(start) is not int or type(end) is not int or not (1 <= start <= end <= 12): raise ValueError('月份区间必须满足1<=monthStart<=monthEnd<=12') return {'year': year, 'monthStart': start, 'monthEnd': end} if has_month and has_quarter: raise ValueError('month与quarter不能同时提供') if has_month: month = value['month'] if type(month) is not int or not 1 <= month <= 12: raise ValueError('月份必须为1至12之间的整数') return {'year': year, 'month': month} if has_quarter: quarter = value['quarter'] if type(quarter) is not int or not 1 <= quarter <= 4: raise ValueError('季度必须为1至4之间的整数') return {'year': year, 'quarter': quarter} return {'year': year} def expected_months(period): """Return all calendar months selected by a supported period.""" normalized = normalize_period(period) if normalized is None: raise ValueError('缺少期间') if 'month' in normalized: return [normalized['month']] if 'quarter' in normalized: start = (normalized['quarter'] - 1) * 3 + 1 return list(range(start, start + 3)) if 'monthStart' in normalized: return list(range(normalized['monthStart'], normalized['monthEnd'] + 1)) return list(range(1, 13))