summaryrefslogtreecommitdiff
path: root/lib/vendor-regular-registrations/repository.ts
blob: d4c979a5e5feebef422e166d9cdfd96a633f2282 (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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import db from "@/db/db";
import {
  vendorRegularRegistrations,
  vendors,
  vendorAttachments,
  vendorInvestigationAttachments,
  basicContract,
  vendorPQSubmissions,
  vendorInvestigations,
} from "@/db/schema";
import { eq, desc, and, sql, inArray } from "drizzle-orm";
import type { VendorRegularRegistration } from "@/config/vendorRegularRegistrationsColumnsConfig";

export async function getVendorRegularRegistrations(
): Promise<VendorRegularRegistration[]> {
  try {
    // DB 레코드 기준으로 정규업체등록 데이터를 가져옴
    const registrations = await db
      .select({
        // 정규업체등록 정보
        id: vendorRegularRegistrations.id,
        vendorId: vendorRegularRegistrations.vendorId,
        status: vendorRegularRegistrations.status,
        potentialCode: vendorRegularRegistrations.potentialCode,
        majorItems: vendorRegularRegistrations.majorItems,
        registrationRequestDate: vendorRegularRegistrations.registrationRequestDate,
        assignedDepartment: vendorRegularRegistrations.assignedDepartment,
        assignedUser: vendorRegularRegistrations.assignedUser,
        remarks: vendorRegularRegistrations.remarks,
        // 벤더 기본 정보
        businessNumber: vendors.taxId,
        companyName: vendors.vendorName,
        establishmentDate: vendors.createdAt,
        representative: vendors.representativeName,
      })
      .from(vendorRegularRegistrations)
      .innerJoin(vendors, eq(vendorRegularRegistrations.vendorId, vendors.id))
      .orderBy(desc(vendorRegularRegistrations.createdAt));

    // 벤더 ID 배열 생성
    const vendorIds = registrations.map(r => r.vendorId);

    // 벤더 첨부파일 정보 조회 - 벤더별로 그룹화
    const vendorAttachmentsList = vendorIds.length > 0 ? await db
      .select()
      .from(vendorAttachments)
      .where(inArray(vendorAttachments.vendorId, vendorIds)) : [];

    // 실사 첨부파일 정보 조회 - 실사 ID를 통해 벤더 ID 매핑
    const investigationAttachmentsList = vendorIds.length > 0 ? await db
      .select({
        vendorId: vendorInvestigations.vendorId,
        attachmentId: vendorInvestigationAttachments.id,
        fileName: vendorInvestigationAttachments.fileName,
        attachmentType: vendorInvestigationAttachments.attachmentType,
        createdAt: vendorInvestigationAttachments.createdAt,
      })
      .from(vendorInvestigationAttachments)
      .innerJoin(vendorInvestigations, eq(vendorInvestigationAttachments.investigationId, vendorInvestigations.id))
      .where(inArray(vendorInvestigations.vendorId, vendorIds)) : [];

    // 각 등록 레코드별로 데이터를 매핑하여 결과 반환
    return registrations.map((registration) => {
      // 벤더별 첨부파일 필터링
      const vendorFiles = vendorAttachmentsList.filter(att => att.vendorId === registration.vendorId);
      const investigationFiles = investigationAttachmentsList.filter(att => att.vendorId === registration.vendorId);
      
      // 디버깅을 위한 로그
      console.log(`📋 벤더 ID ${registration.vendorId} (${registration.companyName}) 첨부파일 현황:`, {
        vendorFiles: vendorFiles.map(f => ({ type: f.attachmentType, fileName: f.fileName })),
        investigationFiles: investigationFiles.map(f => ({ type: f.attachmentType, fileName: f.fileName }))
      });
      
      // 문서 제출 현황 - 실제 첨부파일 존재 여부 확인 (DB 타입명과 정확히 매칭)
      const documentSubmissionsStatus = {
        businessRegistration: vendorFiles.some(f => f.attachmentType === "BUSINESS_REGISTRATION"),
        creditEvaluation: vendorFiles.some(f => f.attachmentType === "CREDIT_REPORT"),
        bankCopy: vendorFiles.some(f => f.attachmentType === "BANK_ACCOUNT_COPY"),
        auditResult: investigationFiles.length > 0, // 실사 첨부파일이 하나라도 있으면 true
      };

      // 문서별 파일 정보 (다운로드용)
      const documentFiles = {
        businessRegistration: vendorFiles.filter(f => f.attachmentType === "BUSINESS_REGISTRATION"),
        creditEvaluation: vendorFiles.filter(f => f.attachmentType === "CREDIT_REPORT"),
        bankCopy: vendorFiles.filter(f => f.attachmentType === "BANK_ACCOUNT_COPY"),
        auditResult: investigationFiles,
      };

      // 문서 제출 현황 로그
      console.log(`📊 벤더 ID ${registration.vendorId} 문서 제출 현황:`, documentSubmissionsStatus);

      // 계약 동의 현황 (기본값 - 추후 실제 계약 테이블과 연동)
      const contractAgreementsStatus = {
        cp: "not_submitted",
        gtc: "not_submitted",
        standardSubcontract: "not_submitted",
        safetyHealth: "not_submitted",
        ethics: "not_submitted",
        domesticCredit: "not_submitted",
        safetyQualification: "not_submitted",
      };

      return {
        id: registration.id,
        vendorId: registration.vendorId,
        status: registration.status || "audit_pass",
        potentialCode: registration.potentialCode,
        businessNumber: registration.businessNumber || "",
        companyName: registration.companyName || "",
        majorItems: registration.majorItems,
        establishmentDate: registration.establishmentDate?.toISOString() || null,
        representative: registration.representative,
        documentSubmissions: documentSubmissionsStatus,
        documentFiles: documentFiles, // 파일 정보 추가
        contractAgreements: contractAgreementsStatus,
        additionalInfo: true, // TODO: 추가정보 로직 구현 필요
        registrationRequestDate: registration.registrationRequestDate || null,
        assignedDepartment: registration.assignedDepartment,
        assignedUser: registration.assignedUser,
        remarks: registration.remarks,
      };
    });
  } catch (error) {
    console.error("Error fetching vendor regular registrations:", error);
    throw new Error("정규업체 등록 목록을 가져오는 중 오류가 발생했습니다.");
  }
}

export async function createVendorRegularRegistration(data: {
  vendorId: number;
  status?: string;
  potentialCode?: string;
  majorItems?: string;
  assignedDepartment?: string;
  assignedDepartmentCode?: string;
  assignedUser?: string;
  assignedUserCode?: string;
  remarks?: string;
}) {
  try {
    const [registration] = await db
      .insert(vendorRegularRegistrations)
      .values({
        vendorId: data.vendorId,
        status: data.status || "audit_pass",
        potentialCode: data.potentialCode,
        majorItems: data.majorItems,
        assignedDepartment: data.assignedDepartment,
        assignedDepartmentCode: data.assignedDepartmentCode,
        assignedUser: data.assignedUser,
        assignedUserCode: data.assignedUserCode,
        remarks: data.remarks,
      })
      .returning();

    return registration;
  } catch (error) {
    console.error("Error creating vendor regular registration:", error);
    throw new Error("정규업체 등록을 생성하는 중 오류가 발생했습니다.");
  }
}

export async function updateVendorRegularRegistration(
  id: number,
  data: Partial<{
    status: string;
    potentialCode: string;
    majorItems: string;
    registrationRequestDate: string;
    assignedDepartment: string;
    assignedDepartmentCode: string;
    assignedUser: string;
    assignedUserCode: string;
    remarks: string;
  }>
) {
  try {
    const [registration] = await db
      .update(vendorRegularRegistrations)
      .set({
        ...data,
        updatedAt: new Date(),
      })
      .where(eq(vendorRegularRegistrations.id, id))
      .returning();

    return registration;
  } catch (error) {
    console.error("Error updating vendor regular registration:", error);
    throw new Error("정규업체 등록을 업데이트하는 중 오류가 발생했습니다.");
  }
}

export async function getVendorRegularRegistrationById(id: number) {
  try {
    const [registration] = await db
      .select()
      .from(vendorRegularRegistrations)
      .where(eq(vendorRegularRegistrations.id, id));

    return registration;
  } catch (error) {
    console.error("Error fetching vendor regular registration by id:", error);
    throw new Error("정규업체 등록 정보를 가져오는 중 오류가 발생했습니다.");
  }
}