summaryrefslogtreecommitdiff
path: root/lib/dashboard/partners-service.ts
blob: ac8ca920c4ef7dbf5dfc140b176ffe457733f0d6 (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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
"use server";

import db from "@/db/db";
import { sql } from "drizzle-orm";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { getPartnerTablesByDomain } from "@/config/partners-dashboard-table";
import { TableConfig } from "@/types/dashboard";

export interface PartnersDashboardStats {
  tableName: string;
  displayName: string;
  total: number;
  pending: number;
  inProgress: number;
  completed: number;
}

export interface PartnersUserDashboardStats extends PartnersDashboardStats {
  myTotal: number;
  myPending: number;
  myInProgress: number;
  myCompleted: number;
}

export interface PartnersDashboardData {
  domain: string;
  companyId: string;
  teamStats: PartnersDashboardStats[];
  userStats: PartnersUserDashboardStats[];
  summary: {
    totalTasks: number;
    myTasks: number;
    teamPending: number;
    teamInProgress: number;
    teamCompleted: number;
    myPending: number;
    myInProgress: number;
    myCompleted: number;
  };
}

// Partners 팀 대시보드 데이터 조회 (회사 필터링 포함)
export async function getPartnersTeamDashboardData(domain: string): Promise<PartnersDashboardStats[]> {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.companyId) {
      throw new Error("회사 정보가 없습니다.");
    }

    const companyId = session.user.companyId;
    const tables = getPartnerTablesByDomain(domain);
    
    if (tables.length === 0) {
      console.warn(`파트너 도메인 '${domain}'에 대한 테이블이 없습니다.`);
      return [];
    }

    console.log(`👥 회사 ID: ${companyId}로 파트너 데이터 조회`);

    // 병렬 처리로 성능 향상
    const results = await Promise.allSettled(
      tables.map(tableConfig => getPartnersTableStats(tableConfig, companyId))
    );

    // 성공한 결과만 반환
    const successfulResults: PartnersDashboardStats[] = [];
    results.forEach((result, index) => {
      if (result.status === 'fulfilled') {
        successfulResults.push(result.value);
      } else {
        console.error(`파트너 테이블 ${tables[index].tableName} 통계 조회 실패:`, result.reason);
      }
    });

    return successfulResults;
  } catch (error) {
    console.error("파트너 팀 대시보드 데이터 조회 실패:", error);
    throw new Error("파트너 팀 대시보드 데이터를 불러오는데 실패했습니다.");
  }
}

// Partners 사용자 대시보드 데이터 조회
export async function getPartnersUserDashboardData(domain: string): Promise<PartnersUserDashboardStats[]> {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id || !session?.user?.companyId) {
      throw new Error("사용자 또는 회사 정보가 없습니다.");
    }

    const userId = session.user.id;
    const companyId = session.user.companyId;
    const tables = getPartnerTablesByDomain(domain);
    
    if (tables.length === 0) {
      console.warn(`파트너 도메인 '${domain}'에 대한 테이블이 없습니다.`);
      return [];
    }


    // 병렬 처리로 성능 향상
    const results = await Promise.allSettled(
      tables.map(async (tableConfig) => {
        const [teamStats, userStats] = await Promise.all([
          getPartnersTableStats(tableConfig, companyId),
          getPartnersUserTableStats(tableConfig, companyId, userId)
        ]);

        return {
          ...teamStats,
          myTotal: userStats.total,
          myPending: userStats.pending,
          myInProgress: userStats.inProgress,
          myCompleted: userStats.completed
        } as PartnersUserDashboardStats;
      })
    );

    // 성공한 결과만 반환
    const successfulResults: PartnersUserDashboardStats[] = [];
    results.forEach((result, index) => {
      if (result.status === 'fulfilled') {
        successfulResults.push(result.value);
      } else {
        console.error(`파트너 테이블 ${tables[index].tableName} 사용자 통계 조회 실패:`, result.reason);
      }
    });

    return successfulResults;
  } catch (error) {
    console.error("파트너 사용자 대시보드 데이터 조회 실패:", error);
    throw new Error("파트너 사용자 대시보드 데이터를 불러오는데 실패했습니다.");
  }
}

// Partners 전체 대시보드 데이터 조회
export async function getPartnersDashboardData(domain: string): Promise<PartnersDashboardData> {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id || !session?.user?.companyId) {
      throw new Error("사용자 또는 회사 정보가 없습니다.");
    }

    const [teamStats, userStats] = await Promise.all([
      getPartnersTeamDashboardData(domain),
      getPartnersUserDashboardData(domain)
    ]);

    // 요약 통계 계산
    const summary = {
      totalTasks: teamStats.reduce((sum, stat) => sum + stat.total, 0),
      myTasks: userStats.reduce((sum, stat) => sum + stat.myTotal, 0),
      teamPending: teamStats.reduce((sum, stat) => sum + stat.pending, 0),
      teamInProgress: teamStats.reduce((sum, stat) => sum + stat.inProgress, 0),
      teamCompleted: teamStats.reduce((sum, stat) => sum + stat.completed, 0),
      myPending: userStats.reduce((sum, stat) => sum + stat.myPending, 0),
      myInProgress: userStats.reduce((sum, stat) => sum + stat.myInProgress, 0),
      myCompleted: userStats.reduce((sum, stat) => sum + stat.myCompleted, 0)
    };

    return {
      domain,
      companyId: session.user.companyId,
      teamStats,
      userStats,
      summary
    };
  } catch (error) {
    console.error("파트너 대시보드 데이터 조회 실패:", error);
    throw new Error("파트너 대시보드 데이터를 불러오는데 실패했습니다.");
  }
}

