Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Collect role and industry to identify professional segments (#3045)
Luke Vella88a642c409bc
diff --git a/apps/landing/src/app/[locale]/(main)/privacy-policy/page.tsx b/apps/landing/src/app/[locale]/(main)/privacy-policy/page.tsxindex dd4b6ba6f..0c0392f2c 100644--- a/apps/landing/src/app/[locale]/(main)/privacy-policy/page.tsx+++ b/apps/landing/src/app/[locale]/(main)/privacy-policy/page.tsx@@ -7,7 +7,7 @@ export default async function PrivacyPolicy() {return (<div className="prose mx-auto max-w-3xl"><h1>Privacy Policy</h1>- <p>Last updated: 1 August 2023</p>+ <p>Last updated: 21 August 2026</p><p>At rallly.co, we take your privacy seriously. This privacy policyexplains how we collect, use, and disclose your personal data, and your@@ -18,12 +18,12 @@ export default async function PrivacyPolicy() {<h2>Information we collect</h2><p>- We store personal data (names and email addresses) on- DigitalOcean's servers, which are located in the United States. The- reason for storing data in the US is to improve performance for users by- having the data stored closer to where our compute services are running.- By using our services, you acknowledge that your personal data may be- transferred to and stored in the United States.+ We store personal data (names and email addresses) on Neon's+ servers, which are located in the United States. The reason for storing+ data in the US is to improve performance for users by having the data+ stored closer to where our compute services are running. By using our+ services, you acknowledge that your personal data may be transferred to+ and stored in the United States.</p><p>@@ -41,6 +41,49 @@ export default async function PrivacyPolicy() {website.</p>+ <h2>Optional information about your work</h2>++ <p>+ If you set up an account for work, we ask for two further pieces of+ information about you:+ </p>++ <ul>+ <li>+ Your role — self-declared, chosen from a list or described in your own+ words.+ </li>+ <li>+ The sector your organisation works in — suggested by us, and yours to+ confirm or change.+ </li>+ </ul>++ <p>+ We use this to understand which professional groups use Rallly, so we+ can improve the product for them and focus our documentation and+ marketing on the people it is written for. This information is also+ shared with Posthog, our analytics processor, for the same purpose.+ </p>++ <p>+ The sector field is suggested for you: we guess it from your email+ address's domain and the organisation name you enter, so that the+ field arrives filled in rather than blank. The guess is only a+ suggestion. Nothing is recorded until you submit the form, and you can+ change it to any other option, or to "Prefer not to say",+ before you do.+ </p>++ <p>+ Both fields are optional. You can skip either one when setting up your+ account, and neither is required to use Rallly — skipping them has no+ effect on the service you receive. To change or remove an answer you+ have already given, email us at{" "}+ <a href="mailto:[email protected]">[email protected]</a> and we will+ update or erase it.+ </p>+<h2>Legal basis for processing</h2><p>@@ -51,6 +94,16 @@ export default async function PrivacyPolicy() {contractual obligations to you.</p>+ <p>+ Your role and your organisation's sector are processed on the basis+ of consent alone, since they are optional and are not needed to deliver+ the service. You give that consent by submitting the setup form with a+ value in either field — including a suggested sector you choose to leave+ as it is. Choosing "Prefer not to say", or leaving a field+ unanswered, gives no consent and stores nothing. You can withdraw+ consent at any time by asking us to erase the answer.+ </p>+<h2>Retention of personal data</h2><p>diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.jsonindex 8af0ae352..73ac7f48f 100644--- a/apps/web/public/locales/en/app.json+++ b/apps/web/public/locales/en/app.json@@ -366,6 +366,21 @@"imageUploadInvalidFileTypeDescription": "Accepted formats: {formats}","inappropriateContent": "Inappropriate content","increaseSeats": "Increase seats",+ "industry": "Industry",+ "industryArtsAndEntertainment": "Arts and entertainment",+ "industryEducation": "Education",+ "industryGovernment": "Government",+ "industryHealthcare": "Healthcare",+ "industryHospitality": "Hospitality",+ "industryNone": "Prefer not to say",+ "industryNonProfit": "Non-profit",+ "industryOther": "Other",+ "industryPlaceholder": "Select an industry...",+ "industryProfessionalServices": "Professional services",+ "industryRealEstate": "Real estate",+ "industryRecruiting": "Recruiting",+ "industryReligiousOrganisation": "Religious organisation",+ "industryTechnology": "Technology","instanceSettingsDescription": "Configure your instance settings","invalidEmailAddress": "Please enter a valid email address","invalidFileType": "Invalid file type",@@ -385,6 +400,21 @@"invitePending": "An invitation has already been sent to this email address","inviteSent": "Invitation sent","inviteUpdated": "Invitation updated with new role",+ "jobTitle": "Your role",+ "jobTitleAdministratorOrCoordinator": "Administrator or coordinator",+ "jobTitleConsultantOrFreelancer": "Consultant or freelancer",+ "jobTitleExecutiveAssistant": "Executive assistant",+ "jobTitleFounderOrOwner": "Founder or owner",+ "jobTitleHealthcarePractitioner": "Healthcare practitioner",+ "jobTitleManagerOrTeamLead": "Manager or team lead",+ "jobTitleNone": "Prefer not to say",+ "jobTitleOther": "Other",+ "jobTitleOtherLabel": "Describe your role",+ "jobTitleOtherPlaceholder": "e.g. Practice manager",+ "jobTitlePlaceholder": "Select a role...",+ "jobTitleRecruiter": "Recruiter",+ "jobTitleSales": "Sales",+ "jobTitleTeacherOrLecturer": "Teacher or lecturer","joinSpace": "Join {spaceName}","keyBenefits": "Key benefits","language": "Language",diff --git a/apps/web/src/app/[locale]/setup/actions.ts b/apps/web/src/app/[locale]/setup/actions.tsindex b2f3da893..8102fc2dd 100644--- a/apps/web/src/app/[locale]/setup/actions.ts+++ b/apps/web/src/app/[locale]/setup/actions.ts@@ -1,9 +1,14 @@"use server";+import { headers } from "next/headers";import * as z from "zod";import { adoptOrphanedPolls } from "@/features/poll/mutations";import { getOwnedSpace } from "@/features/space/data";import { createSpace } from "@/features/space/mutations";+import { industrySchema } from "@/features/space/schema";+import { inferIndustry } from "@/features/space/utils";+import { jobTitleSchema } from "@/features/user/schema";+import authLib from "@/lib/auth";import { identifyGroup, track } from "@/lib/posthog";import { authActionClient } from "@/lib/safe-action/server";@@ -12,6 +17,12 @@ const setupSpaceSchema = z.discriminatedUnion("spaceType", [z.object({spaceType: z.literal("work"),organizationName: z.string().min(1).max(100),+ // Both optional: a required field against a guessed taxonomy forces bad+ // matches, and a skipped one reads as "none of these fit", which is+ // itself signal. Optionality is also what makes consent workable as the+ // legal basis for holding them.+ industry: industrySchema.optional(),+ jobTitle: jobTitleSchema.optional(),}),]);@@ -19,13 +30,30 @@ const setupSpaceSchema = z.discriminatedUnion("spaceType", [* Creates the user's space at the end of onboarding — registration doesn't* create one, so this is where every account gets theirs. Accounts that* already own a space (pre-existing accounts sent through setup to backfill- * profile fields, or a re-submit) only retry poll adoption: setup never- * renames or duplicates an existing space.+ * profile fields, or a re-submit) only re-persist the job title and retry+ * poll adoption: setup never renames or duplicates an existing space.*/export const setupSpaceAction = authActionClient.metadata({ actionName: "setup_space" }).inputSchema(setupSpaceSchema).action(async ({ ctx, parsedInput }) => {+ const jobTitle =+ parsedInput.spaceType === "work" ? parsedInput.jobTitle : undefined;++ if (jobTitle) {+ // Written before the space, and before the early return below, so a+ // retry after a partial failure still persists it — the answer belongs+ // to the person, not to the space being created.+ //+ // Session-defined target, so the Better-Auth endpoint rather than a+ // mutation: it writes the row and refreshes the session snapshot and+ // cookie cache in one step.+ await authLib.api.updateUser({+ body: { jobTitle },+ headers: await headers(),+ });+ }+const ownedSpace = await getOwnedSpace(ctx.user.id);if (ownedSpace) {@@ -44,9 +72,14 @@ export const setupSpaceAction = authActionClient? parsedInput.organizationName: "Personal";+ const industry =+ parsedInput.spaceType === "work" ? parsedInput.industry : undefined;+const space = await createSpace({name,ownerId: ctx.user.id,+ spaceType: parsedInput.spaceType,+ industry,});// Guest linking migrates polls without a space; pull them into the one@@ -66,9 +99,29 @@ export const setupSpaceAction = authActionClienttier: space.tier,member_count: 1,seat_count: 1,+ industry,},});+ if (industry) {+ // Re-run the classifier here rather than trusting an "inferred" value+ // posted by the form: the pair is what makes classifier accuracy+ // queryable, so that half has to be the server's own guess.+ track(ctx.user, {+ event: "space:industry_set",+ properties: {+ inferred_industry: inferIndustry({+ email: ctx.user.email,+ organizationName: name,+ }),+ final_industry: industry,+ },+ groups: {+ space: space.id,+ },+ });+ }+track(ctx.user, {event: "space_setup",properties: {@@ -80,6 +133,9 @@ export const setupSpaceAction = authActionClient$set: {name: ctx.user.name,timeZone: ctx.user.timeZone ?? undefined,+ // Person property, so the segment can be joined against anything+ // the user does later — not just this event.+ ...(jobTitle ? { job_title: jobTitle } : {}),},},groups: {diff --git a/apps/web/src/app/[locale]/setup/components/setup-form.tsx b/apps/web/src/app/[locale]/setup/components/setup-form.tsxindex a60ee55fc..e19006cb0 100644--- a/apps/web/src/app/[locale]/setup/components/setup-form.tsx+++ b/apps/web/src/app/[locale]/setup/components/setup-form.tsx@@ -19,6 +19,11 @@ import { useForm } from "react-hook-form";import * as z from "zod";import { setupSpaceAction } from "@/app/[locale]/setup/actions";import { TimeZoneSelect } from "@/components/time-zone-picker/time-zone-select";+import { IndustrySelect } from "@/features/space/components/industry-select";+import { industries } from "@/features/space/constants";+import { inferIndustry } from "@/features/space/utils";+import { JobTitleSelect } from "@/features/user/components/job-title-select";+import { JOB_TITLE_OTHER_MAX_LENGTH } from "@/features/user/constants";import { Trans, useTranslation } from "@/i18n/client";import { authClient } from "@/lib/auth-client";import { getLocaleDefaults } from "@/lib/datetime/locales";@@ -37,6 +42,11 @@ function useSetupFormSchema() {timeFormat: z.enum(["hours12", "hours24"]),spaceType: z.enum(["personal", "work"]),organizationName: z.string().max(100),+ // Both optional: a required field against a guessed taxonomy forces+ // bad matches, and a skipped one reads as "none of these fit", which+ // is itself signal.+ industry: z.enum(industries).nullable(),+ jobTitle: z.string().max(JOB_TITLE_OTHER_MAX_LENGTH).nullable(),}).refine((data) =>@@ -80,10 +90,17 @@ export function SetupForm({defaultName,defaultTimeZone,defaultTimeFormat,+ email,}: {defaultName: string;defaultTimeZone?: string;defaultTimeFormat?: TimeFormat;+ /**+ * Only used to guess an industry. The server runs the same classifier on+ * the way in, so nothing here is trusted — this just lets the guess follow+ * the organization name as it is typed, which the server can't see yet.+ */+ email: string;}) {const { t } = useTranslation();const { locale } = useLocale();@@ -98,10 +115,29 @@ export function SetupForm({timeFormat: defaultTimeFormat ?? getLocaleDefaults(locale).timeFormat,spaceType: "personal" as const,organizationName: "",+ industry: null,+ jobTitle: null,},});const spaceType = form.watch("spaceType");+ const organizationName = form.watch("organizationName");++ // The inferred value is a prefill, not an answer: once the user touches the+ // field it stops moving, and what gets stored is whatever they confirmed.+ const industryTouched = React.useRef(false);+ const setIndustryValue = form.setValue;++ React.useEffect(() => {+ if (industryTouched.current) {+ return;+ }++ setIndustryValue(+ "industry",+ inferIndustry({ email, organizationName }) ?? null,+ );+ }, [email, organizationName, setIndustryValue]);return (<Form {...form}>@@ -113,6 +149,8 @@ export function SetupForm({timeFormat,spaceType,organizationName,+ industry,+ jobTitle,}) => {const res = await authClient.updateUser({name,@@ -134,7 +172,12 @@ export function SetupForm({// redirects onward while the button stays loading.await setupSpace.executeAsync(spaceType === "work"- ? { spaceType, organizationName: organizationName.trim() }+ ? {+ spaceType,+ organizationName: organizationName.trim(),+ industry: industry ?? undefined,+ jobTitle: jobTitle ?? undefined,+ }: { spaceType },);},@@ -255,32 +298,85 @@ export function SetupForm({)}/>{spaceType === "work" ? (- <FormField- control={form.control}- name="organizationName"- render={({ field }) => (- <FormItem>- <FormLabel>- <Trans- i18nKey="organizationName"- defaults="Organization name"- />- </FormLabel>- <FormControl>- <Input- {...field}- data-1p-ignore- autoFocus={true}- placeholder={t("organizationNamePlaceholder", {- defaultValue: "e.g. Acme Corp",- })}- disabled={form.formState.isSubmitting}- />- </FormControl>- <FormMessage />- </FormItem>- )}- />+ <>+ <FormField+ control={form.control}+ name="organizationName"+ render={({ field }) => (+ <FormItem>+ <FormLabel>+ <Trans+ i18nKey="organizationName"+ defaults="Organization name"+ />+ </FormLabel>+ <FormControl>+ <Input+ {...field}+ data-1p-ignore+ autoFocus={true}+ placeholder={t("organizationNamePlaceholder", {+ defaultValue: "e.g. Acme Corp",+ })}+ disabled={form.formState.isSubmitting}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ {/* Industry first: confirming a sector primes a more precise+ answer to the role question below. */}+ <FormField+ control={form.control}+ name="industry"+ render={({ field }) => (+ <FormItem>+ <FormLabel htmlFor="industry">+ <Trans i18nKey="industry" defaults="Industry" />+ <span className="ml-1 font-normal text-muted-foreground">+ <Trans i18nKey="optional" defaults="(optional)" />+ </span>+ </FormLabel>+ <FormControl>+ <IndustrySelect+ id="industry"+ value={field.value}+ onValueChange={(value) => {+ industryTouched.current = true;+ field.onChange(value);+ }}+ disabled={form.formState.isSubmitting}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="jobTitle"+ render={({ field }) => (+ <FormItem>+ <FormLabel htmlFor="jobTitle">+ <Trans i18nKey="jobTitle" defaults="Your role" />+ <span className="ml-1 font-normal text-muted-foreground">+ <Trans i18nKey="optional" defaults="(optional)" />+ </span>+ </FormLabel>+ <FormControl>+ <JobTitleSelect+ id="jobTitle"+ value={field.value}+ onValueChange={field.onChange}+ disabled={form.formState.isSubmitting}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ </>) : null}{form.formState.errors.root?.message ? (<FormMessage>{form.formState.errors.root.message}</FormMessage>diff --git a/apps/web/src/app/[locale]/setup/page.tsx b/apps/web/src/app/[locale]/setup/page.tsxindex 15ab00505..bc1218c30 100644--- a/apps/web/src/app/[locale]/setup/page.tsx+++ b/apps/web/src/app/[locale]/setup/page.tsx@@ -65,6 +65,7 @@ export default async function SetupPage(props: {defaultName={user.name}defaultTimeZone={user.timeZone ?? device.timeZone}defaultTimeFormat={user.timeFormat ?? device.timeFormat}+ email={user.email}/></div></article>diff --git a/apps/web/src/features/space/components/industry-select.tsx b/apps/web/src/features/space/components/industry-select.tsxnew file mode 100644index 000000000..9d596ade3--- /dev/null+++ b/apps/web/src/features/space/components/industry-select.tsx@@ -0,0 +1,120 @@+"use client";++import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@rallly/ui/select";+import type { Industry } from "@/features/space/constants";+import { industries } from "@/features/space/constants";+import { Trans, useTranslation } from "@/i18n/client";++// Base UI treats null as "nothing selected"; the picklist needs a real value+// to hang the opt-out on, so it gets a sentinel that maps back to null.+const NONE_VALUE = "none";++function IndustryLabel({ industry }: { industry: Industry }) {+ switch (industry) {+ case "education":+ return <Trans i18nKey="industryEducation" defaults="Education" />;+ case "healthcare":+ return <Trans i18nKey="industryHealthcare" defaults="Healthcare" />;+ case "professional_services":+ return (+ <Trans+ i18nKey="industryProfessionalServices"+ defaults="Professional services"+ />+ );+ case "technology":+ return <Trans i18nKey="industryTechnology" defaults="Technology" />;+ case "non_profit":+ return <Trans i18nKey="industryNonProfit" defaults="Non-profit" />;+ case "government":+ return <Trans i18nKey="industryGovernment" defaults="Government" />;+ case "recruiting":+ return <Trans i18nKey="industryRecruiting" defaults="Recruiting" />;+ case "real_estate":+ return <Trans i18nKey="industryRealEstate" defaults="Real estate" />;+ case "religious_organisation":+ return (+ <Trans+ i18nKey="industryReligiousOrganisation"+ defaults="Religious organisation"+ />+ );+ case "arts_and_entertainment":+ return (+ <Trans+ i18nKey="industryArtsAndEntertainment"+ defaults="Arts and entertainment"+ />+ );+ case "hospitality":+ return <Trans i18nKey="industryHospitality" defaults="Hospitality" />;+ case "other":+ return <Trans i18nKey="industryOther" defaults="Other" />;+ }+}++/**+ * Sector picker for a work space. Optional by design — "prefer not to say"+ * clears it, which both keeps consent a workable legal basis and records+ * "none of these fit" as an answer in its own right.+ */+export function IndustrySelect({+ value,+ onValueChange,+ disabled,+ id,+}: {+ value?: Industry | null;+ onValueChange: (value: Industry | null) => void;+ disabled?: boolean;+ id?: string;+}) {+ const { t } = useTranslation();++ return (+ <Select<string | null, false>+ items={[+ {+ value: NONE_VALUE,+ label: t("industryNone", { defaultValue: "Prefer not to say" }),+ },+ ...industries.map((industry) => ({+ value: industry,+ label: <IndustryLabel industry={industry} />,+ })),+ ]}+ // Unset renders the placeholder rather than "Prefer not to say" — an+ // untouched optional field hasn't been answered either way, and the+ // opt-out item exists to clear a value that was set.+ value={value ?? null}+ onValueChange={(next) => {+ onValueChange(next === NONE_VALUE ? null : (next as Industry));+ }}+ disabled={disabled}+ >+ <SelectTrigger id={id} className="w-full">+ <SelectValue+ placeholder={t("industryPlaceholder", {+ defaultValue: "Select an industry...",+ })}+ />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value={NONE_VALUE}>+ <Trans i18nKey="industryNone" defaults="Prefer not to say" />+ </SelectItem>+ {industries.map((industry) => (+ <SelectItem key={industry} value={industry}>+ <IndustryLabel industry={industry} />+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ );+}diff --git a/apps/web/src/features/space/constants.ts b/apps/web/src/features/space/constants.tsindex 893acf78c..efd22d6b5 100644--- a/apps/web/src/features/space/constants.ts+++ b/apps/web/src/features/space/constants.ts@@ -6,3 +6,260 @@ export const spaceIconAssetProfile = {accept: ["image/jpeg", "image/png"],maxSize: 2 * 1024 * 1024,} as const satisfies AssetProfile;++/**+ * Self-declared sector for a work space. Deliberately a string union rather+ * than a Prisma enum: a v2 taxonomy is expected once override rates and+ * free-text roles are in, and changing a set of strings is lighter than an+ * enum migration. The first five mirror Doodle's Industries menu so the+ * segments are comparable.+ */+export const industries = [+ "education",+ "healthcare",+ "professional_services",+ "technology",+ "non_profit",+ "government",+ "recruiting",+ "real_estate",+ "religious_organisation",+ "arts_and_entertainment",+ "hospitality",+ "other",+] as const;++export type Industry = (typeof industries)[number];++/**+ * Email domain suffixes that identify a sector on their own, matched as+ * complete suffixes rather than as individual labels. Individual labels are+ * not safe: "edu" appears in both "example.edu" (a university) and+ * "attacker.edu.com" (anyone at all), and only the first is evidence.+ *+ * Checked before the keyword table — a .edu address outranks any word in an+ * organization name. Free-mail domains (gmail.com, outlook.com) match nothing+ * here and fall through to the keyword check.+ *+ * Deliberately not a public-suffix list: this is a prefill the user confirms,+ * so covering the common registries beats carrying a dependency that has to+ * be kept current. A suffix that isn't listed simply yields no guess.+ */+export const industryDomainRules: ReadonlyArray<{+ suffixes: readonly string[];+ industry: Industry;+}> = [+ {+ suffixes: [+ "edu",+ "edu.au",+ "edu.sg",+ "edu.in",+ "ac.uk",+ "ac.nz",+ "ac.jp",+ "ac.za",+ "ac.at",+ "sch.uk",+ ],+ industry: "education",+ },+ {+ suffixes: [+ "gov",+ "mil",+ "gov.uk",+ "gov.au",+ "gov.in",+ "gov.za",+ "govt.nz",+ "gc.ca",+ ],+ industry: "government",+ },+ { suffixes: ["org", "org.uk", "org.au", "org.nz"], industry: "non_profit" },+];++/**+ * Organization name keywords, checked as whole words against a normalized+ * name when the domain yields nothing. Ordered by specificity: the first+ * entry whose keyword appears wins, so narrow sectors precede broad ones+ * ("clinic" before "services").+ */+export const industryKeywordRules: ReadonlyArray<{+ keywords: readonly string[];+ industry: Industry;+}> = [+ {+ keywords: [+ "school",+ "college",+ "university",+ "academy",+ "kindergarten",+ "preschool",+ "education",+ "institute",+ "faculty",+ "campus",+ "tutoring",+ ],+ industry: "education",+ },+ {+ keywords: [+ "hospital",+ "clinic",+ "medical",+ "health",+ "healthcare",+ "dental",+ "dentist",+ "physio",+ "physiotherapy",+ "therapy",+ "pharmacy",+ "veterinary",+ "vet",+ "care",+ ],+ industry: "healthcare",+ },+ {+ keywords: [+ "church",+ "parish",+ "chapel",+ "cathedral",+ "synagogue",+ "mosque",+ "temple",+ "ministry",+ "ministries",+ "diocese",+ "congregation",+ ],+ industry: "religious_organisation",+ },+ {+ keywords: [+ "recruiting",+ "recruitment",+ "recruiters",+ "staffing",+ "talent",+ "headhunting",+ "hiring",+ ],+ industry: "recruiting",+ },+ {+ keywords: [+ "realty",+ "estate",+ "estates",+ "properties",+ "property",+ "lettings",+ "brokerage",+ ],+ industry: "real_estate",+ },+ {+ keywords: [+ "charity",+ "foundation",+ "nonprofit",+ "ngo",+ "trust",+ "volunteers",+ "volunteering",+ ],+ industry: "non_profit",+ },+ {+ keywords: [+ "council",+ "municipality",+ "department",+ "agency",+ "bureau",+ "authority",+ ],+ industry: "government",+ },+ {+ keywords: [+ "software",+ "technologies",+ "technology",+ "tech",+ "digital",+ "labs",+ "systems",+ "data",+ "cloud",+ "cyber",+ "robotics",+ "ai",+ ],+ industry: "technology",+ },+ {+ keywords: [+ "hotel",+ "hostel",+ "resort",+ "restaurant",+ "cafe",+ "catering",+ "bistro",+ "brewery",+ "hospitality",+ "travel",+ "tours",+ ],+ industry: "hospitality",+ },+ {+ keywords: [+ "studio",+ "studios",+ "theatre",+ "theater",+ "gallery",+ "museum",+ "orchestra",+ "choir",+ "band",+ "productions",+ "media",+ "music",+ "dance",+ "film",+ ],+ industry: "arts_and_entertainment",+ },+ {+ keywords: [+ "consulting",+ "consultancy",+ "consultants",+ "advisory",+ "advisors",+ "accounting",+ "accountants",+ "law",+ "legal",+ "solicitors",+ "attorneys",+ "notary",+ "architects",+ "engineering",+ "partners",+ "associates",+ "services",+ ],+ industry: "professional_services",+ },+];diff --git a/apps/web/src/features/space/mutations.ts b/apps/web/src/features/space/mutations.tsindex a47cb65d4..c7c80b933 100644--- a/apps/web/src/features/space/mutations.ts+++ b/apps/web/src/features/space/mutations.ts@@ -1,6 +1,6 @@import "server-only";-import type { SpaceTier } from "@rallly/database";+import type { SpaceTier, SpaceType } from "@rallly/database";import { prisma } from "@rallly/database";import { after } from "next/server";import { createSpaceDTO } from "@/features/space/data";@@ -14,16 +14,22 @@ export async function createSpace({name = "Personal",ownerId,tier = isSelfHosted ? "pro" : "hobby",+ spaceType,+ industry,}: {name?: string;ownerId: string;tier?: SpaceTier;+ spaceType?: SpaceType;+ industry?: string | null;}) {const space = await prisma.space.create({data: {name,ownerId,tier,+ spaceType,+ industry,members: {create: {userId: ownerId,diff --git a/apps/web/src/features/space/schema.ts b/apps/web/src/features/space/schema.tsindex 9d26fcf74..041f07e71 100644--- a/apps/web/src/features/space/schema.ts+++ b/apps/web/src/features/space/schema.ts@@ -1,5 +1,5 @@import * as z from "zod";-import { spaceIconAssetProfile } from "@/features/space/constants";+import { industries, spaceIconAssetProfile } from "@/features/space/constants";export const memberRoleSchema = z.enum(["member", "admin"]);export type MemberRole = z.infer<typeof memberRoleSchema>;@@ -7,6 +7,10 @@ export type MemberRole = z.infer<typeof memberRoleSchema>;export const spaceTierSchema = z.enum(["hobby", "pro"]);export type SpaceTier = z.infer<typeof spaceTierSchema>;+// The taxonomy is validated here rather than in the database so a v2 list+// costs a deploy instead of an enum migration.+export const industrySchema = z.enum(industries);+export const createSpaceSchema = z.object({name: z.string().min(1).max(100),});diff --git a/apps/web/src/features/space/utils.test.ts b/apps/web/src/features/space/utils.test.tsnew file mode 100644index 000000000..13de87a22--- /dev/null+++ b/apps/web/src/features/space/utils.test.ts@@ -0,0 +1,115 @@+import { describe, expect, it } from "vitest";+import { inferIndustry } from "@/features/space/utils";++describe("inferIndustry", () => {+ it("infers education from an academic domain", () => {+ expect(inferIndustry({ email: "[email protected]" })).toBe("education");+ expect(inferIndustry({ email: "[email protected]" })).toBe("education");+ expect(inferIndustry({ email: "[email protected]" })).toBe("education");+ });++ it("infers government from a public sector domain", () => {+ expect(inferIndustry({ email: "[email protected]" })).toBe("government");+ expect(inferIndustry({ email: "[email protected]" })).toBe("government");+ expect(inferIndustry({ email: "[email protected]" })).toBe("government");+ });++ it("infers non-profit from a .org domain", () => {+ expect(inferIndustry({ email: "[email protected]" })).toBe("non_profit");+ });++ it("matches domain labels whole, not as substrings", () => {+ expect(inferIndustry({ email: "[email protected]" })).toBeUndefined();+ expect(inferIndustry({ email: "[email protected]" })).toBeUndefined();+ });++ it("does not let a label anywhere but the suffix claim a sector", () => {+ // Each of these carries a sector label while ending in .com or .co, so+ // anyone could register one and be classified. Only the suffix counts.+ expect(inferIndustry({ email: "[email protected]" })).toBeUndefined();+ expect(+ inferIndustry({ email: "[email protected]" }),+ ).toBeUndefined();+ expect(inferIndustry({ email: "[email protected]" })).toBeUndefined();+ expect(inferIndustry({ email: "[email protected]" })).toBeUndefined();+ expect(inferIndustry({ email: "[email protected]" })).toBeUndefined();+ expect(inferIndustry({ email: "[email protected]" })).toBeUndefined();+ });++ it("requires a label in front of the suffix", () => {+ // A bare suffix is not somebody's organization.+ expect(inferIndustry({ email: "ada@edu" })).toBeUndefined();+ expect(inferIndustry({ email: "ada@org" })).toBeUndefined();+ });++ it("still matches a genuine multi-label suffix", () => {+ expect(inferIndustry({ email: "[email protected]" })).toBe("government");+ expect(inferIndustry({ email: "[email protected]" })).toBe(+ "education",+ );+ expect(inferIndustry({ email: "[email protected]" })).toBe("education");+ expect(inferIndustry({ email: "[email protected]" })).toBe("non_profit");+ });++ it("falls through free-mail domains to the organization name", () => {+ expect(+ inferIndustry({+ email: "[email protected]",+ organizationName: "Northside Dental Clinic",+ }),+ ).toBe("healthcare");+ expect(inferIndustry({ email: "[email protected]" })).toBeUndefined();+ });++ it("prefers the domain over the organization name", () => {+ expect(+ inferIndustry({+ email: "[email protected]",+ organizationName: "Acme Software",+ }),+ ).toBe("education");+ });++ it("matches organization name keywords as whole words", () => {+ expect(inferIndustry({ organizationName: "Acme Software" })).toBe(+ "technology",+ );+ expect(inferIndustry({ organizationName: "ACME SOFTWARE" })).toBe(+ "technology",+ );+ expect(inferIndustry({ organizationName: "Software-Werk" })).toBe(+ "technology",+ );+ // "care" must not fire on "Careers", nor "vet" on "Velvet"+ expect(inferIndustry({ organizationName: "Careers Ltd" })).toBeUndefined();+ expect(inferIndustry({ organizationName: "Velvet Ltd" })).toBeUndefined();+ });++ it("resolves overlapping keywords by table order", () => {+ // "church" (religious) is checked before "services" (professional)+ expect(inferIndustry({ organizationName: "Grace Church Services" })).toBe(+ "religious_organisation",+ );+ });++ it("returns undefined when nothing matches", () => {+ expect(inferIndustry({})).toBeUndefined();+ expect(inferIndustry({ email: "[email protected]" })).toBeUndefined();+ expect(+ inferIndustry({ email: " ", organizationName: " " }),+ ).toBeUndefined();+ expect(+ inferIndustry({ email: null, organizationName: null }),+ ).toBeUndefined();+ });++ it("tolerates a malformed email", () => {+ expect(inferIndustry({ email: "not-an-email" })).toBeUndefined();+ expect(+ inferIndustry({+ email: "not-an-email",+ organizationName: "City Council",+ }),+ ).toBe("government");+ });+});diff --git a/apps/web/src/features/space/utils.ts b/apps/web/src/features/space/utils.tsindex dedf3751e..7c5b5967d 100644--- a/apps/web/src/features/space/utils.ts+++ b/apps/web/src/features/space/utils.ts@@ -1,4 +1,9 @@import type { SpaceMemberRole as PrismaSpaceMemberRole } from "@rallly/database";+import type { Industry } from "@/features/space/constants";+import {+ industryDomainRules,+ industryKeywordRules,+} from "@/features/space/constants";import type { MemberRole } from "@/features/space/schema";export const toDBRole = (role: MemberRole): PrismaSpaceMemberRole => {@@ -18,3 +23,53 @@ export const fromDBRole = (role: PrismaSpaceMemberRole): MemberRole => {return "admin";}};++/**+ * Guess a work space's sector from the owner's email domain and the+ * organization name. Domain first — a .edu address outranks any word in a+ * name — then whole-word keywords against the name. Returns undefined when+ * nothing matches: the field has no default, the user picks.+ *+ * The guess is only ever a prefill. What gets stored is what the user+ * confirms, and both values are reported to PostHog so the classifier's+ * accuracy stays measurable.+ */+export function inferIndustry({+ email,+ organizationName,+}: {+ email?: string | null;+ organizationName?: string | null;+}): Industry | undefined {+ const domain = email?.trim().toLowerCase().split("@")[1];++ if (domain) {+ // The suffix has to match end-to-end, with at least one label in front of+ // it. Matching labels individually is what let anyone claim a sector by+ // registering around one: "attacker.edu.com" and "foo.edu.attacker.com"+ // both contain the label "edu" while ending in ".com". Requiring a label+ // before the suffix also stops a bare "edu" host from matching itself.+ for (const rule of industryDomainRules) {+ if (rule.suffixes.some((suffix) => domain.endsWith(`.${suffix}`))) {+ return rule.industry;+ }+ }+ }++ const words = organizationName+ ?.toLowerCase()+ .split(/[^a-z0-9]+/)+ .filter(Boolean);++ if (words?.length) {+ const wordSet = new Set(words);++ for (const rule of industryKeywordRules) {+ if (rule.keywords.some((keyword) => wordSet.has(keyword))) {+ return rule.industry;+ }+ }+ }++ return undefined;+}diff --git a/apps/web/src/features/user/components/job-title-select.test.tsx b/apps/web/src/features/user/components/job-title-select.test.tsxnew file mode 100644index 000000000..12dc067b0--- /dev/null+++ b/apps/web/src/features/user/components/job-title-select.test.tsx@@ -0,0 +1,100 @@+import userEvent from "@testing-library/user-event";+import React from "react";+import { describe, expect, it } from "vitest";+import { JobTitleSelect } from "@/features/user/components/job-title-select";+import { render, screen, waitFor } from "@/test/test-utils";++/**+ * Mirrors how the setup form drives the picker: the parent owns the value and+ * feeds it straight back, so a mode derived from that value would collapse the+ * moment the typed text matched a picklist key.+ */+function Harness({ initial = null }: { initial?: string | null }) {+ const [value, setValue] = React.useState<string | null>(initial);+ return (+ <>+ <JobTitleSelect id="jobTitle" value={value} onValueChange={setValue} />+ <output data-testid="value">{value ?? "null"}</output>+ </>+ );+}++async function chooseOther(user: ReturnType<typeof userEvent.setup>) {+ await user.click(screen.getByRole("combobox"));+ await user.click(screen.getByRole("option", { name: "Other" }));+}++describe("JobTitleSelect", () => {+ it("stores a picklist selection by key", async () => {+ const user = userEvent.setup();+ render(<Harness />);++ await user.click(screen.getByRole("combobox"));+ await user.click(screen.getByRole("option", { name: "Recruiter" }));++ await waitFor(() =>+ expect(screen.getByTestId("value")).toHaveTextContent("recruiter"),+ );+ });++ it("keeps the free text input mounted when the text matches a picklist key", async () => {+ const user = userEvent.setup();+ render(<Harness />);++ await chooseOther(user);+ const input = screen.getByLabelText("Describe your role");+ await user.type(input, "sales");++ // The bug this guards: "sales" is a picklist key, so deriving the mode+ // from the value unmounted the input mid-keystroke and silently turned+ // the answer into the Sales picklist entry.+ await waitFor(() =>+ expect(screen.getByTestId("value")).toHaveTextContent("sales"),+ );+ expect(screen.getByLabelText("Describe your role")).toHaveValue("sales");+ });++ it("falls back to the Other key when the free text is cleared", async () => {+ const user = userEvent.setup();+ render(<Harness />);++ await chooseOther(user);+ const input = screen.getByLabelText("Describe your role");+ await user.type(input, "Practice manager");+ await waitFor(() =>+ expect(screen.getByTestId("value")).toHaveTextContent("Practice manager"),+ );++ await user.clear(input);+ // waitFor, not a bare expect: clearing the input drives a state update in+ // the parent harness, and asserting before React flushes it made this+ // test fail intermittently under full-suite load.+ await waitFor(() =>+ expect(screen.getByTestId("value")).toHaveTextContent("other"),+ );+ expect(screen.getByLabelText("Describe your role")).toBeInTheDocument();+ });++ it("opens in Other mode for a stored free-text value", () => {+ render(<Harness initial="Practice manager" />);++ expect(screen.getByLabelText("Describe your role")).toHaveValue(+ "Practice manager",+ );+ });++ it("clears the answer via the opt-out", async () => {+ const user = userEvent.setup();+ render(<Harness initial="recruiter" />);++ await user.click(screen.getByRole("combobox"));+ await user.click(screen.getByRole("option", { name: "Prefer not to say" }));++ await waitFor(() =>+ expect(screen.getByTestId("value")).toHaveTextContent("null"),+ );+ expect(+ screen.queryByLabelText("Describe your role"),+ ).not.toBeInTheDocument();+ });+});diff --git a/apps/web/src/features/user/components/job-title-select.tsx b/apps/web/src/features/user/components/job-title-select.tsxnew file mode 100644index 000000000..241d51a74--- /dev/null+++ b/apps/web/src/features/user/components/job-title-select.tsx@@ -0,0 +1,188 @@+"use client";++import { Input } from "@rallly/ui/input";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@rallly/ui/select";+import React from "react";+import type { JobTitle } from "@/features/user/constants";+import {+ JOB_TITLE_OTHER_MAX_LENGTH,+ jobTitles,+} from "@/features/user/constants";+import { Trans, useTranslation } from "@/i18n/client";++// Base UI treats null as "nothing selected"; the picklist needs a real value+// to hang the opt-out on, so it gets a sentinel that maps back to null.+const NONE_VALUE = "none";++function isPicklistValue(value: string): value is JobTitle {+ return (jobTitles as readonly string[]).includes(value);+}++function JobTitleLabel({ jobTitle }: { jobTitle: JobTitle }) {+ switch (jobTitle) {+ case "executive_assistant":+ return (+ <Trans+ i18nKey="jobTitleExecutiveAssistant"+ defaults="Executive assistant"+ />+ );+ case "administrator_or_coordinator":+ return (+ <Trans+ i18nKey="jobTitleAdministratorOrCoordinator"+ defaults="Administrator or coordinator"+ />+ );+ case "manager_or_team_lead":+ return (+ <Trans+ i18nKey="jobTitleManagerOrTeamLead"+ defaults="Manager or team lead"+ />+ );+ case "recruiter":+ return <Trans i18nKey="jobTitleRecruiter" defaults="Recruiter" />;+ case "teacher_or_lecturer":+ return (+ <Trans+ i18nKey="jobTitleTeacherOrLecturer"+ defaults="Teacher or lecturer"+ />+ );+ case "healthcare_practitioner":+ return (+ <Trans+ i18nKey="jobTitleHealthcarePractitioner"+ defaults="Healthcare practitioner"+ />+ );+ case "consultant_or_freelancer":+ return (+ <Trans+ i18nKey="jobTitleConsultantOrFreelancer"+ defaults="Consultant or freelancer"+ />+ );+ case "founder_or_owner":+ return (+ <Trans i18nKey="jobTitleFounderOrOwner" defaults="Founder or owner" />+ );+ case "sales":+ return <Trans i18nKey="jobTitleSales" defaults="Sales" />;+ case "other":+ return <Trans i18nKey="jobTitleOther" defaults="Other" />;+ }+}++/**+ * Role picker. The stored value is either a picklist key or, behind "Other",+ * whatever the user typed — one value, so the caller stores exactly what it+ * receives. Picking "Other" and typing nothing still stores "other": "none of+ * these fit" is an answer worth keeping, and the free text is what the v2+ * taxonomy will be built from.+ */+export function JobTitleSelect({+ value,+ onValueChange,+ disabled,+ id,+}: {+ value?: string | null;+ onValueChange: (value: string | null) => void;+ disabled?: boolean;+ id?: string;+}) {+ const { t } = useTranslation();++ const startsCustom = Boolean(value) && !isPicklistValue(value as string);++ // The text lives here rather than in the stored value so clearing the input+ // doesn't collapse the selection back to "nothing chosen".+ const [otherText, setOtherText] = React.useState(+ startsCustom ? (value as string) : "",+ );++ // "Other" is held as its own state rather than derived from the value.+ // Deriving it meant typing free text that happens to match a picklist key —+ // "sales", "recruiter", "other" — flipped the select to that entry and+ // unmounted the input mid-keystroke, silently discarding what was typed.+ const [isOther, setIsOther] = React.useState(startsCustom);++ // Unset renders the placeholder rather than "Prefer not to say" — an+ // untouched optional field hasn't been answered either way, and the opt-out+ // item exists to clear a value that was set.+ const selected = isOther ? "other" : (value ?? null);++ return (+ <div className="space-y-2">+ <Select<string | null, false>+ items={[+ {+ value: NONE_VALUE,+ label: t("jobTitleNone", { defaultValue: "Prefer not to say" }),+ },+ ...jobTitles.map((jobTitle) => ({+ value: jobTitle,+ label: <JobTitleLabel jobTitle={jobTitle} />,+ })),+ ]}+ value={selected}+ onValueChange={(next) => {+ setIsOther(next === "other");++ if (next === NONE_VALUE) {+ onValueChange(null);+ } else if (next === "other") {+ onValueChange(otherText.trim() || "other");+ } else {+ onValueChange(next as JobTitle);+ }+ }}+ disabled={disabled}+ >+ <SelectTrigger id={id} className="w-full">+ <SelectValue+ placeholder={t("jobTitlePlaceholder", {+ defaultValue: "Select a role...",+ })}+ />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value={NONE_VALUE}>+ <Trans i18nKey="jobTitleNone" defaults="Prefer not to say" />+ </SelectItem>+ {jobTitles.map((jobTitle) => (+ <SelectItem key={jobTitle} value={jobTitle}>+ <JobTitleLabel jobTitle={jobTitle} />+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ {isOther ? (+ <Input+ value={otherText}+ maxLength={JOB_TITLE_OTHER_MAX_LENGTH}+ disabled={disabled}+ aria-label={t("jobTitleOtherLabel", {+ defaultValue: "Describe your role",+ })}+ placeholder={t("jobTitleOtherPlaceholder", {+ defaultValue: "e.g. Practice manager",+ })}+ onChange={(event) => {+ const next = event.target.value;+ setOtherText(next);+ onValueChange(next.trim() || "other");+ }}+ />+ ) : null}+ </div>+ );+}diff --git a/apps/web/src/features/user/constants.ts b/apps/web/src/features/user/constants.tsindex fc9fd9cd4..0c2cd77e5 100644--- a/apps/web/src/features/user/constants.ts+++ b/apps/web/src/features/user/constants.ts@@ -6,3 +6,31 @@ export const avatarAssetProfile = {accept: ["image/jpeg", "image/png"],maxSize: 2 * 1024 * 1024,} as const satisfies AssetProfile;++/**+ * Self-declared role. A property of the person, not the organization, so it+ * lives on User. The list mixes occupation with seniority on purpose:+ * "founder_or_owner" and the like are catch-alls meaning "no specific+ * occupation fits". Free text behind "other" is the instrument for building+ * a v2 list.+ */+export const jobTitles = [+ "executive_assistant",+ "administrator_or_coordinator",+ "manager_or_team_lead",+ "recruiter",+ "teacher_or_lecturer",+ "healthcare_practitioner",+ "consultant_or_freelancer",+ "founder_or_owner",+ "sales",+ "other",+] as const;++export type JobTitle = (typeof jobTitles)[number];++/**+ * Cap on the free text revealed by picking "other" for the role. Long enough+ * for a real job title, short enough that the values stay groupable.+ */+export const JOB_TITLE_OTHER_MAX_LENGTH = 100;diff --git a/apps/web/src/features/user/schema.test.ts b/apps/web/src/features/user/schema.test.tsnew file mode 100644index 000000000..61276ad82--- /dev/null+++ b/apps/web/src/features/user/schema.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from "vitest";+import { JOB_TITLE_OTHER_MAX_LENGTH } from "@/features/user/constants";+import { jobTitleFieldSchema } from "@/features/user/schema";++describe("jobTitleFieldSchema", () => {+ // Better-Auth runs an additional field's validator against every value that+ // isn't `undefined`, so a non-nullable schema here would make the field+ // impossible to erase — and an un-withdrawable answer can't rest on consent.+ it("accepts null, which is how the answer is withdrawn", () => {+ expect(jobTitleFieldSchema.parse(null)).toBeNull();+ });++ it("accepts a picklist key", () => {+ expect(jobTitleFieldSchema.parse("executive_assistant")).toBe(+ "executive_assistant",+ );+ });++ it("trims free text, since the parsed value is what gets stored", () => {+ expect(jobTitleFieldSchema.parse(" Practice manager ")).toBe(+ "Practice manager",+ );+ });++ it("rejects blank and whitespace-only free text", () => {+ expect(jobTitleFieldSchema.safeParse("").success).toBe(false);+ expect(jobTitleFieldSchema.safeParse(" ").success).toBe(false);+ });++ it("caps free text length", () => {+ const atLimit = "a".repeat(JOB_TITLE_OTHER_MAX_LENGTH);+ expect(jobTitleFieldSchema.parse(atLimit)).toBe(atLimit);+ expect(jobTitleFieldSchema.safeParse(`${atLimit}a`).success).toBe(false);+ });+});diff --git a/apps/web/src/features/user/schema.ts b/apps/web/src/features/user/schema.tsindex 54d22befa..94a59578b 100644--- a/apps/web/src/features/user/schema.ts+++ b/apps/web/src/features/user/schema.ts@@ -1,10 +1,33 @@import type { TimeFormat } from "@rallly/database";import * as z from "zod";+import { JOB_TITLE_OTHER_MAX_LENGTH } from "@/features/user/constants";export const userRoleSchema = z.enum(["admin", "user"]);export type UserRole = z.infer<typeof userRoleSchema>;+/**+ * Either a key from the `jobTitles` picklist or, behind "other", whatever the+ * user typed — one column for both. A free-text answer is a job title like+ * any other, and keeping them together is what lets the values be counted+ * when building a v2 taxonomy. Null clears the answer: consent is the legal+ * basis for holding it, so it has to stay withdrawable.+ */+export const jobTitleSchema = z+ .string()+ .trim()+ .min(1)+ .max(JOB_TITLE_OTHER_MAX_LENGTH);++/**+ * The same rule, plus the null that clears the field. Better-Auth runs a+ * field's validator against every value that isn't `undefined`, so the+ * `jobTitle` additional field has to accept null explicitly or erasing it+ * fails validation — which would leave the answer un-withdrawable and consent+ * unworkable as its legal basis.+ */+export const jobTitleFieldSchema = jobTitleSchema.nullable();+export type UserDTO = {id: string;name: string;diff --git a/apps/web/src/lib/auth.ts b/apps/web/src/lib/auth.tsindex d33feee2a..3432b1927 100644--- a/apps/web/src/lib/auth.ts+++ b/apps/web/src/lib/auth.ts@@ -28,6 +28,7 @@ import { linkAnonymousUser } from "@/features/auth/mutations";import { isEmailBlocked, isTemporaryEmail } from "@/features/auth/utils";import { getStripe } from "@/features/billing/service";import type { UserDTO } from "@/features/user/schema";+import { jobTitleFieldSchema } from "@/features/user/schema";import { getTranslation } from "@/i18n/server";import { getLocale } from "@/i18n/server/get-locale";import { SESSION_TTL_SECONDS } from "@/lib/auth-config";@@ -253,6 +254,17 @@ export const authLib = betterAuth({input: true,required: false,},+ // `input: true` is what lets the field be written at all — the update+ // endpoint rejects fields marked otherwise — so it is reachable from+ // authClient.updateUser too. The validator bounds it there as well as+ // on the server actions that normally write it, and trims what it+ // stores: Better-Auth persists the value the validator returns.+ jobTitle: {+ type: "string",+ input: true,+ required: false,+ validator: { input: jobTitleFieldSchema },+ },},},secondaryStorage: kvdiff --git a/packages/database/prisma/migrations/20260821000000_add_professional_segment_fields/migration.sql b/packages/database/prisma/migrations/20260821000000_add_professional_segment_fields/migration.sqlnew file mode 100644index 000000000..6984018da--- /dev/null+++ b/packages/database/prisma/migrations/20260821000000_add_professional_segment_fields/migration.sql@@ -0,0 +1,9 @@+-- CreateEnum+CREATE TYPE "space_types" AS ENUM ('personal', 'work');++-- AlterTable+ALTER TABLE "spaces" ADD COLUMN "space_type" "space_types",+ADD COLUMN "industry" TEXT;++-- AlterTable+ALTER TABLE "users" ADD COLUMN "job_title" TEXT;diff --git a/packages/database/prisma/models/space.prisma b/packages/database/prisma/models/space.prismaindex 5ec95e028..2a3a7b2cd 100644--- a/packages/database/prisma/models/space.prisma+++ b/packages/database/prisma/models/space.prisma@@ -1,9 +1,14 @@model Space {- id String @id @default(uuid())+ id String @id @default(uuid())name Stringimage String?- ownerId String @map("owner_id")- tier SpaceTier @default(hobby)+ ownerId String @map("owner_id")+ tier SpaceTier @default(hobby)+ spaceType SpaceType? @map("space_type")+ // Self-declared sector, optional. Stored as a string rather than an enum+ // because the taxonomy is expected to change; validation lives in+ // features/space/schema.ts.+ industry String?primaryColor String? @map("primary_color")showBranding Boolean @default(false) @map("show_branding")hideAttribution Boolean @default(false) @map("hide_attribution")@@ -32,6 +37,13 @@ enum SpaceMemberRole {MEMBER}+enum SpaceType {+ personal+ work++ @@map("space_types")+}+enum SpaceTier {hobbyprodiff --git a/packages/database/prisma/models/user.prisma b/packages/database/prisma/models/user.prismaindex b187a44ca..aa2f40a12 100644--- a/packages/database/prisma/models/user.prisma+++ b/packages/database/prisma/models/user.prisma@@ -58,6 +58,10 @@ model User {isAnonymous Boolean @default(false) @map("anonymous")lastSeenAt DateTime @default(now()) @map("last_seen_at")deletedAt DateTime? @map("deleted_at")+ // Self-declared role, optional. Free-form string rather than an enum so+ // the taxonomy can change without a migration; validation lives in+ // features/user/schema.ts.+ jobTitle String? @map("job_title")comments Comment[]polls Poll[]diff --git a/packages/posthog/.env.sample b/packages/posthog/.env.sampleindex 71994a1a5..c245e45bc 100644--- a/packages/posthog/.env.sample+++ b/packages/posthog/.env.sample@@ -1,4 +1,5 @@# purge-guest-profiles: personal API key with query:read and person:write scopes+# backfill-space-type: the same key, needs only query:read# https://app.posthog.com/settings/user-api-keysPOSTHOG_PERSONAL_API_KEY=POSTHOG_PROJECT_ID=diff --git a/packages/posthog/package.json b/packages/posthog/package.jsonindex 53ef03784..25c22d273 100644--- a/packages/posthog/package.json+++ b/packages/posthog/package.json@@ -9,6 +9,7 @@},"scripts": {"backfill-space-group-properties": "dotenv -e .env -- pnpx tsx ./src/scripts/backfill-space-group-properties.ts",+ "backfill-space-type": "dotenv -e .env -- pnpx tsx ./src/scripts/backfill-space-type.ts","purge-guest-profiles": "dotenv -e .env -- pnpx tsx ./src/scripts/purge-guest-profiles.ts","test:unit": "vitest run","type-check": "tsc --noEmit"diff --git a/packages/posthog/src/scripts/backfill-space-type.ts b/packages/posthog/src/scripts/backfill-space-type.tsnew file mode 100644index 000000000..ee34f555c--- /dev/null+++ b/packages/posthog/src/scripts/backfill-space-type.ts@@ -0,0 +1,241 @@+import { prisma } from "@rallly/database";++/**+ * Backfills `Space.spaceType` from PostHog history.+ *+ * The setup flow has always asked whether a space is personal or for work,+ * but until this feature the answer only reached PostHog as the `space_type`+ * property on `space_setup` — never the database, so it could not be joined+ * in SQL. Every one of those events names its space through the `space`+ * group key, which is what makes the answer recoverable.+ *+ * Spaces created before the `space_setup` event existed, and spaces whose+ * event is outside PostHog's retention window, stay null. Null is not a+ * third value: it means unknown, and the product treats it as "not a work+ * space" (no prompt, no alert).+ *+ * Only fills nulls. A space whose type the user has since confirmed in the+ * app is never overwritten by a historical event.+ *+ * DRY RUN by default — prints totals and a sample. Pass --apply to write.+ *+ * Usage:+ * pnpm --filter @rallly/posthog backfill-space-type+ * pnpm --filter @rallly/posthog backfill-space-type -- --apply+ *+ * Requires in packages/posthog/.env (see .env.sample):+ * POSTHOG_PERSONAL_API_KEY personal API key with query:read+ * POSTHOG_PROJECT_ID+ * POSTHOG_API_HOST optional, defaults to https://us.posthog.com+ * DATABASE_URL+ */++const API_HOST = process.env.POSTHOG_API_HOST ?? "https://us.posthog.com";+const PROJECT_ID = process.env.POSTHOG_PROJECT_ID;+const API_KEY = process.env.POSTHOG_PERSONAL_API_KEY;++const SAMPLE_SIZE = 10;+// HogQL rows per keyset page. OFFSET is rejected for personal API keys, so+// pagination walks the group key instead.+const PAGE_SIZE = 10000;+// Postgres caps a statement at 65535 bind parameters; updateMany takes one+// per id plus the value, so stay well clear.+const UPDATE_BATCH_SIZE = 1000;+const MAX_RATE_LIMIT_RETRIES = 5;++function sleep(ms: number) {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++async function apiRequest({+ path,+ method = "GET",+ body,+}: {+ path: string;+ method?: "GET" | "POST";+ body?: unknown;+}) {+ for (let attempt = 0; ; attempt++) {+ const res = await fetch(`${API_HOST}${path}`, {+ method,+ headers: {+ Authorization: `Bearer ${API_KEY}`,+ "Content-Type": "application/json",+ },+ body: body ? JSON.stringify(body) : undefined,+ });++ if (res.status === 429) {+ if (attempt >= MAX_RATE_LIMIT_RETRIES) {+ throw new Error(`Rate limited on ${path} after ${attempt} retries`);+ }+ const retryAfter = Number(res.headers.get("Retry-After")) || 60;+ console.info(`⏳ Rate limited — waiting ${retryAfter}s before retrying`);+ await sleep(retryAfter * 1000);+ continue;+ }++ if (!res.ok) {+ throw new Error(`${method} ${path} → ${res.status}: ${await res.text()}`);+ }++ return res.status === 204 ? null : res.json();+ }+}++async function hogqlQuery(query: string): Promise<unknown[][]> {+ const data = await apiRequest({+ path: `/api/projects/${PROJECT_ID}/query/`,+ method: "POST",+ body: { query: { kind: "HogQLQuery", query } },+ });+ return data.results ?? [];+}++// Escape a space id for safe interpolation into a HogQL string literal. The+// values come from PostHog itself, but keep the escape so a malformed one+// can't break out of the literal.+function quote(value: string): string {+ return value.replaceAll("\\", "\\\\").replaceAll("'", "\\'");+}++type SpaceType = "personal" | "work";++/**+ * One row per space: its id and the type it was set up as. A space can have+ * more than one `space_setup` event (the action is retry-safe), so collapse+ * to the earliest — the first answer is the one the user gave at setup.+ *+ * Pagination is driven by the raw page, not by `records`. Rows with an+ * unrecognised space_type are dropped from `records`, so a full page holding+ * even one of them would otherwise look short and end the run early, leaving+ * every later space null.+ */+async function fetchSetupPage(after?: string): Promise<{+ records: Array<{ spaceId: string; spaceType: SpaceType }>;+ lastSpaceId?: string;+ isLastPage: boolean;+}> {+ const rows = await hogqlQuery(`+ SELECT+ $group_0 AS space_id,+ argMin(properties.space_type, timestamp) AS space_type+ FROM events+ WHERE event = 'space_setup'+ AND $group_0 != ''+ ${after ? `AND $group_0 > '${quote(after)}'` : ""}+ GROUP BY space_id+ ORDER BY space_id ASC+ LIMIT ${PAGE_SIZE}+ `);++ // Annotated so the literal keeps the narrowed union rather than widening+ // spaceType to string — the return type no longer supplies that context.+ const records: Array<{ spaceId: string; spaceType: SpaceType }> =+ rows.flatMap(([spaceId, spaceType]) =>+ typeof spaceId === "string" &&+ (spaceType === "personal" || spaceType === "work")+ ? [{ spaceId, spaceType }]+ : [],+ );++ const lastSpaceId = rows.at(-1)?.[0];++ if (lastSpaceId !== undefined && typeof lastSpaceId !== "string") {+ // The cursor is the only thing advancing the scan; a non-string here+ // would silently restart it from the same place forever.+ throw new Error("HogQL returned a non-string space_id");+ }++ return {+ records,+ lastSpaceId,+ isLastPage: rows.length < PAGE_SIZE,+ };+}++(async function backfillSpaceType() {+ const apply = process.argv.slice(2).includes("--apply");++ if (!process.env.DATABASE_URL || !API_KEY || !PROJECT_ID) {+ console.error(+ "❌ POSTHOG_PERSONAL_API_KEY, POSTHOG_PROJECT_ID and DATABASE_URL must be set — see packages/posthog/.env.sample",+ );+ process.exit(1);+ }++ console.info(+ apply+ ? "⚠️ APPLY mode — spaces with no stored type will be updated.\n"+ : "🔍 DRY RUN — nothing will be written. Pass --apply to write.\n",+ );++ const byType: Record<SpaceType, string[]> = {+ personal: [],+ work: [],+ };++ let after: string | undefined;++ console.info(`📸 Reading space_setup events (HogQL, ${PAGE_SIZE}/page)…`);++ for (;;) {+ const { records, lastSpaceId, isLastPage } = await fetchSetupPage(after);++ for (const { spaceId, spaceType } of records) {+ byType[spaceType].push(spaceId);++ if (+ !apply &&+ byType.personal.length + byType.work.length <= SAMPLE_SIZE+ ) {+ console.info(`• ${spaceId} → ${spaceType}`);+ }+ }++ if (isLastPage || lastSpaceId === undefined) {+ break;+ }++ after = lastSpaceId;+ }++ const found = byType.personal.length + byType.work.length;+ let updated = 0;++ try {+ for (const spaceType of ["personal", "work"] as const) {+ const ids = byType[spaceType];++ for (let i = 0; i < ids.length; i += UPDATE_BATCH_SIZE) {+ const batch = ids.slice(i, i + UPDATE_BATCH_SIZE);++ // `spaceType: null` in the filter is what keeps this idempotent and+ // non-destructive: a value set in the app always wins over history.+ const where = { id: { in: batch }, spaceType: null };++ if (apply) {+ const result = await prisma.space.updateMany({+ where,+ data: { spaceType },+ });+ updated += result.count;+ } else {+ updated += await prisma.space.count({ where });+ }+ }+ }+ } finally {+ await prisma.$disconnect();+ }++ console.info(+ apply+ ? `\n📊 Done: ${found} space(s) resolved from PostHog, ${updated} updated (the rest already had a type or no longer exist).`+ : `\n🔍 Dry run complete: ${found} space(s) resolved from PostHog, ${updated} would be updated. Re-run with --apply to write.`,+ );+})().catch((error) => {+ console.error(`❌ ${error instanceof Error ? error.message : error}`);+ process.exit(1);+});