summaryrefslogtreecommitdiff
path: root/lib/vendor-regular-registrations/service.ts
blob: ae6ba2a288dcc2519a04a6468e2ab256922fe39e (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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
"use server"
import { revalidateTag, unstable_cache } from "next/cache";
import {
  getVendorRegularRegistrations,
  createVendorRegularRegistration,
  updateVendorRegularRegistration,
  getVendorRegularRegistrationById,
} from "./repository";

import { getServerSession } from "next-auth";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { headers } from "next/headers";
import { sendEmail } from "@/lib/mail/sendEmail";
import { 
  vendors, 
  vendorRegularRegistrations,
  vendorAttachments, 
  vendorInvestigations, 
  vendorInvestigationAttachments,
  basicContract,
  vendorPQSubmissions,
  vendorBusinessContacts,
  vendorAdditionalInfo,
  basicContractTemplates
} from "@/db/schema";
import db from "@/db/db";
import { inArray, eq, desc, and, lt } from "drizzle-orm";
import { sendSingleVendorToMDG } from "@/lib/soap/mdg/send/vendor-master/send-single-vendor";

// 3개월 이상 정규등록검토 상태인 등록을 장기미등록으로 변경
async function updatePendingApprovals() {
  try {
    const threeMonthsAgo = new Date();
    threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3);

    // 3개월 이상 조건충족 상태인 등록들을 조회
    const outdatedRegistrations = await db
      .select()
      .from(vendorRegularRegistrations)
      .where(
        and(
          eq(vendorRegularRegistrations.status, "approval_ready"),
          lt(vendorRegularRegistrations.updatedAt, threeMonthsAgo)
        )
      );

    // 장기미등록으로 상태 변경
    if (outdatedRegistrations.length > 0) {
      await db
        .update(vendorRegularRegistrations)
        .set({
          status: "registration_failed",
          updatedAt: new Date(),
          remarks: "3개월 이상 조건충족 상태로 장기미등록으로 변경",
        })
        .where(
          and(
            eq(vendorRegularRegistrations.status, "approval_ready"),
            lt(vendorRegularRegistrations.updatedAt, threeMonthsAgo)
          )
        );

      console.log(`${outdatedRegistrations.length}개의 등록이 장기미등록으로 변경되었습니다.`);
    }
  } catch (error) {
    console.error("장기미등록 상태 업데이트 오류:", error);
  }
}

// 캐싱과 에러 핸들링이 포함된 조회 함수
export async function fetchVendorRegularRegistrations(input?: {
  search?: string;
  status?: string[];
  page?: number;
  perPage?: number;
}) {
  return unstable_cache(
    async () => {
      try {
        // 장기미등록 상태 업데이트 실행
        await updatePendingApprovals();
        
        const registrations = await getVendorRegularRegistrations();
        
        let filteredData = registrations;

        // 검색 필터링
        if (input?.search) {
          const searchLower = input.search.toLowerCase();
          filteredData = filteredData.filter(
            (reg) =>
              reg.companyName.toLowerCase().includes(searchLower) ||
              reg.businessNumber.toLowerCase().includes(searchLower) ||
              reg.potentialCode?.toLowerCase().includes(searchLower) ||
              reg.representative?.toLowerCase().includes(searchLower)
          );
        }

        // 상태 필터링
        if (input?.status && input.status.length > 0) {
          filteredData = filteredData.filter((reg) =>
            input.status!.includes(reg.status)
          );
        }

        // 페이지네이션
        const page = input?.page || 1;
        const perPage = input?.perPage || 50;
        const offset = (page - 1) * perPage;
        const paginatedData = filteredData.slice(offset, offset + perPage);
        const pageCount = Math.ceil(filteredData.length / perPage);

        return {
          success: true,
          data: paginatedData,
          pageCount,
          total: filteredData.length,
        };
      } catch (error) {
        console.error("Error in fetchVendorRegularRegistrations:", error);
        return {
          success: false,
          error: error instanceof Error ? error.message : "정규업체 등록 목록을 가져오는 중 오류가 발생했습니다.",
        };
      }
    },
    [JSON.stringify(input || {})],
    {
      revalidate: 60, // 1분 캐시로 단축
      tags: ["vendor-regular-registrations"],
    }
  )();
}

