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
|
import {
pgTable,
text,
varchar,
timestamp,
integer,
numeric,
date,
boolean,
unique,
jsonb,
uniqueIndex, pgView
} from "drizzle-orm/pg-core"
import { projects } from "./projects"
import { vendorContacts, vendors } from "./vendors"
import { eq, sql } from "drizzle-orm";
// ============ contracts (계약/PO 정보) ============
export const contracts = pgTable("contracts", {
// 주 키
id: integer("id").primaryKey().generatedAlwaysAsIdentity(),
// 프로젝트와 벤더 참조
projectId: integer("project_id")
.notNull()
.references(() => projects.id, { onDelete: "cascade" }),
vendorId: integer("vendor_id")
.notNull()
.references(() => vendors.id, { onDelete: "cascade" }),
// 계약/PO 번호(유니크)
contractNo: varchar("contract_no", { length: 100 }).notNull().unique(),
contractName: varchar("contract_name", { length: 255 }).notNull(),
// 계약/PO 상태나 기간
status: varchar("status", { length: 50 }).notNull().default("ACTIVE"),
startDate: date("start_date"), // 발주일(혹은 유효 시작일)
endDate: date("end_date"), // 계약 종료일/유효 기간 등
// --- PO에 자주 쓰이는 필드 추가 ---
paymentTerms: text("payment_terms"), // 결제 조건(예: 30일 후 현금, 선금/잔금 등)
deliveryTerms: text("delivery_terms"), // 납품 조건(Incoterms 등)
deliveryDate: date("delivery_date"), // 납품 기한(납기 예정일)
deliveryLocation: varchar("delivery_location", { length: 255 }), // 납품 장소
// 가격/금액 관련
currency: varchar("currency", { length: 10 }).default("KRW"), // 통화 (KRW, USD 등)
totalAmount: numeric("total_amount", { precision: 12, scale: 2 }), // 총 계약 금액(아이템 합산 등)
discount: numeric("discount", { precision: 12, scale: 2 }), // 전체 할인
tax: numeric("tax", { precision: 12, scale: 2 }), // 전체 세금
shippingFee: numeric("shipping_fee", { precision: 12, scale: 2 }), // 배송비
netTotal: numeric("net_total", { precision: 12, scale: 2 }), // (합계) - (할인) + (세금) + (배송비)
// 부분 납품/부분 결제 가능 여부
partialShippingAllowed: boolean("partial_shipping_allowed").default(false),
partialPaymentAllowed: boolean("partial_payment_allowed").default(false),
// 추가 메모/비고
remarks: text("remarks"),
// 버전 관리 (PO 재발행 등)
version: integer("version").default(1),
// 생성/수정 시각
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at").defaultNow().notNull(),
})
// 타입 추론
export type Contract = typeof contracts.$inferSelect
// ============ contract_items (1:N 관계) ============
// 한 계약(contracts.id)에 여러 아이템을 연결
export const contractItems = pgTable("contract_items", {
id: integer("id").primaryKey().generatedAlwaysAsIdentity(),
contractId: integer("contract_id")
.notNull()
.references(() => contracts.id, { onDelete: "cascade" }),
itemId: integer("item_id")
.notNull()
// .references(() => items.id, { onDelete: "cascade" })
,
// --- 품목(아이템) 단위 정보 ---
description: text("description"), // 품목 설명 (스펙, 모델명 등)
quantity: integer("quantity").notNull().default(1),
unitPrice: numeric("unit_price", { precision: 10, scale: 2 }),
taxRate: numeric("tax_rate", { precision: 5, scale: 2 }), // % (예: 10.00)
taxAmount: numeric("tax_amount", { precision: 10, scale: 2 }), // 계산된 세금
totalLineAmount: numeric("total_line_amount", { precision: 12, scale: 2 }), // (수량×단가±할인+세금) 등
// 비고
remark: text("remark"),
// 생성/수정 시각
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at").defaultNow().notNull(),
}, (t) => [
// 같은 계약 + 같은 itemId에 대한 중복을 막음
unique().on(t.contractId, t.itemId),
uniqueIndex("contract_items_contract_item_idx").on(t.contractId, t.itemId),
])
export type ContractItem = typeof contractItems.$inferSelect
// ============ DocuSign 연동용 (전자서명 이력) ============
// Envelope(전자서명 요청) 테이블
export const contractEnvelopes = pgTable("contract_envelopes", {
id: integer("id").primaryKey().generatedAlwaysAsIdentity(),
// 연결된 계약
contractId: integer("contract_id")
.notNull()
.references(() => contracts.id, { onDelete: "cascade" }),
// DocuSign에서 발급되는 Envelope/Document 식별자
envelopeId: varchar("envelope_id", { length: 200 }).notNull(),
documentId: varchar("document_id", { length: 200 }),
// Envelope 전체 상태 (예: sent, completed, voided ...)
envelopeStatus: varchar("envelope_status", { length: 50 }),
fileName: varchar("file_name", { length: 255 }).notNull(),
filePath: varchar("file_path", { length: 1024 }).notNull(),
// 생성/수정 시각
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at").defaultNow().notNull(),
});
// 하나의 Envelope에 여러 서명자(사인 요청 대상)가 있을 수 있음
export const contractSigners = pgTable("contract_signers", {
id: integer("id").primaryKey().generatedAlwaysAsIdentity(),
// Envelope와 1:N 관계
envelopeId: integer("envelope_id")
.notNull()
.references(() => contractEnvelopes.id, { onDelete: "cascade" }),
// Reference to vendor_contacts table (optional - if signer is from vendor contacts)
vendorContactId: integer("vendor_contact_id")
.references(() => vendorContacts.id),
// Is this signer from the requester (company) side or vendor side
signerType: varchar("signer_type", {
length: 20,
enum: ["REQUESTER", "VENDOR"]
}).notNull().default("VENDOR"),
// 서명자 정보 (manual entry or populated from vendor contact)
signerEmail: varchar("signer_email", { length: 255 }).notNull(),
signerName: varchar("signer_name", { length: 100 }).notNull(),
signerPosition: varchar("signer_position", { length: 100 }),
// 서명자별 상태 (sent, delivered, signed, declined, etc.)
signerStatus: varchar("signer_status", { length: 50 }).default("PENDING"),
signedAt: timestamp("signed_at"),
// 생성/수정 시각
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at").defaultNow().notNull(),
});
export const contractsDetailView = pgView("contracts_detail_view").as((qb) => {
return qb
.select({
// Contract primary information
id: contracts.id,
contractNo: contracts.contractNo,
contractName: contracts.contractName,
status: contracts.status,
startDate: contracts.startDate,
endDate: contracts.endDate,
// Project information
projectId: contracts.projectId,
projectCode: projects.code,
projectName: projects.name,
// Vendor information
vendorId: contracts.vendorId,
vendorName: vendors.vendorName,
// Payment and delivery details
paymentTerms: contracts.paymentTerms,
deliveryTerms: contracts.deliveryTerms,
deliveryDate: contracts.deliveryDate,
deliveryLocation: contracts.deliveryLocation,
// Financial information
currency: contracts.currency,
totalAmount: contracts.totalAmount,
discount: contracts.discount,
tax: contracts.tax,
shippingFee: contracts.shippingFee,
netTotal: contracts.netTotal,
// Additional settings
partialShippingAllowed: contracts.partialShippingAllowed,
partialPaymentAllowed: contracts.partialPaymentAllowed,
remarks: contracts.remarks,
version: contracts.version,
// Timestamps
createdAt: contracts.createdAt,
updatedAt: contracts.updatedAt,
// Electronic signature status
hasSignature: sql<boolean>`EXISTS (
SELECT 1
FROM ${contractEnvelopes}
WHERE ${contractEnvelopes.contractId} = ${contracts.id}
)`.as("has_signature"),
// hasItme: sql<boolean>`EXISTS (
// SELECT 1
// FROM ${contractItems}
// WHERE ${contractItems.contractId} = ${contracts.id}
// )`.as("has_signature"),
// =========================
// 1) contract_items -> JSON
// =========================
// 'items' (or "contractItems")라는 필드를 JSON 배열로 가져오기
items: sql<string>`COALESCE((
SELECT json_agg(
json_build_object(
'id', ci.id,
'itemId', ci.item_id,
'description', ci.description,
'quantity', ci.quantity,
'unitPrice', ci.unit_price,
'taxRate', ci.tax_rate,
'taxAmount', ci.tax_amount,
'totalLineAmount', ci.total_line_amount,
'remark', ci.remark,
'createdAt', ci.created_at,
'updatedAt', ci.updated_at
)
)
FROM ${contractItems} AS ci
WHERE ci.contract_id = ${contracts.id}
), '[]')`.as("items"),
// =========================
// 2) contract_envelopes -> JSON
// =========================
envelopes: sql<string>`COALESCE((
SELECT json_agg(
json_build_object(
'id', ce.id,
'envelopeId', ce.envelope_id,
'documentId', ce.document_id,
'envelopeStatus', ce.envelope_status,
'fileName', ce.file_name,
'filePath', ce.file_path,
'createdAt', ce.created_at,
'updatedAt', ce.updated_at,
'signers', (
SELECT json_agg(
json_build_object(
'id', cs.id,
'vendorContactId', cs.vendor_contact_id,
'signerType', cs.signer_type,
'signerEmail', cs.signer_email,
'signerName', cs.signer_name,
'signerPosition', cs.signer_position,
'signerStatus', cs.signer_status,
'signedAt', cs.signed_at
)
)
FROM ${contractSigners} AS cs
WHERE cs.envelope_id = ce.id
)
)
)
FROM ${contractEnvelopes} AS ce
WHERE ce.contract_id = ${contracts.id}
), '[]')`.as("envelopes"),
})
.from(contracts)
.leftJoin(projects, eq(contracts.projectId, projects.id))
.leftJoin(vendors, eq(contracts.vendorId, vendors.id))
});
export interface ContractItemParsed {
id: number
itemId: number
description: string | null
quantity: number
unitPrice: number | null
taxRate: number | null
taxAmount: number | null
totalLineAmount: number | null
remark: string | null
createdAt: string
updatedAt: string
}
// 기존 Envelope + Signers
export interface Envelope {
id: number
envelopeId: string
documentId: string | null
envelopeStatus: string | null
fileName: string
filePath: string
createdAt: string
updatedAt: string
signers?: {
id: number
vendorContactId: number | null
signerType: string
signerEmail: string
signerName: string
signerPosition: string | null
signerStatus: string
signedAt: string | null
}[]
}
// Drizzle가 만들어준 raw type
export type ContractDetail = typeof contractsDetailView.$inferSelect;
// 우리가 UI에서 쓰고 싶은 파싱된 타입
export type ContractDetailParsed = Omit<ContractDetail, "envelopes" | "items"> & {
envelopes: Envelope[]
items: ContractItemParsed[]
}
|