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
|
/**
* 정규업체 등록 관련 결재 액션 핸들러
*
* 실제 비즈니스 로직만 포함 (결재 로직은 approval-workflow에서 처리)
*/
'use server';
import { submitRegistrationRequest } from './service';
import { debugLog, debugError, debugSuccess } from '@/lib/debug-utils';
import type { RegistrationRequestData } from '@/components/vendor-regular-registrations/registration-request-dialog';
import db from '@/db/db';
import { eq } from 'drizzle-orm';
import { vendors } from '@/db/schema/vendors';
import { vendorAdditionalInfo } from '@/db/schema/vendorRegistrations';
/**
* 정규업체 등록 핸들러 (결재 승인 후 실행됨)
*
* 이 함수는 직접 호출하지 않고, 결재 워크플로우에서 자동으로 호출됨
*
* @param payload - withApproval()에서 전달한 actionPayload
*/
export async function registerVendorInternal(payload: {
registrationId: number;
requestData: RegistrationRequestData;
}) {
debugLog('[VendorRegistrationHandler] 정규업체 등록 핸들러 시작', {
registrationId: payload.registrationId,
companyName: payload.requestData.companyNameKor,
});
try {
// 실제 정규업체 등록 처리
debugLog('[VendorRegistrationHandler] submitRegistrationRequest 호출');
const result = await submitRegistrationRequest(
payload.registrationId,
payload.requestData
);
if (!result.success) {
debugError('[VendorRegistrationHandler] 정규업체 등록 실패', result.error);
throw new Error(result.error || '정규업체 등록에 실패했습니다.');
}
debugSuccess('[VendorRegistrationHandler] 정규업체 등록 완료', {
registrationId: payload.registrationId,
});
return {
success: true,
message: '정규업체 등록이 완료되었습니다.',
};
} catch (error) {
debugError('[VendorRegistrationHandler] 정규업체 등록 중 에러', error);
throw error;
}
}
/**
* 정규업체 등록 데이터를 결재 템플릿 변수로 매핑
*
* 제공된 HTML 템플릿의 변수명에 맞춰 매핑
*
* @param payload - 정규업체 등록 데이터
* @returns 템플릿 변수 객체 (Record<string, string>)
*/
export async function mapRegistrationToTemplateVariables(payload: {
requestData: RegistrationRequestData;
requestedAt: Date;
vendorId?: number; // vendors 테이블에서 정보를 가져오기 위한 vendorId
}): Promise<Record<string, string>> {
const { requestData, requestedAt, vendorId } = payload;
// vendors 테이블에서 추가 정보 가져오기
let vendorInfo: any = {};
if (vendorId) {
try {
const vendorResult = await db
.select({
postalCode: vendors.postalCode,
businessSize: vendors.businessSize,
addressDetail: vendors.addressDetail,
// FAX, 사업유형, 산업유형은 vendors 테이블에 없으므로 빈 값으로 처리
})
.from(vendors)
.where(eq(vendors.id, vendorId))
.limit(1);
vendorInfo = vendorResult[0] || {};
} catch (error) {
console.warn('[Template Variables] Failed to fetch vendor info:', error);
}
}
// 추가정보 조회
let additionalInfo = {
businessType: '',
industryType: '',
companySize: '',
revenue: '',
factoryEstablishedDate: '',
preferredContractTerms: '',
};
if (vendorId) {
const additionalInfoResult = await db
.select({
businessType: vendorAdditionalInfo.businessType,
industryType: vendorAdditionalInfo.industryType,
companySize: vendorAdditionalInfo.companySize,
revenue: vendorAdditionalInfo.revenue,
factoryEstablishedDate: vendorAdditionalInfo.factoryEstablishedDate,
preferredContractTerms: vendorAdditionalInfo.preferredContractTerms,
})
.from(vendorAdditionalInfo)
.where(eq(vendorAdditionalInfo.vendorId, vendorId))
.limit(1);
additionalInfo = additionalInfoResult[0] || additionalInfo;
}
console.log('[Template Variables] Additional info:', additionalInfo);
const variables = {
// 협력업체 기본정보 (템플릿의 정확한 변수명 사용)
' 협력업체 기본정보-사업자번호 ': requestData.businessNumber || '',
' 협력업체 기본정보-업체명 ': requestData.companyNameKor || '',
' 협력업체 기본정보-대표자명 ': requestData.representativeNameKor || '',
' 협력업체 기본정보 대표전화 ': requestData.headOfficePhone || '',
' 협력업체 기본정보 -FAX ': '', // FAX 정보는 vendors 테이블에 없으므로 빈 문자열
' 협력업체 기본정보 -E-mail ': requestData.representativeEmail || '',
' 협력업체 기본정보-우편번호 ': vendorInfo.postalCode || '', // vendors 테이블에서 우편번호 가져오기
' 협력업체 기본정보-회사주소': requestData.headOfficeAddress || '',
' 협력업체 기본정보-상세주소': vendorInfo.addressDetail || '', // 상세주소는 벤더 상세주소로
' 협력업체 기본정보-사업유형': additionalInfo.businessType || '', // 주요품목을 사업유형으로 사용
' 협력업체 기본정보-산업유형': additionalInfo.industryType || '', // 주요품목을 산업유형으로도 사용
' 협력업체 기본정보-회사규모': additionalInfo.companySize || '', // 기업규모
// 담당자 연락처 (각 담당자별로 동일한 정보 반복 - 템플릿에서 여러 번 사용됨)
' 협력업체 관리-상세보기-영업담당자-담당자명 ': requestData.businessContacts.sales.name || '',
' 협력업체 관리-상세보기-영업담당자-직급 ': requestData.businessContacts.sales.position || '',
' 협력업체 관리-상세보기-영업담당자-부서 ': requestData.businessContacts.sales.department || '',
' 협력업체 관리-상세보기-영업담당자-담당업무 ': requestData.businessContacts.sales.responsibility || '',
' 협력업체 관리-상세보기-영업담당자-이메일 ': requestData.businessContacts.sales.email || '',
' 협력업체 관리-상세보기-설계담당자-담당자명 ': requestData.businessContacts.design.name || '',
' 협력업체 관리-상세보기-설계담당자-직급 ': requestData.businessContacts.design.position || '',
' 협력업체 관리-상세보기-설계담당자-부서 ': requestData.businessContacts.design.department || '',
' 협력업체 관리-상세보기-설계담당자-담당업무 ': requestData.businessContacts.design.responsibility || '',
' 협력업체 관리-상세보기-설계담당자-이메일 ': requestData.businessContacts.design.email || '',
' 협력업체 관리-상세보기-납기담당자-담당자명 ': requestData.businessContacts.delivery.name || '',
' 협력업체 관리-상세보기-납기담당자-직급 ': requestData.businessContacts.delivery.position || '',
' 협력업체 관리-상세보기-납기담당자-부서 ': requestData.businessContacts.delivery.department || '',
' 협력업체 관리-상세보기-납기담당자-담당업무 ': requestData.businessContacts.delivery.responsibility || '',
' 협력업체 관리-상세보기-납기담당자-이메일 ': requestData.businessContacts.delivery.email || '',
' 협력업체 관리-상세보기-품질담당자-담당자명 ': requestData.businessContacts.quality.name || '',
' 협력업체 관리-상세보기-품질담당자-직급 ': requestData.businessContacts.quality.position || '',
' 협력업체 관리-상세보기-품질담당자-부서 ': requestData.businessContacts.quality.department || '',
' 협력업체 관리-상세보기-품질담당자-담당업무 ': requestData.businessContacts.quality.responsibility || '',
' 협력업체 관리-상세보기-품질담당자-이메일 ': requestData.businessContacts.quality.email || '',
' 협력업체 관리-상세보기-세금계산서담당자-담당자명 ': requestData.businessContacts.taxInvoice.name || '',
' 협력업체 관리-상세보기-세금계산서담당자-직급 ': requestData.businessContacts.taxInvoice.position || '',
' 협력업체 관리-상세보기-세금계산서담당자-부서 ': requestData.businessContacts.taxInvoice.department || '',
' 협력업체 관리-상세보기-세금계산서담당자-담당업무 ': requestData.businessContacts.taxInvoice.responsibility || '',
' 협력업체 관리-상세보기-세금계산서담당자-이메일 ': requestData.businessContacts.taxInvoice.email || '',
// 기본계약서 현황 (정규업체 등록 시점에는 아직 계약서가 없으므로 빈 값)
'정규업체등록관리-문서현황-계약동의현황-계약유형 ': '정규업체 등록 요청',
'정규업체등록관리-문서현황-계약동의현황-상태 ': '등록 대기',
'정규업체등록관리-문서현황-계약동의현황-서약일자 ': new Date(requestedAt).toLocaleDateString('ko-KR'),
};
// 디버깅을 위한 로그 출력
console.log('[Template Variables] Generated variables:', Object.keys(variables));
console.log('[Template Variables] Sample values:', {
companyName: variables[' 협력업체 기본정보-업체명 '],
businessNumber: variables[' 협력업체 기본정보-사업자번호 '],
representative: variables[' 협력업체 기본정보-대표자명 '],
});
return variables;
}
|