Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(today): load more reports in the today sidebar (#110650)

Vojta Bartoš7df67f811f84
diff --git a/frontend/src/scenes/project-homepage/today/Today.scss b/frontend/src/scenes/project-homepage/today/Today.scss
index 2dc7637c79b2..6cf7207083cd 100644
--- a/frontend/src/scenes/project-homepage/today/Today.scss
+++ b/frontend/src/scenes/project-homepage/today/Today.scss
@@ -98,6 +98,27 @@
gap: 8px;
}
+// Lines up with the row titles: the row padding plus the icon and its gap.
+.TodaySidebar__more {
+ align-self: flex-start;
+ padding-inline: 0;
+ margin: 2px 0 0 65px;
+ font-size: 12px;
+ color: var(--today-muted);
+
+ &:hover {
+ color: var(--today-ink);
+ }
+}
+
+.TodaySidebar__more--empty {
+ color: var(--today-faint);
+
+ &:hover {
+ color: var(--today-faint);
+ }
+}
+
.TodayNavItem {
--report-color: #5c5c57;
diff --git a/frontend/src/scenes/project-homepage/today/TodayHomeSidebar.tsx b/frontend/src/scenes/project-homepage/today/TodayHomeSidebar.tsx
index 12b7a996edd0..e5517a3d5d2b 100644
--- a/frontend/src/scenes/project-homepage/today/TodayHomeSidebar.tsx
+++ b/frontend/src/scenes/project-homepage/today/TodayHomeSidebar.tsx
@@ -13,8 +13,9 @@ import { TodayPreviewTrigger } from '~/layout/today/TodayPreviewTrigger'
import { isExternalHref, itemHref, itemSource, itemStateLabel } from './todayBriefingItems'
import { TodayIcon } from './TodayIcon'
import { todayLogic } from './todayLogic'
+import { TodayMoreReports } from './TodayMoreReports'
import { TodayNavItem } from './TodayNavItem'
-import { reportIcon, reportMeta, reportSource, reportTitle } from './todaySignalReports'
+import { TodayReportNavItem } from './TodayReportNavItem'
function PersonalBriefingNavItems(): JSX.Element {
const { briefingItems, reportPreviews, hoveredItemKey } = useValues(todayLogic)
@@ -63,14 +64,11 @@ export function TodayHomeSidebar(): JSX.Element {
reports,
topReports,
reportsFailed,
- hoveredReportId,
reportSummary,
showPersonalBriefing,
personalBriefing,
teamReportPreviews,
- reportStateOverrides,
} = useValues(todayLogic)
- const { reportOpened, setHoveredReportId } = useActions(todayLogic)
// The team reports stand in until the personal briefing is written, so only their own load counts.
const loading = topReports === null && !reportsFailed
@@ -115,26 +113,16 @@ export function TodayHomeSidebar(): JSX.Element {
</>
) : (
reports.map((report) => (
- <TodayPreviewTrigger key={report.id} payload={teamReportPreviews.sidebar[report.id]}>
- <TodayNavItem
- title={reportTitle(report)}
- meta={
- itemStateLabel({ state: reportStateOverrides[report.id] ?? 'open' }) ??
- reportMeta(report)
- }
- color={reportSource(report).color}
- icon={<TodayIcon icon={reportIcon(report)} />}
- to={urls.todayReport(report.id)}
- active={hoveredReportId === report.id}
- current={reportId === report.id}
- state={reportStateOverrides[report.id]}
- dataAttr="today-nav-report"
- onClick={() => reportOpened(report, 'sidebar')}
- onHoverChange={(hovered) => setHoveredReportId(hovered ? report.id : null)}
- />
- </TodayPreviewTrigger>
+ <TodayReportNavItem
+ key={report.id}
+ report={report}
+ preview={teamReportPreviews.sidebar[report.id]}
+ source="sidebar"
+ dataAttr="today-nav-report"
+ />
))
)}
+ <TodayMoreReports />
</div>
</div>
</div>
diff --git a/frontend/src/scenes/project-homepage/today/TodayMoreReports.tsx b/frontend/src/scenes/project-homepage/today/TodayMoreReports.tsx
new file mode 100644
index 000000000000..01ba5a79e514
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/TodayMoreReports.tsx
@@ -0,0 +1,70 @@
+import { useActions, useValues } from 'kea'
+
+import { Button, Spinner } from '@posthog/quill'
+
+import { LinkPrimitive } from 'lib/lemon-ui/Link'
+import { urls } from 'scenes/urls'
+
+import { todayLogic } from './todayLogic'
+import { TodayReportNavItem } from './TodayReportNavItem'
+
+/** The reports for the person past the ones the sidebar lists, loaded on request. */
+export function TodayMoreReports(): JSX.Element | null {
+ const {
+ canLoadMoreReports,
+ moreReports,
+ moreReportsLoading,
+ sidebarMoreReports,
+ moreReportPreviews,
+ moreReportsInInbox,
+ } = useValues(todayLogic)
+ const { loadMoreReports } = useActions(todayLogic)
+
+ if (canLoadMoreReports) {
+ return (
+ <Button
+ variant="link-muted"
+ size="sm"
+ className="TodaySidebar__more"
+ // The spinner sits next to the label rather than over it: quill's `loading` overlays the
+ // button's box, which on this left-aligned link lands above the text.
+ disabled={moreReportsLoading}
+ onClick={loadMoreReports}
+ data-attr="today-nav-load-more"
+ >
+ {moreReportsLoading && <Spinner />}
+ Show more reports
+ </Button>
+ )
+ }
+ if (!moreReports) {
+ return null
+ }
+ return (
+ <>
+ {sidebarMoreReports.map((report) => (
+ <TodayReportNavItem
+ key={report.id}
+ report={report}
+ preview={moreReportPreviews.sidebar[report.id]}
+ source="sidebar_more"
+ dataAttr="today-nav-more-report"
+ />
+ ))}
+ {moreReportsInInbox > 0 ? (
+ <Button
+ variant="link-muted"
+ size="sm"
+ className="TodaySidebar__more"
+ nativeButton={false}
+ render={<LinkPrimitive to={urls.inbox()} />}
+ data-attr="today-nav-more-inbox"
+ >
+ {moreReportsInInbox} more for you in the Inbox
+ </Button>
+ ) : sidebarMoreReports.length === 0 ? (
+ <p className="TodaySidebar__more TodaySidebar__more--empty">No other reports need you right now</p>
+ ) : null}
+ </>
+ )
+}
diff --git a/frontend/src/scenes/project-homepage/today/TodayReportNavItem.tsx b/frontend/src/scenes/project-homepage/today/TodayReportNavItem.tsx
new file mode 100644
index 000000000000..1e39064cad3d
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/TodayReportNavItem.tsx
@@ -0,0 +1,44 @@
+import { useActions, useValues } from 'kea'
+
+import { urls } from 'scenes/urls'
+
+import type { TodayReportPreview } from '~/layout/today/todayPreviewCards'
+import { TodayPreviewTrigger } from '~/layout/today/TodayPreviewTrigger'
+
+import { SignalReport } from 'products/signals/frontend/inbox/types'
+
+import { itemStateLabel } from './todayBriefingItems'
+import { TodayIcon } from './TodayIcon'
+import { TodayReportOpenSource, todayLogic } from './todayLogic'
+import { TodayNavItem } from './TodayNavItem'
+import { reportIcon, reportMeta, reportSource, reportTitle } from './todaySignalReports'
+
+interface TodayReportNavItemProps {
+ report: SignalReport
+ preview: TodayReportPreview
+ source: Extract<TodayReportOpenSource, 'sidebar' | 'sidebar_more'>
+ dataAttr: string
+}
+
+export function TodayReportNavItem({ report, preview, source, dataAttr }: TodayReportNavItemProps): JSX.Element {
+ const { reportId, hoveredReportId, reportStateOverrides } = useValues(todayLogic)
+ const { reportOpened, setHoveredReportId } = useActions(todayLogic)
+
+ return (
+ <TodayPreviewTrigger payload={preview}>
+ <TodayNavItem
+ title={reportTitle(report)}
+ meta={itemStateLabel({ state: reportStateOverrides[report.id] ?? 'open' }) ?? reportMeta(report)}
+ color={reportSource(report).color}
+ icon={<TodayIcon icon={reportIcon(report)} />}
+ to={urls.todayReport(report.id)}
+ active={hoveredReportId === report.id}
+ current={reportId === report.id}
+ state={reportStateOverrides[report.id]}
+ dataAttr={dataAttr}
+ onClick={() => reportOpened(report, source)}
+ onHoverChange={(hovered) => setHoveredReportId(hovered ? report.id : null)}
+ />
+ </TodayPreviewTrigger>
+ )
+}
diff --git a/frontend/src/scenes/project-homepage/today/todayLogic.test.ts b/frontend/src/scenes/project-homepage/today/todayLogic.test.ts
index a8c1c6ecc5a2..7478282eed1c 100644
--- a/frontend/src/scenes/project-homepage/today/todayLogic.test.ts
+++ b/frontend/src/scenes/project-homepage/today/todayLogic.test.ts
@@ -8,7 +8,7 @@ import { makeReport } from 'products/signals/frontend/inbox/__mocks__/inboxMocks
import { SignalReport, SignalReportStatus } from 'products/signals/frontend/inbox/types'
import type { BriefingApi, BriefingItemReportApi } from 'products/today/frontend/generated/api.schemas'
-import { BRIEFING_POLL_MS, TOP_REPORT_COUNT, reportIdFromPath, todayLogic } from './todayLogic'
+import { BRIEFING_POLL_MS, MORE_REPORTS_LIMIT, TOP_REPORT_COUNT, reportIdFromPath, todayLogic } from './todayLogic'
import { isSampleReportId } from './todaySampleReports'
import { GENERAL_REPORT_PROMPTS, briefingForReports, reportPrompts } from './todaySignalReports'
@@ -345,6 +345,49 @@ describe('todayLogic', () => {
expect(Object.fromEntries(listParams!.entries())).toEqual({ limit: String(TOP_REPORT_COUNT) })
})
+ it.each([
+ ['one the list returns too', 'report:a', 'open', ['b', 'c'], 2],
+ // The briefing can show a report the list ranks past its page; it is on screen, so it is not "more".
+ ['one the list does not return', 'report:z', 'open', ['a', 'b', 'c'], 1],
+ // The count holds only open reports, so a resolved one on screen does not take a report off it.
+ ['a resolved one the list does not return', 'report:z', 'done', ['a', 'b', 'c'], 2],
+ ] as const)(
+ 'loads more reports past the briefing without the ones it shows, and counts the rest for the Inbox, when the briefing shows %s',
+ async (_name, shownKey, shownState, listed, remaining) => {
+ const [a, b, c] = ['a', 'b', 'c'].map((id) => makeReport({ id }))
+ const byId = { a, b, c }
+ listResponse = [200, { results: [a, b, c], count: 5 }]
+ const briefing = makeBriefing({ more_reports_count: 4 })
+ briefing.items[0].key = shownKey
+ briefing.items[0].state = shownState
+ briefing.paragraphs[0][0].item_key = shownKey
+ briefingResponses = [[200, briefing]]
+ const logic = todayLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners().toMatchValues({ canLoadMoreReports: true })
+
+ await expectLogic(logic, () => {
+ logic.actions.loadMoreReports()
+ })
+ .toDispatchActions(['loadMoreReportsSuccess'])
+ .toMatchValues({
+ sidebarMoreReports: listed.map((id) => byId[id as keyof typeof byId]),
+ moreReportsInInbox: remaining,
+ canLoadMoreReports: false,
+ })
+ expect(Object.fromEntries(listParams!.entries())).toEqual({ limit: String(MORE_REPORTS_LIMIT) })
+
+ // A refresh writes a briefing over other reports, so the loaded list folds back up.
+ await expectLogic(logic, () => {
+ logic.actions.refreshBriefing()
+ })
+ .toDispatchActions(['refreshBriefing'])
+ .toMatchValues({ moreReports: null, sidebarMoreReports: [], canLoadMoreReports: true })
+ // Let the reload the refresh triggers finish, so it cannot land in the next test.
+ .toDispatchActions(['refreshBriefingSuccess', 'loadPersonalBriefingSuccess'])
+ }
+ )
+
it('shows sample reports from ?sample=1 without asking the API, until ?sample=0', async () => {
router.actions.push('/project/1/home', { sample: '1' })
const logic = todayLogic()
diff --git a/frontend/src/scenes/project-homepage/today/todayLogic.ts b/frontend/src/scenes/project-homepage/today/todayLogic.ts
index 63a9606d4400..8da98215bb8f 100644
--- a/frontend/src/scenes/project-homepage/today/todayLogic.ts
+++ b/frontend/src/scenes/project-homepage/today/todayLogic.ts
@@ -36,6 +36,7 @@ import type {
BriefingApi,
BriefingItemApi,
BriefingItemStateEnumApi,
+ TodayItemReasonEnumApi,
} from 'products/today/frontend/generated/api.schemas'
import type { TeamPublicType } from '../../../types'
@@ -54,13 +55,17 @@ import { SAMPLE_BRIEFING, isSampleReportId, parseSampleParam, sampleTopReports }
import { TodayBriefingSegment, briefingForReports, teamReportCard } from './todaySignalReports'
export const TOP_REPORT_COUNT = 5
+// The most reports the for_you endpoint returns in one call (MAX_FOR_YOU_REPORTS on the backend).
+export const MORE_REPORTS_LIMIT = 20
+// The briefing reasons a report gets when it names the person, the reports the for_you count covers.
+const NAMES_PERSON_REASONS: ReadonlySet<TodayItemReasonEnumApi> = new Set(['waiting_for_you', 'suggested_reviewer'])
const CLOCK_MS = 30_000
export const BRIEFING_POLL_MS = 5_000
// The run's budget is 10 minutes (RUN_TIMEOUT in logic/generate.py). Stop asking a little after that.
const MAX_BRIEFING_POLLS = 132
/** Where a report was opened from, sent with the `today report opened` event. */
-export type TodayReportOpenSource = 'briefing' | 'chip' | 'sidebar'
+export type TodayReportOpenSource = 'briefing' | 'chip' | 'sidebar' | 'sidebar_more'
/** Where a question to PostHog AI came from, sent with the `today ai asked` event. */
export type TodayAskSource = 'ask_box' | 'walk_through' | 'report_page'
@@ -211,6 +216,7 @@ export interface todayLogicValues {
briefingPolls: number
briefingProgress: TodayBriefingProgress | null
briefingWaiting: boolean
+ canLoadMoreReports: boolean
gaveUpWaitingFor: string | null
greeting: string
hour: number
@@ -218,6 +224,10 @@ export interface todayLogicValues {
hoveredReportId: string | null
inboxMore: TodayInboxMore | null
moreReportCount: number
+ moreReportPreviews: Record<TodayReportPreview['surface'], Record<string, TodayReportPreview>>
+ moreReports: TodayReports | null
+ moreReportsInInbox: number
+ moreReportsLoading: boolean
now: number
personalBriefing: BriefingApi | null
personalBriefingFailed: boolean
@@ -232,6 +242,8 @@ export interface todayLogicValues {
reports: SignalReport[]
reportsFailed: boolean
showPersonalBriefing: boolean
+ shownReportIds: string[]
+ sidebarMoreReports: SignalReport[]
teamReportPreviews: Record<TodayReportPreview['surface'], Record<string, TodayReportPreview>>
topReports: TodayReports | null
topReportsLoading: boolean
@@ -287,6 +299,21 @@ export interface todayLogicActions {
item: BriefingItemApi
surface: TodayItemOpenSurface
}
+ loadMoreReports: () => any
+ loadMoreReportsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadMoreReportsSuccess: (
+ moreReports: TodayReports,
+ payload?: any
+ ) => {
+ moreReports: TodayReports
+ payload?: any
+ }
loadPersonalBriefing: () => any
loadPersonalBriefingFailure: (
error: string,
@@ -425,6 +452,32 @@ export interface todayLogicMeta {
reports: SignalReport[]
) => Record<TodayReportPreview['surface'], Record<string, TodayReportPreview>>
briefingProgress: (briefingItems: BriefingItemApi[]) => TodayBriefingProgress | null
+ shownReportIds: (
+ showPersonalBriefing: boolean,
+ briefingItems: BriefingItemApi[],
+ reports: SignalReport[]
+ ) => string[]
+ sidebarMoreReports: (
+ moreReports: TodayReports | null,
+ shownReportIds: string[],
+ useSampleData: boolean
+ ) => SignalReport[]
+ moreReportPreviews: (
+ sidebarMoreReports: SignalReport[]
+ ) => Record<TodayReportPreview['surface'], Record<string, TodayReportPreview>>
+ canLoadMoreReports: (
+ moreReports: TodayReports | null,
+ useSampleData: boolean,
+ showPersonalBriefing: boolean,
+ personalBriefing: BriefingApi | null,
+ moreReportCount: number
+ ) => boolean
+ moreReportsInInbox: (
+ moreReports: TodayReports | null,
+ showPersonalBriefing: boolean,
+ briefingItems: BriefingItemApi[],
+ reports: SignalReport[]
+ ) => number
briefingWaiting: (
personalBriefing: BriefingApi | null,
gaveUpWaitingFor: string | null,
@@ -504,6 +557,21 @@ export const todayLogic = kea<todayLogicType>([
},
},
],
+ // Every report the endpoint ranks for the person. The sidebar drops the ones it already shows.
+ moreReports: [
+ null as TodayReports | null,
+ {
+ loadMoreReports: async (): Promise<TodayReports> => {
+ if (values.currentProjectId === null) {
+ return { results: [], count: 0 }
+ }
+ const response = await signalsReportsForYouRetrieve(String(values.currentProjectId), {
+ limit: MORE_REPORTS_LIMIT,
+ })
+ return { results: response.results as unknown as SignalReport[], count: response.count }
+ },
+ },
+ ],
personalBriefing: [
null as BriefingApi | null,
{
@@ -585,6 +653,11 @@ export const todayLogic = kea<todayLogicType>([
stopWaitingForBriefing: () => 0,
},
],
+ // A refreshed briefing names other reports, so the list the sidebar loaded past the old one goes.
+ moreReports: {
+ refreshBriefing: () => null,
+ setUseSampleData: () => null,
+ },
// The refresh call returns before the page reloads the briefing. Until that reload returns
// the `writing` briefing, the page still waits, so the badge does not flip back to the button.
// A verdict shows at once in the text, the left bar and the hover card. The next briefing load
@@ -700,6 +773,73 @@ export const todayLogic = kea<todayLogicType>([
return done > 0 ? { done, total: briefingItems.length } : null
},
],
+ shownReportIds: [
+ (s) => [s.showPersonalBriefing, s.briefingItems, s.reports],
+ (showPersonalBriefing: boolean, briefingItems: BriefingItemApi[], reports: SignalReport[]): string[] =>
+ showPersonalBriefing
+ ? briefingItems.map(itemReportId).filter((id): id is string => id !== null)
+ : reports.map((report) => report.id),
+ ],
+ // Read against the list on screen now, so a briefing that loads later does not show a report twice.
+ sidebarMoreReports: [
+ (s) => [s.moreReports, s.shownReportIds, s.useSampleData],
+ (moreReports: TodayReports | null, shownReportIds: string[], useSampleData: boolean): SignalReport[] => {
+ if (!moreReports || useSampleData) {
+ return []
+ }
+ const shown = new Set(shownReportIds)
+ return moreReports.results.filter((report) => !shown.has(report.id))
+ },
+ ],
+ moreReportPreviews: [
+ (s) => [s.sidebarMoreReports],
+ (
+ sidebarMoreReports: SignalReport[]
+ ): Record<TodayReportPreview['surface'], Record<string, TodayReportPreview>> =>
+ previewsBySurface(sidebarMoreReports.map((report) => [report.id, teamReportCard(report)])),
+ ],
+ // The endpoint has no next page, so the sidebar loads more one time and then links to the Inbox.
+ canLoadMoreReports: [
+ (s) => [s.moreReports, s.useSampleData, s.showPersonalBriefing, s.personalBriefing, s.moreReportCount],
+ (
+ moreReports: TodayReports | null,
+ useSampleData: boolean,
+ showPersonalBriefing: boolean,
+ personalBriefing: BriefingApi | null,
+ moreReportCount: number
+ ): boolean => {
+ if (moreReports || useSampleData) {
+ return false
+ }
+ return showPersonalBriefing ? (personalBriefing?.more_reports_count ?? 0) > 0 : moreReportCount > 0
+ },
+ ],
+ // The endpoint counts the loaded reports plus the other open reports that name the person.
+ // What is neither loaded nor already on screen: the count covers the whole set for the person,
+ // including briefing items the page ranked past the loaded ones.
+ moreReportsInInbox: [
+ (s) => [s.moreReports, s.showPersonalBriefing, s.briefingItems, s.reports],
+ (
+ moreReports: TodayReports | null,
+ showPersonalBriefing: boolean,
+ briefingItems: BriefingItemApi[],
+ reports: SignalReport[]
+ ): number => {
+ if (!moreReports) {
+ return 0
+ }
+ // Past the loaded page the count holds only open reports that name the person, so a resolved
+ // item, or one the person only claimed, is not in it and must not be taken off it.
+ const countedShownIds = showPersonalBriefing
+ ? briefingItems
+ .filter((item) => item.state === 'open' && NAMES_PERSON_REASONS.has(item.reason))
+ .map(itemReportId)
+ .filter((id): id is string => id !== null)
+ : reports.map((report) => report.id)
+ const visible = new Set([...moreReports.results.map((report) => report.id), ...countedShownIds])
+ return Math.max(moreReports.count - visible.size, 0)
+ },
+ ],
// While a newer briefing is written, the server returns the shown one as `writing`, so the
// text stays on screen and the page keeps asking until the new one is ready.
briefingWaiting: [
@@ -853,16 +993,25 @@ export const todayLogic = kea<todayLogicType>([
})
return
}
- const rank = values.reports.findIndex((report) => teamReportCard(report).key === cardKey) + 1
- if (rank === 0 || values.useSampleData) {
+ if (values.useSampleData) {
return
}
- posthog.capture('today report previewed', {
- list: 'team',
- rank,
- has_metric: !!values.reports[rank - 1].metrics?.length,
- surface,
- })
+ // The team list stays loaded under the personal briefing, but only the list on screen counts.
+ for (const [list, reports] of [
+ ['team', values.showPersonalBriefing ? [] : values.reports],
+ ['more', values.sidebarMoreReports],
+ ] as const) {
+ const rank = reports.findIndex((report) => teamReportCard(report).key === cardKey) + 1
+ if (rank > 0) {
+ posthog.capture('today report previewed', {
+ list,
+ rank,
+ has_metric: !!reports[rank - 1].metrics?.length,
+ surface,
+ })
+ return
+ }
+ }
},
locationChanged: ({ searchParams }) => {
const useSampleData = parseSampleParam(searchParams.sample)
@@ -965,6 +1114,20 @@ export const todayLogic = kea<todayLogicType>([
})
}
},
+ loadMoreReports: () => {
+ // pinned: analytics event name and properties. Renaming them breaks dashboards.
+ posthog.capture('today more reports clicked', { shown_report_count: values.shownReportIds.length })
+ },
+ loadMoreReportsSuccess: () => {
+ // pinned: analytics event name and properties. Renaming them breaks dashboards.
+ posthog.capture('today more reports loaded', {
+ report_count: values.sidebarMoreReports.length,
+ inbox_report_count: values.moreReportsInInbox,
+ })
+ },
+ loadMoreReportsFailure: () => {
+ lemonToast.error('Couldn’t load more reports. Try again in a minute.')
+ },
reportOpened: ({ report, source }) => {
if (values.useSampleData) {
return
diff --git a/products/signals/backend/briefing_reports.py b/products/signals/backend/briefing_reports.py
index b7ffbd75b647..682e08728e10 100644
--- a/products/signals/backend/briefing_reports.py
+++ b/products/signals/backend/briefing_reports.py
@@ -11,7 +11,7 @@ from datetime import datetime
from enum import StrEnum
from typing import Any
-from django.db.models import Case, CharField, Count, F, Func, JSONField, OuterRef, Q, QuerySet, Subquery, Value, When
+from django.db.models import Case, CharField, F, Func, JSONField, OuterRef, Q, QuerySet, Subquery, Value, When
from django.db.models.functions import Cast
import pydantic
@@ -336,20 +336,17 @@ def _briefing_pick(candidates: Sequence[_BriefingCandidate], limit: int | None)
return ranked if limit is None else ranked[:limit]
-def reports_for_briefing(*, team_id: int, user_id: int, limit: int | None = None) -> list[BriefingReport]:
- """Open, actionable reports for one person, in briefing order, each tagged with its strongest relation.
+def _relation_to_person(team_id: int, user: User) -> Case:
+ """A report's strongest `BriefingReportRelation` to the person, or NULL when it has none.
- A report appears once, under the first `BriefingReportRelation` that matches. One query reads
- every candidate with its relation, priority and served scores, up to `_CANDIDATE_LIMIT`, so the
- model ranks the whole set and not only the newest reports. Urgent-unowned keeps only P0.
- `_briefing_pick` orders the candidates and `limit` keeps the best of them.
+ Reads the `briefing_priority` annotation, so the queryset must carry `_latest_priority()` first.
"""
- names_me = _names_person(team_id, User.objects.get(id=user_id))
- claimed = reports_with_active_claim(team_id=team_id, actor=ArtefactAttribution.from_user(user_id))
+ names_me = _names_person(team_id, user)
+ claimed = reports_with_active_claim(team_id=team_id, actor=ArtefactAttribution.from_user(user.id))
unowned = ~reports_with_active_claim(team_id=team_id) & ~implementation_pr_report_filter(
team_id=team_id, active_only=True
)
- relation = Case(
+ return Case(
When(
names_me & Q(status=SignalReport.Status.PENDING_INPUT), then=Value(BriefingReportRelation.WAITING_FOR_YOU)
),
@@ -367,11 +364,28 @@ def reports_for_briefing(*, team_id: int, user_id: int, limit: int | None = None
default=Value(None),
output_field=CharField(),
)
- rows = (
+
+
+def _reports_for_person(team_id: int, user: User) -> QuerySet[SignalReport]:
+ """The open reports that are for this person: the set the briefing ranks and the Inbox counts."""
+ return (
_open_reports(team_id)
.annotate(briefing_priority=_latest_priority())
- .annotate(briefing_relation=relation)
+ .annotate(briefing_relation=_relation_to_person(team_id, user))
.filter(briefing_relation__isnull=False)
+ )
+
+
+def reports_for_briefing(*, team_id: int, user_id: int, limit: int | None = None) -> list[BriefingReport]:
+ """Open, actionable reports for one person, in briefing order, each tagged with its strongest relation.
+
+ A report appears once, under the first `BriefingReportRelation` that matches. One query reads
+ every candidate with its relation, priority and served scores, up to `_CANDIDATE_LIMIT`, so the
+ model ranks the whole set and not only the newest reports. Urgent-unowned keeps only P0.
+ `_briefing_pick` orders the candidates and `limit` keeps the best of them.
+ """
+ rows = (
+ _reports_for_person(team_id, User.objects.get(id=user_id))
.annotate(briefing_heads=_latest_served_heads())
.order_by("-updated_at")
.values_list("id", "updated_at", "briefing_relation", "briefing_priority", "briefing_heads")[:_CANDIDATE_LIMIT]
@@ -425,17 +439,17 @@ class OpenReportCounts:
def open_report_counts(*, team_id: int, user: User, exclude_report_ids: Sequence[str] = ()) -> OpenReportCounts:
- """How many open, actionable reports the project has, and how many of them name this person.
+ """How many open, actionable reports the project has, and how many of them are for this person.
- `exclude_report_ids` leaves out the reports a briefing already shows; one that is resolved or
- does not name the person was never in the set, so it is not subtracted from it.
+ `for_person` counts the same set `reports_for_briefing` ranks (named, claimed, or an unowned P0),
+ so a "more for you" number agrees with the list it follows. `exclude_report_ids` leaves out the
+ reports already on screen; one that is resolved or not for the person was never in the set, so
+ it is not subtracted from it.
"""
- row = (
- _open_reports(team_id)
- .exclude(id__in=list(exclude_report_ids))
- .aggregate(in_project=Count("id"), for_person=Count("id", filter=_names_person(team_id, user)))
- )
- return OpenReportCounts(for_person=row["for_person"], in_project=row["in_project"])
+ excluded = list(exclude_report_ids)
+ in_project = _open_reports(team_id).exclude(id__in=excluded).count()
+ for_person = _reports_for_person(team_id, user).exclude(id__in=excluded).count()
+ return OpenReportCounts(for_person=for_person, in_project=in_project)
def _pull_request_state(state: str, merged: bool) -> str | None:
diff --git a/products/signals/backend/test/test_briefing_reports.py b/products/signals/backend/test/test_briefing_reports.py
index 04dcbef8118e..61df82203564 100644
--- a/products/signals/backend/test/test_briefing_reports.py
+++ b/products/signals/backend/test/test_briefing_reports.py
@@ -133,7 +133,8 @@ class TestReportsForBriefing(BaseTest):
team_id=self.team.id, user=self.user, exclude_report_ids=[str(shown_open.id), str(resolved.id)]
)
- assert counts.in_project == 1
+ # An unowned P0 is for the person the same way the briefing ranks it, so both counts agree.
+ assert (counts.in_project, counts.for_person) == (1, 1)
def test_merge_chance_comes_from_the_latest_readable_served_score(self) -> None:
rescored = self._urgent_report("Rescored")