summaryrefslogtreecommitdiff
path: root/lib/vendor-document-list/plant/upload/service.ts
blob: 18e6c13222a0e746e8a3cb2d3e0f7595d4bee3c1 (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
import db from "@/db/db"
import { stageSubmissionView, StageSubmissionView } from "@/db/schema"
import { and, asc, desc, eq, or, ilike, isTrue, sql, isNotNull, count } from "drizzle-orm"
import { filterColumns } from "@/lib/filter-columns"
import { GetStageSubmissionsSchema } from "./validation"
import { getServerSession } from 'next-auth/next'
import { authOptions } from '@/app/api/auth/[...nextauth]/route'
import { redirect } from "next/navigation"

// Repository functions (동일)
async function selectStageSubmissions(
  tx: typeof db,
  params: {
    where?: any
    orderBy?: any
    offset?: number
    limit?: number
  }
) {
  const { where, orderBy = [desc(stageSubmissionView.isOverdue)], offset = 0, limit = 10 } = params
  
  const query = tx
    .select()
    .from(stageSubmissionView)
    .$dynamic()
  
  if (where) query.where(where)
  if (orderBy) query.orderBy(...(Array.isArray(orderBy) ? orderBy : [orderBy]))
  query.limit(limit).offset(offset)
  
  return await query
}

async function countStageSubmissions(tx: typeof db, where?: any) {
  const query = tx
    .select({   count: count() })
    .from(stageSubmissionView)
    .$dynamic()
  
  if (where) query.where(where)
  
  const result = await query
  return result[0]?.count ?? 0
}

// Service function with session check
export async function getStageSubmissions(input: GetStageSubmissionsSchema) {
  // Session 체크
  const session = await getServerSession(authOptions)
  if (!session?.user?.id) {
    return {
      success: false,
      error: '로그인이 필요합니다.'
    }
  }
  const vendorId = session.user.companyId // companyId가 vendorId

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

    // Advanced filters
    const advancedWhere = filterColumns({
      table: stageSubmissionView,
      filters: input.filters,
      joinOperator: input.joinOperator,
    })

    // Global search
    let globalWhere
    if (input.search) {
      const s = `%${input.search}%`
      globalWhere = or(
        ilike(stageSubmissionView.documentTitle, s),
        ilike(stageSubmissionView.docNumber, s),
        ilike(stageSubmissionView.vendorDocNumber, s),
        ilike(stageSubmissionView.stageName, s)
        // vendorName 검색 제거 (자기 회사만 보므로)
      )
    }

    // Status filters
    let statusWhere
    if (input.submissionStatus && input.submissionStatus !== "all") {
      switch (input.submissionStatus) {
        case "required":
          statusWhere = eq(stageSubmissionView.requiresSubmission, true)
          break
        case "submitted":
          statusWhere = eq(stageSubmissionView.latestSubmissionStatus, "SUBMITTED")
          break
        case "approved":
          statusWhere = eq(stageSubmissionView.latestReviewStatus, "APPROVED")
          break
        case "rejected":
          statusWhere = eq(stageSubmissionView.latestReviewStatus, "REJECTED")
          break
      }
    }

    // Sync status filter
    let syncWhere
    if (input.syncStatus && input.syncStatus !== "all") {
      if (input.syncStatus === "pending") {
        syncWhere = or(
          eq(stageSubmissionView.latestSyncStatus, "pending"),
          eq(stageSubmissionView.requiresSync, true)
        )
      } else {
        syncWhere = eq(stageSubmissionView.latestSyncStatus, input.syncStatus)
      }
    }

    // Project filter
    let projectWhere = input.projectId ? eq(stageSubmissionView.projectId, input.projectId) : undefined

    // ✅ 벤더 필터 - session의 companyId 사용
    const vendorWhere = eq(stageSubmissionView.vendorId, vendorId)

    const finalWhere = and(
      vendorWhere, // 항상 벤더 필터 적용
      advancedWhere,
      globalWhere,
      statusWhere,
      syncWhere,
      projectWhere
    )

    const orderBy =
      input.sort.length > 0
        ? input.sort.map((item) =>
            item.desc 
              ? desc(stageSubmissionView[item.id]) 
              : asc(stageSubmissionView[item.id])
          )
        : [desc(stageSubmissionView.isOverdue), asc(stageSubmissionView.daysUntilDue)]

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

    const pageCount = Math.ceil(total / input.perPage)

    return { data, pageCount }
  } catch (err) {
    console.error("Error fetching stage submissions:", err)
    return { data: [], pageCount: 0 }
  }
}

// 프로젝트 목록 조회 - 벤더 필터 적용
export async function getProjects() {
    const session = await getServerSession(authOptions)
    if (!session?.user?.id) {
      return {
        success: false,
        error: '로그인이 필요합니다.'
      }
    }
  if (!session?.user?.companyId) {
    return []
  }
  
  const vendorId = session.user.companyId

  const projects = await db
    .selectDistinct({
      id: stageSubmissionView.projectId,
      code: stageSubmissionView.projectCode,
    })
    .from(stageSubmissionView)
    .where(
      and(
        eq(stageSubmissionView.vendorId, vendorId),
        isNotNull(stageSubmissionView.projectId)
      )
    )
    .orderBy(asc(stageSubmissionView.projectCode))

  return projects
}

// 통계 조회 - 벤더별
export async function getSubmissionStats() {
    const session = await getServerSession(authOptions)
    if (!session?.user?.id) {
      return {
        success: false,
        error: '로그인이 필요합니다.'
      }
    }


  if (!session?.user?.companyId) {
    return {
      pending: 0,
      overdue: 0,
      awaitingSync: 0,
      completed: 0,
    }
  }
  
  const vendorId = session.user.companyId

  const stats = await db
    .select({
      pending: sql<number>`count(*) filter (where ${stageSubmissionView.requiresSubmission} = true)::int`,
      overdue: sql<number>`count(*) filter (where ${stageSubmissionView.isOverdue} = true)::int`,
      awaitingSync: sql<number>`count(*) filter (where ${stageSubmissionView.requiresSync} = true)::int`,
      completed: sql<number>`count(*) filter (where ${stageSubmissionView.latestReviewStatus} = 'APPROVED')::int`,
    })
    .from(stageSubmissionView)
    .where(eq(stageSubmissionView.vendorId, vendorId))

  return stats[0] || {
    pending: 0,
    overdue: 0,
    awaitingSync: 0,
    completed: 0,
  }
}