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 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 | 5x 5x 5x 5x 5x 12x 12x 2x 10x 1x 9x 53x 1x 9x 9x 6x 1x 5x 5x 16x 1x 4x 11x 4x 9x 14x 6x 4x 9x 9x 2x 7x 1x 6x 3x 3x 3x 3x 10x 1x 2x 2x 1x 1x 14x 14x 2x 12x 1x 11x 3x 8x 8x 1x 7x 7x 5x 1x 4x 4x 3x 1x 3x 6x 6x 1x 5x 5x 1x 20x 4x 17x 1x 15x 3x 3x 1x 4x 3x 2x 4x 2x 1x 1x 1x 5x 5x 3x 12x 3x 18x 3x 2x 2x 4x 4x 16x 16x 4x 24x 4x 4x | // Pipeline Stages Service - Business Logic Layer
import type { Dal } from "../../dal";
import type { PipelineStage } from "../../db/schema";
import {
ForbiddenError,
NotFoundError,
ValidationError,
ConflictError,
} from "../../lib/errors";
const MAX_INTERMEDIATE_STAGES = 5;
const STAGE_NAME_MIN_LENGTH = 1;
const STAGE_NAME_MAX_LENGTH = 50;
const DEFAULT_PIPELINE_STAGES = [
{ name: "New", position: 0, stageType: "system_entry" as const },
{
name: "In Discussion",
position: 1,
stageType: "default_deletable" as const,
},
{ name: "Won", position: 2, stageType: "system_terminal_won" as const },
{ name: "Lost", position: 3, stageType: "system_terminal_lost" as const },
];
const DEFAULT_LEAD_SOURCES = [
{
name: "Interioring Marketplace",
icon: "rocket",
color: "#FF6B35",
isSystem: true,
},
{ name: "Walk-in", icon: "door-open", color: "#10B981", isSystem: false },
{ name: "Referral", icon: "users", color: "#8B5CF6", isSystem: false },
{ name: "Instagram", icon: "instagram", color: "#E4405F", isSystem: false },
{ name: "Google", icon: "search", color: "#4285F4", isSystem: false },
{ name: "Other", icon: "circle", color: "#6B7280", isSystem: false },
];
function validateStageName(name: string): string {
const trimmed = name.trim();
if (
trimmed.length < STAGE_NAME_MIN_LENGTH ||
trimmed.length > STAGE_NAME_MAX_LENGTH
) {
throw new ValidationError(
`Stage name must be between ${STAGE_NAME_MIN_LENGTH} and ${STAGE_NAME_MAX_LENGTH} characters`,
);
}
// Must contain at least one alphanumeric character
if (!/[a-zA-Z0-9]/.test(trimmed)) {
throw new ValidationError(
"Stage name must contain at least one alphanumeric character",
);
}
return trimmed;
}
export class PipelineStagesService {
constructor(private dal: Dal) {}
async getStages(proId: string): Promise<PipelineStage[]> {
return this.dal.pipelineStages.findByProId(proId);
}
async createStage(
proId: string,
input: { name: string; position?: number },
): Promise<PipelineStage> {
const name = validateStageName(input.name);
// Check intermediate stage limit
const intermediateCount =
await this.dal.pipelineStages.countIntermediateByProId(proId);
if (intermediateCount >= MAX_INTERMEDIATE_STAGES) {
throw new ValidationError(
`Maximum ${MAX_INTERMEDIATE_STAGES} custom stages allowed`,
);
}
// Check for duplicate name
const existingStages =
await this.dal.pipelineStages.findByProId(proId);
if (
existingStages.some((s) => s.name.toLowerCase() === name.toLowerCase())
) {
throw new ConflictError(`Stage "${name}" already exists`);
}
// Determine position: insert before terminal stages
const terminalIndex = existingStages.findIndex(
(s) =>
s.stageType === "system_terminal_won" ||
s.stageType === "system_terminal_lost",
);
const position =
input.position ??
(terminalIndex >= 0 ? terminalIndex : existingStages.length);
// Shift positions of terminal stages
for (const stage of existingStages) {
if (stage.position >= position) {
await this.dal.pipelineStages.update(stage.id, {
position: stage.position + 1,
});
}
}
return this.dal.pipelineStages.create({
proId,
name,
position,
stageType: "user_created",
});
}
async updateStage(
proId: string,
stageId: number,
input: { name: string },
): Promise<PipelineStage> {
const stage = await this.dal.pipelineStages.findById(stageId);
if (!stage || stage.deletedAt) {
throw new NotFoundError("Pipeline stage", String(stageId));
}
if (stage.proId !== proId) {
throw new ForbiddenError("Stage does not belong to this pro");
}
// System stages cannot be renamed
if (
stage.stageType === "system_entry" ||
stage.stageType === "system_terminal_won" ||
stage.stageType === "system_terminal_lost"
) {
throw new ValidationError("System stages cannot be renamed");
}
const name = validateStageName(input.name);
// Check for duplicate name
const existingStages = await this.dal.pipelineStages.findByProId(
stage.proId,
);
if (
existingStages.some(
(s) => s.id !== stageId && s.name.toLowerCase() === name.toLowerCase(),
)
) {
throw new ConflictError(`Stage "${name}" already exists`);
}
const updated = await this.dal.pipelineStages.update(stageId, { name });
if (!updated) {
throw new NotFoundError("Pipeline stage", String(stageId));
}
return updated;
}
async deleteStage(
proId: string,
stageId: number,
reassignToStageId?: number,
): Promise<void> {
const stage = await this.dal.pipelineStages.findById(stageId);
if (!stage || stage.deletedAt) {
throw new NotFoundError("Pipeline stage", String(stageId));
}
if (stage.proId !== proId) {
throw new ForbiddenError("Stage does not belong to this pro");
}
// Cannot delete system stages
if (
stage.stageType === "system_entry" ||
stage.stageType === "system_terminal_won" ||
stage.stageType === "system_terminal_lost"
) {
throw new ValidationError("System stages cannot be deleted");
}
// Cannot delete last intermediate stage
const intermediateCount =
await this.dal.pipelineStages.countIntermediateByProId(stage.proId);
if (intermediateCount <= 1) {
throw new ValidationError("Cannot delete the last intermediate stage");
}
// Check if any leads are on this stage
const leadCount = await this.dal.leads.countByStageId(stageId);
if (leadCount > 0) {
if (!reassignToStageId) {
throw new ValidationError(
"Cannot delete stage with active leads. Provide a reassignment target stage.",
);
}
const targetStage =
await this.dal.pipelineStages.findById(reassignToStageId);
if (
!targetStage ||
targetStage.deletedAt ||
targetStage.proId !== stage.proId ||
targetStage.id === stageId
) {
throw new ValidationError("Invalid reassignment target stage");
}
// Move all leads to target stage before deletion
await this.dal.leads.reassignStage(stageId, reassignToStageId);
}
// Soft delete the stage
await this.dal.pipelineStages.softDelete(stageId);
}
async reorderStages(
proId: string,
stageIds: number[],
): Promise<PipelineStage[]> {
const existingStages =
await this.dal.pipelineStages.findByProId(proId);
// Validate that all stages are included in the reorder
if (stageIds.length !== existingStages.length) {
throw new ValidationError(
`All ${existingStages.length} stages must be included in reorder`,
);
}
const uniqueIds = new Set(stageIds);
if (uniqueIds.size !== stageIds.length) {
throw new ValidationError("Duplicate stage IDs in reorder request");
}
// Validate all IDs belong to this pro
const existingIds = new Set(existingStages.map((s) => s.id));
for (const id of stageIds) {
if (!existingIds.has(id)) {
throw new ValidationError(`Stage ${id} does not belong to this pro`);
}
}
// Validate system stage order: New first, Won/Lost last
const stageMap = new Map(existingStages.map((s) => [s.id, s]));
const firstStage = stageMap.get(stageIds[0]);
if (firstStage?.stageType !== "system_entry") {
throw new ValidationError('"New" stage must be first in the pipeline');
}
// Won and Lost must be last two
const lastTwo = stageIds.slice(-2).map((id) => stageMap.get(id));
const hasWon = lastTwo.some((s) => s?.stageType === "system_terminal_won");
const hasLost = lastTwo.some(
(s) => s?.stageType === "system_terminal_lost",
);
if (!hasWon || !hasLost) {
throw new ValidationError(
'"Won" and "Lost" stages must be last in the pipeline',
);
}
await this.dal.pipelineStages.reorder(proId, stageIds);
return this.dal.pipelineStages.findByProId(proId);
}
/**
* Idempotent initialization — safe for concurrent requests.
* Uses createIfNotExists DAL methods that handle conflicts gracefully.
*/
async ensureInitialized(proId: string): Promise<void> {
const count = await this.dal.pipelineStages.countByProId(proId);
if (count > 0) return;
// Race-safe: createIfNotExists ignores conflicts from concurrent calls
for (const def of DEFAULT_PIPELINE_STAGES) {
await this.dal.pipelineStages.createIfNotExists({
proId,
name: def.name,
position: def.position,
stageType: def.stageType,
});
}
for (const def of DEFAULT_LEAD_SOURCES) {
await this.dal.leadSources.createIfNotExists({
proId,
name: def.name,
icon: def.icon,
color: def.color,
isSystem: def.isSystem,
});
}
await this.dal.crmSettings.upsert(proId, {});
}
async hasStages(proId: string): Promise<boolean> {
const count = await this.dal.pipelineStages.countByProId(proId);
return count > 0;
}
/**
* @deprecated Use ensureInitialized instead (race-safe).
*/
async initializeDefaultPipeline(proId: string): Promise<{
stages: PipelineStage[];
}> {
// Create default pipeline stages
const stages: PipelineStage[] = [];
for (const def of DEFAULT_PIPELINE_STAGES) {
const stage = await this.dal.pipelineStages.create({
proId,
name: def.name,
position: def.position,
stageType: def.stageType,
});
stages.push(stage);
}
// Create default lead sources
for (const def of DEFAULT_LEAD_SOURCES) {
await this.dal.leadSources.create({
proId,
name: def.name,
icon: def.icon,
color: def.color,
isSystem: def.isSystem,
});
}
// Create default CRM settings
await this.dal.crmSettings.upsert(proId, {});
return { stages };
}
}
|