summaryrefslogtreecommitdiff
path: root/lib/vendor-investigation/handlers.ts
blob: 24cad8708c0d5a6e3a3e00128efb01bfa5e98d7b (plain)
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
/**
 * PQ 실사 관련 결재 액션 핸들러
 * 
 * 실제 비즈니스 로직만 포함 (결재 로직은 approval-workflow에서 처리)
 */

'use server';

import { requestInvestigationAction } from '@/lib/pq/service';
import { debugLog, debugError, debugSuccess } from '@/lib/debug-utils';

/**
 * PQ 실사 의뢰 핸들러 (결재 승인 후 실행됨)
 * 
 * 이 함수는 직접 호출하지 않고, 결재 워크플로우에서 자동으로 호출됨
 * 
 * @param payload - withApproval()에서 전달한 actionPayload
 */
export async function requestPQInvestigationInternal(payload: {
  pqSubmissionIds: number[];
  qmManagerId: number;
  qmManagerName?: string;
  forecastedAt: Date;
  investigationAddress: string;
  investigationNotes?: string;
  vendorNames?: string; // 복수 업체 이름 (표시용)
  currentUser: { id: number; epId: string | null; email?: string };
}) {
  debugLog('[PQInvestigationHandler] 실사 의뢰 핸들러 시작', {
    pqCount: payload.pqSubmissionIds.length,
    qmManagerId: payload.qmManagerId,
    currentUser: payload.currentUser,
    vendorNames: payload.vendorNames,
  });

  try {
    // 실제 실사 의뢰 처리
    debugLog('[PQInvestigationHandler] requestInvestigationAction 호출');
    const result = await requestInvestigationAction(
      payload.pqSubmissionIds,
      payload.currentUser,
      {
        qmManagerId: payload.qmManagerId,
        forecastedAt: payload.forecastedAt,
        investigationAddress: payload.investigationAddress,
        investigationNotes: payload.investigationNotes,
      }
    );

    if (!result.success) {
      debugError('[PQInvestigationHandler] 실사 의뢰 실패', result.error);
      throw new Error(result.error || '실사 의뢰에 실패했습니다.');
    }

    debugSuccess('[PQInvestigationHandler] 실사 의뢰 완료', {
      count: result.count,
    });

    return {
      success: true,
      count: result.count,
      message: `${result.count}개 업체에 대해 실사가 의뢰되었습니다.`,
    };
  } catch (error) {
    debugError('[PQInvestigationHandler] 실사 의뢰 중 에러', error);
    throw error;
  }
}

/**
 * PQ 실사 의뢰 데이터를 결재 템플릿 변수로 매핑
 * 
 * @param payload - 실사 의뢰 데이터
 * @returns 템플릿 변수 객체 (Record<string, string>)
 */
export async function mapPQInvestigationToTemplateVariables(payload: {
  vendorNames: string; // 여러 업체명 (쉼표로 구분)
  qmManagerName: string;
  qmManagerEmail?: string;
  forecastedAt: Date;
  investigationAddress: string;
  investigationNotes?: string;
  requestedAt: Date;
}): Promise<Record<string, string>> {
  // 담당자 연락처 (QM담당자 이메일)
  const contactInfo = payload.qmManagerEmail 
    ? `<p>${payload.qmManagerName}: ${payload.qmManagerEmail}</p>`
    : `<p>${payload.qmManagerName}</p>`;

  // 실사 사유/목적 (있으면 포함, 없으면 빈 문자열)
  const investigationPurpose = payload.investigationNotes || '';

  return {
    협력사명: payload.vendorNames,
    실사요청일: new Date(payload.requestedAt).toLocaleDateString('ko-KR'),
    실사예정일: new Date(payload.forecastedAt).toLocaleDateString('ko-KR'),
    실사장소: payload.investigationAddress,
    QM담당자: payload.qmManagerName,
    담당자연락처: contactInfo,
    실사사유목적: investigationPurpose,
  };
}

/**
 * PQ 실사 재의뢰 핸들러 (결재 승인 후 실행됨)
 * 
 * 이 함수는 직접 호출하지 않고, 결재 워크플로우에서 자동으로 호출됨
 * 
 * @param payload - withApproval()에서 전달한 actionPayload
 */
export async function reRequestPQInvestigationInternal(payload: {
  investigationIds: number[];
  vendorNames?: string; // 복수 업체 이름 (표시용)
}) {
  debugLog('[PQReRequestHandler] 실사 재의뢰 핸들러 시작', {
    investigationCount: payload.investigationIds.length,
    vendorNames: payload.vendorNames,
  });

  try {
    // 실제 실사 재의뢰 처리
    const { reRequestInvestigationAction } = await import('@/lib/pq/service');
    debugLog('[PQReRequestHandler] reRequestInvestigationAction 호출');
    
    const result = await reRequestInvestigationAction(payload.investigationIds);

    if (!result.success) {
      debugError('[PQReRequestHandler] 실사 재의뢰 실패', result.error);
      throw new Error(result.error || '실사 재의뢰에 실패했습니다.');
    }

    debugSuccess('[PQReRequestHandler] 실사 재의뢰 완료', {
      count: result.count,
    });

    return {
      success: true,
      count: result.count,
      message: `${result.count}개 업체에 대해 실사가 재의뢰되었습니다.`,
    };
  } catch (error) {
    debugError('[PQReRequestHandler] 실사 재의뢰 중 에러', error);
    throw error;
  }
}

/**
 * PQ 실사 재의뢰 데이터를 결재 템플릿 변수로 매핑
 * 
 * @param payload - 실사 재의뢰 데이터
 * @returns 템플릿 변수 객체 (Record<string, string>)
 */
export async function mapPQReRequestToTemplateVariables(payload: {
  vendorNames: string; // 여러 업체명 (쉼표로 구분)
  investigationCount: number;
  canceledDate?: Date;
  reRequestedAt: Date;
  reason?: string;
  // 기존 실사 정보 (재의뢰 시 필요)
  forecastedAt?: Date;
  investigationAddress?: string;
  qmManagerName?: string;
  qmManagerEmail?: string;
}): Promise<Record<string, string>> {
  // 실사요청일은 재의뢰 요청일로 설정
  const requestDate = new Date(payload.reRequestedAt).toLocaleDateString('ko-KR');
  
  // 실사예정일 (기존 실사 정보 사용, 없으면 빈 문자열)
  const forecastedDate = payload.forecastedAt 
    ? new Date(payload.forecastedAt).toLocaleDateString('ko-KR')
    : '';

  // 담당자 연락처 (QM담당자 이메일, 없으면 빈 문자열)
  const contactInfo = payload.qmManagerEmail 
    ? `<p>${payload.qmManagerName || 'QM담당자'}: ${payload.qmManagerEmail}</p>`
    : '<p>담당자 정보 없음</p>';

  // 실사 사유/목적 (재의뢰 사유, 있으면 포함, 없으면 빈 문자열)
  const investigationPurpose = payload.reason || '';

  return {
    협력사명: payload.vendorNames,
    실사요청일: requestDate,
    실사예정일: forecastedDate,
    실사장소: payload.investigationAddress || '',
    QM담당자: payload.qmManagerName || '',
    담당자연락처: contactInfo,
    실사사유목적: investigationPurpose,
  };
}