summaryrefslogtreecommitdiff
path: root/lib/vendor-investigation/validations.ts
blob: 29fb46cb278cb87891db77022efcc9b65d033650 (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
import {
    createSearchParamsCache,
    parseAsArrayOf,
    parseAsInteger,
    parseAsString,
    parseAsStringEnum,
} from "nuqs/server"
import * as z from "zod"
import { getFiltersStateParser, getSortingStateParser } from "@/lib/parsers"
import { vendorInvestigationsView } from "@/db/schema"

export const searchParamsInvestigationCache = createSearchParamsCache({
    // Common flags
    flags: parseAsArrayOf(z.enum(["advancedTable", "floatingBar"])).withDefault([]),

    // Paging
    page: parseAsInteger.withDefault(1),
    perPage: parseAsInteger.withDefault(10),

    // Sorting - adjusting for vendorInvestigationsView
    sort: getSortingStateParser<typeof vendorInvestigationsView.$inferSelect>().withDefault([
        { id: "createdAt", desc: true },
    ]),

    // Advanced filter
    filters: getFiltersStateParser().withDefault([]),
    joinOperator: parseAsStringEnum(["and", "or"]).withDefault("and"),

    // Global search
    search: parseAsString.withDefault(""),

    // -----------------------------------------------------------------
    // Fields specific to vendor investigations
    // -----------------------------------------------------------------

    // investigationStatus: PLANNED, IN_PROGRESS, COMPLETED, CANCELED, RESULT_SENT
    investigationStatus: parseAsStringEnum(["PLANNED", "IN_PROGRESS", "COMPLETED", "CANCELED", "RESULT_SENT"]),

    // In case you also want to filter by vendorName, vendorCode, etc.
    vendorName: parseAsString.withDefault(""),
    vendorCode: parseAsString.withDefault(""),

    // If you need to filter by vendor status (e.g., PQ_SUBMITTED, ACTIVE, etc.),
    // you can include it here too. Example:
    // vendorStatus: parseAsStringEnum([
    //   "PENDING_REVIEW",
    //   "IN_REVIEW",
    //   "REJECTED",
    //   "IN_PQ",
    //   "PQ_SUBMITTED",
    //   "PQ_FAILED",
    //   "PQ_APPROVED",
    //   "APPROVED",
    //   "ACTIVE",
    //   "INACTIVE",
    //   "BLACKLISTED",
    // ]).optional(),
})

// Finally, export the type you can use in your server action:
export type GetVendorsInvestigationSchema = Awaited<ReturnType<typeof searchParamsInvestigationCache.parse>>

// 실사 진행 관리용 스키마
export const updateVendorInvestigationProgressSchema = z
  .object({
    investigationId: z.number({
      required_error: "Investigation ID is required",
    }),
    investigationAddress: z
      .string({ required_error: "실사 주소는 필수입니다." })
      .min(1, "실사 주소는 필수입니다."),
    investigationMethod: z.enum([
      "PURCHASE_SELF_EVAL",
      "DOCUMENT_EVAL",
      "PRODUCT_INSPECTION",
      "SITE_VISIT_EVAL",
    ], { required_error: "실사 방법은 필수입니다." }),

    // 날짜 필드들
    forecastedAt: z.union([
      z.date(),
      z.string().transform((str) => (str ? new Date(str) : undefined)),
    ]),

    confirmedAt: z.union([
      z.date(),
      z.string().transform((str) => (str ? new Date(str) : undefined)),
    ], { required_error: "실사 계획 확정일은 필수입니다." }),
  })
  .superRefine((data, ctx) => {
    // 방문/제품 평가일 경우 forecastedAt은 필수 아님, 그 외에는 필수
    const method = data.investigationMethod
    const requiresForecast = method !== "PRODUCT_INSPECTION" && method !== "SITE_VISIT_EVAL"
    if (requiresForecast && !data.forecastedAt) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        path: ["forecastedAt"],
        message: "실사 수행 예정일은 필수입니다.",
      })
    }

    // 날짜 순서 검증: forecastedAt과 confirmedAt 간의 관계 검증
    if (data.forecastedAt && data.confirmedAt) {
      const forecastedDate = new Date(data.forecastedAt);
      const confirmedDate = new Date(data.confirmedAt);

      if (confirmedDate < forecastedDate) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          path: ["confirmedAt"],
          message: "실사 계획 확정일은 실사 수행 예정일보다 과거일 수 없습니다.",
        });
      }
    }
  })

export type UpdateVendorInvestigationProgressSchema = z.infer<typeof updateVendorInvestigationProgressSchema>

