summaryrefslogtreecommitdiff
path: root/lib/users/service.ts
blob: e32d450efb7983a4aa0efe9e86ec8c342a51d218 (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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
// lib/users/service.ts
"use server";

import { Otp } from '@/types/user';
import { getAllUsers, createUser, getUserById, updateUser, deleteUser, getUserByEmail, createOtp,getOtpByEmailAndToken, updateOtp, findOtpByEmail ,getOtpByEmailAndCode, findAllRoles, getRoleAssignedUsers} from './repository';
import logger from '@/lib/logger';
import { Role, roles, userRoles, users, userView, type User } from '@/db/schema/users';
import { saveDocument } from '../storage';
import { GetSimpleUsersSchema, GetUsersSchema } from '../admin-users/validations';
import { revalidatePath, revalidateTag, unstable_cache, unstable_noStore } from 'next/cache';
import { filterColumns } from '../filter-columns';
import { countUsers, countUsersSimple, selectUsers, selectUsersWithCompanyAndRoles } from '../admin-users/repository';
import db from "@/db/db";
import { getErrorMessage } from "@/lib/handle-error";
import { getServerSession } from "next-auth/next"
import { authOptions } from "@/app/api/auth/[...nextauth]/route"
import { and, or, desc, asc, ilike, eq, isNull, sql, count, inArray, ne } from "drizzle-orm";

interface AssignUsersArgs {
  roleId: number
  userIds: number[]
}


export const fetchAllUsers = async (): Promise<User[]> => {
  try {
    logger.info('Fetching all users');
    const users = await getAllUsers();
    logger.debug({ count: users.length }, 'Fetched users successfully');
    return users;
  } catch (error) {
    logger.error({ error }, 'Error fetching all users');
    throw new Error('Failed to fetch users');
  }
};


export const fetchRoleAssignedUserID = async (roleId: number) => {
  try {
    logger.info('Fetching all users');
    const users = await getRoleAssignedUsers(roleId);
    logger.debug({ count: users.length }, 'Fetched users successfully');
    return users;
  } catch (error) {
    logger.error({ error }, 'Error fetching all users');
    throw new Error('Failed to fetch users');
  }
};


export const addNewUser = async (name: string, email: string): Promise<User> => {
  try {
    logger.info({ name, email }, 'Creating a new user');
    const user = await createUser(name, email);
    logger.debug({ user }, 'User created successfully');
    return user;
  } catch (error) {
    logger.error({ error }, 'Error creating a new user');
    throw new Error('Failed to create user');
  }
};

export const findUserById = async (id: number): Promise<User | null> => {
  try {
    logger.info({ id }, 'Fetching user by ID');
    const user = await getUserById(id);
    if (!user) {
      logger.warn({ id }, 'User not found');
    } else {
      logger.debug({ user }, 'User fetched successfully');
    }
    return user;
  } catch (error) {
    logger.error({ error }, 'Error fetching user by ID');
    throw new Error('Failed to fetch user');
  }
};

export const findUserByEmail = async (email: string): Promise<User | null> => {
  try {
    logger.info({ email }, 'Fetching user by Email');
    const user = await getUserByEmail(email);
    if (!user) {
      logger.warn({ email }, 'User not found');
    } else {
      logger.debug({ user }, 'User fetched successfully');
    }
    return user;
  } catch (error) {
    logger.error({ error }, 'Error fetching user by ID');
    throw new Error('Failed to fetch user');
  }
};

export const modifyUser = async (id: number, data: Partial<User>): Promise<User | null> => {
  try {
    logger.info({ id, data }, 'Updating user');
    const user = await updateUser(id, data);
    if (!user) {
      logger.warn({ id }, 'User not found for update');
    } else {
      logger.debug({ user }, 'User updated successfully');
    }
    return user;
  } catch (error) {
    logger.error({ error }, 'Error updating user');
    throw new Error('Failed to update user');
  }
};

export const removeUser = async (id: number): Promise<boolean> => {
  try {
    logger.info({ id }, 'Deleting user');
    const success = await deleteUser(id);
    if (success) {
      logger.debug({ id }, 'User deleted successfully');
    } else {
      logger.warn({ id }, 'User not found for deletion');
    }
    return success;
  } catch (error) {
    logger.error({ error }, 'Error deleting user');
    throw new Error('Failed to delete user');
  }
};

export const addNewOtp = async (
  email: string,
  code: string,
  createdAt: Date,
  otpToken: string,
  otpExpires: Date
): Promise<Otp> => {
  try {
    logger.info({ email }, 'Creating or updating an OTP record');

    // 1) 먼저 email로 Otp가 있는지 조회
    const existingOtp = await findOtpByEmail(email);

    // 2) 이미 있으면 update
    if (existingOtp) {
      const otp = await updateOtp(email, code, createdAt, otpToken, otpExpires);
      logger.debug({ otp }, 'OTP updated successfully');
      return otp;
    }
    // 3) 없으면 새로 생성
    else {
      const otp = await createOtp(email, code, createdAt, otpToken, otpExpires);
      logger.debug({ otp }, 'OTP created successfully');
      return otp;
    }
  } catch (error) {
    logger.error({ error }, 'Error creating or updating OTP');
    throw new Error('Failed to create or update OTP');
  }
};

export const findOtpByEmailandToken = async (email: string, otpToken: string): Promise<Otp | null> => {
  try {
    logger.info({ email }, 'Fetching otp by Email');
    const otp = await getOtpByEmailAndToken(email, otpToken);
    if (!otp) {
      logger.warn({ email }, 'Otp not found');
    } else {
      logger.debug({ otp }, 'Otp fetched successfully');
    }
    return otp;
  } catch (error) {
    logger.error({ error }, 'Error fetching user by ID');
    throw new Error('Failed to fetch user');
  }
};


export async function findEmailandOtp(email: string, code: string) {
  try {
    // 1) otp 조회
    const otpRecord: Otp | null = await getOtpByEmailAndCode(email, code)
    if (!otpRecord) {
      return null
    }

    // 2) 사용자 정보 추가로 조회
    const userRecord: User | null = await getUserByEmail(email)
    if (!userRecord) {
      return null
    }

    // 3) 필요한 형태로 "통합된 객체"를 반환
    return {
      otpExpires: otpRecord.otpExpires,
      email: userRecord.email,
      name: userRecord.name,    // DB 에서 가져온 실제 이름
      id: userRecord.id,        // user id
      imageUrl:userRecord.imageUrl,
      companyId:userRecord.companyId,
      techCompanyId:userRecord.techCompanyId,
      domain:userRecord.domain
      // 기타 필요한 필드...
    }

  } catch (error) {
    // 에러 처리
    throw new Error('Failed to fetch user & otp')
  }
}

export async function findEmailTemp(email: string) {
  try {

    // 2) 사용자 정보 추가로 조회
    const userRecord: User | null = await getUserByEmail(email)
    if (!userRecord) {
      return null
    }

    // 3) 필요한 형태로 "통합된 객체"를 반환
    return {
      email: userRecord.email,
      name: userRecord.name,    // DB 에서 가져온 실제 이름
      id: userRecord.id,        // user id
      imageUrl:userRecord.imageUrl,
      companyId:userRecord.companyId,
      techCompanyId:userRecord.techCompanyId,
      domain:userRecord.domain
      // 기타 필요한 필드...
    }

  } catch (error) {
    // 에러 처리
    throw new Error('Failed to fetch user & otp')
  }
}

export async function updateUserProfileImage(formData: FormData) {
  // 1) FormData에서 데이터 꺼내기
  const file = formData.get("file") as File | null
  const userId = Number(formData.get("userId"))
  const name = formData.get("name") as string
  const email = formData.get("email") as string

  // 2) 기본적인 유효성 검증
  if (!file) {
    throw new Error("No file found in the FormData.")
  }
  if (!userId) {
    throw new Error("userId is required.")
  }

  try {
    // 3) 파일 저장 (해시 생성)
    const directory = './public/profiles'
    const { hashedFileName } = await saveDocument(file, directory)

    // 4) DB 업데이트
    const imageUrl = hashedFileName
    const data = { name, email, imageUrl }
    const user = await updateUser(userId, data)
    if (!user) {
      // updateUser가 null을 반환하면, DB 업데이트 실패 혹은 해당 유저가 없음
      throw new Error(`User with id=${userId} not found or update failed.`)
    }

    // 5) 성공 시 성공 정보 반환
    return { success: true, user }
  } catch (err: any) {
    // DB 업데이트 중 발생하는 에러나 saveDocument 내부 에러 등을 처리
    console.error("[updateUserProfileImage] Error:", err)
    throw new Error(err.message ?? "Failed to update user profile.")
  }
}

export async function getUsersEVCP(input: GetUsersSchema) {
  return unstable_cache(
    async () => {
      try {
        const offset = (input.page - 1) * input.perPage;

        // (1) advancedWhere
        const advancedWhere = filterColumns({
          table: userView,
          filters: input.filters,
          joinOperator: input.joinOperator,
        });

        // (2) globalWhere
        let globalWhere;
        if (input.search) {
          const s = `%${input.search}%`;
          globalWhere = or(
            ilike(userView.user_name, s),
            ilike(userView.user_email, s),
            ilike(userView.company_name, s)
          );
        }

        // (3) 디폴트 domainWhere = eq(userView.domain, "partners")
        //     다만, 사용자가 이미 domain 필터를 줬다면 적용 X
        let domainWhere;
        const hasDomainFilter = input.filters?.some((f) => f.id === "user_domain");
        if (!hasDomainFilter) {
          domainWhere = eq(userView.user_domain, "evcp");
        }

        // (4) 최종 where
        const finalWhere = and(advancedWhere, globalWhere, domainWhere);

        // (5) 정렬
        const orderBy =
          input.sort.length > 0
            ? input.sort.map((item) =>
                item.desc ? desc(userView[item.id]) : asc(userView[item.id])
              )
            : [desc(users.createdAt)];

        // ...
        const { data, total } = await db.transaction(async (tx) => {
          const data = await selectUsersWithCompanyAndRoles(tx, {
            where: finalWhere,
            orderBy,
            offset,
            limit: input.perPage,
          });

          const total = await countUsers(tx, finalWhere);
          return { data, total };
        });

        const pageCount = Math.ceil(total / input.perPage);
        return { data, pageCount };
      } catch (err) {
        return { data: [], pageCount: 0 };
      }
    },
    [JSON.stringify(input)],
    {
      revalidate: 3600,
      tags: ["users"],
    }
  )();
}


export async function getUsersNotPartners(input: GetSimpleUsersSchema) {
  return unstable_cache(
    async () => {
      try {
        const offset = (input.page - 1) * input.perPage;

        // (1) advancedWhere
        const advancedWhere = filterColumns({
          table: users,
          filters: input.filters,
          joinOperator: input.joinOperator,
        });

        // (2) globalWhere
        let globalWhere;
        if (input.search) {
          const s = `%${input.search}%`;
          globalWhere = or(
            ilike(users.name, s),
            ilike(users.email, s),
            ilike(users.deptName, s),
          );
        }

        // (3) 디폴트 domainWhere = eq(userView.domain, "partners")
        //     다만, 사용자가 이미 domain 필터를 줬다면 적용 X
        let domainWhere;
        const hasDomainFilter = input.filters?.some((f) => f.id === "domain");
        if (!hasDomainFilter) {
          domainWhere = ne(users.domain, "partners");
        }

        // (4) 최종 where
        const finalWhere = and(advancedWhere, globalWhere, domainWhere);

        // (5) 정렬
        const orderBy =
          input.sort.length > 0
            ? input.sort.map((item) =>
                item.desc ? desc(users[item.id]) : asc(users[item.id])
              )
            : [desc(users.createdAt)];

        // ...
        const { data, total } = await db.transaction(async (tx) => {
          const data = await selectUsers(tx, {
            where: finalWhere,
            orderBy,
            offset,
            limit: input.perPage,
          });


          console.log(data)

          const total = await countUsersSimple(tx, finalWhere);
          return { data, total };
        });

        const pageCount = Math.ceil(total / input.perPage);
        return { data, pageCount };
      } catch (err) {

        console.log(err)
        return { data: [], pageCount: 0 };
      }
    },
    [JSON.stringify(input)],
    {
      revalidate: 3600,
      tags: ["users-access-control"],
    }
  )();
}

export async function getAllRoles(): Promise<Role[]> {
  try {
    return await findAllRoles(); 
  } catch (err) {
    throw new Error("Failed to get roles");
  }
}


export async function getUsersAll(input: GetUsersSchema, domain: string) {
  return unstable_cache(
    async () => {
      try {
        const offset = (input.page - 1) * input.perPage;

        // (1) advancedWhere
        const advancedWhere = filterColumns({
          table: userView,
          filters: input.filters,
          joinOperator: input.joinOperator,
        });

        // (2) globalWhere
        let globalWhere;
        if (input.search) {
          const s = `%${input.search}%`;
          globalWhere = or(
            ilike(userView.user_name, s),
            ilike(userView.user_email, s),
            ilike(userView.company_name, s)
          );
        }

        // (3) domainWhere - 무조건 들어가야 하는 domain 조건
        const domainWhere = eq(userView.user_domain, domain);

        // (4) 최종 where
        //    domainWhere과 advancedWhere, globalWhere를 모두 and로 묶는다.
        //    (globalWhere가 존재하지 않을 수 있으니, and() 호출 시 undefined를 자동 무시할 수도 있음)
        const finalWhere = and(domainWhere, advancedWhere, globalWhere);

        // (5) 정렬
        const orderBy =
          input.sort.length > 0
            ? input.sort.map((item) =>
                item.desc ? desc(userView[item.id]) : asc(userView[item.id])
              )
            : [desc(users.createdAt)];

        const { data, total } = await db.transaction(async (tx) => {
          const data = await selectUsersWithCompanyAndRoles(tx, {
            where: finalWhere,
            orderBy,
            offset,
            limit: input.perPage,
          });

          const total = await countUsers(tx, finalWhere);
          return { data, total };
        });

        const pageCount = Math.ceil(total / input.perPage);
        return { data, pageCount };
      } catch (err) {
        return { data: [], pageCount: 0 };
      }
    },
    // (6) 캐시 종속성 배열에 domain도 추가
    [JSON.stringify(input), domain],
    {
      revalidate: 3600,
      tags: ["users"],
    }
  )();
}


export async function getUsersAllbyVendor(input: GetUsersSchema, domain: string) {

      try {

        const session = await getServerSession(authOptions)
        if (!session?.user) {
          throw new Error("인증이 필요합니다.")
        }

        const companyId = session?.user.companyId

        const offset = (input.page - 1) * input.perPage;

        // (1) advancedWhere
        const advancedWhere = filterColumns({
          table: userView,
          filters: input.filters,
          joinOperator: input.joinOperator,
        });

        // (2) globalWhere
        let globalWhere;
        if (input.search) {
          const s = `%${input.search}%`;
          globalWhere = or(
            ilike(userView.user_name, s),
            ilike(userView.user_email, s),
          );
        }

        // (3) domainWhere - 무조건 들어가야 하는 domain 조건
        const domainWhere = eq(userView.user_domain, domain);

        // (4) 최종 where
        //    domainWhere과 advancedWhere, globalWhere를 모두 and로 묶는다.
        //    (globalWhere가 존재하지 않을 수 있으니, and() 호출 시 undefined를 자동 무시할 수도 있음)
        const finalWhere = and(domainWhere, advancedWhere, globalWhere, eq(userView.company_id, companyId));

        // (5) 정렬
        const orderBy =
          input.sort.length > 0
            ? input.sort.map((item) =>
                item.desc ? desc(userView[item.id]) : asc(userView[item.id])
              )
            : [desc(users.createdAt)];

        const { data, total } = await db.transaction(async (tx) => {
          const data = await selectUsersWithCompanyAndRoles(tx, {
            where: finalWhere,
            orderBy,
            offset,
            limit: input.perPage,
          });

          const total = await countUsers(tx, finalWhere);
          return { data, total };
        });

        const pageCount = Math.ceil(total / input.perPage);
        return { data, pageCount };
      } catch (err) {
        return { data: [], pageCount: 0 };
      }

}

export async function assignUsersToRole(roleId: number, userIds: number[]) {
  unstable_noStore(); // 캐싱 방지(Next.js 서버 액션용)
  try{
    await db.transaction(async (tx) => {
      // 1) 기존 userRoles 레코드 삭제
      await tx.delete(userRoles).where(eq(userRoles.roleId, roleId))
  
      // 2) 새로 넣기
      if (userIds.length > 0) {
        await tx.insert(userRoles).values(
          userIds.map((uid) => ({ userId: uid, roleId }))
        )
      }
    })
    revalidateTag("users");
    revalidateTag("roles");

    return { data: null, error: null };
  } catch (err){
    return { data: null, error: getErrorMessage(err) };

  }

}


export type UserDomain = "pending" | "evcp" | "procurement" | "sales" | "engineering" | "partners"

/**
 * 여러 사용자에게 도메인을 일괄 할당하는 함수
 */
export async function assignUsersDomain(
  userIds: number[],
  domain: UserDomain
) {
  try {
    if (!userIds.length) {
      return { 
        success: false, 
        message: "할당할 사용자가 없습니다." 
      }
    }

    if (!domain) {
      return { 
        success: false, 
        message: "도메인을 선택해주세요." 
      }
    }

    // 사용자들의 도메인 업데이트
    const result = await db
      .update(users)
      .set({ 
        domain,
        updatedAt: new Date(),
      })
      .where(inArray(users.id, userIds))
      .returning({
        id: users.id,
        name: users.name,
        email: users.email,
        domain: users.domain,
      })

    // 관련 페이지들 revalidate
    revalidatePath("/evcp/user-management")
    revalidatePath("/")

    return { 
      success: true, 
      message: `${result.length}명의 사용자 도메인이 업데이트되었습니다.`,
      data: result
    }
  } catch (error) {
    console.error("사용자 도메인 할당 오류:", error)
    return { 
      success: false, 
      message: "도메인 할당 중 오류가 발생했습니다." 
    }
  }
}

/**
 * 단일 사용자의 도메인을 변경하는 함수
 */
export async function assignUserDomain(
  userId: number, 
  domain: UserDomain
) {
  try {
    const result = await db
      .update(users)
      .set({ 
        domain,
        updatedAt: new Date(),
      })
      .where(eq(users.id, userId))
      .returning({
        id: users.id,
        name: users.name,
        email: users.email,
        domain: users.domain,
      })

    if (result.length === 0) {
      return { 
        success: false, 
        message: "사용자를 찾을 수 없습니다." 
      }
    }

    revalidatePath("/evcp/user-management")
    revalidatePath("/evcp/users")

    return { 
      success: true, 
      message: `${result[0].name}님의 도메인이 ${domain}으로 변경되었습니다.`,
      data: result[0]
    }
  } catch (error) {
    console.error("사용자 도메인 할당 오류:", error)
    return { 
      success: false, 
      message: "도메인 할당 중 오류가 발생했습니다." 
    }
  }
}

/**
 * 도메인별 사용자 통계를 조회하는 함수
 */
export async function getUserDomainStats() {
  try {
    const stats = await db
      .select({
        domain: users.domain,
        count: count(),
      })
      .from(users)
      .where(eq(users.isActive, true))
      .groupBy(users.domain)

    return { 
      success: true, 
      data: stats 
    }
  } catch (error) {
    console.error("도메인 통계 조회 오류:", error)
    return { 
      success: false, 
      message: "통계 조회 중 오류가 발생했습니다.",
      data: [] 
    }
  }
}

/**
 * pending 도메인 사용자 목록을 조회하는 함수 (관리자용)
 */
export async function getPendingUsers() {
  try {
    const pendingUsers = await db
      .select({
        id: users.id,
        name: users.name,
        email: users.email,
        createdAt: users.createdAt,
        domain: users.domain,
      })
      .from(users)
      .where(and(
        eq(users.domain, "pending"),
        eq(users.isActive, true)
      ))
      .orderBy(desc(users.createdAt))

    return { 
      success: true, 
      data: pendingUsers 
    }
  } catch (error) {
    console.error("pending 사용자 조회 오류:", error)
    return { 
      success: false, 
      message: "사용자 조회 중 오류가 발생했습니다.",
      data: [] 
    }
  }
}

// ✅ Role 정보 조회 함수 추가
export async function getUserRoles(userId: number): Promise<string[]> {
  try {
    const userWithRoles = await db
      .select({
        roleName: roles.name,
      })
      .from(userRoles)
      .innerJoin(roles, eq(userRoles.roleId, roles.id))
      .where(eq(userRoles.userId, userId))

    return userWithRoles.map(r => r.roleName)
  } catch (error) {
    console.error('Error fetching user roles:', error)
    return []
  }
}