summaryrefslogtreecommitdiff
path: root/lib/bidding
diff options
context:
space:
mode:
Diffstat (limited to 'lib/bidding')
-rw-r--r--lib/bidding/approval-actions.ts325
-rw-r--r--lib/bidding/detail/bidding-actions.ts160
-rw-r--r--lib/bidding/detail/service.ts58
-rw-r--r--lib/bidding/detail/table/bidding-award-dialog.tsx190
-rw-r--r--lib/bidding/detail/table/bidding-detail-vendor-table.tsx77
-rw-r--r--lib/bidding/failure/biddings-closure-dialog.tsx77
-rw-r--r--lib/bidding/failure/biddings-failure-table.tsx81
-rw-r--r--lib/bidding/handlers.ts429
-rw-r--r--lib/bidding/list/bidding-pr-documents-dialog.tsx2
-rw-r--r--lib/bidding/list/create-bidding-dialog.tsx64
-rw-r--r--lib/bidding/service.ts69
-rw-r--r--lib/bidding/validation.ts2
-rw-r--r--lib/bidding/vendor/components/pr-items-pricing-table.tsx8
-rw-r--r--lib/bidding/vendor/partners-bidding-detail.tsx27
-rw-r--r--lib/bidding/vendor/partners-bidding-list-columns.tsx13
15 files changed, 1415 insertions, 167 deletions
diff --git a/lib/bidding/approval-actions.ts b/lib/bidding/approval-actions.ts
index 3a82b08f..6f02e80c 100644
--- a/lib/bidding/approval-actions.ts
+++ b/lib/bidding/approval-actions.ts
@@ -12,7 +12,7 @@
'use server';
import { ApprovalSubmissionSaga } from '@/lib/approval';
-import { mapBiddingInvitationToTemplateVariables } from './handlers';
+import { mapBiddingInvitationToTemplateVariables, mapBiddingClosureToTemplateVariables, mapBiddingAwardToTemplateVariables } from './handlers';
import { debugLog, debugError, debugSuccess } from '@/lib/debug-utils';
/**
@@ -99,7 +99,7 @@ export async function prepareBiddingApprovalData(data: {
materialCode: prItemsForBidding.materialNumber,
materialCodeName: prItemsForBidding.materialInfo,
quantity: prItemsForBidding.quantity,
- purchasingUnit: prItemsForBidding.purchaseUnit,
+ purchasingUnit: prItemsForBidding.priceUnit,
targetUnitPrice: prItemsForBidding.targetUnitPrice,
quantityUnit: prItemsForBidding.quantityUnit,
totalWeight: prItemsForBidding.totalWeight,
@@ -241,3 +241,324 @@ export async function requestBiddingInvitationWithApproval(data: {
return result;
}
+
+/**
+ * 폐찰 결재를 거쳐 입찰 폐찰을 처리하는 서버 액션
+ *
+ * ✅ 사용법 (클라이언트 컴포넌트에서):
+ * ```typescript
+ * const result = await requestBiddingClosureWithApproval({
+ * biddingId: 123,
+ * description: "폐찰 사유",
+ * currentUser: { id: 1, epId: 'EP001', email: 'user@example.com' },
+ * approvers: ['EP002', 'EP003']
+ * });
+ *
+ * if (result.status === 'pending_approval') {
+ * toast.success(`폐찰 결재가 상신되었습니다. (ID: ${result.approvalId})`);
+ * }
+ * ```
+ */
+/**
+ * 폐찰 결재를 위한 공통 데이터 준비 헬퍼 함수
+ */
+export async function prepareBiddingClosureApprovalData(data: {
+ biddingId: number;
+ description: string;
+}) {
+ // 1. 입찰 정보 조회 (템플릿 변수용)
+ debugLog('[BiddingClosureApproval] 입찰 정보 조회 시작');
+ const { default: db } = await import('@/db/db');
+ const { biddings } = await import('@/db/schema');
+ const { eq } = await import('drizzle-orm');
+
+ const biddingInfo = await db
+ .select({
+ id: biddings.id,
+ title: biddings.title,
+ })
+ .from(biddings)
+ .where(eq(biddings.id, data.biddingId))
+ .limit(1);
+
+ if (biddingInfo.length === 0) {
+ debugError('[BiddingClosureApproval] 입찰 정보를 찾을 수 없음');
+ throw new Error('입찰 정보를 찾을 수 없습니다');
+ }
+
+ debugLog('[BiddingClosureApproval] 입찰 정보 조회 완료', {
+ biddingId: data.biddingId,
+ title: biddingInfo[0].title,
+ });
+
+ // 2. 템플릿 변수 매핑
+ debugLog('[BiddingClosureApproval] 템플릿 변수 매핑 시작');
+ const requestedAt = new Date();
+ const { mapBiddingClosureToTemplateVariables } = await import('./handlers');
+ const variables = await mapBiddingClosureToTemplateVariables({
+ biddingId: data.biddingId,
+ description: data.description,
+ requestedAt,
+ });
+ debugLog('[BiddingClosureApproval] 템플릿 변수 매핑 완료', {
+ variableKeys: Object.keys(variables),
+ });
+
+ return {
+ bidding: biddingInfo[0],
+ variables,
+ };
+}
+
+export async function requestBiddingClosureWithApproval(data: {
+ biddingId: number;
+ description: string;
+ files?: File[];
+ currentUser: { id: number; epId: string | null; email?: string };
+ approvers?: string[]; // Knox EP ID 배열 (결재선)
+}) {
+ debugLog('[BiddingClosureApproval] 폐찰 결재 서버 액션 시작', {
+ biddingId: data.biddingId,
+ description: data.description,
+ userId: data.currentUser.id,
+ hasEpId: !!data.currentUser.epId,
+ });
+
+ // 1. 입력 검증
+ if (!data.currentUser.epId) {
+ debugError('[BiddingClosureApproval] Knox EP ID 없음');
+ throw new Error('Knox EP ID가 필요합니다');
+ }
+
+ if (!data.description.trim()) {
+ debugError('[BiddingClosureApproval] 폐찰 사유 없음');
+ throw new Error('폐찰 사유를 입력해주세요');
+ }
+ // 유찰상태인지 확인
+ const { bidding } = await db
+ .select()
+ .from(biddings)
+ .where(eq(biddings.id, data.biddingId))
+ .limit(1);
+
+ if (bidding.status !== 'bidding_disposal') {
+ debugError('[BiddingClosureApproval] 유찰 상태가 아닙니다.');
+ throw new Error('유찰 상태인 입찰만 폐찰할 수 있습니다.');
+ }
+
+ // 2. 입찰 상태를 결재 진행중으로 변경
+ debugLog('[BiddingClosureApproval] 입찰 상태 변경 시작');
+ const { default: db } = await import('@/db/db');
+ const { biddings } = await import('@/db/schema');
+ const { eq } = await import('drizzle-orm');
+
+ await db
+ .update(biddings)
+ .set({
+ status: 'closure_pending', // 폐찰 결재 진행중 상태
+ updatedBy: data.currentUser.epId,
+ updatedAt: new Date()
+ })
+ .where(eq(biddings.id, data.biddingId));
+
+ debugLog('[BiddingClosureApproval] 입찰 상태 변경 완료', {
+ biddingId: data.biddingId,
+ newStatus: 'closure_pending'
+ });
+
+ // 3. 결재 데이터 준비
+ const { bidding: approvalBidding, variables } = await prepareBiddingClosureApprovalData({
+ biddingId: data.biddingId,
+ description: data.description,
+ });
+
+ // 4. 결재 워크플로우 시작 (Saga 패턴)
+ debugLog('[BiddingClosureApproval] ApprovalSubmissionSaga 생성');
+ const saga = new ApprovalSubmissionSaga(
+ // actionType: 핸들러를 찾을 때 사용할 키
+ 'bidding_closure',
+
+ // actionPayload: 결재 승인 후 핸들러에 전달될 데이터 (최소 데이터만)
+ {
+ biddingId: data.biddingId,
+ description: data.description,
+ files: data.files,
+ currentUserId: data.currentUser.id, // ✅ 결재 승인 후 핸들러 실행 시 필요
+ },
+
+ // approvalConfig: 결재 상신 정보 (템플릿 포함)
+ {
+ title: `폐찰 - ${approvalBidding.title}`,
+ description: `${approvalBidding.title} 입찰 폐찰 결재`,
+ templateName: '폐찰 품의 요청서', // 한국어 템플릿명
+ variables, // 치환할 변수들
+ approvers: data.approvers,
+ currentUser: data.currentUser,
+ }
+ );
+
+ debugLog('[BiddingClosureApproval] Saga 실행 시작');
+ const result = await saga.execute();
+
+ debugSuccess('[BiddingClosureApproval] 폐찰 결재 워크플로우 완료', {
+ approvalId: result.approvalId,
+ pendingActionId: result.pendingActionId,
+ status: result.status,
+ });
+
+ return result;
+}
+
+/**
+ * 낙찰 결재를 거쳐 입찰 낙찰을 처리하는 서버 액션
+ *
+ * ✅ 사용법 (클라이언트 컴포넌트에서):
+ * ```typescript
+ * const result = await requestBiddingAwardWithApproval({
+ * biddingId: 123,
+ * selectionReason: "낙찰 사유",
+ * currentUser: { id: 1, epId: 'EP001', email: 'user@example.com' },
+ * approvers: ['EP002', 'EP003']
+ * });
+ *
+ * if (result.status === 'pending_approval') {
+ * toast.success(`낙찰 결재가 상신되었습니다. (ID: ${result.approvalId})`);
+ * }
+ * ```
+ */
+/**
+ * 낙찰 결재를 위한 공통 데이터 준비 헬퍼 함수
+ */
+export async function prepareBiddingAwardApprovalData(data: {
+ biddingId: number;
+ selectionReason: string;
+}) {
+ // 1. 입찰 정보 조회 (템플릿 변수용)
+ debugLog('[BiddingAwardApproval] 입찰 정보 조회 시작');
+ const { default: db } = await import('@/db/db');
+ const { biddings } = await import('@/db/schema');
+ const { eq } = await import('drizzle-orm');
+
+ const biddingInfo = await db
+ .select({
+ id: biddings.id,
+ title: biddings.title,
+ })
+ .from(biddings)
+ .where(eq(biddings.id, data.biddingId))
+ .limit(1);
+
+ if (biddingInfo.length === 0) {
+ debugError('[BiddingAwardApproval] 입찰 정보를 찾을 수 없음');
+ throw new Error('입찰 정보를 찾을 수 없습니다');
+ }
+
+ debugLog('[BiddingAwardApproval] 입찰 정보 조회 완료', {
+ biddingId: data.biddingId,
+ title: biddingInfo[0].title,
+ });
+
+ // 2. 템플릿 변수 매핑
+ debugLog('[BiddingAwardApproval] 템플릿 변수 매핑 시작');
+ const requestedAt = new Date();
+ const { mapBiddingAwardToTemplateVariables } = await import('./handlers');
+ const variables = await mapBiddingAwardToTemplateVariables({
+ biddingId: data.biddingId,
+ selectionReason: data.selectionReason,
+ requestedAt,
+ });
+ debugLog('[BiddingAwardApproval] 템플릿 변수 매핑 완료', {
+ variableKeys: Object.keys(variables),
+ });
+
+ return {
+ bidding: biddingInfo[0],
+ variables,
+ };
+}
+
+export async function requestBiddingAwardWithApproval(data: {
+ biddingId: number;
+ selectionReason: string;
+ currentUser: { id: number; epId: string | null; email?: string };
+ approvers?: string[]; // Knox EP ID 배열 (결재선)
+}) {
+ debugLog('[BiddingAwardApproval] 낙찰 결재 서버 액션 시작', {
+ biddingId: data.biddingId,
+ selectionReason: data.selectionReason,
+ userId: data.currentUser.id,
+ hasEpId: !!data.currentUser.epId,
+ });
+
+ // 1. 입력 검증
+ if (!data.currentUser.epId) {
+ debugError('[BiddingAwardApproval] Knox EP ID 없음');
+ throw new Error('Knox EP ID가 필요합니다');
+ }
+
+ if (!data.selectionReason.trim()) {
+ debugError('[BiddingAwardApproval] 낙찰 사유 없음');
+ throw new Error('낙찰 사유를 입력해주세요');
+ }
+
+ // 2. 입찰 상태를 결재 진행중으로 변경
+ debugLog('[BiddingAwardApproval] 입찰 상태 변경 시작');
+ const { default: db } = await import('@/db/db');
+ const { biddings } = await import('@/db/schema');
+ const { eq } = await import('drizzle-orm');
+
+ await db
+ .update(biddings)
+ .set({
+ status: 'award_pending', // 낙찰 결재 진행중 상태
+ updatedBy: data.currentUser.epId,
+ updatedAt: new Date()
+ })
+ .where(eq(biddings.id, data.biddingId));
+
+ debugLog('[BiddingAwardApproval] 입찰 상태 변경 완료', {
+ biddingId: data.biddingId,
+ newStatus: 'award_pending'
+ });
+
+ // 3. 결재 데이터 준비
+ const { bidding, variables } = await prepareBiddingAwardApprovalData({
+ biddingId: data.biddingId,
+ selectionReason: data.selectionReason,
+ });
+
+ // 4. 결재 워크플로우 시작 (Saga 패턴)
+ debugLog('[BiddingAwardApproval] ApprovalSubmissionSaga 생성');
+ const saga = new ApprovalSubmissionSaga(
+ // actionType: 핸들러를 찾을 때 사용할 키
+ 'bidding_award',
+
+ // actionPayload: 결재 승인 후 핸들러에 전달될 데이터 (최소 데이터만)
+ {
+ biddingId: data.biddingId,
+ selectionReason: data.selectionReason,
+ currentUserId: data.currentUser.id, // ✅ 결재 승인 후 핸들러 실행 시 필요
+ },
+
+ // approvalConfig: 결재 상신 정보 (템플릿 포함)
+ {
+ title: `낙찰 - ${bidding.title}`,
+ description: `${bidding.title} 입찰 낙찰 결재`,
+ templateName: '입찰 결과 업체 선정 품의 요청서', // 한국어 템플릿명
+ variables, // 치환할 변수들
+ approvers: data.approvers,
+ currentUser: data.currentUser,
+ }
+ );
+
+ debugLog('[BiddingAwardApproval] Saga 실행 시작');
+ const result = await saga.execute();
+
+ debugSuccess('[BiddingAwardApproval] 낙찰 결재 워크플로우 완료', {
+ approvalId: result.approvalId,
+ pendingActionId: result.pendingActionId,
+ status: result.status,
+ });
+
+ return result;
+}
diff --git a/lib/bidding/detail/bidding-actions.ts b/lib/bidding/detail/bidding-actions.ts
index 70bba1c3..fb659039 100644
--- a/lib/bidding/detail/bidding-actions.ts
+++ b/lib/bidding/detail/bidding-actions.ts
@@ -143,85 +143,85 @@ export async function checkAllVendorsFinalSubmitted(biddingId: number) {
}
}
-// 개찰 서버 액션 (조기개찰/개찰 구분)
-export async function performBidOpening(
- biddingId: number,
- userId: string,
- isEarly: boolean = false // 조기개찰 여부
-) {
- try {
- const userName = await getUserNameById(userId)
+// // 개찰 서버 액션 (조기개찰/개찰 구분)
+// export async function performBidOpening(
+// biddingId: number,
+// userId: string,
+// isEarly: boolean = false // 조기개찰 여부
+// ) {
+// try {
+// const userName = await getUserNameById(userId)
- return await db.transaction(async (tx) => {
- // 1. 입찰 정보 조회
- const [bidding] = await tx
- .select({
- id: biddings.id,
- status: biddings.status,
- submissionEndDate: biddings.submissionEndDate,
- })
- .from(biddings)
- .where(eq(biddings.id, biddingId))
- .limit(1)
-
- if (!bidding) {
- return {
- success: false,
- error: '입찰 정보를 찾을 수 없습니다.'
- }
- }
-
- // 2. 개찰 가능 여부 확인 (evaluation_of_bidding 상태에서만)
- if (bidding.status !== 'evaluation_of_bidding') {
- return {
- success: false,
- error: '입찰평가중 상태에서만 개찰할 수 있습니다.'
- }
- }
-
- // 3. 모든 벤더가 최종제출했는지 확인
- const checkResult = await checkAllVendorsFinalSubmitted(biddingId)
- if (!checkResult.allSubmitted) {
- return {
- success: false,
- error: `모든 벤더가 최종 제출해야 개찰할 수 있습니다. (${checkResult.submittedCompanies}/${checkResult.totalCompanies})`
- }
- }
-
- // 4. 조기개찰 여부 결정
- const now = new Date()
- const submissionEndDate = bidding.submissionEndDate ? new Date(bidding.submissionEndDate) : null
- const isBeforeDeadline = submissionEndDate && now < submissionEndDate
-
- // 마감일 전이면 조기개찰, 마감일 후면 일반 개찰
- const newStatus = (isEarly || isBeforeDeadline) ? 'early_bid_opening' : 'bid_opening'
-
- // 5. 입찰 상태 변경
- await tx
- .update(biddings)
- .set({
- status: newStatus,
- updatedAt: new Date()
- })
- .where(eq(biddings.id, biddingId))
-
- // 캐시 무효화
- revalidateTag(`bidding-${biddingId}`)
- revalidateTag('bidding-detail')
- revalidatePath(`/evcp/bid/${biddingId}`)
-
- return {
- success: true,
- message: `${newStatus === 'early_bid_opening' ? '조기개찰' : '개찰'}이 완료되었습니다.`,
- status: newStatus
- }
- })
- } catch (error) {
- console.error('Failed to perform bid opening:', error)
- return {
- success: false,
- error: error instanceof Error ? error.message : '개찰에 실패했습니다.'
- }
- }
-}
+// return await db.transaction(async (tx) => {
+// // 1. 입찰 정보 조회
+// const [bidding] = await tx
+// .select({
+// id: biddings.id,
+// status: biddings.status,
+// submissionEndDate: biddings.submissionEndDate,
+// })
+// .from(biddings)
+// .where(eq(biddings.id, biddingId))
+// .limit(1)
+
+// if (!bidding) {
+// return {
+// success: false,
+// error: '입찰 정보를 찾을 수 없습니다.'
+// }
+// }
+
+// // 2. 개찰 가능 여부 확인 (evaluation_of_bidding 상태에서만)
+// if (bidding.status !== 'evaluation_of_bidding') {
+// return {
+// success: false,
+// error: '입찰평가중 상태에서만 개찰할 수 있습니다.'
+// }
+// }
+
+// // 3. 모든 벤더가 최종제출했는지 확인
+// const checkResult = await checkAllVendorsFinalSubmitted(biddingId)
+// if (!checkResult.allSubmitted) {
+// return {
+// success: false,
+// error: `모든 벤더가 최종 제출해야 개찰할 수 있습니다. (${checkResult.submittedCompanies}/${checkResult.totalCompanies})`
+// }
+// }
+
+// // 4. 조기개찰 여부 결정
+// const now = new Date()
+// const submissionEndDate = bidding.submissionEndDate ? new Date(bidding.submissionEndDate) : null
+// const isBeforeDeadline = submissionEndDate && now < submissionEndDate
+
+// // 마감일 전이면 조기개찰, 마감일 후면 일반 개찰
+// const newStatus = (isEarly || isBeforeDeadline) ? 'early_bid_opening' : 'bid_opening'
+
+// // 5. 입찰 상태 변경
+// await tx
+// .update(biddings)
+// .set({
+// status: newStatus,
+// updatedAt: new Date()
+// })
+// .where(eq(biddings.id, biddingId))
+
+// // 캐시 무효화
+// revalidateTag(`bidding-${biddingId}`)
+// revalidateTag('bidding-detail')
+// revalidatePath(`/evcp/bid/${biddingId}`)
+
+// return {
+// success: true,
+// message: `${newStatus === 'early_bid_opening' ? '조기개찰' : '개찰'}이 완료되었습니다.`,
+// status: newStatus
+// }
+// })
+// } catch (error) {
+// console.error('Failed to perform bid opening:', error)
+// return {
+// success: false,
+// error: error instanceof Error ? error.message : '개찰에 실패했습니다.'
+// }
+// }
+// }
diff --git a/lib/bidding/detail/service.ts b/lib/bidding/detail/service.ts
index d0f8070f..297c6f98 100644
--- a/lib/bidding/detail/service.ts
+++ b/lib/bidding/detail/service.ts
@@ -1251,9 +1251,55 @@ export async function getAwardedCompanies(biddingId: number) {
}
}
+// 입찰의 PR 아이템 금액 합산하여 bidding 업데이트
+async function updateBiddingAmounts(biddingId: number) {
+ try {
+ // 해당 bidding의 모든 PR 아이템들의 금액 합계 계산
+ const amounts = await db
+ .select({
+ totalTargetAmount: sql<number>`COALESCE(SUM(${prItemsForBidding.targetAmount}), 0)`,
+ totalBudgetAmount: sql<number>`COALESCE(SUM(${prItemsForBidding.budgetAmount}), 0)`,
+ totalActualAmount: sql<number>`COALESCE(SUM(${prItemsForBidding.actualAmount}), 0)`
+ })
+ .from(prItemsForBidding)
+ .where(eq(prItemsForBidding.biddingId, biddingId))
+
+ const { totalTargetAmount, totalBudgetAmount, totalActualAmount } = amounts[0]
+
+ // bidding 테이블 업데이트
+ await db
+ .update(biddings)
+ .set({
+ targetPrice: totalTargetAmount,
+ budget: totalBudgetAmount,
+ finalBidPrice: totalActualAmount,
+ updatedAt: new Date()
+ })
+ .where(eq(biddings.id, biddingId))
+
+ console.log(`Bidding ${biddingId} amounts updated: target=${totalTargetAmount}, budget=${totalBudgetAmount}, actual=${totalActualAmount}`)
+ } catch (error) {
+ console.error('Failed to update bidding amounts:', error)
+ throw error
+ }
+}
+
// PR 품목 정보 업데이트
export async function updatePrItem(prItemId: number, input: Partial<typeof prItemsForBidding.$inferSelect>, userId: string) {
try {
+ // 업데이트 전 biddingId 확인
+ const prItem = await db
+ .select({ biddingId: prItemsForBidding.biddingId })
+ .from(prItemsForBidding)
+ .where(eq(prItemsForBidding.id, prItemId))
+ .limit(1)
+
+ if (!prItem[0]?.biddingId) {
+ throw new Error('PR item not found or biddingId is missing')
+ }
+
+ const biddingId = prItem[0].biddingId
+
await db
.update(prItemsForBidding)
.set({
@@ -1262,12 +1308,14 @@ export async function updatePrItem(prItemId: number, input: Partial<typeof prIte
})
.where(eq(prItemsForBidding.id, prItemId))
+ // PR 아이템 금액 합산하여 bidding 업데이트
+ await updateBiddingAmounts(biddingId)
+
// 캐시 무효화
- if (input.biddingId) {
- revalidateTag(`bidding-${input.biddingId}`)
- revalidateTag('pr-items')
- revalidatePath(`/evcp/bid/${input.biddingId}`)
- }
+ revalidateTag(`bidding-${biddingId}`)
+ revalidateTag('pr-items')
+ revalidatePath(`/evcp/bid/${biddingId}`)
+
return { success: true, message: '품목 정보가 성공적으로 업데이트되었습니다.' }
} catch (error) {
console.error('Failed to update PR item:', error)
diff --git a/lib/bidding/detail/table/bidding-award-dialog.tsx b/lib/bidding/detail/table/bidding-award-dialog.tsx
index 9a4614bd..ff104fac 100644
--- a/lib/bidding/detail/table/bidding-award-dialog.tsx
+++ b/lib/bidding/detail/table/bidding-award-dialog.tsx
@@ -26,7 +26,8 @@ import {
} from '@/components/ui/table'
import { Trophy, Building2, Calculator } from 'lucide-react'
import { useToast } from '@/hooks/use-toast'
-import { getAwardedCompanies, awardBidding } from '@/lib/bidding/detail/service'
+import { getAwardedCompanies } from '@/lib/bidding/detail/service'
+import { requestBiddingAwardWithApproval } from '@/lib/bidding/approval-actions'
import { AwardSimpleFileUpload } from './components/award-simple-file-upload'
interface BiddingAwardDialogProps {
@@ -34,6 +35,12 @@ interface BiddingAwardDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
onSuccess: () => void
+ onApprovalPreview?: (data: {
+ templateName: string
+ variables: Record<string, string>
+ title: string
+ selectionReason: string
+ }) => void
}
interface AwardedCompany {
@@ -47,7 +54,8 @@ export function BiddingAwardDialog({
biddingId,
open,
onOpenChange,
- onSuccess
+ onSuccess,
+ onApprovalPreview
}: BiddingAwardDialogProps) {
const { toast } = useToast()
const { data: session } = useSession()
@@ -106,26 +114,36 @@ const userId = session?.user?.id || '2';
return
}
- startTransition(async () => {
- const result = await awardBidding(biddingId, selectionReason, userId)
+ // 결재 템플릿 변수 준비
+ const { mapBiddingAwardToTemplateVariables } = await import('@/lib/bidding/handlers')
- if (result.success) {
- toast({
- title: '성공',
- description: result.message,
- })
- onSuccess()
- onOpenChange(false)
- // 폼 초기화
- setSelectionReason('')
- } else {
- toast({
- title: '오류',
- description: result.error,
- variant: 'destructive',
+ try {
+ const variables = await mapBiddingAwardToTemplateVariables({
+ biddingId,
+ selectionReason,
+ requestedAt: new Date()
+ })
+
+ // 상위 컴포넌트로 결재 미리보기 데이터 전달
+ if (onApprovalPreview) {
+ onApprovalPreview({
+ templateName: '입찰 결과 업체 선정 품의 요청서',
+ variables,
+ title: `낙찰 - ${bidding?.title}`,
+ selectionReason
})
}
- })
+
+ onOpenChange(false)
+ setSelectionReason('')
+ } catch (error) {
+ console.error('낙찰 템플릿 변수 준비 실패:', error)
+ toast({
+ title: '오류',
+ description: '결재 문서 준비 중 오류가 발생했습니다.',
+ variant: 'destructive',
+ })
+ }
}
@@ -251,11 +269,143 @@ const userId = session?.user?.id || '2';
type="submit"
disabled={isPending || awardedCompanies.length === 0}
>
- {isPending ? '처리 중...' : '낙찰 완료'}
+ {isPending ? '상신 중...' : '결재 상신'}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
)
+
+ return (
+ <>
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2">
+ <Trophy className="w-5 h-5 text-yellow-600" />
+ 낙찰 처리
+ </DialogTitle>
+ <DialogDescription>
+ 낙찰된 업체의 발주비율과 선정 사유를 확인하고 낙찰을 완료하세요.
+ </DialogDescription>
+ </DialogHeader>
+
+ <form onSubmit={handleSubmit}>
+ <div className="space-y-6">
+ {/* 낙찰 업체 정보 */}
+ <Card>
+ <CardHeader>
+ <CardTitle className="flex items-center gap-2">
+ <Building2 className="w-4 h-4" />
+ 낙찰 업체 정보
+ </CardTitle>
+ </CardHeader>
+ <CardContent>
+ {isLoading ? (
+ <div className="text-center py-4">
+ <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto"></div>
+ <p className="mt-2 text-sm text-muted-foreground">낙찰 업체 정보를 불러오는 중...</p>
+ </div>
+ ) : awardedCompanies.length > 0 ? (
+ <div className="space-y-4">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>업체명</TableHead>
+ <TableHead className="text-right">견적금액</TableHead>
+ <TableHead className="text-right">발주비율</TableHead>
+ <TableHead className="text-right">발주금액</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {awardedCompanies.map((company) => (
+ <TableRow key={company.companyId}>
+ <TableCell className="font-medium">
+ <div className="flex items-center gap-2">
+ <Badge variant="default" className="bg-green-600">낙찰</Badge>
+ {company.companyName}
+ </div>
+ </TableCell>
+ <TableCell className="text-right">
+ {company.finalQuoteAmount.toLocaleString()}원
+ </TableCell>
+ <TableCell className="text-right">
+ {company.awardRatio}%
+ </TableCell>
+ <TableCell className="text-right font-semibold">
+ {(company.finalQuoteAmount * company.awardRatio / 100).toLocaleString()}원
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+
+ {/* 최종입찰가 요약 */}
+ <div className="flex items-center justify-between p-4 bg-blue-50 border border-blue-200 rounded-lg">
+ <div className="flex items-center gap-2">
+ <Calculator className="w-5 h-5 text-blue-600" />
+ <span className="font-semibold text-blue-800">최종입찰가</span>
+ </div>
+ <span className="text-xl font-bold text-blue-800">
+ {finalBidPrice.toLocaleString()}원
+ </span>
+ </div>
+ </div>
+ ) : (
+ <div className="text-center py-8">
+ <Trophy className="w-12 h-12 text-gray-400 mx-auto mb-4" />
+ <p className="text-gray-500 mb-2">낙찰된 업체가 없습니다</p>
+ <p className="text-sm text-gray-400">
+ 먼저 업체 수정 다이얼로그에서 발주비율을 산정해주세요.
+ </p>
+ </div>
+ )}
+ </CardContent>
+ </Card>
+
+ {/* 낙찰 사유 */}
+ <div className="space-y-2">
+ <Label htmlFor="selectionReason">
+ 낙찰 사유 <span className="text-red-500">*</span>
+ </Label>
+ <Textarea
+ id="selectionReason"
+ placeholder="낙찰 사유를 상세히 입력해주세요..."
+ value={selectionReason}
+ onChange={(e) => setSelectionReason(e.target.value)}
+ rows={4}
+ className="resize-none"
+ />
+ </div>
+
+ {/* 첨부파일 */}
+ <AwardSimpleFileUpload
+ biddingId={biddingId}
+ userId={userId}
+ readOnly={false}
+ />
+ </div>
+
+ <DialogFooter className="mt-6">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => onOpenChange(false)}
+ disabled={isPending}
+ >
+ 취소
+ </Button>
+ <Button
+ type="submit"
+ disabled={isPending || awardedCompanies.length === 0}
+ >
+ {isPending ? '상신 중...' : '결재 상신'}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ </>
+ )
}
diff --git a/lib/bidding/detail/table/bidding-detail-vendor-table.tsx b/lib/bidding/detail/table/bidding-detail-vendor-table.tsx
index 1fa116ab..08fc0293 100644
--- a/lib/bidding/detail/table/bidding-detail-vendor-table.tsx
+++ b/lib/bidding/detail/table/bidding-detail-vendor-table.tsx
@@ -14,6 +14,8 @@ import { QuotationVendor, getPriceAdjustmentFormByBiddingCompanyId } from '@/lib
import { Bidding } from '@/db/schema'
import { PriceAdjustmentDialog } from '@/components/bidding/price-adjustment-dialog'
import { QuotationHistoryDialog } from './quotation-history-dialog'
+import { ApprovalPreviewDialog } from '@/lib/approval/approval-preview-dialog'
+import { requestBiddingAwardWithApproval } from '@/lib/bidding/approval-actions'
import { useToast } from '@/hooks/use-toast'
interface BiddingDetailVendorTableContentProps {
@@ -99,6 +101,13 @@ export function BiddingDetailVendorTableContent({
const [isPriceAdjustmentDialogOpen, setIsPriceAdjustmentDialogOpen] = React.useState(false)
const [quotationHistoryData, setQuotationHistoryData] = React.useState<any>(null)
const [isQuotationHistoryDialogOpen, setIsQuotationHistoryDialogOpen] = React.useState(false)
+ const [approvalPreviewData, setApprovalPreviewData] = React.useState<{
+ templateName: string
+ variables: Record<string, string>
+ title: string
+ selectionReason: string
+ } | null>(null)
+ const [isApprovalPreviewDialogOpen, setIsApprovalPreviewDialogOpen] = React.useState(false)
const handleEdit = (vendor: QuotationVendor) => {
setSelectedVendor(vendor)
@@ -187,6 +196,47 @@ export function BiddingDetailVendorTableContent({
clearOnDefault: true,
})
+ // 낙찰 결재 상신 핸들러
+ const handleAwardApprovalConfirm = async (data: { approvers: string[]; title: string; attachments?: File[] }) => {
+ if (!session?.user?.id || !approvalPreviewData) return
+
+ try {
+ const result = await requestBiddingAwardWithApproval({
+ biddingId,
+ selectionReason: approvalPreviewData.selectionReason,
+ currentUser: {
+ id: Number(session.user.id),
+ epId: session.user.epId || null,
+ email: session.user.email || undefined
+ },
+ approvers: data.approvers,
+ })
+
+ if (result.status === 'pending_approval') {
+ toast({
+ title: '성공',
+ description: `낙찰 결재가 상신되었습니다. (ID: ${result.approvalId})`,
+ })
+ setIsApprovalPreviewDialogOpen(false)
+ setApprovalPreviewData(null)
+ onRefresh()
+ } else {
+ toast({
+ title: '오류',
+ description: '낙찰 결재 상신 중 오류가 발생했습니다.',
+ variant: 'destructive',
+ })
+ }
+ } catch (error) {
+ console.error('낙찰 결재 상신 실패:', error)
+ toast({
+ title: '오류',
+ description: '낙찰 결재 상신 중 오류가 발생했습니다.',
+ variant: 'destructive',
+ })
+ }
+ }
+
return (
<>
<DataTable table={table}>
@@ -221,6 +271,10 @@ export function BiddingDetailVendorTableContent({
open={isAwardDialogOpen}
onOpenChange={setIsAwardDialogOpen}
onSuccess={onRefresh}
+ onApprovalPreview={(data) => {
+ setApprovalPreviewData(data)
+ setIsApprovalPreviewDialogOpen(true)
+ }}
/>
<PriceAdjustmentDialog
@@ -238,6 +292,29 @@ export function BiddingDetailVendorTableContent({
biddingCurrency={quotationHistoryData?.biddingCurrency || 'KRW'}
targetPrice={quotationHistoryData?.targetPrice}
/>
+
+ {/* 낙찰 결재 미리보기 다이얼로그 */}
+ {session?.user && session.user.epId && approvalPreviewData && (
+ <ApprovalPreviewDialog
+ open={isApprovalPreviewDialogOpen}
+ onOpenChange={(open) => {
+ setIsApprovalPreviewDialogOpen(open)
+ if (!open) {
+ setApprovalPreviewData(null)
+ }
+ }}
+ templateName={approvalPreviewData.templateName}
+ variables={approvalPreviewData.variables}
+ title={approvalPreviewData.title}
+ currentUser={{
+ id: Number(session.user.id),
+ epId: session.user.epId,
+ name: session.user.name || undefined,
+ email: session.user.email || undefined
+ }}
+ onConfirm={handleAwardApprovalConfirm}
+ />
+ )}
</>
)
}
diff --git a/lib/bidding/failure/biddings-closure-dialog.tsx b/lib/bidding/failure/biddings-closure-dialog.tsx
index 64aba42f..93ba0eda 100644
--- a/lib/bidding/failure/biddings-closure-dialog.tsx
+++ b/lib/bidding/failure/biddings-closure-dialog.tsx
@@ -2,8 +2,9 @@
"use client"
import { useState } from "react"
+import { useSession } from "next-auth/react"
import { toast } from "sonner"
-import { bidClosureAction } from "@/lib/bidding/actions"
+import { requestBiddingClosureWithApproval } from "@/lib/bidding/approval-actions"
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
@@ -19,17 +20,29 @@ interface BiddingsClosureDialogProps {
title: string;
biddingNumber: string;
} | null;
- userId: string;
onSuccess?: () => void;
+ onApprovalPreview?: (data: {
+ templateName: string
+ variables: Record<string, string>
+ title: string
+ description: string
+ files?: File[]
+ }) => void
}
+
+interface ClosureFormData {
+ description: string;
+ files: File[];
+}
export function BiddingsClosureDialog({
open,
onOpenChange,
bidding,
- userId,
- onSuccess
+ onSuccess,
+ onApprovalPreview
}: BiddingsClosureDialogProps) {
+ const { data: session } = useSession()
const [description, setDescription] = useState('')
const [files, setFiles] = useState<File[]>([])
const [isSubmitting, setIsSubmitting] = useState(false)
@@ -42,36 +55,44 @@ interface BiddingsClosureDialogProps {
return
}
- setIsSubmitting(true)
-
+ // 결재 템플릿 변수 준비
+ const { mapBiddingClosureToTemplateVariables } = await import('@/lib/bidding/handlers')
+
try {
- const result = await bidClosureAction(bidding.id, {
+ const variables = await mapBiddingClosureToTemplateVariables({
+ biddingId: bidding.id,
description: description.trim(),
- files
- }, userId)
-
- if (result.success) {
- toast.success(result.message)
- onOpenChange(false)
- onSuccess?.()
- // 페이지 새로고침 또는 상태 업데이트
- window.location.reload()
- } else {
- toast.error(result.error || '폐찰 처리 중 오류가 발생했습니다.')
+ requestedAt: new Date()
+ })
+
+ // 상위 컴포넌트로 결재 미리보기 데이터 전달
+ if (onApprovalPreview) {
+ onApprovalPreview({
+ templateName: '폐찰 품의 요청서',
+ variables,
+ title: `폐찰 - ${bidding.title}`,
+ description: description.trim(),
+ files
+ })
}
+
+ onOpenChange(false)
+ // 폼 초기화
+ setDescription('')
+ setFiles([])
} catch (error) {
- toast.error('폐찰 처리 중 오류가 발생했습니다.')
- } finally {
- setIsSubmitting(false)
+ console.error('폐찰 템플릿 변수 준비 실패:', error)
+ toast.error('결재 문서 준비 중 오류가 발생했습니다.')
}
}
-
+
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
if (e.target.files) {
setFiles(Array.from(e.target.files))
}
}
-
+
+
if (!bidding) return null
return (
@@ -99,7 +120,7 @@ interface BiddingsClosureDialogProps {
required
/>
</div>
-
+
<div className="space-y-2">
<Label htmlFor="files">첨부파일</Label>
<Input
@@ -116,7 +137,7 @@ interface BiddingsClosureDialogProps {
</div>
)}
</div>
-
+
<div className="flex justify-end gap-2 pt-4">
<Button
type="button"
@@ -131,12 +152,12 @@ interface BiddingsClosureDialogProps {
variant="destructive"
disabled={isSubmitting || !description.trim()}
>
- {isSubmitting ? '처리 중...' : '폐찰하기'}
+ {isSubmitting ? '상신 중...' : '결재 상신'}
</Button>
</div>
</form>
</DialogContent>
</Dialog>
- )
- }
+ </>
+ )
\ No newline at end of file
diff --git a/lib/bidding/failure/biddings-failure-table.tsx b/lib/bidding/failure/biddings-failure-table.tsx
index 43020322..a0f98466 100644
--- a/lib/bidding/failure/biddings-failure-table.tsx
+++ b/lib/bidding/failure/biddings-failure-table.tsx
@@ -24,6 +24,8 @@ import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, D
import { FileX, RefreshCw, Undo2 } from "lucide-react"
import { bidClosureAction, cancelDisposalAction } from "@/lib/bidding/actions"
import { increaseRoundOrRebid } from "@/lib/bidding/service"
+import { ApprovalPreviewDialog } from "@/lib/approval/approval-preview-dialog"
+import { requestBiddingClosureWithApproval } from "@/lib/bidding/approval-actions"
import { useToast } from "@/hooks/use-toast"
type BiddingFailureItem = {
@@ -88,6 +90,14 @@ export function BiddingsFailureTable({ promises }: BiddingsFailureTableProps) {
const [selectedBidding, setSelectedBidding] = React.useState<BiddingFailureItem | null>(null)
const [isRebidDialogOpen, setIsRebidDialogOpen] = React.useState(false)
const [selectedBiddingForRebid, setSelectedBiddingForRebid] = React.useState<BiddingFailureItem | null>(null)
+ const [approvalPreviewData, setApprovalPreviewData] = React.useState<{
+ templateName: string
+ variables: Record<string, string>
+ title: string
+ description: string
+ files?: File[]
+ } | null>(null)
+ const [isApprovalPreviewDialogOpen, setIsApprovalPreviewDialogOpen] = React.useState(false)
const { toast } = useToast()
const [rowAction, setRowAction] = React.useState<DataTableRowAction<BiddingFailureItem> | null>(null)
@@ -424,11 +434,14 @@ export function BiddingsFailureTable({ promises }: BiddingsFailureTableProps) {
open={biddingClosureDialogOpen}
onOpenChange={handleBiddingClosureDialogClose}
bidding={selectedBidding}
- userId={session.user.id}
onSuccess={() => {
router.refresh()
handleBiddingClosureDialogClose()
}}
+ onApprovalPreview={(data) => {
+ setApprovalPreviewData(data)
+ setIsApprovalPreviewDialogOpen(true)
+ }}
/>
)}
@@ -465,6 +478,72 @@ export function BiddingsFailureTable({ promises }: BiddingsFailureTableProps) {
</DialogFooter>
</DialogContent>
</Dialog>
+
+ {/* 폐찰 결재 미리보기 다이얼로그 */}
+ {session?.user && session.user.epId && approvalPreviewData && (
+ <ApprovalPreviewDialog
+ open={isApprovalPreviewDialogOpen}
+ onOpenChange={(open) => {
+ setIsApprovalPreviewDialogOpen(open)
+ if (!open) {
+ setApprovalPreviewData(null)
+ }
+ }}
+ templateName={approvalPreviewData.templateName}
+ variables={approvalPreviewData.variables}
+ title={approvalPreviewData.title}
+ currentUser={{
+ id: Number(session.user.id),
+ epId: session.user.epId,
+ name: session.user.name || undefined,
+ email: session.user.email || undefined
+ }}
+ onConfirm={handleClosureApprovalConfirm}
+ />
+ )}
</>
)
+
+ // 폐찰 결재 상신 핸들러
+ const handleClosureApprovalConfirm = async (data: { approvers: string[]; title: string; attachments?: File[] }) => {
+ if (!session?.user?.id || !approvalPreviewData || !selectedBidding) return
+
+ try {
+ const result = await requestBiddingClosureWithApproval({
+ biddingId: selectedBidding.id,
+ description: approvalPreviewData.description,
+ files: approvalPreviewData.files,
+ currentUser: {
+ id: Number(session.user.id),
+ epId: session.user.epId || null,
+ email: session.user.email || undefined
+ },
+ approvers: data.approvers,
+ })
+
+ if (result.status === 'pending_approval') {
+ toast({
+ title: '성공',
+ description: `폐찰 결재가 상신되었습니다. (ID: ${result.approvalId})`,
+ })
+ setIsApprovalPreviewDialogOpen(false)
+ setApprovalPreviewData(null)
+ handleBiddingClosureDialogClose()
+ router.refresh()
+ } else {
+ toast({
+ title: '오류',
+ description: '폐찰 결재 상신 중 오류가 발생했습니다.',
+ variant: 'destructive',
+ })
+ }
+ } catch (error) {
+ console.error('폐찰 결재 상신 실패:', error)
+ toast({
+ title: '오류',
+ description: '폐찰 결재 상신 중 오류가 발생했습니다.',
+ variant: 'destructive',
+ })
+ }
+ }
}
diff --git a/lib/bidding/handlers.ts b/lib/bidding/handlers.ts
index fc2951d4..d55107c0 100644
--- a/lib/bidding/handlers.ts
+++ b/lib/bidding/handlers.ts
@@ -281,3 +281,432 @@ export async function mapBiddingInvitationToTemplateVariables(payload: {
...materialVariables,
};
}
+
+/**
+ * 폐찰 데이터를 결재 템플릿 변수로 매핑
+ *
+ * @param payload - 폐찰 데이터
+ * @returns 템플릿 변수 객체 (Record<string, string>)
+ */
+export async function mapBiddingClosureToTemplateVariables(payload: {
+ biddingId: number;
+ description: string;
+ requestedAt: Date;
+}): Promise<Record<string, string>> {
+ const { biddingId, description, requestedAt } = payload;
+
+ // 1. 입찰 정보 조회
+ debugLog('[BiddingClosureMapper] 입찰 정보 조회 시작');
+ const { default: db } = await import('@/db/db');
+ const { biddings, prItemsForBidding, biddingCompanies, biddingVendorSubmissions } = await import('@/db/schema');
+ const { eq, leftJoin } = await import('drizzle-orm');
+
+ const biddingInfo = await db
+ .select({
+ id: biddings.id,
+ title: biddings.title,
+ biddingNumber: biddings.biddingNumber,
+ projectName: biddings.projectName,
+ itemName: biddings.itemName,
+ biddingType: biddings.biddingType,
+ bidPicName: biddings.bidPicName,
+ supplyPicName: biddings.supplyPicName,
+ targetPrice: biddings.targetPrice,
+ winnerCount: biddings.winnerCount,
+ })
+ .from(biddings)
+ .where(eq(biddings.id, biddingId))
+ .limit(1);
+
+ if (biddingInfo.length === 0) {
+ debugError('[BiddingClosureMapper] 입찰 정보를 찾을 수 없음');
+ throw new Error('입찰 정보를 찾을 수 없습니다');
+ }
+
+ const bidding = biddingInfo[0];
+
+ // 2. 입찰 대상 자재 정보 조회
+ const biddingItemsInfo = await db
+ .select({
+ id: prItemsForBidding.id,
+ materialCode: prItemsForBidding.materialNumber,
+ materialCodeName: prItemsForBidding.materialInfo,
+ quantity: prItemsForBidding.quantity,
+ quantityUnit: prItemsForBidding.quantityUnit,
+ targetUnitPrice: prItemsForBidding.targetUnitPrice,
+ currency: prItemsForBidding.targetCurrency,
+ })
+ .from(prItemsForBidding)
+ .where(eq(prItemsForBidding.biddingId, biddingId));
+
+ // 3. 입찰 참여 업체 및 제출 정보 조회
+ const vendorSubmissions = await db
+ .select({
+ vendorId: biddingCompanies.vendorId,
+ vendorName: biddingCompanies.vendorName,
+ vendorCode: biddingCompanies.vendorCode,
+ targetPrice: biddingVendorSubmissions.targetPrice,
+ bidPrice: biddingVendorSubmissions.bidPrice,
+ submitted: biddingVendorSubmissions.submitted,
+ })
+ .from(biddingCompanies)
+ .leftJoin(biddingVendorSubmissions, eq(biddingCompanies.id, biddingVendorSubmissions.biddingCompanyId))
+ .where(eq(biddingCompanies.biddingId, biddingId));
+
+ debugLog('[BiddingClosureMapper] 입찰 정보 조회 완료', {
+ biddingId,
+ itemCount: biddingItemsInfo.length,
+ vendorCount: vendorSubmissions.length,
+ });
+
+ // 기본 정보 매핑
+ const title = bidding.title || '폐찰';
+ const biddingTitle = bidding.title || '';
+ const biddingNumber = bidding.biddingNumber || '';
+ const winnerCount = (bidding.winnerCount || 1).toString();
+ const contractType = bidding.biddingType || '';
+ const targetPrice = bidding.targetPrice ? bidding.targetPrice.toLocaleString() : '';
+ const biddingManager = bidding.bidPicName || bidding.supplyPicName || '';
+ const biddingOverview = bidding.itemName || '';
+
+ // 폐찰 사유
+ const closureReason = description;
+
+ // 협력사별 입찰 현황 매핑
+ const vendorVariables: Record<string, string> = {};
+ vendorSubmissions.forEach((vendor, index) => {
+ const num = index + 1;
+ vendorVariables[`협력사_코드_${num}`] = vendor.vendorCode || '';
+ vendorVariables[`협력사명_${num}`] = vendor.vendorName || '';
+ vendorVariables[`응찰유무_${num}`] = vendor.submitted ? '응찰' : '미응찰';
+ vendorVariables[`내정가_${num}`] = vendor.targetPrice ? vendor.targetPrice.toLocaleString() : '';
+ vendorVariables[`입찰가_${num}`] = vendor.bidPrice ? vendor.bidPrice.toLocaleString() : '';
+ vendorVariables[`비율_${num}`] = (vendor.targetPrice && vendor.bidPrice && vendor.targetPrice > 0)
+ ? ((vendor.bidPrice / vendor.targetPrice) * 100).toFixed(2) + '%'
+ : '';
+ });
+
+ // 품목별 입찰 정보 매핑 (간소화 - 첫 번째 품목 기준으로 매핑)
+ const materialVariables: Record<string, string> = {};
+ biddingItemsInfo.forEach((item, index) => {
+ const num = index + 1;
+ materialVariables[`품목코드_${num}`] = item.materialCode || '';
+ materialVariables[`품목명_${num}`] = item.materialCodeName || '';
+ materialVariables[`수량_${num}`] = item.quantity ? item.quantity.toLocaleString() : '';
+ materialVariables[`단위_${num}`] = item.quantityUnit || '';
+ materialVariables[`통화_${num}`] = item.currency || '';
+ materialVariables[`내정가_${num}`] = item.targetUnitPrice ? item.targetUnitPrice.toLocaleString() : '';
+
+ // 각 품목에 대한 협력사별 입찰가 (간소화: 동일 품목에 대한 모든 업체 입찰가 표시)
+ vendorSubmissions.forEach((vendor, vendorIndex) => {
+ const vendorNum = vendorIndex + 1;
+ materialVariables[`협력사코드_${num}`] = vendor.vendorCode || '';
+ materialVariables[`협력사명_${num}`] = vendor.vendorName || '';
+ materialVariables[`입찰가_${num}`] = vendor.bidPrice ? vendor.bidPrice.toLocaleString() : '';
+ });
+ });
+
+ return {
+ 제목: title,
+ 입찰명: biddingTitle,
+ 입찰번호: biddingNumber,
+ 낙찰업체수: winnerCount,
+ 계약구분: contractType,
+ 내정가: targetPrice,
+ 입찰담당자: biddingManager,
+ 입찰개요: biddingOverview,
+ 폐찰_사유: closureReason,
+ ...vendorVariables,
+ ...materialVariables,
+ };
+}
+
+/**
+ * 폐찰 핸들러 (결재 승인 후 실행됨)
+ *
+ * ✅ Internal 함수: 결재 워크플로우에서 자동 호출됨 (직접 호출 금지)
+ *
+ * @param payload - withApproval()에서 전달한 actionPayload (최소 데이터만)
+ */
+export async function requestBiddingClosureInternal(payload: {
+ biddingId: number;
+ description: string;
+ files?: File[];
+ currentUserId: number; // ✅ 결재 상신한 사용자 ID
+}) {
+ debugLog('[BiddingClosureHandler] 폐찰 핸들러 시작', {
+ biddingId: payload.biddingId,
+ description: payload.description,
+ currentUserId: payload.currentUserId,
+ });
+
+ // ✅ userId 검증: 핸들러에서 userId가 없으면 잘못된 상황 (예외 처리)
+ if (!payload.currentUserId || payload.currentUserId <= 0) {
+ const errorMessage = 'currentUserId가 없습니다. actionPayload에 currentUserId가 포함되지 않았습니다.';
+ debugError('[BiddingClosureHandler]', errorMessage);
+ throw new Error(errorMessage);
+ }
+
+ try {
+ // 1. 입찰 상태를 폐찰로 변경
+ const { default: db } = await import('@/db/db');
+ const { biddings } = await import('@/db/schema');
+ const { eq } = await import('drizzle-orm');
+
+ await db
+ .update(biddings)
+ .set({
+ status: 'closed',
+ updatedBy: payload.currentUserId.toString(),
+ updatedAt: new Date(),
+ remarks: payload.description, // 폐찰 사유를 remarks에 저장
+ })
+ .where(eq(biddings.id, payload.biddingId));
+
+ debugSuccess('[BiddingClosureHandler] 폐찰 완료', {
+ biddingId: payload.biddingId,
+ description: payload.description,
+ });
+
+ // 4. 첨부파일들 저장 (evaluation_doc로 저장)
+ if (payload.files && payload.files.length > 0) {
+ const { saveFile } = await import('@/lib/file-stroage');
+ const { biddingDocuments } = await import('@/db/schema');
+
+ for (const file of payload.files) {
+ try {
+ const saveResult = await saveFile({
+ file,
+ directory: `biddings/${payload.biddingId}/closure-documents`,
+ originalName: file.name,
+ userId: payload.currentUserId.toString()
+ })
+
+ if (saveResult.success) {
+ await db.insert(biddingDocuments).values({
+ biddingId: payload.biddingId,
+ documentType: 'evaluation_doc',
+ fileName: saveResult.fileName!,
+ originalFileName: saveResult.originalName!,
+ fileSize: saveResult.fileSize!,
+ mimeType: file.type,
+ filePath: saveResult.publicPath!,
+ title: `폐찰 문서 - ${file.name}`,
+ description: payload.description,
+ isPublic: false,
+ isRequired: false,
+ uploadedBy: payload.currentUserId.toString(),
+ })
+ } else {
+ console.error(`Failed to save closure file: ${file.name}`, saveResult.error)
+ }
+ } catch (error) {
+ console.error(`Error saving closure file: ${file.name}`, error)
+ }
+ }
+ }
+
+
+ return {
+ success: true,
+ biddingId: payload.biddingId,
+ message: `입찰이 폐찰 처리되었습니다.`,
+ };
+ } catch (error) {
+ debugError('[BiddingClosureHandler] 폐찰 중 에러', error);
+ throw error;
+ }
+}
+
+/**
+ * 낙찰 핸들러 (결재 승인 후 실행됨)
+ *
+ * ✅ Internal 함수: 결재 워크플로우에서 자동 호출됨 (직접 호출 금지)
+ *
+ * @param payload - withApproval()에서 전달한 actionPayload (최소 데이터만)
+ */
+export async function requestBiddingAwardInternal(payload: {
+ biddingId: number;
+ selectionReason: string;
+ currentUserId: number; // ✅ 결재 상신한 사용자 ID
+}) {
+ debugLog('[BiddingAwardHandler] 낙찰 핸들러 시작', {
+ biddingId: payload.biddingId,
+ selectionReason: payload.selectionReason,
+ currentUserId: payload.currentUserId,
+ });
+
+ // ✅ userId 검증: 핸들러에서 userId가 없으면 잘못된 상황 (예외 처리)
+ if (!payload.currentUserId || payload.currentUserId <= 0) {
+ const errorMessage = 'currentUserId가 없습니다. actionPayload에 currentUserId가 포함되지 않았습니다.';
+ debugError('[BiddingAwardHandler]', errorMessage);
+ throw new Error(errorMessage);
+ }
+
+ try {
+ // 기존 awardBidding 함수 로직을 재구성하여 실행
+ const { awardBidding } = await import('@/lib/bidding/detail/service');
+
+ const result = await awardBidding(payload.biddingId, payload.selectionReason, payload.currentUserId.toString());
+
+ if (!result.success) {
+ debugError('[BiddingAwardHandler] 낙찰 처리 실패', result.error);
+ throw new Error(result.error || '낙찰 처리에 실패했습니다.');
+ }
+
+ debugSuccess('[BiddingAwardHandler] 낙찰 완료', {
+ biddingId: payload.biddingId,
+ selectionReason: payload.selectionReason,
+ });
+
+ return {
+ success: true,
+ biddingId: payload.biddingId,
+ message: `입찰이 낙찰 처리되었습니다.`,
+ };
+ } catch (error) {
+ debugError('[BiddingAwardHandler] 낙찰 중 에러', error);
+ throw error;
+ }
+}
+
+/**
+ * 낙찰 데이터를 결재 템플릿 변수로 매핑
+ *
+ * @param payload - 낙찰 데이터
+ * @returns 템플릿 변수 객체 (Record<string, string>)
+ */
+export async function mapBiddingAwardToTemplateVariables(payload: {
+ biddingId: number;
+ selectionReason: string;
+ requestedAt: Date;
+}): Promise<Record<string, string>> {
+ const { biddingId, selectionReason, requestedAt } = payload;
+
+ // 1. 입찰 정보 조회
+ debugLog('[BiddingAwardMapper] 입찰 정보 조회 시작');
+ const { default: db } = await import('@/db/db');
+ const { biddings, prItemsForBidding } = await import('@/db/schema');
+ const { eq } = await import('drizzle-orm');
+
+ const biddingInfo = await db
+ .select({
+ id: biddings.id,
+ title: biddings.title,
+ biddingNumber: biddings.biddingNumber,
+ projectName: biddings.projectName,
+ itemName: biddings.itemName,
+ biddingType: biddings.biddingType,
+ bidPicName: biddings.bidPicName,
+ supplyPicName: biddings.supplyPicName,
+ targetPrice: biddings.targetPrice,
+ winnerCount: biddings.winnerCount,
+ })
+ .from(biddings)
+ .where(eq(biddings.id, biddingId))
+ .limit(1);
+
+ if (biddingInfo.length === 0) {
+ debugError('[BiddingAwardMapper] 입찰 정보를 찾을 수 없음');
+ throw new Error('입찰 정보를 찾을 수 없습니다');
+ }
+
+ const bidding = biddingInfo[0];
+
+ // 2. 낙찰된 업체 정보 조회
+ const { getAwardedCompanies } = await import('@/lib/bidding/detail/service');
+ const awardedCompanies = await getAwardedCompanies(biddingId);
+
+ // 3. 입찰 대상 자재 정보 조회
+ const biddingItemsInfo = await db
+ .select({
+ id: prItemsForBidding.id,
+ materialNumber: prItemsForBidding.materialNumber,
+ materialInfo: prItemsForBidding.materialInfo,
+ priceUnit: prItemsForBidding.priceUnit,
+ quantity: prItemsForBidding.quantity,
+ quantityUnit: prItemsForBidding.quantityUnit,
+ totalWeight: prItemsForBidding.totalWeight,
+ weightUnit: prItemsForBidding.weightUnit,
+ targetUnitPrice: prItemsForBidding.targetUnitPrice,
+ currency: prItemsForBidding.targetCurrency,
+ })
+ .from(prItemsForBidding)
+ .where(eq(prItemsForBidding.biddingId, biddingId));
+
+ debugLog('[BiddingAwardMapper] 입찰 정보 조회 완료', {
+ biddingId,
+ itemCount: biddingItemsInfo.length,
+ awardedCompanyCount: awardedCompanies.length,
+ });
+
+ // 기본 정보 매핑
+ const title = bidding.title || '낙찰';
+ const biddingTitle = bidding.title || '';
+ const biddingNumber = bidding.biddingNumber || '';
+ const winnerCount = (bidding.winnerCount || 1).toString();
+ const contractType = bidding.biddingType || '';
+ const budget = bidding.targetPrice ? bidding.targetPrice.toLocaleString() : '';
+ const targetPrice = bidding.targetPrice ? bidding.targetPrice.toLocaleString() : '';
+ const biddingManager = bidding.bidPicName || bidding.supplyPicName || '';
+ const biddingOverview = bidding.itemName || '';
+
+ // 업체 선정 사유
+ const selectionReasonMapped = selectionReason;
+
+ // 낙찰된 업체 정보 매핑
+ const vendorVariables: Record<string, string> = {};
+ awardedCompanies.forEach((company, index) => {
+ const num = index + 1;
+ vendorVariables[`협력사_코드_${num}`] = company.vendorCode || '';
+ vendorVariables[`협력사명_${num}`] = company.companyName || '';
+ vendorVariables[`기업규모_${num}`] = company.companySize || ''; // TODO: 기업규모 정보가 없으므로 빈 값
+ vendorVariables[`연동제희망여부_${num}`] = 'N'; // TODO: 연동제 정보 미개발
+ vendorVariables[`연동제적용여부_${num}`] = 'N'; // TODO: 연동제 정보 미개발
+ vendorVariables[`낙찰유무_${num}`] = '낙찰';
+ vendorVariables[`확정금액_${num}`] = (company.finalQuoteAmount * company.awardRatio / 100).toLocaleString();
+ vendorVariables[`내정액_${num}`] = company.targetPrice ? company.targetPrice.toLocaleString() : '';
+ vendorVariables[`입찰액_${num}`] = company.finalQuoteAmount.toLocaleString();
+ vendorVariables[`비율_${num}`] = company.targetPrice && company.targetPrice > 0
+ ? ((company.finalQuoteAmount / company.targetPrice) * 100).toFixed(2) + '%'
+ : '';
+ });
+
+ // 품목별 입찰 정보 매핑
+ const materialVariables: Record<string, string> = {};
+ biddingItemsInfo.forEach((item, index) => {
+ const num = index + 1;
+ materialVariables[`자재번호_${num}`] = item.materialNumber || '';
+ materialVariables[`자재내역_${num}`] = item.materialInfo || '';
+ materialVariables[`구매단위_${num}`] = item.priceUnit || '';
+ materialVariables[`수량_${num}`] = item.quantity ? item.quantity.toLocaleString() : '';
+ materialVariables[`수량단위_${num}`] = item.quantityUnit || '';
+ materialVariables[`총중량_${num}`] = item.totalWeight ? item.totalWeight.toLocaleString() : '';
+ materialVariables[`중량단위_${num}`] = item.weightUnit || '';
+ materialVariables[`통화_${num}`] = item.currency || '';
+ materialVariables[`내정액_${num}`] = item.targetUnitPrice ? item.targetUnitPrice.toLocaleString() : '';
+
+ // 각 품목에 대한 낙찰 협력사 정보 (낙찰된 업체만 표시)
+ awardedCompanies.forEach((company, companyIndex) => {
+ const companyNum = companyIndex + 1;
+ materialVariables[`협력사명_${num}`] = company.companyName || '';
+ materialVariables[`입찰액_${num}`] = company.finalQuoteAmount.toLocaleString();
+ });
+ });
+
+ return {
+ 제목: title,
+ 입찰명: biddingTitle,
+ 입찰번호: biddingNumber,
+ 낙찰업체수: winnerCount,
+ 계약구분: contractType,
+ 예산: budget,
+ 내정액: targetPrice,
+ 입찰담당자: biddingManager,
+ 입찰개요: biddingOverview,
+ 업체선정사유: selectionReasonMapped,
+ 대상_자재_수: biddingItemsInfo.length.toString(),
+ ...vendorVariables,
+ ...materialVariables,
+ };
+}
diff --git a/lib/bidding/list/bidding-pr-documents-dialog.tsx b/lib/bidding/list/bidding-pr-documents-dialog.tsx
index ad377ee5..9d291ad8 100644
--- a/lib/bidding/list/bidding-pr-documents-dialog.tsx
+++ b/lib/bidding/list/bidding-pr-documents-dialog.tsx
@@ -304,7 +304,7 @@ export function PrDocumentsDialog({
</div>
</TableCell>
<TableCell className="text-xs">
- {item.purchaseUnit || "-"}
+ {item.priceUnit || "-"}
</TableCell>
<TableCell>
<div className="flex items-center gap-1">
diff --git a/lib/bidding/list/create-bidding-dialog.tsx b/lib/bidding/list/create-bidding-dialog.tsx
index 2f458873..90abda57 100644
--- a/lib/bidding/list/create-bidding-dialog.tsx
+++ b/lib/bidding/list/create-bidding-dialog.tsx
@@ -201,8 +201,8 @@ export function CreateBiddingDialog() {
materialGroupInfo: '',
materialNumber: '',
materialInfo: '',
- priceUnit: '',
- purchaseUnit: '1',
+ priceUnit: '1',
+ purchaseUnit: 'EA',
materialWeight: '',
wbsCode: '',
wbsName: '',
@@ -427,8 +427,8 @@ export function CreateBiddingDialog() {
materialGroupInfo: '',
materialNumber: '',
materialInfo: '',
- priceUnit: '',
- purchaseUnit: '1',
+ priceUnit: '1',
+ purchaseUnit: 'EA',
materialWeight: '',
wbsCode: '',
wbsName: '',
@@ -471,8 +471,8 @@ export function CreateBiddingDialog() {
prev.map((item) => {
if (item.id === id) {
const updatedItem = { ...item, ...updates }
- // 내정단가, 수량, 중량, 구매단위가 변경되면 내정금액 재계산
- if (updates.targetUnitPrice || updates.quantity || updates.totalWeight || updates.purchaseUnit) {
+ // 내정단가, 수량, 중량, 가격단위가 변경되면 내정금액 재계산
+ if (updates.targetUnitPrice || updates.quantity || updates.totalWeight || updates.priceUnit) {
updatedItem.targetAmount = calculateTargetAmount(updatedItem)
}
return updatedItem
@@ -497,17 +497,17 @@ export function CreateBiddingDialog() {
const calculateTargetAmount = (item: PRItemInfo) => {
const unitPrice = parseFloat(item.targetUnitPrice) || 0
- const purchaseUnit = parseFloat(item.purchaseUnit) || 1 // 기본값 1
+ const priceUnit = parseFloat(item.priceUnit) || 1 // 기본값 1
let amount = 0
if (quantityWeightMode === 'quantity') {
const quantity = parseFloat(item.quantity) || 0
- // (수량 / 구매단위) * 내정단가
- amount = (quantity / purchaseUnit) * unitPrice
+ // (수량 / 가격단위) * 내정단가
+ amount = (quantity / priceUnit) * unitPrice
} else {
const weight = parseFloat(item.totalWeight) || 0
- // (중량 / 구매단위) * 내정단가
- amount = (weight / purchaseUnit) * unitPrice
+ // (중량 / 가격단위) * 내정단가
+ amount = (weight / priceUnit) * unitPrice
}
// 소수점 버림
@@ -772,6 +772,7 @@ export function CreateBiddingDialog() {
<th className="border-r px-3 py-3 text-left text-xs font-medium min-w-[300px]">자재명</th>
<th className="border-r px-3 py-3 text-left text-xs font-medium min-w-[120px]">수량</th>
<th className="border-r px-3 py-3 text-left text-xs font-medium min-w-[80px]">단위</th>
+ <th className="border-r px-3 py-3 text-left text-xs font-medium min-w-[80px]">가격단위</th>
<th className="border-r px-3 py-3 text-left text-xs font-medium min-w-[80px]">구매단위</th>
<th className="border-r px-3 py-3 text-left text-xs font-medium min-w-[120px]">내정단가</th>
<th className="border-r px-3 py-3 text-left text-xs font-medium min-w-[120px]">내정금액</th>
@@ -955,13 +956,48 @@ export function CreateBiddingDialog() {
type="number"
min="1"
step="1"
- placeholder="구매단위"
- value={item.purchaseUnit || ''}
- onChange={(e) => updatePRItem(item.id, { purchaseUnit: e.target.value })}
+ placeholder="가격단위"
+ value={item.priceUnit || ''}
+ onChange={(e) => updatePRItem(item.id, { priceUnit: e.target.value })}
className="h-8 text-xs"
/>
</td>
<td className="border-r px-3 py-2">
+ {quantityWeightMode === 'quantity' ? (
+ <Select
+ value={item.purchaseUnit || item.quantityUnit || 'EA'}
+ onValueChange={(value) => updatePRItem(item.id, { purchaseUnit: value })}
+ >
+ <SelectTrigger className="h-8 text-xs">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="EA">EA</SelectItem>
+ <SelectItem value="SET">SET</SelectItem>
+ <SelectItem value="LOT">LOT</SelectItem>
+ <SelectItem value="M">M</SelectItem>
+ <SelectItem value="M2">M²</SelectItem>
+ <SelectItem value="M3">M³</SelectItem>
+ </SelectContent>
+ </Select>
+ ) : (
+ <Select
+ value={item.purchaseUnit || item.weightUnit || 'KG'}
+ onValueChange={(value) => updatePRItem(item.id, { purchaseUnit: value })}
+ >
+ <SelectTrigger className="h-8 text-xs">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="KG">KG</SelectItem>
+ <SelectItem value="TON">TON</SelectItem>
+ <SelectItem value="G">G</SelectItem>
+ <SelectItem value="LB">LB</SelectItem>
+ </SelectContent>
+ </Select>
+ )}
+ </td>
+ <td className="border-r px-3 py-2">
<Input
type="number"
min="0"
diff --git a/lib/bidding/service.ts b/lib/bidding/service.ts
index 0261ad57..fe37eaea 100644
--- a/lib/bidding/service.ts
+++ b/lib/bidding/service.ts
@@ -2363,7 +2363,7 @@ export async function updateBiddingSchedule(
.insert(specificationMeetings)
.values({
biddingId,
- meetingDate: specificationMeeting.meetingDate,
+ meetingDate: parseDate(specificationMeeting.meetingDate),
meetingTime: specificationMeeting.meetingTime || null,
location: specificationMeeting.location,
address: specificationMeeting.address || null,
@@ -2545,6 +2545,39 @@ export async function removeBiddingItem(itemId: number) {
}
}
+// 입찰의 PR 아이템 금액 합산하여 bidding 업데이트
+async function updateBiddingAmounts(biddingId: number) {
+ try {
+ // 해당 bidding의 모든 PR 아이템들의 금액 합계 계산
+ const amounts = await db
+ .select({
+ totalTargetAmount: sql<number>`COALESCE(SUM(${prItemsForBidding.targetAmount}), 0)`,
+ totalBudgetAmount: sql<number>`COALESCE(SUM(${prItemsForBidding.budgetAmount}), 0)`,
+ totalActualAmount: sql<number>`COALESCE(SUM(${prItemsForBidding.actualAmount}), 0)`
+ })
+ .from(prItemsForBidding)
+ .where(eq(prItemsForBidding.biddingId, biddingId))
+
+ const { totalTargetAmount, totalBudgetAmount, totalActualAmount } = amounts[0]
+
+ // bidding 테이블 업데이트
+ await db
+ .update(biddings)
+ .set({
+ targetPrice: totalTargetAmount,
+ budget: totalBudgetAmount,
+ finalBidPrice: totalActualAmount,
+ updatedAt: new Date()
+ })
+ .where(eq(biddings.id, biddingId))
+
+ console.log(`Bidding ${biddingId} amounts updated: target=${totalTargetAmount}, budget=${totalBudgetAmount}, actual=${totalActualAmount}`)
+ } catch (error) {
+ console.error('Failed to update bidding amounts:', error)
+ throw error
+ }
+}
+
// PR 아이템 추가 (전체 필드 지원)
export async function addPRItemForBidding(
biddingId: number,
@@ -2620,6 +2653,9 @@ export async function addPRItemForBidding(
hasSpecDocument: item.hasSpecDocument || false,
}).returning()
+ // PR 아이템 금액 합산하여 bidding 업데이트
+ await updateBiddingAmounts(biddingId)
+
revalidatePath(`/evcp/bid/${biddingId}/info`)
revalidatePath(`/evcp/bid/${biddingId}`)
@@ -2653,6 +2689,7 @@ export async function getBiddingVendors(biddingId: number) {
currency: sql<string>`'KRW'`,
invitationStatus: biddingCompanies.invitationStatus,
isPriceAdjustmentApplicableQuestion: biddingCompanies.isPriceAdjustmentApplicableQuestion,
+ businessSize: vendors.businessSize,
})
.from(biddingCompanies)
.leftJoin(vendors, eq(biddingCompanies.companyId, vendors.id))
@@ -3223,7 +3260,7 @@ export async function searchVendorsForBidding(searchTerm: string = "", biddingId
)
)
.orderBy(asc(vendorsWithTypesView.vendorName));
-
+
return result;
} catch (error) {
@@ -3232,6 +3269,34 @@ export async function searchVendorsForBidding(searchTerm: string = "", biddingId
}
}
+// 선택된 vendor들의 businessSize 정보를 가져오는 함수
+export async function getVendorsBusinessSize(vendorIds: number[]) {
+ try {
+ if (vendorIds.length === 0) {
+ return {};
+ }
+
+ const result = await db
+ .select({
+ id: vendors.id,
+ businessSize: vendors.businessSize,
+ })
+ .from(vendors)
+ .where(inArray(vendors.id, vendorIds));
+
+ // Map 형태로 변환하여 반환
+ const businessSizeMap: Record<number, string | null> = {};
+ result.forEach(vendor => {
+ businessSizeMap[vendor.id] = vendor.businessSize;
+ });
+
+ return businessSizeMap;
+ } catch (error) {
+ console.error('Error getting vendors business size:', error);
+ return {};
+ }
+}
+
// 차수증가 또는 재입찰 함수
export async function increaseRoundOrRebid(biddingId: number, userId: string | undefined, type: 'round_increase' | 'rebidding') {
if (!userId) {
diff --git a/lib/bidding/validation.ts b/lib/bidding/validation.ts
index f70e498e..73c2fe21 100644
--- a/lib/bidding/validation.ts
+++ b/lib/bidding/validation.ts
@@ -114,7 +114,7 @@ export const createBiddingSchema = z.object({
isUrgent: z.boolean().default(false),
// 구매조직
- purchasingOrganization: z.string().optional(),
+ purchasingOrganization: z.string().min(1, "구매조직을 선택해주세요"),
// 담당자 정보 (개선된 구조)
bidPicId: z.number().int().positive().optional(),
diff --git a/lib/bidding/vendor/components/pr-items-pricing-table.tsx b/lib/bidding/vendor/components/pr-items-pricing-table.tsx
index efa10af2..22051a13 100644
--- a/lib/bidding/vendor/components/pr-items-pricing-table.tsx
+++ b/lib/bidding/vendor/components/pr-items-pricing-table.tsx
@@ -294,10 +294,10 @@ export function PrItemsPricingTable({
<TableHead>자재내역</TableHead>
<TableHead>수량</TableHead>
<TableHead>단위</TableHead>
- <TableHead>구매단위</TableHead>
+ <TableHead>가격단위</TableHead>
<TableHead>중량</TableHead>
<TableHead>중량단위</TableHead>
- <TableHead>가격단위</TableHead>
+ <TableHead>구매단위</TableHead>
<TableHead>SHI 납품요청일</TableHead>
<TableHead>견적단가</TableHead>
<TableHead>견적금액</TableHead>
@@ -336,12 +336,12 @@ export function PrItemsPricingTable({
{item.quantity ? parseFloat(item.quantity).toLocaleString() : '-'}
</TableCell>
<TableCell>{item.quantityUnit || '-'}</TableCell>
- <TableCell>{item.purchaseUnit || '-'}</TableCell>
+ <TableCell>{item.priceUnit || '-'}</TableCell>
<TableCell className="text-right">
{item.totalWeight ? parseFloat(item.totalWeight).toLocaleString() : '-'}
</TableCell>
<TableCell>{item.weightUnit || '-'}</TableCell>
- <TableCell>{item.priceUnit || '-'}</TableCell>
+ <TableCell>{item.purchaseUnit || '-'}</TableCell>
<TableCell>
{item.requestedDeliveryDate ?
formatDate(item.requestedDeliveryDate, 'KR') : '-'
diff --git a/lib/bidding/vendor/partners-bidding-detail.tsx b/lib/bidding/vendor/partners-bidding-detail.tsx
index 0215bcb6..504fc916 100644
--- a/lib/bidding/vendor/partners-bidding-detail.tsx
+++ b/lib/bidding/vendor/partners-bidding-detail.tsx
@@ -854,7 +854,7 @@ export function PartnersBiddingDetail({ biddingId, companyId }: PartnersBiddingD
<Label className="text-sm font-medium text-muted-foreground mb-2 block">제출 마감 정보</Label>
{(() => {
const now = new Date()
- const deadline = new Date(biddingDetail.submissionEndDate)
+ const deadline = new Date(biddingDetail.submissionEndDate.toISOString().slice(0, 16).replace('T', ' '))
const isExpired = deadline < now
const timeLeft = deadline.getTime() - now.getTime()
const daysLeft = Math.floor(timeLeft / (1000 * 60 * 60 * 24))
@@ -873,7 +873,7 @@ export function PartnersBiddingDetail({ biddingId, companyId }: PartnersBiddingD
<Calendar className="w-5 h-5" />
<span className="font-medium">제출 마감일:</span>
<span className="text-lg font-semibold">
- {formatDate(biddingDetail.submissionEndDate, 'KR')}
+ {biddingDetail.submissionEndDate.toISOString().slice(0, 16).replace('T', ' ')}
</span>
</div>
{isExpired ? (
@@ -1025,7 +1025,7 @@ export function PartnersBiddingDetail({ biddingId, companyId }: PartnersBiddingD
</div>
{/* <div>
- <Label className="text-muted-foreground">연동제 적용</Label>
+ <Label className="text-muted-foreground">하도급법 적용여부</Label>
<div className="mt-1 p-3 bg-muted rounded-md">
<p className="font-medium">{biddingConditions.isPriceAdjustmentApplicable ? "적용 가능" : "적용 불가"}</p>
</div>
@@ -1179,7 +1179,7 @@ export function PartnersBiddingDetail({ biddingId, companyId }: PartnersBiddingD
<CardContent className="space-y-4">
{/* 공통 필드 - 품목등의 명칭 */}
<div className="space-y-2">
- <Label htmlFor="itemName">품목등의 명칭 *</Label>
+ <Label htmlFor="itemName">물품등의 명칭 *</Label>
<Input
id="itemName"
value={priceAdjustmentForm.itemName}
@@ -1205,7 +1205,7 @@ export function PartnersBiddingDetail({ biddingId, companyId }: PartnersBiddingD
</div>
<div className="space-y-2">
- <Label htmlFor="adjustmentRatio">연동 비율 (%) *</Label>
+ <Label htmlFor="adjustmentRatio">반영비율 (%) *</Label>
<Input
id="adjustmentRatio"
type="number"
@@ -1229,7 +1229,7 @@ export function PartnersBiddingDetail({ biddingId, companyId }: PartnersBiddingD
</div>
<div className="space-y-2">
- <Label htmlFor="referenceDate">기준시점 *</Label>
+ <Label htmlFor="referenceDate">원재료 기준 가격의 변동률 산정을 위한 기준시점 *</Label>
<Input
id="referenceDate"
type="date"
@@ -1240,7 +1240,7 @@ export function PartnersBiddingDetail({ biddingId, companyId }: PartnersBiddingD
</div>
<div className="space-y-2">
- <Label htmlFor="comparisonDate">비교시점 *</Label>
+ <Label htmlFor="comparisonDate">원재료 기준 가격의 변동률 산정을 위한 비교시점 *</Label>
<Input
id="comparisonDate"
type="date"
@@ -1251,7 +1251,7 @@ export function PartnersBiddingDetail({ biddingId, companyId }: PartnersBiddingD
</div>
<div className="space-y-2">
- <Label htmlFor="contractorWriter">수탁기업(협력사) 작성자 *</Label>
+ <Label htmlFor="contractorWriter">수탁기업(협력사)작성자 *</Label>
<Input
id="contractorWriter"
value={priceAdjustmentForm.contractorWriter}
@@ -1322,7 +1322,7 @@ export function PartnersBiddingDetail({ biddingId, companyId }: PartnersBiddingD
</div>
<div className="space-y-2">
- <Label htmlFor="priceAdjustmentNotes">기타 사항</Label>
+ <Label htmlFor="priceAdjustmentNotes">기타사항</Label>
<Textarea
id="priceAdjustmentNotes"
value={priceAdjustmentForm.notes}
@@ -1376,6 +1376,15 @@ export function PartnersBiddingDetail({ biddingId, companyId }: PartnersBiddingD
</CardContent>
</Card>
)}
+
+ {/* 참고 경고문 */}
+ <div className="text-xs text-red-600 space-y-2 bg-red-50 p-3 rounded-md border border-red-200 mt-4">
+ <p className="font-medium">※ 참고사항</p>
+ <div className="space-y-1">
+ <p>• 납품대금의 10% 이상을 차지하는 주요 원재료가 있는 경우 모든 주요 원재료에 대해서 적용 또는 미적용에 대한 연동표를 작성해야 한다.</p>
+ <p>• 납품대급연동표를 허위로 작성하거나 근거자료를 허위로 제출할 경우 본 계약이 체결되지 않을 수 있으며, 본 계약이 체결되었더라도 계약의 전부 또는 일부를 해제 또는 해지할 수 있다.</p>
+ </div>
+ </div>
</>
)}
diff --git a/lib/bidding/vendor/partners-bidding-list-columns.tsx b/lib/bidding/vendor/partners-bidding-list-columns.tsx
index 63d097c0..8cbddb3d 100644
--- a/lib/bidding/vendor/partners-bidding-list-columns.tsx
+++ b/lib/bidding/vendor/partners-bidding-list-columns.tsx
@@ -169,6 +169,19 @@ export function getPartnersBiddingListColumns({ setRowAction }: PartnersBiddingL
}
const handleView = () => {
+ // 입찰기간 체크 (현 시간 기준으로 입찰기간 시작 전이면 접근 불가)
+ const now = new Date()
+ const startDate = row.original.submissionStartDate ? new Date(row.original.submissionStartDate) : null
+ const endDate = row.original.submissionEndDate ? new Date(row.original.submissionEndDate) : null
+
+ if (startDate && now < startDate) {
+ toast.warning('입찰기간 전 접근 제한', {
+ description: `입찰기간이 아직 시작되지 않았습니다. 입찰 시작일: ${format(startDate, "yyyy-MM-dd HH:mm")}`,
+ duration: 5000,
+ })
+ return
+ }
+
// 사양설명회 체크
if (!checkSpecificationMeeting()) {
return