// Partners 테이블별 전체 통계 조회 (회사 필터링 포함)
async function getPartnersTableStats(config: TableConfig, companyId: string): Promise<PartnersDashboardStats> {
  try {
    
    // 1단계: 회사별 총 개수 확인
    const totalQuery = `
      SELECT COUNT(*)::INTEGER as total 
      FROM "${config.tableName}" 
      WHERE "vendor_id" = '${companyId}'
    `;
    
    const totalResult = await db.execute(sql.raw(totalQuery));
    
    // 2단계: 회사별 상태값 분포 확인
    const statusQuery = `
      SELECT "${config.statusField}" as status, COUNT(*) as count
      FROM "${config.tableName}"
      WHERE "vendor_id" = '${companyId}' AND "${config.statusField}" IS NOT NULL
      GROUP BY "${config.statusField}"
      ORDER BY count DESC
    `;
    
    const statusResult = await db.execute(sql.raw(statusQuery));
    
    // 3단계: 상태별 개수 조회
    const pendingValues = Object.entries(config.statusMapping)
      .filter(([_, mapped]) => mapped === 'pending')
      .map(([original]) => original);
    
    const inProgressValues = Object.entries(config.statusMapping)
      .filter(([_, mapped]) => mapped === 'in_progress')
      .map(([original]) => original);
    
    const completedValues = Object.entries(config.statusMapping)
      .filter(([_, mapped]) => mapped === 'completed')
      .map(([original]) => original);
    

    let pendingCount = 0;
    let inProgressCount = 0; 
    let completedCount = 0;
    
    // Pending 개수 (회사 필터 포함)
    if (pendingValues.length > 0) {
      const pendingValuesList = pendingValues.map(v => `'${v.replace(/'/g, "''")}'`).join(',');
      const pendingQuery = `
        SELECT COUNT(*)::INTEGER as count
        FROM "${config.tableName}"
        WHERE "vendor_id" = '${companyId}' AND "${config.statusField}" IN (${pendingValuesList})
      `;
      
      const pendingResult = await db.execute(sql.raw(pendingQuery));
      pendingCount = parseInt(pendingResult.rows[0]?.count || '0');
    }
    
    // In Progress 개수 (회사 필터 포함)
    if (inProgressValues.length > 0) {
      const inProgressValuesList = inProgressValues.map(v => `'${v.replace(/'/g, "''")}'`).join(',');
      const inProgressQuery = `
        SELECT COUNT(*)::INTEGER as count
        FROM "${config.tableName}"
        WHERE "vendor_id" = '${companyId}' AND "${config.statusField}" IN (${inProgressValuesList})
      `;
      
      const inProgressResult = await db.execute(sql.raw(inProgressQuery));
      inProgressCount = parseInt(inProgressResult.rows[0]?.count || '0');
    }
    
    // Completed 개수 (회사 필터 포함)
    if (completedValues.length > 0) {
      const completedValuesList = completedValues.map(v => `'${v.replace(/'/g, "''")}'`).join(',');
      const completedQuery = `
        SELECT COUNT(*)::INTEGER as count
        FROM "${config.tableName}"
        WHERE "vendor_id" = '${companyId}' AND "${config.statusField}" IN (${completedValuesList})
      `;
      
      const completedResult = await db.execute(sql.raw(completedQuery));
      completedCount = parseInt(completedResult.rows[0]?.count || '0');
    }
    
    const stats = {
      tableName: config.tableName,
      displayName: config.displayName,
      total: parseInt(totalResult.rows[0]?.total || '0'),
      pending: pendingCount,
      inProgress: inProgressCount,
      completed: completedCount
    };

    return stats;
  } catch (error) {
    console.error(`❌ 파트너 테이블 ${config.tableName} 통계 조회 중 오류:`, error);
    return createEmptyPartnersStats(config);
  }
}

