summaryrefslogtreecommitdiff
path: root/lib/poa/service.ts
blob: a11cbdd80423f55b82b5372a34ea59d21b59ec4c (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
"use server";

import db from "@/db/db";
import { GetChangeOrderSchema } from "./validations";
import { unstable_cache } from "@/lib/unstable-cache";
import { filterColumns } from "@/lib/filter-columns";
import {
  asc,
  desc,
  ilike,
  and,
  or,
  count,
} from "drizzle-orm";

import {
  poaDetailView,
} from "@/db/schema/contract";

/**
 * POA 목록 조회
 */
export async function getChangeOrders(input: GetChangeOrderSchema) {
  return unstable_cache(
    async () => {
      try {
        const offset = (input.page - 1) * input.perPage;

        // 1. Build where clause
        let advancedWhere;
        try {
          advancedWhere = filterColumns({
            table: poaDetailView,
            filters: input.filters,
            joinOperator: input.joinOperator,
          });
        } catch (whereErr) {
          console.error("Error building advanced where:", whereErr);
          advancedWhere = undefined;
        }

        let globalWhere;
        if (input.search) {
          try {
            const s = `%${input.search}%`;
            globalWhere = or(
              ilike(poaDetailView.contractNo, s),
              ilike(poaDetailView.originalContractName, s),
              ilike(poaDetailView.projectCode, s),
              ilike(poaDetailView.projectName, s),
              ilike(poaDetailView.vendorName, s)
            );
          } catch (searchErr) {
            console.error("Error building search where:", searchErr);
            globalWhere = undefined;
          }
        }

        // 2. Combine where clauses
        let finalWhere;
        if (advancedWhere && globalWhere) {
          finalWhere = and(advancedWhere, globalWhere);
        } else {
          finalWhere = advancedWhere || globalWhere;
        }

        // 3. Build order by
        let orderBy;
        try {
          orderBy =
            input.sort.length > 0
              ? input.sort.map((item) =>
                  item.desc
                    ? desc(poaDetailView[item.id])
                    : asc(poaDetailView[item.id])
                )
              : [desc(poaDetailView.createdAt)];
        } catch (orderErr) {
          console.error("Error building order by:", orderErr);
          orderBy = [desc(poaDetailView.createdAt)];
        }

        // 4. Execute queries
        let data = [];
        let total = 0;

        try {
          const queryBuilder = db.select().from(poaDetailView);

          if (finalWhere) {
            queryBuilder.where(finalWhere);
          }

          queryBuilder.orderBy(...orderBy);
          queryBuilder.offset(offset).limit(input.perPage);

          data = await queryBuilder;

          const countBuilder = db
            .select({ count: count() })
            .from(poaDetailView);

          if (finalWhere) {
            countBuilder.where(finalWhere);
          }

          const countResult = await countBuilder;
          total = countResult[0]?.count || 0;
        } catch (queryErr) {
          console.error("Query execution failed:", queryErr);
          throw queryErr;
        }

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

        return { data, pageCount };
      } catch (err) {
        console.error("Error in getChangeOrders:", err);
        if (err instanceof Error) {
          console.error("Error message:", err.message);
          console.error("Error stack:", err.stack);
        }
        return { data: [], pageCount: 0 };
      }
    },
    [JSON.stringify(input)],
    {
      revalidate: 3600,
      tags: [`poa`],
    }
  )();
}