"""Chara Dasha dates, dated once here instead of by each display layer (BUG-1811). 占星师 2026-11-08 第五轮裁定 5:所有大运日期必须由原生大运引擎生成,显示层不得 自己按年数比例重算。``jaimini.calc_chara_dasha_with_antardasha`` returns durations only, so the chart page used to cut the twelve sign periods itself (365.25-day years from the birth day) while the report's Chara section (``rashi_dashas_native._chara``) cut them another way (calendar-year anniversaries from the birth date). Two surfaces of the same technique disagreed by up to a day and neither copied an engine field. This module dates the sequence the engine returned, once, with the rule the report already used: * a mahadasha ends on the calendar anniversary of the birth date, so a 2-year period that starts on 1990-06-15 ends on 1992-06-15 (29 February falls back to the 28th); * its twelve antardashas are an equal split of that span in exact seconds, the last one pinned to the mahadasha end; * every interval is ``[start, end)``; a 0-year period keeps its row with ``start == end`` and no occupied time; * dates are local calendar days; ``start_ts`` / ``end_ts`` are the same boundaries in UTC epoch seconds when the birth zone is known, so a boundary can be compared exactly without printing a clock time. The chart's ``/api/dasha/chara`` and the report's ``chara`` section both read ``date_sequence``; no consumer does this arithmetic itself. """ from __future__ import annotations from datetime import date, datetime, time as clock_time, timedelta, timezone from typing import Any, Iterable YEAR_BASIS = "calendar_year_anniversary" INTERVAL = "[start, end)" def add_years(day: date, years: int) -> date: """The anniversary rule: the same month and day, ``years`` later.""" try: return day.replace(year=day.year + int(years)) except ValueError: # 29 February in a common year return day.replace(year=day.year + int(years), day=28) def _midnight(day: date) -> datetime: return datetime.combine(day, clock_time.min) def _epoch_seconds(moment: datetime, tz_hours: float | None) -> int | None: if tz_hours is None: return None return int(round((moment - timedelta(hours=float(tz_hours))).replace(tzinfo=timezone.utc).timestamp())) def _boundaries(start: datetime, end: datetime, tz_hours: float | None) -> dict[str, Any]: return { "start": start.date().isoformat(), "end": end.date().isoformat(), "start_ts": _epoch_seconds(start, tz_hours), "end_ts": _epoch_seconds(end, tz_hours), } def split_equal(start: datetime, end: datetime, count: int) -> list[tuple[datetime, datetime]]: """``count`` equal slices of ``[start, end)``; the last one ends exactly at ``end``.""" total = (end - start).total_seconds() if count <= 0 or total <= 0: return [] rows = [] for index in range(count): child_start = start + timedelta(seconds=total * index / count) child_end = end if index == count - 1 else start + timedelta(seconds=total * (index + 1) / count) rows.append((child_start, child_end)) return rows def date_sequence( sequence: Iterable[Any], birth: date, *, tz_hours: float | None = None, ) -> list[dict[str, Any]]: """The engine's Chara rows with ``start`` / ``end`` (local days) and their exact instants.""" cursor = _midnight(birth) out: list[dict[str, Any]] = [] for entry in sequence: if not isinstance(entry, dict): continue years = int(entry.get("duration_years") or 0) end = _midnight(add_years(cursor.date(), years)) antardashas = [] raw_antardashas = entry.get("antardashas") children_raw = [item for item in raw_antardashas if isinstance(item, dict)] if isinstance(raw_antardashas, list) else [] slices = split_equal(cursor, end, len(children_raw)) if not slices: # A 0-year mahadasha occupies no time; its rows stay, each with start == end (never current). slices = [(cursor, cursor) for _ in children_raw] for child, (child_start, child_end) in zip(children_raw, slices): if not isinstance(child, dict): continue antardashas.append({ "sign": child.get("sign"), "sign_index": child.get("sign_idx", child.get("sign_index")), "lord": child.get("lord"), "order": child.get("order"), **_boundaries(child_start, child_end, tz_hours), }) out.append({ "sign": entry.get("sign"), "sign_index": entry.get("sign_idx", entry.get("sign_index")), "lord": entry.get("lord"), "years": years, "zero_year": years == 0, **_boundaries(cursor, end, tz_hours), "antardashas": antardashas, }) cursor = end return out def date_basis(tz_hours: float | None) -> dict[str, Any]: """How to read the rows ``attach`` writes: one rule, one interval, one producer.""" return { "year_basis": YEAR_BASIS, "interval": INTERVAL, "timezone_offset_hours": tz_hours, "source": "scripts/chart_dasha/chara_dates.py", "boundary": "start / end = local calendar days; start_ts / end_ts = UTC epoch seconds when the zone is known", } def birth_from_body(body: dict[str, Any] | None) -> date: """The birth date the dasha sequence is dated from (the endpoint's own fields).""" raw = body or {} try: year = int(raw.get("year")) except (TypeError, ValueError): year = datetime.now().year try: month = int(raw.get("month") or 1) except (TypeError, ValueError): month = 1 try: day = int(raw.get("day") or 1) except (TypeError, ValueError): day = 1 try: return date(year, min(max(month, 1), 12), min(max(day, 1), 31)) except ValueError: return date(year, 1, 1) def timezone_hours(body: dict[str, Any] | None) -> float | None: raw = body or {} value = raw.get("tz", raw.get("timezone")) if value is None: return None if isinstance(value, str): text = value.strip().upper().replace("UTC", "").replace("GMT", "") if not text: return None value = text try: return float(value) except (TypeError, ValueError): return None def attach(chara: dict[str, Any], birth: date, *, tz_hours: float | None = None) -> dict[str, Any]: """Write the engine dates onto the rows ``jaimini`` returned, in place.""" dated = date_sequence(chara.get("dasha_sequence") or [], birth, tz_hours=tz_hours) rows = [row for row in chara.get("dasha_sequence") or [] if isinstance(row, dict)] for row, dates in zip(rows, dated): for key in ("start", "end", "start_ts", "end_ts"): row[key] = dates[key] for child, child_dates in zip( [item for item in row.get("antardashas") or [] if isinstance(item, dict)], dates["antardashas"], ): for key in ("start", "end", "start_ts", "end_ts"): child[key] = child_dates[key] chara["date_basis"] = date_basis(tz_hours) return chara