summaryrefslogtreecommitdiff
path: root/components/login/partner-auth-form.tsx
blob: ebd2219c4bbf2a80f3805d3704efc1af2850831a (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
"use client"

import * as React from "react"
import { useToast } from "@/hooks/use-toast"
import { useRouter, useParams, usePathname } from "next/navigation"
import { useTranslation } from "@/i18n/client"
import Link from "next/link"

import { Button } from "@/components/ui/button"
import { Label } from "@/components/ui/label"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { GlobeIcon, ChevronDownIcon, Loader, Ship, LogIn, InfoIcon, HelpCircle } from "lucide-react"
import { languages } from "@/config/language"
import { cn } from "@/lib/utils"
import { buttonVariants } from "@/components/ui/button"
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip"
import {
  Alert,
  AlertDescription,
  AlertTitle,
} from "@/components/ui/alert"

import { checkJoinPortal } from "@/lib/vendors/service"
import Image from "next/image"
// ↑ 실제 경로 맞춤 수정 (ex: "@/app/[lng]/actions/joinPortal" 등)

export function CompanyAuthForm({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
  const [isLoading, setIsLoading] = React.useState<boolean>(false)
  const [showInfoBanner, setShowInfoBanner] = React.useState<boolean>(true)
  const [taxIdWarning, setTaxIdWarning] = React.useState<boolean>(false)
  const router = useRouter()
  const { toast } = useToast()

  const params = useParams() || {};
  const pathname = usePathname() || '';

  const lng = params.lng as string
  const { t, i18n } = useTranslation(lng, "login")

  // 컴포넌트 마운트 시 초기 상태 설정
  React.useEffect(() => {
    setTaxIdWarning(false)
  }, [])

  const handleChangeLanguage = (lang: string) => {
    const segments = pathname.split("/")
    segments[1] = lang
    router.push(segments.join("/"))
  }

  const currentLanguageText =
    i18n.language === "ko"
      ? t("languages.korean")
        : t("languages.english")

  // 로그인 페이지로 이동
  const goToLogin = () => {
    router.push(`/${lng}/partners`);
  }

  // 사업자등록번호 검증 함수
  const validateTaxId = (value: string) => {
    // - 제거하고 숫자만 추출
    const numericValue = value.replace(/-/g, '').replace(/\D/g, '');
    // 한국 기업의 사업자등록번호는 10자리 숫자
    const isValidLength = numericValue.length === 10;
    setTaxIdWarning(!isValidLength && numericValue.length > 0);
    return isValidLength;
  }

  // ---------------------------
  // 1) onSubmit -> 서버 액션 호출
  // ---------------------------
  async function onSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault()
    setIsLoading(true)

    const formData = new FormData(event.currentTarget)
    const taxID = formData.get("taxid")?.toString().trim()

    if (!taxID) {
      toast({
        variant: "destructive",
        title: "오류",
        description: "Tax ID를 입력해주세요.",
      })
      setIsLoading(false)
      return
    }

    // 제출 시에도 검증 수행
    validateTaxId(taxID)

    try {
      // ---------------------------
      // 2) 서버 액션 호출
      // ---------------------------
      const result = await checkJoinPortal(taxID)

      if (result.success) {
        toast({
          variant: "default",
          title: "성공",
          description: "가입 신청이 가능합니다",
        })
        // 가입 가능 → signup 페이지 이동
        router.push(`/partners/signup?taxID=${taxID}`)
      } else {
        // 이미 등록된 기업인 경우 - 로그인으로 안내하는 토스트와 함께 추가 액션 제공
        toast({
          variant: "destructive",
          title: "가입이 진행 중이거나 완료된 회사",
          description: `${result.data} 에 연락하여 계정 생성 요청을 하시기 바랍니다.`,
        })

        // 로그인 액션 버튼이 있는 알림 표시
        setTimeout(() => {
          toast({
            title: "이미 등록된 회사이신가요?",
            description: "로그인 페이지로 이동하여 계정에 접속하세요.",
            action: (
              <Button variant="outline" onClick={goToLogin} className="bg-blue-50 border-blue-300">
                <LogIn className="mr-2 h-4 w-4" />
                로그인하기
              </Button>
            ),
          })
        }, 1000);
      }
    } catch (error: unknown) {
      console.error('Form submission error:', error)
      toast({
        variant: "destructive",
        title: "오류",
        description: "서버 액션 호출에 실패했습니다. 잠시 후 다시 시도해주세요.",
      })
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div className="container relative flex h-screen flex-col items-center justify-center md:grid lg:max-w-none lg:grid-cols-2 lg:px-0">

      {/* Left BG 이미지 영역 */}

      <div className="flex flex-col w-full h-screen lg:p-2">
        {/* Top bar */}
        <div className="flex items-center justify-between p-4">
          <div className="flex items-center space-x-2">
            <Ship className="w-4 h-4" />
            <span className="text-md font-bold">eVCP</span>
          </div>

          {/* 로그인 버튼 가시성 개선 */}
          <Link
            href={`/${lng}/partners`}
            className={cn(
              buttonVariants({ variant: "outline" }),
              "border-blue-500 text-blue-600 hover:bg-blue-50"
            )}
          >
            <LogIn className="mr-2 h-4 w-4" />
            {t("login") || "로그인"}
          </Link>
        </div>
        <div className="flex-1 flex items-center justify-center">
          <div className="mx-auto w-full flex flex-col space-y-6 sm:w-[400px]">
            {/* 정보 알림 배너 - 업체 등록과 로그인의 관계 설명 */}
            {showInfoBanner && (
              <Alert className="bg-blue-50 border-blue-200">
                <InfoIcon className="h-4 w-4 text-blue-600" />
                <AlertTitle className="text-blue-700 mt-1">
                  {t("registrationInfoTitle") || "업체 등록 신청 안내"}
                </AlertTitle>
                <AlertDescription className="text-blue-600">
                  {t("registrationInfoDescription") || "이미 등록된 업체의 직원이신가요? 상단의 로그인 버튼을 눌러 로그인하세요. 새로운 업체 등록을 원하시면 아래 양식을 작성해주세요."}
                </AlertDescription>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => setShowInfoBanner(false)}
                  className="absolute top-2 right-4 h-6 w-6 p-0"
                >
                  ✕
                </Button>
              </Alert>
            )}

            <div className="flex flex-col space-y-2 text-center">
              <h1 className="text-2xl font-semibold tracking-tight">
                {t("heading") || "업체 등록 신청"}
              </h1>
              <p className="text-sm text-muted-foreground">
                {t("subheading") || "귀사의 사업자 등록 번호를 입력하여 등록을 시작하세요"}
              </p>
            </div>

            <div className={cn("grid gap-6", className)} {...props}>
              <form onSubmit={onSubmit}>
                <div className="grid gap-4">
                  <div className="grid gap-2">
                    <div className="flex items-center justify-between">
                      <Label htmlFor="taxid">
                        사업자등록번호 / Tax ID
                      </Label>
                      <TooltipProvider>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <Button variant="ghost" size="icon" className="h-6 w-6 p-0">
                              <HelpCircle className="h-4 w-4 text-muted-foreground" />
                              <span className="sr-only">Help</span>
                            </Button>
                          </TooltipTrigger>
                          <TooltipContent>
                            <p className="max-w-xs">
                              {t("taxIdTooltip") || "법인/개인사업자 사업자등록번호를 '-' 포함하여 입력해주세요 (예: 123-45-67890)"}
                            </p>
                          </TooltipContent>
                        </Tooltip>
                      </TooltipProvider>
                    </div>
                    <input
                      id="taxid"
                      name="taxid"
                      placeholder="000-00-00000"
                      type="text"
                      autoCapitalize="none"
                      autoComplete="off"
                      autoCorrect="off"
                      disabled={isLoading}
                      onChange={(e) => validateTaxId(e.target.value)}
                      className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:opacity-50"
                    />
                    <p className="text-xs text-muted-foreground">
                      {t("taxIdHint") || "사업자 등록 번호는 업체 인증에 사용됩니다"}
                    </p>
                    {taxIdWarning && (
                      <div className="flex items-center gap-2 p-2 bg-orange-50 border border-orange-200 rounded-md">
                        <InfoIcon className="h-4 w-4 text-orange-600 flex-shrink-0" />
                        <p className="text-xs text-orange-700">
                          {t("taxIdWarning") || "한국 기업의 사업자등록번호는 10자리 숫자입니다. 외국 기업의 경우 다른 형식으로 입력 가능합니다."}
                        </p>
                      </div>
                    )}
                  </div>
                  <Button type="submit" disabled={isLoading} variant="samsung">
                    {isLoading && <Loader className="mr-2 h-4 w-4 animate-spin" />}
                    {t("joinButton") || "업체 등록 시작하기"}
                  </Button>

                  {/* 로그인 안내 링크 추가 */}
                  <div className="text-center">
                    <Button
                      variant="link"
                      className="text-blue-600 hover:text-blue-800 text-sm"
                      onClick={goToLogin}
                      type="button"
                    >
                      {t("alreadyRegistered") || "이미 등록된 업체이신가요? 로그인하기"}
                    </Button>
                  </div>

                  {/* 언어 선택 Dropdown */}
                  <div className="mx-auto">
                    <DropdownMenu>
                      <DropdownMenuTrigger asChild>
                        <Button variant="ghost" className="flex items-center gap-2">
                          <GlobeIcon className="h-4 w-4" />
                          <span>{currentLanguageText}</span>
                          <ChevronDownIcon className="h-4 w-4" />
                        </Button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent align="end">
                        <DropdownMenuRadioGroup
                          value={i18n.language}
                          onValueChange={(value) => handleChangeLanguage(value)}
                        >
                          {languages.map((v) => (
                            <DropdownMenuRadioItem key={v.value} value={v.value}>
                              {t(v.labelKey)}
                            </DropdownMenuRadioItem>
                          ))}
                        </DropdownMenuRadioGroup>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </div>
                </div>
              </form>
            </div>
            <p className="px-8 text-center text-sm text-muted-foreground">
              {/* 1118 구매 파워유저 요구사항에 따라 삭제 */}
              {/* {t("agreement")}{" "}
              <Link
                href={`/${lng}/privacy`}  // 개인정보처리방침만 남김
                className="underline underline-offset-4 hover:text-primary"
              >
                {t("privacyPolicy")}
              </Link> */}
              {/* {t("privacyAgreement")}.  */}
            </p>
          </div>
        </div>

      </div>


      {/* Right Content */}
      <div className="relative hidden h-full flex-col p-10 text-white dark:border-r md:flex">
        {/* Image 컴포넌트로 대체 */}
        <div className="absolute inset-0">
          <Image
            src="/background-images/yard.webp"
            alt="Background image"
            fill
            priority
            sizes="(max-width: 1024px) 100vw, 50vw"
            className="object-cover"
          />
        </div>
        <div className="relative z-10 mt-auto">
          <blockquote className="space-y-2">
            <p className="text-sm">&ldquo;{t("blockquote")}&rdquo;</p>
            {/* <footer className="text-sm">SHI</footer> */}
          </blockquote>
        </div>
      </div>

    </div>
  )
}