export async function getCurrentUserInfo() {
  const session = await getServerSession(authOptions);
  return {
    userId: session?.user?.id ? String(session.user.id) : null,
    userName: session?.user?.name || null,
  };
}

// 누락계약요청 이메일 발송
export async function sendMissingContractRequestEmails(vendorIds: number[]) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user) {
      return { success: false, error: "로그인이 필요합니다." };
    }

    // 벤더 정보 조회
    const vendorList = await db
      .select({
        id: vendors.id,
        vendorName: vendors.vendorName,
        email: vendors.email,
      })
      .from(vendors)
      .where(inArray(vendors.id, vendorIds));

    if (vendorList.length === 0) {
      return { success: false, error: "선택된 업체를 찾을 수 없습니다." };
    }

    const headersList = await headers();
    const host = headersList.get('host') || 'localhost:3000';
    // const protocol = process.env.NODE_ENV === 'production' ? 'https' : 'http';
    const protocol ='http';// 운영 시점에서는 https로 변경
    const baseUrl = `${protocol}://${host}`;
    const contractManagementUrl = `${baseUrl}/ko/partners/basic-contract`; // 실제 기본계약 관리 페이지 URL로 수정 필요

    let successCount = 0;
    let errorCount = 0;

    // 각 벤더에게 이메일 발송
    await Promise.all(
      vendorList.map(async (vendor) => {
        if (!vendor.email) {
          errorCount++;
          return;
        }

        try {

          await sendEmail({
            to: vendor.email,
            subject: "[SHI] 정규업체 등록을 위한 기본계약/서약 진행 요청",
            template: "vendor-missing-contract-request",
            context: {
              vendorName: vendor.vendorName,
              contractManagementUrl,
              senderName: session.user.name || "구매담당자",
              senderEmail: session.user.email || "",
              currentYear: new Date().getFullYear(),
            },
          });
          successCount++;
        } catch (error) {
          console.error(`Failed to send email to ${vendor.vendorName}:`, error);
          errorCount++;
        }
      })
    );

    if (errorCount > 0) {
      return {
        success: false,
        error: `${successCount}개 업체에 발송 성공, ${errorCount}개 업체 발송 실패`,
      };
    }

    return {
      success: true,
      message: `${successCount}개 업체에 누락계약요청 이메일을 발송했습니다.`,
    };
  } catch (error) {
    console.error("Error sending missing contract request emails:", error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "이메일 발송 중 오류가 발생했습니다.",
    };
  }
}

// 추가정보요청 이메일 발송
export async function sendAdditionalInfoRequestEmails(vendorIds: number[]) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user) {
      return { success: false, error: "로그인이 필요합니다." };
    }

    // 벤더 정보 조회
    const vendorList = await db
      .select({
        id: vendors.id,
        vendorName: vendors.vendorName,
        email: vendors.email,
      })
      .from(vendors)
      .where(inArray(vendors.id, vendorIds));

    if (vendorList.length === 0) {
      return { success: false, error: "선택된 업체를 찾을 수 없습니다." };
    }

    const headersList = await headers();
    const host = headersList.get('host') || 'localhost:3000';
    // const protocol = process.env.NODE_ENV === 'production' ? 'https' : 'http';
    const protocol ='http';// 운영 시점에서는 https로 변경
    const baseUrl = `${protocol}://${host}`;
    const vendorInfoUrl = `${baseUrl}/ko/partners/info`; // 실제 업체정보 관리 페이지 URL로 수정 필요

    let successCount = 0;
    let errorCount = 0;

    // 각 벤더에게 이메일 발송
    await Promise.all(
      vendorList.map(async (vendor) => {
        if (!vendor.email) {
          errorCount++;
          return;
        }

        try {
          await sendEmail({
            to: vendor.email,
            subject: "[SHI] 정규업체 등록을 위한 추가정보 입력 요청",
            template: "vendor-regular-registration-request",
            context: {
              vendorName: vendor.vendorName,
              vendorInfoUrl,
              senderName: session.user.name || "구매담당자",
              senderEmail: session.user.email || "",
              currentYear: new Date().getFullYear(),
            },
          });
          successCount++;
        } catch (error) {
          console.error(`Failed to send email to ${vendor.vendorName}:`, error);
          errorCount++;
        }
      })
    );

    if (errorCount > 0) {
      return {
        success: false,
        error: `${successCount}개 업체에 발송 성공, ${errorCount}개 업체 발송 실패`,
      };
    }

    return {
      success: true,
      message: `${successCount}개 업체에 추가정보요청 이메일을 발송했습니다.`,
    };
  } catch (error) {
    console.error("Error sending additional info request emails:", error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "이메일 발송 중 오류가 발생했습니다.",
    };
  }
}

