All files / src/trpc/routers phase.ts

11.25% Statements 9/80
0% Branches 0/20
18.75% Functions 3/16
11.39% Lines 9/79

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                          11x                                   2x 2x                                                                                                                                                             12x 12x 12x 15x         15x   12x                                                                                                                                                                                                                                          
/**
 * Phase Router — create, list, get, update, dependencies, bulk create
 */
 
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import type { Phase } from '../../db/schema.js';
import type { ProcedureBuilder } from '../trpc.js';
import { requirePhaseRepository, requireTaskRepository, requireBranchManager, requireInitiativeRepository, requireProjectRepository, requireExecutionOrchestrator } from './_helpers.js';
import { phaseBranchName } from '../../git/branch-naming.js';
import { ensureProjectClone } from '../../git/project-clones.js';
 
export function phaseProcedures(publicProcedure: ProcedureBuilder) {
  return {
    createPhase: publicProcedure
      .input(z.object({
        initiativeId: z.string().min(1),
        name: z.string().min(1),
      }))
      .mutation(async ({ ctx, input }) => {
        const repo = requirePhaseRepository(ctx);
        return repo.create({
          initiativeId: input.initiativeId,
          name: input.name,
          status: 'pending',
        });
      }),
 
    listPhases: publicProcedure
      .input(z.object({ initiativeId: z.string().min(1) }))
      .query(async ({ ctx, input }) => {
        const repo = requirePhaseRepository(ctx);
        return repo.findByInitiativeId(input.initiativeId);
      }),
 
    getPhase: publicProcedure
      .input(z.object({ id: z.string().min(1) }))
      .query(async ({ ctx, input }) => {
        const repo = requirePhaseRepository(ctx);
        const phase = await repo.findById(input.id);
        if (!phase) {
          throw new TRPCError({
            code: 'NOT_FOUND',
            message: `Phase '${input.id}' not found`,
          });
        }
        return phase;
      }),
 
    updatePhase: publicProcedure
      .input(z.object({
        id: z.string().min(1),
        name: z.string().min(1).optional(),
        content: z.string().nullable().optional(),
        status: z.enum(['pending', 'approved', 'in_progress', 'completed', 'blocked', 'pending_review']).optional(),
      }))
      .mutation(async ({ ctx, input }) => {
        const repo = requirePhaseRepository(ctx);
        const { id, ...data } = input;
        return repo.update(id, data);
      }),
 
    approvePhase: publicProcedure
      .input(z.object({ phaseId: z.string().min(1) }))
      .mutation(async ({ ctx, input }) => {
        const repo = requirePhaseRepository(ctx);
        const taskRepo = requireTaskRepository(ctx);
 
        const phase = await repo.findById(input.phaseId);
        if (!phase) {
          throw new TRPCError({
            code: 'NOT_FOUND',
            message: `Phase '${input.phaseId}' not found`,
          });
        }
        if (phase.status !== 'pending') {
          throw new TRPCError({
            code: 'BAD_REQUEST',
            message: `Phase must be pending to approve (current status: ${phase.status})`,
          });
        }
 
        // Validate phase has work tasks (filter out detail tasks)
        const phaseTasks = await taskRepo.findByPhaseId(input.phaseId);
        const workTasks = phaseTasks.filter((t) => t.category !== 'detail');
        if (workTasks.length === 0) {
          throw new TRPCError({
            code: 'BAD_REQUEST',
            message: 'Phase must have tasks before it can be approved',
          });
        }
 
        return repo.update(input.phaseId, { status: 'approved' });
      }),
 
    deletePhase: publicProcedure
      .input(z.object({ id: z.string().min(1) }))
      .mutation(async ({ ctx, input }) => {
        const repo = requirePhaseRepository(ctx);
        await repo.delete(input.id);
        return { success: true };
      }),
 
    createPhasesFromPlan: publicProcedure
      .input(z.object({
        initiativeId: z.string().min(1),
        phases: z.array(z.object({
          name: z.string().min(1),
        })),
      }))
      .mutation(async ({ ctx, input }) => {
        const repo = requirePhaseRepository(ctx);
        const created: Phase[] = [];
        for (const p of input.phases) {
          const phase = await repo.create({
            initiativeId: input.initiativeId,
            name: p.name,
            status: 'pending',
          });
          created.push(phase);
        }
        return created;
      }),
 
    listInitiativePhaseDependencies: publicProcedure
      .input(z.object({ initiativeId: z.string().min(1) }))
      .query(async ({ ctx, input }) => {
        const repo = requirePhaseRepository(ctx);
        return repo.findDependenciesByInitiativeId(input.initiativeId);
      }),
 
    createPhaseDependency: publicProcedure
      .input(z.object({
        phaseId: z.string().min(1),
        dependsOnPhaseId: z.string().min(1),
      }))
      .mutation(async ({ ctx, input }) => {
        const repo = requirePhaseRepository(ctx);
 
        const phase = await repo.findById(input.phaseId);
        if (!phase) {
          throw new TRPCError({
            code: 'NOT_FOUND',
            message: `Phase '${input.phaseId}' not found`,
          });
        }
 
        const dependsOnPhase = await repo.findById(input.dependsOnPhaseId);
        if (!dependsOnPhase) {
          throw new TRPCError({
            code: 'NOT_FOUND',
            message: `Phase '${input.dependsOnPhaseId}' not found`,
          });
        }
 
        await repo.createDependency(input.phaseId, input.dependsOnPhaseId);
        return { success: true };
      }),
 
    getPhaseDependencies: publicProcedure
      .input(z.object({ phaseId: z.string().min(1) }))
      .query(async ({ ctx, input }) => {
        const repo = requirePhaseRepository(ctx);
        const dependencies = await repo.getDependencies(input.phaseId);
        return { dependencies };
      }),
 
    getPhaseDependents: publicProcedure
      .input(z.object({ phaseId: z.string().min(1) }))
      .query(async ({ ctx, input }) => {
        const repo = requirePhaseRepository(ctx);
        const dependents = await repo.getDependents(input.phaseId);
        return { dependents };
      }),
 
    removePhaseDependency: publicProcedure
      .input(z.object({
        phaseId: z.string().min(1),
        dependsOnPhaseId: z.string().min(1),
      }))
      .mutation(async ({ ctx, input }) => {
        const repo = requirePhaseRepository(ctx);
        await repo.removeDependency(input.phaseId, input.dependsOnPhaseId);
        return { success: true };
      }),
 
    getPhaseReviewDiff: publicProcedure
      .input(z.object({ phaseId: z.string().min(1) }))
      .query(async ({ ctx, input }) => {
        const phaseRepo = requirePhaseRepository(ctx);
        const initiativeRepo = requireInitiativeRepository(ctx);
        const projectRepo = requireProjectRepository(ctx);
        const branchManager = requireBranchManager(ctx);
 
        const phase = await phaseRepo.findById(input.phaseId);
        if (!phase) {
          throw new TRPCError({ code: 'NOT_FOUND', message: `Phase '${input.phaseId}' not found` });
        }
        if (phase.status !== 'pending_review') {
          throw new TRPCError({ code: 'BAD_REQUEST', message: `Phase is not pending review (status: ${phase.status})` });
        }
 
        const initiative = await initiativeRepo.findById(phase.initiativeId);
        if (!initiative?.branch) {
          throw new TRPCError({ code: 'BAD_REQUEST', message: 'Initiative has no branch configured' });
        }
 
        const initBranch = initiative.branch;
        const phBranch = phaseBranchName(initBranch, phase.name);
 
        const projects = await projectRepo.findProjectsByInitiativeId(phase.initiativeId);
        let rawDiff = '';
 
        for (const project of projects) {
          const clonePath = await ensureProjectClone(project, ctx.workspaceRoot!);
          const diff = await branchManager.diffBranches(clonePath, initBranch, phBranch);
          if (diff) {
            rawDiff += diff + '\n';
          }
        }
 
        return {
          phaseName: phase.name,
          sourceBranch: phBranch,
          targetBranch: initBranch,
          rawDiff,
        };
      }),
 
    approvePhaseReview: publicProcedure
      .input(z.object({ phaseId: z.string().min(1) }))
      .mutation(async ({ ctx, input }) => {
        const orchestrator = requireExecutionOrchestrator(ctx);
        await orchestrator.approveAndMergePhase(input.phaseId);
        return { success: true };
      }),
  };
}