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

100% Statements 134/134
88.57% Branches 62/70
100% Functions 51/51
100% Lines 114/114

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                        45x     45x 604x 604x   604x 888x 378x   860x     604x       45x 473x 473x   473x 1118x 1118x   860x 860x 260x 258x 258x     860x 860x     860x 473x       45x 251x 251x 530x 266x 14x   251x   279x       45x           604x   604x 860x 860x   257x 279x     860x 243x 243x   617x       617x             45x     152x   708x   860x 473x 473x   473x 949x 949x   794x     254x 254x 60x     194x 194x               949x 949x     473x 860x 781x 26x 755x     473x 473x 860x 860x     473x 604x               45x         234x 702x     1242x     1007x                   45x         285x                           45x         56x 180x       45x         47x 47x 47x 134x     47x               45x       65x   65x 106x 69x   35x     69x 69x         45x         22x 21x   22x   49x   22x 22x 45x   26x                 22x                   27x 24x   33x     5x 5x     5x 1x                 45x  
import { routedNeeds, withStageNeeds } from "./capability.ts";
import { complexityOf } from "./complexity.ts";
import { featuresOf, isEnabled } from "./project.ts";
import type { NewPage } from "./projectFile.ts";
import { TICKET_SIZES } from "./constants.ts";
import type { Capability } from "./types/Capability.ts";
import type { Project } from "./types/Project.ts";
import type { ReceiptRow } from "./types/ReceiptRow.ts";
import type { Template } from "./types/Template.ts";
import type { TicketSize } from "./types/TicketSize.ts";
 
/** The points a shared ticket holds before the next block wraps onto a new one. */
export const TICKET_WIDTH = { supervised: 13, fast: 21 } as const;
 
/** Puts each block after the ones it needs from the same group, keeping template order otherwise. */
const inDependencyOrder = (group: Capability[], needs: Map<string, string[]>): Capability[] => {
    const left = [...group];
    const order: Capability[] = [];
 
    while (left.length > 0) {
        const ready = left.findIndex(({ id }) =>
            (needs.get(id) ?? []).every((need) => !left.some((other) => other.id === need)),
        );
        order.push(...left.splice(Math.max(0, ready), 1));
    }
 
    return order;
};
 
/** Every block each one waits on, directly or through others, among the blocks being bundled. */
const ancestorsOf = (ids: string[], needs: Map<string, string[]>): Map<string, Set<string>> => {
    const known = new Set(ids);
    const ancestors = new Map<string, Set<string>>();
 
    const walk = (id: string, seen: Set<string>): Set<string> => {
        const cached = ancestors.get(id);
        if (cached) return cached;
 
        const found = new Set<string>();
        for (const need of needs.get(id) ?? []) {
            if (!known.has(need) || seen.has(need)) continue;
            found.add(need);
            for (const further of walk(need, new Set([...seen, need]))) found.add(further);
        }
 
        ancestors.set(id, found);
        return found;
    };
 
    for (const id of ids) walk(id, new Set([id]));
    return ancestors;
};
 
/** Whether every member would wait on exactly what the ticket waits on, so none inherits a wait. */
const sharesWaits = (members: string[], ancestors: Map<string, Set<string>>): boolean => {
    const inside = new Set(members);
    const outside = (id: string) =>
        [...(ancestors.get(id) ?? [])]
            .filter((need) => !inside.has(need))
            .sort((a, b) => a.localeCompare(b))
            .join(",");
    const [first, ...rest] = members.map(outside);
 
    return rest.every((waits) => waits === first);
};
 
/** Puts each block in the first ticket it fits, by width and by waits, or starts another. */
const pack = (
    group: Capability[],
    width: number,
    needs: Map<string, string[]>,
    ancestors: Map<string, Set<string>>,
): Capability[][] => {
    const lines: { members: Capability[]; points: number }[] = [];
 
    for (const capability of inDependencyOrder(group, needs)) {
        const weight = capability.complexity ?? 0;
        const line = lines.find(
            ({ members, points }) =>
                points + weight <= width &&
                sharesWaits([...members.map(({ id }) => id), capability.id], ancestors),
        );
 
        if (line) {
            line.members.push(capability);
            line.points += weight;
        } else {
            lines.push({ members: [capability], points: weight });
        }
    }
 
    return lines.map(({ members }) => members);
};
 
/**
 * Mirrors `bundlesOf` in the scripts' `domain/filing.ts`; change both together. `pool` is every
 * block that is on and unsettled, filed or not, so the bundles never shift as tickets are filed.
 */
export const bundlesOf = (
    pool: Capability[],
    size: TicketSize,
    needs: Map<string, string[]> = routedNeeds(pool, () => true),
): Capability[][] => {
    if (size === "block") return pool.map((capability) => [capability]);
 
    const byId = new Map(pool.map((capability) => [capability.id, capability]));
    const ancestors = ancestorsOf([...byId.keys()], needs);
    const levels = new Map<string, number>();
 
    const levelOf = (capability: Capability, walking: Set<string>): number => {
        const known = levels.get(capability.id);
        if (known !== undefined) return known;
 
        const level = Math.max(
            0,
            ...(needs.get(capability.id) ?? []).flatMap((need) => {
                const dependency = byId.get(need);
                if (dependency?.stage !== capability.stage || walking.has(need)) {
                    return [];
                }
 
                const behind = levelOf(dependency, new Set([...walking, need]));
                return [
                    capability.kind !== "build" && dependency.kind === "build"
                        ? behind + 1
                        : behind,
                ];
            }),
        );
 
        levels.set(capability.id, level);
        return level;
    };
 
    const keyOf = (capability: Capability): string => {
        if (capability.kind === "owner") return `owner:${capability.id}`;
        if (capability.kind === "spike")
            return size === "fast" ? "spike" : `spike:${capability.id}`;
        return `build:${capability.stage}:${levelOf(capability, new Set([capability.id]))}`;
    };
 
    const groups = new Map<string, Capability[]>();
    for (const capability of pool) {
        const key = keyOf(capability);
        groups.set(key, [...(groups.get(key) ?? []), capability]);
    }
 
    return [...groups.values()].flatMap((group) =>
        pack(group, TICKET_WIDTH[size], needs, ancestors),
    );
};
 