// 법무검토 Skip 기능
export async function skipLegalReview(vendorIds: number[], skipReason: string) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user) {
      return { success: false, error: "로그인이 필요합니다." };
    }

    let successCount = 0;
    let errorCount = 0;

    for (const vendorId of vendorIds) {
      try {
        // 해당 벤더의 registration 찾기 또는 생성
        const vendorList = await db
          .select({ id: vendors.id })
          .from(vendors)
          .where(eq(vendors.id, vendorId));

        if (vendorList.length === 0) {
          errorCount++;
          continue;
        }

        // registration 조회
        const existingRegistrations = await db
          .select()
          .from(vendorRegularRegistrations)
          .where(eq(vendorRegularRegistrations.vendorId, vendorId));

        let registrationId;
        if (existingRegistrations.length === 0) {
          // 새로 생성
          const newRegistration = await createVendorRegularRegistration({
            vendorId: vendorId,
            status: "under_review", // 검토중으로 변경
            remarks: `GTC Skip: ${skipReason}`,
          });
          registrationId = newRegistration.id;
        } else {
          // 기존 registration 업데이트
          registrationId = existingRegistrations[0].id;
          const currentRemarks = existingRegistrations[0].remarks || "";
          const newRemarks = currentRemarks 
            ? `${currentRemarks}\nGTC Skip: ${skipReason}`
            : `GTC Skip: ${skipReason}`;

          await updateVendorRegularRegistration(registrationId, {
            gtcSkipped: true, // GTC Skip 여부 설정
            remarks: newRemarks,
          });
        }

        successCount++;
      } catch (error) {
        console.error(`Failed to skip legal review for vendor ${vendorId}:`, error);
        errorCount++;
      }
    }

    if (errorCount > 0) {
      return {
        success: false,
        error: `${successCount}개 업체 처리 성공, ${errorCount}개 업체 처리 실패`,
      };
    }

    return {
      success: true,
      message: `${successCount}개 업체의 GTC를 Skip 처리했습니다.`,
    };
  } catch (error) {
    console.error("Error skipping legal review:", error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "GTC Skip 처리 중 오류가 발생했습니다.",
    };
  }
}

// 주요품목 업데이트
export async function updateMajorItems(
  registrationId: number,
  majorItems: string
) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user) {
      return { success: false, error: "로그인이 필요합니다." };
    }

    const result = await updateVendorRegularRegistration(registrationId, {
      majorItems: majorItems,
    });

    if (!result) {
      return { success: false, error: "등록 정보를 찾을 수 없습니다." };
    }

    // 캐시 무효화
    revalidateTag("vendor-regular-registrations");
    
    return {
      success: true,
      message: "주요품목이 업데이트되었습니다.",
    };
  } catch (error) {
    console.error("Error updating major items:", error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "주요품목 업데이트 중 오류가 발생했습니다.",
    };
  }
}

