summaryrefslogtreecommitdiff
path: root/lib/techsales-rfq/repository.ts
blob: 8a579427084a2cd9f9fcd3d5e3da23f4532598e8 (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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
/* eslint-disable @typescript-eslint/no-explicit-any */

import {
  techSalesRfqs,
  techSalesVendorQuotations,
  vendors,
  users,
  itemShipbuilding
} from "@/db/schema";
import {
    asc,
    desc, count, SQL, sql
} from "drizzle-orm";
import { PgTransaction } from "drizzle-orm/pg-core";


export type NewTechSalesRfq = typeof techSalesRfqs.$inferInsert;
/**
 * 기술영업 RFQ 생성
 * ID 및 생성일 리턴
 */
export async function insertTechSalesRfq(
  tx: PgTransaction<any, any, any>,
  data: NewTechSalesRfq
) {
  return tx
  .insert(techSalesRfqs)
  .values(data)
  .returning({ id: techSalesRfqs.id, createdAt: techSalesRfqs.createdAt });
}

/**
 * 단건/복수 조회 시 공통으로 사용 가능한 SELECT 함수 예시
 *  - 트랜잭션(tx)을 받아서 사용하도록 구현
 */
export async function selectTechSalesRfqs(
  tx: PgTransaction<any, any, any>,
  params: {
    where?: any;
    orderBy?: (ReturnType<typeof asc> | ReturnType<typeof desc>)[];
    offset?: number;
    limit?: number;
  }
) {
  const { where, orderBy, offset = 0, limit = 10 } = params;

  return tx
    .select()
    .from(techSalesRfqs)
    .where(where ?? undefined)
    .orderBy(...(orderBy ?? []))
    .offset(offset)
    .limit(limit);
}
/** 총 개수 count */
export async function countTechSalesRfqs(
  tx: PgTransaction<any, any, any>,
  where?: any
) {
  const res = await tx.select({ count: count() }).from(techSalesRfqs).where(where);
  return res[0]?.count ?? 0;
}

/**
 * RFQ 정보 직접 조인 조회 (뷰 대신 테이블 조인 사용) 
 */
export async function selectTechSalesRfqsWithJoin(
  tx: PgTransaction<any, any, any>,
  params: {
    where?: any;
    orderBy?: (ReturnType<typeof asc> | ReturnType<typeof desc> | SQL<unknown>)[];
    offset?: number;
    limit?: number;
  }
) {
  const { where, orderBy, offset = 0, limit = 10 } = params;

  // 별칭 방식을 변경하여 select, join, where, orderBy 등을 순차적으로 수행
  const query = tx.select({
    // RFQ 기본 정보
    id: techSalesRfqs.id,
    rfqCode: techSalesRfqs.rfqCode,
    itemId: techSalesRfqs.itemId,
    itemName: itemShipbuilding.itemList,
    materialCode: techSalesRfqs.materialCode,
    
    // 날짜 및 상태 정보
    dueDate: techSalesRfqs.dueDate,
    rfqSendDate: techSalesRfqs.rfqSendDate,
    status: techSalesRfqs.status,
    
    // 담당자 및 비고
    picCode: techSalesRfqs.picCode,
    remark: techSalesRfqs.remark,
    cancelReason: techSalesRfqs.cancelReason,
    
    // 생성/수정 정보
    createdAt: techSalesRfqs.createdAt,
    updatedAt: techSalesRfqs.updatedAt,
    
    // 사용자 정보
    createdBy: techSalesRfqs.createdBy,
    createdByName: sql<string>`created_user.name`,
    updatedBy: techSalesRfqs.updatedBy,
    updatedByName: sql<string>`updated_user.name`,
    sentBy: techSalesRfqs.sentBy,
    sentByName: sql<string | null>`sent_user.name`,
    
    // 프로젝트 정보 (스냅샷)
    projectSnapshot: techSalesRfqs.projectSnapshot,
    seriesSnapshot: techSalesRfqs.seriesSnapshot,
    
    // 프로젝트 핵심 정보
    pspid: sql<string>`${techSalesRfqs.projectSnapshot}->>'pspid'`,
    projNm: sql<string>`${techSalesRfqs.projectSnapshot}->>'projNm'`,
    sector: sql<string>`${techSalesRfqs.projectSnapshot}->>'sector'`,
    projMsrm: sql<number>`(${techSalesRfqs.projectSnapshot}->>'projMsrm')::int`,
    ptypeNm: sql<string>`${techSalesRfqs.projectSnapshot}->>'ptypeNm'`,
    
    // 첨부파일 개수
    attachmentCount: sql<number>`(
      SELECT COUNT(*) 
      FROM tech_sales_attachments 
      WHERE tech_sales_attachments.tech_sales_rfq_id = ${techSalesRfqs.id}
    )`,
    
    // 벤더 견적 개수
    quotationCount: sql<number>`(
      SELECT COUNT(*) 
      FROM tech_sales_vendor_quotations 
      WHERE tech_sales_vendor_quotations.rfq_id = ${techSalesRfqs.id}
    )`,
  })
  .from(techSalesRfqs)
  .leftJoin(itemShipbuilding, sql`split_part(${techSalesRfqs.materialCode}, ',', 1) = ${itemShipbuilding.itemCode}`)
  .leftJoin(sql`${users} AS created_user`, sql`${techSalesRfqs.createdBy} = created_user.id`)
  .leftJoin(sql`${users} AS updated_user`, sql`${techSalesRfqs.updatedBy} = updated_user.id`)
  .leftJoin(sql`${users} AS sent_user`, sql`${techSalesRfqs.sentBy} = sent_user.id`);

  // where 조건 적용
  const queryWithWhere = where ? query.where(where) : query;
  
  // orderBy 적용
  const queryWithOrderBy = orderBy?.length 
    ? queryWithWhere.orderBy(...orderBy)
    : queryWithWhere.orderBy(desc(techSalesRfqs.createdAt));
  
  // offset과 limit 적용 후 실행
  return queryWithOrderBy.offset(offset).limit(limit);
}

/**
 * RFQ 개수 직접 조회 (뷰 대신 테이블 조인 사용)
 */
export async function countTechSalesRfqsWithJoin(
  tx: PgTransaction<any, any, any>,
  where?: any
) {
  const res = await tx
    .select({ count: count() })
    .from(techSalesRfqs)
    .leftJoin(itemShipbuilding, sql`split_part(${techSalesRfqs.materialCode}, ',', 1) = ${itemShipbuilding.itemCode}`)
    .where(where ?? undefined);
  return res[0]?.count ?? 0;
}

/**
 * 벤더 견적서 직접 조인 조회 (뷰 대신 테이블 조인 사용)
 */
export async function selectTechSalesVendorQuotationsWithJoin(
  tx: PgTransaction<any, any, any>,
  params: {
    where?: any;
    orderBy?: (ReturnType<typeof asc> | ReturnType<typeof desc> | SQL<unknown>)[];
    offset?: number;
    limit?: number;
  }
) {
  const { where, orderBy, offset = 0, limit = 10 } = params;

  // 별칭 방식을 변경하여 select, join, where, orderBy 등을 순차적으로 수행
  const query = tx.select({
    // 견적 기본 정보
    id: techSalesVendorQuotations.id,
    rfqId: techSalesVendorQuotations.rfqId,
    rfqCode: techSalesRfqs.rfqCode,
    vendorId: techSalesVendorQuotations.vendorId,
    vendorName: vendors.vendorName,
    vendorCode: vendors.vendorCode,
    
    // 견적 상세 정보
    totalPrice: techSalesVendorQuotations.totalPrice,
    currency: techSalesVendorQuotations.currency,
    validUntil: techSalesVendorQuotations.validUntil,
    status: techSalesVendorQuotations.status,
    remark: techSalesVendorQuotations.remark,
    rejectionReason: techSalesVendorQuotations.rejectionReason,
    
    // 날짜 정보
    submittedAt: techSalesVendorQuotations.submittedAt,
    acceptedAt: techSalesVendorQuotations.acceptedAt,
    createdAt: techSalesVendorQuotations.createdAt,
    updatedAt: techSalesVendorQuotations.updatedAt,
    
    // 생성/수정 사용자
    createdBy: techSalesVendorQuotations.createdBy,
    createdByName: sql<string | null>`created_user.name`,
    updatedBy: techSalesVendorQuotations.updatedBy,
    updatedByName: sql<string | null>`updated_user.name`,
    
    // 프로젝트 정보
    materialCode: techSalesRfqs.materialCode,
    itemId: techSalesRfqs.itemId,
    itemName: itemShipbuilding.itemList,
    
    // 프로젝트 핵심 정보
    pspid: sql<string>`${techSalesRfqs.projectSnapshot}->>'pspid'`,
    projNm: sql<string>`${techSalesRfqs.projectSnapshot}->>'projNm'`,
    sector: sql<string>`${techSalesRfqs.projectSnapshot}->>'sector'`,
    
    // 첨부파일 개수
    attachmentCount: sql<number>`(
      SELECT COUNT(*) 
      FROM tech_sales_attachments 
      WHERE tech_sales_attachments.tech_sales_rfq_id = ${techSalesRfqs.id}
    )`,
  })
  .from(techSalesVendorQuotations)
  .leftJoin(techSalesRfqs, sql`${techSalesVendorQuotations.rfqId} = ${techSalesRfqs.id}`)
  .leftJoin(vendors, sql`${techSalesVendorQuotations.vendorId} = ${vendors.id}`)
  .leftJoin(itemShipbuilding, sql`split_part(${techSalesRfqs.materialCode}, ',', 1) = ${itemShipbuilding.itemCode}`)
  .leftJoin(sql`${users} AS created_user`, sql`${techSalesVendorQuotations.createdBy} = created_user.id`)
  .leftJoin(sql`${users} AS updated_user`, sql`${techSalesVendorQuotations.updatedBy} = updated_user.id`);

  // where 조건 적용
  const queryWithWhere = where ? query.where(where) : query;
  
  // orderBy 적용
  const queryWithOrderBy = orderBy?.length 
    ? queryWithWhere.orderBy(...orderBy)
    : queryWithWhere.orderBy(desc(techSalesVendorQuotations.createdAt));
  
  // offset과 limit 적용 후 실행
  return queryWithOrderBy.offset(offset).limit(limit);
}

/**
 * 벤더 견적서 개수 직접 조회 (뷰 대신 테이블 조인 사용)
 */
export async function countTechSalesVendorQuotationsWithJoin(
  tx: PgTransaction<any, any, any>,
  where?: any
) {
  const res = await tx
    .select({ count: count() })
    .from(techSalesVendorQuotations)
    .leftJoin(techSalesRfqs, sql`${techSalesVendorQuotations.rfqId} = ${techSalesRfqs.id}`)
    .leftJoin(vendors, sql`${techSalesVendorQuotations.vendorId} = ${vendors.id}`)
    .leftJoin(itemShipbuilding, sql`split_part(${techSalesRfqs.materialCode}, ',', 1) = ${itemShipbuilding.itemCode}`)
    .where(where ?? undefined);
  return res[0]?.count ?? 0;
}

/**
 * RFQ 대시보드 데이터 직접 조인 조회 (뷰 대신 테이블 조인 사용)
 */
export async function selectTechSalesDashboardWithJoin(
  tx: PgTransaction<any, any, any>,
  params: {
    where?: any;
    orderBy?: (ReturnType<typeof asc> | ReturnType<typeof desc> | SQL<unknown>)[];
    offset?: number;
    limit?: number;
  }
) {
  const { where, orderBy, offset = 0, limit = 10 } = params;

  // 별칭 방식을 변경하여 select, join, where, orderBy 등을 순차적으로 수행
  const query = tx.select({
    // RFQ 기본 정보
    id: techSalesRfqs.id,
    rfqCode: techSalesRfqs.rfqCode,
    status: techSalesRfqs.status,
    dueDate: techSalesRfqs.dueDate,
    rfqSendDate: techSalesRfqs.rfqSendDate,
    materialCode: techSalesRfqs.materialCode,
    
    // 아이템 정보
    itemId: techSalesRfqs.itemId,
    itemName: itemShipbuilding.itemList,
    
    // 프로젝트 정보
    pspid: sql<string>`${techSalesRfqs.projectSnapshot}->>'pspid'`,
    projNm: sql<string>`${techSalesRfqs.projectSnapshot}->>'projNm'`,
    sector: sql<string>`${techSalesRfqs.projectSnapshot}->>'sector'`,
    projMsrm: sql<number>`(${techSalesRfqs.projectSnapshot}->>'projMsrm')::int`,
    ptypeNm: sql<string>`${techSalesRfqs.projectSnapshot}->>'ptypeNm'`,
    
    // 벤더 견적 통계
    vendorCount: sql<number>`(
      SELECT COUNT(DISTINCT vendor_id) 
      FROM tech_sales_vendor_quotations 
      WHERE tech_sales_vendor_quotations.rfq_id = ${techSalesRfqs.id}
    )`,
    
    quotationCount: sql<number>`(
      SELECT COUNT(*) 
      FROM tech_sales_vendor_quotations 
      WHERE tech_sales_vendor_quotations.rfq_id = ${techSalesRfqs.id}
    )`,
    
    submittedQuotationCount: sql<number>`(
      SELECT COUNT(*) 
      FROM tech_sales_vendor_quotations 
      WHERE tech_sales_vendor_quotations.rfq_id = ${techSalesRfqs.id}
      AND tech_sales_vendor_quotations.status = 'Submitted'
    )`,
    
    minPrice: sql<string | null>`(
      SELECT MIN(total_price) 
      FROM tech_sales_vendor_quotations 
      WHERE tech_sales_vendor_quotations.rfq_id = ${techSalesRfqs.id}
      AND tech_sales_vendor_quotations.status = 'Submitted'
    )`,
    
    maxPrice: sql<string | null>`(
      SELECT MAX(total_price) 
      FROM tech_sales_vendor_quotations 
      WHERE tech_sales_vendor_quotations.rfq_id = ${techSalesRfqs.id}
      AND tech_sales_vendor_quotations.status = 'Submitted'
    )`,
    
    avgPrice: sql<string | null>`(
      SELECT AVG(total_price) 
      FROM tech_sales_vendor_quotations 
      WHERE tech_sales_vendor_quotations.rfq_id = ${techSalesRfqs.id}
      AND tech_sales_vendor_quotations.status = 'Submitted'
    )`,
    
    // 첨부파일 통계
    attachmentCount: sql<number>`(
      SELECT COUNT(*) 
      FROM tech_sales_attachments 
      WHERE tech_sales_attachments.tech_sales_rfq_id = ${techSalesRfqs.id}
    )`,
    
    // 코멘트 통계
    commentCount: sql<number>`(
      SELECT COUNT(*) 
      FROM tech_sales_rfq_comments 
      WHERE tech_sales_rfq_comments.rfq_id = ${techSalesRfqs.id}
    )`,
    
    unreadCommentCount: sql<number>`(
      SELECT COUNT(*) 
      FROM tech_sales_rfq_comments 
      WHERE tech_sales_rfq_comments.rfq_id = ${techSalesRfqs.id}
      AND tech_sales_rfq_comments.is_read = false
    )`,
    
    // 생성/수정 정보
    createdAt: techSalesRfqs.createdAt,
    updatedAt: techSalesRfqs.updatedAt,
    createdByName: sql<string>`created_user.name`,
  })
  .from(techSalesRfqs)
  .leftJoin(itemShipbuilding, sql`split_part(${techSalesRfqs.materialCode}, ',', 1) = ${itemShipbuilding.itemCode}`)
  .leftJoin(sql`${users} AS created_user`, sql`${techSalesRfqs.createdBy} = created_user.id`);

  // where 조건 적용
  const queryWithWhere = where ? query.where(where) : query;
  
  // orderBy 적용
  const queryWithOrderBy = orderBy?.length 
    ? queryWithWhere.orderBy(...orderBy)
    : queryWithWhere.orderBy(desc(techSalesRfqs.updatedAt));
  
  // offset과 limit 적용 후 실행
  return queryWithOrderBy.offset(offset).limit(limit);
}