/**
 * The tickets the unfiled blocks of `pool` would become: a block filed alone becomes its suggested
 * tickets, and a bundle one ticket for whichever of its members are still unfiled.
 */
export const ticketsToFile = (
    pool: Capability[],
    needs?: Map<string, string[]>,
    filed: Set<string> = new Set(),
): Record<TicketSize, number> =>
    Object.fromEntries(
        TICKET_SIZES.map((size) => [
            size,
            bundlesOf(pool, size, needs)
                .map((bundle) => bundle.filter(({ id }) => !filed.has(id)))
                .reduce(
                    (sum, bundle) =>
                        sum +
                        (bundle.length > 1
                            ? 1
                            : Math.max(bundle.length, bundle[0]?.tickets.length ?? 0)),
                    0,
                ),
        ]),
    ) as Record<TicketSize, number>;
 
/** A project not yet written, so a template's features and counts can be shown before it exists. */
export const draftProject = (
    template: Template,
    switches: Record<string, boolean> = {},
    ticketSize: TicketSize = "block",
    extras: Capability[] = [],
): Project => ({
    id: "",
    title: "",
    template: template.id,
    area: "",
    milestone: "",
    summary: "",
    switches,
    ticketSize,
    settled: {},
    extras,
});
 
/** The blocks a template turns on under these switches, its defaults where a switch is unset. */
export const blocksOn = (
    template: Template,
    switches: Record<string, boolean> = {},
    extras: Capability[] = [],
): Capability[] =>
    template.capabilities.filter((capability) =>
        isEnabled(capability, draftProject(template, switches, "block", extras), template),
    );
 
/** What a template files under these switches and extras: blocks, tickets at each size, and points. */
export const estimateOf = (
    template: Template,
    switches: Record<string, boolean> = {},
    extras: Capability[] = [],
) => {
    const project = draftProject(template, switches, "block", extras);
    const blocks = [...blocksOn(template, switches, extras), ...extras];
    const needs = routedNeeds(withStageNeeds([...template.capabilities, ...extras]), (capability) =>
        isEnabled(capability, project, template),
    );
 
    return {
        blocks: blocks.length,
        tickets: ticketsToFile(blocks, needs),
        points: complexityOf(blocks),
    };
};
 
/** What each page adds, in order: its type's points plus any on-demand setup no earlier page brought. */
export const pageCosts = (
    template: Template,
    pages: { type: string }[],
): { points: number; setup: Capability[] }[] => {
    const brought = new Set<string>();
 
    return pages.map(({ type }) => {
        const pageType = template.types.find(({ id }) => id === type);
        const setup = template.capabilities.filter(
            ({ id, onDemand }) =>
                onDemand && !brought.has(id) && (pageType?.dependsOn.includes(id) ?? false),
        );
 
        for (const { id } of setup) brought.add(id);
        return { points: (pageType?.complexity ?? 0) + complexityOf(setup), setup };
    });
};
 
/** The core blocks, each feature switched on and each page: `estimateOf`'s points, line by line. */
export const receiptOf = (
    template: Template,
    switches: Record<string, boolean> = {},
    pages: NewPage[] = [],
): ReceiptRow[] => {
    const optionalGroups = new Set(
        template.groups.filter(({ optional }) => optional).map(({ id }) => id),
    );
    const core = template.capabilities.filter(
        ({ optional, onDemand, group }) =>
            !optional && !onDemand && !(group && optionalGroups.has(group)),
    );
    const costs = pageCosts(template, pages);
    const on = featuresOf(draftProject(template, switches), template).filter(
        ({ enabled }) => enabled,
    );
    const row = ({ id, title, points }: (typeof on)[number], nested: boolean): ReceiptRow => ({
        id,
        label: title,
        type: null,
        setup: [],
        points,
        nested,
    });
 
    return [
        {
            id: "core",
            label: "",
            type: null,
            setup: [],
            points: complexityOf(core),
            nested: false,
        },
        ...on
            .filter(({ within }) => within === null)
            .flatMap((parent) => [
                row(parent, false),
                ...on.filter(({ within }) => within === parent.id).map((child) => row(child, true)),
            ]),
        ...pages.map(({ type, title }, index) => {
            const { points, setup } = costs[index] ?? { points: 0, setup: [] };
            return {
                id: `page-${index}`,
                label: title,
                type: template.types.find(({ id }) => id === type)?.title ?? null,
                setup: setup.map((block) => block.title),
                points,
                nested: false,
            };
        }),
    ];
};
 
/** What a template files with its defaults on. */
export const templateEstimate = (template: Template) => estimateOf(template);