// 벤더용 현황 조회 함수들
export async function fetchVendorRegistrationStatus(vendorId: number) {
  return unstable_cache(
    async () => {
      try {
        // 벤더 기본 정보
        const vendor = await db
          .select({
            id: vendors.id,
            vendorName: vendors.vendorName,
            taxId: vendors.taxId,
            representativeName: vendors.representativeName,
            country: vendors.country,
            createdAt: vendors.createdAt,
            updatedAt: vendors.updatedAt,
          })
          .from(vendors)
          .where(eq(vendors.id, vendorId))
          .limit(1)

        if (!vendor[0]) {
          return {
            success: false,
            error: "벤더 정보를 찾을 수 없습니다.",
          }
        }

        // 정규업체 등록 정보 (없을 수도 있음 - 기존 정규업체이거나 아직 등록 진행 안함)
        const registration = await db
          .select({
            id: vendorRegularRegistrations.id,
            vendorId: vendorRegularRegistrations.vendorId,
            potentialCode: vendorRegularRegistrations.potentialCode,
            status: vendorRegularRegistrations.status,
            majorItems: vendorRegularRegistrations.majorItems,
            registrationRequestDate: vendorRegularRegistrations.registrationRequestDate,
            assignedDepartment: vendorRegularRegistrations.assignedDepartment,
            assignedDepartmentCode: vendorRegularRegistrations.assignedDepartmentCode,
            assignedUser: vendorRegularRegistrations.assignedUser,
            assignedUserCode: vendorRegularRegistrations.assignedUserCode,
            remarks: vendorRegularRegistrations.remarks,
            safetyQualificationContent: vendorRegularRegistrations.safetyQualificationContent,
            gtcSkipped: vendorRegularRegistrations.gtcSkipped,
            createdAt: vendorRegularRegistrations.createdAt,
            updatedAt: vendorRegularRegistrations.updatedAt,
          })
          .from(vendorRegularRegistrations)
          .where(eq(vendorRegularRegistrations.vendorId, vendorId))
          .limit(1)

        // 정규업체 등록 정보가 없는 경우 (정상적인 상황)
        if (!registration[0]) {
          return {
            success: false,
            error: "정규업체 등록 진행 정보가 없습니다.", // 에러가 아닌 정보성 메시지
            noRegistration: true // 등록 정보가 없음을 명시적으로 표시
          }
        }

        // 벤더 첨부파일 조회
        const vendorFiles = await db
          .select()
          .from(vendorAttachments)
          .where(eq(vendorAttachments.vendorId, vendorId))

        // 실사 결과 조회 (vendor_investigation_attachments)
        const investigationFiles = await db
          .select({
            attachmentId: vendorInvestigationAttachments.id,
            fileName: vendorInvestigationAttachments.fileName,
            filePath: vendorInvestigationAttachments.filePath,
            createdAt: vendorInvestigationAttachments.createdAt,
          })
          .from(vendorInvestigationAttachments)
          .innerJoin(vendorInvestigations, eq(vendorInvestigationAttachments.investigationId, vendorInvestigations.id))
          .where(eq(vendorInvestigations.vendorId, vendorId))

        // PQ 제출 정보
        const pqSubmission = await db
          .select()
          .from(vendorPQSubmissions)
          .where(eq(vendorPQSubmissions.vendorId, vendorId))
          .orderBy(desc(vendorPQSubmissions.createdAt))
          .limit(1)

        // 기본계약 정보 - 템플릿 정보와 함께 조회
        const allVendorContracts = await db
          .select({
            templateId: basicContract.templateId,
            templateName: basicContractTemplates.templateName,
            status: basicContract.status,
            createdAt: basicContract.createdAt,
            filePath: basicContract.filePath,
            fileName: basicContract.fileName,
          })
          .from(basicContract)
          .leftJoin(basicContractTemplates, eq(basicContract.templateId, basicContractTemplates.id))
          .where(eq(basicContract.vendorId, vendorId))
          .orderBy(desc(basicContract.createdAt))

        // 계약 필터링 (기술자료, 비밀유지 제외)
        const filteredContracts = allVendorContracts.filter(contract => 
          contract.templateName && 
          !contract.templateName.includes("기술자료") && 
          !contract.templateName.includes("비밀유지")
        )

        // 템플릿 이름별로 가장 최신 계약만 유지
        const vendorContracts = filteredContracts.reduce((acc: typeof filteredContracts, contract) => {
          const existing = acc.find((c: typeof contract) => c.templateName === contract.templateName)
          if (!existing || (contract.createdAt && existing.createdAt && contract.createdAt > existing.createdAt)) {
            return acc.filter((c: typeof contract) => c.templateName !== contract.templateName).concat(contract)
          }
          return acc
        }, [] as typeof filteredContracts)

        console.log(`🏢 Partners 벤더 ID ${vendorId} 기본계약 정보:`, {
          allContractsCount: allVendorContracts.length,
          filteredContractsCount: filteredContracts.length,
          finalContractsCount: vendorContracts.length,
          vendorContracts: vendorContracts.map((c: any) => ({
            templateName: c.templateName,
            status: c.status,
            createdAt: c.createdAt
          }))
        })

        // 업무담당자 정보
        const businessContacts = await db
          .select()
          .from(vendorBusinessContacts)
          .where(eq(vendorBusinessContacts.vendorId, vendorId))

        // 추가정보
        const additionalInfo = await db
          .select()
          .from(vendorAdditionalInfo)
          .where(eq(vendorAdditionalInfo.vendorId, vendorId))
          .limit(1)

        // 문서 제출 현황 계산
        const documentStatus = {
          businessRegistration: vendorFiles.some(f => f.attachmentType === "BUSINESS_REGISTRATION"),
          creditEvaluation: vendorFiles.some(f => f.attachmentType === "CREDIT_REPORT"), // CREDIT_EVALUATION -> CREDIT_REPORT
          bankCopy: vendorFiles.some(f => f.attachmentType === "BANK_ACCOUNT_COPY"), // BANK_COPY -> BANK_ACCOUNT_COPY
          auditResult: investigationFiles.length > 0, // DocumentStatusDialog에서 사용하는 키
          cpDocument: vendorContracts.some(c => c.status === "COMPLETED"),
          gtc: vendorContracts.some(c => c.templateName?.includes("GTC") && c.status === "COMPLETED"),
          standardSubcontract: vendorContracts.some(c => c.templateName?.includes("표준하도급") && c.status === "COMPLETED"),
          safetyHealth: vendorContracts.some(c => c.templateName?.includes("안전보건") && c.status === "COMPLETED"),
          ethics: vendorContracts.some(c => c.templateName?.includes("윤리") && c.status === "COMPLETED"),
          domesticCredit: vendorContracts.some(c => c.templateName?.includes("신용") && c.status === "COMPLETED"),
          safetyQualification: investigationFiles.length > 0,
        }

        // 문서별 파일 정보 (다운로드용)
        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,
        }

        // 미완성 항목 계산
        const missingDocuments = Object.entries(documentStatus)
          .filter(([, value]) => !value)
          .map(([key]) => key)

        const requiredContactTypes = ["sales", "design", "delivery", "quality", "tax_invoice"]
        const existingContactTypes = businessContacts.map(contact => contact.contactType)
        const missingContactTypes = requiredContactTypes.filter(type => !existingContactTypes.includes(type))
        
        // 추가정보 완료 여부 (업무담당자 + 추가정보 테이블 모두 필요)
        const contactsCompleted = missingContactTypes.length === 0
        const additionalInfoTableCompleted = !!additionalInfo[0]
        const additionalInfoCompleted = contactsCompleted && additionalInfoTableCompleted
        
        console.log(`🔍 Partners 벤더 ID ${vendorId} 전체 데이터:`, {
          vendor: vendor[0],
          registration: registration[0],
          safetyQualificationContent: registration[0]?.safetyQualificationContent,
          gtcSkipped: registration[0]?.gtcSkipped,
          requiredContactTypes,
          existingContactTypes,
          missingContactTypes,
          contactsCompleted,
          additionalInfoTableCompleted,
          additionalInfoData: additionalInfo[0],
          finalAdditionalInfoCompleted: additionalInfoCompleted,
          basicContractsCount: vendorContracts.length
        })

        return {
          success: true,
          data: {
            vendor: vendor[0],
            registration: registration[0] || null,
            documentStatus,
            documentFiles, // 문서별 파일 정보 추가
            missingDocuments,
            businessContacts,
            missingContactTypes,
            additionalInfo: additionalInfo[0] || null, // 실제 추가정보 데이터 반환
            additionalInfoCompleted, // 완료 여부는 별도 필드로 추가
            pqSubmission: pqSubmission[0] || null,
            auditPassed: investigationFiles.length > 0,
            basicContracts: vendorContracts, // 기본계약 정보 추가
            incompleteItemsCount: {
              documents: missingDocuments.length,
              contacts: missingContactTypes.length,
              additionalInfo: !additionalInfo[0] ? 1 : 0,
            }
          }
        }
      } catch (error) {
        console.error("Error in fetchVendorRegistrationStatus:", error)
        return {
          success: false,
          error: error instanceof Error ? error.message : "현황 조회 중 오류가 발생했습니다.",
        }
      }
    },
    [`vendor-registration-status-${vendorId}`],
    {
      revalidate: 300, // 5분 캐시
      tags: ["vendor-registration-status", `vendor-${vendorId}`],
    }
  )()
}

