sop-material-preview.ts 7.15 KB
import { Prisma } from '@prisma/client';

import { AppError } from '../lib/errors.js';
import type { PrismaClientLike } from '../plugins/prisma.js';
import type {
  SopMaterialPreviewApiResponse,
  SopMaterialPreviewModel,
} from '../../packages/contracts/src/index.js';

interface SopStrategyActionRow {
  id: number;
  content: string | null;
  bgColor: string | null;
  materialJson: string | null;
  intervalPx: number | null;
}

interface SopStrategyEventLogPayload {
  strategyId: number | null;
  customerInstanceId: bigint | null;
  taskId: number | null;
  eventType: string;
  eventCode: string;
  eventData: string;
  eventTime: string;
}

export interface SopMaterialPreviewRepository {
  findActionById(actionId: number): Promise<SopStrategyActionRow | null>;

  saveEventLog(payload: SopStrategyEventLogPayload): Promise<void>;
}

export interface SopMaterialPreviewVisitPayload {
  actionId: string;
  strategyId?: string;
  customerInstanceId?: string;
  taskId?: string;
  customerPhone?: string;
  storeName?: string;
  customerName?: string;
}

function normalizeText(value: unknown, fallback = ''): string {
  if (typeof value === 'string') {
    return value.trim();
  }

  if (typeof value === 'number' && Number.isFinite(value)) {
    return String(value);
  }

  return fallback;
}

function normalizeNullableInteger(value: unknown): number | null {
  const text = normalizeText(value);
  if (text.length === 0) {
    return null;
  }

  const parsed = Number.parseInt(text, 10);
  return Number.isFinite(parsed) ? parsed : null;
}

function normalizeNullableBigInt(value: unknown): bigint | null {
  const text = normalizeText(value);
  if (text.length === 0) {
    return null;
  }

  try {
    return BigInt(text);
  } catch {
    return null;
  }
}

function isRecord(value: unknown): value is Record<string, unknown> {
  return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
}

function normalizeMaterialItems(value: unknown): { type: string; url: string }[] | null {
  if (!Array.isArray(value)) {
    return null;
  }

  const items = value.map((item) => {
    if (!isRecord(item)) {
      return null;
    }

    if (typeof item.type !== 'string' || typeof item.url !== 'string') {
      return null;
    }

    return {
      type: item.type.trim(),
      url: item.url.trim(),
    };
  });

  return items.includes(null) ? null : (items as { type: string; url: string }[]);
}

function normalizeBgColor(value: unknown): string {
  const text = normalizeText(value);
  return text.length > 0 ? text : '#ffffff';
}

function normalizeIntervalPx(value: unknown): number {
  const parsed = typeof value === 'number' ? value : Number.parseFloat(normalizeText(value));
  if (!Number.isFinite(parsed) || parsed < 0) {
    return 0;
  }

  return Math.floor(parsed);
}

function normalizePreviewModel(row: SopStrategyActionRow): SopMaterialPreviewModel {
  let parsed: unknown;

  if (normalizeText(row.materialJson).length === 0) {
    throw new AppError('SOP_MATERIAL_PREVIEW_MATERIAL_INVALID', '素材配置不能为空', 422, {
      id: row.id,
    });
  }

  try {
    parsed = JSON.parse(row.materialJson ?? '');
  } catch {
    throw new AppError('SOP_MATERIAL_PREVIEW_MATERIAL_INVALID', '素材配置无法解析', 422, {
      id: row.id,
    });
  }

  const materials = normalizeMaterialItems(parsed);
  if (!materials || materials.length === 0) {
    throw new AppError('SOP_MATERIAL_PREVIEW_MATERIAL_INVALID', '素材配置不能为空', 422, {
      id: row.id,
    });
  }

  return {
    id: row.id,
    content: normalizeText(row.content, 'SOP 素材展示/预览') || 'SOP 素材展示/预览',
    bgColor: normalizeBgColor(row.bgColor),
    intervalPx: normalizeIntervalPx(row.intervalPx),
    materials,
  };
}

