summaryrefslogtreecommitdiff
path: root/lib/material-groups/services.ts
blob: be683077f2309f4ccfabac9dcaa5ed26f256235b (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
'use server'

import { and, asc, desc, ilike, or, sql, eq } from 'drizzle-orm';
import db from '@/db/db';
import { filterColumns } from "@/lib/filter-columns";
import { materialSearchView } from "@/db/schema/items";

// 자재그룹 뷰의 컬럼 타입 정의
type MaterialGroupColumn = keyof typeof materialSearchView.$inferSelect;

export interface GetMaterialGroupsInput {
  page: number;
  perPage: number;
  search?: string;
  sort: Array<{
    id: MaterialGroupColumn;
    desc: boolean;
  }>;
  filters?: any[];
  joinOperator: 'and' | 'or';
}

/**
 * 자재그룹 목록을 조회합니다.
 * materialSearchView를 사용하여 MATKL(자재그룹코드)와 ATWTB(자재그룹 설명)의 고유한 조합을 조회
 */
export async function getMaterialGroups(input: GetMaterialGroupsInput) {
  const safePerPage = Math.min(input.perPage, 100);
  
  try {
    const offset = (input.page - 1) * safePerPage;
    
    // 고급 필터링
    const advancedWhere = filterColumns({
      table: materialSearchView,
      filters: (input.filters || []) as any,
      joinOperator: input.joinOperator,
    });

    // 전역 검색 - 주요 컬럼들에 대해 검색
    let globalWhere;
    if (input.search) {
      const s = `%${input.search}%`;
      globalWhere = or(
        ilike(materialSearchView.materialGroupCode, s),      // 자재그룹코드
        ilike(materialSearchView.materialGroupDesc, s),     // 자재그룹명
      );
    }

    const finalWhere = and(advancedWhere, globalWhere);

    // 정렬 처리 - 타입 안전하게 처리
    const orderBy = input.sort.length > 0
      ? input.sort.map((item) => {
          const column = materialSearchView[item.id];
          return item.desc ? desc(column) : asc(column);
        })
      : [asc(materialSearchView.materialGroupCode)];

    // 데이터 조회
    const { data, total } = await db.transaction(async (tx) => {
      const data = await tx
        .select({
          materialGroupCode: materialSearchView.materialGroupCode,
          materialGroupDesc: materialSearchView.materialGroupDesc,
        })
        .from(materialSearchView)
        .where(finalWhere)
        .orderBy(...orderBy)
        .offset(offset)
        .limit(safePerPage);

      const totalResult = await tx
        .select({
          count: sql<number>`count(*)`
        })
        .from(materialSearchView)
        .where(finalWhere);
      
      const total = Number(totalResult[0]?.count) || 0;
      return { data, total };
    });

    const pageCount = Math.ceil(total / safePerPage);
    return { data, pageCount };
  } catch (err) {
    console.error('Error in getMaterialGroups:', err);
    return { data: [], pageCount: 0 };
  }
}

/**
 * 무한 스크롤을 위한 자재그룹 조회 (페이지네이션 없음)
 */
export interface GetMaterialGroupsInfiniteInput extends Omit<GetMaterialGroupsInput, 'page' | 'perPage'> {
  limit?: number; // 무한 스크롤용 추가 옵션
}

export async function getMaterialGroupsInfinite(input: GetMaterialGroupsInfiniteInput) {
  try {
    // 고급 필터링
    const advancedWhere = filterColumns({
      table: materialSearchView,
      filters: (input.filters || []) as any,
      joinOperator: input.joinOperator || "and",
    });

    // 전역 검색
    let globalWhere;
    if (input.search) {
      const s = `%${input.search}%`;
      globalWhere = or(
        ilike(materialSearchView.materialGroupCode, s),
        ilike(materialSearchView.materialGroupDesc, s),
      );
    }

    const finalWhere = and(advancedWhere, globalWhere);

    // 정렬 처리 - 타입 안전하게 처리
    const orderBy = input.sort.length > 0
      ? input.sort.map((item) => {
          const column = materialSearchView[item.id];
          return item.desc ? desc(column) : asc(column);
        })
      : [asc(materialSearchView.materialGroupCode)];

    // 전체 데이터 조회 (클라이언트에서 가상화 처리)
    const data = await db
      .select({
        materialGroupCode: materialSearchView.materialGroupCode,
        materialGroupDesc: materialSearchView.materialGroupDesc,
      })
      .from(materialSearchView)
      .where(finalWhere)
      .orderBy(...orderBy);

    return { data };
  } catch (err) {
    console.error('Error in getMaterialGroupsInfinite:', err);
    return { data: [] };
  }
}

/**
 * 특정 자재그룹 상세 정보 조회
 */
export async function getMaterialGroupDetail(materialGroupCode: string) {
  try {
    const materialGroup = await db
      .select()
      .from(materialSearchView)
      .where(eq(materialSearchView.materialGroupCode, materialGroupCode))
      .limit(1);

    return materialGroup.length > 0 ? materialGroup[0] : null;
  } catch (err) {
    console.error('Error in getMaterialGroupDetail:', err);
    return null;
  }
}