// 서명/직인 업로드 (임시 - 실제로는 파일 업로드 로직 필요)
export async function uploadVendorSignature(vendorId: number, signatureData: {
  type: "signature" | "seal"
  signerName?: string
  imageFile: string // base64 or file path
}) {
  try {
    // TODO: 실제 파일 업로드 및 저장 로직 구현
    console.log("Signature upload for vendor:", vendorId, signatureData)
    
    // 캐시 무효화
    revalidateTag(`vendor-registration-status`)
    revalidateTag(`vendor-${vendorId}`)
    
    return {
      success: true,
      message: "서명/직인이 등록되었습니다.",
    }
  } catch (error) {
    console.error("Error uploading signature:", error)
    return {
      success: false,
      error: error instanceof Error ? error.message : "서명/직인 등록 중 오류가 발생했습니다.",
    }
  }
}

// 업무담당자 정보 저장
export async function saveVendorBusinessContacts(
  vendorId: number,
  contacts: Array<{
    contactType: "sales" | "design" | "delivery" | "quality" | "tax_invoice"
    contactName: string
    position: string
    department: string
    responsibility: string
    email: string
  }>
) {
  try {
    // 기존 데이터 삭제
    await db
      .delete(vendorBusinessContacts)
      .where(eq(vendorBusinessContacts.vendorId, vendorId))

    // 새 데이터 삽입
    if (contacts.length > 0) {
      await db
        .insert(vendorBusinessContacts)
        .values(contacts.map(contact => ({
          ...contact,
          vendorId,
        })))
    }
    
    // 캐시 무효화
    revalidateTag("vendor-registration-status")
    revalidateTag(`vendor-${vendorId}`)
    
    return {
      success: true,
      message: "업무담당자 정보가 저장되었습니다.",
    }
  } catch (error) {
    console.error("Error saving business contacts:", error)
    return {
      success: false,
      error: error instanceof Error ? error.message : "업무담당자 정보 저장 중 오류가 발생했습니다.",
    }
  }
}

