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 --}}
+
+
+
+
+
+ {{this.newTestimonyCount}}
+
+
+ {{#ifGreaterThan this.newTestimonyCount 1}}
+ New Inputs
+ {{else}}
+ New Input
+ {{/ifGreaterThan}}
+
+
+ {{#each this.stances}}
+
+ | {{this.count}} |
+ {{this.stance}} |
+
+ {{/each}}
+
+
+
+
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}`)
|