summaryrefslogtreecommitdiff
path: root/lib/swp/table/swp-table-toolbar.tsx
blob: 6858f42e1d6909f63d5e528c5b400a38b7688427 (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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
"use client";

import { useState, useTransition, useMemo } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { Label } from "@/components/ui/label";
import { RefreshCw, Download, Search, X, Check, ChevronsUpDown } from "lucide-react";
import { syncSwpProjectAction, type SwpTableFilters } from "../actions";
import { useToast } from "@/hooks/use-toast";
import { useRouter } from "next/navigation";
import { cn } from "@/lib/utils";

interface SwpTableToolbarProps {
  filters: SwpTableFilters;
  onFiltersChange: (filters: SwpTableFilters) => void;
  projects?: Array<{ PROJ_NO: string; PROJ_NM: string }>;
}

export function SwpTableToolbar({
  filters,
  onFiltersChange,
  projects = [],
}: SwpTableToolbarProps) {
  const [isSyncing, startSync] = useTransition();
  const [localFilters, setLocalFilters] = useState<SwpTableFilters>(filters);
  const { toast } = useToast();
  const router = useRouter();
  const [projectSearchOpen, setProjectSearchOpen] = useState(false);
  const [projectSearch, setProjectSearch] = useState("");

  // 동기화 핸들러
  const handleSync = () => {
    const projectNo = localFilters.projNo;
    
    if (!projectNo) {
      toast({
        variant: "destructive",
        title: "프로젝트 선택 필요",
        description: "동기화할 프로젝트를 먼저 선택해주세요.",
      });
      return;
    }

    startSync(async () => {
      try {
        toast({
          title: "동기화 시작",
          description: `프로젝트 ${projectNo} 동기화를 시작합니다...`,
        });

        const result = await syncSwpProjectAction(projectNo, "V");

        if (result.success) {
          toast({
            title: "동기화 완료",
            description: `문서 ${result.stats.documents.total}개, 파일 ${result.stats.files.total}개 동기화 완료`,
          });
          
          // 페이지 새로고침
          router.refresh();
        } else {
          throw new Error(result.errors.join(", "));
        }
      } catch (error) {
        console.error("동기화 실패:", error);
        toast({
          variant: "destructive",
          title: "동기화 실패",
          description: error instanceof Error ? error.message : "알 수 없는 오류",
        });
      }
    });
  };

  /**
   * 파일 업로드 핸들러
   * 1) 네트워크 드라이브에 정해진 규칙대로, 파일이름 기반으로 파일 업로드하기 (단, cpyCd는 어떻게 해결할지 고민해봐야 함...)
   * 2) 1~N개 파일 받아서, 파일 이름 기준으로 파싱해서 SaveInBoxList API를 통해 업로드 처리
   * 
   * 개발중인 동안은 토스트 반환하도록 처리
  */ 
  const handleUploadFiles = () => {
    toast({
      title: "파일 업로드",
      description: "현재 개발중입니다.",
    });
  }

  // 검색 적용
  const handleSearch = () => {
    onFiltersChange(localFilters);
  };

  // 검색 초기화
  const handleReset = () => {
    const resetFilters: SwpTableFilters = {};
    setLocalFilters(resetFilters);
    onFiltersChange(resetFilters);
  };

  // 프로젝트 필터링
  const filteredProjects = useMemo(() => {
    if (!projectSearch) return projects;
    
    const search = projectSearch.toLowerCase();
    return projects.filter(
      (proj) =>
        proj.PROJ_NO.toLowerCase().includes(search) ||
        proj.PROJ_NM.toLowerCase().includes(search)
    );
  }, [projects, projectSearch]);

  return (
    <div className="space-y-4">
      {/* 상단 액션 바 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <Button
            onClick={handleSync}
            disabled={isSyncing || !localFilters.projNo}
            size="sm"
          >
            <RefreshCw className={`h-4 w-4 mr-2 ${isSyncing ? "animate-spin" : ""}`} />
            {isSyncing ? "동기화 중..." : "SWP 동기화"}
          </Button>
          
        </div>

        <div className="text-sm text-muted-foreground">
          SWP 문서 관리 시스템
        </div>
        <div>
          <Button variant="outline" size="sm" onClick={handleUploadFiles}>
            파일 업로드하기
          </Button>
        </div>
      </div>

      {/* 검색 필터 */}
      <div className="rounded-lg border p-4 space-y-4">
        <div className="flex items-center justify-between">
          <h3 className="text-sm font-semibold">검색 필터</h3>
          <Button
            variant="ghost"
            size="sm"
            onClick={handleReset}
            className="h-8"
          >
            <X className="h-4 w-4 mr-1" />
            초기화
          </Button>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {/* 프로젝트 번호 */}
          <div className="space-y-2">
            <Label htmlFor="projNo">프로젝트 번호</Label>
            {projects.length > 0 ? (
              <Popover open={projectSearchOpen} onOpenChange={setProjectSearchOpen}>
                <PopoverTrigger asChild>
                  <Button
                    variant="outline"
                    role="combobox"
                    aria-expanded={projectSearchOpen}
                    className="w-full justify-between"
                  >
                    {localFilters.projNo ? (
                      <span>
                        {projects.find((p) => p.PROJ_NO === localFilters.projNo)?.PROJ_NO || localFilters.projNo}
                        {" ["}
                        {projects.find((p) => p.PROJ_NO === localFilters.projNo)?.PROJ_NM}
                        {"]"}
                      </span>
                    ) : (
                      <span className="text-muted-foreground">프로젝트 선택</span>
                    )}
                    <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="w-[400px] p-0" align="start">
                  <div className="p-2">
                    <div className="flex items-center border rounded-md px-3">
                      <Search className="h-4 w-4 mr-2 opacity-50" />
                      <Input
                        placeholder="프로젝트 번호 또는 이름으로 검색..."
                        value={projectSearch}
                        onChange={(e) => setProjectSearch(e.target.value)}
                        className="border-0 focus-visible:ring-0 focus-visible:ring-offset-0"
                      />
                    </div>
                  </div>
                  <div className="max-h-[300px] overflow-y-auto">
                    <div className="p-1">
                      <Button
                        variant="ghost"
                        className="w-full justify-start font-normal"
                        onClick={() => {
                          setLocalFilters({ ...localFilters, projNo: undefined });
                          setProjectSearchOpen(false);
                          setProjectSearch("");
                        }}
                      >
                        <Check
                          className={cn(
                            "mr-2 h-4 w-4",
                            !localFilters.projNo ? "opacity-100" : "opacity-0"
                          )}
                        />
                        전체
                      </Button>
                      {filteredProjects.map((proj) => (
                        <Button
                          key={proj.PROJ_NO}
                          variant="ghost"
                          className="w-full justify-start font-normal"
                          onClick={() => {
                            setLocalFilters({ ...localFilters, projNo: proj.PROJ_NO });
                            setProjectSearchOpen(false);
                            setProjectSearch("");
                          }}
                        >
                          <Check
                            className={cn(
                              "mr-2 h-4 w-4",
                              localFilters.projNo === proj.PROJ_NO ? "opacity-100" : "opacity-0"
                            )}
                          />
                          <span className="font-mono text-sm">{proj.PROJ_NO} [{proj.PROJ_NM}]</span>
                        </Button>
                      ))}
                      {filteredProjects.length === 0 && (
                        <div className="py-6 text-center text-sm text-muted-foreground">
                          검색 결과가 없습니다.
                        </div>
                      )}
                    </div>
                  </div>
                </PopoverContent>
              </Popover>
            ) : (
              <Input
                id="projNo"
                placeholder="계약된 프로젝트가 없습니다"
                value={localFilters.projNo || ""}
                onChange={(e) =>
                  setLocalFilters({ ...localFilters, projNo: e.target.value })
                }
                disabled
                className="bg-muted"
              />
            )}
          </div>

          {/* 문서 번호 */}
          <div className="space-y-2">
            <Label htmlFor="docNo">문서 번호</Label>
            <Input
              id="docNo"
              placeholder="문서 번호 검색"
              value={localFilters.docNo || ""}
              onChange={(e) =>
                setLocalFilters({ ...localFilters, docNo: e.target.value })
              }
            />
          </div>

          {/* 문서 제목 */}
          <div className="space-y-2">
            <Label htmlFor="docTitle">문서 제목</Label>
            <Input
              id="docTitle"
              placeholder="제목 검색"
              value={localFilters.docTitle || ""}
              onChange={(e) =>
                setLocalFilters({ ...localFilters, docTitle: e.target.value })
              }
            />
          </div>

          {/* 패키지 번호 */}
          <div className="space-y-2">
            <Label htmlFor="pkgNo">패키지</Label>
            <Input
              id="pkgNo"
              placeholder="패키지 번호"
              value={localFilters.pkgNo || ""}
              onChange={(e) =>
                setLocalFilters({ ...localFilters, pkgNo: e.target.value })
              }
            />
          </div>

          {/* 업체 코드 */}
          <div className="space-y-2">
            <Label htmlFor="vndrCd">업체 코드</Label>
            <Input
              id="vndrCd"
              placeholder="업체 코드"
              value={localFilters.vndrCd || ""}
              onChange={(e) =>
                setLocalFilters({ ...localFilters, vndrCd: e.target.value })
              }
            />
          </div>

          {/* 스테이지 */}
          <div className="space-y-2">
            <Label htmlFor="stage">스테이지</Label>
            <Select
              value={localFilters.stage || "__all__"}
              onValueChange={(value) =>
                setLocalFilters({ ...localFilters, stage: value === "__all__" ? undefined : value })
              }
            >
              <SelectTrigger id="stage">
                <SelectValue placeholder="전체" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="__all__">전체</SelectItem>
                <SelectItem value="IFA">IFA</SelectItem>
                <SelectItem value="IFC">IFC</SelectItem>
                <SelectItem value="AFC">AFC</SelectItem>
                <SelectItem value="BFC">BFC</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>

        <div className="flex justify-end">
          <Button onClick={handleSearch} size="sm">
            <Search className="h-4 w-4 mr-2" />
            검색
          </Button>
        </div>
      </div>
    </div>
  );
}