// 추가정보 저장
export async function saveVendorAdditionalInfo(
  vendorId: number,
  info: {
    businessType?: string
    industryType?: string
    companySize?: string
    revenue?: string
    factoryEstablishedDate?: string
    preferredContractTerms?: string
  }
) {
  try {
    const existing = await db
      .select()
      .from(vendorAdditionalInfo)
      .where(eq(vendorAdditionalInfo.vendorId, vendorId))
      .limit(1)
    
    if (existing[0]) {
      // 업데이트
      await db
        .update(vendorAdditionalInfo)
        .set({
          ...info,
          factoryEstablishedDate: info.factoryEstablishedDate || null,
          revenue: info.revenue || null,
          updatedAt: new Date(),
        })
        .where(eq(vendorAdditionalInfo.vendorId, vendorId))
    } else {
      // 신규 삽입
      await db
        .insert(vendorAdditionalInfo)
        .values({
          ...info,
          vendorId,
          factoryEstablishedDate: info.factoryEstablishedDate || null,
          revenue: info.revenue || null,
        })
    }
    
    // 캐시 무효화
    revalidateTag("vendor-registration-status")
    revalidateTag(`vendor-${vendorId}`)
    
    return {
      success: true,
      message: "추가정보가 저장되었습니다.",
    }
  } catch (error) {
    console.error("Error saving additional info:", error)
    return {
      success: false,
      error: error instanceof Error ? error.message : "추가정보 저장 중 오류가 발생했습니다.",
    }
  }
}

