: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import { MakeLogicType, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { ApiConfig } from 'lib/api'
import { dayjs } from 'lib/dayjs'
import { dateMapping } from 'lib/utils/dateFilters'
import { engineeringAnalyticsTeamCiHealth } from '../generated/api'
import type { TeamCIHealthItemApi } from '../generated/api.schemas'
import {
LoaderStatus,
awaitsRepoForward,
engineeringAnalyticsLogic,
loaderStatusFromError,
} from './engineeringAnalyticsLogic'
const projectId = (): string => String(ApiConfig.getCurrentProjectId())
export type TeamsWindow = '-24h' | '-7d' | '-14d' | '-30d'
export const DEFAULT_TEAMS_WINDOW: TeamsWindow = '-14d'
export const TEAMS_WINDOW_LABELS: Record<TeamsWindow, { prior: string; current: string }> = {
'-24h': { prior: 'Previous 24 hours', current: 'Last 24 hours' },
'-7d': { prior: 'Previous 7 days', current: 'Last 7 days' },
'-14d': { prior: 'Previous 14 days', current: 'Last 14 days' },
'-30d': { prior: 'Previous 30 days', current: 'Last 30 days' },
}
function isTeamsWindow(value: unknown): value is TeamsWindow {
return typeof value === 'string' && value in TEAMS_WINDOW_LABELS
}
const MAX_TEAMS_WINDOW_DAYS = 30
/** Whether the team page can show this range: one of its presets, or a fixed range of at most 30 days. */
export function isTeamsDateRange(dateFrom: string | null, dateTo: string | null): boolean {
if (isTeamsWindow(dateFrom)) {
return dateTo === null
}
if (!dateFrom || dateFrom.startsWith('-') || !dayjs(dateFrom).isValid()) {
return false
}
const span = (dateTo ? dayjs(dateTo) : dayjs()).diff(dayjs(dateFrom), 'day')
return span >= 0 && span <= MAX_TEAMS_WINDOW_DAYS
}
// date_from presets the team endpoints accept (max 30d; an equal-length prior twin is scanned).
export const TEAMS_WINDOW_DATE_OPTIONS = dateMapping.filter(({ values }) => isTeamsWindow(values[0]))
export const UNOWNED_TEAM = 'unowned'
export function teamLabel(ownerTeam: string): string {
return ownerTeam === UNOWNED_TEAM ? 'Unowned' : ownerTeam
}
export interface TeamCIHealthRow {
ownerTeam: string
/** Owned tests an in-job retry recovered in the window: the queue's `confirmed_flake`. */
flakyTestCount: number
flakyTestCountPrior: number
/** Owned tests that failed with no such proof and still hit the blast-radius bar. */
regressionTestCount: number
failedRunCount: number
failedRunCountPrior: number
/** Owned test files per the daily owners.yaml census; null until a census ran. */
testFileCount: number | null
testFileCountPrior: number | null
/** Merged PRs by the team's members; null without the membership snapshot. */
mergedPrCount: number | null
mergedPrCountPrior: number | null
}
export interface TeamsData {
rows: TeamCIHealthRow[]
truncated: boolean
limit: number
}
export function toTeamCIHealthRow(it: TeamCIHealthItemApi): TeamCIHealthRow {
return {
ownerTeam: it.owner_team,
flakyTestCount: it.flaky_test_count,
flakyTestCountPrior: it.flaky_test_count_prior,
regressionTestCount: it.regression_test_count,
failedRunCount: it.failed_run_count,
failedRunCountPrior: it.failed_run_count_prior,
testFileCount: it.test_file_count ?? null,
testFileCountPrior: it.test_file_count_prior ?? null,
mergedPrCount: it.merged_pr_count ?? null,
mergedPrCountPrior: it.merged_pr_count_prior ?? null,
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface teamsLogicValues {
scopeRepo: string | null // engineeringAnalyticsLogic
sourceId: string | null // engineeringAnalyticsLogic
teams: TeamsData | null
teamsFailed: boolean
teamsLoading: boolean
teamsNotConnected: boolean
teamsStatus: LoaderStatus
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface teamsLogicActions {
refresh: () => {
value: true
} // engineeringAnalyticsLogic
loadTeams: (_: void) => void
loadTeamsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadTeamsSuccess: (
teams: TeamsData,
payload?: void
) => {
teams: TeamsData
payload?: void
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface teamsLogicMeta {
__keaTypeGenInternalSelectorTypes: {
teamsFailed: (teamsStatus: LoaderStatus) => boolean
teamsNotConnected: (teamsStatus: LoaderStatus) => boolean
}
}
export type teamsLogicType = MakeLogicType<teamsLogicValues, teamsLogicActions, Record<string, any>, teamsLogicMeta>
export const teamsLogic = kea<teamsLogicType>([
path(['products', 'engineering_analytics', 'frontend', 'scenes', 'teamsLogic']),
connect(() => ({
values: [engineeringAnalyticsLogic, ['sourceId', 'scopeRepo']],
actions: [engineeringAnalyticsLogic, ['refresh']],
})),
loaders(({ values }) => ({
teams: [
null as TeamsData | null,
{
loadTeams: async (_: void, breakpoint): Promise<TeamsData> => {
const data = await engineeringAnalyticsTeamCiHealth(projectId(), {
date_from: DEFAULT_TEAMS_WINDOW,
source_id: values.sourceId ?? undefined,
repo: values.scopeRepo ?? undefined,
})
// A repository switch starts a new load; drop this response if one did.
breakpoint()
return {
rows: data.items.map(toTeamCIHealthRow),
truncated: data.truncated,
limit: data.limit,
}
},
},
],
})),
reducers({
teamsStatus: [
'ok' as LoaderStatus,
{
loadTeams: () => 'ok',
loadTeamsSuccess: () => 'ok',
loadTeamsFailure: (_, { errorObject }) => loaderStatusFromError(errorObject),
},
],
}),
selectors({
teamsFailed: [(s) => [s.teamsStatus], (status: LoaderStatus): boolean => status === 'error'],
teamsNotConnected: [(s) => [s.teamsStatus], (status: LoaderStatus): boolean => status === 'notConnected'],
}),
listeners(({ actions }) => ({
// engineeringAnalyticsLogic refreshes on every source or repo change and after a repo-less forward.
refresh: () => actions.loadTeams(),
})),
afterMount(({ actions }) => {
if (!awaitsRepoForward()) {
actions.loadTeams()
}
}),
])