summaryrefslogtreecommitdiff
path: root/lib/vendors/repository.ts
blob: ff19593266a7258f93e66db0b6bd96339b1be7f0 (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
// src/lib/vendors/repository.ts

import { and, eq, inArray, count, gt, AnyColumn, SQLWrapper, SQL} from "drizzle-orm";
import { PgTransaction } from "drizzle-orm/pg-core";
import { VendorContact, vendorContacts, vendorItemsView, vendorPossibleItems, vendors, type Vendor } from "@/db/schema/vendors";
import db from '@/db/db';
import { items } from "@/db/schema/items";
import { rfqs,rfqItems, rfqEvaluations, vendorResponses } from "@/db/schema/rfq";
import { sql } from "drizzle-orm";

interface SelectVendorsOptions {
  where?: any;
  orderBy?: any[];
  offset?: number;
  limit?: number;
}
export declare function asc(column: AnyColumn | SQLWrapper): SQL;
export declare function desc(column: AnyColumn | SQLWrapper): SQL;
export type NewVendorContact = typeof vendorContacts.$inferInsert
export type NewVendorItem = typeof vendorPossibleItems.$inferInsert

/**
 * 1) SELECT (목록 조회)
 */
export async function selectVendors(
    tx: PgTransaction<any, any, any>,
  { where, orderBy, offset, limit }: SelectVendorsOptions
) {
  return tx
    .select()
    .from(vendors)
    .where(where ?? undefined)
    .orderBy(...(orderBy ?? []))
    .offset(offset ?? 0)
    .limit(limit ?? 20);
}

/**
 * 2) COUNT
 */
export async function countVendors(
    tx: PgTransaction<any, any, any>,
    where?: any
  ) {
    const res = await tx.select({ count: count() }).from(vendors).where(where);
    return res[0]?.count ?? 0;
  }
  

/**
 * 3) INSERT (단일 벤더 생성)
 *    - id/createdAt/updatedAt은 DB default 사용
 *    - 반환값은 "생성된 레코드" 배열 ([newVendor])
 */
export async function insertVendor(
  tx: PgTransaction<any, any, any>,
  data: Omit<Vendor, "id" | "createdAt" | "updatedAt">
) {
  return tx.insert(vendors).values(data).returning();
}

/**
 * 4) UPDATE (단일 벤더)
 */
export async function updateVendor(
  tx: PgTransaction<any, any, any>,
  id: string,
  data: Partial<Vendor>
) {
  return tx
    .update(vendors)
    .set(data)
    .where(eq(vendors.id, Number(id)))
    .returning();
}

/**
 * 5) UPDATE (복수 벤더)
 *    - 여러 개의 id를 받아 일괄 업데이트
 */
export async function updateVendors(
  tx: PgTransaction<any, any, any>,
  ids: string[],
  data: Partial<Vendor>
) {
  const numericIds = ids.map((i) => Number(i));
  return tx
    .update(vendors)
    .set(data)
    .where(inArray(vendors.id, numericIds))
    .returning();
}

/** status 기준 groupBy */
export async function groupByStatus(
    tx: PgTransaction<any, any, any>,
) {
  return tx
    .select({
      status: vendors.status,
      count: count(),
    })
    .from(vendors)
    .groupBy(vendors.status)
    .having(gt(count(), 0));
}


// ID로 사용자 조회
export const getVendorById = async (id: number): Promise<Vendor | null> => {
  const vendorsRes = await db.select().from(vendors).where(eq(vendors.id, id)).execute();
  if (vendorsRes.length === 0) return null;

  const vendor = vendorsRes[0];
  return vendor
};

export const getVendorContactsById = async (id: number): Promise<VendorContact | null> => {
  const contactsRes = await db.select().from(vendorContacts).where(eq(vendorContacts.vendorId, id)).execute();
  if (contactsRes.length === 0) return null;

  const contact = contactsRes[0];
  return contact
};

export async function selectVendorContacts(
  tx: PgTransaction<any, any, any>,
  params: {
    where?: any; // drizzle-orm의 조건식 (and, eq...) 등
    orderBy?: (ReturnType<typeof asc> | ReturnType<typeof desc>)[];
    offset?: number;
    limit?: number;
  }
) {
  const { where, orderBy, offset = 0, limit = 10 } = params;

  return tx
    .select()
    .from(vendorContacts)
    .where(where)
    .orderBy(...(orderBy ?? []))
    .offset(offset)
    .limit(limit);
}

export async function countVendorContacts(
  tx: PgTransaction<any, any, any>,
  where?: any
) {
  const res = await tx.select({ count: count() }).from(vendorContacts).where(where);
  return res[0]?.count ?? 0;
}

export async function insertVendorContact(
  tx: PgTransaction<any, any, any>,
  data: NewVendorContact // DB와 동일한 insert 가능한 타입
) {
  // returning() 사용 시 배열로 돌아오므로 [0]만 리턴
  return tx
    .insert(vendorContacts)
    .values(data)
    .returning({ id: vendorContacts.id, createdAt: vendorContacts.createdAt });
}


export async function selectVendorItems(
  tx: PgTransaction<any, any, any>,
  params: {
    where?: any; // drizzle-orm의 조건식 (and, eq...) 등
    orderBy?: (ReturnType<typeof asc> | ReturnType<typeof desc>)[];
    offset?: number;
    limit?: number;
  }
) {
  const { where, orderBy, offset = 0, limit = 10 } = params;

  return tx
  .select({
    // vendor_possible_items cols
    vendorItemId: vendorItemsView.vendorItemId,
    vendorId: vendorItemsView.vendorId,
    itemCode: vendorItemsView.itemCode,
    createdAt: vendorItemsView.createdAt,
    updatedAt: vendorItemsView.updatedAt,
    itemName: vendorItemsView.itemName,         
    description: vendorItemsView.description,  
  })
  .from(vendorItemsView)
  .where(where ?? undefined)
  .orderBy(...(orderBy ?? []))
  .offset(offset)
  .limit(limit);
}

export async function countVendorItems(
  tx: PgTransaction<any, any, any>,
  where?: any
) {
  const res = await tx.select({ count: count() }).from(vendorItemsView).where(where);
  return res[0]?.count ?? 0;
}

export async function insertVendorItem(
  tx: PgTransaction<any, any, any>,
  data: NewVendorItem // DB와 동일한 insert 가능한 타입
) {
  // returning() 사용 시 배열로 돌아오므로 [0]만 리턴
  return tx
    .insert(vendorPossibleItems)
    .values(data)
    .returning({ id: vendorPossibleItems.id, createdAt: vendorPossibleItems.createdAt });
}

export async function selectRfqHistory(
  tx: PgTransaction<any, any, any>,
  { where, orderBy, offset, limit }: SelectVendorsOptions
) {
  return tx
      .select({
          // RFQ 기본 정보
          id: rfqs.id,
          rfqCode: rfqs.rfqCode,

          description: rfqs.description,
          dueDate: rfqs.dueDate,
          status: rfqs.status,
          createdAt: rfqs.createdAt,
          
   
          // Item 정보 (집계)
          itemCount: sql<number>`count(distinct ${rfqItems.id})::integer`,
          
          // 평가 정보
          tbeResult: sql<string>`
              (select result from ${rfqEvaluations} 
              where rfq_id = ${rfqs.id} 
              and vendor_id = ${vendorResponses.vendorId} 
              and eval_type = 'TBE' 
              limit 1)`,
          cbeResult: sql<string>`
              (select result from ${rfqEvaluations} 
              where rfq_id = ${rfqs.id} 
              and vendor_id = ${vendorResponses.vendorId} 
              and eval_type = 'CBE' 
              limit 1)`
      })
      .from(rfqs)
      .innerJoin(vendorResponses, eq(rfqs.id, vendorResponses.rfqId))

      .leftJoin(rfqItems, eq(rfqs.id, rfqItems.rfqId))
      .where(where ?? undefined)
      .groupBy(
          rfqs.id,
          rfqs.rfqCode,
      
          rfqs.description,
          rfqs.dueDate,
          rfqs.status,
          rfqs.createdAt,
        
          vendorResponses.vendorId,
     
      )
      .orderBy(...(orderBy ?? []))
      .offset(offset ?? 0)
      .limit(limit ?? 20);
}

export async function countRfqHistory(
  tx: PgTransaction<any, any, any>,
  where?: any
) {
  const [{ count }] = await tx
      .select({
          count: sql<number>`count(distinct ${rfqs.id})::integer`,
      })
      .from(rfqs)
      .innerJoin(vendorResponses, eq(rfqs.id, vendorResponses.rfqId))
      .where(where ?? undefined);

  return count;
}