sop-material-preview.test.ts 10.7 KB
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { buildApp } from '../app.js';

function createPrismaFactory() {
  return () => ({
    $connect: async () => undefined,
    $disconnect: async () => undefined,
    $queryRaw: async () => [],
    $executeRaw: async () => 0,
  });
}

describe('sop material preview route', () => {
  beforeEach(() => {
    vi.useFakeTimers();
    vi.setSystemTime(new Date('2026-06-23T10:11:12.000Z'));
  });

  afterEach(() => {
    vi.useRealTimers();
    vi.restoreAllMocks();
  });

  it('returns a normalized preview model for a valid actionId and records a task visit', async () => {
    const saveEventLog = vi.fn(async () => undefined);
    const app = buildApp(
      {
        nodeEnv: 'test',
        port: 3002,
        host: '127.0.0.1',
        logLevel: 'silent',
        databaseUrl: 'mysql://test',
      },
      {
        createPrismaClient: createPrismaFactory(),
        sopMaterialPreviewRouteOptions: {
          createRepository: () => ({
            findActionById: async (actionId: number) => ({
              id: actionId,
              content: 'SOP 预览标题',
              bgColor: null,
              materialJson: JSON.stringify([
                { type: 'image', url: 'https://cdn.example.com/one.jpg' },
                { type: 'video', url: 'https://cdn.example.com/two.mp4' },
              ]),
              intervalPx: null,
            }),
            saveEventLog,
          }),
        },
      },
    );

    const response = await app.inject({
      method: 'GET',
      url: '/api/sop-material-preview?actionId=123&strategyId=5&customerInstanceId=9001&taskId=33&customerPhone=13476670746&storeName=%E6%B5%8B%E8%AF%95%E9%97%A8%E5%BA%97&customerName=%E5%A4%A7%E5%B9%85%E5%BA%A6%E5%8F%91',
    });

    expect(response.statusCode).toBe(200);
    expect(response.json()).toEqual({
      id: 123,
      content: 'SOP 预览标题',
      bgColor: '#ffffff',
      intervalPx: 0,
      materials: [
        { type: 'image', url: 'https://cdn.example.com/one.jpg' },
        { type: 'video', url: 'https://cdn.example.com/two.mp4' },
      ],
    });
    expect(saveEventLog).toHaveBeenCalledTimes(1);
    expect(saveEventLog).toHaveBeenCalledWith({
      strategyId: 5,
      customerInstanceId: 9001n,
      taskId: 33,
      eventType: 'page_view',
      eventCode: 'sop_strategy_h5_marketing_page_view',
      eventData: JSON.stringify({
        source: 'query_action_id',
        actionId: '123',
        customerPhone: '13476670746',
        storeName: '测试门店',
        customerName: '大幅度发',
      }),
      eventTime: '2026-06-23 18:11:12',
    });

    await app.close();
  });

  it('does not record an event log when taskId is missing', async () => {
    const saveEventLog = vi.fn(async () => undefined);
    const app = buildApp(
      {
        nodeEnv: 'test',
        port: 3002,
        host: '127.0.0.1',
        logLevel: 'silent',
        databaseUrl: 'mysql://test',
      },
      {
        createPrismaClient: createPrismaFactory(),
        sopMaterialPreviewRouteOptions: {
          createRepository: () => ({
            findActionById: async (actionId: number) => ({
              id: actionId,
              content: 'SOP 预览标题',
              bgColor: '#fefefe',
              materialJson: JSON.stringify([{ type: 'image', url: 'https://cdn.example.com/one.jpg' }]),
              intervalPx: 12,
            }),
            saveEventLog,
          }),
        },
      },
    );

    const response = await app.inject({
      method: 'GET',
      url: '/api/sop-material-preview?actionId=123',
    });

    expect(response.statusCode).toBe(200);
    expect(saveEventLog).not.toHaveBeenCalled();

    await app.close();
  });

  it('passes customerInstanceId through to event logging', async () => {
    const saveEventLog = vi.fn(async () => undefined);
    const app = buildApp(
      {
        nodeEnv: 'test',
        port: 3002,
        host: '127.0.0.1',
        logLevel: 'silent',
        databaseUrl: 'mysql://test',
      },
      {
        createPrismaClient: createPrismaFactory(),
        sopMaterialPreviewRouteOptions: {
          createRepository: () => ({
            findActionById: async (actionId: number) => ({
              id: actionId,
              content: 'SOP 预览标题',
              bgColor: '#fefefe',
              materialJson: JSON.stringify([{ type: 'image', url: 'https://cdn.example.com/one.jpg' }]),
              intervalPx: 12,
            }),
            saveEventLog,
          }),
        },
      },
    );

    const response = await app.inject({
      method: 'GET',
      url: '/api/sop-material-preview?actionId=123&taskId=33&customerInstanceId=9001',
    });

    expect(response.statusCode).toBe(200);
    expect(saveEventLog).toHaveBeenCalledWith({
      strategyId: null,
      customerInstanceId: 9001n,
      taskId: 33,
      eventType: 'page_view',
      eventCode: 'sop_strategy_h5_marketing_page_view',
      eventData: JSON.stringify({
        source: 'query_action_id',
        actionId: '123',
        customerPhone: '',
        storeName: '',
        customerName: '',
      }),
      eventTime: '2026-06-23 18:11:12',
    });

    await app.close();
  });

  it('returns a structured error when the actionId is missing', async () => {
    const app = buildApp(
      {
        nodeEnv: 'test',
        port: 3002,
        host: '127.0.0.1',
        logLevel: 'silent',
        databaseUrl: 'mysql://test',
      },
      {
        createPrismaClient: createPrismaFactory(),
        sopMaterialPreviewRouteOptions: {
          createRepository: () => ({
            findActionById: async () => null,
            saveEventLog: async () => undefined,
          }),
        },
      },
    );

    const response = await app.inject({
      method: 'GET',
      url: '/api/sop-material-preview',
    });

    expect(response.statusCode).toBe(400);
    expect(response.json()).toEqual({
      error: {
        code: 'SOP_MATERIAL_PREVIEW_ACTION_ID_INVALID',
        message: '素材 actionId 非法',
        requestId: expect.any(String),
        details: {
          missingFields: ['actionId'],
        },
      },
    });

    await app.close();
  });

  it('returns a structured error when the action does not exist', async () => {
    const app = buildApp(
      {
        nodeEnv: 'test',
        port: 3002,
        host: '127.0.0.1',
        logLevel: 'silent',
        databaseUrl: 'mysql://test',
      },
      {
        createPrismaClient: createPrismaFactory(),
        sopMaterialPreviewRouteOptions: {
          createRepository: () => ({
            findActionById: async () => null,
            saveEventLog: async () => undefined,
          }),
        },
      },
    );

    const response = await app.inject({
      method: 'GET',
      url: '/api/sop-material-preview?actionId=999',
    });

    expect(response.statusCode).toBe(404);
    expect(response.json()).toEqual({
      error: {
        code: 'SOP_MATERIAL_PREVIEW_NOT_FOUND',
        message: '素材不存在',
        requestId: expect.any(String),
        details: {
          id: 999,
        },
      },
    });

    await app.close();
  });

  it('returns a structured error when material_json is invalid', async () => {
    const app = buildApp(
      {
        nodeEnv: 'test',
        port: 3002,
        host: '127.0.0.1',
        logLevel: 'silent',
        databaseUrl: 'mysql://test',
      },
      {
        createPrismaClient: createPrismaFactory(),
        sopMaterialPreviewRouteOptions: {
          createRepository: () => ({
            findActionById: async (actionId: number) => ({
              id: actionId,
              content: 'SOP 预览标题',
              bgColor: '#fefefe',
              materialJson: '{invalid-json',
              intervalPx: 12,
            }),
            saveEventLog: async () => undefined,
          }),
        },
      },
    );

    const response = await app.inject({
      method: 'GET',
      url: '/api/sop-material-preview?actionId=123',
    });

    expect(response.statusCode).toBe(422);
    expect(response.json()).toMatchObject({
      error: {
        code: 'SOP_MATERIAL_PREVIEW_MATERIAL_INVALID',
        message: '素材配置无法解析',
        requestId: expect.any(String),
        details: {
          id: 123,
        },
      },
    });

    await app.close();
  });

  it('returns a structured error when material_json is empty', async () => {
    const app = buildApp(
      {
        nodeEnv: 'test',
        port: 3002,
        host: '127.0.0.1',
        logLevel: 'silent',
        databaseUrl: 'mysql://test',
      },
      {
        createPrismaClient: createPrismaFactory(),
        sopMaterialPreviewRouteOptions: {
          createRepository: () => ({
            findActionById: async (actionId: number) => ({
              id: actionId,
              content: 'SOP 预览标题',
              bgColor: '#fefefe',
              materialJson: '[]',
              intervalPx: 12,
            }),
            saveEventLog: async () => undefined,
          }),
        },
      },
    );

    const response = await app.inject({
      method: 'GET',
      url: '/api/sop-material-preview?actionId=123',
    });

    expect(response.statusCode).toBe(422);
    expect(response.json()).toMatchObject({
      error: {
        code: 'SOP_MATERIAL_PREVIEW_MATERIAL_INVALID',
        message: '素材配置不能为空',
        requestId: expect.any(String),
        details: {
          id: 123,
        },
      },
    });

    await app.close();
  });

  it('keeps rendering when event log persistence fails', async () => {
    const saveEventLog = vi.fn(async () => {
      throw new Error('boom');
    });
    const app = buildApp(
      {
        nodeEnv: 'test',
        port: 3002,
        host: '127.0.0.1',
        logLevel: 'silent',
        databaseUrl: 'mysql://test',
      },
      {
        createPrismaClient: createPrismaFactory(),
        sopMaterialPreviewRouteOptions: {
          createRepository: () => ({
            findActionById: async (actionId: number) => ({
              id: actionId,
              content: 'SOP 预览标题',
              bgColor: '#fefefe',
              materialJson: JSON.stringify([{ type: 'image', url: 'https://cdn.example.com/one.jpg' }]),
              intervalPx: 12,
            }),
            saveEventLog,
          }),
        },
      },
    );

    const response = await app.inject({
      method: 'GET',
      url: '/api/sop-material-preview?actionId=123&taskId=33',
    });

    expect(response.statusCode).toBe(200);
    expect(response.json()).toEqual({
      id: 123,
      content: 'SOP 预览标题',
      bgColor: '#fefefe',
      intervalPx: 12,
      materials: [{ type: 'image', url: 'https://cdn.example.com/one.jpg' }],
    });
    expect(saveEventLog).toHaveBeenCalledTimes(1);

    await app.close();
  });
});