summaryrefslogtreecommitdiff
path: root/lib/admin-users/repository.ts
blob: 63e98b4e5a5deb28ab85f0fea701daf115f80e04 (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
import db from "@/db/db"; 
import { users, userRoles,userView,roles, type User, type UserRole, type UserView, Role  } from "@/db/schema/users";
import { companies, type Company } from "@/db/schema/companies";
import {
  eq,
  inArray,
  asc,
  desc,
  and,
  count,
  gt,
  sql,
  SQL,
} from "drizzle-orm";
import { PgTransaction } from "drizzle-orm/pg-core";
import { Vendor, vendors } from "@/db/schema/vendors";

// ============================================================
// 타입
// ============================================================

export type NewUser = typeof users.$inferInsert;       // User insert 시 필요한 타입
export type NewUserRole = typeof userRoles.$inferInsert; // UserRole insert 시 필요한 타입
export type NewCompany = typeof companies.$inferInsert;   // Company insert 시 필요한 타입



export async function selectUsersWithCompanyAndRoles(
  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

  // 1) 쿼리 빌더 생성
  const queryBuilder = tx
    .select()
    .from(userView)
    .where(where)
    .orderBy(...(orderBy ?? []))
    .offset(offset)
    .limit(limit)

  const rows = await queryBuilder
  return rows
}

export async function selectUsers(
  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

  // 1) 쿼리 빌더 생성
  const queryBuilder = tx
    .select()
    .from(users)
    .where(where)
    .orderBy(...(orderBy ?? []))
    .offset(offset)
    .limit(limit)

  const rows = await queryBuilder
  return rows
}


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

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

export async function groupByCompany(
  tx: PgTransaction<any, any, any>,
) {
  return tx
    .select({
      companyId: users.companyId,
      count: count(),
    })
    .from(users)
    .groupBy(users.companyId)
    .having(gt(count(), 0));
}

export async function groupByRole(tx: PgTransaction<any, any, any>) {
  return tx
    .select({
      roleId: userRoles.roleId, 
      count: sql<number>`COUNT(*)`.as("count"),
    })
    .from(users)
    .leftJoin(userRoles, eq(userRoles.userId, users.id))
    .leftJoin(roles, eq(roles.id, userRoles.roleId))
    .groupBy(userRoles.roleId, roles.id, roles.name)
    .having(gt(sql<number>`COUNT(*)` /* 또는 count()와 동일 */, 0));
}

export async function insertUser(
  tx: PgTransaction<any, any, any>,
  data: NewUser
) {
  return tx.insert(users).values(data).returning();
}

export async function insertUserRole(
  tx: PgTransaction<any, any, any>,
  data: NewUserRole
) {
  return tx.insert(userRoles).values(data).returning();
}

export async function updateUser(
  tx: PgTransaction<any, any, any>,
  userId: number,
  data: Partial<User>
) {
  return tx
    .update(users)
    .set(data)
    .where(eq(users.id, userId))
    .returning();
}

/** 복수 업데이트 */
export async function updateUsers(
  tx: PgTransaction<any, any, any>,
ids: number[],
data: Partial<User>
) {
return tx
  .update(users)
  .set(data)
  .where(inArray(users.id, ids))
  .returning({ companyId: users.companyId });
}

export async function deleteRolesByUserId(
  tx: PgTransaction<any, any, any>,
  userId: number
) {
  return tx.delete(userRoles).where(eq(userRoles.userId, userId));
}


export async function deleteRolesByUserIds(
  tx: PgTransaction<any, any, any>,
  ids: number[]
) {
  return tx.delete(userRoles).where(inArray(userRoles.userId, ids));
}

export async function deleteUserById(
  tx: PgTransaction<any, any, any>,
  userId: number
) {
  return tx.delete(users).where(eq(users.id, userId));
}


export async function deleteUsersByIds(
  tx: PgTransaction<any, any, any>,
  ids: number[]
) {
  return tx.delete(users).where(inArray(users.id, ids));
}

export async function findAllCompanies(): Promise<Vendor[]> {
  return db.select().from(vendors).orderBy(asc(vendors.vendorName));
}

export async function findAllRoles(): Promise<Role[]> {
  return db.select().from(roles).where(eq(roles.domain ,'partners')).orderBy(asc(roles.name));
}

export const getUserById = async (id: number): Promise<UserView | null> => {
  const userFouned = await db.select().from(userView).where(eq(userView.user_id, id)).execute();
  if (userFouned.length === 0) return null;

  const user = userFouned[0];
  return user
};