summaryrefslogtreecommitdiff
path: root/lib/users/service.ts
diff options
context:
space:
mode:
Diffstat (limited to 'lib/users/service.ts')
-rw-r--r--lib/users/service.ts70
1 files changed, 69 insertions, 1 deletions
diff --git a/lib/users/service.ts b/lib/users/service.ts
index 0d0121b3..ad01c22a 100644
--- a/lib/users/service.ts
+++ b/lib/users/service.ts
@@ -9,10 +9,12 @@ import { saveDocument } from '../storage';
import { GetUsersSchema } from '../admin-users/validations';
import { revalidateTag, unstable_cache, unstable_noStore } from 'next/cache';
import { filterColumns } from '../filter-columns';
-import { asc, desc, ilike, inArray, and, gte, lte, not, or, eq } from "drizzle-orm";
import { countUsers, 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 } from "drizzle-orm";
interface AssignUsersArgs {
roleId: number
@@ -415,6 +417,72 @@ export async function getUsersAll(input: GetUsersSchema, domain: string) {
}
+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{