From ebf6dd4ee06b0bc26bca8dfac84374ea5d765082 Mon Sep 17 00:00:00 2001 From: jesse-ux Date: Tue, 17 Nov 2026 13:59:05 +0800 Subject: [PATCH] fix: preserve chosen birth scenarios without confirming the time --- frontend/src/app/api/account/route.ts | 2 + .../src/app/api/chart-choice/adopt/route.ts | 17 +- frontend/src/app/api/consult/route.ts | 12 +- .../chart-choice/chart-choice-page.tsx | 86 +- .../src/lib/chart-choice-both-versions.ts | 69 +- frontend/src/lib/chart-choice/contract.ts | 24 +- .../src/lib/chart-choice/route-support.ts | 1 + .../chart-choice/self-selected-scenario.ts | 20 + frontend/src/lib/chart-choice/server.ts | 76 +- frontend/src/lib/chart-subject-write.ts | 2 + .../src/lib/consultation-route-service.ts | 29 +- frontend/src/lib/home-profile.ts | 5 + frontend/src/lib/home-types.ts | 1 + frontend/src/lib/people-archive-view.ts | 3 +- .../src/lib/personal-report-longform-birth.ts | 8 +- .../src/lib/personal-report-route-core.ts | 5 +- frontend/src/mastra/consultation-tools.ts | 2 + frontend/src/mastra/consultation-workflow.ts | 28 +- .../20261117130000_chart_choice_scenario.sql | 94 + ...chart-choice-self-choice-20261116.test.tsx | 86 +- ...ice-self-choice-scenario-20261117.test.tsx | 183 ++ ...atabase-chart-choice-scenario-1958.test.ts | 104 + .../chart-choice-self-choice-20261116.json | 2038 ++++++++++++++++- scripts/chart_choice/service.py | 88 +- tests/test_chart_choice.py | 39 +- 25 files changed, 2803 insertions(+), 219 deletions(-) create mode 100644 frontend/src/lib/chart-choice/self-selected-scenario.ts create mode 100644 frontend/supabase/migrations/20261117130000_chart_choice_scenario.sql create mode 100644 frontend/tests/chart-choice-self-choice-scenario-20261117.test.tsx create mode 100644 frontend/tests/database-chart-choice-scenario-1958.test.ts diff --git a/frontend/src/app/api/account/route.ts b/frontend/src/app/api/account/route.ts index cfe4c29d7..b0574650a 100644 --- a/frontend/src/app/api/account/route.ts +++ b/frontend/src/app/api/account/route.ts @@ -1,4 +1,5 @@ import { NextResponse } from "next/server"; +import { isSelfSelectedScenario } from "@/lib/chart-choice/self-selected-scenario"; import { parseRectificationPriceCredits, } from "@/lib/birth-time-consultation-consent"; @@ -211,6 +212,7 @@ export async function GET() { entitlements: activeSubscription.entitlement_snapshot, } : null, hasConfirmedBirthTime: profile.birth_time_status === "confirmed" + && !isSelfSelectedScenario(profile.active_birth_provenance) && typeof profile.active_birth_time === "string", hasUsableBirthTime: (profile.birth_time_status === "accepted" || profile.birth_time_status === "confirmed") && typeof profile.active_birth_time === "string", diff --git a/frontend/src/app/api/chart-choice/adopt/route.ts b/frontend/src/app/api/chart-choice/adopt/route.ts index 1f1129cc5..0191fc77f 100644 --- a/frontend/src/app/api/chart-choice/adopt/route.ts +++ b/frontend/src/app/api/chart-choice/adopt/route.ts @@ -25,18 +25,24 @@ const choiceSchema = z.object({ rangeChosen: z.boolean().optional(), ...evidenceInput, }).strict(); -const selfChoiceSchema = z.object({ +const selfChoiceFields = { selfChoice: z.literal(true), subjectId: z.string().max(64).optional(), window: windowSchema.optional(), - mode: z.enum(["preview", "choice"]).default("choice"), choices: z.array(z.object({ line_at: z.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/), side: z.enum(["before", "after", "unsure"]), }).strict()).max(720), +}; +const selfChoicePreviewSchema = z.object({ ...selfChoiceFields, mode: z.literal("preview") }).strict(); +const selfChoiceSaveSchema = z.object({ + ...selfChoiceFields, + mode: z.literal("choice").default("choice"), + baseRecordId: z.string().uuid().nullable(), + declarationFingerprint: z.string().regex(/^[a-f0-9]{64}$/), }).strict(); -const bodySchema = z.union([selfChoiceSchema, choiceSchema, z.object({ +const bodySchema = z.union([selfChoicePreviewSchema, selfChoiceSaveSchema, choiceSchema, z.object({ mode: z.literal("restore_default"), subjectId: z.string().max(64).optional(), recordId: z.string().uuid(), @@ -63,9 +69,10 @@ export async function POST(request: Request) { if (!parsed.success) return NextResponse.json({ error: "请求格式不对", code: "bad_request" }, { status: 400 }); try { if ("selfChoice" in parsed.data) { + const admin = createAdminSupabaseClient(); return NextResponse.json(parsed.data.mode === "preview" - ? await previewSelfChoice(caller.supabase, caller.userId, parsed.data) - : await adoptSelfChoice(caller.supabase, createAdminSupabaseClient(), caller.userId, parsed.data)); + ? await previewSelfChoice(caller.supabase, admin, caller.userId, parsed.data) + : await adoptSelfChoice(caller.supabase, admin, caller.userId, parsed.data)); } if (!RECT_QUESTIONNAIRE_ENABLED && (parsed.data.mode === "preview" || parsed.data.mode === "choice")) { const { subjectId, window, rangeChosen } = parsed.data; diff --git a/frontend/src/app/api/consult/route.ts b/frontend/src/app/api/consult/route.ts index d836ed4a6..332c24996 100644 --- a/frontend/src/app/api/consult/route.ts +++ b/frontend/src/app/api/consult/route.ts @@ -11,6 +11,7 @@ import { runConsultationWorkflow, } from "@/mastra"; import { blocksPromptExtraction } from "@/lib/consult-safety"; +import { selfSelectedScenarioOpening } from "@/mastra/consultation-workflow"; import { consultDomainConcurrency, consultPrepParallelEnabled, modelVersionCacheTtlMs } from "@/lib/consult/prep-flags"; import { ConsultationInputBlockedError, @@ -1201,8 +1202,10 @@ export async function POST(request: Request) { // override it for this question only. Earlier turns no longer set the mode. const answerMode = consultationAnswerMode({ question: visibleQuestion, baseMode: requestedAnswerMode }); const natalInstruction = `${natalToolInstruction}${natalUserTurnShape({ entrypoint: consultEntrypoint, history, summaryText: historyWindow.summaryText, answerMode })}`; + const scenarioOpening = selfSelectedScenarioOpening(prepared.serverChart?.selfSelectedScenario, followUpTurn, visibleQuestion); const adoptedRangeNote = consultationMode === "verified_chart" && prepared.serverChart?.truth.birthTimeStatus === "accepted" + && !prepared.serverChart.selfSelectedScenario && prepared.serverChart.toolInput.candidate_range ? ` ${ACCEPTED_RANGE_READING_INSTRUCTION}` : ""; @@ -1210,7 +1213,7 @@ export async function POST(request: Request) { ? generalNoMinuteInstruction(Boolean(generalDailyContext)) : consultationMode === "declared_birth_window" ? declaredWindowInstruction() - : `${natalInstruction}${adoptedRangeNote}`; + : `${natalInstruction}${adoptedRangeNote}${scenarioOpening}`; const consultationBaseMessages = (overflow: boolean) => { const tail = overflow ? lastConsultationPair(history) : history; const mapped = tail.map((message) => message.role === "user" @@ -1836,7 +1839,8 @@ export async function POST(request: Request) { // The grounded fallback writes from the injected workflow; same first-turn // / follow-up split as the agentic path (BUG-1071), one statement of it. const legacyAnswerMode = consultationAnswerMode({ question: visibleQuestion, baseMode: requestedAnswerMode }); - const legacyNatalInstruction = hasPriorAssistantAnswer(history, { summaryText: historyWindow.summaryText }) + const legacyFollowUp = hasPriorAssistantAnswer(history, { summaryText: historyWindow.summaryText }); + const legacyNatalInstruction = legacyFollowUp ? followUpAnswerShapeInstruction(legacyAnswerMode) : `${answerModeTurnLine(legacyAnswerMode)}${natalAnswerShapeBody(legacyAnswerMode)}${legacyAnswerMode === "plain" ? "文末技法审计表由产品界面折叠展示,不写进正文。" : ""}星盘事实只使用系统里已经注入的计算结果,不要复述内部字段、JSON 或再跑一遍咨询流程。`; @@ -1855,7 +1859,7 @@ export async function POST(request: Request) { content: consultationUserTurnContent({ currentTime: currentTimeContext(requestTime), name, - instruction: legacyNatalInstruction, + instruction: legacyNatalInstruction + selfSelectedScenarioOpening(prepared.serverChart.selfSelectedScenario, legacyFollowUp, visibleQuestion), summaryText: historyWindow.summaryText, droppedCount: historyWindow.droppedCount, question: resolvedQuestion.modelQuestion, @@ -1880,7 +1884,7 @@ export async function POST(request: Request) { content: consultationUserTurnContent({ currentTime: currentTimeContext(requestTime), name, - instruction: legacyNatalInstruction, + instruction: legacyNatalInstruction + selfSelectedScenarioOpening(prepared.serverChart.selfSelectedScenario, legacyFollowUp, visibleQuestion), summaryText: historyWindow.summaryText, droppedCount: historyWindow.droppedCount, question: resolvedQuestion.modelQuestion, diff --git a/frontend/src/components/chart-choice/chart-choice-page.tsx b/frontend/src/components/chart-choice/chart-choice-page.tsx index 639a7b3c8..bee353413 100644 --- a/frontend/src/components/chart-choice/chart-choice-page.tsx +++ b/frontend/src/components/chart-choice/chart-choice-page.tsx @@ -34,6 +34,7 @@ import { type ChartChoiceWindow, type SelfChoicePick, type SelfChoicePreview, + type SelfChoicePreviewResponse, } from "@/lib/chart-choice/contract"; import { SIDE_TEXT, @@ -74,29 +75,33 @@ type Step = | { kind: "home" } | { kind: "packet_loading" } | { kind: "narrow"; packet: Extract } - | { kind: "certain"; packet: Extract } + | { kind: "certain"; packet: Extract; notice?: string } | { kind: "range"; packet: Choose | Complete; request: ChartChoiceRequest } | { kind: "choose"; packet: Choose; request: ChartChoiceRequest; previous?: Step; draft?: RoundDraft } | { kind: "result"; packet: Choose; decision: ChartChoiceDecision; saving: boolean; overrideSide?: ChartChoiceSide } | { kind: "chart_range"; packet: ChartChoiceQuestionnaire; request: ChartChoiceRequest; previous?: Step } | { kind: "chart_question"; packet: ChartChoiceQuestionnaire; request: ChartChoiceRequest; back: Step; submitted: ChartChoiceChartAnswers; answer: ChartAnswer } - | { kind: "final"; packet: FinalPacket; decision: FinalDecision; body: ResultRequest; back: Step } - | { kind: "self_choice"; preview: SelfChoicePreview; final: Extract; stopped?: boolean }; + | { kind: "final"; packet: FinalPacket; decision: FinalDecision; body: ResultRequest; back: Step; notice?: string } + | { kind: "self_choice"; preview: SelfChoicePreviewResponse; final: Extract; stopped?: boolean }; const COPY = { title: "生时纠正", profileHref: (subjectId: string) => (subjectId === "self" ? "/people?self=1" : `/people?edit=${encodeURIComponent(subjectId)}`), }; +class ChartChoiceRequestError extends Error { + constructor(message: string, readonly code?: string) { super(message); } +} + async function postJson(url: string, body: unknown): Promise { const response = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }); - const payload = await response.json().catch(() => null) as (T & { error?: string }) | null; - if (!response.ok || !payload) throw new Error(payload?.error || "暂时没有响应,请稍后再试。"); + const payload = await response.json().catch(() => null) as (T & { error?: string; code?: string }) | null; + if (!response.ok || !payload) throw new ChartChoiceRequestError(payload?.error || "暂时没有响应,请稍后再试。", payload?.code); return payload; } @@ -154,7 +159,7 @@ export function ChartChoiceFlow({ subjectId }: { readonly subjectId: string }) { const [rangeChosen, setRangeChosen] = useState(false); const generation = useRef(0); - const loadPacket = useCallback(async (request: ChartChoiceRequest, showRange = true, previous?: Step) => { + const loadPacket = useCallback(async (request: ChartChoiceRequest, showRange = true, previous?: Step, notice?: string) => { const ticket = ++generation.current; setWindow(request.window); setAnswers({}); @@ -168,11 +173,11 @@ export function ChartChoiceFlow({ subjectId }: { readonly subjectId: string }) { if (ticket !== generation.current) return; if (!RECT_QUESTIONNAIRE_ENABLED) { if (packet.status === "certain") { - setStep({ kind: "certain", packet }); + setStep({ kind: "certain", packet, notice }); } else if (packet.status === "complete" && packet.decision.reported_choice) { setStep({ kind: "final", packet, decision: packet.decision, body: { subjectId, adaptive: true, mode: "choice", ...(request.window ? { window: request.window } : {}) }, - back: { kind: "home" }, + back: { kind: "home" }, notice, }); } else { throw new Error("暂时没有可用的结果,请重试。"); @@ -276,7 +281,11 @@ export function ChartChoiceFlow({ subjectId }: { readonly subjectId: string }) { ? : null); - return <>{renderStep()}; + return <> + {(step.kind === "final" || step.kind === "certain") && step.notice + ?

{step.notice}

: null} + {renderStep()} + ; function retry(target: Retry) { if (target.kind === "start") { @@ -332,18 +341,31 @@ export function ChartChoiceFlow({ subjectId }: { readonly subjectId: string }) { async function runSelfChoice( final: Extract, choices: readonly SelfChoicePick[], - mode: "preview" | "choice", + binding?: SelfChoicePreviewResponse, ) { setPending(true); const back = step; + const body = { selfChoice: true, subjectId, choices, ...(final.body.window ? { window: final.body.window } : {}) }; try { - const preview = await postJson("/api/chart-choice/adopt", { - selfChoice: true, subjectId, mode, choices, ...(final.body.window ? { window: final.body.window } : {}), - }); - if (mode === "preview") setStep({ kind: "self_choice", final, preview }); - else afterSave(adoptedClock(preview.decision.saved_at, final.packet.reported_at)); + if (binding) { + const saved = await postJson("/api/chart-choice/adopt", { + ...body, mode: "choice", baseRecordId: binding.current_record_id, + declarationFingerprint: binding.declaration_fingerprint, + }); + afterSave(adoptedClock(saved.decision.saved_at, final.packet.reported_at)); + } else { + const preview = await postJson("/api/chart-choice/adopt", { ...body, mode: "preview" }); + setStep({ kind: "self_choice", final, preview }); + } } catch (error) { - setStep({ kind: "failed", message: (error as Error).message, retry: { kind: "back", step: back } }); + if (error instanceof ChartChoiceRequestError && error.code === "stale_choice") { + const refreshed = await readStart(subjectId); + if ("ready" in refreshed) { + setStart(refreshed.ready); + setRangeChosen(false); + await loadPacket({}, false, undefined, error.message); + } else setStep(refreshed); + } else setStep({ kind: "failed", message: (error as Error).message, retry: { kind: "back", step: back } }); } finally { setPending(false); } @@ -506,15 +528,15 @@ export function ChartChoiceFlow({ subjectId }: { readonly subjectId: string }) { defaultOnly={!RECT_QUESTIONNAIRE_ENABLED} rangeChips={!RECT_QUESTIONNAIRE_ENABLED ? rangeChips(step.packet) : null} onBack={RECT_QUESTIONNAIRE_ENABLED ? () => restore(step.back) : hasHistory ? toHome : undefined} - onSelfChoice={() => void runSelfChoice(step, [], "preview")} + onSelfChoice={() => void runSelfChoice(step, [])} onAccept={() => void saveFinal(step)} />; case "self_choice": return restore(step.final)} - onPick={(pick) => void runSelfChoice(step.final, [...step.preview.decision.choices, pick], "preview")} + onPick={(pick) => void runSelfChoice(step.final, [...step.preview.decision.choices, pick])} onStop={() => setStep({ ...step, stopped: true })} - onAccept={() => void runSelfChoice(step.final, step.preview.decision.choices, "choice")} />; + onAccept={() => void runSelfChoice(step.final, step.preview.decision.choices, step.preview)} />; } } } @@ -853,13 +875,14 @@ function FlipSummary({ summary, reportedAt }: { readonly summary: ChartChoiceLineSummary; readonly reportedAt?: string | null; }) { - if (!summary.nearest_at) return

这个时间范围内六张盘都不变,可以直接用。

; + if (!summary.nearest_at) return

这个时间范围内,六张盘的上升星座都不变。

; const stable = Object.keys(CHART_NAMES).filter((chart) => !summary.charts[chart]).map((chart) => CHART_NAMES[chart]); const changing = Object.keys(CHART_NAMES).filter((chart) => summary.charts[chart]).map((chart) => CHART_NAMES[chart]); const seconds = reportedAt ? Math.round(Math.abs(minutesFrom(reportedAt) - minutesFrom(summary.nearest_at)) * 60) : null; return
-

不受影响:{stable.join("、") || "无"}。

-

差几分钟就不同:{changing.join("、")}。

+

上升星座不变:{stable.join("、") || "无"}。

+

上升星座会变:{changing.join("、")}。

+ {summary.line_count ?

共有 {summary.line_count} 处换座。

: null} {reportedAt && seconds !== null && seconds < 120 ?

你填的 {clockLabel(reportedAt)} 离 {clockLabel(summary.nearest_at, reportedAt, true)} 这条线只有 {seconds >= 60 ? Math.floor(seconds / 60) + " 分 " : ""}{seconds % 60} 秒。

: null} @@ -881,12 +904,17 @@ function KeyCharts({ charts, undetermined, reference, segment, window = segment, const uncertain = Boolean(row.flips_at || undetermined?.includes(row.chart)); const flip = summary?.charts[row.chart]; const flipAt = flip?.at ?? row.flips_at; + const allFlips = flip?.lines ?? []; + const describeFlip = (value: { at: string; before: string; after: string }) => + clockLabel(value.at, reference, true) + " 之前" + value.before + "上升,之后" + value.after + "上升"; return
{CHART_NAMES[row.chart]}
{segment ? : null} - {flip ? {clockLabel(flip.at, reference, true)} 之前{flip.before}上升,之后{flip.after}上升 - {flip.count > 1 ? "等 " + flip.count + " 处" : null} : {row.sign ? `${row.sign}上升,` : ""}{uncertain ? "范围内会换座" : noSignChange(trial, window)} + segments={splitBand(segment, allFlips.length ? allFlips.map(({ at }) => at) : flipAt ? [flipAt] : [])} highlighted={[0]} /> : null} + {flip && allFlips.length > 1 ?
+ {describeFlip(flip)}等 {allFlips.length} 处 +
    {allFlips.map((line) =>
  • {describeFlip(line)}
  • )}
+
: flip ? {describeFlip(flip)} : {row.sign ? `${row.sign}上升,` : ""}{uncertain ? "范围内会换座" : noSignChange(trial, window)} {row.flips_at ? `(${clockLabel(row.flips_at, reference, true)} 换)` : null}}
; @@ -1153,7 +1181,7 @@ function ReadingPlan({
{chosen !== "none" && byChosen.length ? (<>
按{SIDE_TEXT[chosen]}读
{byChosen.join("、")}
) : null} {twoWays.length ? (<>
两版都读
{twoWays.join("、")}
) : null} - {unchanged.length ? (<>
不受影响
{unchanged.join("、")}
) : null} + {unchanged.length ? (<>
上升星座不变
{unchanged.join("、")}
) : null}
); } @@ -1267,11 +1295,13 @@ export function SelfChoiceStep({ preview, reference, stopped, pending, onBack, o readonly onAccept: () => void; }) { const { decision, next } = preview; + const remaining = decision.remaining_lines?.length ?? decision.line_summary.line_count ?? 0; if (next && !stopped) return <> {!pending ? 返回 : null}

{clockLabel(next.at, reference, true)} 分界线

-

范围 {segmentLabel(decision.segment)}

+

范围 {segmentLabel(decision.segment)}

+ {remaining > 0 ?

还有 {remaining} 条线没选。

: null}
{next.comparisons.map((comparison) => )} : null} + {remaining > 0 ?

还有 {remaining} 条线没选。

: null}

这是你自己选的,可以随时改。

+

这不是出生时间已核实,你填的时间和范围都还保留着。

用 {saved}
; } diff --git a/frontend/src/lib/chart-choice-both-versions.ts b/frontend/src/lib/chart-choice-both-versions.ts index 620e6a8f5..717cf0c17 100644 --- a/frontend/src/lib/chart-choice-both-versions.ts +++ b/frontend/src/lib/chart-choice-both-versions.ts @@ -6,8 +6,9 @@ * 咨询照常按采用的分钟排盘;这里只为这些领域另外算出另一边的分盘, * 交给模型一段写明「两版都读」的说明。没有这些字段的旧资料完全不受影响。 */ +import { z } from "zod"; import { recordOrEmpty as record } from "@/lib/guards"; -import { SELF_CHOICE_BASIS } from "./chart-choice/contract"; +import { isSelfSelectedScenario } from "./chart-choice/self-selected-scenario"; /** Domain keys and charts written by scripts/chart_choice/readings.py DOMAIN. */ export const CHART_CHOICE_DOMAIN_CHARTS: Readonly>> = { @@ -32,15 +33,75 @@ export type ChartChoiceBothVersionsInput = Readonly<{ const minutePattern = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/; export const CHART_CHOICE_OTHER_AT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::[0-5]\d)?$/; +const scenarioSchema = z.object({ + segment: z.object({ start_at: z.string().regex(CHART_CHOICE_OTHER_AT), end_at: z.string().regex(CHART_CHOICE_OTHER_AT) }), + saved_at: z.string().regex(CHART_CHOICE_OTHER_AT), + key_charts: z.array(z.object({ + chart: z.enum(["D1", "D2", "D6", "D8", "D9", "D10"]), + sign: z.enum(["白羊", "金牛", "双子", "巨蟹", "狮子", "处女", "天秤", "天蝎", "射手", "摩羯", "水瓶", "双鱼"]), + })).min(1).max(6), + is_primary: z.boolean(), +}); +export const chartChoiceScenariosSchema = z.object({ + primary: scenarioSchema, + alternatives: z.array(scenarioSchema).max(3), + comparison: scenarioSchema.optional(), + omitted: z.number().int().min(0), +}); +export type ChartChoiceScenariosInput = z.infer; + +function readScenarios(value: unknown) { + const provenance = record(value); + if (!isSelfSelectedScenario(provenance)) return null; + const items = z.array(scenarioSchema).min(1).max(4).safeParse(provenance.scenarios); + if (!items.success || items.data.filter((item) => item.is_primary).length !== 1) return null; + return items.data; +} + +export function chartChoiceScenariosFromProvenance(value: unknown): ChartChoiceScenariosInput | null { + const items = readScenarios(value); + if (!items) return null; + const provenance = record(value); + const omitted = z.number().int().min(0).catch(0).parse(provenance.scenarios_omitted); + const outside = scenarioSchema.safeParse(provenance.comparison_scenario); + const comparison = outside.success && !outside.data.is_primary ? outside.data : undefined; + const alternatives = items.length > 2 || omitted ? items.filter((item) => !item.is_primary) : []; + if (!alternatives.length && !comparison && !omitted) return null; + return { primary: items.find((item) => item.is_primary)!, alternatives, comparison, omitted }; +} + +export function compareChartChoiceScenarios(input: ChartChoiceScenariosInput) { + const primary = new Map(input.primary.key_charts.map(({ chart, sign }) => [chart, sign])); + const evidence = (scenario: (typeof input.alternatives)[number]) => ({ + segment: scenario.segment, + saved_at: scenario.saved_at, + ascendant_changes: scenario.key_charts.flatMap(({ chart, sign }) => { + const before = primary.get(chart); + return before && before !== sign ? [{ chart, primary: before, alternative: sign }] : []; + }), + }); + return { + primary_segment: input.primary.segment, + other_scenarios: input.alternatives.map(evidence), + ...(input.comparison ? { opposite_side: evidence(input.comparison) } : {}), + scenarios_omitted: input.omitted, + notice: "使用主情景。问题涉及换座带来不同结论时,分开说明已经计算的其他情景。" + + (input.omitted ? `另有 ${input.omitted} 种情景没有算。不能编写其结论。` : ""), + }; +} + /** Read the both-versions request from a profile's provenance; null when there is none. */ export function chartChoiceBothVersionsFromProvenance(value: unknown): ChartChoiceBothVersionsInput | null { const provenance = record(value); if (provenance.source !== "user_choice") return null; if (!Array.isArray(provenance.both_versions) || provenance.both_versions.length === 0) return null; - const otherAt = typeof provenance.other_saved_at === "string" ? provenance.other_saved_at : ""; - const selfChoice = provenance.basis === SELF_CHOICE_BASIS && provenance.declared_by_user === true; + const selfChoice = isSelfSelectedScenario(provenance); + const scenarios = readScenarios(provenance); + if (scenarios && (scenarios.length !== 2 || provenance.scenarios_omitted)) return null; + const otherAt = scenarios?.find((item) => !item.is_primary)?.saved_at + ?? (typeof provenance.other_saved_at === "string" ? provenance.other_saved_at : ""); if (!(selfChoice ? CHART_CHOICE_OTHER_AT : minutePattern).test(otherAt)) return null; - const chosen = provenance.chosen_side; + const chosen = scenarios ? scenarios[0].is_primary ? "before" : "after" : provenance.chosen_side; if (chosen !== "before" && chosen !== "after") return null; const seen = new Set(); const domains = []; diff --git a/frontend/src/lib/chart-choice/contract.ts b/frontend/src/lib/chart-choice/contract.ts index 34c9742e8..20fa5de73 100644 --- a/frontend/src/lib/chart-choice/contract.ts +++ b/frontend/src/lib/chart-choice/contract.ts @@ -52,7 +52,10 @@ export type ChartChoiceLine = { }; export type ChartChoiceLineSummary = Readonly<{ nearest_at: string | null; - charts: Readonly>>; + line_count?: number; + charts: Readonly)[]; + }>>>; }>; export type ChartChoiceMinorLine = Pick; export type ChartChoiceKeyChart = { @@ -239,20 +242,35 @@ export type SelfChoiceRequest = Readonly<{ window?: ChartChoiceWindow; choices: readonly SelfChoicePick[]; }>; +export type SelfChoiceBinding = Readonly<{ baseRecordId: string | null; declarationFingerprint: string }>; +export type SelfChoiceScenario = Readonly<{ + segment: ChartChoiceWindow; + saved_at: string; + key_charts: readonly ChartChoiceKeyChart[]; + is_primary: boolean; +}>; export type SelfChoiceDecision = Readonly<{ saved_at: string; segment: ChartChoiceWindow; choices: readonly SelfChoicePick[]; key_charts: readonly ChartChoiceKeyChart[]; line_summary: ChartChoiceLineSummary; - chosen_side?: ChartChoiceSide; + chosen_side?: ChartChoiceSide | "none"; both_versions: readonly string[]; - other_saved_at?: string; + other_saved_at?: string | null; + remaining_lines?: readonly ChartChoiceMinorLine[]; + scenarios?: readonly SelfChoiceScenario[]; + scenarios_omitted?: number; + comparison_scenario?: SelfChoiceScenario; }>; export type SelfChoicePreview = Readonly<{ decision: SelfChoiceDecision; next?: ChartChoiceLine & { readonly comparisons: readonly ChartChoiceComparison[] }; }>; +export type SelfChoicePreviewResponse = SelfChoicePreview & Readonly<{ + current_record_id: string | null; + declaration_fingerprint: string; +}>; export type ChartChoiceStart = | { diff --git a/frontend/src/lib/chart-choice/route-support.ts b/frontend/src/lib/chart-choice/route-support.ts index 27ec3866b..6422173f1 100644 --- a/frontend/src/lib/chart-choice/route-support.ts +++ b/frontend/src/lib/chart-choice/route-support.ts @@ -51,6 +51,7 @@ const ERROR_TEXT: Record = { engine_unavailable: "排盘服务暂时没有响应,请稍后再试。", no_choice: "这个范围里没有需要选的分界线。", record_stale: "出生资料改过了,这次的结果不能再用。", + stale_choice: "出生资料改过了,这次的结果不能再用。", answer_window_disabled: "答题得出的时间范围已停用。可以保存填写的时间和原范围。", }; diff --git a/frontend/src/lib/chart-choice/self-selected-scenario.ts b/frontend/src/lib/chart-choice/self-selected-scenario.ts new file mode 100644 index 000000000..6295d44e1 --- /dev/null +++ b/frontend/src/lib/chart-choice/self-selected-scenario.ts @@ -0,0 +1,20 @@ +import { asRecord } from "../guards.ts"; +import { SELF_CHOICE_BASIS } from "./contract.ts"; + +export function isSelfSelectedScenario(provenance: unknown): boolean { + const source = asRecord(provenance); + return source?.selection_kind === "self_selected_scenario" || source?.basis === SELF_CHOICE_BASIS; +} + +export type ScenarioSelection = "before" | "after" | "unsure"; + +export function selfSelectedScenarioSide(value: unknown): ScenarioSelection | undefined { + if (!isSelfSelectedScenario(value)) return undefined; + const source = asRecord(value); + const choices = source?.choices; + const last = Array.isArray(choices) ? asRecord(choices.at(-1))?.side : undefined; + if (last === "before" || last === "after" || last === "unsure") return last; + if (!Array.isArray(choices) && !source?.other_saved_at + && (source?.chosen_side === "before" || source?.chosen_side === "after")) return source.chosen_side; + return "unsure"; +} diff --git a/frontend/src/lib/chart-choice/server.ts b/frontend/src/lib/chart-choice/server.ts index 471e75760..a30a8db20 100644 --- a/frontend/src/lib/chart-choice/server.ts +++ b/frontend/src/lib/chart-choice/server.ts @@ -7,7 +7,8 @@ import { resolveAyanamsa } from "../ayanamsa.ts"; import { CHART_VIEW_NODE_MODE } from "../chart-view-load.ts"; import { prepareChartViewProfile } from "../chart-view-profile-read.ts"; import { lagnaPrecheckWindow, type LagnaPrecheckWindow } from "../lagna-precheck.ts"; -import { ConsultationSubjectError, loadSubjectBirth, SELF_SUBJECT_ID } from "../subject-birth.ts"; +import { ConsultationSubjectError, isChartSubjectId, loadSubjectBirth, SELF_SUBJECT_ID, subjectIdFromQuery } from "../subject-birth.ts"; +import { isSelfSelectedScenario } from "./self-selected-scenario.ts"; import type { ChartChoiceAdoptRequest, ChartChoiceHistory, @@ -21,7 +22,9 @@ import type { ChartChoiceQuestionnaire, ChartChoiceStart, ChartChoiceWindow, + SelfChoiceBinding, SelfChoiceDecision, + SelfChoicePreviewResponse, SelfChoicePreview, SelfChoiceRequest, } from "./contract.ts"; @@ -37,7 +40,7 @@ const ROUNDS_VERSION = "chart-choice-v2"; const MAX_RECORD_SPAN_MINUTES = Math.max(...RECORD_RANGE_CHOICES); export class ChartChoiceError extends Error { - constructor(readonly code: "subject_not_found" | "profile_incomplete" | "bad_window" | "bad_event_date" | "engine_unavailable" | "no_choice" | "record_stale" | "answer_window_disabled", readonly status: number) { + constructor(readonly code: "subject_not_found" | "profile_incomplete" | "bad_window" | "bad_event_date" | "engine_unavailable" | "no_choice" | "record_stale" | "stale_choice" | "answer_window_disabled", readonly status: number) { super(code); this.name = "ChartChoiceError"; } @@ -577,8 +580,7 @@ export async function restoreChartChoiceDefault( const history = await readHistory(admin, userId, subject.subjectId); const current = history.records.find((record) => record.id === history.current_record_id); const provenance = current?.detail.provenance; - const selfChoice = provenance?.source === "user_choice" && provenance.basis === SELF_CHOICE_BASIS - && provenance.declared_by_user === true; + const selfChoice = isSelfSelectedScenario(provenance); if (current?.id !== request.recordId || !current.reusable || (!selfChoice && provenance?.source !== "user_choice_from_answers")) { throw new ChartChoiceError("record_stale", 409); @@ -611,9 +613,37 @@ async function evaluateSelfChoice( return { subject, window, result, reported: subject.declared ? reportedAt(subject.declared) : null }; } -export async function previewSelfChoice(supabase: unknown, userId: string, request: SelfChoiceRequest, fetchImpl?: typeof fetch) { +async function readSelfChoiceState(admin: RpcClient, userId: string, requested: unknown) { + const subjectId = subjectIdFromQuery(requested); + if (subjectId !== SELF_SUBJECT_ID && !isChartSubjectId(subjectId)) throw new ChartChoiceError("subject_not_found", 404); + const { data, error } = await admin.rpc("chart_choice_scenario_state_v1", { + p_user_id: userId, p_chart_profile_id: subjectId === SELF_SUBJECT_ID ? null : subjectId, + }); + if (error) throw new ChartChoiceError("engine_unavailable", 503); + const state = asRecord(data); + if (!state) throw new ChartChoiceError("subject_not_found", 404); + const id = state.current_record_id; + const fingerprint = state.declaration_fingerprint; + if ((id !== null && (typeof id !== "string" || !isChartSubjectId(id))) + || typeof fingerprint !== "string" || !/^[a-f0-9]{64}$/.test(fingerprint)) { + throw new ChartChoiceError("engine_unavailable", 503); + } + return { baseRecordId: id, declarationFingerprint: fingerprint }; +} + +function requireSelfChoiceState(actual: SelfChoiceBinding, expected: SelfChoiceBinding) { + if (actual.baseRecordId !== expected.baseRecordId || actual.declarationFingerprint !== expected.declarationFingerprint) { + throw new ChartChoiceError("stale_choice", 409); + } +} + +export async function previewSelfChoice( + supabase: unknown, admin: RpcClient, userId: string, request: SelfChoiceRequest, fetchImpl?: typeof fetch, +): Promise { + const before = await readSelfChoiceState(admin, userId, request.subjectId); const { result } = await evaluateSelfChoice(supabase, userId, request, false, fetchImpl); - return result; + requireSelfChoiceState(await readSelfChoiceState(admin, userId, request.subjectId), before); + return { ...result, current_record_id: before.baseRecordId, declaration_fingerprint: before.declarationFingerprint }; } function sameWindow(value: unknown, window: ChartChoiceWindow): boolean { @@ -624,7 +654,7 @@ function sameWindow(value: unknown, window: ChartChoiceWindow): boolean { function alreadyUsingSelfChoice(active: Subject["active"], window: ChartChoiceWindow, decision: SelfChoiceDecision): boolean { const prior = asRecord(active.provenance); const [date, time] = decision.saved_at.split("T"); - return prior?.source === "user_choice" && prior.basis === SELF_CHOICE_BASIS && prior.declared_by_user === true + return prior?.selection_kind === "self_selected_scenario" && active.date === date && sameSavedClock(time, active.time) && sameWindow(prior.window, window) && sameWindow(prior.segment, decision.segment) && Array.isArray(prior.choices) && prior.choices.length === decision.choices.length @@ -632,45 +662,59 @@ function alreadyUsingSelfChoice(active: Subject["active"], window: ChartChoiceWi const pick = asRecord(value); return pick?.line_at === decision.choices[index].line_at && pick.side === decision.choices[index].side; }) - && prior.other_saved_at === (decision.other_saved_at ?? null) + && (prior.other_saved_at ?? null) === (decision.other_saved_at ?? null) && JSON.stringify(prior.both_versions) === JSON.stringify(decision.both_versions); } export async function adoptSelfChoice( - supabase: unknown, admin: RpcClient, userId: string, request: SelfChoiceRequest, fetchImpl?: typeof fetch, + supabase: unknown, admin: RpcClient, userId: string, request: SelfChoiceRequest & SelfChoiceBinding, fetchImpl?: typeof fetch, ): Promise<{ decision: SelfChoiceDecision }> { + requireSelfChoiceState(await readSelfChoiceState(admin, userId, request.subjectId), request); const { subject, window, result: { decision }, reported } = await evaluateSelfChoice(supabase, userId, request, true, fetchImpl); const active = await activeChoice(supabase, subject, userId); - if (alreadyUsingSelfChoice(active, window, decision)) return { decision }; + if (alreadyUsingSelfChoice(active, window, decision)) { + requireSelfChoiceState(await readSelfChoiceState(admin, userId, subject.subjectId), request); + return { decision }; + } const [date, time] = decision.saved_at.split("T"); const rule = "user_override"; const provenance = { contract: ROUNDS_VERSION, engine_version: ROUNDS_VERSION, source: "user_choice", rule, declared_by_user: true, basis: SELF_CHOICE_BASIS, - segment: decision.segment, window, reported_at: reported, choices: decision.choices, - chosen_side: decision.chosen_side, other_saved_at: decision.other_saved_at ?? null, both_versions: decision.both_versions, + selection_kind: "self_selected_scenario", + declared_window: subject.declared && !declaredNeedsRange(subject.declared) + ? { start_at: subject.declared.start_at, end_at: subject.declared.end_at } : null, + segment: decision.segment, scenario_segment: decision.segment, window, reported_at: reported, choices: decision.choices, + chosen_side: decision.chosen_side, both_versions: decision.both_versions, + ...(decision.other_saved_at === undefined ? {} : { other_saved_at: decision.other_saved_at }), + remaining_lines: decision.remaining_lines ?? [], + scenarios: decision.scenarios ?? [], + scenarios_omitted: decision.scenarios_omitted ?? 0, + ...(decision.comparison_scenario ? { comparison_scenario: decision.comparison_scenario } : {}), undetermined_charts: Object.keys(decision.line_summary.charts), rounds: [], events: [], adopted_at: new Date().toISOString(), }; const detail: ChartChoiceRecordDetail = { window, reported_at: reported ?? midpointAt(window), line: null, - other_lines: 0, questions: [], answers: {}, unchanged: [], charts: [], + other_lines: decision.remaining_lines?.length ?? 0, questions: [], answers: {}, unchanged: [], charts: [], decision: { saved_at: decision.saved_at, segment: decision.segment, key_charts: decision.key_charts, line_summary: decision.line_summary, undetermined_charts: provenance.undetermined_charts, both_versions_domains: decision.both_versions, chosen_side: decision.chosen_side ?? "none", rule, }, }; - const { error } = await admin.rpc("chart_choice_adopt_v4", { + const { error } = await admin.rpc("chart_choice_adopt_scenario_v1", { p_user_id: userId, p_chart_profile_id: subject.subjectId === SELF_SUBJECT_ID ? null : subject.subjectId, + p_base_record_id: request.baseRecordId, p_declaration_fingerprint: request.declarationFingerprint, p_time: time.length === 5 ? time + ":00" : time, p_date: date, p_offset: subject.location.tz, p_detail: detail, p_provenance: provenance, - ...rangeToSave(subject, undefined, false), }); if (error) { - if (String(error.message ?? "").includes("chart_choice_subject_not_found")) throw new ChartChoiceError("subject_not_found", 404); + const reason = error.message ?? ""; + if (reason.includes("chart_choice_stale_choice")) throw new ChartChoiceError("stale_choice", 409); + if (reason.includes("chart_choice_subject_not_found")) throw new ChartChoiceError("subject_not_found", 404); throw new ChartChoiceError("engine_unavailable", 503); } return { decision }; diff --git a/frontend/src/lib/chart-subject-write.ts b/frontend/src/lib/chart-subject-write.ts index e6c396e5d..0cde20cea 100644 --- a/frontend/src/lib/chart-subject-write.ts +++ b/frontend/src/lib/chart-subject-write.ts @@ -1,4 +1,5 @@ import { birthWindowRetired, RETIRED_BIRTH_WINDOW_REASON } from "./retired-birth-window.ts"; +import { isSelfSelectedScenario } from "./chart-choice/self-selected-scenario.ts"; import { isAyanamsaName, resolveAyanamsa } from "./ayanamsa.ts"; import { parsePersonRelation } from "./person-relation.ts"; import { parseProfileGender } from "./profile-gender.ts"; @@ -239,6 +240,7 @@ export function libraryProfileFromSubjectRow(row: Record): Reco uncertaintyAfterMinutes: typeof row.uncertainty_after_minutes === "number" ? row.uncertainty_after_minutes : null, ...readBirthTimeDeclarationDetail(row), birthTimeStatus: status, + ...(isSelfSelectedScenario(row.active_birth_provenance) ? { selfSelectedScenario: true } : {}), countryCode: typeof stored.countryCode === "string" ? stored.countryCode : "CN", provinceCode: typeof stored.provinceCode === "string" ? stored.provinceCode : "", cityCode: typeof stored.cityCode === "string" ? stored.cityCode : "", diff --git a/frontend/src/lib/consultation-route-service.ts b/frontend/src/lib/consultation-route-service.ts index 44b9a6ff3..8fcfa9e1d 100644 --- a/frontend/src/lib/consultation-route-service.ts +++ b/frontend/src/lib/consultation-route-service.ts @@ -25,7 +25,8 @@ import { type OwnedChartProfile, } from "./consultation-subject-resolver.ts"; import { asRecord as record } from "@/lib/guards"; -import { chartChoiceBothVersionsFromProvenance, type ChartChoiceBothVersionsInput } from "./chart-choice-both-versions.ts"; +import { chartChoiceBothVersionsFromProvenance, chartChoiceScenariosFromProvenance, type ChartChoiceBothVersionsInput, type ChartChoiceScenariosInput } from "./chart-choice-both-versions.ts"; +import { selfSelectedScenarioSide, type ScenarioSelection } from "./chart-choice/self-selected-scenario.ts"; export type ConsultationProfileTruthErrorCode = | "profile_unavailable" @@ -67,11 +68,14 @@ type ServerChartToolInput = Readonly<{ candidate_range?: Readonly<{ start_time: string; end_time: string; candidate_intervals?: ReportCandidateClockRange["candidate_intervals"] }>; unreliable_vargas?: readonly ("D1" | "D9" | "D10")[]; chart_choice_both_versions?: ChartChoiceBothVersionsInput; + chart_choice_scenarios?: ChartChoiceScenariosInput; + second?: number; }>; export type ServerChartConsultation = Readonly<{ name: string; toolInput: ServerChartToolInput; + selfSelectedScenario?: ScenarioSelection; truth: Readonly<{ birthDate: string; reportedBirthTime: string | null; @@ -380,11 +384,14 @@ function serverChartFromProfile( hasActiveBirthTime: Boolean(activeBirthTime), }); const retired = birthWindowRetired(profile.active_birth_provenance); + const scenario = mode === "verified_chart" ? selfSelectedScenarioSide(profile.active_birth_provenance) : undefined; + const second = /^\d\d:\d\d:([0-5]\d)(?:\.\d+)?$/.exec(String(profile.active_birth_time))?.[1]; const original = retired ? declaredBirthWindow(profile) : null; return Object.freeze({ name, gender: parseProfileGender(profile.gender), + ...(scenario ? { selfSelectedScenario: scenario } : {}), toolInput: Object.freeze({ year, month, @@ -399,9 +406,10 @@ function serverChartFromProfile( // BUG-1828:绑定盘显式带口径,缺省是产品默认值。 node_mode: PRODUCT_DEFAULT_NODE_MODE, position_mode: PRODUCT_DEFAULT_POSITION_MODE, - declared_accuracy: accuracy.declaredAccuracy, - time_source: accuracy.timeSource, - ...(retired ? { birth_time_accuracy: "provisional" as const } : {}), + declared_accuracy: scenario ? "minute" : accuracy.declaredAccuracy, + time_source: scenario ? "self_selected_scenario" : accuracy.timeSource, + ...(scenario && second ? { second: Number(second) } : {}), + ...(retired || scenario ? { birth_time_accuracy: "provisional" as const } : {}), ...(original && original.minutes > 1 ? { candidate_range: { start_time: original.start_at.slice(11), end_time: original.end_at.slice(11), candidate_intervals: [{ start_at: original.start_at, end_at: original.end_at }], @@ -601,17 +609,24 @@ export async function prepareConsultationRoute( serverChart = serverChartFromProfile(profile, consultationMode); if (consultationMode === "verified_chart" && serverChart.truth.birthTimeStatus === "accepted") { // 生时纠正「两版都读」的领域(产品 2026-11-07);旧资料没有这些字段时不变。 - const bothVersions = chartChoiceBothVersionsFromProvenance(record(profile)?.active_birth_provenance); - if (bothVersions) { + const provenance = record(profile)?.active_birth_provenance; + const bothVersions = chartChoiceBothVersionsFromProvenance(provenance); + const scenarios = chartChoiceScenariosFromProvenance(provenance); + if (bothVersions || scenarios) { serverChart = Object.freeze({ ...serverChart, - toolInput: Object.freeze({ ...serverChart.toolInput, chart_choice_both_versions: bothVersions }), + toolInput: Object.freeze({ + ...serverChart.toolInput, + ...(bothVersions ? { chart_choice_both_versions: bothVersions } : {}), + ...(scenarios ? { chart_choice_scenarios: scenarios } : {}), + }), }); } } if ( consultationMode === "verified_chart" && serverChart.truth.birthTimeStatus === "accepted" + && !serverChart.selfSelectedScenario && subjectRole === "self" && input.loadCandidateRange ) { diff --git a/frontend/src/lib/home-profile.ts b/frontend/src/lib/home-profile.ts index 2f859b859..c9fa12f75 100644 --- a/frontend/src/lib/home-profile.ts +++ b/frontend/src/lib/home-profile.ts @@ -35,6 +35,7 @@ import { effectiveBirthDate } from "@/lib/effective-birth-date"; import type { OnboardingIntakeHint } from "@/lib/onboarding-intake"; import { parsePersonRelation } from "@/lib/person-relation"; import { parseProfileGender } from "@/lib/profile-gender"; +import { isSelfSelectedScenario } from "@/lib/chart-choice/self-selected-scenario"; /** Needs the city table loaded (china-locations-client.ts); undefined until then. */ export function findProvince(code: string) { @@ -167,6 +168,7 @@ export function profileBirthTimeLabel(profile: Profile) { } export function profileBirthTimeStatusLabel(profile: Profile) { + if (profile.selfSelectedScenario) return "用户自选情景"; if (profile.birthTimeStatus === "confirmed") return "时间已确认"; if (profile.birthTimeStatus === "candidate" || profile.birthTimeStatus === "accepted") return "时间为候选"; if (profile.birthTimeStatus === "rectifying" || profile.birthTimeStatus === "assessing") return "正在评估时间"; @@ -298,6 +300,7 @@ export function readProfile(value: unknown): Profile { birth_time?: unknown; reported_birth_time?: unknown; active_birth_time?: unknown; + active_birth_provenance?: unknown; birth_time_source?: unknown; birth_time_period?: unknown; declared_window_start?: unknown; @@ -401,6 +404,8 @@ export function readProfile(value: unknown): Profile { ? profile.uncertainty_after_minutes : typeof profile.uncertaintyAfterMinutes === "number" ? profile.uncertaintyAfterMinutes : null, birthTimeStatus: status, + ...(profile.selfSelectedScenario === true || isSelfSelectedScenario(profile.active_birth_provenance) + ? { selfSelectedScenario: true } : {}), rectificationCaseId: typeof profile.rectification_case_id === "string" ? profile.rectification_case_id : "", countryCode: typeof countryCode === "string" && countryCode ? countryCode : "CN", provinceCode: typeof provinceCode === "string" ? provinceCode : "", diff --git a/frontend/src/lib/home-types.ts b/frontend/src/lib/home-types.ts index 088671de2..25d5942ae 100644 --- a/frontend/src/lib/home-types.ts +++ b/frontend/src/lib/home-types.ts @@ -32,6 +32,7 @@ export type Profile = BirthTimeDraft & { rectificationCaseId: string; activeDate?: string; activeTimezoneOffset?: number; + selfSelectedScenario?: boolean; ayanamsa: AyanamsaName; /** Optional; absent or null = not filled (TASK-consult-gender-optional-20260927). */ gender?: ProfileGender | null; diff --git a/frontend/src/lib/people-archive-view.ts b/frontend/src/lib/people-archive-view.ts index f9db197e0..82ccbc3e7 100644 --- a/frontend/src/lib/people-archive-view.ts +++ b/frontend/src/lib/people-archive-view.ts @@ -70,7 +70,8 @@ export function peopleRowMeta(profile: Profile): string { * has a time, and a hospital-record time is not a 校正结果. */ export function peopleTimeRectified(profile: Profile): boolean { - return (profile.birthTimeStatus === "accepted" || profile.birthTimeStatus === "confirmed") + return !profile.selfSelectedScenario + && (profile.birthTimeStatus === "accepted" || profile.birthTimeStatus === "confirmed") && profile.rectificationCaseId.trim() !== ""; } diff --git a/frontend/src/lib/personal-report-longform-birth.ts b/frontend/src/lib/personal-report-longform-birth.ts index b04308b96..e06295e57 100644 --- a/frontend/src/lib/personal-report-longform-birth.ts +++ b/frontend/src/lib/personal-report-longform-birth.ts @@ -1,4 +1,5 @@ import { birthRowForReading, birthWindowRetired } from "./retired-birth-window.ts"; +import { isSelfSelectedScenario } from "./chart-choice/self-selected-scenario.ts"; import { globalBirthProfileFromAccountRow, } from "./server-owned-birth-profile"; @@ -146,12 +147,13 @@ export function buildLongformBirthPayload( const year = Number.parseInt(dateMatch[1], 10); const provenance = asRecord(account?.active_birth_provenance); const retired = birthWindowRetired(provenance); + const scenario = isSelfSelectedScenario(provenance); const multiClock = provenance?.contract === "chart-choice-v2" && (account?.birth_time_status === "accepted" || account?.birth_time_status === "confirmed") ? reportAdoptedClock(account.active_birth_time) : undefined; const rectified = account && (provenance?.contract !== "chart-choice-v2" || multiClock) ? rectifiedReadingWindow(account, dateMatch[0], multiClock ?? timeMatch[0]) : null; - const readingMinuteConfirmed = !retired && (rectified + const readingMinuteConfirmed = !retired && !scenario && (rectified ? rectified.source === "rectified_range" && rectified.before_minutes === 0 && rectified.after_minutes === 0 : extras.readingMinuteConfirmed ?? extras.birthTimeAccuracy === "confirmed"); const birthWindow = rectified ?? (!readingMinuteConfirmed && account ? readingBirthWindow(account, timeMatch[0]) : undefined); @@ -173,10 +175,10 @@ export function buildLongformBirthPayload( today: extras.today, target_year: extras.targetYear, age: extras.targetYear - year, - birth_time_accuracy: retired ? "provisional" : rectified && readingMinuteConfirmed ? "confirmed" : extras.birthTimeAccuracy, + birth_time_accuracy: retired || scenario ? "provisional" : rectified && readingMinuteConfirmed ? "confirmed" : extras.birthTimeAccuracy, ...(readingMinuteConfirmed ? {} : { reading_minute_confirmed: false }), ...(birthWindow ? { birth_time_window: birthWindow } : {}), - ...(!retired && extras.candidateRange ? { candidate_range: extras.candidateRange } : {}), + ...(!retired && !scenario && extras.candidateRange ? { candidate_range: extras.candidateRange } : {}), birthplace_label: accountText(row, "birth_place_label") ?? undefined, coordinate_source: "user_reported", coordinate_precision: "unverified_user_coordinates", diff --git a/frontend/src/lib/personal-report-route-core.ts b/frontend/src/lib/personal-report-route-core.ts index 6aa1ac8f4..c83c89b90 100644 --- a/frontend/src/lib/personal-report-route-core.ts +++ b/frontend/src/lib/personal-report-route-core.ts @@ -19,6 +19,7 @@ import { parseReportCandidateRange, type ReportCandidateClockRange } from "./rep import { effectiveBirthDate } from "./effective-birth-date"; import { asRecord as record, finiteNumberOrNull as finiteNumber } from "@/lib/guards"; +import { isSelfSelectedScenario } from "./chart-choice/self-selected-scenario"; import { personalReportCreateRequestSchema, type PersonalReportCreateRequest, @@ -254,7 +255,9 @@ export function resolveReportBirthTimeSensitivityInput( representativeTime: string, candidateRange: ReportCandidateClockRange | null, ): Partial { - void profileValue; + if (isSelfSelectedScenario(record(profileValue)?.active_birth_provenance)) { + return { birth_time_accuracy: "provisional", representative_time: representativeTime }; + } if (birthTimeStatus === "confirmed") { return { birth_time_accuracy: "confirmed", representative_time: representativeTime }; } diff --git a/frontend/src/mastra/consultation-tools.ts b/frontend/src/mastra/consultation-tools.ts index 1bd7ffec5..e9dc5edaa 100644 --- a/frontend/src/mastra/consultation-tools.ts +++ b/frontend/src/mastra/consultation-tools.ts @@ -907,6 +907,8 @@ function mergeConsultationEvidencePackets( ...(audit !== undefined ? { technique_audit_table: audit } : {}), ...(varga !== undefined ? { varga_spectrum: varga } : {}), ...(western !== undefined ? { western_spectrum: western } : {}), + chart_choice_both_versions: contracts.find((contract) => contract.chart_choice_both_versions)?.chart_choice_both_versions, + chart_choice_scenarios: contracts.find((contract) => contract.chart_choice_scenarios)?.chart_choice_scenarios, must_use_layers: unionStringList(contracts.map((contract) => contract.must_use_layers)), }, claim_cards: options.claimCards, diff --git a/frontend/src/mastra/consultation-workflow.ts b/frontend/src/mastra/consultation-workflow.ts index fbfdaf18d..9dc9f7700 100644 --- a/frontend/src/mastra/consultation-workflow.ts +++ b/frontend/src/mastra/consultation-workflow.ts @@ -10,7 +10,19 @@ import { } from "../lib/calculation-modes.ts"; import { applyUnreliableVargasToWorkflowContext } from "../lib/consultation-birth-time-mode.ts"; import { recordOrEmpty as record } from "@/lib/guards"; -import { applyBothVersionsToWorkflowContext, CHART_CHOICE_OTHER_AT, loadOtherVersionCharts } from "../lib/chart-choice-both-versions.ts"; +import { applyBothVersionsToWorkflowContext, CHART_CHOICE_OTHER_AT, chartChoiceScenariosSchema, compareChartChoiceScenarios, loadOtherVersionCharts } from "../lib/chart-choice-both-versions.ts"; +import type { ScenarioSelection } from "../lib/chart-choice/self-selected-scenario.ts"; + +export function selfSelectedScenarioOpening(selection: ScenarioSelection | undefined, followUp: boolean, question: string): string { + if (!selection) return ""; + if (followUp && !/出生(?:时间|时刻|钟点)|生时|时辰|几点出生|birth\s+time/i.test(question)) { + return " 已经说明过所用情景,本轮直接回答,不重复说明。"; + } + const opening = selection === "unsure" + ? "你没有选定线前还是线后,受影响的地方我会把几种情况分开说。" + : `这次按你自己选的${selection === "before" ? "线前" : "线后"}情景来看,不是出生时间已核实;你填的时间和范围都还保留着。`; + return ` 回答开头原样写一次:「${opening}」其余正文根据已计算的情景回答,不加重复的自选提示。`; +} export const consultationInputSchema = z.object({ year: z.number().int().min(1900).max(2100), @@ -18,6 +30,7 @@ export const consultationInputSchema = z.object({ day: z.number().int().min(1).max(31), hour: z.number().int().min(0).max(23), minute: z.number().int().min(0).max(59), + second: z.number().int().min(0).max(59).optional(), lat: z.number().min(-90).max(90), lon: z.number().min(-180).max(180), tz: z.number().min(-12).max(14), @@ -43,6 +56,7 @@ export const consultationInputSchema = z.object({ unreliable_vargas: z.array(z.enum(["D1", "D9", "D10"])).min(1).optional(), // 生时纠正「两版都读」(产品 2026-11-07)。Server-owned, never sent to the // consultation workflow; only the other side's charts are fetched for it. + chart_choice_scenarios: chartChoiceScenariosSchema.optional(), chart_choice_both_versions: z.object({ chosen_side: z.enum(["before", "after"]), other_at: z.string().regex(CHART_CHOICE_OTHER_AT), @@ -173,7 +187,7 @@ export async function runConsultationWorkflow( ) { const { entryMode, question, theme, unreliable_vargas: unreliableVargas, - chart_choice_both_versions: bothVersions, ...workflowInput + chart_choice_both_versions: bothVersions, chart_choice_scenarios: scenarios, ...workflowInput } = input; const plan = options?.plan ?? createConsultationPlan({ userIntent: question, theme }); const workflowRequest = projectConsultationWorkflowRequest(question, theme, plan); @@ -227,7 +241,10 @@ export async function runConsultationWorkflow( "Jyotish API returned an incomplete consultation contract", ); } - const context = applyUnreliableVargasToWorkflowContext(attachMinuteSensitiveThemes(parsed.data), unreliableVargas); + const base = applyUnreliableVargasToWorkflowContext(attachMinuteSensitiveThemes(parsed.data), unreliableVargas); + const context = scenarios ? { + ...base, consumer_context: { ...base.consumer_context, chart_choice_scenarios: compareChartChoiceScenarios(scenarios) }, + } : base; if (!bothVersions) return context; const block = await loadOtherVersionCharts( { lat: input.lat, lon: input.lon, tz: input.tz, ayanamsa: input.ayanamsa, city: input.city, node_mode: input.node_mode, position_mode: input.position_mode }, @@ -316,6 +333,7 @@ export const consultationEvidencePacketSchema = z.object({ western_spectrum: modelOutputEvidenceSchema.optional(), must_use_layers: modelOutputEvidenceSchema.optional(), chart_choice_both_versions: modelOutputEvidenceSchema.optional(), + chart_choice_scenarios: modelOutputEvidenceSchema.optional(), }), claim_cards: z.array(z.object({ category: z.enum(consultationEvidenceCategoryValues), @@ -878,6 +896,9 @@ function projectEvidenceContract( ...(contract.chart_choice_both_versions && typeof contract.chart_choice_both_versions === "object" ? { chart_choice_both_versions: contract.chart_choice_both_versions as ModelOutputValue } : {}), + ...(contract.chart_choice_scenarios && typeof contract.chart_choice_scenarios === "object" + ? { chart_choice_scenarios: contract.chart_choice_scenarios as ModelOutputValue } + : {}), }; } @@ -974,6 +995,7 @@ export function toAgentConsultationContext(data: JsonRecord) { varga_spectrum: consumerContext.varga_spectrum, western_spectrum: consumerContext.western_spectrum, chart_choice_both_versions: consumerContext.chart_choice_both_versions, + chart_choice_scenarios: consumerContext.chart_choice_scenarios, }, chart: { birth: chart.birth, ascendant: chart.ascendant, planets: chart.planets, houses: chart.houses, diff --git a/frontend/supabase/migrations/20261117130000_chart_choice_scenario.sql b/frontend/supabase/migrations/20261117130000_chart_choice_scenario.sql new file mode 100644 index 000000000..55668ef11 --- /dev/null +++ b/frontend/supabase/migrations/20261117130000_chart_choice_scenario.sql @@ -0,0 +1,94 @@ +-- BUG-1958: compare the preview against the same row that receives the save. +-- Existing adoption RPCs and stored records remain compatible. +begin; + +create or replace function public.chart_choice_scenario_state_v1( + p_user_id uuid, p_chart_profile_id uuid +) +returns jsonb +language sql +stable +security definer +set search_path = '' +as $$ + with subject as ( + select to_jsonb(p) as doc + from public.profiles p where p_chart_profile_id is null and p.id = p_user_id + union all + select to_jsonb(p) from public.chart_profiles p + where p.id = p_chart_profile_id and p.user_id = p_user_id and p.role = 'other' + ), declaration as ( + select jsonb_object_agg(field, coalesce(doc->field, 'null'::jsonb)) as value + from subject + cross join unnest(array[ + 'birth_date', 'reported_birth_time', 'birth_time_source', 'birth_time_period', + 'declared_window_start', 'declared_window_end', 'uncertainty_before_minutes', + 'uncertainty_after_minutes', 'birth_time_uncertainty_known', 'birth_time_clue', + 'birth_time_shichen', 'latitude', 'longitude', 'timezone_offset', 'timezone_id', + 'ayanamsa', 'country_code', 'province_code', 'city_code', 'district_code' + ]) as fields(field) + ) + select jsonb_build_object( + 'current_record_id', case when doc->>'birth_time_status' in ('accepted','confirmed') + then doc#>>'{active_birth_provenance,record_id}' end, + 'declaration_fingerprint', encode(sha256(convert_to(declaration.value::text, 'UTF8')), 'hex') + ) + from subject cross join declaration; +$$; + +create or replace function public.chart_choice_adopt_scenario_v1( + p_user_id uuid, p_chart_profile_id uuid, p_base_record_id uuid, + p_declaration_fingerprint text, p_time time without time zone, p_date date, + p_offset double precision, p_provenance jsonb, p_detail jsonb +) +returns jsonb +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_state jsonb; + v_revision bigint; +begin + if p_chart_profile_id is null then + perform 1 from public.profiles where id = p_user_id for update; + else + perform 1 from public.chart_profiles + where id = p_chart_profile_id and user_id = p_user_id and role = 'other' for update; + end if; + if not found then + raise exception 'chart_choice_subject_not_found' using errcode = 'P0001'; + end if; + + v_state := public.chart_choice_scenario_state_v1(p_user_id, p_chart_profile_id); + if p_base_record_id::text is distinct from v_state->>'current_record_id' + or p_declaration_fingerprint is distinct from v_state->>'declaration_fingerprint' then + raise exception 'chart_choice_stale_choice' using errcode = 'P0001'; + end if; + if p_provenance->>'selection_kind' is distinct from 'self_selected_scenario' + or p_provenance->>'basis' is distinct from 'self_choice_20261116' then + raise exception 'chart_choice_invalid_input' using errcode = 'P0001'; + end if; + + select count(*) + 1 into v_revision + from public.chart_choice_records r + where r.user_id = p_user_id and r.chart_profile_id is not distinct from p_chart_profile_id + and (r.detail#>>'{provenance,basis}' = 'self_choice_20261116' + or r.detail#>>'{provenance,selection_kind}' = 'self_selected_scenario'); + + return public.chart_choice_adopt_v4( + p_user_id, p_chart_profile_id, p_time, p_date, p_offset, + p_provenance || jsonb_build_object('choice_revision', v_revision), + null, null, null, null, p_detail + ); +end; +$$; + +revoke all on function public.chart_choice_scenario_state_v1(uuid, uuid) from public, anon, authenticated; +grant execute on function public.chart_choice_scenario_state_v1(uuid, uuid) to service_role; +revoke all on function public.chart_choice_adopt_scenario_v1(uuid, uuid, uuid, text, time without time zone, date, + double precision, jsonb, jsonb) from public, anon, authenticated; +grant execute on function public.chart_choice_adopt_scenario_v1(uuid, uuid, uuid, text, time without time zone, date, + double precision, jsonb, jsonb) to service_role; + +commit; diff --git a/frontend/tests/chart-choice-self-choice-20261116.test.tsx b/frontend/tests/chart-choice-self-choice-20261116.test.tsx index 5471f06e1..f673fa670 100644 --- a/frontend/tests/chart-choice-self-choice-20261116.test.tsx +++ b/frontend/tests/chart-choice-self-choice-20261116.test.tsx @@ -25,15 +25,15 @@ test("self-choice result describes the six charts from real transitions and only const render = (packet: Complete) => renderToStaticMarkup( {}} onSelfChoice={() => {}} />); const reported = render(fixtures.reported); - assert.match(reported, /不受影响:主盘。/); - assert.match(reported, /差几分钟就不同:婚恋、事业、钱财、日常、突变。/); - assert.match(reported, /04:59:43 之前巨蟹上升,之后狮子上升等 5 处/); + assert.match(reported, /上升星座不变:主盘。/); + assert.match(reported, /上升星座会变:婚恋、事业、钱财、日常、突变。/); + assert.match(reported, /04:59:43 之前巨蟹上升,之后狮子上升等 5 处<\/summary>/); assert.match(reported, /你填的 05:00 离 04:59:43 这条线只有 17 秒。/); assert.match(reported, />自己选线前线后<\/button>/); assert.doesNotMatch(reported, forbiddenCopy); const stable = render(fixtures.stable); - assert.match(stable, /这个时间范围内六张盘都不变,可以直接用。/); + assert.match(stable, /这个时间范围内,六张盘的上升星座都不变。/); assert.doesNotMatch(stable, /自己选线前线后/); const midnight = render(fixtures.midnight); assert.match(midnight, /你填的 00:00 离 8月8日 23:59:35 这条线只有 25 秒。/); @@ -77,14 +77,17 @@ test("self-choice page selects each line once, stops or keeps narrowing, and off }; return Response.json({ saved_at: original.saved_at }); } - assert.deepEqual(Object.keys(body).sort(), ["choices", "mode", "selfChoice", "subjectId"]); assert.equal(body.selfChoice, true); if (body.mode === "preview") { + assert.deepEqual(Object.keys(body).sort(), ["choices", "mode", "selfChoice", "subjectId"]); const next = [fixtures.first, ...scenario.previews][calls++]; assert.deepEqual(body.choices, next.decision.choices); - return Response.json(next); + return Response.json({ ...next, current_record_id: current?.id ?? null, declaration_fingerprint: "a".repeat(64) }); } assert.equal(body.mode, "choice"); + assert.deepEqual(Object.keys(body).sort(), ["baseRecordId", "choices", "declarationFingerprint", "mode", "selfChoice", "subjectId"]); + assert.equal(body.baseRecordId, null); + assert.equal(body.declarationFingerprint, "a".repeat(64)); const decision = scenario.end.decision; assert.deepEqual(body.choices, decision.choices); current = { @@ -162,22 +165,35 @@ test("self-choice API recomputes from storage, preserves declaration, de-duplica }; const writes = []; const records = []; + let fingerprint = "a".repeat(64); const admin = { rpc: async (name, args) => { + const current = row.active_birth_provenance?.record_id ?? null; if (name === "chart_choice_records_v1") { - return { data: { current_record_id: recordId, records }, error: null }; + return { data: { current_record_id: current, records }, error: null }; + } + if (name === "chart_choice_scenario_state_v1") { + return { data: { current_record_id: current, declaration_fingerprint: fingerprint }, error: null }; } - assert.equal(name, "chart_choice_adopt_v4"); assert.equal(args.p_chart_profile_id, null); - for (const key of ["p_window_start", "p_window_end", "p_before_minutes", "p_after_minutes"]) { - assert.equal(args[key], null); + if (name === "chart_choice_adopt_scenario_v1") { + assert.equal(args.p_base_record_id, current); + assert.equal(args.p_declaration_fingerprint, fingerprint); + assert.equal(args.p_window_start, undefined); + args.p_provenance.choice_revision = 1 + writes.filter((write) => write.p_provenance.selection_kind).length; + } else { + assert.equal(name, "chart_choice_adopt_v4"); + for (const key of ["p_window_start", "p_window_end", "p_before_minutes", "p_after_minutes"]) { + assert.equal(args[key], null); + } } + const savedId = recordId.slice(0, -1) + String(writes.length + 1); writes.push(args); - row.active_birth_provenance = { ...args.p_provenance, record_id: recordId }; + row.active_birth_provenance = { ...args.p_provenance, record_id: savedId }; row.active_birth_time = args.p_time; row.active_birth_date = args.p_date; row.birth_time_status = "accepted"; - records.unshift({ id: recordId, reusable: true, detail: { ...args.p_detail, provenance: args.p_provenance } }); - return { data: { record_id: recordId }, error: null }; + records.unshift({ id: savedId, reusable: true, detail: { ...args.p_detail, provenance: args.p_provenance } }); + return { data: { record_id: savedId }, error: null }; } }; mock.module("server-only", { namedExports: {} }); mock.module("@/lib/supabase/server", { namedExports: { createServerSupabaseClient: async () => supabase } }); @@ -185,7 +201,7 @@ test("self-choice API recomputes from storage, preserves declaration, de-duplica mock.module("@/lib/product-access", { namedExports: { isProductEnabled: async () => true } }); mock.module("@/lib/request-rate-limit", { namedExports: { consumeUserRequestRateLimit: () => ({ ok: true }) } }); const { POST } = await import("./src/app/api/chart-choice/adopt/route.ts"); - const { chartChoiceBothVersionsFromProvenance } = await import("./src/lib/chart-choice-both-versions.ts"); + const { chartChoiceBothVersionsFromProvenance, chartChoiceScenariosFromProvenance } = await import("./src/lib/chart-choice-both-versions.ts"); const engine = []; globalThis.fetch = async (url, init) => { const body = JSON.parse(init.body); @@ -211,16 +227,39 @@ test("self-choice API recomputes from storage, preserves declaration, de-duplica assert.equal(engine.length, 0); const preview = await post({ selfChoice: true, mode: "preview", choices: [] }); assert.equal(preview.status, 200); - assert.deepEqual(await preview.json(), first); + assert.deepEqual(await preview.json(), { ...first, current_record_id: null, declaration_fingerprint: fingerprint }); + assert.equal((await post({ selfChoice: true, choices: [] })).status, 400); const narrow = { start_at: reported.reported_at, end_at: reported.window.end_at }; + const binding = async () => { + const response = await post({ selfChoice: true, mode: "preview", choices: [] }); + assert.equal(response.status, 200); + const data = await response.json(); + return { baseRecordId: data.current_record_id, declarationFingerprint: data.declaration_fingerprint }; + }; + const initial = await binding(); for (let repeat = 0; repeat < 2; repeat++) { - const response = await post({ selfChoice: true, choices: finished.decision.choices, window: narrow }); + const response = await post({ selfChoice: true, choices: finished.decision.choices, window: narrow, ...await binding() }); assert.equal(response.status, 200); assert.deepEqual(await response.json(), { decision: finished.decision }); } assert.equal(writes.length, 1); assert.equal(engine.filter(([path, body]) => path.endsWith("/decide") && body.self_choice).length, 2); + const replay = await post({ selfChoice: true, choices: finished.decision.choices, ...initial }); + assert.equal(replay.status, 409); + assert.equal((await replay.json()).code, "stale_choice"); + const beforeEdit = await binding(); + fingerprint = "b".repeat(64); + const changed = await post({ selfChoice: true, choices: finished.decision.choices, ...beforeEdit }); + assert.equal(changed.status, 409); + assert.equal((await changed.json()).code, "stale_choice"); + assert.equal(writes.length, 1); const saved = row.active_birth_provenance; + assert.equal(saved.selection_kind, "self_selected_scenario"); + assert.equal(saved.choice_revision, 1); + assert.deepEqual(saved.declared_window, reported.window); + assert.deepEqual(saved.scenario_segment, saved.segment); + assert.deepEqual(saved.remaining_lines, finished.decision.remaining_lines); + assert.deepEqual(saved.scenarios, finished.decision.scenarios); assert.equal(saved.source, "user_choice"); assert.equal(saved.rule, "user_override"); assert.equal(saved.declared_by_user, true); @@ -232,15 +271,18 @@ test("self-choice API recomputes from storage, preserves declaration, de-duplica assert.equal(row.birth_time_status, "accepted"); assert.deepEqual(Object.fromEntries(Object.keys(declared).map((key) => [key, row[key]])), declared); - const uncertain = await post({ selfChoice: true, choices: unsure.decision.choices }); + const uncertain = await post({ selfChoice: true, choices: unsure.decision.choices, ...await binding() }); assert.equal(uncertain.status, 200); - const both = chartChoiceBothVersionsFromProvenance(row.active_birth_provenance); - assert.deepEqual(both.domains.map(({ chart }) => chart), ["D10", "D2", "D6", "D8"]); - assert.equal(both.chosen_side, "after"); + assert.equal(chartChoiceBothVersionsFromProvenance(row.active_birth_provenance), null); + const scenarios = chartChoiceScenariosFromProvenance(row.active_birth_provenance); + assert.equal(scenarios.alternatives.length, 3); + assert.ok(scenarios.omitted > 0); assert.equal(row.active_birth_time, declared.reported_birth_time + ":00"); - assert.ok(both.other_at < first.next.at); + assert.equal(row.active_birth_provenance.choice_revision, 2); + assert.equal(row.active_birth_provenance.other_saved_at, null); + assert.equal(row.active_birth_provenance.chosen_side, "none"); - const restored = await post({ mode: "restore_default", recordId }); + const restored = await post({ mode: "restore_default", recordId: row.active_birth_provenance.record_id }); assert.equal(restored.status, 200); assert.deepEqual(await restored.json(), { saved_at: reported.reported_at }); assert.equal(row.active_birth_time, declared.reported_birth_time + ":00"); diff --git a/frontend/tests/chart-choice-self-choice-scenario-20261117.test.tsx b/frontend/tests/chart-choice-self-choice-scenario-20261117.test.tsx new file mode 100644 index 000000000..d96ebceb3 --- /dev/null +++ b/frontend/tests/chart-choice-self-choice-scenario-20261117.test.tsx @@ -0,0 +1,183 @@ +import "./install-test-document"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; +import React from "react"; +import { renderToStaticMarkup } from "react-dom/server"; +import { ChartChoiceFlow, FinalStep, SelfChoiceStep } from "../src/components/chart-choice/chart-choice-page"; +import { SELF_CHOICE_BASIS, type ChartChoiceEnginePacket, type SelfChoicePreview } from "../src/lib/chart-choice/contract"; +import { isSelfSelectedScenario } from "../src/lib/chart-choice/self-selected-scenario"; +import { chartChoiceBothVersionsFromProvenance, chartChoiceScenariosFromProvenance, compareChartChoiceScenarios } from "../src/lib/chart-choice-both-versions"; +import { libraryProfileFromSubjectRow } from "../src/lib/chart-subject-write"; +import { readProfile, profileBirthTimeStatusLabel } from "../src/lib/home-profile"; +import { peopleTimeRectified } from "../src/lib/people-archive-view"; +import { buildLongformBirthPayload } from "../src/lib/personal-report-longform-birth"; +import { marriageMatchBirthBody } from "../src/lib/marriage-match-service"; +import { resolveReportBirthTimeSensitivityInput } from "../src/lib/personal-report-route-core"; +import { prepareConsultationRoute } from "../src/lib/consultation-route-service"; +import { selfSelectedScenarioOpening } from "../src/mastra/consultation-workflow"; +import { createClientLifecycleHarness } from "./react-client-lifecycle-test-support"; + +Object.assign(globalThis, { React }); +type Complete = Extract; +const fixture = JSON.parse(readFileSync(new URL("./fixtures/chart-choice-self-choice-20261116.json", import.meta.url), "utf8")) as { + reported: Complete; stable: Complete; first: SelfChoicePreview; unsure: SelfChoicePreview; finished: SelfChoicePreview; three: SelfChoicePreview; +}; +const AGE = { today: "2042-02-03", targetYear: 2042, candidateRange: null, birthTimeAccuracy: "confirmed" as const }; +const basis = { source: "user_choice", basis: SELF_CHOICE_BASIS, declared_by_user: true }; +const row = { + name: "Fictional Scenario", birth_date: "1997-08-08", reported_birth_time: "05:00:00", active_birth_time: "05:00:17", + active_birth_date: "1997-08-08", active_birth_timezone_offset: 8, birth_time_source: "approximate", birth_time_status: "accepted", + latitude: 36.42, longitude: 114.21, timezone_offset: 8, timezone_id: "Asia/Shanghai", birth_place_label: "虚构市", + rectification_case_id: "synthetic-case", ayanamsa: "lahiri", +}; + +test("self-selected scenario results disclose the full list of checked ascendant transitions", () => { + const render = (packet: Complete) => renderToStaticMarkup( {}} onSelfChoice={() => {}} />); + const result = render(fixture.reported); + assert.match(result, /上升星座不变:主盘。/); + assert.match(result, /上升星座会变:婚恋、事业、钱财、日常、突变。/); + assert.match(render(fixture.stable), /这个时间范围内,六张盘的上升星座都不变。/); + const el = document.createElement("div"); + el.innerHTML = result; + const summary = fixture.reported.decision.reported_choice!.line_summary!; + assert.match(el.textContent ?? "", new RegExp(`共有 ${summary.line_count} 处换座。`)); + for (const entry of el.querySelectorAll("details")) { + entry.open = true; + const summaryText = entry.querySelector("summary")!.textContent!; + const count = Number(/等 (\d+) 处/.exec(summaryText)?.[1]); + const rows = Array.from(entry.querySelectorAll("li"), ({ textContent }) => textContent); + assert.equal(rows.length, count); + assert.ok(rows.every((text) => /\d{2}:\d{2}:\d{2} 之前.+上升,之后.+上升/.test(text ?? ""))); + } + assert.ok(el.querySelectorAll("details").length >= 2); +}); + +test("self-selected scenario UI keeps fixed option order and explains the unverified choice once", () => { + const render = (preview: SelfChoicePreview) => renderToStaticMarkup( {}} onPick={() => {}} + onStop={() => {}} onAccept={() => {}} />); + const choosing = render(fixture.first); + const confirmation = render(fixture.unsure); + const el = document.createElement("div"); + el.innerHTML = choosing; + assert.deepEqual(Array.from(el.querySelectorAll('[role="group"] button'), (button) => button.textContent), ["线前", "线后", "不确定"]); + assert.match(confirmation, new RegExp(`还有 ${fixture.unsure.decision.remaining_lines?.length} 条线没选。`)); + const approved = "这不是出生时间已核实,你填的时间和范围都还保留着。"; + assert.equal(confirmation.split(approved).length, 2); + assert.doesNotMatch(choosing + confirmation.replace(approved, ""), /可以直接用|不受影响|推荐|打分|更符合|已核实|已确认|已校正/); +}); + +test("stale self-choice save reloads the current start and returns to a fresh result", async () => { + const h = createClientLifecycleHarness(); + const previous = globalThis.fetch; + const fp = "d".repeat(64); + let starts = 0; + let packets = 0; + let saves = 0; + globalThis.fetch = async (url, init) => { + const path = String(url); + if (path.startsWith("/api/chart-choice?")) { + starts++; + return Response.json({ + status: "ready", subjectId: "self", name: row.name, window: fixture.reported.window, + reportedAt: fixture.reported.reported_at, precision: "minutes", rangeAdjustable: false, + history: { current_record_id: null, records: [] }, + }); + } + if (path === "/api/chart-choice/packet") { + packets++; + return Response.json(fixture.reported); + } + assert.equal(path, "/api/chart-choice/adopt"); + const body = JSON.parse(String(init?.body)); + if (body.mode === "preview") return Response.json({ ...(body.choices.length ? fixture.unsure : fixture.first), + current_record_id: null, declaration_fingerprint: fp }); + assert.equal(body.baseRecordId, null); + assert.equal(body.declarationFingerprint, fp); + saves++; + return Response.json({ code: "stale_choice", error: "出生资料改过了,这次的结果不能再用。" }, { status: 409 }); + }; + const click = async (text: string) => { + const find = () => h.elements().find((item) => item.tagName === "BUTTON" && item.text === text); + for (let i = 0; i < 10 && !find(); i++) await h.idle(); + const target = find(); + assert.ok(target, text); + await h.event(target); + }; + try { + await h.render(); + await click("自己选线前线后"); + await click("不确定"); + await click("用 " + fixture.unsure.decision.saved_at.slice(11)); + for (let i = 0; i < 10 && packets < 2; i++) await h.idle(); + assert.equal(starts, 2); + assert.equal(packets, 2); + assert.equal(saves, 1); + assert.ok(h.elements().some((item) => item.text === "出生资料改过了,这次的结果不能再用。")); + assert.ok(h.elements().some((item) => item.text === "自己选线前线后")); + assert.equal(h.errors.length, 0); + } finally { + globalThis.fetch = previous; + await h.close(); + } +}); + +test("new and historical self-selected scenarios remain usable without a confirmed badge or report input", () => { + assert.equal(isSelfSelectedScenario(basis), true); + assert.equal(isSelfSelectedScenario({ selection_kind: "self_selected_scenario" }), true); + assert.equal(isSelfSelectedScenario({ source: "reported_time_default" }), false); + const point = "1997-08-08T05:00:17"; + const provenance = { ...basis, contract: "chart-choice-v2", segment: { start_at: point, end_at: point } }; + const stored = { ...row, active_birth_provenance: provenance }; + const profile = readProfile(stored); + assert.equal(profile.time, "05:00"); + assert.equal(profileBirthTimeStatusLabel(profile), "用户自选情景"); + assert.equal(peopleTimeRectified(profile), false); + assert.equal(peopleTimeRectified(readProfile(row)), true); + assert.equal(libraryProfileFromSubjectRow(stored).selfSelectedScenario, true); + assert.equal(buildLongformBirthPayload(stored, AGE)?.reading_minute_confirmed, false); + assert.equal(buildLongformBirthPayload(stored, AGE)?.birth_time_accuracy, "provisional"); + assert.equal(marriageMatchBirthBody(stored, AGE.today).reading_minute_confirmed, undefined); + assert.equal(resolveReportBirthTimeSensitivityInput(stored, "accepted", "05:00", { + startTime: "05:00", endTime: "05:00", + }).birth_time_accuracy, "provisional"); +}); + +test("chat uses the saved scenario with one opening and computed alternatives only", async () => { + const legacy = { ...basis, choices: [{ side: "before" }] }; + const { scenarios, scenarios_omitted } = fixture.unsure.decision; + assert.ok(scenarios && scenarios.length >= 3 && scenarios_omitted); + const provenance = { ...basis, choices: [{ side: "unsure" }], scenarios, scenarios_omitted }; + assert.equal(chartChoiceBothVersionsFromProvenance(provenance), null); + const comparison = chartChoiceScenariosFromProvenance(provenance)!; + const block = compareChartChoiceScenarios(comparison); + assert.deepEqual(block.other_scenarios.map((item) => item.saved_at), + scenarios.filter((item) => !item.is_primary).map((item) => item.saved_at)); + assert.match(block.notice, new RegExp(`另有 ${scenarios_omitted} 种情景没有算`)); + const three = chartChoiceScenariosFromProvenance({ ...basis, scenarios: fixture.three.decision.scenarios })!; + assert.equal(compareChartChoiceScenarios(three).other_scenarios.length, 2); + assert.equal(compareChartChoiceScenarios(three).scenarios_omitted, 0); + const adjacent = chartChoiceScenariosFromProvenance({ + ...basis, scenarios: fixture.finished.decision.scenarios, comparison_scenario: fixture.finished.decision.comparison_scenario, + })!; + assert.ok(compareChartChoiceScenarios(adjacent).opposite_side?.ascendant_changes.length); + const prepared = await prepareConsultationRoute({ + userId: "synthetic-owner", mode: "verified_chart", loadProfile: async () => ({ ...row, active_birth_provenance: provenance }), + resolveTimezoneOffset: async (value) => value, + loadCandidateRange: async () => { throw new Error("Unrelated candidate range should not be read"); }, + reserve: async () => true, + }); + assert.equal(prepared.serverChart?.selfSelectedScenario, "unsure"); + assert.equal(prepared.serverChart?.toolInput.birth_time_accuracy, "provisional"); + assert.equal(prepared.serverChart?.toolInput.time_source, "self_selected_scenario"); + assert.equal(prepared.serverChart?.toolInput.second, 17); + assert.ok(prepared.serverChart?.toolInput.chart_choice_scenarios); + assert.match(selfSelectedScenarioOpening("unsure", false, "事业"), /你没有选定线前还是线后/); + assert.match(selfSelectedScenarioOpening("before", false, "事业"), /自己选的线前情景/); + assert.doesNotMatch(selfSelectedScenarioOpening("after", true, "事业"), /出生时间已核实/); + assert.match(selfSelectedScenarioOpening("after", true, "出生时间是哪一天?"), /自己选的线后情景/); + assert.equal(selfSelectedScenarioOpening(undefined, false, "事业"), ""); + assert.equal(isSelfSelectedScenario(legacy), true); +}); diff --git a/frontend/tests/database-chart-choice-scenario-1958.test.ts b/frontend/tests/database-chart-choice-scenario-1958.test.ts new file mode 100644 index 000000000..ef9618307 --- /dev/null +++ b/frontend/tests/database-chart-choice-scenario-1958.test.ts @@ -0,0 +1,104 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { randomUUID } from "node:crypto"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import { Client } from "pg"; +import { runMigrations } from "../scripts/db-migrate.mjs"; +import { startPostgresFixture } from "./helpers/postgres-fixture.ts"; + +const docker = spawnSync("docker", ["version"], { stdio: "ignore" }).status === 0; +const migrationDirs = ["../db/migrations", "../supabase/migrations"].map( + (dir) => fileURLToPath(new URL(dir, import.meta.url)), +); +const provenance = { + selection_kind: "self_selected_scenario", + basis: "self_choice_20261116", + source: "user_choice", + rule: "user_override", + declared_by_user: true, + chosen_side: "before", +}; +type State = { current_record_id: string | null; declaration_fingerprint: string }; + +test("BUG-1958 compares preview and allocates scenario revisions under the same PostgreSQL lock", { + skip: !docker && "docker unavailable", +}, async () => { + const fixture = startPostgresFixture(); + const migrationUrl = fixture.connectionUrl("schema_owner", "schema-owner-test-password"); + const owner = randomUUID(); + const otherOwner = randomUUID(); + const person = randomUUID(); + const editor = new Client({ connectionString: migrationUrl }); + const first = new Client({ connectionString: fixture.connectionUrl("service_runtime", "service-runtime-test-password") }); + const second = new Client({ connectionString: fixture.connectionUrl("service_runtime", "service-runtime-test-password") }); + const ordinary = new Client({ connectionString: fixture.connectionUrl("app_runtime", "app-runtime-test-password") }); + try { + assert.equal(await runMigrations({ connectionString: migrationUrl, migrationsDirectory: undefined, migrationsDirectories: migrationDirs }), 0); + await Promise.all([editor.connect(), first.connect(), second.connect(), ordinary.connect()]); + for (const id of [owner, otherOwner]) { + fixture.psqlAs("identity_runtime", "identity-runtime-test-password", + "insert into identity.users(id,name,email,email_verified) values ('" + id + + "','Fictional Scenario','" + id + "@example.invalid',true)"); + } + await editor.query( + "update public.profiles set birth_date='2041-02-03', reported_birth_time='09:00', " + + "birth_time_status='reported', declared_window_start='08:45', declared_window_end='09:15' where id=$1", [owner], + ); + await editor.query( + "insert into public.chart_profiles (id,user_id,role,name,profile,birth_date,reported_birth_time,birth_time_status) " + + "values ($1,$2,'other','Fictional Scenario','{}','2041-02-03','09:00','reported')", [person, owner], + ); + await Promise.all([first.query("set role service_role"), second.query("set role service_role"), ordinary.query("set role authenticated")]); + async function state(client: Client, user = owner, subject: string | null = null) { + const result = await client.query<{ value: State | null }>( + "select public.chart_choice_scenario_state_v1($1,$2) as value", [user, subject], + ); + return result.rows[0].value; + } + function save(client: Client, expected: State, subject: string | null = null) { + return client.query<{ value: { record_id: string } }>( + "select public.chart_choice_adopt_scenario_v1($1,$2,$3,$4,'09:02','2041-02-03',0,$5,$6) as value", + [owner, subject, expected.current_record_id, expected.declaration_fingerprint, provenance, {}], + ); + } + await assert.rejects(state(ordinary), /permission denied/); + assert.equal(await state(first, otherOwner, person), null); + const preview = (await state(first))!; + assert.equal(preview.current_record_id, null); + assert.match(preview.declaration_fingerprint, /^[a-f0-9]{64}$/); + const concurrent = await Promise.allSettled([save(first, preview), save(second, preview)]); + assert.equal(concurrent.filter((item) => item.status === "fulfilled").length, 1); + const loser = concurrent.find((item) => item.status === "rejected"); + assert.ok(loser && loser.status === "rejected"); + assert.match(loser.reason.message, /chart_choice_stale_choice/); + + const afterFirst = (await state(first))!; + assert.notEqual(afterFirst.current_record_id, null); + assert.equal(afterFirst.declaration_fingerprint, preview.declaration_fingerprint); + await assert.rejects(save(first, preview), /chart_choice_stale_choice/); + await save(first, afterFirst); + const saved = (await state(first))!; + const revisions = await editor.query<{ revision: string; kind: string }>( + "select detail#>>'{provenance,choice_revision}' as revision, detail#>>'{provenance,selection_kind}' as kind " + + "from public.chart_choice_records where user_id=$1 and chart_profile_id is null order by created_at", [owner], + ); + assert.deepEqual(revisions.rows, [1, 2].map((revision) => ({ revision: String(revision), kind: provenance.selection_kind }))); + await editor.query("update public.profiles set declared_window_start='08:35' where id=$1", [owner]); + assert.notEqual((await state(first))!.declaration_fingerprint, saved.declaration_fingerprint); + await assert.rejects(save(first, saved), /chart_choice_stale_choice/); + assert.equal((await editor.query("select id from public.chart_choice_records where user_id=$1", [owner])).rowCount, 2); + const other = (await state(first, owner, person))!; + await save(first, other, person); + const otherRevision = await editor.query<{ revision: string }>( + "select detail#>>'{provenance,choice_revision}' as revision from public.chart_choice_records where chart_profile_id=$1", [person], + ); + assert.equal(otherRevision.rows[0].revision, "1"); + } finally { + try { + await Promise.allSettled([editor.end(), first.end(), second.end(), ordinary.end()]); + } finally { + fixture.stop(); + } + } +}); diff --git a/frontend/tests/fixtures/chart-choice-self-choice-20261116.json b/frontend/tests/fixtures/chart-choice-self-choice-20261116.json index 2480c4ee4..54e1d6f21 100644 --- a/frontend/tests/fixtures/chart-choice-self-choice-20261116.json +++ b/frontend/tests/fixtures/chart-choice-self-choice-20261116.json @@ -133,36 +133,127 @@ "remaining_key_lines": 11, "line_summary": { "nearest_at": "1997-08-08T04:59:43", + "line_count": 11, "charts": { "D10": { "at": "1997-08-08T04:59:43", + "before": "巨蟹", + "after": "狮子", "count": 5, - "before": "巨蟹", - "after": "狮子" - }, - "D2": { - "at": "1997-08-08T04:59:43", - "count": 1, - "before": "巨蟹", - "after": "狮子" - }, - "D6": { - "at": "1997-08-08T04:59:43", - "count": 3, - "before": "射手", - "after": "摩羯" - }, - "D8": { - "at": "1997-08-08T04:59:43", - "count": 3, - "before": "巨蟹", - "after": "狮子" + "lines": [ + { + "at": "1997-08-08T04:30:14", + "before": "金牛", + "after": "双子" + }, + { + "at": "1997-08-08T04:44:57", + "before": "双子", + "after": "巨蟹" + }, + { + "at": "1997-08-08T04:59:43", + "before": "巨蟹", + "after": "狮子" + }, + { + "at": "1997-08-08T05:14:30", + "before": "狮子", + "after": "处女" + }, + { + "at": "1997-08-08T05:29:18", + "before": "处女", + "after": "天秤" + } + ] }, "D9": { "at": "1997-08-08T05:07:55", - "count": 4, "before": "天蝎", - "after": "射手" + "after": "射手", + "count": 4, + "lines": [ + { + "at": "1997-08-08T04:35:08", + "before": "处女", + "after": "天秤" + }, + { + "at": "1997-08-08T04:51:30", + "before": "天秤", + "after": "天蝎" + }, + { + "at": "1997-08-08T05:07:55", + "before": "天蝎", + "after": "射手" + }, + { + "at": "1997-08-08T05:24:22", + "before": "射手", + "after": "摩羯" + } + ] + }, + "D6": { + "at": "1997-08-08T04:59:43", + "before": "射手", + "after": "摩羯", + "count": 3, + "lines": [ + { + "at": "1997-08-08T04:35:08", + "before": "天蝎", + "after": "射手" + }, + { + "at": "1997-08-08T04:59:43", + "before": "射手", + "after": "摩羯" + }, + { + "at": "1997-08-08T05:24:22", + "before": "摩羯", + "after": "水瓶" + } + ] + }, + "D8": { + "at": "1997-08-08T04:59:43", + "before": "巨蟹", + "after": "狮子", + "count": 3, + "lines": [ + { + "at": "1997-08-08T04:41:16", + "before": "双子", + "after": "巨蟹" + }, + { + "at": "1997-08-08T04:59:43", + "before": "巨蟹", + "after": "狮子" + }, + { + "at": "1997-08-08T05:18:12", + "before": "狮子", + "after": "处女" + } + ] + }, + "D2": { + "at": "1997-08-08T04:59:43", + "before": "巨蟹", + "after": "狮子", + "count": 1, + "lines": [ + { + "at": "1997-08-08T04:59:43", + "before": "巨蟹", + "after": "狮子" + } + ] } } } @@ -509,40 +600,369 @@ ], "line_summary": { "nearest_at": "1997-08-08T04:59:43", + "line_count": 11, "charts": { "D10": { "at": "1997-08-08T04:59:43", + "before": "巨蟹", + "after": "狮子", "count": 5, - "before": "巨蟹", - "after": "狮子" - }, - "D2": { - "at": "1997-08-08T04:59:43", - "count": 1, - "before": "巨蟹", - "after": "狮子" - }, - "D6": { - "at": "1997-08-08T04:59:43", - "count": 3, - "before": "射手", - "after": "摩羯" - }, - "D8": { - "at": "1997-08-08T04:59:43", - "count": 3, - "before": "巨蟹", - "after": "狮子" + "lines": [ + { + "at": "1997-08-08T04:30:14", + "before": "金牛", + "after": "双子" + }, + { + "at": "1997-08-08T04:44:57", + "before": "双子", + "after": "巨蟹" + }, + { + "at": "1997-08-08T04:59:43", + "before": "巨蟹", + "after": "狮子" + }, + { + "at": "1997-08-08T05:14:30", + "before": "狮子", + "after": "处女" + }, + { + "at": "1997-08-08T05:29:18", + "before": "处女", + "after": "天秤" + } + ] }, "D9": { "at": "1997-08-08T05:07:55", - "count": 4, "before": "天蝎", - "after": "射手" + "after": "射手", + "count": 4, + "lines": [ + { + "at": "1997-08-08T04:35:08", + "before": "处女", + "after": "天秤" + }, + { + "at": "1997-08-08T04:51:30", + "before": "天秤", + "after": "天蝎" + }, + { + "at": "1997-08-08T05:07:55", + "before": "天蝎", + "after": "射手" + }, + { + "at": "1997-08-08T05:24:22", + "before": "射手", + "after": "摩羯" + } + ] + }, + "D6": { + "at": "1997-08-08T04:59:43", + "before": "射手", + "after": "摩羯", + "count": 3, + "lines": [ + { + "at": "1997-08-08T04:35:08", + "before": "天蝎", + "after": "射手" + }, + { + "at": "1997-08-08T04:59:43", + "before": "射手", + "after": "摩羯" + }, + { + "at": "1997-08-08T05:24:22", + "before": "摩羯", + "after": "水瓶" + } + ] + }, + "D8": { + "at": "1997-08-08T04:59:43", + "before": "巨蟹", + "after": "狮子", + "count": 3, + "lines": [ + { + "at": "1997-08-08T04:41:16", + "before": "双子", + "after": "巨蟹" + }, + { + "at": "1997-08-08T04:59:43", + "before": "巨蟹", + "after": "狮子" + }, + { + "at": "1997-08-08T05:18:12", + "before": "狮子", + "after": "处女" + } + ] + }, + "D2": { + "at": "1997-08-08T04:59:43", + "before": "巨蟹", + "after": "狮子", + "count": 1, + "lines": [ + { + "at": "1997-08-08T04:59:43", + "before": "巨蟹", + "after": "狮子" + } + ] } } }, - "both_versions": [] + "remaining_lines": [ + { + "at": "1997-08-08T04:30:14", + "charts": [ + "D10" + ] + }, + { + "at": "1997-08-08T04:35:08", + "charts": [ + "D9", + "D6" + ] + }, + { + "at": "1997-08-08T04:41:16", + "charts": [ + "D8" + ] + }, + { + "at": "1997-08-08T04:44:57", + "charts": [ + "D10" + ] + }, + { + "at": "1997-08-08T04:51:30", + "charts": [ + "D9" + ] + }, + { + "at": "1997-08-08T04:59:43", + "charts": [ + "D10", + "D2", + "D6", + "D8" + ] + }, + { + "at": "1997-08-08T05:07:55", + "charts": [ + "D9" + ] + }, + { + "at": "1997-08-08T05:14:30", + "charts": [ + "D10" + ] + }, + { + "at": "1997-08-08T05:18:12", + "charts": [ + "D8" + ] + }, + { + "at": "1997-08-08T05:24:22", + "charts": [ + "D9", + "D6" + ] + }, + { + "at": "1997-08-08T05:29:18", + "charts": [ + "D10" + ] + } + ], + "scenarios": [ + { + "segment": { + "start_at": "1997-08-08T04:44:57", + "end_at": "1997-08-08T04:51:29" + }, + "saved_at": "1997-08-08T04:50", + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "天秤", + "decided_by": null + }, + { + "chart": "D10", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D2", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D6", + "sign": "射手", + "decided_by": null + }, + { + "chart": "D8", + "sign": "巨蟹", + "decided_by": null + } + ], + "is_primary": false + }, + { + "segment": { + "start_at": "1997-08-08T04:51:30", + "end_at": "1997-08-08T04:59:42" + }, + "saved_at": "1997-08-08T04:58", + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "天蝎", + "decided_by": null + }, + { + "chart": "D10", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D2", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D6", + "sign": "射手", + "decided_by": null + }, + { + "chart": "D8", + "sign": "巨蟹", + "decided_by": null + } + ], + "is_primary": false + }, + { + "segment": { + "start_at": "1997-08-08T04:59:43", + "end_at": "1997-08-08T05:07:54" + }, + "saved_at": "1997-08-08T05:00", + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "天蝎", + "decided_by": null + }, + { + "chart": "D10", + "sign": "狮子", + "decided_by": null + }, + { + "chart": "D2", + "sign": "狮子", + "decided_by": null + }, + { + "chart": "D6", + "sign": "摩羯", + "decided_by": null + }, + { + "chart": "D8", + "sign": "狮子", + "decided_by": null + } + ], + "is_primary": true + }, + { + "segment": { + "start_at": "1997-08-08T05:07:55", + "end_at": "1997-08-08T05:14:29" + }, + "saved_at": "1997-08-08T05:09", + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "射手", + "decided_by": null + }, + { + "chart": "D10", + "sign": "狮子", + "decided_by": null + }, + { + "chart": "D2", + "sign": "狮子", + "decided_by": null + }, + { + "chart": "D6", + "sign": "摩羯", + "decided_by": null + }, + { + "chart": "D8", + "sign": "狮子", + "decided_by": null + } + ], + "is_primary": false + } + ], + "scenarios_omitted": 8, + "both_versions": [], + "chosen_side": "none", + "other_saved_at": null }, "next": { "at": "1997-08-08T04:59:43", @@ -796,35 +1216,311 @@ ], "line_summary": { "nearest_at": "1997-08-08T04:51:30", + "line_count": 5, "charts": { - "D9": { - "at": "1997-08-08T04:51:30", - "count": 2, - "before": "天秤", - "after": "天蝎" - }, "D10": { "at": "1997-08-08T04:44:57", + "before": "双子", + "after": "巨蟹", "count": 2, - "before": "双子", - "after": "巨蟹" + "lines": [ + { + "at": "1997-08-08T04:30:14", + "before": "金牛", + "after": "双子" + }, + { + "at": "1997-08-08T04:44:57", + "before": "双子", + "after": "巨蟹" + } + ] }, - "D8": { - "at": "1997-08-08T04:41:16", - "count": 1, - "before": "双子", - "after": "巨蟹" + "D9": { + "at": "1997-08-08T04:51:30", + "before": "天秤", + "after": "天蝎", + "count": 2, + "lines": [ + { + "at": "1997-08-08T04:35:08", + "before": "处女", + "after": "天秤" + }, + { + "at": "1997-08-08T04:51:30", + "before": "天秤", + "after": "天蝎" + } + ] }, "D6": { "at": "1997-08-08T04:35:08", - "count": 1, "before": "天蝎", - "after": "射手" + "after": "射手", + "count": 1, + "lines": [ + { + "at": "1997-08-08T04:35:08", + "before": "天蝎", + "after": "射手" + } + ] + }, + "D8": { + "at": "1997-08-08T04:41:16", + "before": "双子", + "after": "巨蟹", + "count": 1, + "lines": [ + { + "at": "1997-08-08T04:41:16", + "before": "双子", + "after": "巨蟹" + } + ] } } }, + "remaining_lines": [ + { + "at": "1997-08-08T04:30:14", + "charts": [ + "D10" + ] + }, + { + "at": "1997-08-08T04:35:08", + "charts": [ + "D9", + "D6" + ] + }, + { + "at": "1997-08-08T04:41:16", + "charts": [ + "D8" + ] + }, + { + "at": "1997-08-08T04:44:57", + "charts": [ + "D10" + ] + }, + { + "at": "1997-08-08T04:51:30", + "charts": [ + "D9" + ] + } + ], + "scenarios": [ + { + "segment": { + "start_at": "1997-08-08T04:35:08", + "end_at": "1997-08-08T04:41:15" + }, + "saved_at": "1997-08-08T04:40", + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "天秤", + "decided_by": null + }, + { + "chart": "D10", + "sign": "双子", + "decided_by": null + }, + { + "chart": "D2", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D6", + "sign": "射手", + "decided_by": null + }, + { + "chart": "D8", + "sign": "双子", + "decided_by": null + } + ], + "is_primary": false + }, + { + "segment": { + "start_at": "1997-08-08T04:41:16", + "end_at": "1997-08-08T04:44:56" + }, + "saved_at": "1997-08-08T04:43", + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "天秤", + "decided_by": null + }, + { + "chart": "D10", + "sign": "双子", + "decided_by": null + }, + { + "chart": "D2", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D6", + "sign": "射手", + "decided_by": null + }, + { + "chart": "D8", + "sign": "巨蟹", + "decided_by": null + } + ], + "is_primary": false + }, + { + "segment": { + "start_at": "1997-08-08T04:44:57", + "end_at": "1997-08-08T04:51:29" + }, + "saved_at": "1997-08-08T04:50", + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "天秤", + "decided_by": null + }, + { + "chart": "D10", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D2", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D6", + "sign": "射手", + "decided_by": null + }, + { + "chart": "D8", + "sign": "巨蟹", + "decided_by": null + } + ], + "is_primary": false + }, + { + "segment": { + "start_at": "1997-08-08T04:51:30", + "end_at": "1997-08-08T04:59:42" + }, + "saved_at": "1997-08-08T04:58", + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "天蝎", + "decided_by": null + }, + { + "chart": "D10", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D2", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D6", + "sign": "射手", + "decided_by": null + }, + { + "chart": "D8", + "sign": "巨蟹", + "decided_by": null + } + ], + "is_primary": true + } + ], + "scenarios_omitted": 2, "both_versions": [], - "chosen_side": "before" + "comparison_scenario": { + "segment": { + "start_at": "1997-08-08T04:59:43", + "end_at": "1997-08-08T05:07:54" + }, + "saved_at": "1997-08-08T05:00", + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "天蝎", + "decided_by": null + }, + { + "chart": "D10", + "sign": "狮子", + "decided_by": null + }, + { + "chart": "D2", + "sign": "狮子", + "decided_by": null + }, + { + "chart": "D6", + "sign": "摩羯", + "decided_by": null + }, + { + "chart": "D8", + "sign": "狮子", + "decided_by": null + } + ], + "is_primary": false + }, + "chosen_side": "none", + "other_saved_at": null }, "next": { "at": "1997-08-08T04:51:30", @@ -953,35 +1649,311 @@ ], "line_summary": { "nearest_at": "1997-08-08T05:07:55", + "line_count": 5, "charts": { "D9": { "at": "1997-08-08T05:07:55", - "count": 2, "before": "天蝎", - "after": "射手" + "after": "射手", + "count": 2, + "lines": [ + { + "at": "1997-08-08T05:07:55", + "before": "天蝎", + "after": "射手" + }, + { + "at": "1997-08-08T05:24:22", + "before": "射手", + "after": "摩羯" + } + ] }, "D10": { "at": "1997-08-08T05:14:30", - "count": 2, "before": "狮子", - "after": "处女" + "after": "处女", + "count": 2, + "lines": [ + { + "at": "1997-08-08T05:14:30", + "before": "狮子", + "after": "处女" + }, + { + "at": "1997-08-08T05:29:18", + "before": "处女", + "after": "天秤" + } + ] }, "D8": { "at": "1997-08-08T05:18:12", - "count": 1, "before": "狮子", - "after": "处女" + "after": "处女", + "count": 1, + "lines": [ + { + "at": "1997-08-08T05:18:12", + "before": "狮子", + "after": "处女" + } + ] }, "D6": { "at": "1997-08-08T05:24:22", - "count": 1, "before": "摩羯", - "after": "水瓶" + "after": "水瓶", + "count": 1, + "lines": [ + { + "at": "1997-08-08T05:24:22", + "before": "摩羯", + "after": "水瓶" + } + ] } } }, + "remaining_lines": [ + { + "at": "1997-08-08T05:07:55", + "charts": [ + "D9" + ] + }, + { + "at": "1997-08-08T05:14:30", + "charts": [ + "D10" + ] + }, + { + "at": "1997-08-08T05:18:12", + "charts": [ + "D8" + ] + }, + { + "at": "1997-08-08T05:24:22", + "charts": [ + "D9", + "D6" + ] + }, + { + "at": "1997-08-08T05:29:18", + "charts": [ + "D10" + ] + } + ], + "scenarios": [ + { + "segment": { + "start_at": "1997-08-08T04:59:43", + "end_at": "1997-08-08T05:07:54" + }, + "saved_at": "1997-08-08T05:00", + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "天蝎", + "decided_by": null + }, + { + "chart": "D10", + "sign": "狮子", + "decided_by": null + }, + { + "chart": "D2", + "sign": "狮子", + "decided_by": null + }, + { + "chart": "D6", + "sign": "摩羯", + "decided_by": null + }, + { + "chart": "D8", + "sign": "狮子", + "decided_by": null + } + ], + "is_primary": true + }, + { + "segment": { + "start_at": "1997-08-08T05:07:55", + "end_at": "1997-08-08T05:14:29" + }, + "saved_at": "1997-08-08T05:09", + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "射手", + "decided_by": null + }, + { + "chart": "D10", + "sign": "狮子", + "decided_by": null + }, + { + "chart": "D2", + "sign": "狮子", + "decided_by": null + }, + { + "chart": "D6", + "sign": "摩羯", + "decided_by": null + }, + { + "chart": "D8", + "sign": "狮子", + "decided_by": null + } + ], + "is_primary": false + }, + { + "segment": { + "start_at": "1997-08-08T05:14:30", + "end_at": "1997-08-08T05:18:11" + }, + "saved_at": "1997-08-08T05:16", + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "射手", + "decided_by": null + }, + { + "chart": "D10", + "sign": "处女", + "decided_by": null + }, + { + "chart": "D2", + "sign": "狮子", + "decided_by": null + }, + { + "chart": "D6", + "sign": "摩羯", + "decided_by": null + }, + { + "chart": "D8", + "sign": "狮子", + "decided_by": null + } + ], + "is_primary": false + }, + { + "segment": { + "start_at": "1997-08-08T05:18:12", + "end_at": "1997-08-08T05:24:21" + }, + "saved_at": "1997-08-08T05:20", + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "射手", + "decided_by": null + }, + { + "chart": "D10", + "sign": "处女", + "decided_by": null + }, + { + "chart": "D2", + "sign": "狮子", + "decided_by": null + }, + { + "chart": "D6", + "sign": "摩羯", + "decided_by": null + }, + { + "chart": "D8", + "sign": "处女", + "decided_by": null + } + ], + "is_primary": false + } + ], + "scenarios_omitted": 2, "both_versions": [], - "chosen_side": "after" + "comparison_scenario": { + "segment": { + "start_at": "1997-08-08T04:51:30", + "end_at": "1997-08-08T04:59:42" + }, + "saved_at": "1997-08-08T04:58", + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "天蝎", + "decided_by": null + }, + { + "chart": "D10", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D2", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D6", + "sign": "射手", + "decided_by": null + }, + { + "chart": "D8", + "sign": "巨蟹", + "decided_by": null + } + ], + "is_primary": false + }, + "chosen_side": "none", + "other_saved_at": null }, "next": { "at": "1997-08-08T05:07:55", @@ -1115,9 +2087,94 @@ ], "line_summary": { "nearest_at": null, + "line_count": 0, "charts": {} }, + "remaining_lines": [], + "scenarios": [ + { + "segment": { + "start_at": "1997-08-08T04:51:30", + "end_at": "1997-08-08T04:59:42" + }, + "saved_at": "1997-08-08T04:58", + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "天蝎", + "decided_by": null + }, + { + "chart": "D10", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D2", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D6", + "sign": "射手", + "decided_by": null + }, + { + "chart": "D8", + "sign": "巨蟹", + "decided_by": null + } + ], + "is_primary": true + } + ], + "scenarios_omitted": 0, "both_versions": [], + "comparison_scenario": { + "segment": { + "start_at": "1997-08-08T04:44:57", + "end_at": "1997-08-08T04:51:29" + }, + "saved_at": "1997-08-08T04:50", + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "天秤", + "decided_by": null + }, + { + "chart": "D10", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D2", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D6", + "sign": "射手", + "decided_by": null + }, + { + "chart": "D8", + "sign": "巨蟹", + "decided_by": null + } + ], + "is_primary": false + }, "chosen_side": "after" } }, @@ -1173,47 +2230,369 @@ ], "line_summary": { "nearest_at": "1997-08-08T04:59:43", + "line_count": 11, "charts": { "D10": { "at": "1997-08-08T04:59:43", + "before": "巨蟹", + "after": "狮子", "count": 5, - "before": "巨蟹", - "after": "狮子" - }, - "D2": { - "at": "1997-08-08T04:59:43", - "count": 1, - "before": "巨蟹", - "after": "狮子" - }, - "D6": { - "at": "1997-08-08T04:59:43", - "count": 3, - "before": "射手", - "after": "摩羯" - }, - "D8": { - "at": "1997-08-08T04:59:43", - "count": 3, - "before": "巨蟹", - "after": "狮子" + "lines": [ + { + "at": "1997-08-08T04:30:14", + "before": "金牛", + "after": "双子" + }, + { + "at": "1997-08-08T04:44:57", + "before": "双子", + "after": "巨蟹" + }, + { + "at": "1997-08-08T04:59:43", + "before": "巨蟹", + "after": "狮子" + }, + { + "at": "1997-08-08T05:14:30", + "before": "狮子", + "after": "处女" + }, + { + "at": "1997-08-08T05:29:18", + "before": "处女", + "after": "天秤" + } + ] }, "D9": { "at": "1997-08-08T05:07:55", - "count": 4, "before": "天蝎", - "after": "射手" + "after": "射手", + "count": 4, + "lines": [ + { + "at": "1997-08-08T04:35:08", + "before": "处女", + "after": "天秤" + }, + { + "at": "1997-08-08T04:51:30", + "before": "天秤", + "after": "天蝎" + }, + { + "at": "1997-08-08T05:07:55", + "before": "天蝎", + "after": "射手" + }, + { + "at": "1997-08-08T05:24:22", + "before": "射手", + "after": "摩羯" + } + ] + }, + "D6": { + "at": "1997-08-08T04:59:43", + "before": "射手", + "after": "摩羯", + "count": 3, + "lines": [ + { + "at": "1997-08-08T04:35:08", + "before": "天蝎", + "after": "射手" + }, + { + "at": "1997-08-08T04:59:43", + "before": "射手", + "after": "摩羯" + }, + { + "at": "1997-08-08T05:24:22", + "before": "摩羯", + "after": "水瓶" + } + ] + }, + "D8": { + "at": "1997-08-08T04:59:43", + "before": "巨蟹", + "after": "狮子", + "count": 3, + "lines": [ + { + "at": "1997-08-08T04:41:16", + "before": "双子", + "after": "巨蟹" + }, + { + "at": "1997-08-08T04:59:43", + "before": "巨蟹", + "after": "狮子" + }, + { + "at": "1997-08-08T05:18:12", + "before": "狮子", + "after": "处女" + } + ] + }, + "D2": { + "at": "1997-08-08T04:59:43", + "before": "巨蟹", + "after": "狮子", + "count": 1, + "lines": [ + { + "at": "1997-08-08T04:59:43", + "before": "巨蟹", + "after": "狮子" + } + ] } } }, - "both_versions": [ - "career", - "money", - "pressure", - "change" + "remaining_lines": [ + { + "at": "1997-08-08T04:30:14", + "charts": [ + "D10" + ] + }, + { + "at": "1997-08-08T04:35:08", + "charts": [ + "D9", + "D6" + ] + }, + { + "at": "1997-08-08T04:41:16", + "charts": [ + "D8" + ] + }, + { + "at": "1997-08-08T04:44:57", + "charts": [ + "D10" + ] + }, + { + "at": "1997-08-08T04:51:30", + "charts": [ + "D9" + ] + }, + { + "at": "1997-08-08T04:59:43", + "charts": [ + "D10", + "D2", + "D6", + "D8" + ] + }, + { + "at": "1997-08-08T05:07:55", + "charts": [ + "D9" + ] + }, + { + "at": "1997-08-08T05:14:30", + "charts": [ + "D10" + ] + }, + { + "at": "1997-08-08T05:18:12", + "charts": [ + "D8" + ] + }, + { + "at": "1997-08-08T05:24:22", + "charts": [ + "D9", + "D6" + ] + }, + { + "at": "1997-08-08T05:29:18", + "charts": [ + "D10" + ] + } ], - "chosen_side": "after", - "other_saved_at": "1997-08-08T04:58" + "scenarios": [ + { + "segment": { + "start_at": "1997-08-08T04:44:57", + "end_at": "1997-08-08T04:51:29" + }, + "saved_at": "1997-08-08T04:50", + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "天秤", + "decided_by": null + }, + { + "chart": "D10", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D2", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D6", + "sign": "射手", + "decided_by": null + }, + { + "chart": "D8", + "sign": "巨蟹", + "decided_by": null + } + ], + "is_primary": false + }, + { + "segment": { + "start_at": "1997-08-08T04:51:30", + "end_at": "1997-08-08T04:59:42" + }, + "saved_at": "1997-08-08T04:58", + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "天蝎", + "decided_by": null + }, + { + "chart": "D10", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D2", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D6", + "sign": "射手", + "decided_by": null + }, + { + "chart": "D8", + "sign": "巨蟹", + "decided_by": null + } + ], + "is_primary": false + }, + { + "segment": { + "start_at": "1997-08-08T04:59:43", + "end_at": "1997-08-08T05:07:54" + }, + "saved_at": "1997-08-08T05:00", + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "天蝎", + "decided_by": null + }, + { + "chart": "D10", + "sign": "狮子", + "decided_by": null + }, + { + "chart": "D2", + "sign": "狮子", + "decided_by": null + }, + { + "chart": "D6", + "sign": "摩羯", + "decided_by": null + }, + { + "chart": "D8", + "sign": "狮子", + "decided_by": null + } + ], + "is_primary": true + }, + { + "segment": { + "start_at": "1997-08-08T05:07:55", + "end_at": "1997-08-08T05:14:29" + }, + "saved_at": "1997-08-08T05:09", + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "射手", + "decided_by": null + }, + { + "chart": "D10", + "sign": "狮子", + "decided_by": null + }, + { + "chart": "D2", + "sign": "狮子", + "decided_by": null + }, + { + "chart": "D6", + "sign": "摩羯", + "decided_by": null + }, + { + "chart": "D8", + "sign": "狮子", + "decided_by": null + } + ], + "is_primary": false + } + ], + "scenarios_omitted": 8, + "both_versions": [], + "chosen_side": "none", + "other_saved_at": null } }, "minuteDistance": { @@ -1387,5 +2766,466 @@ "resolved": [], "stop_reason": "stopped" } + }, + "three": { + "decision": { + "saved_at": "1997-08-08T05:00", + "segment": { + "start_at": "1997-08-08T04:50:00", + "end_at": "1997-08-08T05:05:00" + }, + "choices": [], + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "天蝎", + "decided_by": null, + "flips_at": "1997-08-08T04:51:30" + }, + { + "chart": "D10", + "sign": "狮子", + "decided_by": null, + "flips_at": "1997-08-08T04:59:43" + }, + { + "chart": "D2", + "sign": "狮子", + "decided_by": null, + "flips_at": "1997-08-08T04:59:43" + }, + { + "chart": "D6", + "sign": "摩羯", + "decided_by": null, + "flips_at": "1997-08-08T04:59:43" + }, + { + "chart": "D8", + "sign": "狮子", + "decided_by": null, + "flips_at": "1997-08-08T04:59:43" + } + ], + "line_summary": { + "nearest_at": "1997-08-08T04:59:43", + "line_count": 2, + "charts": { + "D9": { + "at": "1997-08-08T04:51:30", + "before": "天秤", + "after": "天蝎", + "count": 1, + "lines": [ + { + "at": "1997-08-08T04:51:30", + "before": "天秤", + "after": "天蝎" + } + ] + }, + "D10": { + "at": "1997-08-08T04:59:43", + "before": "巨蟹", + "after": "狮子", + "count": 1, + "lines": [ + { + "at": "1997-08-08T04:59:43", + "before": "巨蟹", + "after": "狮子" + } + ] + }, + "D2": { + "at": "1997-08-08T04:59:43", + "before": "巨蟹", + "after": "狮子", + "count": 1, + "lines": [ + { + "at": "1997-08-08T04:59:43", + "before": "巨蟹", + "after": "狮子" + } + ] + }, + "D6": { + "at": "1997-08-08T04:59:43", + "before": "射手", + "after": "摩羯", + "count": 1, + "lines": [ + { + "at": "1997-08-08T04:59:43", + "before": "射手", + "after": "摩羯" + } + ] + }, + "D8": { + "at": "1997-08-08T04:59:43", + "before": "巨蟹", + "after": "狮子", + "count": 1, + "lines": [ + { + "at": "1997-08-08T04:59:43", + "before": "巨蟹", + "after": "狮子" + } + ] + } + } + }, + "remaining_lines": [ + { + "at": "1997-08-08T04:51:30", + "charts": [ + "D9" + ] + }, + { + "at": "1997-08-08T04:59:43", + "charts": [ + "D10", + "D2", + "D6", + "D8" + ] + } + ], + "scenarios": [ + { + "segment": { + "start_at": "1997-08-08T04:50:00", + "end_at": "1997-08-08T04:51:29" + }, + "saved_at": "1997-08-08T04:50", + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "天秤", + "decided_by": null + }, + { + "chart": "D10", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D2", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D6", + "sign": "射手", + "decided_by": null + }, + { + "chart": "D8", + "sign": "巨蟹", + "decided_by": null + } + ], + "is_primary": false + }, + { + "segment": { + "start_at": "1997-08-08T04:51:30", + "end_at": "1997-08-08T04:59:42" + }, + "saved_at": "1997-08-08T04:58", + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "天蝎", + "decided_by": null + }, + { + "chart": "D10", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D2", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D6", + "sign": "射手", + "decided_by": null + }, + { + "chart": "D8", + "sign": "巨蟹", + "decided_by": null + } + ], + "is_primary": false + }, + { + "segment": { + "start_at": "1997-08-08T04:59:43", + "end_at": "1997-08-08T05:05:00" + }, + "saved_at": "1997-08-08T05:00", + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "天蝎", + "decided_by": null + }, + { + "chart": "D10", + "sign": "狮子", + "decided_by": null + }, + { + "chart": "D2", + "sign": "狮子", + "decided_by": null + }, + { + "chart": "D6", + "sign": "摩羯", + "decided_by": null + }, + { + "chart": "D8", + "sign": "狮子", + "decided_by": null + } + ], + "is_primary": true + } + ], + "scenarios_omitted": 0, + "both_versions": [], + "chosen_side": "none", + "other_saved_at": null + }, + "next": { + "at": "1997-08-08T04:59:43", + "degree": 15.0, + "charts": [ + "D10", + "D2", + "D6", + "D8" + ], + "flips": { + "D10": { + "before": "巨蟹", + "after": "狮子" + }, + "D2": { + "before": "巨蟹", + "after": "狮子" + }, + "D6": { + "before": "射手", + "after": "摩羯" + }, + "D8": { + "before": "巨蟹", + "after": "狮子" + } + }, + "comparisons": [ + { + "chart": "D10", + "label": "事业", + "chart_label": "事业盘 D10", + "before": { + "chart": "D10", + "domain": "career", + "label": "事业", + "chart_label": "事业盘 D10", + "ascendant": "巨蟹", + "ascendant_index": 3, + "points": [ + { + "kind": "occupant", + "fact": "金星在事业位", + "meaning": "审美、设计和人缘,讲究舒适" + }, + { + "kind": "lord", + "fact": "管事业的星(火星)落在第 5 宫", + "meaning": "靠专长、兴趣和脑力吃饭,偏技术、研究、创作或教育" + }, + { + "kind": "lord", + "fact": "代表你自己的星(月亮)落在第 3 宫", + "meaning": "主动、爱表达,靠自己闯" + } + ] + }, + "after": { + "chart": "D10", + "domain": "career", + "label": "事业", + "chart_label": "事业盘 D10", + "ascendant": "狮子", + "ascendant_index": 4, + "points": [ + { + "kind": "occupant", + "fact": "木星在事业位", + "meaning": "大平台和贵人,重学识、有分寸" + }, + { + "kind": "occupant", + "fact": "罗睺在事业位", + "meaning": "野心大、不走寻常路,和外来或新兴的东西有缘" + }, + { + "kind": "occupant", + "fact": "土星在命位", + "meaning": "慢热、担责任、能坚持,早年辛苦、后劲足" + }, + { + "kind": "lord", + "fact": "管事业的星(金星)落在第 9 宫", + "meaning": "遇到导师、去远方、读更高的学历会推动事业" + }, + { + "kind": "lord", + "fact": "代表你自己的星(太阳)落在第 3 宫", + "meaning": "主动、爱表达,靠自己闯" + } + ] + } + }, + { + "chart": "D2", + "label": "钱财", + "chart_label": "钱财盘 D2", + "before": { + "chart": "D2", + "domain": "money", + "label": "钱财", + "chart_label": "钱财盘 D2", + "ascendant": "巨蟹", + "ascendant_index": 3, + "points": [ + { + "kind": "hora", + "fact": "上升落在月亮这一半。月亮、水星、金星、罗睺、计都在你这一半。", + "meaning": "钱更多来自和人打交道、做买卖、做内容或和审美有关的东西,来得灵活、零散" + } + ] + }, + "after": { + "chart": "D2", + "domain": "money", + "label": "钱财", + "chart_label": "钱财盘 D2", + "ascendant": "狮子", + "ascendant_index": 4, + "points": [ + { + "kind": "hora", + "fact": "上升落在太阳这一半。太阳、火星、木星、土星在你这一半。", + "meaning": "钱更多来自自己出头、拿职位、担责任,在体系里往上走,来得慢但稳" + } + ] + } + }, + { + "chart": "D6", + "label": "日常遇到压力时", + "chart_label": "分盘 D6", + "before": { + "chart": "D6", + "domain": "pressure", + "label": "日常遇到压力时", + "chart_label": "分盘 D6", + "ascendant": "射手", + "ascendant_index": 8, + "points": [ + { + "kind": "ascendant", + "fact": "上升落在射手", + "meaning": "先处理眼前最紧的一件事" + } + ] + }, + "after": { + "chart": "D6", + "domain": "pressure", + "label": "日常遇到压力时", + "chart_label": "分盘 D6", + "ascendant": "摩羯", + "ascendant_index": 9, + "points": [ + { + "kind": "ascendant", + "fact": "上升落在摩羯", + "meaning": "先维持原有节奏,把任务逐件做完" + } + ] + } + }, + { + "chart": "D8", + "label": "遇到意外变化时", + "chart_label": "分盘 D8", + "before": { + "chart": "D8", + "domain": "change", + "label": "遇到意外变化时", + "chart_label": "分盘 D8", + "ascendant": "巨蟹", + "ascendant_index": 3, + "points": [ + { + "kind": "ascendant", + "fact": "上升落在巨蟹", + "meaning": "先找熟悉的人商量下一步" + } + ] + }, + "after": { + "chart": "D8", + "domain": "change", + "label": "遇到意外变化时", + "chart_label": "分盘 D8", + "ascendant": "狮子", + "ascendant_index": 4, + "points": [ + { + "kind": "ascendant", + "fact": "上升落在狮子", + "meaning": "先动手试一个新办法" + } + ] + } + } + ] + } } } diff --git a/scripts/chart_choice/service.py b/scripts/chart_choice/service.py index dbb690731..0aa48d547 100644 --- a/scripts/chart_choice/service.py +++ b/scripts/chart_choice/service.py @@ -162,14 +162,18 @@ def _line_view(line: Line, order: tuple[str, ...]) -> dict: def _line_summary(lines: list[Line], reference: datetime) -> dict: - nearest = sorted(lines, key=lambda line: (abs(line.at - reference), line.at)) - charts: dict[str, dict] = {} - for line in nearest: + ordered = sorted((line for line in lines if line.flips.keys() & set(KEY_CHARTS)), key=lambda line: line.at) + nearest = min(ordered, key=lambda line: (abs(line.at - reference), line.at), default=None) + chart_lines: dict[str, list[dict]] = {} + for line in ordered: view = _line_view(line, KEY_CHARTS) for chart, signs in view["flips"].items(): - row = charts.setdefault(chart, {"at": view["at"], "count": 0, **signs}) - row["count"] += 1 - return {"nearest_at": _at_s(nearest[0].at) if nearest else None, "charts": charts} + chart_lines.setdefault(chart, []).append({"at": view["at"], **signs}) + charts: dict[str, dict] = {} + for chart, flips in chart_lines.items(): + closest = min(flips, key=lambda flip: abs(_input_line(flip["at"]) - reference)) + charts[chart] = {**closest, "count": len(flips), "lines": flips} + return {"nearest_at": _at_s(nearest.at) if nearest else None, "line_count": len(ordered), "charts": charts} def _comparisons(req: ChartRequest, before_at: datetime, after_at: datetime, charts: list[str]) -> list[dict]: @@ -645,6 +649,30 @@ def _self_choice_lines(req: ChartRequest, start: datetime, end: datetime) -> lis return sorted(by_time.values(), key=lambda line: line.at) +def _self_choice_scenarios( + req: ChartRequest, segment: Segment, lines: list[Line], reported: datetime, original: Segment, +) -> tuple[list[dict], int]: + starts = [segment[0], *(line.at for line in lines)] + ends = [*(line.at - ONE_SECOND for line in lines), segment[1]] + pieces = list(zip(starts, ends)) + + def distance(index: int) -> tuple[timedelta, int]: + lo, hi = pieces[index] + return max(lo - reported, reported - hi, timedelta()), index + + nearest = sorted(range(len(pieces)), key=distance)[:4] + primary = nearest[0] + scenarios = [] + for index in sorted(nearest): + piece = pieces[index] + saved = _self_choice_at(piece, reported, original) + scenarios.append({ + "segment": _segment(*piece), "saved_at": _saved_at(saved), + "key_charts": _key_chart_rows(req, saved, [], []), "is_primary": index == primary, + }) + return scenarios, len(pieces) - len(scenarios) + + def _self_choice( body: dict, req: ChartRequest, segment: Segment, reported: datetime, *, deciding: bool, ) -> dict: @@ -658,7 +686,7 @@ def _self_choice( lines = all_lines next_line = nearest_line(lines, reported) - unsure = None + comparison_segment = None for entry in choices: if not isinstance(entry, dict) or set(entry) != {"line_at", "side"}: raise ChartChoiceInputError("each choice needs only line_at and side") @@ -667,23 +695,45 @@ def _self_choice( or _input_line(entry["line_at"]) != next_line.at): raise ChartChoiceInputError("self-choice line is not the next available line") if side == "unsure": - unsure, next_line = next_line, None + next_line = None else: + opposing = "after" if side == "before" else "before" + lo, hi = _side(segment, next_line, opposing) + opposing_lines = [line.at for line in lines if lo < line.at <= hi] + if opposing_lines: + if opposing == "before": + lo = opposing_lines[-1] + else: + hi = opposing_lines[0] - ONE_SECOND + comparison_segment = (lo, hi) segment = _side(segment, next_line, side) lines = [line for line in lines if segment[0] < line.at <= segment[1]] next_line = nearest_line(lines, reported) - saved = _self_choice_at(segment, reported, original) - resolved = {"saved_at": _saved_at(saved), "segment": _segment(*segment), "choices": choices, - "key_charts": _key_chart_rows(req, saved, lines, []), - "line_summary": _line_summary(lines, reported), "both_versions": []} - if unsure is not None: - chosen = "before" if saved < unsure.at else "after" - preceding = max((line.at for line in lines if line.at < unsure.at), default=segment[0]) - following = min((line.at for line in lines if line.at > unsure.at), default=segment[1] + ONE_SECOND) - other = (unsure.at, following - ONE_SECOND) if chosen == "before" else (preceding, unsure.at - ONE_SECOND) - resolved.update(chosen_side=chosen, other_saved_at=_saved_at(_self_choice_at(other, reported, original)), - both_versions=[DOMAIN[key]["key"] for key in KEY_CHARTS if key in unsure.flips]) + scenarios, omitted = _self_choice_scenarios(req, segment, lines, reported, original) + primary = next(item for item in scenarios if item["is_primary"]) + saved = datetime.fromisoformat(primary["saved_at"]) + resolved = { + "saved_at": primary["saved_at"], "segment": _segment(*segment), "choices": choices, + "key_charts": _key_chart_rows(req, saved, lines, []), "line_summary": _line_summary(lines, reported), + "remaining_lines": [{"at": _at_s(line.at), "charts": [key for key in KEY_CHARTS if key in line.flips]} + for line in lines], + "scenarios": scenarios, "scenarios_omitted": omitted, "both_versions": [], + } + if comparison_segment: + comparison_at = _self_choice_at(comparison_segment, reported, original) + resolved["comparison_scenario"] = { + "segment": _segment(*comparison_segment), "saved_at": _saved_at(comparison_at), + "key_charts": _key_chart_rows(req, comparison_at, [], []), "is_primary": False, + } + if len(lines) == 1: + line = lines[0] + other = next(item for item in scenarios if not item["is_primary"]) + resolved.update(chosen_side="before" if saved < line.at else "after", + other_saved_at=other["saved_at"], + both_versions=[DOMAIN[key]["key"] for key in KEY_CHARTS if key in line.flips]) + elif lines: + resolved.update(chosen_side="none", other_saved_at=None) elif choices: resolved["chosen_side"] = choices[-1]["side"] diff --git a/tests/test_chart_choice.py b/tests/test_chart_choice.py index a7ca32e05..0195177ab 100644 --- a/tests/test_chart_choice.py +++ b/tests/test_chart_choice.py @@ -27,7 +27,7 @@ from scripts.chart_choice.boundaries import ( # noqa: E402 from scripts.chart_choice import adaptive, astrologer, chart_questions, interview # noqa: E402 from scripts.chart_choice.decision import decide, decide_with_evidence, reported_is_neutral # noqa: E402 from scripts.chart_choice.readings import SIGN_CN # noqa: E402 -from scripts.chart_choice.service import _self_choice_at, build_packet, decide_packet # noqa: E402 +from scripts.chart_choice.service import _self_choice_at, _self_choice_scenarios, build_packet, decide_packet # noqa: E402 # Fictional reference input (not a user record): mid-latitude north China, early morning. BODY = { @@ -759,18 +759,47 @@ def test_self_choice_replays_real_lines_without_scoring(monkeypatch): assert "next" not in unsure assert unsure["decision"]["segment"] == initial["decision"]["segment"] assert unsure["decision"]["saved_at"] == BODY["reported_at"] - assert unsure["decision"]["chosen_side"] == "after" - assert unsure["decision"]["other_saved_at"].endswith("04:58") - other_saved = datetime.fromisoformat(unsure["decision"]["other_saved_at"]) + assert unsure["decision"]["chosen_side"] == "none" + assert unsure["decision"]["other_saved_at"] is None + assert unsure["decision"]["both_versions"] == [] + assert len(unsure["decision"]["scenarios"]) == 4 + assert unsure["decision"]["scenarios_omitted"] > 0 + primary = next(item for item in unsure["decision"]["scenarios"] if item["is_primary"]) + assert primary["saved_at"] == BODY["reported_at"] + alternative = next(item for item in unsure["decision"]["scenarios"] + if item["segment"]["end_at"].endswith("04:59:42")) + other_saved = datetime.fromisoformat(alternative["saved_at"]) assert datetime.fromisoformat(first["at"]) - other_saved >= timedelta(seconds=60) assert signature(ascendant_longitude(REQ, other_saved), charts) == expected_signs - assert unsure["decision"]["both_versions"] == ["career", "money", "pressure", "change"] + assert len(unsure["decision"]["remaining_lines"]) == initial["decision"]["line_summary"]["line_count"] + assert len(initial["decision"]["line_summary"]["charts"]["D10"]["lines"]) == 5 with pytest.raises(ChartChoiceInputError, match="next available"): decide_packet({**body, "choices": [pick(before["next"], "after")]}) with pytest.raises(ChartChoiceInputError, match="next available"): decide_packet({**body, "choices": [pick(first, "unsure"), pick(before["next"], "after")]}) +@pytest.mark.parametrize(("line_count", "expected_count", "omitted"), [(0, 1, 0), (1, 2, 0), (2, 3, 0), (5, 4, 2)]) +def test_self_choice_partitions_every_remaining_line_and_caps_nearest(line_count, expected_count, omitted): + lo = datetime(1997, 8, 8, 4, 30) + hi = lo + timedelta(minutes=40) + reported = lo + timedelta(minutes=17) + lines = [Line(lo + timedelta(minutes=5 * i, seconds=30), 0, {"D10": (1, 2)}) + for i in range(1, line_count + 1)] + scenarios, omitted_count = _self_choice_scenarios(REQ, (lo, hi), lines, reported, (lo, hi)) + assert (len(scenarios), omitted_count) == (expected_count, omitted) + assert sum(item["is_primary"] for item in scenarios) == 1 + assert next(item["saved_at"] for item in scenarios if item["is_primary"]) == "1997-08-08T04:47" + assert [item["segment"]["start_at"] for item in scenarios] == sorted(item["segment"]["start_at"] for item in scenarios) + for item in scenarios: + start, end, saved = (datetime.fromisoformat(value) for value in + (item["segment"]["start_at"], item["segment"]["end_at"], item["saved_at"])) + assert start <= saved <= end + assert saved == _self_choice_at((start, end), reported, (lo, hi)) + assert len(item["key_charts"]) == 6 + assert not any(start < line.at <= end for line in lines) + + def test_self_choice_preserves_boundary_second_when_no_whole_minute_fits(): body = {**BODY, "start_at": "1997-08-08T04:59", "end_at": "1997-08-08T05:00", "self_choice": True}