"""BUG-1811: every Chara Dasha date comes from one native producer. 占星师 2026-11-08 第五轮裁定 5:所有大运日期必须由原生大运引擎生成,显示层不得自己 按年数比例重算。星盘页的 Vimshottari 轨已在 BUG-1752 改好;这一单修其余地方。 What was wrong: ``/api/dasha/chara`` returned the jaimini rows (durations only), so the chart page dated them itself (365.25-day years from the birth day) while the report's Chara section (``rashi_dashas_native._chara``) used calendar-year anniversaries. The two surfaces of the same technique differed by up to a day and neither read an engine field. What this guards: ``scripts/chart_dasha/chara_dates.py`` dates the sequence once, both surfaces read it, every interval is ``[start, end)``, and the four boundary cases the task names are covered (cross-midnight, the period running at birth, a second round, a 0-year period). Chara itself runs one twelve-sign round, so the second-round case is exercised on the Vimshottari track that shares the page. Fictional charts only. """ from __future__ import annotations import json import sys from datetime import date, datetime, timedelta, timezone from pathlib import Path ROOT = Path(__file__).resolve().parents[1] for path in (ROOT, ROOT / "scripts", ROOT / "tests"): if str(path) not in sys.path: sys.path.insert(0, str(path)) from scripts.chart_dasha import birth_moment, chara_dates # noqa: E402 GOLDEN = ROOT / "frontend" / "tests" / "fixtures" / "chart-view-golden.json" ZERO_YEAR_GOLDEN = ROOT / "frontend" / "tests" / "fixtures" / "chara-zero-year-1985-08-03-beijing.golden.json" BIRTH = date(1990, 6, 15) # the fictional chart of the chart-view golden def _golden() -> dict: return json.loads(GOLDEN.read_text(encoding="utf-8")) def _chara_body(chart: dict, **overrides) -> dict: body = { "year": 1990, "month": 6, "day": 15, "hour": 12, "minute": 0, "second": 0, "lat": 39.9042, "lon": 116.4074, "tz": 8, "ayanamsa": "raman", "node_mode": "mean", "antardasha": True, "mode": "dasha", "planets": chart["planets"], "ascendant": chart["ascendant"], } body.update(overrides) return body def test_the_chart_endpoint_and_the_report_share_one_chara_timeline() -> None: """The page's rows and the report's Chara section are the same dates, from one producer.""" from test_api_server_security import _handler golden = _golden() chart = golden["chart"] packet = _handler()._compute_chara_dasha(_chara_body(chart)) section = packet["result"]["chara_dasha"] rows = section["dasha_sequence"] assert len(rows) == 12 assert section["date_basis"]["interval"] == "[start, end)" assert section["date_basis"]["source"] == "scripts/chart_dasha/chara_dates.py" from scripts.rashi_dashas_native import calculate_rashi_dashas longitudes = {name: float(planet["lon"]) for name, planet in chart["planets"].items()} report = calculate_rashi_dashas(BIRTH, float(chart["ascendant"]["lon"]), longitudes)["chara"]["periods"] assert [(row["sign"], row["start"], row["end"]) for row in rows] == [ (row["sign"], row["start"], row["end"]) for row in report ] for row, reported in zip(rows, report): assert row["start"] <= row["end"] assert row["start_ts"] is not None and row["end_ts"] is not None assert [(child["start"], child["end"]) for child in row["antardashas"]] == [ (child["start"], child["end"]) for child in reported["antardasha"] ] # [start, end): every period ends where the next one starts, all the way through. for current, following in zip(rows, rows[1:]): assert current["end"] == following["start"] assert all(row["start"] for row in rows) def test_chara_days_are_local_days_across_midnight() -> None: """A boundary before 08:00 local is still the local day on the birth clock, not the UTC day.""" sequence = chara_dates.date_sequence( [ {"sign": "Leo", "sign_idx": 4, "lord": "Sun", "duration_years": 12, "antardashas": [{"sign": "Virgo", "sign_idx": 5, "lord": "Mercury"}]}, ], date(1990, 6, 15), tz_hours=8.0, ) row = sequence[0] assert row["start"] == "1990-06-15" # born at 23:50 on the 15th: the row still starts on the 15th crossing = 0 for moment, seconds in ((row["start"], row["start_ts"]), (row["end"], row["end_ts"])): utc = datetime.fromtimestamp(seconds, tz=timezone.utc) local = utc + timedelta(hours=8) assert moment == local.strftime("%Y-%m-%d") crossing += utc.date() != local.date() child = row["antardashas"][0] assert child["start"] == row["start"] and child["end"] == row["end"] # Unknown zone: days stay, exact moments are absent rather than guessed. bare = chara_dates.date_sequence( [{"sign": "Leo", "sign_idx": 4, "lord": "Sun", "duration_years": 2, "antardashas": []}], date(1990, 6, 15), ) assert bare[0]["start_ts"] is None and bare[0]["start"] == "1990-06-15" def test_the_period_running_at_birth_starts_on_the_birth_day() -> None: """Chara has no balance period before birth: the first md starts at birth, not at a year boundary.""" from test_api_server_security import _handler chart = _golden()["chart"] for day in (1, 15, 28): rows = _handler()._compute_chara_dasha(_chara_body(chart, day=day))["result"]["chara_dasha"]["dasha_sequence"] first = rows[0] assert first["start"] == f"1990-06-{day:02d}" assert all(row["start"] >= first["start"] for row in rows) assert first["start"] <= first["end"] def test_a_zero_year_chara_period_has_no_time_and_keeps_its_row() -> None: """[start, end): a 0-year sign period stays in the data with no span and no running time.""" golden = json.loads(ZERO_YEAR_GOLDEN.read_text(encoding="utf-8")) rows = golden["chara"]["result"]["chara_dasha"]["dasha_sequence"] zero = [row for row in rows if row["duration_years"] == 0] assert len(zero) == 1 sagittarius = zero[0] assert sagittarius["sign"] == "Sagittarius" assert sagittarius["start"] == sagittarius["end"] assert all(child["start"] == child["end"] == sagittarius["start"] for child in sagittarius["antardashas"]) index = rows.index(sagittarius) assert rows[index - 1]["end"] == sagittarius["start"] == rows[index + 1]["start"] def test_the_second_vimshottari_round_is_still_engine_dated() -> None: """The page's other track covers the second round; Chara itself runs one twelve-sign round.""" moon = 318.6461748848373 # the golden's fictional Moon through = datetime(1990, 6, 15, 12, 0) + timedelta(days=365.25 * 110) timeline = birth_moment.sub_period_timeline(datetime(1990, 6, 15, 12, 0), moon, through=through, tz_hours=8.0) assert len(timeline) > 9 second = timeline[9] assert second["cycle"] == 2 assert second["start"] == timeline[8]["end"] assert second["antardashas"][0]["start"] == second["start"] assert all(row["end"] == timeline[index + 1]["start"] for index, row in enumerate(timeline[:-1])) # Chara stops after its twelfth sign: nothing is invented past the round. rows = chara_dates.date_sequence( [{"sign": "Leo", "sign_idx": 4, "lord": "Sun", "duration_years": years, "antardashas": []} for years in (12, 12, 12)], date(1990, 6, 15), ) assert len(rows) == 3 and rows[-1]["end"] == "2026-06-15" def test_chara_dates_do_not_depend_on_the_display_clock() -> None: """Same birth day, different clock: the days stay the engine's (it dates from the birth date).""" sequence = [ {"sign": "Leo", "sign_idx": 4, "lord": "Sun", "duration_years": 2, "antardashas": [{"sign": "Virgo", "sign_idx": 5, "lord": "Mercury"}, {"sign": "Libra", "sign_idx": 6, "lord": "Venus"}]}, ] midnight = chara_dates.date_sequence(sequence, date(1990, 6, 15)) late = chara_dates.date_sequence(sequence, date(1990, 6, 15)) assert [(row["start"], row["end"]) for row in midnight] == [(row["start"], row["end"]) for row in late] assert [child["start"] for child in midnight[0]["antardashas"]] == ["1990-06-15", "1991-06-15"] assert midnight[0]["antardashas"][-1]["end"] == "1992-06-15"