All files / apps/developer-portal/layers/workflows/shared projectView.ts

100% Statements 161/161
90% Branches 135/150
100% Functions 56/56
100% Lines 129/129

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310                                  44x 444x 860x   644x   444x             44x   44x 522x 947x                   44x                 44x     44x           185x 185x 117x   185x 185x 430x 185x 430x               524x 430x 430x   185x 430x   336x       185x 1151x 1151x     185x 185x 180x 180x   88x 88x   180x   34x   180x 180x     185x 430x 430x   324x 324x   316x 430x   286x 430x   430x 238x   210x 73x   210x     48x 48x 41x 31x 1x   30x     430x 1486x   185x 430x 430x   430x 115x 113x 113x     430x     522x   185x 430x   316x   430x 78x   87x 87x 87x                     238x               430x         336x         90x         430x   185x 185x 291x 291x   286x 82x 82x 2x 291x   291x 291x     185x 430x 209x 81x   185x 680x 259x       430x       185x 430x     189x       185x 1665x   3870x       185x 115x 18x     97x 97x 1x     99x 96x 2x     94x 4x     90x       185x 1x             430x 185x 316x   185x 115x         185x                         430x          
import { routedNeeds, withStageNeeds } from "./capability.ts";
import { featuresOf, isEnabled, isGroupEnabled } from "./project.ts";
import { day, issueAsOf, ticketStatus } from "./ticket.ts";
import { ticketsToFile } from "./ticketSize.ts";
import { CAPABILITY_LABEL_PREFIX, CAPABILITY_STATES } from "./constants.ts";
import type { Capability } from "./types/Capability.ts";
import type { CapabilityState } from "./types/CapabilityState.ts";
import type { CapabilityView } from "./types/CapabilityView.ts";
import type { Points } from "./types/Points.ts";
import type { Progress } from "./types/Progress.ts";
import type { Project } from "./types/Project.ts";
import type { ProjectView } from "./types/ProjectView.ts";
import type { Snapshot } from "./types/Snapshot.ts";
import type { StageView } from "./types/StageView.ts";
import type { Template } from "./types/Template.ts";
import type { UnsortedIssue } from "./types/UnsortedIssue.ts";
 
const progressOf = (capabilities: CapabilityView[]): Progress => {
    const counted = capabilities.filter(
        (capability) => capability.state !== "off" && capability.state !== "skipped",
    );
    const done = counted.filter((capability) => capability.state === "done").length;
 
    return {
        done,
        total: counted.length,
        percent: counted.length === 0 ? 0 : Math.round((done / counted.length) * 100),
    };
};
 
const NO_POINTS: Points = { done: 0, total: 0, estimated: 0, unestimated: 0 };
 
const addPoints = (list: Points[]): Points =>
    list.reduce(
        (sum, points) => ({
            done: sum.done + points.done,
            total: sum.total + points.total,
            estimated: sum.estimated + points.estimated,
            unestimated: sum.unestimated + points.unestimated,
        }),
        NO_POINTS,
    );
 
/** What needs the owner first, then what an agent can take, then what can't move yet. */
const LEFT_ORDER: CapabilityState[] = [
    "waiting-on-you",
    "ready",
    "in-flight",
    "can-file",
    "blocked",
    "waits",
];
 
const FINISHED = new Set<CapabilityState>(["done", "skipped", "off"]);
 
