占星师 2026-11-08 第五轮裁定 5:所有大运日期必须由原生大运引擎生成,显示层 不得自己按年数比例重算。BUG-1752 只修了星盘页的 Vimshottari 轨;Chara 轨仍在 浏览器里按 365.25 天/年从出生日推大运、按年数比例切分运,与报告页的公历周年 口径最多差一天。 - 新增 scripts/chart_dasha/chara_dates.py:给 jaimini 的十二段与每段十二个 分运写 start / end(本地日历日)与 start_ts / end_ts(UTC 秒);[start, end), 末段终点钉在父段终点,0 年段保留 start == end,平年 2 月 29 日落 28 日。 - /api/dasha/chara 返回前写这些字段并带 date_basis。 - rashi_dashas_native._chara 改读同一模块(报告输出不变,已与旧版逐段对照)。 - 星盘页 charaTrack 只复制引擎日期;删掉 addYears;没有日期的行不显示。 - 文案 CHARA_ANTARDASHA_DATE_NOTE 改为「与大运同一套边界」。 - 两份真实引擎响应 fixture 的 chara 段用 _compute_chara_dasha 重抓。 - BUG_HISTORY BUG-1811;PROGRESS-dasha-dates-engine-only-20261109。 验证:pytest 新用例 6 passed,相关 63 passed;node --test 新用例 4 pass、 既有 105 pass;tsc exit 0;lint 0 error。 Co-Authored-By: Grok (agent loop)
185 lines
7.2 KiB
Python
185 lines
7.2 KiB
Python
"""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
|