1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
|
/* eslint-disable @typescript-eslint/no-explicit-any */
'use server';
/* IMPORT */
import {
and,
asc,
desc,
ilike,
or,
} from 'drizzle-orm';
import {
countRegEvalCriteria,
deleteRegEvalCriteria,
deleteRegEvalCriteriaDetails,
insertRegEvalCriteria,
insertRegEvalCriteriaDetails,
selectRegEvalCriteria,
selectRegEvalCriteriaWithDetails,
updateRegEvalCriteria,
updateRegEvalCriteriaDetails,
} from './repository';
import db from '@/db/db';
import * as ExcelJS from 'exceljs';
import { filterColumns } from '@/lib/filter-columns';
import {
regEvalCriteriaColumnsConfig,
} from '@/config/regEvalCriteriaColumnsConfig';
import {
REG_EVAL_CRITERIA_CATEGORY2_ENUM,
REG_EVAL_CRITERIA_CATEGORY_ENUM,
REG_EVAL_CRITERIA_ITEM_ENUM,
regEvalCriteriaView,
type NewRegEvalCriteria,
type NewRegEvalCriteriaDetails,
type RegEvalCriteria,
type RegEvalCriteriaDetails,
type RegEvalCriteriaView,
} from '@/db/schema';
import { type GetRegEvalCriteriaSchema } from './validations';
// ----------------------------------------------------------------------------------------------------
/* TYPES */
interface ImportResult {
errorFile: File | null,
errorMessage: string | null,
successMessage?: string,
}
type ExcelRowData = {
criteriaData: NewRegEvalCriteria,
detailList: (NewRegEvalCriteriaDetails & { rowIndex: number, toDelete: boolean })[],
}
// ----------------------------------------------------------------------------------------------------
/* CONSTANTS */
const HEADER_ROW_INDEX = 2;
const DATA_START_ROW_INDEX = 3;
const EXCEL_HEADERS = [
'Category',
'Score Category',
'Item',
'Classification',
'Range',
'Detail',
'Remarks',
'ID',
'Criteria ID',
'Order Index',
'Equipment-Shipbuilding Score',
'Equipment-Marine Engineering Score',
'Bulk-Shipbuilding Score',
'Bulk-Marine Engineering Score',
];
// ----------------------------------------------------------------------------------------------------
/* FUNCTION FOR GETTING CRITERIA */
async function getRegEvalCriteria(input: GetRegEvalCriteriaSchema) {
try {
const offset = (input.page - 1) * input.perPage;
const advancedWhere = filterColumns({
table: regEvalCriteriaView,
filters: input.filters,
joinOperator: input.joinOperator,
});
// Filtering
let globalWhere;
if (input.search) {
const s = `%${input.search}%`;
globalWhere = or(
ilike(regEvalCriteriaView.category, s),
ilike(regEvalCriteriaView.item, s),
ilike(regEvalCriteriaView.classification, s),
);
}
const finalWhere = and(advancedWhere, globalWhere);
// Sorting
const orderBy = input.sort.length > 0
? input.sort.map((item) => {
return item.desc
? desc(regEvalCriteriaView[item.id])
: asc(regEvalCriteriaView[item.id]);
})
: [asc(regEvalCriteriaView.id)];
// Getting Data
const { data, total } = await db.transaction(async (tx) => {
const data = await selectRegEvalCriteria(tx, {
where: finalWhere,
orderBy,
offset,
limit: input.perPage,
});
const total = await countRegEvalCriteria(tx, finalWhere);
return { data, total };
});
const pageCount = Math.ceil(total / input.perPage);
return { data, pageCount };
} catch (err) {
console.error('Error in Getting Regular Evaluation Criteria: ', err);
return { data: [], pageCount: 0 };
}
}
/* FUNCTION FOR GETTING CRITERIA WITH DETAILS */
async function getRegEvalCriteriaWithDetails(id: number) {
try {
return await db.transaction(async (tx) => {
return await selectRegEvalCriteriaWithDetails(tx, id);
});
} catch (err) {
console.error('Error in Getting Regular Evaluation Criteria with Details: ', err);
return null;
}
}
// ----------------------------------------------------------------------------------------------------
/* FUNCTION FOR CREATING CRITERIA WITH DETAILS */
async function createRegEvalCriteriaWithDetails(
criteriaData: NewRegEvalCriteria,
detailList: Omit<NewRegEvalCriteriaDetails, 'criteriaId'>[],
) {
try {
return await db.transaction(async (tx) => {
const criteria = await insertRegEvalCriteria(tx, criteriaData);
const criteriaId = criteria.id;
const newDetailList = detailList.map((detailItem, index) => ({
...detailItem,
criteriaId,
orderIndex: detailItem.orderIndex || index,
}));
const criteriaDetails: NewRegEvalCriteriaDetails[] = [];
for (let idx = 0; idx < newDetailList.length; idx += 1) {
criteriaDetails.push(await insertRegEvalCriteriaDetails(tx, newDetailList[idx]));
}
return { ...criteria, criteriaDetails };
});
} catch (error) {
console.error('Error in Creating New Regular Evaluation Criteria with Details: ', error);
throw new Error('Failed to Create New Regular Evaluation Criteria with Details');
}
}
// ----------------------------------------------------------------------------------------------------
/* FUNCTION FOR MODIFYING CRITERIA WITH DETAILS */
async function modifyRegEvalCriteriaWithDetails(
id: number,
criteriaData: Partial<RegEvalCriteria>,
detailList: Partial<RegEvalCriteriaDetails>[],
) {
try {
return await db.transaction(async (tx) => {
const modifiedCriteria = await updateRegEvalCriteria(tx, id, criteriaData);
const originCriteria = await getRegEvalCriteriaWithDetails(id);
const originCriteriaDetails = originCriteria?.criteriaDetails || [];
const detailIdList = detailList
.filter(item => item.id !== undefined)
.map(item => item.id);
const toDeleteIdList = originCriteriaDetails.filter(
(item) => !detailIdList.includes(item.id),
);
for (const item of toDeleteIdList) {
await deleteRegEvalCriteriaDetails(tx, item.id);
}
const criteriaDetails = [];
for (let idx = 0; idx < detailList.length; idx += 1) {
const detailItem = detailList[idx];
const isUpdate = detailItem.id;
const isInsert = !detailItem.id && detailItem.detail;
if (isUpdate) {
const updatedDetail = await updateRegEvalCriteriaDetails(tx, detailItem.id!, detailItem);
criteriaDetails.push(updatedDetail);
} else if (isInsert) {
const newDetailItem = {
...detailItem,
criteriaId: id,
detail: detailItem.detail!,
orderIndex: detailItem.orderIndex || idx,
};
const insertedDetail = await insertRegEvalCriteriaDetails(tx, newDetailItem);
criteriaDetails.push(insertedDetail);
}
}
return { ...modifiedCriteria, criteriaDetails };
});
} catch (error) {
console.error('Error in Modifying Regular Evaluation Criteria with Details: ', error);
throw new Error('Failed to Modify Regular Evaluation Criteria with Details');
}
}
// ----------------------------------------------------------------------------------------------------
/* FUNCTION FOR REMOVING CRITERIA WITH DETAILS */
async function removeRegEvalCriteria(id: number) {
try {
return await db.transaction(async (tx) => {
return await deleteRegEvalCriteria(tx, id);
});
} catch (err) {
console.error('Error in Removing Regular Evaluation Criteria with Details: ', err);
throw new Error('Failed to Remove Regular Evaluation Criteria with Details');
}
}
/* FUNCTION FOR REMOVING CRITERIA DETAILS */
async function removeRegEvalCriteriaDetails(id: number) {
try {
return await db.transaction(async (tx) => {
return await deleteRegEvalCriteriaDetails(tx, id);
});
} catch (err) {
console.error('Error in Removing Regular Evaluation Criteria Details: ', err);
throw new Error('Failed to Remove Regular Evaluation Criteria Details');
}
}
// ----------------------------------------------------------------------------------------------------
/* FUNCTION FOR IMPORTING EXCEL FILES */
async function importRegEvalCriteriaExcel(file: File): Promise<ImportResult> {
try {
const buffer = await file.arrayBuffer();
const workbook = new ExcelJS.Workbook();
try {
await workbook.xlsx.load(buffer);
} catch {
throw new Error('유효한 Excel 파일이 아닙니다. 파일을 다시 확인해주세요.');
}
const worksheet = workbook.worksheets[0];
if (!worksheet) {
throw new Error('Excel 파일에 워크시트가 없습니다.');
};
if (worksheet.rowCount === 0) {
throw new Error('워크시트에 데이터가 없습니다.');
}
const headerRow = worksheet.getRow(HEADER_ROW_INDEX);
if (!headerRow || headerRow.cellCount < EXCEL_HEADERS.length || !Array.isArray(headerRow.values)) {
throw new Error('Excel 파일의 워크시트에서 유효한 헤더 행을 찾지 못했습니다.');
}
const headerValues = headerRow?.values?.slice(1);
const isHeaderMatched = EXCEL_HEADERS.every((header, idx) => {
const actualHeader = (headerValues[idx] ?? '').toString().trim();
return actualHeader === header;
});
if (!isHeaderMatched) {
throw new Error('Excel 파일의 워크시트에서 유효한 헤더 행을 찾지 못했습니다.');
}
const columnIndexMap = new Map<string, number>();
headerRow.eachCell((cell, colIndex) => {
if (typeof cell.value === 'string') {
columnIndexMap.set(cell.value.trim(), colIndex);
}
});
const columnToFieldMap = new Map<number, keyof RegEvalCriteriaView>();
regEvalCriteriaColumnsConfig.forEach((cfg) => {
if (!cfg.excelHeader) {
return;
}
const colIndex = columnIndexMap.get(cfg.excelHeader.trim());
if (colIndex !== undefined) {
columnToFieldMap.set(colIndex, cfg.id);
}
});
const errorRows: { rowIndex: number; message: string }[] = [];
const rowDataList: ExcelRowData[] = [];
const criteriaMap = new Map<string, {
criteria: NewRegEvalCriteria,
criteriaDetails: (NewRegEvalCriteriaDetails & { rowIndex: number, toDelete: boolean })[],
}>();
for (let r = DATA_START_ROW_INDEX; r <= worksheet.rowCount; r += 1) {
const row = worksheet.getRow(r);
if (!row) {
continue;
}
const lastCellValue = row.getCell(row.cellCount).value;
const isDelete = typeof lastCellValue === 'string' && lastCellValue.toLowerCase() === 'd';
const rowFields = {} as Record<string, any>;
columnToFieldMap.forEach((fieldId, colIdx) => {
const cellValue = row.getCell(colIdx).value;
rowFields[fieldId] = cellValue ?? null;
});
const requiredFields = ['category', 'category2', 'item', 'classification', 'detail'];
for (const field of requiredFields) {
if (!rowFields[field]) {
errorRows.push({ rowIndex: r, message: `필수 필드 누락: ${field}` });
}
}
if (!REG_EVAL_CRITERIA_CATEGORY_ENUM.includes(rowFields.category)) {
errorRows.push({ rowIndex: r, message: `유효하지 않은 Category 값: ${rowFields.category}` });
}
if (!REG_EVAL_CRITERIA_CATEGORY2_ENUM.includes(rowFields.category2)) {
errorRows.push({ rowIndex: r, message: `유효하지 않은 Score Category 값: ${rowFields.category2}` });
}
if (!REG_EVAL_CRITERIA_ITEM_ENUM.includes(rowFields.item)) {
errorRows.push({ rowIndex: r, message: `유효하지 않은 Item 값: ${rowFields.item}` });
}
const criteriaKey = [
rowFields.criteriaId ?? '',
rowFields.category,
rowFields.category2,
rowFields.item,
rowFields.classification,
rowFields.range ?? '',
].join('|');
const criteriaDetail: NewRegEvalCriteriaDetails = {
id: rowFields.id,
criteriaId: rowFields.criteriaId,
detail: rowFields.detail,
orderIndex: rowFields.orderIndex,
scoreEquipShip: rowFields.scoreEquipShip,
scoreEquipMarine: rowFields.scoreEquipMarine,
scoreBulkShip: rowFields.scoreBulkShip,
scoreBulkMarine: rowFields.scoreBulkMarine,
};
if (!criteriaMap.has(criteriaKey)) {
const criteria: NewRegEvalCriteria = {
id: rowFields.criteriaId,
category: rowFields.category,
category2: rowFields.category2,
item: rowFields.item,
classification: rowFields.classification,
range: rowFields.range,
remarks: rowFields.remarks,
};
criteriaMap.set(criteriaKey, {
criteria,
criteriaDetails: [{
...criteriaDetail,
rowIndex: r,
toDelete: isDelete,
}],
});
} else {
const existing = criteriaMap.get(criteriaKey)!;
existing.criteriaDetails.push({
...criteriaDetail,
rowIndex: r,
toDelete: isDelete,
});
}
}
criteriaMap.forEach(({ criteria, criteriaDetails }) => {
rowDataList.push({
criteriaData: criteria,
detailList: criteriaDetails,
});
});
// console.log('원본 데이터: ');
// console.dir(rowDataList, { depth: null });
if (errorRows.length > 0) {
const workbook = new ExcelJS.Workbook();
const sheet = workbook.addWorksheet('Error List');
sheet.columns = [
{ header: 'Row Index', key: 'rowIndex', width: 10 },
{ header: 'Error Message', key: 'message', width: 50 },
];
errorRows.forEach((errorRow) => {
sheet.addRow({
rowIndex: errorRow.rowIndex,
message: errorRow.message,
});
});
const buffer = await workbook.xlsx.writeBuffer();
const errorFile = new File(
[buffer],
'error_rows.xlsx',
{
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
lastModified: Date.now(),
}
);
return {
errorFile,
errorMessage: '입력된 데이터 중에서 잘못된 데이터가 있어 오류 파일을 생성했습니다.',
};
}
const existingData = await db.transaction(async (tx) => {
return await selectRegEvalCriteria(tx, { limit: Number.MAX_SAFE_INTEGER });
});
const existingIds = existingData.map((row) => row.criteriaId!)
const existingIdSet = new Set<number>(existingIds);
// console.log('기존 데이터: ');
// console.dir(existingData, { depth: null });
const createList: {
criteriaData: NewRegEvalCriteria,
detailList: Omit<NewRegEvalCriteriaDetails, 'criteriaId'>[],
}[] = [];
const updateList: {
id: number,
criteriaData: Partial<RegEvalCriteria>,
detailList: Partial<RegEvalCriteriaDetails>[],
}[] = [];
const deleteIdList: number[] = [];
for (const { criteriaData, detailList } of rowDataList) {
const { id: criteriaId } = criteriaData;
const allMarkedForDelete = detailList.every(d => d.toDelete);
if (allMarkedForDelete) {
if (criteriaId && existingIdSet.has(criteriaId)) {
deleteIdList.push(criteriaId);
}
continue;
}
if (!criteriaId) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { id, ...newCriteriaData } = criteriaData;
const newDetailList = detailList.map(d => {
if (d.id != null) {
throw new Error(`새로운 기준 항목에 ID가 존재합니다: ${d.rowIndex}행`);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { rowIndex, toDelete, id, criteriaId, ...rest } = d;
return rest;
});
createList.push({
criteriaData: newCriteriaData,
detailList: newDetailList,
});
} else if (existingIdSet.has(criteriaId)) {
const matchedExistingDetails = existingData.filter(d => d.criteriaId === criteriaId);
const hasDeletedDetail = detailList.some(d => d.toDelete === true);
const hasNewDetail = detailList.some(d => d.id == null);
const matchedExistingCriteria = matchedExistingDetails[0];
const criteriaChanged = (
matchedExistingCriteria.category !== criteriaData.category ||
matchedExistingCriteria.category2 !== criteriaData.category2 ||
matchedExistingCriteria.item !== criteriaData.item ||
matchedExistingCriteria.classification !== criteriaData.classification ||
matchedExistingCriteria.range !== criteriaData.range ||
matchedExistingCriteria.remarks !== criteriaData.remarks
);
const detailChanged = detailList.some(d => {
if (!d.id) {
return false;
}
const matched = matchedExistingDetails.find(e => e.id === d.id);
if (!matched) {
throw Error(`존재하지 않는 잘못된 ID(${d.id})가 있습니다.`);
}
return (
matched.detail !== d.detail ||
matched.orderIndex !== d.orderIndex ||
matched.scoreEquipShip !== d.scoreEquipShip ||
matched.scoreEquipMarine !== d.scoreEquipMarine ||
matched.scoreBulkShip !== d.scoreBulkShip ||
matched.scoreBulkMarine !== d.scoreBulkMarine
);
});
if (hasDeletedDetail || hasNewDetail || criteriaChanged || detailChanged) {
const updatedDetails = detailList
.filter(d => !d.toDelete)
.map(d => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { rowIndex, toDelete, ...rest } = d;
const cleaned = Object.fromEntries(
Object.entries(rest).map(([key, value]) => [
key,
value === '' ? null : value,
])
);
return cleaned;
});
updateList.push({
id: criteriaId,
criteriaData,
detailList: updatedDetails,
});
}
} else {
throw Error(`존재하지 않는 잘못된 Criteria ID(${criteriaId})가 있습니다.`);
}
}
console.log('생성: ');
console.dir(createList, { depth: null });
console.log('업뎃: ');
console.dir(updateList, { depth: null });
console.log('삭제: ', deleteIdList);
if (createList.length > 0) {
for (const { criteriaData, detailList } of createList) {
await createRegEvalCriteriaWithDetails(criteriaData, detailList);
}
}
if (updateList.length > 0) {
for (const { id, criteriaData, detailList } of updateList) {
await modifyRegEvalCriteriaWithDetails(id, criteriaData, detailList);
}
}
if (deleteIdList.length > 0) {
for (const id of deleteIdList) {
await removeRegEvalCriteria(id);
}
}
const msg: string[] = [];
if (createList.length > 0) {
msg.push(`${createList.length}건 생성`);
}
if (updateList.length > 0) {
msg.push(`${updateList.length}건 수정`);
}
if (deleteIdList.length > 0) {
msg.push(`${deleteIdList.length}건 삭제`);
}
const successMessage = msg.length > 0
? '기준 항목이 정상적으로 ' + msg.join(', ') + '되었습니다.'
: '변경사항이 존재하지 않습니다.';
return {
errorFile: null,
errorMessage: null,
successMessage,
};
} catch (error) {
let message = 'Excel 파일을 읽는 중 오류가 발생했습니다.';
if (error instanceof Error) {
message = error.message;
}
return {
errorFile: null,
errorMessage: message,
};
}
}
// ----------------------------------------------------------------------------------------------------
/* EXPORT */
export {
createRegEvalCriteriaWithDetails,
modifyRegEvalCriteriaWithDetails,
getRegEvalCriteria,
getRegEvalCriteriaWithDetails,
importRegEvalCriteriaExcel,
removeRegEvalCriteria,
removeRegEvalCriteriaDetails,
};
|