/** One project laid over its template and its last GitHub snapshot, as of a day or as synced. */
export const projectView = (
    project: Project,
    template: Template,
    snapshot: Snapshot | null,
    asOf: string | null = null,
): ProjectView => {
    const syncedOn = snapshot?.syncedAt ? day(snapshot.syncedAt) : null;
    const issues = (snapshot?.issues ?? []).flatMap(
        (issue) => issueAsOf(issue, asOf, syncedOn) ?? [],
    );
    const extraIds = new Set(project.extras.map((extra) => extra.id));
    const all = withStageNeeds([...template.capabilities, ...project.extras]);
    const byId = new Map(all.map((capability) => [capability.id, capability]));
    const enabled = new Map(
        all.map((capability) => [
            capability.id,
            extraIds.has(capability.id)
                ? isGroupEnabled(capability.group, project, template)
                : isEnabled(capability, project, template),
        ]),
    );
 
    const needs = routedNeeds(all, ({ id }) => enabled.get(id) === true);
    const dependents = new Map(all.map(({ id }) => [id, [] as string[]]));
    for (const [id, list] of needs) for (const need of list) dependents.get(need)?.push(id);
 
    const live = new Map(
        all.map(({ id }) => [
            id,
            issues.filter((issue) => issue.caps.includes(id) && issue.reason !== "not_planned"),
        ]),
    );
 
    const settledFor = (id: string) => {
        const settled = project.settled[id];
        return settled && (!settled.on || asOf === null || settled.on <= asOf) ? settled : null;
    };
 
    const finished = new Map<string, boolean>();
    const isFinished = (id: string): boolean => {
        const known = finished.get(id);
        if (known !== undefined) return known;
 
        const settled = settledFor(id);
        const tickets = live.get(id) ?? [];
        const result =
            !enabled.get(id) ||
            settled !== null ||
            (tickets.length > 0 && tickets.every(({ state }) => state === "closed"));
 
        finished.set(id, result);
        return result;
    };
 
    const stateOf = (capability: Capability): CapabilityState => {
        const { id } = capability;
        if (!enabled.get(id)) return "off";
 
        const settled = settledFor(id);
        if (settled) return settled.status;
 
        const tickets = live.get(id) ?? [];
        if (tickets.length > 0 && tickets.every(({ state }) => state === "closed")) return "done";
 
        const open = (needs.get(id) ?? []).filter((need) => !isFinished(need));
        const openTickets = tickets.filter(({ state }) => state === "open");
 
        if (openTickets.length === 0) {
            if (capability.kind === "owner" && open.length === 0) return "waiting-on-you";
 
            const holding = open.filter(
                (need) => byId.get(need)?.kind !== "build" || (live.get(need) ?? []).length === 0,
            );
            return holding.length > 0 ? "waits" : "can-file";
        }
 
        const statuses = openTickets.map(ticketStatus);
        if (statuses.includes("in-flight")) return "in-flight";
        if (open.length > 0 || statuses.every((status) => status === "blocked")) return "blocked";
        if (capability.kind === "owner" || statuses.includes("waiting-on-you")) {
            return "waiting-on-you";
        }
        return "ready";
    };
 
    const states = new Map(all.map((capability) => [capability.id, stateOf(capability)]));
    const isOpen = (id: string) => !FINISHED.has(states.get(id) ?? "off");
 
    const unblockCount = (id: string): number => {
        const seen = new Set<string>();
        const queue = [...(dependents.get(id) ?? [])];
 
        for (let next = queue.pop(); next !== undefined; next = queue.pop()) {
            if (seen.has(next) || !isOpen(next)) continue;
            seen.add(next);
            queue.push(...(dependents.get(next) ?? []));
        }
 
        return seen.size;
    };
 
    const scores = (id: string) => byId.has(id) && enabled.get(id) === true && !settledFor(id);
 
    const pointsOf = (capability: Capability): Points => {
        if (!scores(capability.id)) return NO_POINTS;
 
        const tickets = live.get(capability.id) ?? [];
 
        if (tickets.length > 0) {
            return addPoints(
                tickets.map((ticket) => {
                    const sharers = ticket.caps.filter(scores);
                    const share = (ticket.complexity ?? 0) / sharers.length;
                    return {
                        done: ticket.state === "closed" ? share : 0,
                        total: share,
                        estimated: 0,
                        unestimated:
                            ticket.complexity === null && sharers[0] === capability.id ? 1 : 0,
                    };
                }),
            );
        }
 
        return {
            done: 0,
            total: capability.complexity ?? 0,
            estimated: capability.complexity ?? 0,
            unestimated: capability.complexity === null ? 1 : 0,
        };
    };
 
    const views: CapabilityView[] = all.map((capability) => ({
        ...capability,
        enabled: enabled.get(capability.id) ?? false,
        extra: extraIds.has(capability.id),
        note: project.settled[capability.id]?.note || null,
        issues: issues.filter((issue) => issue.caps.includes(capability.id)),
        state: states.get(capability.id) ?? "off",
        needs: needs.get(capability.id) ?? [],
        unblocks: dependents.get(capability.id) ?? [],
        waitingOn: isOpen(capability.id)
            ? (needs.get(capability.id) ?? []).filter((need) => !isFinished(need))
            : [],
        unblockCount: unblockCount(capability.id),
        points: pointsOf(capability),
    }));
    const viewById = new Map(views.map((view) => [view.id, view]));
 
    const chains = new Map<string, string[]>();
    const chainFrom = (id: string, walking: Set<string>): string[] => {
        const known = chains.get(id);
        if (known) return known;
 
        const next = (dependents.get(id) ?? [])
            .filter((dependent) => isOpen(dependent) && !walking.has(dependent))
            .map((dependent) => chainFrom(dependent, new Set([...walking, dependent])))
            .sort((a, b) => b.length - a.length)[0];
        const chain = [id, ...(next ?? [])];
 
        chains.set(id, chain);
        return chain;
    };
    const critical =
        views
            .filter((view) => isOpen(view.id) && view.waitingOn.length === 0)
            .map((view) => chainFrom(view.id, new Set([view.id])))
            .sort((a, b) => b.length - a.length)[0] ?? [];
 
    const stages: StageView[] = template.stages.map((stage) => {
        const capabilities = views.filter((capability) => capability.stage === stage.id);
        return {
            ...stage,
            capabilities,
            progress: progressOf(capabilities),
            points: addPoints(capabilities.map(({ points }) => points)),
        };
    });
 
    const left = views
        .filter((view) => isOpen(view.id))
        .sort(
            (a, b) =>
                LEFT_ORDER.indexOf(a.state) - LEFT_ORDER.indexOf(b.state) ||
                b.unblockCount - a.unblockCount,
        );
 
    const counts = Object.fromEntries(
        CAPABILITY_STATES.map((state) => [
            state,
            views.filter((view) => view.state === state).length,
        ]),
    ) as Record<CapabilityState, number>;
 
    const unsorted: UnsortedIssue[] = issues.flatMap((issue): UnsortedIssue[] => {
        if (issue.caps.length === 0) {
            return [{ issue, reason: "noLabel", detail: CAPABILITY_LABEL_PREFIX }];
        }
 
        const group = template.groups.find(({ id }) => issue.caps.includes(id));
        if (group) {
            return [{ issue, reason: "group", detail: group.id }];
        }
 
        const unknown = issue.caps.filter((cap) => !viewById.has(cap));
        if (unknown.length > 0) {
            return [{ issue, reason: "unknown", detail: unknown.join(", ") }];
        }
 
        if (issue.state === "open" && issue.caps.every((cap) => !enabled.get(cap))) {
            return [{ issue, reason: "off", detail: "" }];
        }
 
        return [];
    });
 
    const strays: UnsortedIssue[] =
        asOf === null && left.length > 0
            ? (snapshot?.noMilestone ?? []).map((issue) => ({
                  issue,
                  reason: "noMilestone",
                  detail: "",
              }))
            : [];
 
    const pool = all.filter(({ id }) => enabled.get(id) && !settledFor(id));
    const filedIds = new Set(
        pool.flatMap(({ id }) => ((live.get(id) ?? []).length > 0 ? [id] : [])),
    );
    const tickets = {
        filed: issues.filter((issue) => issue.caps.length > 0 && issue.reason !== "not_planned")
            .length,
        toFile: ticketsToFile(pool, needs, filedIds),
    };
 
    return {
        project,
        template,
        snapshot,
        asOf,
        features: featuresOf(project, template),
        stages,
        capabilities: views,
        left,
        counts,
        critical,
        unsorted: [...unsorted, ...strays],
        progress: progressOf(views),
        points: addPoints(views.map(({ points }) => points)),
        tickets,
        syncedAt: snapshot?.syncedAt ?? null,
    };
};