// 안전적격성 평가 업데이트
export async function updateSafetyQualification(
  registrationId: number,
  safetyQualificationContent: string
) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user) {
      return { success: false, error: "로그인이 필요합니다." };
    }

    const result = await updateVendorRegularRegistration(registrationId, {
      safetyQualificationContent: safetyQualificationContent.trim(),
    });

    if (!result) {
      return { success: false, error: "등록 정보를 찾을 수 없습니다." };
    }

    // 캐시 무효화
    revalidateTag("vendor-regular-registrations");
    
    return {
      success: true,
      message: "안전적격성 평가가 등록되었습니다.",
    };
  } catch (error) {
    console.error("Error updating safety qualification:", error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "안전적격성 평가 등록 중 오류가 발생했습니다.",
    };
  }
}


// 정규업체 등록 요청을 위한 상세 데이터 조회
export async function fetchRegistrationRequestData(registrationId: number) {
  try {
    // 등록 정보 조회
    const registration = await db
      .select()
      .from(vendorRegularRegistrations)
      .where(eq(vendorRegularRegistrations.id, registrationId))
      .limit(1);

    if (!registration[0]) {
      return { success: false, error: "등록 정보를 찾을 수 없습니다." };
    }

    // 벤더 정보 조회
    const vendor = await db
      .select({
        id: vendors.id,
        vendorName: vendors.vendorName,
        taxId: vendors.taxId,
        representativeName: vendors.representativeName,
        representativeBirth: vendors.representativeBirth,
        representativeEmail: vendors.representativeEmail,
        representativePhone: vendors.representativePhone,
        representativeWorkExpirence: vendors.representativeWorkExpirence,
        country: vendors.country,
        corporateRegistrationNumber: vendors.corporateRegistrationNumber,
        address: vendors.address,
        phone: vendors.phone,
        email: vendors.email,
        createdAt: vendors.createdAt,
        updatedAt: vendors.updatedAt,
      })
      .from(vendors)
      .where(eq(vendors.id, registration[0].vendorId))
      .limit(1);

    if (!vendor[0]) {
      return { success: false, error: "벤더 정보를 찾을 수 없습니다." };
    }

    // 업무담당자 정보 조회
    const businessContacts = await db
      .select()
      .from(vendorBusinessContacts)
      .where(eq(vendorBusinessContacts.vendorId, vendor[0].id));

    // 추가정보 조회
    const additionalInfo = await db
      .select()
      .from(vendorAdditionalInfo)
      .where(eq(vendorAdditionalInfo.vendorId, vendor[0].id))
      .limit(1);

    return {
      success: true,
      data: {
        registration: registration[0],
        vendor: vendor[0],
        businessContacts,
        additionalInfo: additionalInfo[0] || null,
      }
    };

  } catch (error) {
    console.error("정규업체 등록 요청 데이터 조회 오류:", error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "데이터 조회 중 오류가 발생했습니다."
    };
  }
}

// 정규업체 등록 요청 서버 액션
// export async function submitRegistrationRequest(
//   registrationId: number,
//   requestData: RegistrationRequestData
// ) {
//   try {
//     const session = await getServerSession(authOptions);
//     if (!session?.user) {
//       return { success: false, error: "인증이 필요합니다." };
//     }

//     // 현재 등록 정보 조회
//     const registration = await db
//       .select()
//       .from(vendorRegularRegistrations)
//       .where(eq(vendorRegularRegistrations.id, registrationId))
//       .limit(1);

//     if (!registration[0]) {
//       return { success: false, error: "등록 정보를 찾을 수 없습니다." };
//     }

//     // 조건충족 상태인지 확인
//     console.log("📋 업데이트 전 현재 데이터:", {
//       registrationId,
//       currentStatus: registration[0].status,
//       currentRemarks: registration[0].remarks,
//       currentUpdatedAt: registration[0].updatedAt
//     });

//     if (registration[0].status !== "approval_ready") {
//       return { success: false, error: "조건충족 상태가 아닙니다." };
//     }