// Partners 사용자별 테이블 통계 조회 (회사 + 사용자 필터링)
async function getPartnersUserTableStats(config: TableConfig, companyId: string, userId: string): Promise<PartnersDashboardStats> {
  try {
    // 사용자 필드가 없는 경우 빈 통계 반환
    if (!hasUserFields(config)) {
      return createEmptyPartnersStats(config);
    }


    // 사용자 조건 생성 (회사 필터 포함)
    const userConditions = [];
    if (config.userFields.creator) {
      userConditions.push(`"${config.userFields.creator}" = '${userId}'`);
    }
    if (config.userFields.updater) {
      userConditions.push(`"${config.userFields.updater}" = '${userId}'`);
    }
    if (config.userFields.assignee) {
      userConditions.push(`"${config.userFields.assignee}" = '${userId}'`);
    }
    
    if (userConditions.length === 0) {
      return createEmptyPartnersStats(config);
    }
    
    const userConditionStr = userConditions.join(' OR ');
    
    // 1. 사용자 + 회사 총 개수
    const userTotalQuery = `
      SELECT COUNT(*)::INTEGER as total 
      FROM "${config.tableName}"
      WHERE "vendor_id" = '${companyId}' AND (${userConditionStr})
    `;
    
    const userTotalResult = await db.execute(sql.raw(userTotalQuery));
    
    // 2. 사용자 + 회사 상태별 개수
    const pendingValues = Object.entries(config.statusMapping)
      .filter(([_, mapped]) => mapped === 'pending')
      .map(([original]) => original);
    
    const inProgressValues = Object.entries(config.statusMapping)
      .filter(([_, mapped]) => mapped === 'in_progress')
      .map(([original]) => original);
    
    const completedValues = Object.entries(config.statusMapping)
      .filter(([_, mapped]) => mapped === 'completed')
      .map(([original]) => original);
    
    let userPendingCount = 0;
    let userInProgressCount = 0; 
    let userCompletedCount = 0;
    
    // User + Company Pending 개수
    if (pendingValues.length > 0) {
      const pendingValuesList = pendingValues.map(v => `'${v.replace(/'/g, "''")}'`).join(',');
      const userPendingQuery = `
        SELECT COUNT(*)::INTEGER as count
        FROM "${config.tableName}"
        WHERE "vendor_id" = '${companyId}' AND (${userConditionStr}) AND "${config.statusField}" IN (${pendingValuesList})
      `;
      
      const userPendingResult = await db.execute(sql.raw(userPendingQuery));
      userPendingCount = parseInt(userPendingResult.rows[0]?.count || '0');
    }
    
    // User + Company In Progress 개수
    if (inProgressValues.length > 0) {
      const inProgressValuesList = inProgressValues.map(v => `'${v.replace(/'/g, "''")}'`).join(',');
      const userInProgressQuery = `
        SELECT COUNT(*)::INTEGER as count
        FROM "${config.tableName}"
        WHERE "vendor_id" = '${companyId}' AND (${userConditionStr}) AND "${config.statusField}" IN (${inProgressValuesList})
      `;
      
      const userInProgressResult = await db.execute(sql.raw(userInProgressQuery));
      userInProgressCount = parseInt(userInProgressResult.rows[0]?.count || '0');
    }
    
    // User + Company Completed 개수
    if (completedValues.length > 0) {
      const completedValuesList = completedValues.map(v => `'${v.replace(/'/g, "''")}'`).join(',');
      const userCompletedQuery = `
        SELECT COUNT(*)::INTEGER as count
        FROM "${config.tableName}"
        WHERE "vendor_id" = '${companyId}' AND (${userConditionStr}) AND "${config.statusField}" IN (${completedValuesList})
      `;
      
      const userCompletedResult = await db.execute(sql.raw(userCompletedQuery));
      userCompletedCount = parseInt(userCompletedResult.rows[0]?.count || '0');
    }

    const stats = {
      tableName: config.tableName,
      displayName: config.displayName,
      total: parseInt(userTotalResult.rows[0]?.total || '0'),
      pending: userPendingCount,
      inProgress: userInProgressCount,
      completed: userCompletedCount
    };

    return stats;
  } catch (error) {
    console.error(`❌ 파트너 테이블 ${config.tableName} 사용자 통계 조회 중 오류:`, error);
    return createEmptyPartnersStats(config);
  }
}

// 유틸리티 함수들
function createEmptyPartnersStats(config: TableConfig): PartnersDashboardStats {
  return {
    tableName: config.tableName,
    displayName: config.displayName,
    total: 0,
    pending: 0,
    inProgress: 0,
    completed: 0
  };
}

function hasUserFields(config: TableConfig): boolean {
  return !!(config.userFields.creator || config.userFields.updater || config.userFields.assignee);
}

// 디버깅 함수: Partners 전용
export async function simplePartnersTest(tableName: string, statusField: string, companyId: string) {
  try {
    
    // 1. 회사별 총 개수
    const totalQuery = `SELECT COUNT(*) as total FROM "${tableName}" WHERE "vendor_id" = '${companyId}'`;
    const totalResult = await db.execute(sql.raw(totalQuery));
    
    // 2. 회사별 상태 분포
    const statusQuery = `
      SELECT "${statusField}" as status, COUNT(*) as count
      FROM "${tableName}"
      WHERE "vendor_id" = '${companyId}'
      GROUP BY "${statusField}"
      ORDER BY count DESC
    `;
    const statusResult = await db.execute(sql.raw(statusQuery));
    
    return {
      total: totalResult.rows[0],
      statusDistribution: statusResult.rows
    };
  } catch (error) {
    console.error("파트너 간단한 테스트 실패:", error);
    return null;
  }
}