summaryrefslogtreecommitdiff
path: root/hooks/use-swp-documents.ts
blob: dca0ec9ed2f7e6e2da44627c559891cf92210a6f (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
"use client";

import useSWR, { mutate } from "swr";
import {
  getDocumentList,
  getDocumentDetail,
  cancelStandbyFile,
  downloadDocumentFile,
  type DocumentListItem,
  type DocumentDetail,
  type DownloadFileResult,
} from "@/lib/swp/document-service";

// ============================================================================
// SWR Hooks
// ============================================================================

/**
 * 문서 목록 조회 Hook
 * @param projNo 프로젝트 번호
 * @param vndrCd 벤더 코드 (선택)
 */
export function useDocumentList(projNo: string | null, vndrCd?: string) {
  const key = projNo ? ["swp-documents", projNo, vndrCd] : null;

  return useSWR<DocumentListItem[]>(
    key,
    async () => {
      if (!projNo) return [];
      return getDocumentList(projNo, vndrCd);
    },
    {
      revalidateOnFocus: false, // 포커스시 재검증 안함
      revalidateOnReconnect: true, // 재연결시 재검증
      dedupingInterval: 5000, // 5초간 중복 요청 방지
    }
  );
}

/**
 * 문서 상세 조회 Hook (Rev-Activity-File 트리)
 * @param projNo 프로젝트 번호
 * @param docNo 문서 번호
 */
export function useDocumentDetail(
  projNo: string | null,
  docNo: string | null
) {
  const key = projNo && docNo ? ["swp-document-detail", projNo, docNo] : null;

  return useSWR<DocumentDetail | null>(
    key,
    async () => {
      if (!projNo || !docNo) throw new Error("projNo and docNo required");
      return getDocumentDetail(projNo, docNo);
    },
    {
      revalidateOnFocus: false,
      revalidateOnReconnect: true,
      dedupingInterval: 2000, // 2초간 중복 요청 방지
      shouldRetryOnError: false,
    }
  );
}

// ============================================================================
// Mutation Helpers
// ============================================================================

/**
 * 파일 취소
 */
export async function useCancelFile(
  boxSeq: string,
  actvSeq: string,
  userId: string,
  options?: {
    onSuccess?: () => void;
    onError?: (error: Error) => void;
  }
) {
  try {
    await cancelStandbyFile(boxSeq, actvSeq, userId);

    // 문서 상세 캐시 무효화 (재조회)
    await mutate(
      (key: unknown) => Array.isArray(key) && key[0] === "swp-document-detail",
      undefined,
      { revalidate: true }
    );

    // 문서 목록 캐시도 무효화
    await mutate(
      (key: unknown) => Array.isArray(key) && key[0] === "swp-documents",
      undefined,
      { revalidate: true }
    );

    options?.onSuccess?.();
  } catch (error) {
    options?.onError?.(
      error instanceof Error ? error : new Error("파일 취소 실패")
    );
    throw error;
  }
}

/**
 * 파일 다운로드
 */
export async function useDownloadFile(
  projNo: string,
  ownDocNo: string,
  fileName: string,
  options?: {
    onSuccess?: () => void;
    onError?: (error: string) => void;
  }
) {
  try {
    const result: DownloadFileResult = await downloadDocumentFile(
      projNo,
      ownDocNo,
      fileName
    );

    if (!result.success || !result.data) {
      const errorMsg = result.error || "파일 다운로드 실패";
      options?.onError?.(errorMsg);
      throw new Error(errorMsg);
    }

    // Blob을 다운로드
    const blob = new Blob([Buffer.from(result.data)], { type: result.mimeType });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = result.fileName || fileName;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);

    options?.onSuccess?.();
  } catch (error) {
    const errorMsg =
      error instanceof Error ? error.message : "파일 다운로드 실패";
    options?.onError?.(errorMsg);
    throw error;
  }
}

/**
 * 수동 새로고침 헬퍼
 */
export function refreshDocumentList(projNo: string, vndrCd?: string) {
  return mutate(["swp-documents", projNo, vndrCd]);
}

export function refreshDocumentDetail(projNo: string, docNo: string) {
  return mutate(["swp-document-detail", projNo, docNo]);
}