All files / src/lib/workflows step-executor.ts

15.57% Statements 76/488
100% Branches 0/0
0% Functions 0/14
15.57% Lines 76/488

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 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 4891x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                                                                                               1x 1x 1x 1x                                                                                                             1x 1x 1x 1x                                           1x 1x 1x 1x                                     1x 1x 1x 1x                                                                                 1x 1x 1x 1x                     1x 1x 1x 1x                   1x 1x 1x 1x                                                                 1x 1x 1x 1x                                                   1x 1x 1x 1x                             1x 1x 1x 1x                                                                         1x 1x 1x 1x                                                                           1x 1x 1x 1x                                                                         1x 1x 1x 1x                    
import { prisma } from "@/lib/prisma";
import { logger } from "@/lib/logging";
import type {
  WorkflowStepConfig,
  WorkflowExecutionContext,
  StepExecutionResult,
  SendEmailStepConfig,
  WaitDelayStepConfig,
  WaitUntilStepConfig,
  ConditionStepConfig,
  SplitABStepConfig,
  UpdateSegmentStepConfig,
  AddPointsStepConfig,
  ApplyCouponStepConfig,
  WebhookStepConfig,
  ConditionGroup,
  ConditionRule } from "./types";
 
const LOG_CATEGORY = "WORKFLOW_STEP_EXECUTOR";
 
/**
 * Execute a workflow step
 */
export async function executeStep(
  step: WorkflowStepConfig,
  context: WorkflowExecutionContext
): Promise<StepExecutionResult> {
  try {
    switch (step.type) {
      case "SEND_EMAIL":
        return await executeSendEmail(
          step.config as SendEmailStepConfig,
          context
        );

      case "WAIT_DELAY":
        return await executeWaitDelay(
          step.config as WaitDelayStepConfig,
          context
        );

      case "WAIT_UNTIL":
        return await executeWaitUntil(
          step.config as WaitUntilStepConfig,
          context
        );

      case "CONDITION":
        return await executeCondition(
          step.config as ConditionStepConfig,
          context
        );

      case "SPLIT_AB":
        return await executeSplitAB(step.config as SplitABStepConfig, context);

      case "UPDATE_SEGMENT":
        return await executeUpdateSegment(
          step.config as UpdateSegmentStepConfig,
          context
        );

      case "ADD_POINTS":
        return await executeAddPoints(
          step.config as AddPointsStepConfig,
          context
        );

      case "APPLY_COUPON":
        return await executeApplyCoupon(
          step.config as ApplyCouponStepConfig,
          context
        );

      case "WEBHOOK":
        return await executeWebhook(step.config as WebhookStepConfig, context);

      case "END":
        return { success: true, data: { ended: true } };

      case "SEND_SMS":
      case "SEND_PUSH":
        // These would require additional integrations
        logger.warn(`Step type ${step.type} not yet implemented`, { category: LOG_CATEGORY });
        return { success: true, data: { skipped: true } };

      default:
        return { success: false, error: `Unknown step type: ${step.type}` };
    }
  } catch (error) {
    const message = error instanceof Error ? error.message : "Unknown error";
    logger.error(`Step execution failed: ${message}`, error instanceof Error ? error : new Error(String(error)), { category: LOG_CATEGORY });
    return { success: false, error: message };
  }
}
 
/**
 * Send an email
 */
async function executeSendEmail(
  config: SendEmailStepConfig,
  context: WorkflowExecutionContext
): Promise<StepExecutionResult> {
  try {
    // Get user data for personalization
    const user = await prisma.user.findUnique({
      where: { id: context.userId }});

    if (!user) {
      return { success: false, error: "User not found" };
    }

    let subject = config.subject || "";
    let body = config.body || "";

    // If using template, fetch it
    if (config.templateId) {
      const template = await prisma.emailTemplate.findUnique({
        where: { id: config.templateId }});
      if (template) {
        subject = template.subject;
        body = template.bodyHtml || template.body;
      }
    }

    // Replace template variables
    const variables = {
      ...config.variables,
      user_name: user.name || "Customer",
      user_email: user.email,
      ...context.variables};

    subject = replaceVariables(subject, variables);
    body = replaceVariables(body, variables);

    // TODO: Actually send the email using your email service
    // For now, just log it
    logger.info(`Would send email to ${user.email}`, {
      category: LOG_CATEGORY,
      subject,
      bodyLength: body.length});

    return {
      success: true,
      data: {
        emailSent: true,
        to: user.email,
        subject}};
  } catch (error) {
    const message = error instanceof Error ? error.message : "Unknown error";
    return { success: false, error: `Email send failed: ${message}` };
  }
}
 
