summaryrefslogtreecommitdiff
path: root/lib/general-contracts/service.ts
diff options
context:
space:
mode:
Diffstat (limited to 'lib/general-contracts/service.ts')
-rw-r--r--lib/general-contracts/service.ts84
1 files changed, 67 insertions, 17 deletions
diff --git a/lib/general-contracts/service.ts b/lib/general-contracts/service.ts
index 2079a0be..8c74c616 100644
--- a/lib/general-contracts/service.ts
+++ b/lib/general-contracts/service.ts
@@ -10,6 +10,7 @@ import { contracts, contractItems, contractEnvelopes, contractSigners } from '@/
import { basicContract, basicContractTemplates } from '@/db/schema/basicContractDocumnet'
import { vendors } from '@/db/schema/vendors'
import { users } from '@/db/schema/users'
+import { projects } from '@/db/schema/projects'
import { filterColumns } from '@/lib/filter-columns'
import { saveDRMFile } from '@/lib/file-stroage'
import { decryptWithServerAction } from '@/components/drm/drmUtils'
@@ -70,9 +71,9 @@ export async function getGeneralContracts(input: GetGeneralContractsSchema) {
)
}
- if (input.selectionMethod && input.selectionMethod.length > 0) {
+ if (input.contractSourceType && input.contractSourceType.length > 0) {
basicConditions.push(
- or(...input.selectionMethod.map(method => eq(generalContracts.selectionMethod, method)))!
+ or(...input.contractSourceType.map(method => eq(generalContracts.contractSourceType, method)))!
)
}
@@ -202,7 +203,7 @@ export async function getGeneralContracts(input: GetGeneralContractsSchema) {
type: generalContracts.type,
executionMethod: generalContracts.executionMethod,
name: generalContracts.name,
- selectionMethod: generalContracts.selectionMethod,
+ contractSourceType: generalContracts.contractSourceType,
startDate: generalContracts.startDate,
endDate: generalContracts.endDate,
validityEndDate: generalContracts.validityEndDate,
@@ -223,6 +224,10 @@ export async function getGeneralContracts(input: GetGeneralContractsSchema) {
vendorId: generalContracts.vendorId,
vendorName: vendors.vendorName,
vendorCode: vendors.vendorCode,
+ // Project info
+ projectId: generalContracts.projectId,
+ projectName: projects.name,
+ projectCode: projects.code,
// User info
managerName: users.name,
lastUpdatedByName: users.name,
@@ -230,6 +235,7 @@ export async function getGeneralContracts(input: GetGeneralContractsSchema) {
.from(generalContracts)
.leftJoin(vendors, eq(generalContracts.vendorId, vendors.id))
.leftJoin(users, eq(generalContracts.registeredById, users.id))
+ .leftJoin(projects, eq(generalContracts.projectId, projects.id))
.where(finalWhere)
.orderBy(...orderByColumns)
.limit(input.perPage)
@@ -281,6 +287,13 @@ export async function getContractById(id: number) {
.where(eq(vendors.id, contract[0].vendorId))
.limit(1)
+ // Get project info
+ const project = contract[0].projectId ? await db
+ .select()
+ .from(projects)
+ .where(eq(projects.id, contract[0].projectId))
+ .limit(1) : null
+
// Get manager info
const manager = await db
.select()
@@ -293,6 +306,11 @@ export async function getContractById(id: number) {
contractItems: items,
attachments,
vendor: vendor[0] || null,
+ vendorCode: vendor[0]?.vendorCode || null,
+ vendorName: vendor[0]?.vendorName || null,
+ project: project ? project[0] : null,
+ projectName: project ? project[0].name : null,
+ projectCode: project ? project[0].code : null,
manager: manager[0] || null
}
} catch (error) {
@@ -354,7 +372,9 @@ export async function createContract(data: Record<string, unknown>) {
try {
// 계약번호 자동 생성
// TODO: 구매 발주담당자 코드 필요 - 파라미터 추가
+ const userId = data.registeredById as string
const contractNumber = await generateContractNumber(
+ userId,
data.type as string
)
@@ -369,8 +389,8 @@ export async function createContract(data: Record<string, unknown>) {
type: data.type as string,
executionMethod: data.executionMethod as string,
name: data.name as string,
- selectionMethod: data.selectionMethod as string,
vendorId: data.vendorId as number,
+ projectId: data.projectId as number,
startDate: data.startDate as string,
endDate: data.endDate as string,
validityEndDate: data.validityEndDate as string,
@@ -553,7 +573,6 @@ export async function createContractItem(contractId: number, itemData: Record<st
.insert(generalContractItems)
.values({
contractId,
- project: itemData.project as string,
itemCode: itemData.itemCode as string,
itemInfo: itemData.itemInfo as string,
specification: itemData.specification as string,
@@ -583,7 +602,6 @@ export async function updateContractItem(itemId: number, itemData: Record<string
const [updatedItem] = await db
.update(generalContractItems)
.set({
- project: itemData.project as string,
itemCode: itemData.itemCode as string,
itemInfo: itemData.itemInfo as string,
specification: itemData.specification as string,
@@ -653,7 +671,6 @@ export async function updateContractItems(contractId: number, items: Record<stri
.values(
items.map((item: Record<string, unknown>) => ({
contractId,
- project: item.project as string,
itemCode: item.itemCode as string,
itemInfo: item.itemInfo as string,
specification: item.specification as string,
@@ -903,11 +920,12 @@ export async function updateContract(id: number, data: Record<string, unknown>)
// 숫자 필드에서 빈 문자열을 null로 변환
const cleanedData = { ...data }
const numericFields = [
- 'vendorId',
- 'warrantyPeriodValue',
- 'warrantyPeriodMax',
- 'contractAmount',
- 'totalAmount',
+ 'vendorId',
+ 'projectId',
+ 'warrantyPeriodValue',
+ 'warrantyPeriodMax',
+ 'contractAmount',
+ 'totalAmount',
'availableBudget',
'liquidatedDamages',
'liquidatedDamagesPercent',
@@ -1537,7 +1555,7 @@ async function mapContractSummaryToDb(contractSummary: any) {
// 계약번호 생성
const contractNumber = await generateContractNumber(
basicInfo.contractType || basicInfo.type || 'UP',
- basicInfo.purchaseManagerCode
+ basicInfo.userId
)
return {
@@ -1699,8 +1717,8 @@ export async function updateOffsetDetails(
// 계약번호 생성 함수
export async function generateContractNumber(
- contractType: string,
- purchaseManagerCode?: string
+ userId?: string,
+ contractType: string
): Promise<string> {
try {
// 계약종류 매핑 (2자리) - GENERAL_CONTRACT_TYPES 상수 사용
@@ -1723,7 +1741,19 @@ export async function generateContractNumber(
}
const typeCode = contractTypeMap[contractType] || 'XX' // 기본값
- // 발주담당자 코드 처리
+ // user 테이블의 user.userCode가 있으면 발주담당자 코드로 사용
+ // userId가 주어졌을 때 user.userCode를 조회, 없으면 '000' 사용
+ let purchaseManagerCode = '000';
+ if (userId) {
+ const user = await db
+ .select({ userCode: users.userCode })
+ .from(users)
+ .where(eq(users.id, userId))
+ .limit(1);
+ if (user[0]?.userCode && user[0].userCode.length >= 3) {
+ purchaseManagerCode = user[0].userCode.substring(0, 3).toUpperCase();
+ }
+ }
let managerCode: string
if (purchaseManagerCode && purchaseManagerCode.length >= 3) {
// 발주담당자 코드가 있으면 3자리 사용
@@ -1776,9 +1806,29 @@ export async function generateContractNumber(
const contractNumber = `C${managerCode}${typeCode}${currentYear.toString().slice(-2)}${finalSequence}`
return contractNumber
-
+
} catch (error) {
console.error('계약번호 생성 오류:', error)
throw new Error('계약번호 생성에 실패했습니다.')
}
}
+
+// 프로젝트 목록 조회
+export async function getProjects() {
+ try {
+ const projectList = await db
+ .select({
+ id: projects.id,
+ code: projects.code,
+ name: projects.name,
+ type: projects.type,
+ })
+ .from(projects)
+ .orderBy(asc(projects.name))
+
+ return projectList
+ } catch (error) {
+ console.error('Error fetching projects:', error)
+ throw new Error('Failed to fetch projects')
+ }
+}