summaryrefslogtreecommitdiff
path: root/lib/rfq-last/service.ts
blob: f2710f02934d32f53af4deb563069fd8a43e7291 (plain)
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
// lib/rfq/service.ts
'use server'

import { unstable_noStore } from "next/cache";
import db from "@/db/db";
import { rfqsLastView } from "@/db/schema";
import { and, desc, asc, ilike, or, eq, SQL, count, gte, lte,isNotNull,ne } from "drizzle-orm";
import { filterColumns } from "@/lib/filter-columns";
import { GetRfqsSchema } from "./validations";

export async function getRfqs(input: GetRfqsSchema) {
  unstable_noStore();

  try {
    const offset = (input.page - 1) * input.perPage;

    // 1. RFQ 타입별 필터링
    let typeFilter: SQL<unknown> | undefined = undefined;
    if (input.rfqCategory) {
      switch (input.rfqCategory) {
        case "general":
          // 일반견적: rfqType이 있는 경우
          typeFilter = and(
            isNotNull(rfqsLastView.rfqType),
            ne(rfqsLastView.rfqType, '')
          );
          break;
        case "itb":
          // ITB: projectCompany가 있는 경우
          typeFilter = and(
            isNotNull(rfqsLastView.projectCompany),
            ne(rfqsLastView.projectCompany, '')
          );
          break;
        case "rfq":
          // RFQ: prNumber가 있는 경우  
          typeFilter = and(
            isNotNull(rfqsLastView.prNumber),
            ne(rfqsLastView.prNumber, '')
          );
          break;
      }
    }

    // 2. 고급 필터 처리
    let advancedWhere: SQL<unknown> | undefined = undefined;
    
    if (input.filters && Array.isArray(input.filters) && input.filters.length > 0) {
      console.log("필터 적용:", input.filters.map(f => `${f.id} ${f.operator} ${f.value}`));
      
      try {
        advancedWhere = filterColumns({
          table: rfqsLastView,
          filters: input.filters,
          joinOperator: input.joinOperator || 'and',
        });
        
        console.log("필터 조건 생성 완료");
      } catch (error) {
        console.error("필터 조건 생성 오류:", error);
        advancedWhere = undefined;
      }
    }

    // 3. 글로벌 검색 조건
    let globalWhere: SQL<unknown> | undefined = undefined;
    if (input.search) {
      const s = `%${input.search}%`;

      const searchConditions: SQL<unknown>[] = [
        ilike(rfqsLastView.rfqCode, s),
        ilike(rfqsLastView.itemCode, s),
        ilike(rfqsLastView.itemName, s),
        ilike(rfqsLastView.packageNo, s),
        ilike(rfqsLastView.packageName, s),
        ilike(rfqsLastView.picName, s),
        ilike(rfqsLastView.engPicName, s),
        ilike(rfqsLastView.projectCode, s),
        ilike(rfqsLastView.projectName, s),
        ilike(rfqsLastView.rfqTitle, s),
        ilike(rfqsLastView.prNumber, s),
      ].filter(Boolean);

      if (searchConditions.length > 0) {
        globalWhere = or(...searchConditions);
      }
    }

    // 4. 최종 WHERE 조건 결합
    const whereConditions: SQL<unknown>[] = [];
    if (typeFilter) whereConditions.push(typeFilter);
    if (advancedWhere) whereConditions.push(advancedWhere);
    if (globalWhere) whereConditions.push(globalWhere);

    const finalWhere = whereConditions.length > 0 ? and(...whereConditions) : undefined;

    // 5. 전체 데이터 수 조회
    const totalResult = await db
      .select({ count: count() })
      .from(rfqsLastView)
      .where(finalWhere);

    const total = totalResult[0]?.count || 0;

    if (total === 0) {
      return { data: [], pageCount: 0, total: 0 };
    }

    console.log("총 데이터 수:", total);

    // 6. 정렬 및 페이징 처리
    const orderByColumns = input.sort.map((sort) => {
      const column = sort.id as keyof typeof rfqsLastView.$inferSelect;
      return sort.desc 
        ? desc(rfqsLastView[column]) 
        : asc(rfqsLastView[column]);
    });

    if (orderByColumns.length === 0) {
      orderByColumns.push(desc(rfqsLastView.createdAt));
    }

    const rfqData = await db
      .select()
      .from(rfqsLastView)
      .where(finalWhere)
      .orderBy(...orderByColumns)
      .limit(input.perPage)
      .offset(offset);

    const pageCount = Math.ceil(total / input.perPage);

    console.log("반환 데이터 수:", rfqData.length);

    return { data: rfqData, pageCount, total };
  } catch (err) {
    console.error("getRfqs 오류:", err);
    return { data: [], pageCount: 0, total: 0 };
  }
}