summaryrefslogtreecommitdiff
path: root/lib/approval-line/table/create-approval-line-sheet.tsx
blob: b7878f71e3d35283b3c8b85a62bcda71a71818d4 (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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
"use client"

import * as React from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { Button } from "@/components/ui/button"
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Textarea } from "@/components/ui/textarea"
import { Separator } from "@/components/ui/separator"
import { toast } from "sonner"
import { Loader2 } from "lucide-react"
import { createApprovalLine } from "../service"
import { type ApprovalLineFormData, ApprovalLineSchema } from "../validations"
import { ApprovalLineSelector } from "@/components/knox/approval/ApprovalLineSelector"
import { OrganizationManagerSelector, type OrganizationManagerItem } from "@/components/common/organization/organization-manager-selector"
import { useSession } from "next-auth/react"
import { getActiveApprovalTemplateCategories, type ApprovalTemplateCategory } from "@/lib/approval-template/category-service"

interface CreateApprovalLineSheetProps {
  open: boolean
  onOpenChange: (open: boolean) => void
}

export function CreateApprovalLineSheet({ open, onOpenChange }: CreateApprovalLineSheetProps) {
  const { data: session } = useSession();
  const [isSubmitting, setIsSubmitting] = React.useState(false);
  const [categories, setCategories] = React.useState<ApprovalTemplateCategory[]>([]);
  const [isLoadingCategories, setIsLoadingCategories] = React.useState(false);

  // 고유 ID 생성 함수 (조직 관리자 추가 시 사용)
  const generateUniqueId = () => `apln-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;

  const form = useForm<ApprovalLineFormData>({
    resolver: zodResolver(ApprovalLineSchema),
    defaultValues: {
      name: "",
      category: "",
      description: "",
      aplns: [
        // 기안자는 항상 첫 번째로 고정 (플레이스홀더)
        {
          id: generateUniqueId(),
          epId: undefined,
          userId: undefined,
          emailAddress: undefined,
          name: "기안자",
          deptName: undefined,
          role: "0",
          seq: "0",
          opinion: "",
        },
      ],
    },
  });

  const aplns = form.watch("aplns");

  // 카테고리 목록 로드
  React.useEffect(() => {
    let active = true;
    const loadCategories = async () => {
      if (!open) return;

      setIsLoadingCategories(true);
      try {
        const data = await getActiveApprovalTemplateCategories();
        if (active) {
          setCategories(data);
        }
      } catch (error) {
        console.error('카테고리 로드 실패:', error);
      } finally {
        if (active) setIsLoadingCategories(false);
      }
    };
    loadCategories();
    return () => {
      active = false;
    };
  }, [open]);

  // 조직 관리자 추가 (공용 선택기 외 보조 입력 경로)
  const addOrganizationManagers = (managers: OrganizationManagerItem[]) => {
    const next = [...aplns];
    const uniqueSeqs = Array.from(new Set(next.map((a) => parseInt(a.seq))));
    const maxSeq = uniqueSeqs.length ? Math.max(...uniqueSeqs) : 0;

    managers.forEach((manager, idx) => {
      const exists = next.findIndex((a) => a.epId === manager.managerId);
      if (exists === -1) {
        const newSeqNum = Math.max(1, maxSeq + 1 + idx);
        const newSeq = newSeqNum.toString();
        next.push({
          id: generateUniqueId(),
          epId: manager.managerId,
          userId: undefined,
          emailAddress: undefined,
          name: manager.managerName,
          deptName: manager.departmentName,
          role: "1",
          seq: newSeq,
          opinion: "",
        });
      }
    });

    form.setValue("aplns", next, { shouldDirty: true });
  };

  const onSubmit = async (data: ApprovalLineFormData) => {
    setIsSubmitting(true);
    try {
      if (!session?.user?.id) {
        toast.error("로그인이 필요합니다.");
        return;
      }

      await createApprovalLine({
        name: data.name,
        category: data.category || undefined,
        description: data.description,
        aplns: data.aplns,
        createdBy: Number(session.user.id),
      });

      toast.success("결재선이 성공적으로 생성되었습니다.");
      form.reset();
      onOpenChange(false);
    } catch {
      toast.error("결재선 생성 중 오류가 발생했습니다.");
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent className="w-full sm:max-w-4xl overflow-y-auto">
        <SheetHeader>
          <SheetTitle>결재선 생성</SheetTitle>
          <SheetDescription>
            새로운 결재선을 생성합니다. 결재자를 추가하고 순서를 조정할 수 있습니다.
          </SheetDescription>
        </SheetHeader>

        <div className="mt-6">
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
              {/* 기본 정보 */}
              <div className="space-y-4">
                <FormField
                  control={form.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>결재선 이름 *</FormLabel>
                      <FormControl>
                        <Input placeholder="결재선 이름을 입력하세요" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="category"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>카테고리</FormLabel>
                      <Select
                        value={field.value || "none"}
                        onValueChange={(value) => field.onChange(value === "none" ? "" : value)}
                        disabled={isLoadingCategories}
                      >
                        <SelectTrigger>
                          <SelectValue placeholder={isLoadingCategories ? "카테고리 로드 중..." : "카테고리를 선택하세요"} />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="none">선택 안함</SelectItem>
                          {categories
                            .sort((a, b) => a.sortOrder - b.sortOrder)
                            .map((category) => (
                              <SelectItem key={`category-${category.id}`} value={category.name}>
                                {category.name}
                                {category.description && (
                                  <span className="text-muted-foreground ml-2">({category.description})</span>
                                )}
                              </SelectItem>
                            ))}
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="description"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>설명</FormLabel>
                      <FormControl>
                        <Textarea placeholder="결재선에 대한 설명을 입력하세요" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              <Separator />

              {/* 결재 경로 */}
              <div className="space-y-4">
                <h3 className="text-lg font-semibold">결재 경로</h3>

                <ApprovalLineSelector
                  value={aplns}
                  onChange={(next) => form.setValue("aplns", next, { shouldDirty: true })}
                  placeholder="결재자를 검색하세요..."
                  domainFilter={{ type: "exclude", domains: ["partners"] }}
                  maxSelections={10}
                />

                {/* 조직 관리자 추가 (선택 사항) */}
                {/* <div className="p-4 border border-dashed border-gray-300 rounded-lg">
                  <div className="mb-2">
                    <label className="text-sm font-medium text-gray-700">조직 관리자로 추가</label>
                    <p className="text-xs text-gray-500">조직별 책임자를 검색하여 추가하세요</p>
                  </div>
                  <OrganizationManagerSelector
                    selectedManagers={[]}
                    onManagersChange={addOrganizationManagers}
                    placeholder="조직 관리자를 검색하세요..."
                    maxSelections={10}
                  />
                </div> */}
              </div>

              <Separator />

              {/* 제출 버튼 */}
              <div className="flex justify-end space-x-3">
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => onOpenChange(false)}
                  disabled={isSubmitting}
                >
                  취소
                </Button>
                <Button type="submit" disabled={isSubmitting}>
                  {isSubmitting ? (
                    <>
                      <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                      생성 중...
                    </>
                  ) : (
                    "결재선 생성"
                  )}
                </Button>
              </div>
            </form>
          </Form>
        </div>
      </SheetContent>
    </Sheet>
  )
}