/**
 * Wait for a delay
 */
async function executeWaitDelay(
  config: WaitDelayStepConfig,
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  _context: WorkflowExecutionContext
): Promise<StepExecutionResult> {
  const multipliers: Record<string, number> = {
    seconds: 1000,
    minutes: 60 * 1000,
    hours: 60 * 60 * 1000,
    days: 24 * 60 * 60 * 1000};

  const multiplier = multipliers[config.unit] || 1000;
  const delayMs = config.duration * multiplier;
  const waitUntil = new Date(Date.now() + delayMs);

  return {
    success: true,
    shouldWait: true,
    waitUntil,
    data: { delayMs, waitUntil: waitUntil.toISOString() }};
}
 
/**
 * Wait until a specific time
 */
async function executeWaitUntil(
  config: WaitUntilStepConfig,
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  _context: WorkflowExecutionContext
): Promise<StepExecutionResult> {
  const waitUntil = new Date(config.time);

  if (waitUntil <= new Date()) {
    // Time already passed, continue immediately
    return { success: true, data: { waited: false } };
  }

  return {
    success: true,
    shouldWait: true,
    waitUntil,
    data: { waitUntil: waitUntil.toISOString() }};
}
 
/**
 * Evaluate a condition
 */
async function executeCondition(
  config: ConditionStepConfig,
  context: WorkflowExecutionContext
): Promise<StepExecutionResult> {
  try {
    // Get user data for evaluation
    const user = await prisma.user.findUnique({
      where: { id: context.userId },
      include: {
        orders: true,
        loyalty: true}});

    if (!user) {
      return { success: false, error: "User not found" };
    }

    // Build evaluation context
    const evalContext: Record<string, unknown> = {
      user_id: user.id,
      user_email: user.email,
      user_name: user.name,
      order_count: user.orders.length,
      total_spent: user.orders.reduce((sum, o) => sum + o.total, 0),
      loyalty_points: user.loyalty?.totalPoints || 0,
      loyalty_tier: user.loyalty?.currentTierId || null,
      ...context.triggerData,
      ...context.stepData};

    // Evaluate conditions
    const result = evaluateConditionGroups(config.conditions, evalContext);

    return {
      success: true,
      nextStepId: result ? config.trueConnectionId : config.falseConnectionId,
      data: { conditionResult: result }};
  } catch (error) {
    const message = error instanceof Error ? error.message : "Unknown error";
    return { success: false, error: `Condition evaluation failed: ${message}` };
  }
}
 
/**
 * Evaluate condition groups (AND between groups)
 */
function evaluateConditionGroups(
  groups: ConditionGroup[],
  context: Record<string, unknown>
): boolean {
  for (const group of groups) {
    const groupResult = evaluateConditionGroup(group, context);
    if (!groupResult) return false; // All groups must pass (AND)
  }
  return true;
}
 
/**
 * Evaluate a single condition group
 */
function evaluateConditionGroup(
  group: ConditionGroup,
  context: Record<string, unknown>
): boolean {
  if (group.logic === "OR") {
    return group.rules.some((rule) => evaluateRule(rule, context));
  }
  return group.rules.every((rule) => evaluateRule(rule, context));
}
 
/**
 * Evaluate a single condition rule
 */
function evaluateRule(
  rule: ConditionRule,
  context: Record<string, unknown>
): boolean {
  const fieldValue = context[rule.field];
  const compareValue = rule.value;

  switch (rule.operator) {
    case "equals":
      return fieldValue === compareValue;
    case "not_equals":
      return fieldValue !== compareValue;
    case "greater_than":
      return Number(fieldValue) > Number(compareValue);
    case "less_than":
      return Number(fieldValue) < Number(compareValue);
    case "contains":
      return String(fieldValue).includes(String(compareValue));
    case "not_contains":
      return !String(fieldValue).includes(String(compareValue));
    case "is_empty":
      return fieldValue === null || fieldValue === undefined || fieldValue === "";
    case "is_not_empty":
      return fieldValue !== null && fieldValue !== undefined && fieldValue !== "";
    case "in":
      return Array.isArray(compareValue) && compareValue.includes(fieldValue);
    case "not_in":
      return Array.isArray(compareValue) && !compareValue.includes(fieldValue);
    default:
      return false;
  }
}
 
/**
 * A/B test split
 */
