Keep a typed main kind from being ranked as the catalog other kind #116

Merged
an.di merged 2 commits from adilallo/fix/typed-kind-facet-query into main 2026-11-23 18:23:57 +00:00
7 changed files with 174 additions and 48 deletions

No files matched your search

+56 -22
View File
@@ -6,30 +6,33 @@ import {
resolveScaleChipId, resolveScaleChipId,
resolveSizeChipId, resolveSizeChipId,
} from "./communityChipIds"; } from "./communityChipIds";
import { TYPED_ORG_TYPE_MARKER } from "./deckTypes";
const FACET_GROUPS = ["size", "orgType", "scale", "maturity"] as const; const FACET_GROUPS = ["size", "orgType", "scale", "maturity"] as const;
type FacetGroupId = (typeof FACET_GROUPS)[number]; type FacetGroupId = (typeof FACET_GROUPS)[number];
const CHIP_TO_VALUE_BY_GROUP: Record<FacetGroupId, Record<string, string>> = const CHIP_TO_VALUE_BY_GROUP: Record<
(() => { FacetGroupId,
const out: Record<FacetGroupId, Record<string, string>> = { Record<string, string>
size: {}, > = (() => {
orgType: {}, const out: Record<FacetGroupId, Record<string, string>> = {
scale: {}, size: {},
maturity: {}, orgType: {},
}; scale: {},
for (const group of FACET_GROUPS) { maturity: {},
const block = (facetGroups as Record<string, unknown>)[group]; };
if (block && typeof block === "object" && "values" in block) { for (const group of FACET_GROUPS) {
const values = (block as { values: Record<string, { chipId: string }> }) const block = (facetGroups as Record<string, unknown>)[group];
.values; if (block && typeof block === "object" && "values" in block) {
for (const [valueId, entry] of Object.entries(values)) { const values = (block as { values: Record<string, { chipId: string }> })
out[group][entry.chipId] = valueId; .values;
} for (const [valueId, entry] of Object.entries(values)) {
out[group][entry.chipId] = valueId;
} }
} }
return out; }
})(); return out;
})();
const STATE_KEY_BY_GROUP: Record<FacetGroupId, keyof CreateFlowState> = { const STATE_KEY_BY_GROUP: Record<FacetGroupId, keyof CreateFlowState> = {
size: "selectedCommunitySizeIds", size: "selectedCommunitySizeIds",
@@ -45,14 +48,41 @@ const RESOLVE_BY_GROUP: Record<FacetGroupId, (id: string) => string> = {
maturity: resolveMaturityChipId, maturity: resolveMaturityChipId,
}; };
function readChipIds( function readChipIds(state: CreateFlowState, group: FacetGroupId): string[] {
state: CreateFlowState,
group: FacetGroupId,
): string[] {
const value = state[STATE_KEY_BY_GROUP[group]]; const value = state[STATE_KEY_BY_GROUP[group]];
return Array.isArray(value) ? (value as string[]) : []; return Array.isArray(value) ? (value as string[]) : [];
} }
function catalogOrgTypeId(chipId: string): string | null {
const resolved = resolveOrgChipId(chipId);
const valueId =
CHIP_TO_VALUE_BY_GROUP.orgType[resolved] ??
CHIP_TO_VALUE_BY_GROUP.orgType[chipId];
if (!valueId || valueId === "enterprise") return null;
return valueId;
}
/** Catalog kinds keep their order. A typed main kind is a leading marker. */
function appendOrgTypeFacets(params: URLSearchParams, state: CreateFlowState) {
const chipIds = readChipIds(state, "orgType");
const catalogIds: string[] = [];
const seen = new Set<string>();
for (const chipId of chipIds) {
const valueId = catalogOrgTypeId(chipId);
if (!valueId || seen.has(valueId)) continue;
seen.add(valueId);
catalogIds.push(valueId);
}
const firstIsCatalog =
chipIds.length > 0 && catalogOrgTypeId(chipIds[0]) !== null;
if (!firstIsCatalog && catalogIds.length > 0) {
params.append("facet.orgType", TYPED_ORG_TYPE_MARKER);
}
for (const valueId of catalogIds) {
params.append("facet.orgType", valueId);
}
}
/** /**
* Build `facet.size=…&facet.orgType=…` query string from Create Community * Build `facet.size=…&facet.orgType=…` query string from Create Community
* chip selections. Shared by `/api/create-flow/methods` and * chip selections. Shared by `/api/create-flow/methods` and
@@ -61,6 +91,10 @@ function readChipIds(
export function buildFacetQueryString(state: CreateFlowState): string { export function buildFacetQueryString(state: CreateFlowState): string {
const params = new URLSearchParams(); const params = new URLSearchParams();
for (const group of FACET_GROUPS) { for (const group of FACET_GROUPS) {
if (group === "orgType") {
appendOrgTypeFacets(params, state);
continue;
}
const valuesById = CHIP_TO_VALUE_BY_GROUP[group]; const valuesById = CHIP_TO_VALUE_BY_GROUP[group];
const resolve = RESOLVE_BY_GROUP[group]; const resolve = RESOLVE_BY_GROUP[group];
const seen = new Set<string>(); const seen = new Set<string>();
+13 -1
View File
@@ -27,6 +27,12 @@ export const KINDS = [
] as const; ] as const;
export type Kind = (typeof KINDS)[number]; export type Kind = (typeof KINDS)[number];
/**
* First `facet.orgType` value when the main kind was typed.
* Later catalog values stay other kinds instead of becoming the main kind.
*/
export const TYPED_ORG_TYPE_MARKER = "__typed__";
export const SCALES = ["local", "regional", "national", "global"] as const; export const SCALES = ["local", "regional", "national", "global"] as const;
export type Scale = (typeof SCALES)[number]; export type Scale = (typeof SCALES)[number];
@@ -48,7 +54,13 @@ export const TRAIT_KEYS = [
] as const; ] as const;
export type TraitKey = (typeof TRAIT_KEYS)[number]; export type TraitKey = (typeof TRAIT_KEYS)[number];
export const DISPLAY_TIERS = ["frame", "safety", "fitted", "floor", "none"] as const; export const DISPLAY_TIERS = [
"frame",
"safety",
"fitted",
"floor",
"none",
] as const;
export type DisplayTier = (typeof DISPLAY_TIERS)[number]; export type DisplayTier = (typeof DISPLAY_TIERS)[number];
export type RankTier = Exclude<DisplayTier, "none"> | "answers"; export type RankTier = Exclude<DisplayTier, "none"> | "answers";
+4 -4
View File
@@ -15,13 +15,14 @@ function trimmedLocation(raw: unknown): string | undefined {
return trimmed.slice(0, LOCATION_MAX); return trimmed.slice(0, LOCATION_MAX);
} }
/** Place and main group type stored on a finished Rule for launch counts. */ /** Place and catalog group type stored on a finished Rule for launch counts. */
export function publishedRuleAnalyticsFromState(state: CreateFlowState): { export function publishedRuleAnalyticsFromState(state: CreateFlowState): {
communityLocation?: string; communityLocation?: string;
orgType?: Kind; orgType?: Kind;
} { } {
const communityLocation = trimmedLocation(state.communityLocation); const communityLocation = trimmedLocation(state.communityLocation);
const orgType = groupAnswersFromCreateFlowState(state).mainKind ?? undefined; const answers = groupAnswersFromCreateFlowState(state);
const orgType = answers.mainKind ?? answers.otherKinds?.[0];
return { return {
...(communityLocation ? { communityLocation } : {}), ...(communityLocation ? { communityLocation } : {}),
...(orgType ? { orgType } : {}), ...(orgType ? { orgType } : {}),
@@ -37,8 +38,7 @@ export function publishedRuleAnalyticsFromDocument(document: unknown): {
} }
const row = document as Record<string, unknown>; const row = document as Record<string, unknown>;
const communityLocation = trimmedLocation(row.communityLocation) ?? null; const communityLocation = trimmedLocation(row.communityLocation) ?? null;
const orgTypeRaw = const orgTypeRaw = typeof row.orgType === "string" ? row.orgType.trim() : "";
typeof row.orgType === "string" ? row.orgType.trim() : "";
const orgType = isKind(orgTypeRaw) ? orgTypeRaw : null; const orgType = isKind(orgTypeRaw) ? orgTypeRaw : null;
return { communityLocation, orgType }; return { communityLocation, orgType };
} }
+35 -21
View File
@@ -3,6 +3,7 @@ import {
CATALOG_SECTION_IDS, CATALOG_SECTION_IDS,
METHOD_FACET_API_SECTION_IDS, METHOD_FACET_API_SECTION_IDS,
} from "../../create/customRuleFacets"; } from "../../create/customRuleFacets";
import { TYPED_ORG_TYPE_MARKER } from "../../create/deckTypes";
/** /**
* Zod schemas for the recommendation matrix (CR-88). * Zod schemas for the recommendation matrix (CR-88).
@@ -69,18 +70,20 @@ export type OrgTypeValueId = (typeof ORG_TYPE_VALUE_IDS)[number];
export type ScaleValueId = (typeof SCALE_VALUE_IDS)[number]; export type ScaleValueId = (typeof SCALE_VALUE_IDS)[number];
export type MaturityValueId = (typeof MATURITY_VALUE_IDS)[number]; export type MaturityValueId = (typeof MATURITY_VALUE_IDS)[number];
export const FACET_VALUE_IDS_BY_GROUP: Record< export const FACET_VALUE_IDS_BY_GROUP: Record<FacetGroupId, readonly string[]> =
FacetGroupId, {
readonly string[] size: SIZE_VALUE_IDS,
> = { orgType: ORG_TYPE_VALUE_IDS,
size: SIZE_VALUE_IDS, scale: SCALE_VALUE_IDS,
orgType: ORG_TYPE_VALUE_IDS, maturity: MATURITY_VALUE_IDS,
scale: SCALE_VALUE_IDS, };
maturity: MATURITY_VALUE_IDS,
};
const sizeValueIdSchema = z.enum(SIZE_VALUE_IDS); const sizeValueIdSchema = z.enum(SIZE_VALUE_IDS);
const orgTypeValueIdSchema = z.enum(ORG_TYPE_VALUE_IDS); const orgTypeValueIdSchema = z.enum(ORG_TYPE_VALUE_IDS);
const orgTypeRequestValueSchema = z.union([
orgTypeValueIdSchema,
z.literal(TYPED_ORG_TYPE_MARKER),
]);
const scaleValueIdSchema = z.enum(SCALE_VALUE_IDS); const scaleValueIdSchema = z.enum(SCALE_VALUE_IDS);
const maturityValueIdSchema = z.enum(MATURITY_VALUE_IDS); const maturityValueIdSchema = z.enum(MATURITY_VALUE_IDS);
@@ -195,9 +198,10 @@ export type FacetGroupsFile = z.infer<typeof facetGroupsFileSchema>;
* boolean or `{ match, weight? }`). Used by both the seed flattener and the * boolean or `{ match, weight? }`). Used by both the seed flattener and the
* scoring helpers. * scoring helpers.
*/ */
export function resolveFacetMatch( export function resolveFacetMatch(v: FacetMatch | undefined): {
v: FacetMatch | undefined, match: boolean;
): { match: boolean; weight: number | null } { weight: number | null;
} {
if (v === undefined) return { match: false, weight: null }; if (v === undefined) return { match: false, weight: null };
if (typeof v === "boolean") return { match: v, weight: null }; if (typeof v === "boolean") return { match: v, weight: null };
return { match: v.match, weight: v.weight ?? null }; return { match: v.match, weight: v.weight ?? null };
@@ -215,8 +219,8 @@ export const requestedFacetsSchema = z
.object({ .object({
size: z.array(sizeValueIdSchema).max(SIZE_VALUE_IDS.length).optional(), size: z.array(sizeValueIdSchema).max(SIZE_VALUE_IDS.length).optional(),
orgType: z orgType: z
.array(orgTypeValueIdSchema) .array(orgTypeRequestValueSchema)
.max(ORG_TYPE_VALUE_IDS.length) .max(ORG_TYPE_VALUE_IDS.length + 1)
.optional(), .optional(),
scale: z.array(scaleValueIdSchema).max(SCALE_VALUE_IDS.length).optional(), scale: z.array(scaleValueIdSchema).max(SCALE_VALUE_IDS.length).optional(),
maturity: z maturity: z
@@ -238,6 +242,7 @@ export function flattenRequestedFacets(
const values = facets[group]; const values = facets[group];
if (!values) continue; if (!values) continue;
for (const value of values) { for (const value of values) {
if (value === TYPED_ORG_TYPE_MARKER) continue;
out.push({ group, value }); out.push({ group, value });
} }
} }
@@ -248,11 +253,19 @@ export function flattenRequestedFacets(
* Parse `?facet.size=oneMember&facet.orgType=dao&facet.orgType=nonprofit` into * Parse `?facet.size=oneMember&facet.orgType=dao&facet.orgType=nonprofit` into
* a typed `RequestedFacets`. Unknown groups and unknown values are dropped * a typed `RequestedFacets`. Unknown groups and unknown values are dropped
* silently — the API "never errors on partial facets" (§9.3). * silently — the API "never errors on partial facets" (§9.3).
* `facet.orgType=__typed__` is kept, in order, so a typed main kind does not
* promote a later catalog kind to the main kind.
*/ */
export function parseRequestedFacetsFromSearchParams( export function parseRequestedFacetsFromSearchParams(
search: URLSearchParams, search: URLSearchParams,
): RequestedFacets { ): RequestedFacets {
const collected: Record<FacetGroupId, Set<string>> = { const collected: Record<FacetGroupId, string[]> = {
size: [],
orgType: [],
scale: [],
maturity: [],
};
const seen: Record<FacetGroupId, Set<string>> = {
size: new Set(), size: new Set(),
orgType: new Set(), orgType: new Set(),
scale: new Set(), scale: new Set(),
@@ -262,15 +275,16 @@ export function parseRequestedFacetsFromSearchParams(
if (!rawKey.startsWith("facet.")) continue; if (!rawKey.startsWith("facet.")) continue;
const group = rawKey.slice("facet.".length) as FacetGroupId; const group = rawKey.slice("facet.".length) as FacetGroupId;
if (!FACET_GROUP_IDS.includes(group)) continue; if (!FACET_GROUP_IDS.includes(group)) continue;
const allowed = new Set(FACET_VALUE_IDS_BY_GROUP[group]); const allowed = FACET_VALUE_IDS_BY_GROUP[group].includes(rawVal);
if (allowed.has(rawVal)) { const typedMain = group === "orgType" && rawVal === TYPED_ORG_TYPE_MARKER;
collected[group].add(rawVal); if ((!allowed && !typedMain) || seen[group].has(rawVal)) continue;
} seen[group].add(rawVal);
collected[group].push(rawVal);
} }
const out: RequestedFacets = {}; const out: RequestedFacets = {};
for (const group of FACET_GROUP_IDS) { for (const group of FACET_GROUP_IDS) {
if (collected[group].size > 0) { if (collected[group].length > 0) {
out[group] = Array.from(collected[group]) as never; out[group] = collected[group] as never;
} }
} }
return out; return out;
+38
View File
@@ -1,5 +1,11 @@
import { describe, it, expect } from "vitest"; import { describe, it, expect } from "vitest";
import { buildFacetQueryString } from "../../lib/create/buildFacetQueryString"; import { buildFacetQueryString } from "../../lib/create/buildFacetQueryString";
import { TYPED_ORG_TYPE_MARKER } from "../../lib/create/deckTypes";
import {
groupAnswersFromCreateFlowState,
groupAnswersFromRequestedFacets,
} from "../../lib/create/groupAnswers";
import { parseRequestedFacetsFromSearchParams } from "../../lib/server/validation/methodFacetsSchemas";
describe("buildFacetQueryString", () => { describe("buildFacetQueryString", () => {
it("maps community chip ids to facet.* query params", () => { it("maps community chip ids to facet.* query params", () => {
@@ -19,4 +25,36 @@ describe("buildFacetQueryString", () => {
it("returns empty string when no selections", () => { it("returns empty string when no selections", () => {
expect(buildFacetQueryString({})).toBe(""); expect(buildFacetQueryString({})).toBe("");
}); });
it("keeps a catalog other kind from becoming the main kind when the main kind was typed", () => {
const state = {
selectedCommunitySizeIds: ["sixToTwelve"],
selectedOrganizationTypeIds: ["custom-tenants-union", "workersCoop"],
};
const params = new URLSearchParams(buildFacetQueryString(state));
expect(params.getAll("facet.orgType")).toEqual([
TYPED_ORG_TYPE_MARKER,
"workersCoop",
]);
const fromState = groupAnswersFromCreateFlowState(state);
const fromQuery = groupAnswersFromRequestedFacets(
parseRequestedFacetsFromSearchParams(params),
);
expect(fromQuery.mainKind).toBeNull();
expect(fromQuery.otherKinds).toEqual(["workersCoop"]);
expect(fromQuery.mainKind).toBe(fromState.mainKind);
expect(fromQuery.otherKinds).toEqual(fromState.otherKinds);
});
it("does not mark a catalog main kind", () => {
const params = new URLSearchParams(
buildFacetQueryString({
selectedOrganizationTypeIds: ["workersCoop", "nonprofit"],
}),
);
expect(params.getAll("facet.orgType")).toEqual([
"workersCoop",
"nonprofit",
]);
});
}); });
+20
View File
@@ -1,4 +1,5 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { TYPED_ORG_TYPE_MARKER } from "../../lib/create/deckTypes";
import { import {
flattenRequestedFacets, flattenRequestedFacets,
methodFacetsSchema, methodFacetsSchema,
@@ -66,6 +67,17 @@ describe("parseRequestedFacetsFromSearchParams", () => {
params.append("foo", "bar"); params.append("foo", "bar");
expect(parseRequestedFacetsFromSearchParams(params)).toEqual({}); expect(parseRequestedFacetsFromSearchParams(params)).toEqual({});
}); });
it("keeps a typed main-kind marker ahead of catalog kinds", () => {
const params = new URLSearchParams();
params.append("facet.orgType", TYPED_ORG_TYPE_MARKER);
params.append("facet.orgType", "not-a-kind");
params.append("facet.orgType", "workersCoop");
expect(parseRequestedFacetsFromSearchParams(params).orgType).toEqual([
TYPED_ORG_TYPE_MARKER,
"workersCoop",
]);
});
}); });
describe("flattenRequestedFacets", () => { describe("flattenRequestedFacets", () => {
@@ -80,4 +92,12 @@ describe("flattenRequestedFacets", () => {
{ group: "orgType", value: "dao" }, { group: "orgType", value: "dao" },
]); ]);
}); });
it("omits the typed main-kind marker from scoring pairs", () => {
expect(
flattenRequestedFacets({
orgType: [TYPED_ORG_TYPE_MARKER, "workersCoop"],
}),
).toEqual([{ group: "orgType", value: "workersCoop" }]);
});
}); });
@@ -33,4 +33,12 @@ describe("publishedRuleAnalyticsFromState", () => {
}), }),
).toEqual({ communityLocation: "Denver", orgType: "mutualAid" }); ).toEqual({ communityLocation: "Denver", orgType: "mutualAid" });
}); });
it("records a catalog other kind when the main kind was typed", () => {
expect(
publishedRuleAnalyticsFromState({
selectedOrganizationTypeIds: ["custom-tenants-union", "workersCoop"],
}),
).toEqual({ orgType: "workersCoop" });
});
}); });