function buildEventData(payload: SopMaterialPreviewVisitPayload): string {
  return JSON.stringify({
    source: 'query_action_id',
    actionId: normalizeText(payload.actionId),
    customerPhone: normalizeText(payload.customerPhone),
    storeName: normalizeText(payload.storeName),
    customerName: normalizeText(payload.customerName),
  });
}

function normalizeActionId(actionId: string): number {
  const parsed = Number.parseInt(actionId, 10);
  if (!Number.isFinite(parsed)) {
    throw new AppError('SOP_MATERIAL_PREVIEW_ACTION_ID_INVALID', '素材 actionId 非法', 400, {
      missingFields: ['actionId'],
    });
  }

  return parsed;
}

function formatChinaDateTime(date = new Date()): string {
  const chinaDate = new Date(date.getTime() + 8 * 60 * 60 * 1000);
  const pad = (value: number) => String(value).padStart(2, '0');

  return [
    `${chinaDate.getUTCFullYear()}-${pad(chinaDate.getUTCMonth() + 1)}-${pad(chinaDate.getUTCDate())}`,
    `${pad(chinaDate.getUTCHours())}:${pad(chinaDate.getUTCMinutes())}:${pad(chinaDate.getUTCSeconds())}`,
  ].join(' ');
}

export function createPrismaSopMaterialPreviewRepository(prisma: PrismaClientLike): SopMaterialPreviewRepository {
  return {
    async findActionById(actionId) {
      const rows = await prisma.$queryRaw<SopStrategyActionRow>(Prisma.sql`
        SELECT
          id,
          content,
          bg_color AS bgColor,
          material_json AS materialJson,
          interval_px AS intervalPx
        FROM sop_strategy_action
        WHERE id = ${actionId}
        LIMIT 1
      `);

      return rows[0] ?? null;
    },

    async saveEventLog(payload) {
      await prisma.$executeRaw(Prisma.sql`
        INSERT INTO sop_strategy_event_log (
          strategy_id,
          customer_instance_id,
          event_type,
          event_code,
          event_data,
          event_time,
          deleted_flag,
          created_by,
          created_date,
          task_id
        ) VALUES (
          ${payload.strategyId},
          ${payload.customerInstanceId},
          ${payload.eventType},
          ${payload.eventCode},
          ${payload.eventData},
          ${payload.eventTime},
          'N',
          'SYSTEM',
          NOW(),
          ${payload.taskId}
        )
      `);
    },
  };
}

export async function loadSopMaterialPreview(
  repository: SopMaterialPreviewRepository,
  actionId: string,
): Promise<SopMaterialPreviewApiResponse> {
  const normalizedActionId = normalizeActionId(actionId);
  const row = await repository.findActionById(normalizedActionId);

  if (!row) {
    throw new AppError('SOP_MATERIAL_PREVIEW_NOT_FOUND', '素材不存在', 404, {
      id: normalizedActionId,
    });
  }

  return {
    ...normalizePreviewModel(row),
    id: row.id,
  };
}

export async function recordSopMaterialPreviewVisit(
  repository: SopMaterialPreviewRepository,
  payload: SopMaterialPreviewVisitPayload,
): Promise<void> {
  const taskIdRaw = normalizeText(payload.taskId);
  if (taskIdRaw.length === 0) {
    return;
  }

  const taskId = normalizeNullableInteger(taskIdRaw);
  const strategyId = normalizeNullableInteger(payload.strategyId);
  const customerInstanceId = normalizeNullableBigInt(payload.customerInstanceId);

  await repository.saveEventLog({
    strategyId,
    customerInstanceId,
    taskId,
    eventType: 'page_view',
    eventCode: 'sop_strategy_h5_marketing_page_view',
    eventData: buildEventData(payload),
    eventTime: formatChinaDateTime(),
  });
}

export { formatChinaDateTime };