async function executeSplitAB(
  config: SplitABStepConfig,
  context: WorkflowExecutionContext
): Promise<StepExecutionResult> {
  // Use user ID to deterministically assign variant
  const hash = context.userId % 100;
  let cumulative = 0;

  for (const variant of config.variants) {
    cumulative += variant.percentage;
    if (hash < cumulative) {
      return {
        success: true,
        nextStepId: variant.connectionId,
        data: { variant: variant.id, variantName: variant.name }};
    }
  }

  // Default to first variant
  const defaultVariant = config.variants[0];
  return {
    success: true,
    nextStepId: defaultVariant?.connectionId,
    data: { variant: defaultVariant?.id }};
}
 
/**
 * Update segment membership
 */
async function executeUpdateSegment(
  config: UpdateSegmentStepConfig,
  context: WorkflowExecutionContext
): Promise<StepExecutionResult> {
  // Segments are dynamic based on rules, so this is informational
  // In a real implementation, you might have a static segment membership table
  logger.info(`Would ${config.action} user ${context.userId} to segment ${config.segmentId}`, { category: LOG_CATEGORY });

  return {
    success: true,
    data: {
      action: config.action,
      segmentId: config.segmentId}};
}
 
/**
 * Add loyalty points
 */
async function executeAddPoints(
  config: AddPointsStepConfig,
  context: WorkflowExecutionContext
): Promise<StepExecutionResult> {
  try {
    // Find user's loyalty record
    const loyalty = await prisma.customerLoyalty.findUnique({
      where: { userId: context.userId }});

    if (!loyalty) {
      return { success: false, error: "User not enrolled in loyalty program" };
    }

    // Add points
    await prisma.customerLoyalty.update({
      where: { id: loyalty.id },
      data: {
        totalPoints: { increment: config.points },
        lifetimePoints: { increment: config.points }}});

    // Create transaction record
    await prisma.loyaltyTransaction.create({
      data: {
        customerLoyaltyId: loyalty.id,
        points: config.points,
        type: "bonus",
        description: config.reason || "Workflow bonus points"}});

    return {
      success: true,
      data: { pointsAdded: config.points }};
  } catch (error) {
    const message = error instanceof Error ? error.message : "Unknown error";
    return { success: false, error: `Failed to add points: ${message}` };
  }
}
 
/**
 * Apply/create a coupon
 */
async function executeApplyCoupon(
  config: ApplyCouponStepConfig,
  context: WorkflowExecutionContext
): Promise<StepExecutionResult> {
  try {
    let couponCode = config.couponCode;

    // Generate unique code if not provided
    if (!couponCode) {
      couponCode = `AUTO_${context.userId}_${Date.now().toString(36).toUpperCase()}`;
    }

    // Check if promo code already exists
    const existing = await prisma.promoCode.findUnique({
      where: { code: couponCode }});

    if (!existing) {
      // Create a new promotion and promo code
      // This is simplified - in a real implementation you'd have more configuration
      logger.info(`Would create coupon ${couponCode}`, {
        category: LOG_CATEGORY,
        discountType: config.discountType,
        discountValue: config.discountValue,
        expiresIn: config.expiresIn});
    }

    return {
      success: true,
      data: {
        couponCode,
        discountType: config.discountType,
        discountValue: config.discountValue}};
  } catch (error) {
    const message = error instanceof Error ? error.message : "Unknown error";
    return { success: false, error: `Failed to apply coupon: ${message}` };
  }
}
 
/**
 * Call external webhook
 */
async function executeWebhook(
  config: WebhookStepConfig,
  context: WorkflowExecutionContext
): Promise<StepExecutionResult> {
  try {
    const response = await fetch(config.url, {
      method: config.method,
      headers: {
        "Content-Type": "application/json",
        ...config.headers},
      body:
        config.method !== "GET"
          ? JSON.stringify({
              ...config.body,
              userId: context.userId,
              executionId: context.executionId,
              workflowId: context.workflowId})
          : undefined});

    const data = await response.json().catch(() => ({}));

    if (!response.ok) {
      return {
        success: false,
        error: `Webhook failed with status ${response.status}`,
        data};
    }

    return {
      success: true,
      data: { webhookResponse: data }};
  } catch (error) {
    const message = error instanceof Error ? error.message : "Unknown error";
    return { success: false, error: `Webhook failed: ${message}` };
  }
}
 
/**
 * Replace template variables
 */
function replaceVariables(
  text: string,
  variables: Record<string, unknown>
): string {
  return text.replace(/\{\{(\w+)\}\}/g, (match, key) => {
    const value = variables[key];
    return value !== undefined ? String(value) : match;
  });
}