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
|
"use server";
import path from "path";
import { v4 as uuidv4 } from "uuid";
import { headers } from "next/headers";
import db from "@/db/db";
import { GetPOSchema } from "./validations";
import { unstable_cache } from "@/lib/unstable-cache";
import { filterColumns } from "@/lib/filter-columns";
import {
asc,
desc,
ilike,
inArray,
and,
gte,
lte,
not,
or,
eq,
count,
} from "drizzle-orm";
import { countPos, selectPos } from "./repository";
import {
contractEnvelopes,
contractsDetailView,
contractSigners,
contracts,
} from "@/db/schema/contract";
import { vendors, vendorContacts } from "@/db/schema/vendors";
import { revalidatePath } from "next/cache";
import * as z from "zod";
import { POContent } from "@/lib/docuSign/types";
/**
* PQ 목록 조회
*/
export async function getPOs(input: GetPOSchema) {
return unstable_cache(
async () => {
try {
const offset = (input.page - 1) * input.perPage;
// 1. Try a simple query first to make sure the view works at all
try {
const testQuery = await db
.select({ count: count() })
.from(contractsDetailView);
console.log("Test query result:", testQuery);
} catch (testErr) {
console.error("Test query failed:", testErr);
}
// 2. Build where clause with more careful handling
let advancedWhere;
try {
advancedWhere = filterColumns({
table: contractsDetailView,
filters: input.filters,
joinOperator: input.joinOperator,
});
console.log("Advanced where clause built successfully");
} catch (whereErr) {
console.error("Error building advanced where:", whereErr);
advancedWhere = undefined;
}
let globalWhere;
if (input.search) {
try {
const s = `%${input.search}%`;
globalWhere = or(
ilike(contractsDetailView.contractNo, s),
ilike(contractsDetailView.contractName, s)
);
console.log("Global where clause built successfully");
} catch (searchErr) {
console.error("Error building search where:", searchErr);
globalWhere = undefined;
}
}
// 3. Combine where clauses safely
let finalWhere;
if (advancedWhere && globalWhere) {
finalWhere = and(advancedWhere, globalWhere);
} else {
finalWhere = advancedWhere || globalWhere;
}
// 4. Build order by
let orderBy;
try {
orderBy =
input.sort.length > 0
? input.sort.map((item) =>
item.desc
? desc(contractsDetailView[item.id])
: asc(contractsDetailView[item.id])
)
: [asc(contractsDetailView.createdAt)];
} catch (orderErr) {
console.error("Error building order by:", orderErr);
orderBy = [asc(contractsDetailView.createdAt)];
}
// 5. Execute queries with proper error handling
let data = [];
let total = 0;
try {
// Try without transaction first for better error visibility
const queryBuilder = db.select().from(contractsDetailView);
// Add where clause if it exists
if (finalWhere) {
queryBuilder.where(finalWhere);
}
// Add ordering
queryBuilder.orderBy(...orderBy);
// Add pagination
queryBuilder.offset(offset).limit(input.perPage);
// Execute query
data = await queryBuilder;
// Get total count
const countBuilder = db
.select({ count: count() })
.from(contractsDetailView);
if (finalWhere) {
countBuilder.where(finalWhere);
}
const countResult = await countBuilder;
total = countResult[0]?.count || 0;
} catch (queryErr) {
console.error("Query execution failed:", queryErr);
throw queryErr; // Rethrow to be caught by the outer try/catch
}
const pageCount = Math.ceil(total / input.perPage);
return { data, pageCount };
} catch (err) {
// More detailed error logging
console.error("Error in getPOs:", err);
if (err instanceof Error) {
console.error("Error message:", err.message);
console.error("Error stack:", err.stack);
}
return { data: [], pageCount: 0 };
}
},
[JSON.stringify(input)],
{
revalidate: 3600,
tags: [`po`],
}
)();
}
// Schema for a single signer
const signerSchema = z.object({
signerEmail: z.string().email(),
signerName: z.string().min(1),
signerPosition: z.string(),
signerType: z.enum(["REQUESTER", "VENDOR"]),
vendorContactId: z.number().optional(),
});
// Schema for the entire request
const signatureRequestSchema = z.object({
contractId: z.number(),
signers: z.array(signerSchema).min(1, "At least one signer is required"),
});
/**
* Server action to request electronic signatures for a contract from multiple parties
*/
export async function requestSignatures(
input: z.infer<typeof signatureRequestSchema>
): Promise<{ success: boolean; message: string }> {
try {
// Validate the input
const validatedData = signatureRequestSchema.parse(input);
const headersList = await headers();
const host = headersList.get("host");
const proto = headersList.get("x-forwarded-proto") || "http"; // 기본값은 http
const origin = `${proto}://${host}`;
// Use a transaction to ensure data consistency
return await db.transaction(async (tx) => {
// Get contract details using standard select
const [contract] = await tx
.select()
.from(contracts)
.where(eq(contracts.id, validatedData.contractId))
.limit(1);
if (!contract) {
throw new Error(
`Contract with ID ${validatedData.contractId} not found`
);
}
// Generate unique envelope ID
// const envelopeId = `env-${Date.now()}-${Math.floor(
// Math.random() * 1000
// )}`;
// Get contract number or fallback
const contractNo =
contract.contractNo || `contract-${validatedData.contractId}`;
const signer = validatedData.signers.find(
(c) => c.signerType === "REQUESTER"
);
const vendor = validatedData.signers.find(
(c) => c.signerType === "VENDOR"
);
if (!vendor || !signer) {
return {
success: true,
message: `협력업체 서명자를 확인할 수 없습니다.`,
};
}
const { vendorContactId } = vendor;
if (!vendorContactId) {
return {
success: true,
message: `계약 번호를 확인할 수 없습니다.`,
};
}
const [vendorInfoData] = await tx
.select({
vendorContract: vendorContacts,
vendorInfo: vendors,
})
.from(vendorContacts)
.leftJoin(vendors, eq(vendorContacts.vendorId, vendors.id))
.where(eq(vendorContacts.id, vendorContactId))
.limit(1);
const { vendorContract, vendorInfo } = vendorInfoData;
const docuSignTempId = "73b04617-477c-4ec8-8a32-c8da701f6b0c";
const { totalAmount = "0", tax = "0" } = contract;
const totalAmountNum = Number(totalAmount);
const taxNum = Number(tax);
const taxRate = ((taxNum / totalAmountNum) * 100).toFixed(2);
const contractInfo: POContent = [
{ tabLabel: "po_no", value: contractNo },
{ tabLabel: "vendor_name", value: vendorInfo?.vendorName ?? "" },
{ tabLabel: "po_date", value: contract?.startDate ?? "" },
{ tabLabel: "project_name", value: contract.contractName },
{ tabLabel: "vendor_location", value: vendorInfo?.address ?? "" },
{ tabLabel: "shi_email", value: signer.signerEmail },
{ tabLabel: "vendor_email", value: vendorContract.contactEmail },
{ tabLabel: "po_desc", value: contract.contractName },
{ tabLabel: "qty", value: "1" },
{ tabLabel: "unit_price", value: totalAmountNum.toLocaleString() },
{ tabLabel: "total", value: totalAmountNum.toLocaleString() },
{
tabLabel: "grand_total_amount",
value: totalAmountNum.toLocaleString(),
},
{ tabLabel: "tax_rate", value: taxRate },
{ tabLabel: "tax_total", value: taxNum.toLocaleString() },
{
tabLabel: "payment_amount",
value: (totalAmountNum + taxNum).toLocaleString(),
},
{
tabLabel: "remark",
value: `결제 조건: ${contract.paymentTerms}
납품 조건: ${contract.deliveryTerms}
납품 기한: ${contract.deliveryDate}
납품 장소: ${contract.deliveryLocation}
계약 종료일/유효 기간: ${contract.endDate}
Remarks:${contract.remarks}`,
},
];
const sendDocuSign = await fetch(`${origin}/api/po/sendDocuSign`, {
method: "POST",
headers: {
"Content-Type": "application/json", // ✅ 이거 꼭 있어야 함!
},
body: JSON.stringify({
docuSignTempId,
contractInfo,
contractorInfo: {
email: "dts@dtsolution.co.kr",
name: "삼성중공업",
roleName: "shi",
},
subcontractorinfo: {
email: vendorContract.contactEmail,
name: vendorInfo?.vendorName,
roleName: "vendor",
},
ccInfo: [
// {
// email: "kiman.kim@dtsolution.io",
// name: "김기만",
// roleName: "cc",
// },
],
}),
}).then((data) => data.json());
const { success: sendDocuSignResult, envelopeId } = sendDocuSign;
await tx
.update(contracts)
.set({
status: sendDocuSignResult ? "PENDING_SIGNATURE" : "Docu Sign Failed",
})
.where(eq(contracts.id, validatedData.contractId));
if (!sendDocuSignResult) {
return {
success: false,
message: "DocuSign Mail 발송에 실패하였습니다.",
};
}
// Update contract status to indicate pending signatures
const fileName = `${contractNo}-signature.pdf`;
const ext = path.extname(fileName);
const uniqueName = uuidv4() + ext;
// Create a single envelope for all signers
const [newEnvelope] = await tx
.insert(contractEnvelopes)
.values({
contractId: validatedData.contractId,
envelopeId: envelopeId,
envelopeStatus: "sent",
fileName: `${contractNo}-signature.pdf`, // Required field
filePath: `/contracts/${validatedData.contractId}/signatures/${uniqueName}`, // Required field
// Add any other required fields based on your schema
})
.returning();
// // Check for duplicate emails
const signerEmails = new Set();
for (const signer of validatedData.signers) {
if (signerEmails.has(signer.signerEmail)) {
throw new Error(`Duplicate signer email: ${signer.signerEmail}`);
}
signerEmails.add(signer.signerEmail);
}
// Create signer records for each signer
for (const signer of validatedData.signers) {
await tx.insert(contractSigners).values({
envelopeId: newEnvelope.id,
signerEmail: signer.signerEmail,
signerName: signer.signerName,
signerPosition: signer.signerPosition,
signerStatus: "sent",
signerType: signer.signerType,
// Only include vendorContactId if it's provided and the signer is a vendor
...(signer.vendorContactId && signer.signerType === "VENDOR"
? { vendorContactId: signer.vendorContactId }
: {}),
});
}
// Revalidate the path to refresh the data
revalidatePath("/po");
// Return success response
return {
success: true,
message: `Signature requests sent to ${validatedData.signers.length} recipient(s)`,
};
});
} catch (error) {
console.error("Error requesting electronic signatures:", error);
return {
success: false,
message:
error instanceof Error
? error.message
: "Failed to send signature requests",
};
}
}
export async function getVendorContacts(vendorId: number) {
try {
const contacts = await db
.select({
id: vendorContacts.id,
contactName: vendorContacts.contactName,
contactEmail: vendorContacts.contactEmail,
contactPosition: vendorContacts.contactPosition,
contactPhone: vendorContacts.contactPhone,
isPrimary: vendorContacts.isPrimary,
})
.from(vendorContacts)
.where(eq(vendorContacts.vendorId, vendorId))
.orderBy(vendorContacts.isPrimary, vendorContacts.contactName);
return contacts;
} catch (error) {
console.error("Error fetching vendor contacts:", error);
throw new Error("Failed to fetch vendor contacts");
}
}
|