//     // 정규업체 등록 요청 데이터를 JSON으로 저장
//     const registrationRequestData = {
//       requestDate: new Date(),
//       requestedBy: session.user.id,
//       requestedByName: session.user.name,
//       requestData: requestData,
//       status: "requested" // 요청됨
//     };

//     // 트랜잭션으로 상태 변경
//     const updateResult = await db.transaction(async (tx) => {
//       return await tx
//         .update(vendorRegularRegistrations)
//         .set({
//                      status: "registration_requested",
//           remarks: `정규업체 등록 요청됨 - ${new Date().toISOString()}\n요청자: ${session.user.name}`,
//           updatedAt: new Date(),
//         })
//         .where(eq(vendorRegularRegistrations.id, registrationId));
//     });

//     console.log("🔄 업데이트 결과:", {
//       registrationId,
//       updateResult,
//       statusToSet: "registration_requested"
//     });



//     // MDG 인터페이스 연동
//     const mdgResult = await sendRegistrationRequestToMDG(registrationId, requestData);
    
//     if (!mdgResult.success) {
//       console.error('❌ MDG 송신 실패:', mdgResult.error);
//       // MDG 송신 실패해도 등록 요청은 성공으로 처리 (재시도 가능하도록)
//     } else {
//       console.log('✅ MDG 송신 성공:', mdgResult.message);
//     }

//     // Knox 결재 연동은 별도의 결재 워크플로우에서 처리됩니다.
//     // UI에서 registerVendorWithApproval()을 호출하여 결재 프로세스를 시작합니다.

//     console.log("✅ 정규업체 등록 요청 데이터:", {
//       registrationId,
//       companyName: requestData.companyNameKor,
//       businessNumber: requestData.businessNumber,
//       representative: requestData.representativeNameKor,
//       requestedBy: session.user.name,
//       requestDate: new Date().toISOString()
//     });

//     // 캐시 무효화 - 더 강력한 무효화
//     revalidateTag("vendor-regular-registrations");
//     revalidateTag(`vendor-regular-registration-${registrationId}`);
//     revalidateTag("vendor-registration-status");

//     return { 
//       success: true, 
//       message: `정규업체 등록 요청이 성공적으로 제출되었습니다.\n${mdgResult.success ? 'MDG 인터페이스 연동이 완료되었습니다.' : 'MDG 인터페이스 연동에 실패했습니다. (재시도 가능)'}\n결재 승인 후 정규업체 등록이 완료됩니다.` 
//     };

//   } catch (error) {
//     console.error("정규업체 등록 요청 오류:", error);
//     return { 
//       success: false, 
//       error: error instanceof Error ? error.message : "정규업체 등록 요청 중 오류가 발생했습니다." 
//     };
//   }
// }

// MDG로 정규업체 등록 요청 데이터를 보내는 함수
export async function sendRegistrationRequestToMDG(
  registrationId: number
) {
  try {
    console.log('🚀 MDG로 정규업체 등록 요청 데이터 송신 시작');
    
    // 등록 정보 조회
    const registration = await db
      .select()
      .from(vendorRegularRegistrations)
      .where(eq(vendorRegularRegistrations.id, registrationId))
      .limit(1);

    if (!registration[0]) {
      return { success: false, error: "등록 정보를 찾을 수 없습니다." };
    }

    // sendSingleVendorToMDG 함수를 사용하여 MDG로 전송
    // 정규 벤더 모드로 전송
    console.log('📤 sendSingleVendorToMDG 호출 (정규 벤더 모드)');
    const result = await sendSingleVendorToMDG({
      vendorId: registration[0].vendorId,
      mode: 'REGULAR_VENDOR'
    });
    
    console.log('📤 MDG 송신 결과:', result);
    
    if (!result.success) {
      return {
        success: false,
        error: `MDG 송신 실패: ${result.message}`
      };
    }
    
    return {
      success: true,
      message: 'MDG로 정규업체 등록 요청이 성공적으로 전송되었습니다.',
      responseData: result.responseText,
      generatedXML: result.requestXml
    };
    
  } catch (error) {
    console.error('❌ MDG 송신 실패:', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : 'MDG 송신 중 오류가 발생했습니다.'
    };
  }
}