diff --git a/.github/workflows/repo-checks.yml b/.github/workflows/repo-checks.yml index 99606a1a9..b183e37e1 100644 --- a/.github/workflows/repo-checks.yml +++ b/.github/workflows/repo-checks.yml @@ -96,6 +96,7 @@ jobs: tests/integration/ballotQuestions.test.ts tests/integration/backfillTestimonyScope.test.ts tests/integration/conferences.test.ts + tests/integration/conferenceFollowing.test.ts components/auth/hooks.test.ts components/db/useUpcoming.test.ts components/db/testimony diff --git a/components/EditProfilePage/FollowingTab.tsx b/components/EditProfilePage/FollowingTab.tsx index e7f6f9ba3..9170fcb82 100644 --- a/components/EditProfilePage/FollowingTab.tsx +++ b/components/EditProfilePage/FollowingTab.tsx @@ -2,10 +2,13 @@ import { flags } from "components/featureFlags" import { dbService } from "components/db/api" import { useBill } from "components/db" import { formatBillId } from "components/formatting" -import { Internal } from "components/links" +import { Internal, maple } from "components/links" +import { conferenceName, isShown } from "components/conference/types" +import { getConference } from "components/db/conferences" import { FollowBallotQuestionButton, - FollowBillButton + FollowBillButton, + FollowConferenceTopicButton } from "components/shared/FollowButton" import { collection, onSnapshot, query, where } from "firebase/firestore" import { useTranslation } from "next-i18next" @@ -23,6 +26,7 @@ import { export function FollowingTab({ className }: { className?: string }) { const { t } = useTranslation("editProfile") const followedBallotQuestions = useFollowedBallotQuestions() + const followedConferences = useFollowedConferences() return ( <> )} + {flags().conferences && ( + + )} > => useTopicSubscription("ballotQuestion") +const useFollowedConferences = (): LoadableItemsState< + ComponentProps +> => useTopicSubscription("conference") + const useFollowedUsers = (): LoadableItemsState< ComponentProps > => useTopicSubscription("testimony") +/** The field of a subscription doc that says what is followed, by type. */ +const TOPIC_KEYS = { + bill: "billLookup", + ballotQuestion: "ballotQuestionLookup", + conference: "conferenceLookup", + testimony: "userLookup" +} as const + function useTopicSubscription( - type: "bill" | "ballotQuestion" | "testimony" + type: keyof typeof TOPIC_KEYS ): LoadableItemsState { const [state, setState] = useState>({ items: [], @@ -78,12 +102,7 @@ function useTopicSubscription( : null, [uid] ) - const topicKey = - type === "bill" - ? "billLookup" - : type === "ballotQuestion" - ? "ballotQuestionLookup" - : "userLookup" + const topicKey = TOPIC_KEYS[type] useEffect(() => { if (!subscriptionRef || !uid) return @@ -190,3 +209,49 @@ function FollowedBallotQuestionCard({ ) } + +/** A followed conference. One that is hidden, no longer taking input while + * closed conferences are off, keeps its row without a link, so the reader can + * still unfollow it. */ +function FollowedConferenceCard({ + conferenceId, + court +}: { + conferenceId: string + court: number +}) { + const { t } = useTranslation("editProfile") + const uid = useAuth().user?.uid + const { + loading, + error, + result: conference + } = useAsync(() => getConference(court, conferenceId), [court, conferenceId]) + if (loading) return + if (error) return {t("content.error")} + + const shown = conference && isShown(conference) + + return ( +
+ + + {shown ? ( + + {conferenceName(conference)} + + ) : ( +
{conference ? conferenceName(conference) : conferenceId}
+ )} + + + + +
+
+
+ ) +} diff --git a/components/Newsfeed/Newsfeed.tsx b/components/Newsfeed/Newsfeed.tsx index 57be0a7a5..f41109148 100644 --- a/components/Newsfeed/Newsfeed.tsx +++ b/components/Newsfeed/Newsfeed.tsx @@ -252,9 +252,12 @@ export default function Newsfeed() { billId={element.billId} bodyText={element.bodyText} conferenceId={element.conferenceId} + conferenceName={element.conferenceName} + cosignOf={element.cosignOf} court={element.court} header={element.header} isBillMatch={element.isBillMatch} + isConferenceMatch={element.isConferenceMatch} isUserMatch={element.isUserMatch} isBallotQuestionMatch={ element.isBallotQuestionMatch diff --git a/components/Newsfeed/NotificationProps.tsx b/components/Newsfeed/NotificationProps.tsx index a9ba4211e..63787cc14 100644 --- a/components/Newsfeed/NotificationProps.tsx +++ b/components/Newsfeed/NotificationProps.tsx @@ -1,4 +1,7 @@ import { Timestamp } from "firebase/firestore" +import type { CosignOf } from "functions/src/notifications/types" + +export type { CosignOf } export type NotificationProps = { authorUid: string // Testimony author @@ -25,6 +28,9 @@ export type NotificationProps = { ballotStatus?: string // Set on testimony to a committee of conference conferenceId?: string | null + conferenceName?: string | null + isConferenceMatch?: boolean // is subscribed to the conference + cosignOf?: CosignOf | null // set when the testimony cosigns another } export type Notifications = NotificationProps[] diff --git a/components/NewsfeedCard/NewsfeedCard.test.tsx b/components/NewsfeedCard/NewsfeedCard.test.tsx index 094481630..984a709e7 100644 --- a/components/NewsfeedCard/NewsfeedCard.test.tsx +++ b/components/NewsfeedCard/NewsfeedCard.test.tsx @@ -106,6 +106,102 @@ describe("NewsfeedCard", () => { expect(document.querySelector("a[href^='/testimony/']")).toBeNull() }) + it("says a reader follows the conference, by name, when that is the match", () => { + render( + + ) + + const reason = screen.getByText("newsfeed.follow").closest(".card-title")! + expect(reason).toHaveTextContent("newsfeed.followPhone-Free Schools") + expect(reason).not.toHaveTextContent("Alice") + }) + + it("names the conference and the author when the reader follows both", () => { + render( + + ) + + // With no name stored, the conference goes by its bill's title. + const titles = Array.from(document.querySelectorAll(".card-title")) + expect(titles.map(t => t.textContent)).toContain( + "newsfeed.followAn Act relative to student learningnewsfeed.andAlice" + ) + }) + + describe("a cosign", () => { + const cosignOf = { + authorName: "Grace", + content: "Pass a strong final bill this session." + } + const quoted = () => document.querySelector("blockquote") + + it("is tagged, with its own line first and the cosigned input under it", () => { + render( + + ) + + expect(screen.getByText("newsfeed.cosigned")).toBeInTheDocument() + expect(screen.getByText("newsfeed.conferenceCosign")).toBeInTheDocument() + expect(screen.queryByText("newsfeed.conferenceInput")).toBeNull() + const line = screen.getByText('"As a parent, this matters to me."') + const credit = screen.getByText("newsfeed.cosignedInput") + expect( + line.compareDocumentPosition(credit) & Node.DOCUMENT_POSITION_FOLLOWING + ).toBeTruthy() + expect(quoted()).toHaveTextContent(cosignOf.content) + }) + + it("shows the cosigned input without an empty quote when it has no line", () => { + render( + + ) + + expect(screen.getByText("newsfeed.cosigned")).toBeInTheDocument() + expect(screen.queryByText('""')).toBeNull() + expect(screen.getByText("newsfeed.cosignedInput")).toBeInTheDocument() + expect(quoted()).toHaveTextContent(cosignOf.content) + }) + + it("isn't tagged on input that cosigns nothing", () => { + render( + + ) + + expect(screen.queryByText("newsfeed.cosigned")).toBeNull() + expect(screen.getByText("newsfeed.conferenceInput")).toBeInTheDocument() + expect(quoted()).toBeNull() + }) + }) + it("keeps bill testimony on its bill, testimony page and thumbs", () => { render() diff --git a/components/NewsfeedCard/NewsfeedCard.tsx b/components/NewsfeedCard/NewsfeedCard.tsx index 92ba56d64..055f55022 100644 --- a/components/NewsfeedCard/NewsfeedCard.tsx +++ b/components/NewsfeedCard/NewsfeedCard.tsx @@ -10,6 +10,7 @@ import { } from "./NewsfeedCardBody" import NewsfeedCardTitle from "./NewsfeedCardTitle" import { maple } from "components/links" +import { CosignOf } from "../Newsfeed/NotificationProps" const Container = styled.div` max-width: 700px; @@ -22,10 +23,13 @@ export const NewsfeedCard = (props: { billId?: string bodyText: string conferenceId?: string | null + conferenceName?: string | null + cosignOf?: CosignOf | null court?: string header: string isBallotQuestionMatch?: boolean isBillMatch?: boolean + isConferenceMatch?: boolean isUserMatch?: boolean position?: string subheader?: string @@ -45,10 +49,13 @@ export const NewsfeedCard = (props: { authorUid={props.authorUid} billId={props.billId} conferenceHref={conferenceHref} + conferenceName={props.conferenceName} + cosigned={!!props.cosignOf} court={props.court} header={props.header} isBallotQuestionMatch={props.isBallotQuestionMatch} isBillMatch={props.isBillMatch} + isConferenceMatch={props.isConferenceMatch} isUserMatch={props.isUserMatch} subheader={props.subheader} timestamp={formattedTimestamp} @@ -71,6 +78,7 @@ export const NewsfeedCard = (props: { { ) } -/** Testimony on a committee of conference: the stance is the conference - * page's chip, and the card leads to the conference, not the bill. */ +/** + * Testimony on a committee of conference: the stance is the conference page's + * chip, and the card leads to the conference, not the bill. A cosign is + * tagged, with the cosigner's own line first when they wrote one and the + * input they cosigned quoted under it, as the email to their legislators sets + * it out. That quote arrives already trimmed. + */ export const NewsfeedConferenceTestimonyCardBody = (props: { billText?: string conferenceHref: string + cosignOf?: CosignOf | null position?: string text?: string timestamp?: string }) => { - const { billText, conferenceHref, text, timestamp } = props + const { billText, conferenceHref, cosignOf, text, timestamp } = props const { t } = useTranslation("common") return ( @@ -215,13 +222,28 @@ export const NewsfeedConferenceTestimonyCardBody = (props: { {billText}
- {ConferencePosition.guard(props.position) && ( - +
+ {ConferencePosition.guard(props.position) && ( + + )} + {cosignOf && {t("newsfeed.cosigned")}} +
+ {(text || !cosignOf) && ( + {`"${truncateText( + text, + 600 + )}"`} + )} + {cosignOf && ( + <> +
+ {t("newsfeed.cosignedInput", { name: cosignOf.authorName })} +
+
+ {cosignOf.content} +
+ )} - {`"${truncateText( - text, - 600 - )}"`}
diff --git a/components/NewsfeedCard/NewsfeedCardTitle.tsx b/components/NewsfeedCard/NewsfeedCardTitle.tsx index a49f76f42..673329d84 100644 --- a/components/NewsfeedCard/NewsfeedCardTitle.tsx +++ b/components/NewsfeedCard/NewsfeedCardTitle.tsx @@ -9,6 +9,10 @@ interface NewsfeedCardTitleProps { billId?: string /** Set on testimony to a committee of conference: its conference page */ conferenceHref?: string + /** The conference's name, for a reader who follows it */ + conferenceName?: string | null + /** The testimony cosigns another */ + cosigned?: boolean court?: string header?: string subheader?: string @@ -17,6 +21,7 @@ interface NewsfeedCardTitleProps { inHeaderElement?: ReactElement isBallotQuestionMatch?: boolean isBillMatch?: boolean + isConferenceMatch?: boolean isUserMatch?: boolean type?: string userRole?: string @@ -28,10 +33,13 @@ export const NewsfeedCardTitle = (props: NewsfeedCardTitleProps) => { authorUid, billId, conferenceHref, + conferenceName, + cosigned, court, header, isBillMatch, isBallotQuestionMatch, + isConferenceMatch, isUserMatch, subheader, type, @@ -47,6 +55,7 @@ export const NewsfeedCardTitle = (props: NewsfeedCardTitleProps) => { authorUid={authorUid} billId={billId} conferenceHref={conferenceHref} + cosigned={cosigned} court={court} header={header} subheader={subheader} @@ -55,7 +64,9 @@ export const NewsfeedCardTitle = (props: NewsfeedCardTitleProps) => { {isNewsfeed ? ( { } const CardTitleHeadline = (props: NewsfeedCardTitleProps) => { - const { authorUid, billId, conferenceHref, court, header, subheader, type } = - props + const { + authorUid, + billId, + conferenceHref, + cosigned, + court, + header, + subheader, + type + } = props const { t } = useTranslation("common") + const action = !conferenceHref + ? "newsfeed.endorsed" + : cosigned + ? "newsfeed.conferenceCosign" + : "newsfeed.conferenceInput" switch (type) { case "testimony": @@ -118,11 +142,7 @@ const CardTitleHeadline = (props: NewsfeedCardTitleProps) => { {subheader} - {t( - conferenceHref - ? "newsfeed.conferenceInput" - : "newsfeed.endorsed" - )} + {t(action)} {billId && {formatBillId(billId)}} @@ -166,9 +186,11 @@ const CardTitleHeadline = (props: NewsfeedCardTitleProps) => { const CardTitleFollowing = (props: NewsfeedCardTitleProps) => { const { billId, + conferenceName, header, isBallotQuestionMatch, isBillMatch, + isConferenceMatch, isUserMatch, subheader, type @@ -211,6 +233,21 @@ const CardTitleFollowing = (props: NewsfeedCardTitleProps) => { )} ) + } else if (isConferenceMatch) { + return ( + + {t("newsfeed.follow")} + {conferenceName || header} + {isUserMatch && ( + <> + {t("newsfeed.and")} + {subheader} + + )} + + ) } else if (isBillMatch && isUserMatch) { return ( ({ useFlags: () => ({ legislators: false, hearingsAndTranscriptions: true }) })) jest.mock("../hooks", () => ({ useAppDispatch: () => jest.fn() })) +// Following has its own tests; here it is a switch. +let mockFollowVisible = false +jest.mock("./FollowConference", () => ({ + ...jest.requireActual("./FollowConference"), + useConferenceFollow: () => ({ + visible: mockFollowVisible, + following: false, + toggle: jest.fn() + }) +})) jest.mock("./input/useFollowedAuthors", () => ({ useFollowedAuthors: () => new Set() })) diff --git a/components/conference/ConferenceDetails.test.tsx b/components/conference/ConferenceDetails.test.tsx index d867c2a5d..a1d2e4135 100644 --- a/components/conference/ConferenceDetails.test.tsx +++ b/components/conference/ConferenceDetails.test.tsx @@ -128,6 +128,16 @@ jest.mock("../hooks", () => ({ useAppDispatch: () => mockDispatch })) // A card's actions reach for the report API; the page's own tests do not. jest.mock("./input/Kebab", () => ({ Kebab: () => null })) jest.mock("./input/EntryModal", () => ({ EntryModal: () => null })) +// Following has its own tests; here it is a switch. +let mockFollowVisible = false +jest.mock("./FollowConference", () => ({ + ...jest.requireActual("./FollowConference"), + useConferenceFollow: () => ({ + visible: mockFollowVisible, + following: false, + toggle: jest.fn() + }) +})) jest.mock("./input/useFollowedAuthors", () => ({ useFollowedAuthors: () => new Set() })) @@ -445,6 +455,39 @@ describe("ConferenceDetails", () => { expect(screen.getByText("input.empty_title")).toBeInTheDocument() }) + describe("the Follow control", () => { + afterEach(() => { + mockFollowVisible = false + }) + + it("sits beside the title's button while the conference takes input", () => { + mockFollowVisible = true + render() + const follow = screen.getByRole("button", { name: "follow.follow" }) + const [share] = screen.getAllByRole("button", { name: "input.share" }) + expect(follow.parentElement).toBe(share.parentElement) + }) + + it("stands alone on a closed conference, where it is shown", () => { + mockFollowVisible = true + const enacted = { ...conference, status: "enacted" as const } + render() + expect( + screen.getByRole("button", { name: "follow.follow" }) + ).toBeInTheDocument() + expect( + screen.queryByRole("button", { name: "input.share" }) + ).not.toBeInTheDocument() + }) + + it("is absent where the hook hides it", () => { + render() + expect( + screen.queryByRole("button", { name: "follow.follow" }) + ).not.toBeInTheDocument() + }) + }) + it("greys the title's button once the reader has filed", () => { mockUser = { uid: "reader", emailVerified: true } mockItems = [ diff --git a/components/conference/ConferenceDetails.tsx b/components/conference/ConferenceDetails.tsx index 772ed6edc..80e116735 100644 --- a/components/conference/ConferenceDetails.tsx +++ b/components/conference/ConferenceDetails.tsx @@ -19,6 +19,7 @@ import styled from "styled-components" import { ConferenceByline } from "./ConferenceByline" import { ConferenceCommittee } from "./ConferenceCommittee" import { ConferenceDifferences } from "./ConferenceDifferences" +import { FollowConferenceButton, useConferenceFollow } from "./FollowConference" import { ConferencePicker } from "./ConferencePicker" import { ClosedFold, ConferenceRail } from "./ConferenceRail" import { ConferenceResolution, OutcomeFilter } from "./ConferenceResolution" @@ -78,18 +79,18 @@ const Shift = styled.div` * button; level with the title itself where there is no button. Below md the * picker stands for the title, with the link over it and the button under it * at the left. */ -const TitleRow = styled.div<{ $taking: boolean }>` +const TitleRow = styled.div<{ $actions: boolean }>` display: grid; grid-template-columns: minmax(0, 1fr) auto; - grid-template-areas: ${({ $taking }) => - $taking ? `". link" "title share"` : `"title link"`}; + grid-template-areas: ${({ $actions }) => + $actions ? `". link" "title share"` : `"title link"`}; align-items: center; gap: 0.5rem 24px; @media (max-width: 767.98px) { grid-template-columns: minmax(0, 1fr); - grid-template-areas: ${({ $taking }) => - $taking ? `"link" "picker" "share"` : `"link" "picker"`}; + grid-template-areas: ${({ $actions }) => + $actions ? `"link" "picker" "share"` : `"link" "picker"`}; } ` @@ -100,6 +101,9 @@ const Picker = styled.div` const Share = styled.div` grid-area: share; justify-self: end; + display: flex; + align-items: center; + gap: 18px; @media (max-width: 767.98px) { justify-self: start; @@ -264,6 +268,8 @@ function Details({ const followed = useFollowedAuthors(user?.uid) const subject = conferenceName(conference) const taking = takesTestimony(conference) + const follow = useConferenceFollow(conference) + const actions = taking || follow.visible const decided = differences.length > 0 || similarities.length > 0 // Once the report is filed, each question says how the law resolved it. const resolved = hasReport(conference) && differences.length > 0 @@ -485,7 +491,7 @@ function Details({ />
- + {subject} - {taking && ( + {actions && ( - + {follow.visible && ( + + )} + {taking && ( + + )} )} diff --git a/components/conference/FollowConference.test.tsx b/components/conference/FollowConference.test.tsx new file mode 100644 index 000000000..faeabadbb --- /dev/null +++ b/components/conference/FollowConference.test.tsx @@ -0,0 +1,127 @@ +import "@testing-library/jest-dom" +import { render, screen, waitFor } from "@testing-library/react" +import userEvent from "@testing-library/user-event" +import { useState } from "react" +import { FollowContext, OrgFollowStatus } from "../shared/FollowContext" +import { FollowConferenceButton, useConferenceFollow } from "./FollowConference" +import type { ConferenceStatus } from "../../functions/src/conferences/types" + +jest.mock("next-i18next", () => ({ + useTranslation: () => ({ t: (key: string) => key }) +})) + +const push = jest.fn() +jest.mock("next/router", () => ({ + useRouter: () => ({ push, asPath: "/conferences/194/phones" }) +})) + +const mockFlags = { notifications: true } +jest.mock("../featureFlags", () => ({ useFlags: () => mockFlags })) + +let uid: string | undefined +jest.mock("../auth", () => ({ + useAuth: () => ({ user: uid ? { uid } : null }) +})) + +let followed = false +jest.mock("../shared/FollowingQueries", () => ({ + ...jest.requireActual("../shared/FollowingQueries"), + followsTopic: jest.fn(async () => followed), + followConference: jest.fn(async () => {}), + unfollowConference: jest.fn(async () => {}) +})) +const queries = jest.requireMock("../shared/FollowingQueries") + +function Harness({ status }: { status: ConferenceStatus }) { + const follow = useConferenceFollow({ id: "phones", court: 194, status }) + return follow.visible ? ( + + ) : null +} + +function Page({ status = "appointed" }: { status?: ConferenceStatus }) { + const [followStatus, setFollowStatus] = useState({}) + return ( + + + + ) +} + +describe("following a conference", () => { + beforeEach(() => { + jest.clearAllMocks() + uid = undefined + followed = false + mockFlags.notifications = true + }) + + it("sends a signed-out reader to log in", async () => { + render() + + await userEvent.click(screen.getByRole("button", { name: "follow.follow" })) + + expect(queries.followConference).not.toHaveBeenCalled() + expect(push).toHaveBeenCalledWith( + "/login?redirect=%2Fconferences%2F194%2Fphones" + ) + }) + + it("follows, then unfollows, the conference on its topic", async () => { + uid = "reader" + render() + + const button = await screen.findByRole("button", { pressed: false }) + await userEvent.click(button) + expect(queries.followConference).toHaveBeenCalledWith("reader", { + id: "phones", + court: 194 + }) + expect(queries.followsTopic).toHaveBeenCalledWith( + "reader", + "conference-194-phones" + ) + expect(button).toHaveAttribute("aria-pressed", "true") + expect(button).toHaveTextContent("follow.following") + + await userEvent.click(button) + expect(queries.unfollowConference).toHaveBeenCalledWith("reader", { + id: "phones", + court: 194 + }) + expect(button).toHaveAttribute("aria-pressed", "false") + }) + + it("is hidden on a closed conference the reader doesn't follow", async () => { + uid = "reader" + render() + + await waitFor(() => expect(queries.followsTopic).toHaveBeenCalled()) + expect(screen.queryByRole("button")).not.toBeInTheDocument() + }) + + it("lets a follower unfollow a closed conference, and take it back", async () => { + uid = "reader" + followed = true + render() + + const button = await screen.findByRole("button", { pressed: true }) + await userEvent.click(button) + expect(queries.unfollowConference).toHaveBeenCalled() + // Still there, so the unfollow can be undone. + expect(button).toHaveAttribute("aria-pressed", "false") + + await userEvent.click(button) + expect(queries.followConference).toHaveBeenCalled() + }) + + it("is hidden behind the notifications flag", () => { + mockFlags.notifications = false + render() + + expect(screen.queryByRole("button")).not.toBeInTheDocument() + }) +}) diff --git a/components/conference/FollowConference.tsx b/components/conference/FollowConference.tsx new file mode 100644 index 000000000..6b3189374 --- /dev/null +++ b/components/conference/FollowConference.tsx @@ -0,0 +1,114 @@ +import { useTranslation } from "next-i18next" +import { useState } from "react" +import styled from "styled-components" +import { isSitting } from "../../functions/src/shared" +import { useAuth } from "../auth" +import { useFlags } from "../featureFlags" +import { useFollowTopic } from "../shared/FollowButton" +import { + conferenceTopicName, + followConference, + unfollowConference +} from "../shared/FollowingQueries" +import { Bell, BellOff, BellPlus, BellRing } from "./input/icons" +import { ConferenceSummary } from "./types" + +type Followable = Pick + +/** + * Following a conference sends its new input to the reader's newsfeed and + * digest. Once it no longer takes input nothing new can arrive, so the control + * is there only for a reader who already follows it, to unfollow; it stays + * once shown, so an unfollow can be taken back. + */ +export function useConferenceFollow(conference: Followable) { + const uid = useAuth().user?.uid + const { notifications } = useFlags() + const ref = { id: conference.id, court: conference.court } + const follow = useFollowTopic( + conferenceTopicName(conference.court, conference.id), + () => followConference(uid, ref), + () => unfollowConference(uid, ref), + notifications + ) + const [kept, setKept] = useState() + const closedFollowed = + !isSitting(conference) && follow.loaded && follow.following + if (closedFollowed && kept !== conference.id) setKept(conference.id) + // Setting state during render re-renders before commit, so once closedFollowed + // is true, kept already matches. + const visible = + notifications && (isSitting(conference) || kept === conference.id) + return { ...follow, visible } +} + +const Button = styled.button` + display: inline-flex; + flex-shrink: 0; + align-items: center; + gap: 6px; + padding: 0; + border: 0; + background: none; + color: var(--maple-brand-primary); + font-size: 0.875rem; + font-weight: 600; + white-space: nowrap; + cursor: pointer; + + &:hover { + color: var(--maple-brand-primary-strong); + } + + /* Each half swaps to the sign of what a press would do on hover, so the + outcome shows before it happens. */ + .on-hover { + display: none; + } + &:hover .on-hover { + display: inline-flex; + } + &:hover .off-hover { + display: none; + } +` + +/** + * The mockup's Follow control: a word and a bell, blue in both states, since + * it stays a control to press again and the icon and word say which way. + */ +export function FollowConferenceButton({ + following, + toggle +}: { + following: boolean + toggle: () => unknown +}) { + const { t } = useTranslation("conferences") + return ( + + ) +} diff --git a/components/conference/input/accounts.ts b/components/conference/input/accounts.ts index e998fc16d..023b8146a 100644 --- a/components/conference/input/accounts.ts +++ b/components/conference/input/accounts.ts @@ -1,5 +1,8 @@ import { Role } from "functions/src/auth/types" +/** The name an entry is shown under. */ +export { nameOf } from "functions/src/shared" + export type AccountType = "individual" | "organization" | "government" export const accountTypes: AccountType[] = [ @@ -15,10 +18,6 @@ export const accountTypeOf = (role: Role): AccountType => ? "government" : "individual" -/** The name an entry is shown under. */ -export const nameOf = (t: { fullName?: string; authorDisplayName: string }) => - t.fullName || t.authorDisplayName - /** Two letters for the disc, where the account has no picture of its own. */ export const initialsOf = (name: string) => name diff --git a/components/conference/input/icons.tsx b/components/conference/input/icons.tsx index a70800f24..e4bf3defe 100644 --- a/components/conference/input/icons.tsx +++ b/components/conference/input/icons.tsx @@ -182,3 +182,27 @@ export const Minimize2 = (p: Props) => ( ) + +const BellBase = () => +export const Bell = (p: Props) => ( + + + + +) +export const BellRing = (p: Props) => ( + + + + + + +) +export const BellOff = (p: Props) => ( + + + + + + +) diff --git a/components/conference/load.ts b/components/conference/load.ts index 2d92af8d7..421faaf96 100644 --- a/components/conference/load.ts +++ b/components/conference/load.ts @@ -1,5 +1,5 @@ import { districtId } from "functions/src/districts/normalize" -import { currentGeneralCourt, isSitting } from "functions/src/shared" +import { currentGeneralCourt } from "functions/src/shared" import type { Branch } from "../../functions/src/common" import { Conference, @@ -8,7 +8,6 @@ import { listConferences } from "../db/conferences" import { getEventSummary } from "../db/events" -import { flags } from "../featureFlags" import { getMember, getMemberSearchIndex, @@ -18,6 +17,7 @@ import { import { cells } from "./map/geometry" import { byActivity, + isShown, ConfereeView, ConferenceIndexProps, ConferenceLanding, @@ -41,14 +41,9 @@ const summarize = (c: Conference): ConferenceSummary => ({ reportBillId: c.reportBillId ?? null }) -/** Whether the site shows a conference: one still sitting always, one no - * longer taking input only behind the closedConferences flag. */ -const shown = (c: Pick) => - isSitting(c) || flags().closedConferences - /** Every conference in the court the site shows. */ const listShown = async (court: number) => - (await listConferences(court)).filter(shown) + (await listConferences(court)).filter(isShown) /** Conferences as the rail lists them: active first, then by name. */ const railOf = (all: Conference[]) => all.map(summarize).sort(byActivity) @@ -217,7 +212,7 @@ export async function loadConferenceForBill( billId: string ): Promise { const c = await getConferenceForBill(court, billId) - return c && shown(c) ? summarize(c) : null + return c && isShown(c) ? summarize(c) : null } /** The conference a hearing belongs to, by the hearing page's numeric id. */ @@ -230,5 +225,5 @@ export async function loadConferenceForHearing( Number(generalCourtNumber), `hearing-${hearingId}` ) - return c && shown(c) ? summarize(c) : null + return c && isShown(c) ? summarize(c) : null } diff --git a/components/conference/types.ts b/components/conference/types.ts index 80f23c379..6b924b674 100644 --- a/components/conference/types.ts +++ b/components/conference/types.ts @@ -1,11 +1,12 @@ import type { Branch } from "../../functions/src/common" -import { isSitting } from "../../functions/src/shared" +import { conferenceName, isSitting } from "../../functions/src/shared" import type { ConferenceAddressedBy, ConferenceOutcome, ConferenceStatus } from "../../functions/src/conferences/types" import type { EventSummary } from "../db/events" +import { flags } from "../featureFlags" /** The chambers in the order every view shows them: Senate first. */ export const CHAMBERS = ["Senate", "House"] as const @@ -89,10 +90,15 @@ export type ConferenceIndexProps = { } /** The short name where there is one, else the act title. */ -export const conferenceName = (c: Named) => c.name?.trim() || c.title.trim() +export { conferenceName } type Named = { name?: string | null; title: string } +/** Whether the site shows a conference: one still sitting always, one no + * longer taking input only behind the closedConferences flag. */ +export const isShown = (c: Pick) => + isSitting(c) || flags().closedConferences + /** Alphabetical by the name a conference goes by. */ export const byName = (a: Named, b: Named) => conferenceName(a).localeCompare(conferenceName(b)) diff --git a/components/shared/FollowButton.tsx b/components/shared/FollowButton.tsx index 7a09057f5..7aee4a6b7 100644 --- a/components/shared/FollowButton.tsx +++ b/components/shared/FollowButton.tsx @@ -15,7 +15,11 @@ import { profileTopicName, ballotQuestionTopicName, followBallotQuestion, - unfollowBallotQuestion + unfollowBallotQuestion, + ConferenceRef, + conferenceTopicName, + followConference, + unfollowConference } from "./FollowingQueries" import { FollowContext } from "./FollowContext" import { Modal } from "components/bootstrap" @@ -70,6 +74,54 @@ export function FollowBillButton({ ) } +/** + * Whether the reader follows a topic, shared through FollowContext so every + * control for the topic agrees, and a toggle that sends a signed-out reader + * to log in first. `loaded` is false until a signed-in reader's status is + * read. + */ +export function useFollowTopic( + topicName: string, + followAction: () => Promise, + unfollowAction: () => Promise, + /** False skips reading the follow status, for a control that can't show. */ + enabled = true +) { + const uid = useAuth().user?.uid + const router = useRouter() + const { followStatus, setFollowStatus } = useContext(FollowContext) + + useEffect(() => { + if (!uid || !enabled) return + followsTopic(uid, topicName).then(result => + setFollowStatus(prev => ({ ...prev, [topicName]: result })) + ) + }, [uid, topicName, setFollowStatus, enabled]) + + const follow = async () => { + await followAction() + setFollowStatus(prev => ({ ...prev, [topicName]: true })) + } + + const unfollow = async () => { + await unfollowAction() + setFollowStatus(prev => ({ ...prev, [topicName]: false })) + } + + const following = !!uid && !!followStatus[topicName] + const loaded = !uid || topicName in followStatus + + const toggle = () => { + if (!uid) { + router.push(`/login?redirect=${encodeURIComponent(router.asPath)}`) + return + } + return following ? unfollow() : follow() + } + + return { following, loaded, follow, unfollow, toggle } +} + export const BaseFollowButton = ({ topicName, followAction, @@ -89,45 +141,19 @@ export const BaseFollowButton = ({ }) => { const { t } = useTranslation(["profile"]) - const { user } = useAuth() - const uid = user?.uid - const router = useRouter() - - const { followStatus, setFollowStatus } = useContext(FollowContext) const [modalAction, setModalAction] = useState<"follow" | "unfollow" | null>( null ) + const { + following: isFollowing, + follow: FollowClick, + unfollow: UnfollowClick, + toggle + } = useFollowTopic(topicName, followAction, unfollowAction) - useEffect(() => { - if (!uid) return - followsTopic(uid, topicName).then(result => - setFollowStatus(prev => ({ ...prev, [topicName]: result })) - ) - }, [uid, topicName, setFollowStatus]) - - const FollowClick = async () => { - await followAction() - setFollowStatus(prev => ({ ...prev, [topicName]: true })) - } - - const UnfollowClick = async () => { - await unfollowAction() - setFollowStatus(prev => ({ ...prev, [topicName]: false })) - } - - const isFollowing = followStatus[topicName] - const text = isFollowing ? t("button.following") : t("button.follow") - const checkmark = isFollowing ? ( - - ) : null const handleClick = (event: any) => { event.preventDefault() - if (!uid) { - const currentPath = router.asPath - router.push(`/login?redirect=${encodeURIComponent(currentPath)}`) - return - } - isFollowing ? UnfollowClick() : FollowClick() + toggle() } return ( @@ -222,3 +248,21 @@ export function FollowBallotQuestionButton({ /> ) } + +export function FollowConferenceTopicButton({ + conference, + confirmUnfollow +}: { + conference: ConferenceRef + confirmUnfollow?: boolean +}) { + const uid = useAuth().user?.uid + return ( + followConference(uid, conference)} + unfollowAction={() => unfollowConference(uid, conference)} + confirmUnfollow={confirmUnfollow} + /> + ) +} diff --git a/components/shared/FollowingQueries.tsx b/components/shared/FollowingQueries.tsx index 30c488a7c..7609eff6e 100644 --- a/components/shared/FollowingQueries.tsx +++ b/components/shared/FollowingQueries.tsx @@ -14,6 +14,11 @@ export const billTopicName = (court: number, billId: string) => export const profileTopicName = (profileId: string) => `testimony-${profileId}` export const ballotQuestionTopicName = (court: number, id: string) => `ballot-question-${court}-${id}` +export const conferenceTopicName = (court: number, id: string) => + `conference-${court}-${id}` + +/** What following a conference needs to know of it. */ +export type ConferenceRef = { id: string; court: number } export const followBill = async (uid: string | undefined, bill: Bill) => { const topicName = billTopicName(bill.court, bill.id) @@ -82,6 +87,28 @@ export const unfollowBallotQuestion = async ( ballotQuestionTopicName(ballotQuestion.court, ballotQuestion.id) ) +export const followConference = async ( + uid: string | undefined, + conference: ConferenceRef +) => { + const topicName = conferenceTopicName(conference.court, conference.id) + await setDoc(getTopicRef(uid, topicName), { + topicName, + uid, + conferenceLookup: { + conferenceId: conference.id, + court: conference.court + }, + type: "conference" + }) +} + +export const unfollowConference = async ( + uid: string | undefined, + conference: ConferenceRef +) => + await unfollowTopic(uid, conferenceTopicName(conference.court, conference.id)) + export const followsTopic = async ( uid: string | undefined, topicName: string diff --git a/functions/src/email/digestEmail.handlebars b/functions/src/email/digestEmail.handlebars index 017d59c95..6e1478deb 100644 --- a/functions/src/email/digestEmail.handlebars +++ b/functions/src/email/digestEmail.handlebars @@ -9,6 +9,8 @@ {{> bills }} + {{> conferences }} + {{> ballotQuestions }} {{> users }} diff --git a/functions/src/email/digestEmail.test.ts b/functions/src/email/digestEmail.test.ts new file mode 100644 index 000000000..4b2d0c609 --- /dev/null +++ b/functions/src/email/digestEmail.test.ts @@ -0,0 +1,83 @@ +import * as fs from "fs" +import * as handlebars from "handlebars" +import * as path from "path" +import { NotificationEmailDigest } from "../notifications/emailTypes" +import { registerHelpers, registerPartials } from "./handlebarsHelpers" + +const render = (digest: NotificationEmailDigest) => { + registerHelpers() + registerPartials(path.join(__dirname, "partials")) + const source = fs.readFileSync( + path.join(__dirname, "digestEmail.handlebars"), + "utf8" + ) + return handlebars.compile(source)(digest) +} + +const empty: NotificationEmailDigest = { + notificationFrequency: "Weekly", + startDate: new Date("2025-02-22"), + endDate: new Date("2025-03-01"), + bills: [], + numBillsWithNewTestimony: 0, + users: [], + numUsersWithNewTestimony: 0, + ballotQuestions: [], + numBallotQuestionsWithNewTestimony: 0, + conferences: [], + numConferencesWithNewTestimony: 0 +} + +describe("digest email, conferences", () => { + it("links a followed conference and words its stances", () => { + const html = render({ + ...empty, + conferences: [ + { + conferenceId: "phones", + conferenceName: "Phone-Free Schools", + court: "194", + newTestimonyCount: 3, + stances: [ + { stance: "Please pass something", count: 2 }, + { stance: "Don't pass anything", count: 1 } + ] + } + ], + numConferencesWithNewTestimony: 1 + }) + + expect(html).toContain("Conference Committees") + expect(html).toContain( + "https://mapletestimony.org/conferences/194/phones#input" + ) + expect(html).toContain("Phone-Free Schools") + expect(html).toContain("New Inputs") + expect(html).toMatch(/2<\/td>\s*]*>Please pass something/) + expect(html).toContain("Don't pass anything") + }) + + it("leaves the section out for a reader following no conference", () => { + expect(render(empty)).not.toContain("Conference Committees") + }) + + it("points to the rest past four conferences", () => { + const conference = { + conferenceId: "c", + conferenceName: "C", + court: "194", + newTestimonyCount: 1, + stances: [] + } + const html = render({ + ...empty, + conferences: [conference, conference, conference, conference], + numConferencesWithNewTestimony: 6 + }) + expect(html).toContain( + "2 other conference committees you follow received input" + ) + expect(html).toContain("New Input") + expect(html).not.toContain("New Inputs") + }) +}) diff --git a/functions/src/email/partials/conferences/conference.handlebars b/functions/src/email/partials/conferences/conference.handlebars new file mode 100644 index 000000000..41e52fb79 --- /dev/null +++ b/functions/src/email/partials/conferences/conference.handlebars @@ -0,0 +1,34 @@ +{{!-- A followed committee of conference. Its stances are in words: the + position images are bill stances --}} + diff --git a/functions/src/email/partials/conferences/conferences.handlebars b/functions/src/email/partials/conferences/conferences.handlebars new file mode 100644 index 000000000..e541c344b --- /dev/null +++ b/functions/src/email/partials/conferences/conferences.handlebars @@ -0,0 +1,44 @@ +{{!-- Only for readers following a conference with new testimony: unlike + bills, there is no empty state, so other readers' digests don't change --}} +{{#if conferences.length}} +
+
+
+ Conference Committees +
+
+
+
+ {{#each conferences}} + {{> conference}} + {{/each}} +
+
+ {{#ifGreaterThan numConferencesWithNewTestimony 4}} +
+
+ {{#ifGreaterThan numConferencesWithNewTestimony 5}} + {{minusFour numConferencesWithNewTestimony}} other conference committees you follow received input since your last update + {{else}} + {{minusFour numConferencesWithNewTestimony}} other conference committee you follow received input since your last update + {{/ifGreaterThan}} +
+ +
+ {{/ifGreaterThan}} +
+
+{{/if}} diff --git a/functions/src/email/partials/index.ts b/functions/src/email/partials/index.ts index f72d99a2c..1cc372e97 100644 --- a/functions/src/email/partials/index.ts +++ b/functions/src/email/partials/index.ts @@ -2,7 +2,9 @@ import ballotQuestion from "./ballotQuestions/ballotQuestion.handlebars" import ballotQuestions from "./ballotQuestions/ballotQuestions.handlebars" import bill from "./bills/bill.handlebars" import bills from "./bills/bills.handlebars" +import conference from "./conferences/conference.handlebars" import conferenceItem from "./users/conferenceItem.handlebars" +import conferences from "./conferences/conferences.handlebars" import footer from "./footer.handlebars" import header from "./header.handlebars" import newsFeedLink from "./newsFeedLink.handlebars" @@ -15,7 +17,9 @@ export const partials = { ballotQuestions, bill, bills, + conference, conferenceItem, + conferences, footer, header, newsFeedLink, diff --git a/functions/src/notifications/deliverNotifications.test.ts b/functions/src/notifications/deliverNotifications.test.ts index 9213de33c..1a8d7ef83 100644 --- a/functions/src/notifications/deliverNotifications.test.ts +++ b/functions/src/notifications/deliverNotifications.test.ts @@ -1,4 +1,5 @@ -import { buildDigestData, CONFERENCE_STANCES } from "./deliverNotifications" +import { buildDigestData } from "./deliverNotifications" +import { CONFERENCE_STANCES } from "./emailTypes" import { Timestamp } from "../firebase" // Mock firebase module @@ -352,6 +353,102 @@ describe("buildDigestData — conference testimony", () => { }) }) +describe("buildDigestData — conferences", () => { + const conferenceDoc = (overrides: object) => ({ + type: "testimony", + isBillMatch: false, + isUserMatch: false, + isBallotQuestionMatch: false, + isConferenceMatch: true, + billId: "S2581", + header: "An Act relative to phones", + court: "194", + position: "passSomething", + timestamp: now, + authorUid: "author1", + subheader: "Alice", + bodyText: "", + testimonyId: "t1", + userRole: "user", + delivered: false, + ballotQuestionId: null, + ballotQuestionCourt: null, + conferenceId: "phones", + conferenceName: "Phone-Free Schools", + ...overrides + }) + + it("counts a followed conference's testimony by stance, every stance listed", async () => { + setupCollection([ + conferenceDoc({ testimonyId: "t1", position: "passSomething" }), + conferenceDoc({ testimonyId: "t2", position: "passSomething" }), + conferenceDoc({ testimonyId: "t3", position: "passNothing" }) + ]) + + const result = await buildDigestData("uid1", now as any, "Weekly") + + expect(result.conferences).toEqual([ + { + conferenceId: "phones", + conferenceName: "Phone-Free Schools", + court: "194", + newTestimonyCount: 3, + stances: [ + { stance: "Please pass something", count: 2 }, + { stance: "Pass the Senate version", count: 0 }, + { stance: "Pass the House version", count: 0 }, + { stance: "Don't pass anything", count: 1 } + ] + } + ]) + expect(result.numConferencesWithNewTestimony).toBe(1) + // A conference-only reader has something to send, and nothing else. + expect(result.numBillsWithNewTestimony).toBe(0) + expect(result.numUsersWithNewTestimony).toBe(0) + }) + + it("names the conference from the bill's title when it has no name", async () => { + setupCollection([conferenceDoc({ conferenceName: null })]) + + const result = await buildDigestData("uid1", now as any, "Weekly") + + expect(result.conferences[0].conferenceName).toBe( + "An Act relative to phones" + ) + }) + + it("caps conferences at 4, most testimony first, and reports the full count", async () => { + setupCollection([ + ...Array.from({ length: 6 }, (_, i) => + conferenceDoc({ testimonyId: `t${i}`, conferenceId: `c${i}` }) + ), + conferenceDoc({ testimonyId: "extra", conferenceId: "c5" }) + ]) + + const result = await buildDigestData("uid1", now as any, "Weekly") + + expect(result.conferences).toHaveLength(4) + expect(result.conferences[0].conferenceId).toBe("c5") + expect(result.numConferencesWithNewTestimony).toBe(6) + }) + + it("shows testimony matching both the conference and its author in each section", async () => { + setupCollection([conferenceDoc({ isUserMatch: true })]) + + const result = await buildDigestData("uid1", now as any, "Weekly") + + expect(result.numConferencesWithNewTestimony).toBe(1) + expect(result.users[0].bills).toEqual([ + { + billId: "S2581", + court: "194", + conferenceId: "phones", + stance: "Please pass something" + } + ]) + }) +}) + describe("CONFERENCE_STANCES", () => { it("says what the site says", () => { const { input } = require("../../../public/locales/en/conferences.json") diff --git a/functions/src/notifications/deliverNotifications.ts b/functions/src/notifications/deliverNotifications.ts index f7c159c0b..239d731ac 100644 --- a/functions/src/notifications/deliverNotifications.ts +++ b/functions/src/notifications/deliverNotifications.ts @@ -13,6 +13,8 @@ import { BallotQuestionDigest, BillDigest, BillResult, + CONFERENCE_STANCES, + ConferenceDigest, NotificationEmailDigest, Position, UserDigest @@ -26,16 +28,9 @@ const NUM_BILLS_TO_DISPLAY = 4 const NUM_USERS_TO_DISPLAY = 4 const NUM_TESTIMONIES_TO_DISPLAY = 6 const NUM_BALLOT_QUESTIONS_TO_DISPLAY = 4 +const NUM_CONFERENCES_TO_DISPLAY = 4 const EMAIL_TEMPLATE_PATH = "../email/digestEmail.handlebars" -// The site's wording, conferences input.position.*.long; a test holds them equal. -export const CONFERENCE_STANCES: Record = { - passSomething: "Please pass something", - passSenateVersion: "Pass the Senate version", - passHouseVersion: "Pass the House version", - passNothing: "Don't pass anything" -} - const path = require("path") const getVerifiedUserEmail = async (uid: string) => { @@ -117,7 +112,8 @@ const deliverEmailNotifications = async () => { if ( digestData.numBillsWithNewTestimony === 0 && digestData.numUsersWithNewTestimony === 0 && - digestData.numBallotQuestionsWithNewTestimony === 0 + digestData.numBallotQuestionsWithNewTestimony === 0 && + digestData.numConferencesWithNewTestimony === 0 ) { console.log( `No new notifications for ${profileDoc.id} - not sending email` @@ -181,10 +177,14 @@ export const buildDigestData = async ( const billsById: { [billId: string]: BillDigest } = {} const usersById: { [userId: string]: UserDigest } = {} const ballotQuestionsById: { [bqId: string]: BallotQuestionDigest } = {} + const conferencesById: { [conferenceId: string]: ConferenceDigest } = {} notificationsSnapshot.docs.forEach(notificationDoc => { const { notification } = notificationDoc.data() as TestimonySubmissionNotificationFields + // Read only for conference testimony; a bill position has no stance. + const stance = + CONFERENCE_STANCES[notification.position as ConferencePosition] if (notification.isBillMatch) { if (billsById[notification.billId]) { @@ -223,8 +223,7 @@ export const buildDigestData = async ( ...(notification.conferenceId ? { conferenceId: notification.conferenceId, - stance: - CONFERENCE_STANCES[notification.position as ConferencePosition] + stance } : { position: notification.position as Position }) } @@ -270,6 +269,25 @@ export const buildDigestData = async ( } } } + + if (notification.isConferenceMatch && notification.conferenceId) { + const id = notification.conferenceId + const conference = (conferencesById[id] ??= { + conferenceId: id, + conferenceName: notification.conferenceName || notification.header, + court: notification.court, + newTestimonyCount: 0, + stances: Object.values(CONFERENCE_STANCES).map(stance => ({ + stance, + count: 0 + })) + }) + const row = conference.stances.find(s => s.stance === stance) + if (row) row.count++ + else + console.error(`Unknown conference position: ${notification.position}`) + conference.newTestimonyCount++ + } }) const bills = Object.values(billsById).sort((a, b) => { @@ -299,6 +317,10 @@ export const buildDigestData = async ( ) }) + const conferences = Object.values(conferencesById).sort( + (a, b) => b.newTestimonyCount - a.newTestimonyCount + ) + return { notificationFrequency, startDate: startDate.toDate(), @@ -308,7 +330,9 @@ export const buildDigestData = async ( users: users.slice(0, NUM_USERS_TO_DISPLAY), numUsersWithNewTestimony: users.length, ballotQuestions: ballotQuestions.slice(0, NUM_BALLOT_QUESTIONS_TO_DISPLAY), - numBallotQuestionsWithNewTestimony: ballotQuestions.length + numBallotQuestionsWithNewTestimony: ballotQuestions.length, + conferences: conferences.slice(0, NUM_CONFERENCES_TO_DISPLAY), + numConferencesWithNewTestimony: conferences.length } } diff --git a/functions/src/notifications/emailTypes.ts b/functions/src/notifications/emailTypes.ts index ae6fe0bd8..1d0622232 100644 --- a/functions/src/notifications/emailTypes.ts +++ b/functions/src/notifications/emailTypes.ts @@ -1,4 +1,13 @@ import { Frequency } from "../auth/types" +import type { ConferencePosition } from "../testimony/types" + +// The site's wording, conferences input.position.*.long; a test holds them equal. +export const CONFERENCE_STANCES: Record = { + passSomething: "Please pass something", + passSenateVersion: "Pass the Senate version", + passHouseVersion: "Pass the House version", + passNothing: "Don't pass anything" +} export type BillDigest = { billId: string @@ -31,6 +40,15 @@ export type BallotQuestionDigest = { neutralCount: number opposeCount: number } +/** Testimony on a followed committee of conference, counted by stance. */ +export type ConferenceDigest = { + conferenceId: string + conferenceName: string + court: string + newTestimonyCount: number + /** Every stance, in the site's order, so digests compare at a glance. */ + stances: { stance: string; count: number }[] +} export type NotificationEmailDigest = { notificationFrequency: Frequency startDate: Date @@ -41,4 +59,6 @@ export type NotificationEmailDigest = { numUsersWithNewTestimony: number ballotQuestions: BallotQuestionDigest[] // cap of 4 numBallotQuestionsWithNewTestimony: number + conferences: ConferenceDigest[] // cap of 4 + numConferencesWithNewTestimony: number } diff --git a/functions/src/notifications/populateTestimonySubmissionNotificationEvents.test.ts b/functions/src/notifications/populateTestimonySubmissionNotificationEvents.test.ts index 682ac1441..ea84fe718 100644 --- a/functions/src/notifications/populateTestimonySubmissionNotificationEvents.test.ts +++ b/functions/src/notifications/populateTestimonySubmissionNotificationEvents.test.ts @@ -11,7 +11,8 @@ jest.mock("firebase-functions/logger", () => ({ // The Testimony type needs the admin package's own Timestamp class. jest.mock("../firebase", () => ({ db: { - collection: jest.fn() + collection: jest.fn(), + doc: jest.fn() }, Timestamp: jest.requireActual("firebase-admin/firestore").Timestamp })) @@ -57,6 +58,14 @@ const makeEvent = (before: object | null, after: object | null) => ({ params: { userId: "author-uid", testimonyId: "testimony-id" } }) +/** Documents the handler reads, by path; any other path is missing. */ +const setupDocs = (byPath: Record) => + mockDb.doc.mockImplementation((path: string) => ({ + get: jest.fn().mockResolvedValue({ data: () => byPath[path] }) + })) + +const PHONES = "/generalCourts/194/conferences/phones" + beforeEach(() => { jest.clearAllMocks() }) @@ -81,6 +90,155 @@ describe("populateTestimonySubmissionNotificationEventsHandler", () => { ) }) + it("names the conference on conference testimony", async () => { + setupCollection(true) + setupDocs({ + [PHONES]: { name: "Phone-Free Schools", title: "An Act relative" } + }) + + const event = makeEvent( + null, + makeTestimony({ conferenceId: "phones", position: "passSomething" }) + ) + await populateTestimonySubmissionNotificationEventsHandler(event as any) + + expect(mockDb.doc).toHaveBeenCalledWith( + "/generalCourts/194/conferences/phones" + ) + expect(mockAdd).toHaveBeenCalledWith( + expect.objectContaining({ + conferenceId: "phones", + conferenceName: "Phone-Free Schools" + }) + ) + }) + + it("falls back to the conference's title, then to no name", async () => { + setupCollection(true) + setupDocs({ [PHONES]: { title: "An Act relative to phones" } }) + const testimony = makeTestimony({ + conferenceId: "phones", + position: "passSomething" + }) + await populateTestimonySubmissionNotificationEventsHandler( + makeEvent(null, testimony) as any + ) + expect(mockAdd).toHaveBeenLastCalledWith( + expect.objectContaining({ conferenceName: "An Act relative to phones" }) + ) + + setupDocs({ [PHONES]: undefined }) + await populateTestimonySubmissionNotificationEventsHandler( + makeEvent(null, testimony) as any + ) + expect(mockAdd).toHaveBeenLastCalledWith( + expect.objectContaining({ conferenceId: "phones", conferenceName: null }) + ) + }) + + it("names no conference on bill testimony", async () => { + setupCollection(true) + + await populateTestimonySubmissionNotificationEventsHandler( + makeEvent(null, makeTestimony()) as any + ) + + expect(mockDb.doc).not.toHaveBeenCalled() + expect(mockAdd).toHaveBeenCalledWith( + expect.objectContaining({ conferenceId: null, conferenceName: null }) + ) + }) + + describe("on a cosign", () => { + const cosign = (content = "") => + makeTestimony({ + conferenceId: "phones", + position: "passSomething", + content, + cosignOfId: "lead-id", + cosignOfAuthorUid: "lead-uid" + }) + + it("carries the input it cosigns, credited to its author", async () => { + setupCollection(true) + setupDocs({ + "/generalCourts/194/conferences/phones": { name: "Phone-Free Schools" }, + "/users/lead-uid/publishedTestimony/lead-id": { + fullName: "Lead Author", + content: "Keep phones out of classrooms." + } + }) + + await populateTestimonySubmissionNotificationEventsHandler( + makeEvent(null, cosign()) as any + ) + + expect(mockAdd).toHaveBeenCalledWith( + expect.objectContaining({ + conferenceName: "Phone-Free Schools", + testimonyContent: "", + cosignOf: { + authorName: "Lead Author", + content: "Keep phones out of classrooms." + } + }) + ) + }) + + it("names an author without a full name as the site does, and trims a long input", async () => { + setupCollection(true) + setupDocs({ + "/users/lead-uid/publishedTestimony/lead-id": { + authorDisplayName: "Lead Org", + content: "x".repeat(700) + } + }) + + await populateTestimonySubmissionNotificationEventsHandler( + makeEvent(null, cosign()) as any + ) + + expect(mockAdd).toHaveBeenCalledWith( + expect.objectContaining({ + cosignOf: { authorName: "Lead Org", content: `${"x".repeat(600)}...` } + }) + ) + }) + + it("still goes out when the cosigned input is gone", async () => { + setupCollection(true) + setupDocs({}) + + await populateTestimonySubmissionNotificationEventsHandler( + makeEvent(null, cosign("My own line.")) as any + ) + + expect(mockAdd).toHaveBeenCalledWith( + expect.objectContaining({ + testimonyContent: "My own line.", + cosignOf: null + }) + ) + }) + }) + + it("reads nothing more for testimony that cosigns nothing", async () => { + setupCollection(true) + setupDocs({ [PHONES]: { name: "Phone-Free Schools" } }) + + await populateTestimonySubmissionNotificationEventsHandler( + makeEvent( + null, + makeTestimony({ conferenceId: "phones", position: "passSomething" }) + ) as any + ) + + expect(mockDb.doc).toHaveBeenCalledTimes(1) + expect(mockAdd).toHaveBeenCalledWith( + expect.objectContaining({ cosignOf: null }) + ) + }) + it.each(["court", "authorUid", "billId", "position", "content", "version"])( "logs an error and skips new testimony missing %s", async field => { diff --git a/functions/src/notifications/populateTestimonySubmissionNotificationEvents.ts b/functions/src/notifications/populateTestimonySubmissionNotificationEvents.ts index 943c60a70..94353e3d0 100644 --- a/functions/src/notifications/populateTestimonySubmissionNotificationEvents.ts +++ b/functions/src/notifications/populateTestimonySubmissionNotificationEvents.ts @@ -12,8 +12,47 @@ import { } from "firebase-functions/v2/firestore" import * as logger from "firebase-functions/logger" import { db, Timestamp } from "../firebase" +import { conferenceName, nameOf } from "../shared" import { Testimony } from "../testimony/types" -import { TestimonySubmissionNotification } from "./types" +import { CosignOf, TestimonySubmissionNotification } from "./types" + +/** The conference's name for headings, as the site shows it: its short name, + * falling back to its title. Null when the document is missing, so the + * notification still goes out. */ +const conferenceNameOf = async (court: number, conferenceId: string) => { + const snap = await db + .doc(`/generalCourts/${court}/conferences/${conferenceId}`) + .get() + const data = snap.data() + return (data && conferenceName(data)) || null +} + +/** The most of a cosigned input the newsfeed quotes; the event, and each + * follower's copy of it, carries no more. */ +const QUOTE_LENGTH = 600 + +/** What a cosign cosigns, as it reads now, for the newsfeed to quote. Null + * when the testimony isn't a cosign or the cosigned testimony is gone, so the + * notification still goes out. */ +const cosignOfIn = async ({ + cosignOfId, + cosignOfAuthorUid +}: Testimony): Promise => { + if (!cosignOfId || !cosignOfAuthorUid) return null + const snap = await db + .doc(`/users/${cosignOfAuthorUid}/publishedTestimony/${cosignOfId}`) + .get() + const data = snap.data() + if (!data) return null + const content: string = data.content ?? "" + return { + authorName: nameOf(data), + content: + content.length > QUOTE_LENGTH + ? `${content.slice(0, QUOTE_LENGTH)}...` + : content + } +} export const populateTestimonySubmissionNotificationEventsHandler = async ( event: FirestoreEvent< @@ -49,6 +88,11 @@ export const populateTestimonySubmissionNotificationEventsHandler = async ( const testimony = checked.value const bqId = testimony.ballotQuestionId ?? null + const conferenceId = testimony.conferenceId ?? null + const [conferenceName, cosignOf] = await Promise.all([ + conferenceId ? conferenceNameOf(testimony.court, conferenceId) : null, + cosignOfIn(testimony) + ]) const newNotificationEvent: TestimonySubmissionNotification = { type: "testimony", @@ -67,7 +111,9 @@ export const populateTestimonySubmissionNotificationEventsHandler = async ( ballotQuestionId: bqId, ballotQuestionCourt: bqId ? testimony.court : null, - conferenceId: testimony.conferenceId ?? null, + conferenceId, + conferenceName, + cosignOf, updateTime: Timestamp.now() } diff --git a/functions/src/notifications/publishNotifications.ts b/functions/src/notifications/publishNotifications.ts index 9b86f34db..9f72315bd 100644 --- a/functions/src/notifications/publishNotifications.ts +++ b/functions/src/notifications/publishNotifications.ts @@ -69,13 +69,16 @@ const createNotificationFields = ( isBillMatch: false, isUserMatch: false, isBallotQuestionMatch: false, + isConferenceMatch: false, delivered: false, authorUid: entity.userId, testimonyId: entity.testimonyId, userRole: entity.userRole, ballotQuestionId: entity.ballotQuestionId ?? null, ballotQuestionCourt: entity.ballotQuestionCourt ?? null, - conferenceId: entity.conferenceId ?? null + conferenceId: entity.conferenceId ?? null, + conferenceName: entity.conferenceName ?? null, + cosignOf: entity.cosignOf ?? null }, createdAt: Timestamp.now() } @@ -141,11 +144,11 @@ export const publishNotifications = onDocumentWritten( ] : [ `testimony-${topic.userId}`, - // Conference testimony is kept off its bill, so the bill's - // followers don't hear of it. - ...(topic.conferenceId - ? [] - : [`bill-${topic.billCourt}-${topic.billId}`]), + // Conference testimony goes to the conference's followers and + // is kept off its bill, so the bill's followers don't hear of it. + topic.conferenceId + ? `conference-${topic.billCourt}-${topic.conferenceId}` + : `bill-${topic.billCourt}-${topic.billId}`, ...(topic.ballotQuestionId && topic.ballotQuestionCourt != null ? [ `ballot-question-${topic.ballotQuestionCourt}-${topic.ballotQuestionId}` @@ -179,6 +182,8 @@ export const publishNotifications = onDocumentWritten( users[uid].notification.isUserMatch = true } else if (type === "ballotQuestion") { users[uid].notification.isBallotQuestionMatch = true + } else if (type === "conference") { + users[uid].notification.isConferenceMatch = true } else { users[uid].notification.isBillMatch = true } diff --git a/functions/src/notifications/types.ts b/functions/src/notifications/types.ts index 33c4aa5e3..a939c0b36 100644 --- a/functions/src/notifications/types.ts +++ b/functions/src/notifications/types.ts @@ -15,6 +15,13 @@ export type BillHistoryUpdateNotification = Notification & { billHistory: BillHistory } +/** The testimony a cosign cosigns, as it read when the cosign was published, + * so the newsfeed can quote it: its author's name and its first words. */ +export type CosignOf = { + authorName: string + content: string +} + export type TestimonySubmissionNotification = Notification & { type: "testimony" userId: string @@ -27,6 +34,10 @@ export type TestimonySubmissionNotification = Notification & { ballotQuestionId?: string | null ballotQuestionCourt?: number | null conferenceId?: string | null + /** The conference's name for headings, set with conferenceId. */ + conferenceName?: string | null + /** Set on a cosign whose cosigned testimony still exists. */ + cosignOf?: CosignOf | null } export interface TestimonySubmissionNotificationFields { @@ -43,6 +54,8 @@ export interface TestimonySubmissionNotificationFields { isBillMatch: boolean isUserMatch: boolean isBallotQuestionMatch: boolean + /** The reader follows the conference the testimony was filed on. */ + isConferenceMatch?: boolean delivered: boolean testimonyId: string userRole: string @@ -50,6 +63,8 @@ export interface TestimonySubmissionNotificationFields { ballotQuestionId?: string | null ballotQuestionCourt?: number | null conferenceId?: string | null + conferenceName?: string | null + cosignOf?: CosignOf | null } createdAt: FirebaseFirestore.Timestamp } diff --git a/functions/src/shared/conferences.ts b/functions/src/shared/conferences.ts index 0f065be6a..97954b8d1 100644 --- a/functions/src/shared/conferences.ts +++ b/functions/src/shared/conferences.ts @@ -15,3 +15,9 @@ export const isSitting = (c: Pick) => * existed counts as covered. */ export const takesTestimony = (c: Pick) => isSitting(c) && c.covered !== false + +type Named = { name?: string | null; title?: string | null } + +/** The short name where there is one, else the act title. */ +export const conferenceName = (c: Named) => + c.name?.trim() || c.title?.trim() || "" diff --git a/functions/src/shared/names.ts b/functions/src/shared/names.ts index 3bba53745..914afe8e4 100644 --- a/functions/src/shared/names.ts +++ b/functions/src/shared/names.ts @@ -21,3 +21,9 @@ export function splitMemberName(fullName: string) { export const extractLastName = (fullName: string) => splitMemberName(fullName).surname + +/** The name a piece of testimony is shown under. */ +export const nameOf = (t: { + fullName?: string | null + authorDisplayName?: string | null +}) => t.fullName || t.authorDisplayName || "" diff --git a/functions/src/subscriptions/types.ts b/functions/src/subscriptions/types.ts index 6a45ff3ac..90c03308b 100644 --- a/functions/src/subscriptions/types.ts +++ b/functions/src/subscriptions/types.ts @@ -16,4 +16,9 @@ export interface TopicSubscription { ballotQuestionId: string court: number } + + conferenceLookup?: { + conferenceId: string + court: number + } } diff --git a/public/locales/en/common.json b/public/locales/en/common.json index c21e04dda..a5e54ac6b 100644 --- a/public/locales/en/common.json +++ b/public/locales/en/common.json @@ -159,7 +159,10 @@ "and": " and ", "notFollowEither": "You do not follow either", "conferenceInput": " gave input to the conference committee on ", + "conferenceCosign": " cosigned input to the conference committee on ", "conferenceInputPost": "Input Posted ", + "cosigned": "Cosigned", + "cosignedInput": "Cosigned {{name}}’s input:", "endorsed": " endorsed ", "endorsementPost": "Endorsement Posted ", "follow": "You follow ", diff --git a/public/locales/en/conferences.json b/public/locales/en/conferences.json index f123156d0..af4cd1111 100644 --- a/public/locales/en/conferences.json +++ b/public/locales/en/conferences.json @@ -286,5 +286,10 @@ "cosign_closed": "This conference committee is no longer taking input, so your cosign could not be filed.", "fill_window": "Fill the window", "leave_full": "Leave full screen" + }, + "follow": { + "follow": "Follow", + "following": "Following", + "unfollow": "Unfollow" } } diff --git a/public/locales/en/editProfile.json b/public/locales/en/editProfile.json index 2bc1b45be..29374735e 100644 --- a/public/locales/en/editProfile.json +++ b/public/locales/en/editProfile.json @@ -27,6 +27,7 @@ "follow": { "bills": "Bills I Follow", "ballotQuestions": "Ballot Questions I Follow", + "conferences": "Conference Committees I Follow", "orgs": "Users I Follow", "your_followers": "Your Followers", "unfollow": "Unfollow", diff --git a/scripts/firebase-admin/sendTestEmail.ts b/scripts/firebase-admin/sendTestEmail.ts index 1c6dfc1c7..a63b571a6 100644 --- a/scripts/firebase-admin/sendTestEmail.ts +++ b/scripts/firebase-admin/sendTestEmail.ts @@ -201,7 +201,9 @@ const generateTestData = ( numBillsWithNewTestimony: numBills, numUsersWithNewTestimony: numUsers, ballotQuestions: [], - numBallotQuestionsWithNewTestimony: 0 + numBallotQuestionsWithNewTestimony: 0, + conferences: [], + numConferencesWithNewTestimony: 0 } } diff --git a/stories/emailTemplates/NotificationDigestEmail.stories.tsx b/stories/emailTemplates/NotificationDigestEmail.stories.tsx index dc3d1d5c5..96355cd3d 100644 --- a/stories/emailTemplates/NotificationDigestEmail.stories.tsx +++ b/stories/emailTemplates/NotificationDigestEmail.stories.tsx @@ -4,6 +4,8 @@ import { EmailTemplateRenderer } from "./EmailTemplateRenderer" import { BillDigest, BillResult, + CONFERENCE_STANCES, + ConferenceDigest, NotificationEmailDigest, UserDigest } from "functions/src/notifications/emailTypes" @@ -145,10 +147,34 @@ const users = [ generateTestUserData("QDPq42rNB0O6wqVzfMmDHmNE8sN3", "Iranout Ofnameideas", 3) ] +// Invented conference committees, counted by stance. +const conferenceStances = (counts: number[]) => + Object.values(CONFERENCE_STANCES).map((stance, i) => ({ + stance, + count: counts[i] + })) +const conferences: ConferenceDigest[] = [ + { + conferenceId: "quiet-libraries", + conferenceName: "Quiet Libraries", + court: "194", + newTestimonyCount: 6, + stances: conferenceStances([3, 1, 0, 2]) + }, + { + conferenceId: "harbor-ferries", + conferenceName: "Harbor Ferries", + court: "194", + newTestimonyCount: 1, + stances: conferenceStances([0, 0, 1, 0]) + } +] + const generateTestData = ( frequency: Exclude, numBills: number, - numUsers: number + numUsers: number, + numConferences = 0 ): NotificationEmailDigest => { const endDateDay = { Monthly: "30", @@ -164,7 +190,9 @@ const generateTestData = ( numBillsWithNewTestimony: numBills, numUsersWithNewTestimony: numUsers, ballotQuestions: [], - numBallotQuestionsWithNewTestimony: 0 + numBallotQuestionsWithNewTestimony: 0, + conferences: conferences.slice(0, numConferences), + numConferencesWithNewTestimony: numConferences } } @@ -190,6 +218,10 @@ export const OnlyBills: Story = createDigestStory( generateTestData("Weekly", 5, 0) ) +export const OnlyConferences: Story = createDigestStory( + generateTestData("Weekly", 0, 0, 2) +) + export const OnlyUsers: Story = createDigestStory( generateTestData("Weekly", 0, 5) ) diff --git a/tests/integration/common.ts b/tests/integration/common.ts index 0a9c59489..4371fdb2b 100644 --- a/tests/integration/common.ts +++ b/tests/integration/common.ts @@ -91,6 +91,36 @@ export async function deleteOrg(id: string) { export const createFakeBill = () => createNewBill().then(b => b) +/** A conference on `billId`, taking input unless `fields` say otherwise. */ +export async function createConference( + billId: string, + fields: Record = {} +) { + const id = `conference-${nanoid()}`.toLowerCase() + await testDb + .doc(`/generalCourts/${currentGeneralCourt}/conferences/${id}`) + .set({ + id, + court: currentGeneralCourt, + title: "Test conference", + senateBillId: billId, + houseBillId: "H1", + canonicalBillId: billId, + conferees: [], + status: "appointed", + hearingIds: [], + differences: [], + similarities: [], + testimonyCount: 0, + passNothingCount: 0, + passSomethingCount: 0, + passSenateVersionCount: 0, + passHouseVersionCount: 0, + ...fields + }) + return id +} + export async function expectPermissionDenied(work: Promise) { const warn = console.warn console.warn = jest.fn() diff --git a/tests/integration/conferenceFollowing.test.ts b/tests/integration/conferenceFollowing.test.ts new file mode 100644 index 000000000..d8f51bc35 --- /dev/null +++ b/tests/integration/conferenceFollowing.test.ts @@ -0,0 +1,170 @@ +import { waitFor } from "@testing-library/react" +import { currentGeneralCourt } from "functions/src/shared" +import { doc, setDoc } from "firebase/firestore" +import { httpsCallable } from "firebase/functions" +import { nanoid } from "nanoid" +import { firestore, functions } from "../../components/firebase" +import { + followConference, + unfollowConference +} from "../../components/shared/FollowingQueries" +import { terminateFirebase, testDb } from "../testUtils" +import { + createConference, + createFakeBill, + deleteBill, + expectPermissionDenied, + signInUser1, + signInUser2, + signInUser3 +} from "./common" + +afterAll(terminateFirebase) + +const court = currentGeneralCourt +const publishTestimony = httpsCallable< + { draftId: string }, + { publicationId: string } +>(functions, "publishTestimonyV2") + +const subscription = (uid: string, topicName: string) => + testDb.doc(`/users/${uid}/activeTopicSubscriptions/${topicName}`) + +const feedFor = (uid: string, testimonyId: string) => + testDb + .collection(`/users/${uid}/userNotificationFeed`) + .where("notification.testimonyId", "==", testimonyId) + .get() + +describe("following a conference", () => { + let billId: string + let conferenceId: string + let topicName: string + + beforeEach(async () => { + billId = await createFakeBill() + conferenceId = await createConference(billId, { + title: "An Act relative to quiet libraries", + name: "Quiet Libraries" + }) + topicName = `conference-${court}-${conferenceId}` + }) + + afterEach(async () => { + await Promise.all([ + testDb + .doc(`/generalCourts/${court}/conferences/${conferenceId}`) + .delete(), + deleteBill(billId) + ]) + }) + + it("writes a conference subscription, and unfollowing deletes it", async () => { + const { uid } = await signInUser1() + const conference = { id: conferenceId, court } + + await followConference(uid, conference) + expect((await subscription(uid, topicName).get()).data()).toEqual({ + topicName, + uid, + type: "conference", + conferenceLookup: { conferenceId, court } + }) + + await unfollowConference(uid, conference) + expect((await subscription(uid, topicName).get()).exists).toBe(false) + }) + + it("won't let a user follow for someone else", async () => { + const user1 = await signInUser1() + await signInUser2() + + await expectPermissionDenied( + followConference(user1.uid, { id: conferenceId, court }) + ) + }) + + it("sends new input on the conference to its followers, and only them", async () => { + const follower = await signInUser2() + await followConference(follower.uid, { id: conferenceId, court }) + + const author = await signInUser1() + const publicationId = await publishInput(author.uid, { + content: "Keep the libraries quiet.", + position: "passSenateVersion" + }) + + await waitFor( + async () => { + const feed = await feedFor(follower.uid, publicationId) + expect(feed.size).toBe(1) + expect(feed.docs[0].data().notification).toMatchObject({ + type: "testimony", + conferenceId, + conferenceName: "Quiet Libraries", + isConferenceMatch: true, + isBillMatch: false, + isUserMatch: false, + position: "passSenateVersion" + }) + }, + { timeout: 20000, interval: 500 } + ) + // The author hears nothing of their own input. + expect((await feedFor(author.uid, publicationId)).size).toBe(0) + + await subscription(follower.uid, topicName).delete() + }, 30000) + + it("sends a cosign with the input it cosigns, even with no line of its own", async () => { + const follower = await signInUser2() + await followConference(follower.uid, { id: conferenceId, court }) + + const author = await signInUser1() + const lead = await publishInput(author.uid, { + content: "Keep the libraries quiet.", + position: "passSenateVersion" + }) + + const cosigner = await signInUser3() + const cosign = await publishInput(cosigner.uid, { + content: "", + position: "passSenateVersion", + cosignOfId: lead, + cosignOfAuthorUid: author.uid + }) + + await waitFor( + async () => { + const feed = await feedFor(follower.uid, cosign) + expect(feed.size).toBe(1) + expect(feed.docs[0].data().notification).toMatchObject({ + isConferenceMatch: true, + bodyText: "", + cosignOf: { + authorName: expect.any(String), + content: "Keep the libraries quiet." + } + }) + }, + { timeout: 20000, interval: 500 } + ) + + await subscription(follower.uid, topicName).delete() + }, 30000) + + /** Publishes input on the conference as the signed-in user. */ + async function publishInput(uid: string, fields: Record) { + const draftId = nanoid() + await setDoc(doc(firestore, `/users/${uid}/draftTestimony/${draftId}`), { + billId, + court, + attachmentId: null, + ballotQuestionId: null, + conferenceId, + ...fields + }) + const { data } = await publishTestimony({ draftId }) + return data.publicationId + } +}) diff --git a/tests/integration/testimony.test.ts b/tests/integration/testimony.test.ts index 2287727b5..2a4609ec0 100644 --- a/tests/integration/testimony.test.ts +++ b/tests/integration/testimony.test.ts @@ -21,7 +21,8 @@ import { signInUser1, signInUser2, signInUser3, - signInUser4 + signInUser4, + createConference } from "./common" type BaseTestimony = { @@ -727,7 +728,7 @@ describe("publishTestimony", () => { it.each(["reportFiled", "enacted", "dissolved"])( "Refuses testimony on a conference that is %s", async status => { - const closedId = await createConference(billId, status) + const closedId = await createConference(billId, { status }) const { draftId: conferenceDraftId } = await createConferenceDraft( uid, billId, @@ -1621,31 +1622,6 @@ async function createDraftAttachment(uid: string, id: string, content: string) { /** A conference whose canonical bill is `billId`, with its counts zeroed. It * takes testimony only while `status` is appointed. */ -async function createConference(billId: string, status = "appointed") { - const id = `conference-${nanoid()}`.toLowerCase() - await testDb - .doc(`/generalCourts/${currentGeneralCourt}/conferences/${id}`) - .set({ - id, - court: currentGeneralCourt, - title: "Test conference", - senateBillId: billId, - houseBillId: "H1", - canonicalBillId: billId, - conferees: [], - status, - hearingIds: [], - differences: [], - similarities: [], - testimonyCount: 0, - passNothingCount: 0, - passSomethingCount: 0, - passSenateVersionCount: 0, - passHouseVersionCount: 0 - }) - return id -} - async function getConference(id: string) { const doc = await testDb .doc(`/generalCourts/${currentGeneralCourt}/conferences/${id}`)