396 lines
13 KiB
TypeScript
396 lines
13 KiB
TypeScript
"use client";
|
|
import React, { useState } from "react";
|
|
import Link from "next/link";
|
|
import Cookies from "js-cookie";
|
|
import { useRouter } from "next/navigation";
|
|
import withReactContent from "sweetalert2-react-content";
|
|
import Swal from "sweetalert2";
|
|
import { Input } from "../ui/input";
|
|
import { Button } from "../ui/button";
|
|
import { Label } from "../ui/label";
|
|
import { RadioGroup, RadioGroupItem } from "../ui/radio-group";
|
|
import { registerTenant } from "@/service/auth";
|
|
|
|
// ✅ import services
|
|
import { requestOTP, createUser } from "@/service/auth";
|
|
import { EyeFilledIcon, EyeSlashFilledIcon } from "../icons";
|
|
|
|
export default function SignUp() {
|
|
const router = useRouter();
|
|
const MySwal = withReactContent(Swal);
|
|
|
|
const [step, setStep] = useState<"login" | "otp" | "form">("login");
|
|
const [role, setRole] = useState("umum");
|
|
const [email, setEmail] = useState("");
|
|
const [otp, setOtp] = useState(["", "", "", "", "", ""]);
|
|
const [membership, setMembership] = useState("");
|
|
const [certNumber, setCertNumber] = useState("");
|
|
const [membershipType, setMembershipType] = useState("");
|
|
const [nrp, setNrp] = useState("");
|
|
const [firstName, setFirstName] = useState("");
|
|
const [lastName, setLastName] = useState("");
|
|
const [whatsapp, setWhatsapp] = useState("");
|
|
const [namaTenant, setNamaTenant] = useState("");
|
|
const [tenantPassword, setTenantPassword] = useState("");
|
|
const [confirmTenantPassword, setConfirmTenantPassword] = useState("");
|
|
const [firstNameKontributor, setFirstNameKontributor] = useState("");
|
|
const [lastNameKontributor, setLastNameKontributor] = useState("");
|
|
const [whatsappKontributor, setWhatsappKontributor] = useState("");
|
|
const [namaPerusahaan, setNamaPerusahaan] = useState("");
|
|
const [kategoriPerusahaan, setKategoriPerusahaan] = useState("");
|
|
const [kontributorPassword, setKontributorPassword] = useState("");
|
|
const [confirmKontributorPassword, setConfirmKontributorPassword] =
|
|
useState("");
|
|
const [isLoading, setIsLoading] = useState(false);
|
|
const [formErrors, setFormErrors] = useState<any>({});
|
|
// di atas, bareng useState lainnya
|
|
const [isVisible, setIsVisible] = useState(false);
|
|
const [isVisibleSetup, setIsVisibleSetup] = useState([false, false]);
|
|
|
|
// fungsi helper
|
|
const toggleVisibility = () => setIsVisible(!isVisible);
|
|
|
|
// data user lengkap
|
|
const [fullname, setFullname] = useState("");
|
|
const [username, setUsername] = useState("");
|
|
const [phoneNumber, setPhoneNumber] = useState("");
|
|
const [address, setAddress] = useState("");
|
|
const [dateOfBirth, setDateOfBirth] = useState("");
|
|
const [genderType, setGenderType] = useState("male");
|
|
const [password, setPassword] = useState("");
|
|
const [workType, setWorkType] = useState("");
|
|
|
|
// 🔹 Handle OTP Request
|
|
const handleSendOtp = async (e: React.FormEvent) => {
|
|
e.preventDefault();
|
|
|
|
if (!email) {
|
|
MySwal.fire("Error", "Email wajib diisi", "error");
|
|
return;
|
|
}
|
|
|
|
try {
|
|
const res = await requestOTP({ email, name: fullname || email });
|
|
|
|
if (!res?.error) {
|
|
MySwal.fire("Sukses", "OTP berhasil dikirim ke email anda", "success");
|
|
setStep("otp");
|
|
} else {
|
|
MySwal.fire("Gagal", res.message || "Gagal mengirim OTP", "error");
|
|
}
|
|
} catch (err) {
|
|
console.error("Error send otp:", err);
|
|
MySwal.fire("Error", "Terjadi kesalahan server", "error");
|
|
}
|
|
|
|
// If role is tenant, handle tenant registration directly
|
|
if (role === "tenant") {
|
|
handleTenantRegistration(e);
|
|
return;
|
|
}
|
|
|
|
// For other roles, proceed with OTP flow
|
|
setStep("otp");
|
|
};
|
|
|
|
// 🔹 Handle OTP Verification (dummy → lanjut form)
|
|
const handleVerifyOtp = async (e: React.FormEvent) => {
|
|
e.preventDefault();
|
|
const code = otp.join("");
|
|
if (code.length !== 6) {
|
|
MySwal.fire("Error", "OTP harus 6 digit", "error");
|
|
return;
|
|
}
|
|
// TODO: ganti dengan verifyOTP API
|
|
MySwal.fire("Sukses", "OTP diverifikasi!", "success");
|
|
setStep("form"); // lanjut ke form lengkap
|
|
};
|
|
|
|
// 🔹 Handle Register ke API /users
|
|
const handleRegister = async (e: React.FormEvent) => {
|
|
e.preventDefault();
|
|
|
|
const payload = {
|
|
address,
|
|
clientId: "web-app", // contoh default
|
|
dateOfBirth,
|
|
email,
|
|
fullName: fullname, // 🔥 fix disini (bukan fullname)
|
|
genderType,
|
|
identityGroup: "",
|
|
identityGroupNumber: "",
|
|
identityNumber: "",
|
|
identityType: "",
|
|
lastEducation: "",
|
|
password,
|
|
phoneNumber,
|
|
userLevelId: 1,
|
|
userRoleId: 1,
|
|
username,
|
|
workType,
|
|
};
|
|
|
|
try {
|
|
const res = await createUser(payload);
|
|
if (!res?.error) {
|
|
MySwal.fire("Sukses", "Akun berhasil dibuat!", "success");
|
|
router.push("/login");
|
|
} else {
|
|
MySwal.fire("Error", res.message || "Gagal membuat akun", "error");
|
|
}
|
|
} catch (err) {
|
|
console.error("Register error:", err);
|
|
MySwal.fire("Error", "Terjadi kesalahan server", "error");
|
|
}
|
|
};
|
|
|
|
const handleOtpChange = (index: number, value: string) => {
|
|
if (!/^[0-9]?$/.test(value)) return;
|
|
const newOtp = [...otp];
|
|
newOtp[index] = value;
|
|
setOtp(newOtp);
|
|
const nextInput = document.getElementById(`otp-${index + 1}`);
|
|
if (value && nextInput) nextInput.focus();
|
|
};
|
|
|
|
// Form validation functions
|
|
const validateEmail = (email: string) => {
|
|
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
return emailRegex.test(email);
|
|
};
|
|
|
|
const validatePhone = (phone: string) => {
|
|
const phoneRegex = /^[0-9+\-\s()]+$/;
|
|
return phoneRegex.test(phone) && phone.length >= 10;
|
|
};
|
|
|
|
const validatePassword = (password: string) => {
|
|
return password.length >= 8;
|
|
};
|
|
|
|
const validateTenantForm = () => {
|
|
const errors: any = {};
|
|
|
|
if (!firstName.trim()) {
|
|
errors.firstName = "First name is required";
|
|
}
|
|
|
|
if (!lastName.trim()) {
|
|
errors.lastName = "Last name is required";
|
|
}
|
|
|
|
if (!email.trim()) {
|
|
errors.email = "Email is required";
|
|
} else if (!validateEmail(email)) {
|
|
errors.email = "Please enter a valid email address";
|
|
}
|
|
|
|
if (!whatsapp.trim()) {
|
|
errors.whatsapp = "WhatsApp number is required";
|
|
} else if (!validatePhone(whatsapp)) {
|
|
errors.whatsapp = "Please enter a valid phone number";
|
|
}
|
|
|
|
if (!namaTenant.trim()) {
|
|
errors.namaTenant = "Tenant name is required";
|
|
}
|
|
|
|
if (!tenantPassword) {
|
|
errors.tenantPassword = "Password is required";
|
|
} else if (!validatePassword(tenantPassword)) {
|
|
errors.tenantPassword = "Password must be at least 8 characters";
|
|
}
|
|
|
|
if (!confirmTenantPassword) {
|
|
errors.confirmTenantPassword = "Please confirm your password";
|
|
} else if (tenantPassword !== confirmTenantPassword) {
|
|
errors.confirmTenantPassword = "Passwords do not match";
|
|
}
|
|
|
|
setFormErrors(errors);
|
|
return Object.keys(errors).length === 0;
|
|
};
|
|
|
|
const handleTenantRegistration = async (e: React.FormEvent) => {
|
|
e.preventDefault();
|
|
|
|
if (!validateTenantForm()) {
|
|
return;
|
|
}
|
|
|
|
setIsLoading(true);
|
|
setFormErrors({});
|
|
|
|
try {
|
|
const registrationData = {
|
|
adminUser: {
|
|
address: "Jakarta", // Default address as per API requirement
|
|
email: email,
|
|
fullname: `${firstName} ${lastName}`,
|
|
password: tenantPassword,
|
|
phoneNumber: whatsapp,
|
|
username: `${firstName}-${lastName}`, // Using firstName + lastName as username
|
|
},
|
|
client: {
|
|
clientType: "sub_client", // Hardcoded as per API requirement
|
|
name: namaTenant,
|
|
parentClientId: "78356d32-52fa-4dfc-b836-6cebf4e3eead", // Hardcoded as per API requirement
|
|
},
|
|
};
|
|
|
|
const response = await registerTenant(registrationData);
|
|
|
|
if (response.error) {
|
|
MySwal.fire({
|
|
title: "Registration Failed",
|
|
text: response.message || "An error occurred during registration",
|
|
icon: "error",
|
|
confirmButtonText: "OK",
|
|
});
|
|
} else {
|
|
MySwal.fire({
|
|
title: "Registration Successful",
|
|
text: "Your tenant account has been created successfully!",
|
|
icon: "success",
|
|
confirmButtonText: "OK",
|
|
}).then(() => {
|
|
// Redirect to login page or dashboard
|
|
router.push("/auth");
|
|
});
|
|
}
|
|
} catch (error) {
|
|
console.error("Registration error:", error);
|
|
MySwal.fire({
|
|
title: "Registration Failed",
|
|
text: "An unexpected error occurred. Please try again.",
|
|
icon: "error",
|
|
confirmButtonText: "OK",
|
|
});
|
|
} finally {
|
|
setIsLoading(false);
|
|
}
|
|
};
|
|
|
|
return (
|
|
<div className="min-h-screen flex">
|
|
{/* Left Side Logo */}
|
|
<div className="hidden lg:flex lg:w-1/2 bg-white relative overflow-hidden">
|
|
<div className="relative z-10 flex items-center justify-center w-full p-12">
|
|
<div className="text-center">
|
|
<Link href={"/"}>
|
|
<img src="/Group.png" alt="Logo" className="max-w-2xl h-auto" />
|
|
</Link>
|
|
<div className="mt-8 text-black">
|
|
<h2 className="text-2xl font-bold mb-2">Portal NetIdhub</h2>
|
|
<p className="text-sm opacity-80">Platform beyond classic</p>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Right Side Form */}
|
|
<div className="w-full lg:w-1/2 flex items-center justify-center p-8">
|
|
<div className="w-full max-w-md">
|
|
{/* Step 1: Kirim OTP */}
|
|
{step === "login" && (
|
|
<form onSubmit={handleSendOtp} className="space-y-4">
|
|
<Input
|
|
type="text"
|
|
placeholder="Nama Lengkap"
|
|
value={fullname}
|
|
onChange={(e) => setFullname(e.target.value)}
|
|
/>
|
|
<Input
|
|
type="email"
|
|
required
|
|
placeholder="Email"
|
|
value={email}
|
|
onChange={(e) => setEmail(e.target.value)}
|
|
/>
|
|
<Button type="submit" className="w-full bg-[#B89445] text-white">
|
|
Kirim OTP
|
|
</Button>
|
|
</form>
|
|
)}
|
|
|
|
{/* Step 2: Verifikasi OTP */}
|
|
{step === "otp" && (
|
|
<form onSubmit={handleVerifyOtp} className="space-y-4 text-center">
|
|
<h3 className="text-base font-semibold">Masukkan OTP</h3>
|
|
<div className="flex justify-between mb-4">
|
|
{otp.map((value, index) => (
|
|
<input
|
|
key={index}
|
|
id={`otp-${index}`}
|
|
type="text"
|
|
maxLength={1}
|
|
value={value}
|
|
onChange={(e) => handleOtpChange(index, e.target.value)}
|
|
className="w-10 h-12 text-center border rounded-md"
|
|
/>
|
|
))}
|
|
</div>
|
|
<Button type="submit" className="w-full bg-[#B89445] text-white">
|
|
Lanjut
|
|
</Button>
|
|
</form>
|
|
)}
|
|
|
|
{/* Step 3: Form Lengkap */}
|
|
{step === "form" && (
|
|
<form onSubmit={handleRegister} className="space-y-4">
|
|
<Input
|
|
type="text"
|
|
placeholder="Username"
|
|
value={username}
|
|
onChange={(e) => setUsername(e.target.value)}
|
|
/>
|
|
<Input
|
|
type="text"
|
|
placeholder="Nomor HP"
|
|
value={phoneNumber}
|
|
onChange={(e) => setPhoneNumber(e.target.value)}
|
|
/>
|
|
<Input
|
|
type="text"
|
|
placeholder="Alamat"
|
|
value={address}
|
|
onChange={(e) => setAddress(e.target.value)}
|
|
/>
|
|
<Input
|
|
type="date"
|
|
placeholder="Tanggal Lahir"
|
|
value={dateOfBirth}
|
|
onChange={(e) => setDateOfBirth(e.target.value)}
|
|
/>
|
|
<select
|
|
value={genderType}
|
|
onChange={(e) => setGenderType(e.target.value)}
|
|
className="w-full border rounded-md p-2"
|
|
>
|
|
<option value="male">Laki-laki</option>
|
|
<option value="female">Perempuan</option>
|
|
</select>
|
|
<Input
|
|
type="password"
|
|
placeholder="Password"
|
|
value={password}
|
|
onChange={(e) => setPassword(e.target.value)}
|
|
/>
|
|
<Input
|
|
type="text"
|
|
placeholder="Jenis Pekerjaan"
|
|
value={workType}
|
|
onChange={(e) => setWorkType(e.target.value)}
|
|
/>
|
|
<Button type="submit" className="w-full bg-green-600 text-white">
|
|
Daftar
|
|
</Button>
|
|
</form>
|
|
)}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|