mirror of
https://github.com/bitbaum/skif.git
synced 2026-12-04 20:37:04 +01:00
feat(plan): "Did it help?" under every step, and the next plan learns from it (#65)
Each step in "Your steps" can be marked "I did this" or "Not for me", then answered: did it help? Yes, a little, no. Answers are kept per person and step (step_outcomes), so the same step in two plans is one experience, and "Change" takes one back. The next assessment reads them: a step that helped counts like something the person already does (the worry reads as covered), and one that did not help or was not wanted is set aside, listed as such, with the next option recommended and a line saying why. With nothing said, a plan is exactly as before (tested). One form per step with a button per answer: works without JavaScript and the choices sit as equal cells. The roadmap item moves to the changelog. Claude-Session: https://claude.ai/code/session_01TTH5cy8bKmEqzdTyAsbbT8 Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
1 parent
8b3862ca12
commit
efa6c38ee4
16 files changed
+2352
-20
No files matched your search
@@ -0,0 +1,8 @@
|
||||
CREATE TABLE "step_outcomes" (
|
||||
"sub" text NOT NULL,
|
||||
"intervention_key" text NOT NULL,
|
||||
"status" text NOT NULL,
|
||||
"helped" text,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
CONSTRAINT "step_outcomes_sub_intervention_key_pk" PRIMARY KEY("sub","intervention_key")
|
||||
);
|
||||
File diff suppressed because it is too large.
Load diff
@@ -113,6 +113,13 @@
|
||||
"when": 1792660409041,
|
||||
"tag": "0015_inbound_mail",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 16,
|
||||
"version": "7",
|
||||
"when": 1792685665478,
|
||||
"tag": "0016_step_outcomes",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -11,7 +11,9 @@ import { idInput } from "@/domain/inputs";
|
||||
import { readPlan } from "@/domain/plan-versions";
|
||||
import { describeLeans } from "@/domain/preference-fit";
|
||||
import { getAssessment } from "@/server/assessments";
|
||||
import { outcomesOf } from "@/server/step-outcomes";
|
||||
import { requireViewer } from "@/server/viewer";
|
||||
import { stepOutcomeAction } from "../actions";
|
||||
|
||||
export const metadata: Metadata = { title: "Safety Plan" };
|
||||
|
||||
@@ -24,6 +26,7 @@ export default async function AssessmentPage({ params }: { params: Promise<{ id:
|
||||
const assessment = await getAssessment(getDb(), viewer.sub, id.data);
|
||||
if (!assessment) notFound();
|
||||
const plan = readPlan(assessment.plan);
|
||||
const outcomes = await outcomesOf(getDb(), viewer.sub);
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -32,7 +35,7 @@ export default async function AssessmentPage({ params }: { params: Promise<{ id:
|
||||
lead={`${environmentTypeLabel(assessment.environment.type)} · ${formatWhen(assessment.createdAt)}`}
|
||||
/>
|
||||
<PlanSummary plan={plan} />
|
||||
<PlanSteps plan={plan} />
|
||||
<PlanSteps plan={plan} outcomes={outcomes} answer={stepOutcomeAction} />
|
||||
{/* What the plan rests on: there to check, not to act on, so folded. */}
|
||||
<FoldCard
|
||||
title="What this plan is based on"
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import type { ActionState } from "@/components/action-form";
|
||||
import { findIntervention } from "@/config/interventions";
|
||||
import { getDb } from "@/db/client";
|
||||
import { assessmentInput, describeIssue, environmentInput, formFields } from "@/domain/inputs";
|
||||
import { createEnvironment, ensureLifeEnvironment } from "@/server/environments";
|
||||
import { createAssessment } from "@/server/assessments";
|
||||
import { setStepOutcome, type StepAnswer } from "@/server/step-outcomes";
|
||||
import { requireViewer } from "@/server/viewer";
|
||||
|
||||
export async function createAssessmentAction(_: ActionState, form: FormData): Promise<ActionState> {
|
||||
@@ -32,3 +35,22 @@ export async function assessLifeAction(): Promise<void> {
|
||||
const life = await ensureLifeEnvironment(getDb(), viewer.sub);
|
||||
redirect(`/assessments/new?place=${life.id}`);
|
||||
}
|
||||
|
||||
const ANSWERS: Record<string, StepAnswer> = {
|
||||
DONE: { status: "DONE" },
|
||||
NOT_FOR_ME: { status: "NOT_FOR_ME" },
|
||||
YES: { status: "DONE", helped: "YES" },
|
||||
SOMEWHAT: { status: "DONE", helped: "SOMEWHAT" },
|
||||
NO: { status: "DONE", helped: "NO" },
|
||||
UNDO: null,
|
||||
};
|
||||
|
||||
/** "I did this", "Not for me", "Did it help?" under a step of a Safety Plan. */
|
||||
export async function stepOutcomeAction(form: FormData): Promise<void> {
|
||||
const viewer = await requireViewer();
|
||||
const step = form.get("step");
|
||||
const answer = String(form.get("answer") ?? "");
|
||||
if (typeof step !== "string" || !(answer in ANSWERS) || !findIntervention(step)) return;
|
||||
await setStepOutcome(getDb(), viewer.sub, step, ANSWERS[answer]!);
|
||||
revalidatePath("/assessments", "layout");
|
||||
}
|
||||
@@ -15,6 +15,8 @@ import {
|
||||
} from "@/config/interventions";
|
||||
import { PRIORITY_LABELS } from "@/domain/findings";
|
||||
import { planSteps, planVerdict, type FindingPlan, type PlanVerdict, type SafetyPlan } from "@/domain/safety-plan";
|
||||
import type { StepOutcome } from "@/domain/step-outcomes";
|
||||
import { StepOutcomeControls } from "./step-outcome";
|
||||
import { Badge, Card } from "./ui";
|
||||
|
||||
export function InterventionCard({ id, why, emphasis = false }: { id: string; why?: string[]; emphasis?: boolean }) {
|
||||
@@ -159,6 +161,7 @@ export function FindingSection({ finding, shownAbove = false }: { finding: Findi
|
||||
</div>
|
||||
</details>
|
||||
)}
|
||||
<KeyList title="You said these didn't help or weren't for you" keys={finding.setAside ?? []} mark="·" />
|
||||
<KeyList title="Over your budget" keys={finding.overBudget} mark="·" folded />
|
||||
<KeyList
|
||||
title="Ruled out by your limits"
|
||||
@@ -246,8 +249,17 @@ export function FindingsByFamily({ plan, wholeLife }: { plan: SafetyPlan; wholeL
|
||||
}
|
||||
|
||||
/** The plan as a to-do list, before the detail: each step once, with the
|
||||
* worries it answers. Nothing here when there is nothing to do. */
|
||||
export function PlanSteps({ plan }: { plan: SafetyPlan }) {
|
||||
* worries it answers and, when `answer` is given, "Did it help?" under it.
|
||||
* Nothing here when there is nothing to do. */
|
||||
export function PlanSteps({
|
||||
plan,
|
||||
outcomes,
|
||||
answer,
|
||||
}: {
|
||||
plan: SafetyPlan;
|
||||
outcomes?: ReadonlyMap<string, StepOutcome>;
|
||||
answer?: (form: FormData) => Promise<void>;
|
||||
}) {
|
||||
const steps = planSteps(plan);
|
||||
if (steps.length === 0) return null;
|
||||
return (
|
||||
@@ -259,13 +271,14 @@ export function PlanSteps({ plan }: { plan: SafetyPlan }) {
|
||||
return (
|
||||
<li key={step.key} className="flex gap-3 text-sm">
|
||||
<span className="font-semibold text-muted">{n + 1}.</span>
|
||||
<span className="space-y-1">
|
||||
<div className="min-w-0 flex-1 space-y-1">
|
||||
<span className="block font-medium">{i.title}</span>
|
||||
<span className="flex flex-wrap gap-2">
|
||||
{needsPurchase(i.kind) ? <Badge>{costLabel(i.cost)}</Badge> : <Badge tone="accent">Nothing to buy</Badge>}
|
||||
</span>
|
||||
<span className="block text-muted">For: {step.concerns.map(concernLabel).join(" · ")}</span>
|
||||
</span>
|
||||
{answer && <StepOutcomeControls stepKey={step.key} outcome={outcomes?.get(step.key)} action={answer} />}
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { HELPED_LABELS, outcomeSentence, STEP_HELPED, type StepOutcome } from "@/domain/step-outcomes";
|
||||
import { buttonClass } from "./ui";
|
||||
|
||||
const cell = `${buttonClass.secondary} w-full`;
|
||||
|
||||
/**
|
||||
* Under one step of a Safety Plan: "I did this" / "Not for me", then "Did it
|
||||
* help?". One form, one button per answer, so it works without JavaScript and
|
||||
* the choices sit as equal cells. What is said here shapes the next plan.
|
||||
*/
|
||||
export function StepOutcomeControls({
|
||||
stepKey,
|
||||
outcome,
|
||||
action,
|
||||
}: {
|
||||
stepKey: string;
|
||||
outcome: StepOutcome | undefined;
|
||||
action: (form: FormData) => Promise<void>;
|
||||
}) {
|
||||
const sentence = outcomeSentence(outcome);
|
||||
const asking = outcome?.status === "DONE" && !outcome.helped;
|
||||
return (
|
||||
<form action={action} className="mt-2 space-y-2">
|
||||
<input type="hidden" name="step" value={stepKey} />
|
||||
{!outcome && (
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<button type="submit" name="answer" value="DONE" className={cell}>
|
||||
I did this
|
||||
</button>
|
||||
<button type="submit" name="answer" value="NOT_FOR_ME" className={cell}>
|
||||
Not for me
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{asking && (
|
||||
<fieldset className="space-y-2">
|
||||
<legend className="text-sm font-medium">Did it help?</legend>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
{STEP_HELPED.map((h) => (
|
||||
<button key={h} type="submit" name="answer" value={h} className={cell}>
|
||||
{HELPED_LABELS[h]}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</fieldset>
|
||||
)}
|
||||
{outcome && !asking && sentence && (
|
||||
<p className="flex flex-wrap items-center gap-x-3 text-sm text-muted">
|
||||
<span>{sentence}</span>
|
||||
<button type="submit" name="answer" value="UNDO" className={buttonClass.link}>
|
||||
Change
|
||||
</button>
|
||||
</p>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -27,15 +27,6 @@ export const PUBLIC_DEVELOPMENT: DevelopmentProfile = {
|
||||
"Next: named, vetted people you can book inside Skif, each shown with what they fix and what they cost you in privacy.",
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "“Did it help?” after every step",
|
||||
status: "Next",
|
||||
progress: null,
|
||||
targetDate: null,
|
||||
milestones: [
|
||||
"A short follow-up on each step you took, so your next plan is built on what worked for you.",
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Pay for a booking inside Skif",
|
||||
status: "Planned",
|
||||
@@ -61,6 +52,10 @@ export const PUBLIC_DEVELOPMENT: DevelopmentProfile = {
|
||||
},
|
||||
],
|
||||
changelog: [
|
||||
{
|
||||
date: "2026-10-22",
|
||||
done: "“Did it help?” under every step of your Safety Plan: say you did it, or that it is not for you, and then whether it helped. Your next plan learns from it: a step that helped counts as something you already have, and one that did not is set aside, with the next option in its place and a line saying why.",
|
||||
},
|
||||
{
|
||||
date: "2026-10-22",
|
||||
done: "Cards look the same everywhere now: your bookings, preferences and training are drawn exactly like the cards on the public pages, from one definition, and a test refuses a second look.",
|
||||
|
||||
@@ -9,6 +9,7 @@ export * from "./audit";
|
||||
export * from "./bookings";
|
||||
export * from "./complaints";
|
||||
export * from "./mail";
|
||||
export * from "./outcomes";
|
||||
export * from "./people";
|
||||
export * from "./shared";
|
||||
export * from "./threads";
|
||||
@@ -0,0 +1,17 @@
|
||||
/** "Did it help?": what a person said about a step their Safety Plan gave
|
||||
* them (src/domain/step-outcomes.ts). One row per person and step. */
|
||||
import { pgTable, primaryKey, text, timestamp } from "drizzle-orm/pg-core";
|
||||
import type { StepHelped, StepStatus } from "@/domain/step-outcomes";
|
||||
|
||||
export const stepOutcomes = pgTable(
|
||||
"step_outcomes",
|
||||
{
|
||||
sub: text("sub").notNull(),
|
||||
/** An intervention key from src/config/interventions.ts. */
|
||||
interventionKey: text("intervention_key").notNull(),
|
||||
status: text("status").$type<StepStatus>().notNull(),
|
||||
helped: text("helped").$type<StepHelped>(),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
},
|
||||
(t) => [primaryKey({ columns: [t.sub, t.interventionKey] })],
|
||||
);
|
||||
@@ -11,7 +11,9 @@
|
||||
* - for a high-priority finding (a known threat), the *most effective* one,
|
||||
* because proportionality cuts both ways;
|
||||
* - nothing new when what the person already does covers it — unless the
|
||||
* finding is high priority.
|
||||
* finding is high priority;
|
||||
* - learning from "Did it help?": a step that helped counts as covered, and
|
||||
* one that did not (or was "not for me") is set aside for the next option.
|
||||
* "Nothing to buy" is a first-class outcome, not a fallback.
|
||||
*/
|
||||
import type { HardConstraintKey } from "@/config/constraints";
|
||||
@@ -26,6 +28,7 @@ import {
|
||||
type Level,
|
||||
} from "@/config/interventions";
|
||||
import { preferenceFit } from "./preference-fit";
|
||||
import type { PlanLessons } from "./step-outcomes";
|
||||
import { deriveFindings, type Finding, type FindingInput } from "./findings";
|
||||
|
||||
export type PlanInput = FindingInput & {
|
||||
@@ -34,6 +37,8 @@ export type PlanInput = FindingInput & {
|
||||
budget: CostTier;
|
||||
/** The person's trade-off leans; DISCRETION comes from their presence style. */
|
||||
leans: Leans;
|
||||
/** What the person said about earlier steps. Absent: nothing said yet. */
|
||||
lessons?: PlanLessons;
|
||||
};
|
||||
|
||||
export type ExcludedIntervention = { key: string; constraints: HardConstraintKey[] };
|
||||
@@ -49,6 +54,8 @@ export type FindingPlan = Finding & {
|
||||
alternatives: string[];
|
||||
overBudget: string[];
|
||||
excluded: ExcludedIntervention[];
|
||||
/** Tried and did not help, or "not for me". Absent on older plans. */
|
||||
setAside?: string[];
|
||||
};
|
||||
|
||||
export type SafetyPlan = {
|
||||
@@ -88,11 +95,15 @@ function ordering(high: boolean, leans: Leans) {
|
||||
high ? benefit(a, b) || byLeans(a, b) || leastIntrusive(a, b) : byLeans(a, b) || leastIntrusive(a, b);
|
||||
}
|
||||
|
||||
function whyRecommended(i: Intervention, finding: Finding, covered: boolean, leans: Leans): string[] {
|
||||
function whyRecommended(i: Intervention, finding: Finding, covered: boolean, leans: Leans, setAside: string[]): string[] {
|
||||
const why =
|
||||
finding.priority === "HIGH"
|
||||
? ["The most effective option within your limits and budget — this is a high priority."]
|
||||
: ["The least intrusive option within your limits and budget that addresses this."];
|
||||
if (setAside.length) {
|
||||
const titles = setAside.map((k) => findIntervention(k)?.title ?? k).join(", ");
|
||||
why.push(`You said ${titles} didn't help or wasn't for you, so this is the next option.`);
|
||||
}
|
||||
if (covered) why.push("What you already do helps, but a known threat justifies more.");
|
||||
const fit = preferenceFit(i, leans);
|
||||
if (fit.with.length) why.push(`Fits your lean towards ${fit.with.join(", ")}.`);
|
||||
@@ -112,17 +123,21 @@ function planFinding(finding: Finding, input: PlanInput): FindingPlan {
|
||||
const excluded: ExcludedIntervention[] = [];
|
||||
const alreadyCovered: string[] = [];
|
||||
const overBudget: string[] = [];
|
||||
const setAside: string[] = [];
|
||||
const eligible: Intervention[] = [];
|
||||
const worked = input.lessons?.worked ?? [];
|
||||
const notAgain = input.lessons?.setAside ?? [];
|
||||
for (const i of candidates) {
|
||||
const broken = i.conflictsWith.filter((c) => input.constraints.includes(c));
|
||||
if (broken.length > 0) excluded.push({ key: i.key, constraints: broken });
|
||||
else if (i.coveredBy && input.measures.includes(i.coveredBy)) alreadyCovered.push(i.key);
|
||||
else if ((i.coveredBy && input.measures.includes(i.coveredBy)) || worked.includes(i.key)) alreadyCovered.push(i.key);
|
||||
else if (notAgain.includes(i.key)) setAside.push(i.key);
|
||||
else if (costRank(i.cost) > costRank(input.budget)) overBudget.push(i.key);
|
||||
else eligible.push(i);
|
||||
}
|
||||
|
||||
const covered = alreadyCovered.length > 0;
|
||||
const base = { ...finding, alreadyCovered, overBudget, excluded };
|
||||
const base = { ...finding, alreadyCovered, overBudget, excluded, ...(setAside.length ? { setAside } : {}) };
|
||||
if (covered && !high) {
|
||||
return { ...base, outcome: "COVERED", recommended: null, alternatives: eligible.map((i) => i.key) };
|
||||
}
|
||||
@@ -131,7 +146,7 @@ function planFinding(finding: Finding, input: PlanInput): FindingPlan {
|
||||
return {
|
||||
...base,
|
||||
outcome: "RECOMMENDED",
|
||||
recommended: { key: best.key, why: whyRecommended(best, finding, covered, input.leans) },
|
||||
recommended: { key: best.key, why: whyRecommended(best, finding, covered, input.leans, setAside) },
|
||||
alternatives: rest.map((i) => i.key),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildSafetyPlan, type PlanInput } from "./safety-plan";
|
||||
import { lessonsFrom, outcomeSentence, type StepOutcome } from "./step-outcomes";
|
||||
|
||||
const input = (overrides: Partial<PlanInput> = {}): PlanInput => ({
|
||||
environment: "HOME",
|
||||
concerns: ["BURGLARY"],
|
||||
exposures: [],
|
||||
threats: [],
|
||||
upcoming: "",
|
||||
measures: [],
|
||||
constraints: [],
|
||||
budget: "HIGH",
|
||||
leans: {},
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("what a plan learns from Did it help?", () => {
|
||||
it("counts a step that helped as had, and sets aside one that did not or was not wanted", () => {
|
||||
const outcomes = new Map<string, StepOutcome>([
|
||||
["A", { status: "DONE", helped: "YES" }],
|
||||
["B", { status: "DONE", helped: "SOMEWHAT" }],
|
||||
["C", { status: "DONE", helped: "NO" }],
|
||||
["D", { status: "NOT_FOR_ME", helped: null }],
|
||||
["E", { status: "DONE", helped: null }],
|
||||
]);
|
||||
expect(lessonsFrom(outcomes)).toEqual({ worked: ["A", "B"], setAside: ["C", "D"] });
|
||||
});
|
||||
|
||||
it("recommends the next option, and says why, when the first did not help", () => {
|
||||
const first = buildSafetyPlan(input()).findings[0]!;
|
||||
const tried = first.recommended!.key;
|
||||
expect(first.alternatives.length).toBeGreaterThan(0);
|
||||
const next = buildSafetyPlan(input({ lessons: { worked: [], setAside: [tried] } })).findings[0]!;
|
||||
expect(next.recommended!.key).toBe(first.alternatives[0]);
|
||||
expect(next.setAside).toEqual([tried]);
|
||||
expect(next.recommended!.why.join(" ")).toMatch(/didn't help or wasn't for you/);
|
||||
});
|
||||
|
||||
it("treats a step that helped like something the person already does", () => {
|
||||
const first = buildSafetyPlan(input()).findings[0]!;
|
||||
const next = buildSafetyPlan(input({ lessons: { worked: [first.recommended!.key], setAside: [] } })).findings[0]!;
|
||||
expect(next.outcome).toBe("COVERED");
|
||||
expect(next.alreadyCovered).toContain(first.recommended!.key);
|
||||
});
|
||||
|
||||
it("leaves a plan exactly as before when nothing has been said", () => {
|
||||
expect(buildSafetyPlan(input({ lessons: { worked: [], setAside: [] } }))).toEqual(buildSafetyPlan(input()));
|
||||
});
|
||||
|
||||
it("says what each answer means for the next plan", () => {
|
||||
expect(outcomeSentence(undefined)).toBeNull();
|
||||
expect(outcomeSentence({ status: "DONE", helped: null })).toBe("Done.");
|
||||
expect(outcomeSentence({ status: "DONE", helped: "NO" })).toMatch(/suggests something else/);
|
||||
expect(outcomeSentence({ status: "DONE", helped: "YES" })).toMatch(/counts it/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* "Did it help?" — what a person says about each step a Safety Plan gave
|
||||
* them, and what their next plan learns from it. Keyed by person and step,
|
||||
* not by plan: the same step in two plans is one experience.
|
||||
*/
|
||||
export const STEP_STATUSES = ["DONE", "NOT_FOR_ME"] as const;
|
||||
export type StepStatus = (typeof STEP_STATUSES)[number];
|
||||
|
||||
export const STEP_HELPED = ["YES", "SOMEWHAT", "NO"] as const;
|
||||
export type StepHelped = (typeof STEP_HELPED)[number];
|
||||
|
||||
export type StepOutcome = { status: StepStatus; helped: StepHelped | null };
|
||||
|
||||
export const HELPED_LABELS: Record<StepHelped, string> = {
|
||||
YES: "Yes",
|
||||
SOMEWHAT: "A little",
|
||||
NO: "No",
|
||||
};
|
||||
|
||||
/** What the next plan takes from the answers so far. */
|
||||
export type PlanLessons = {
|
||||
/** Done, and it helped: counts like a measure the person already has. */
|
||||
worked: string[];
|
||||
/** Done and it did not help, or "not for me": recommended no more. */
|
||||
setAside: string[];
|
||||
};
|
||||
|
||||
export function lessonsFrom(outcomes: ReadonlyMap<string, StepOutcome>): PlanLessons {
|
||||
const worked: string[] = [];
|
||||
const setAside: string[] = [];
|
||||
for (const [key, o] of outcomes) {
|
||||
if (o.status === "NOT_FOR_ME" || o.helped === "NO") setAside.push(key);
|
||||
else if (o.helped === "YES" || o.helped === "SOMEWHAT") worked.push(key);
|
||||
}
|
||||
return { worked: worked.sort(), setAside: setAside.sort() };
|
||||
}
|
||||
|
||||
/** One line for a step's row, once the person has said something about it. */
|
||||
export function outcomeSentence(o: StepOutcome | undefined): string | null {
|
||||
if (!o) return null;
|
||||
if (o.status === "NOT_FOR_ME") return "Not for you. Your next plan suggests something else.";
|
||||
if (o.helped === "YES") return "Done, and it helped. Your next plan counts it as something you have.";
|
||||
if (o.helped === "SOMEWHAT") return "Done, and it helped a little. Your next plan counts it as something you have.";
|
||||
if (o.helped === "NO") return "Done, but it didn't help. Your next plan suggests something else.";
|
||||
return "Done.";
|
||||
}
|
||||
@@ -6,13 +6,16 @@ import type { AssessmentInput } from "@/domain/inputs";
|
||||
import { fail, ok, type Result } from "@/domain/result";
|
||||
import { leansOf } from "@/domain/preference-fit";
|
||||
import { buildSafetyPlan } from "@/domain/safety-plan";
|
||||
import { lessonsFrom } from "@/domain/step-outcomes";
|
||||
import { getEnvironment, type Environment } from "./environments";
|
||||
import { getPreferences } from "./preferences";
|
||||
import { outcomesOf } from "./step-outcomes";
|
||||
|
||||
export type Assessment = typeof assessments.$inferSelect;
|
||||
|
||||
/** Run an assessment against the person's current hard constraints and save
|
||||
* the answers and the resulting Safety Plan, constraints included, as decided. */
|
||||
* the answers and the resulting Safety Plan, constraints included, as decided.
|
||||
* What the person said about earlier steps ("Did it help?") shapes it too. */
|
||||
export async function createAssessment(
|
||||
db: Db,
|
||||
customerSub: string,
|
||||
@@ -28,6 +31,7 @@ export async function createAssessment(
|
||||
environment: environment.type,
|
||||
constraints: prefs.hardConstraints,
|
||||
leans: leansOf(prefs.axes, prefs.presenceStyle),
|
||||
lessons: lessonsFrom(await outcomesOf(db, customerSub)),
|
||||
});
|
||||
const [row] = await db
|
||||
.insert(assessments)
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { INTERVENTIONS } from "@/config/interventions";
|
||||
import { createTestDb } from "@/test/db";
|
||||
import { outcomesOf, setStepOutcome } from "./step-outcomes";
|
||||
|
||||
const KEY = INTERVENTIONS[0]!.key;
|
||||
|
||||
describe("step outcomes", () => {
|
||||
it("records done, then whether it helped, keeps the answer on a repeat, and forgets on undo", async () => {
|
||||
const db = await createTestDb();
|
||||
await setStepOutcome(db, "a", KEY, { status: "DONE" });
|
||||
expect((await outcomesOf(db, "a")).get(KEY)).toEqual({ status: "DONE", helped: null });
|
||||
await setStepOutcome(db, "a", KEY, { status: "DONE", helped: "YES" });
|
||||
await setStepOutcome(db, "a", KEY, { status: "DONE" });
|
||||
expect((await outcomesOf(db, "a")).get(KEY)).toEqual({ status: "DONE", helped: "YES" });
|
||||
expect((await outcomesOf(db, "b")).size).toBe(0);
|
||||
await setStepOutcome(db, "a", KEY, null);
|
||||
expect((await outcomesOf(db, "a")).size).toBe(0);
|
||||
});
|
||||
|
||||
it("clears 'did it help' when a step becomes not for me", async () => {
|
||||
const db = await createTestDb();
|
||||
await setStepOutcome(db, "a", KEY, { status: "DONE", helped: "NO" });
|
||||
await setStepOutcome(db, "a", KEY, { status: "NOT_FOR_ME" });
|
||||
expect((await outcomesOf(db, "a")).get(KEY)).toEqual({ status: "NOT_FOR_ME", helped: null });
|
||||
});
|
||||
|
||||
it("refuses a step that does not exist", async () => {
|
||||
const db = await createTestDb();
|
||||
await expect(setStepOutcome(db, "a", "TELEPORT", { status: "DONE" })).rejects.toThrow(/Unknown step/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import "server-only";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { findIntervention } from "@/config/interventions";
|
||||
import { stepOutcomes } from "@/db/schema";
|
||||
import type { Db } from "@/db/types";
|
||||
import { STEP_HELPED, STEP_STATUSES, type StepHelped, type StepOutcome, type StepStatus } from "@/domain/step-outcomes";
|
||||
|
||||
/** Everything this person has said about their steps, by intervention key. */
|
||||
export async function outcomesOf(db: Db, sub: string): Promise<Map<string, StepOutcome>> {
|
||||
const rows = await db.select().from(stepOutcomes).where(eq(stepOutcomes.sub, sub));
|
||||
return new Map(rows.map((r) => [r.interventionKey, { status: r.status, helped: r.helped }]));
|
||||
}
|
||||
|
||||
export type StepAnswer = { status: StepStatus; helped?: StepHelped | null } | null;
|
||||
|
||||
/**
|
||||
* Record what the person said about a step, or forget it (`null`). Saying a
|
||||
* step was done keeps an earlier "did it help?" answer unless a new one is
|
||||
* given; "not for me" clears it.
|
||||
*/
|
||||
export async function setStepOutcome(db: Db, sub: string, interventionKey: string, answer: StepAnswer): Promise<void> {
|
||||
if (!findIntervention(interventionKey)) throw new Error(`Unknown step: ${interventionKey}`);
|
||||
const where = and(eq(stepOutcomes.sub, sub), eq(stepOutcomes.interventionKey, interventionKey));
|
||||
if (!answer) {
|
||||
await db.delete(stepOutcomes).where(where);
|
||||
return;
|
||||
}
|
||||
if (!STEP_STATUSES.includes(answer.status)) throw new Error(`Unknown status: ${answer.status}`);
|
||||
if (answer.helped && !STEP_HELPED.includes(answer.helped)) throw new Error(`Unknown answer: ${answer.helped}`);
|
||||
const helped = answer.status === "NOT_FOR_ME" ? null : answer.helped;
|
||||
await db
|
||||
.insert(stepOutcomes)
|
||||
.values({ sub, interventionKey, status: answer.status, helped: helped ?? null })
|
||||
.onConflictDoUpdate({
|
||||
target: [stepOutcomes.sub, stepOutcomes.interventionKey],
|
||||
set: { status: answer.status, ...(helped !== undefined ? { helped } : {}), updatedAt: new Date() },
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user