sop-material-preview.ts 2.64 KB
import type { FastifyPluginAsync } from 'fastify';

import type {
  SopMaterialPreviewApiError,
  SopMaterialPreviewApiResponse,
} from '../../packages/contracts/src/index.js';
import { AppError, createErrorResponse } from '../lib/errors.js';
import {
  createPrismaSopMaterialPreviewRepository,
  loadSopMaterialPreview,
  recordSopMaterialPreviewVisit,
  type SopMaterialPreviewRepository,
} from '../features/sop-material-preview.js';

export interface RouteOptions {
  createRepository?: (repository: SopMaterialPreviewRepository) => SopMaterialPreviewRepository;
}

export const sopMaterialPreviewRoute: FastifyPluginAsync<RouteOptions> = async (app, options) => {
  const baseRepository = createPrismaSopMaterialPreviewRepository(app.prisma);
  const repository = options?.createRepository ? options.createRepository(baseRepository) : baseRepository;

  app.get('/api/sop-material-preview', async (request, reply) => {
    const query = (request.query as {
      actionId?: string;
      strategyId?: string;
      customerInstanceId?: string;
      taskId?: string;
      customerPhone?: string;
      storeName?: string;
      customerName?: string;
    } | undefined) ?? {};
    const actionIdRaw = query.actionId;

    if (typeof actionIdRaw !== 'string' || actionIdRaw.trim().length === 0) {
      const error = new AppError('SOP_MATERIAL_PREVIEW_ACTION_ID_INVALID', '素材 actionId 非法', 400, {
        missingFields: ['actionId'],
      });

      const response: SopMaterialPreviewApiError = createErrorResponse(
        error.code,
        error.message,
        request.id,
        error.details,
      );

      reply.status(error.statusCode).send(response);
      return;
    }

    try {
      const result: SopMaterialPreviewApiResponse = await loadSopMaterialPreview(repository, actionIdRaw);

      try {
        await recordSopMaterialPreviewVisit(repository, {
          actionId: actionIdRaw,
          strategyId: query.strategyId,
          customerInstanceId: query.customerInstanceId,
          taskId: query.taskId,
          customerPhone: query.customerPhone,
          storeName: query.storeName,
          customerName: query.customerName,
        });
      } catch (error) {
        request.log.warn({ err: error }, 'sop material preview event log persistence failed');
      }

      reply.send(result);
    } catch (error) {
      if (error instanceof AppError) {
        const response: SopMaterialPreviewApiError = createErrorResponse(
          error.code,
          error.message,
          request.id,
          error.details,
        );

        reply.status(error.statusCode).send(response);
        return;
      }

      throw error;
    }
  });
};