summaryrefslogtreecommitdiff
path: root/components/common/vendor/vendor-service.ts
blob: bc53be3e79729042305cd847fa5c5d93f6f436b3 (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
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
"use server"

import db from '@/db/db'
import { vendors } from '@/db/schema/vendors'
import { eq, or, ilike, and, asc, desc } from 'drizzle-orm'

// 벤더 타입 정의
export interface VendorSearchItem {
  id: number
  vendorName: string
  vendorCode: string | null
  taxId: string | null // 사업자번호
  status: string
  displayText: string // vendorName + vendorCode로 구성된 표시용 텍스트
  country?: string | null // 국가 정보 (선택적)
}

// 벤더 검색 옵션
export interface VendorSearchOptions {
  searchTerm?: string
  statusFilter?: string // 특정 상태로 필터링
  limit?: number
  offset?: number
  sortBy?: 'vendorName' | 'vendorCode' | 'status'
  sortOrder?: 'asc' | 'desc'
  includeCountry?: boolean // 국가 정보 포함 여부
}

// 페이지네이션 정보
export interface VendorPagination {
  page: number
  perPage: number
  total: number
  pageCount: number
  hasNextPage: boolean
  hasPrevPage: boolean
}

/**
 * 벤더 검색 (페이지네이션 지원)
 * 벤더명, 벤더코드로 검색 가능
 */
export async function searchVendorsForSelector(
  searchTerm: string = "",
  page: number = 1,
  perPage: number = 10,
  options: Omit<VendorSearchOptions, 'searchTerm' | 'limit' | 'offset'> = {}
): Promise<{
  success: boolean
  data: VendorSearchItem[]
  pagination: VendorPagination
  error?: string
}> {
  try {
    const { statusFilter, sortBy = 'vendorName', sortOrder = 'asc', includeCountry = false } = options
    const offset = (page - 1) * perPage

    // WHERE 조건 구성
    let whereClause
    
    // 검색어 조건
    const searchCondition = searchTerm && searchTerm.trim() 
      ? or(
          ilike(vendors.vendorName, `%${searchTerm.trim()}%`),
          ilike(vendors.vendorCode, `%${searchTerm.trim()}%`)
        )
      : undefined

    // 상태 필터 조건 - 타입 안전하게 처리
    const statusCondition = statusFilter 
      ? eq(vendors.status, statusFilter as string)
      : undefined

    // 조건들을 결합
    if (searchCondition && statusCondition) {
      whereClause = and(searchCondition, statusCondition)
    } else if (searchCondition) {
      whereClause = searchCondition
    } else if (statusCondition) {
      whereClause = statusCondition
    }

    // 정렬 옵션
    const orderBy = sortOrder === 'desc' 
      ? desc(vendors[sortBy]) 
      : asc(vendors[sortBy])

    // 전체 개수 조회
    let totalCountQuery = db
      .select({ count: vendors.id })
      .from(vendors)

    if (whereClause) {
      totalCountQuery = totalCountQuery.where(whereClause)
    }

    const totalCountResult = await totalCountQuery
    const total = totalCountResult.length

    // 데이터 조회 - includeCountry에 따라 필드 선택
    const selectFields = includeCountry
      ? {
          id: vendors.id,
          vendorName: vendors.vendorName,
          vendorCode: vendors.vendorCode,
          taxId: vendors.taxId,
          status: vendors.status,
          country: vendors.country,
        }
      : {
          id: vendors.id,
          vendorName: vendors.vendorName,
          vendorCode: vendors.vendorCode,
          taxId: vendors.taxId,
          status: vendors.status,
        }

    let dataQuery = db
      .select(selectFields)
      .from(vendors)

    if (whereClause) {
      dataQuery = dataQuery.where(whereClause)
    }

    const result = await dataQuery
      .orderBy(orderBy)
      .limit(perPage)
      .offset(offset)

    // displayText 추가
    const vendorItems: VendorSearchItem[] = result.map(vendor => ({
      ...vendor,
      displayText: vendor.vendorCode 
        ? `${vendor.vendorName} (${vendor.vendorCode})`
        : vendor.vendorName,
      ...(includeCountry && { country: (vendor as any).country })
    }))

    // 페이지네이션 정보 계산
    const pageCount = Math.ceil(total / perPage)
    const pagination: VendorPagination = {
      page,
      perPage,
      total,
      pageCount,
      hasNextPage: page < pageCount,
      hasPrevPage: page > 1,
    }

    return {
      success: true,
      data: vendorItems,
      pagination
    }
  } catch (error) {
    console.error('Error searching vendors:', error)
    return {
      success: false,
      data: [],
      pagination: {
        page: 1,
        perPage: 10,
        total: 0,
        pageCount: 0,
        hasNextPage: false,
        hasPrevPage: false,
      },
      error: '벤더 검색 중 오류가 발생했습니다.'
    }
  }
}

/**
 * 모든 벤더 조회 (필터링 없음)
 */
export async function getAllVendors(): Promise<{
  success: boolean
  data: VendorSearchItem[]
  error?: string
}> {
  try {
    const result = await db
      .select({
        id: vendors.id,
        vendorName: vendors.vendorName,
        vendorCode: vendors.vendorCode,
        taxId: vendors.taxId,
        status: vendors.status,
      })
      .from(vendors)
      .orderBy(asc(vendors.vendorName))

    const vendorItems: VendorSearchItem[] = result.map(vendor => ({
      ...vendor,
      displayText: vendor.vendorCode 
        ? `${vendor.vendorName} (${vendor.vendorCode})`
        : vendor.vendorName
    }))

    return {
      success: true,
      data: vendorItems
    }
  } catch (error) {
    console.error('Error fetching all vendors:', error)
    return {
      success: false,
      data: [],
      error: '벤더 목록을 조회하는 중 오류가 발생했습니다.'
    }
  }
}

/**
 * 벤더 코드로 조회
 */
export async function getVendorByCode(vendorCode: string): Promise<VendorSearchItem | null> {
  if (!vendorCode.trim()) {
    return null
  }

  try {
    const result = await db
      .select({
        id: vendors.id,
        vendorName: vendors.vendorName,
        vendorCode: vendors.vendorCode,
        taxId: vendors.taxId,
        status: vendors.status,
      })
      .from(vendors)
      .where(eq(vendors.vendorCode, vendorCode.trim()))
      .limit(1)

    if (result.length === 0) {
      return null
    }

    const vendor = result[0]
    return {
      ...vendor,
      displayText: vendor.vendorCode 
        ? `${vendor.vendorName} (${vendor.vendorCode})`
        : vendor.vendorName
    }
  } catch (error) {
    console.error('Error fetching vendor by code:', error)
    return null
  }
}

/**
 * 특정 벤더 조회 (ID로)
 */
export async function getVendorById(vendorId: number): Promise<VendorSearchItem | null> {
  if (!vendorId) {
    return null
  }

  try {
    const result = await db
      .select({
        id: vendors.id,
        vendorName: vendors.vendorName,
        vendorCode: vendors.vendorCode,
        taxId: vendors.taxId,
        status: vendors.status,
      })
      .from(vendors)
      .where(eq(vendors.id, vendorId))
      .limit(1)

    if (result.length === 0) {
      return null
    }

    const vendor = result[0]
    return {
      ...vendor,
      displayText: vendor.vendorCode 
        ? `${vendor.vendorName} (${vendor.vendorCode})`
        : vendor.vendorName
    }
  } catch (error) {
    console.error('Error fetching vendor by ID:', error)
    return null
  }
}

/**
 * 벤더 상태 목록 조회
 */
export async function getVendorStatuses(): Promise<{
  success: boolean
  data: string[]
  error?: string
}> {
  try {
    const result = await db
      .selectDistinct({ status: vendors.status })
      .from(vendors)
      .orderBy(asc(vendors.status))

    const statuses = result.map(row => row.status).filter(Boolean)

    return {
      success: true,
      data: statuses
    }
  } catch (error) {
    console.error('Error fetching vendor statuses:', error)
    return {
      success: false,
      data: [],
      error: '벤더 상태 목록을 조회하는 중 오류가 발생했습니다.'
    }
  }
}