summaryrefslogtreecommitdiff
path: root/lib/integration/service.ts
blob: ad644ca4feedc62b2306714cd7a188d6b76cd078 (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
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
"use server";

import db from "@/db/db";
import { integrations } from "@/db/schema/integration";
import { eq } from "drizzle-orm";
import { GetIntegrationsSchema } from "./validations";
import { filterColumns } from "@/lib/filter-columns";
import { asc, desc, ilike, and, or, count } from "drizzle-orm";

/* -----------------------------------------------------
   1) 통합 목록 조회
----------------------------------------------------- */
export async function getIntegrations(input: GetIntegrationsSchema) {
  try {
    const offset = (input.page - 1) * input.perPage;

    // 1. where 절
    let advancedWhere;
    try {
      advancedWhere = filterColumns({
        table: integrations,
        filters: input.filters,
        joinOperator: input.joinOperator,
      });
    } catch (whereErr) {
      console.error("Error building advanced where:", whereErr);
      advancedWhere = undefined;
    }

    let globalWhere;
    if (input.search) {
      try {
        const s = `%${input.search}%`;
        globalWhere = or(
          ilike(integrations.code, s),
          ilike(integrations.name, s),
          ilike(integrations.sourceSystem, s),
          ilike(integrations.targetSystem, s),
          ilike(integrations.description, s)
        );
      } catch (searchErr) {
        console.error("Error building search where:", searchErr);
        globalWhere = undefined;
      }
    }

    // 2. where 결합
    let finalWhere;
    const whereArr = [advancedWhere, globalWhere].filter(Boolean);
    if (whereArr.length === 2) {
      finalWhere = and(...whereArr);
    } else if (whereArr.length === 1) {
      finalWhere = whereArr[0];
    } else {
      finalWhere = undefined;
    }

    // 3. order by
    let orderBy = [asc(integrations.createdAt)];
    try {
      if (input.sort.length > 0) {
        const sortItems = input.sort
          .map((item) => {
            if (!item || !item.id || typeof item.id !== "string") return null;
            
            // 기본 정렬 컬럼들만 허용
            switch (item.id) {
              case "id":
                return item.desc ? desc(integrations.id) : asc(integrations.id);
              case "code":
                return item.desc ? desc(integrations.code) : asc(integrations.code);
              case "name":
                return item.desc ? desc(integrations.name) : asc(integrations.name);
              case "type":
                return item.desc ? desc(integrations.type) : asc(integrations.type);
              case "status":
                return item.desc ? desc(integrations.status) : asc(integrations.status);
              case "sourceSystem":
                return item.desc ? desc(integrations.sourceSystem) : asc(integrations.sourceSystem);
              case "targetSystem":
                return item.desc ? desc(integrations.targetSystem) : asc(integrations.targetSystem);
              case "createdAt":
                return item.desc ? desc(integrations.createdAt) : asc(integrations.createdAt);
              case "updatedAt":
                return item.desc ? desc(integrations.updatedAt) : asc(integrations.updatedAt);
              default:
                return null;
            }
          })
          .filter((v): v is Exclude<typeof v, null> => v !== null);
        
        if (sortItems.length > 0) {
          orderBy = sortItems;
        }
      }
    } catch (orderErr) {
      console.error("Error building order by:", orderErr);
    }

    // 4. 쿼리 실행
    let data = [];
    let total = 0;

    try {
      const queryBuilder = db.select().from(integrations);

      if (finalWhere !== undefined) {
        queryBuilder.where(finalWhere);
      }

      if (orderBy && orderBy.length > 0) {
        queryBuilder.orderBy(...orderBy);
      }
      if (typeof offset === "number" && !isNaN(offset)) {
        queryBuilder.offset(offset);
      }
      if (typeof input.perPage === "number" && !isNaN(input.perPage)) {
        queryBuilder.limit(input.perPage);
      }

      data = await queryBuilder;

      const countBuilder = db
        .select({ count: count() })
        .from(integrations);

      if (finalWhere !== undefined) {
        countBuilder.where(finalWhere);
      }

      const countResult = await countBuilder;
      total = countResult[0]?.count || 0;
    } catch (queryErr) {
      console.error("Query execution failed:", queryErr);
      throw queryErr;
    }

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

    return { data, pageCount };
  } catch (err) {
    console.error("Error in getIntegrations:", err);
    if (err instanceof Error) {
      console.error("Error message:", err.message);
      console.error("Error stack:", err.stack);
    }
    return { data: [], pageCount: 0 };
  }
}

/* -----------------------------------------------------
   2) 통합 생성
----------------------------------------------------- */
export async function createIntegration(data: Omit<typeof integrations.$inferInsert, "id" | "createdAt" | "updatedAt">) {
  try {
    const [created] = await db.insert(integrations).values({
      ...data,
      createdAt: new Date(),
      updatedAt: new Date(),
    }).returning();
    return { data: created };
  } catch (err) {
    console.error("Error creating integration:", err);
    return { error: "생성 중 오류가 발생했습니다." };
  }
}

/* -----------------------------------------------------
   3) 통합 수정
----------------------------------------------------- */
export async function updateIntegration(id: number, data: Partial<typeof integrations.$inferInsert>) {
  try {
    const [updated] = await db
      .update(integrations)
      .set({
        ...data,
        updatedAt: new Date(),
      })
      .where(eq(integrations.id, id))
      .returning();
    return { data: updated };  
  } catch (err) {
    console.error("Error updating integration:", err);
    return { error: "수정 중 오류가 발생했습니다." };
  }
}

/* -----------------------------------------------------
   4) 통합 삭제
----------------------------------------------------- */
export async function deleteIntegration(id: number) {
  try {
    await db.delete(integrations).where(eq(integrations.id, id));
    return { success: true };
  } catch (err) {
    console.error("Error deleting integration:", err);
    return { error: "삭제 중 오류가 발생했습니다." };
  }
}

// 통합 조회 (단일)
export async function getIntegration(id: number): Promise<ServiceResponse<Integration>> {
  try {
    const result = await db.select().from(integrations).where(eq(integrations.id, id)).limit(1);
    
    if (result.length === 0) {
      return { error: "통합을 찾을 수 없습니다." };
    }

    return { data: result[0] };
  } catch (error) {
    console.error("통합 조회 오류:", error);
    return { error: "통합 조회에 실패했습니다." };
  }
}

// 기존 함수들도 유지 (하위 호환성)
export async function getIntegrationList() {
  try {
    const data = await db.select().from(integrations);
    return data;
  } catch (error) {
    console.error("통합 목록 조회 실패:", error);
    return [];
  }
}