// 실사 결과 입력용 스키마
export const updateVendorInvestigationResultSchema = z.object({
  investigationId: z.number({
    required_error: "Investigation ID is required",
  }),

  // 날짜 필드들
  completedAt: z.union([
    z.date(),
    z.string().transform((str) => str ? new Date(str) : undefined)
  ]),

  // 실사의뢰일 (날짜 검증을 위해 추가)
  requestedAt: z.union([
    z.date(),
    z.string().transform((str) => str ? new Date(str) : undefined)
  ]).optional(),

  evaluationScore: z.number()
    .int("평가 점수는 정수여야 합니다.")
    .min(0, "평가 점수는 0점 이상이어야 합니다.")
    .max(100, "평가 점수는 100점 이하여야 합니다."),
  evaluationResult: z.enum(["APPROVED", "SUPPLEMENT", "SUPPLEMENT_REINSPECT", "SUPPLEMENT_DOCUMENT", "REJECTED", "RESULT_SENT"]),
  investigationNotes: z.string().max(1000, "QM 의견은 1000자 이내로 입력해주세요.").optional(),
  // attachments는 별도의 API로 업로드되므로 이 스키마에서는 optional
  attachments: z.array(z.any()).optional(),
}).superRefine((data, ctx) => {
  // 날짜 검증: 실제 실사일이 실사의뢰일보다 과거가 되지 않도록 검증
  if (data.requestedAt && data.completedAt) {
    const requestedDate = new Date(data.requestedAt);
    const completedDate = new Date(data.completedAt);

    if (completedDate < requestedDate) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        path: ["completedAt"],
        message: "실제 실사일은 실사의뢰일보다 과거일 수 없습니다.",
      });
    }
  }
})

export type UpdateVendorInvestigationResultSchema = z.infer<typeof updateVendorInvestigationResultSchema>

// 기존 호환성을 위한 통합 스키마
export const updateVendorInvestigationSchema = z.object({
  investigationId: z.number({
    required_error: "Investigation ID is required",
  }),
  investigationStatus: z.enum(["PLANNED", "IN_PROGRESS", "COMPLETED", "CANCELED", "SUPPLEMENT_REQUIRED", "RESULT_SENT"], {
    required_error: "실사 상태를 선택해주세요.",
  }),
  investigationAddress: z.string().optional(),
  investigationMethod: z.enum(["PURCHASE_SELF_EVAL", "DOCUMENT_EVAL", "PRODUCT_INSPECTION", "SITE_VISIT_EVAL"]).optional(),

  // 날짜 필드들
  forecastedAt: z.union([
    z.date(),
    z.string().transform((str) => str ? new Date(str) : undefined)
  ]).optional(),

  requestedAt: z.union([
    z.date(),
    z.string().transform((str) => str ? new Date(str) : undefined)
  ]).optional(),

  confirmedAt: z.union([
    z.date(),
    z.string().transform((str) => str ? new Date(str) : undefined)
  ]).optional(),

  completedAt: z.union([
    z.date(),
    z.string().transform((str) => str ? new Date(str) : undefined)
  ]).optional(),

  evaluationScore: z.number()
    .int("평가 점수는 정수여야 합니다.")
    .min(0, "평가 점수는 0점 이상이어야 합니다.")
    .max(100, "평가 점수는 100점 이하여야 합니다.")
    .optional(),
  evaluationResult: z.enum(["APPROVED", "SUPPLEMENT", "SUPPLEMENT_REINSPECT", "SUPPLEMENT_DOCUMENT", "REJECTED", "RESULT_SENT"]).optional(),
  investigationNotes: z.string().max(1000, "QM 의견은 1000자 이내로 입력해주세요.").optional(),
  attachments: z.array(z.any()).min(1, "최소 1개의 첨부파일이 필요합니다."), // File 업로드 필수
}).superRefine((data, ctx) => {
  // 날짜 검증: 실사의뢰일(requestedAt)이 있는 경우 다른 날짜들이 실사의뢰일보다 과거가 되지 않도록 검증
  if (data.requestedAt) {
    const requestedDate = new Date(data.requestedAt);

    // 실사수행/계획일(forecastedAt) 검증
    if (data.forecastedAt) {
      const forecastedDate = new Date(data.forecastedAt);
      if (forecastedDate < requestedDate) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          path: ["forecastedAt"],
          message: "실사 수행 예정일은 실사의뢰일보다 과거일 수 없습니다.",
        });
      }
    }

    // 실사 계획 확정일(confirmedAt) 검증
    if (data.confirmedAt) {
      const confirmedDate = new Date(data.confirmedAt);
      if (confirmedDate < requestedDate) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          path: ["confirmedAt"],
          message: "실사 계획 확정일은 실사의뢰일보다 과거일 수 없습니다.",
        });
      }
    }

    // 실제 실사일(completedAt) 검증
    if (data.completedAt) {
      const completedDate = new Date(data.completedAt);
      if (completedDate < requestedDate) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          path: ["completedAt"],
          message: "실제 실사일은 실사의뢰일보다 과거일 수 없습니다.",
        });
      }
    }
  }
})

export type UpdateVendorInvestigationSchema = z.infer<typeof updateVendorInvestigationSchema>