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
|
"use client";
import {
Box,
Button,
FormControl,
FormLabel,
TextField,
Typography,
Select,
MenuItem,
SelectChangeEvent,
} from "@mui/material";
import Header from "../lib/camera/component/hedear";
import odooApi from "../lib/api/odooApi";
import { getAuth, setAuth } from "../lib/api/auth";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { setCookie } from "cookies-next";
// Ambil tipe parameter untuk setAuth agar sesuai tepat dengan definisinya
type AuthProps = Parameters<typeof setAuth>[0];
type LoginStatus = { code?: number; description?: string };
type LoginResult = {
is_auth?: boolean;
reason?: "NOT_FOUND" | "NOT_ACTIVE" | string;
user?: unknown; // akan dicast ke AuthProps jika lolos
};
type LoginResponse = { status?: LoginStatus; result?: LoginResult };
type Role = "driver" | "dispatch";
const Login = () => {
const router = useRouter();
// state input
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [role, setRole] = useState<"" | Role>("");
// state error helperText
const [emailError, setEmailError] = useState(false);
const [emailErrorMessage, setEmailErrorMessage] = useState("");
const [passwordError, setPasswordError] = useState(false);
const [passwordErrorMessage, setPasswordErrorMessage] = useState("");
const [roleError, setRoleError] = useState(false);
const [roleErrorMessage, setRoleErrorMessage] = useState("");
const [loading, setLoading] = useState(false);
useEffect(() => {
const token = getAuth();
if (token) router.push("/");
}, [router]);
const validateInputs = (e: string, p: string, r: "" | Role) => {
let ok = true;
if (!e || !/\S+@\S+\.\S+/.test(e)) {
setEmailError(true);
setEmailErrorMessage("Please enter a valid email address.");
ok = false;
} else {
setEmailError(false);
setEmailErrorMessage("");
}
if (!p || p.length < 6) {
setPasswordError(true);
setPasswordErrorMessage("Password must be at least 6 characters long.");
ok = false;
} else {
setPasswordError(false);
setPasswordErrorMessage("");
}
if (!r) {
setRoleError(true);
setRoleErrorMessage("Please select a role.");
ok = false;
} else {
setRoleError(false);
setRoleErrorMessage("");
}
return ok;
};
const handleRoleChange = (e: SelectChangeEvent) => {
const val = e.target.value as Role | "";
setRole(val);
if (val) {
setRoleError(false);
setRoleErrorMessage("");
}
};
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
// Ambil dari FormData agar sesuai dengan form yang disubmit
const fd = new FormData(event.currentTarget);
const rawEmail = fd.get("email");
const rawPassword = fd.get("password");
const rawRole = fd.get("role");
const emailStr = typeof rawEmail === "string" ? rawEmail.trim() : "";
const passwordStr = typeof rawPassword === "string" ? rawPassword : "";
const roleStr: "" | Role = rawRole === "driver" || rawRole === "dispatch" ? rawRole : "";
if (!validateInputs(emailStr, passwordStr, roleStr)) return;
try {
setLoading(true);
// Kirim web_role juga (opsional, kalau backend abaikan juga tidak masalah)
const res = (await odooApi("POST", "/api/v1/user/login", {
email: emailStr,
password: passwordStr,
web_role: roleStr,
})) as unknown as LoginResponse;
const auth = res?.result;
if (res?.status?.code === 200 && auth?.is_auth) {
if (auth.user && typeof auth.user === "object") {
setAuth(auth.user as AuthProps);
}
// Simpan pilihan role agar bisa dipakai di halaman lain
setCookie("web_role", roleStr, { path: "/" });
router.push("/");
return;
}
// Tangani alasan gagal umum
switch (auth?.reason) {
case "NOT_FOUND":
alert("Email tidak ditemukan");
break;
case "NOT_ACTIVE":
alert("Akun anda belum aktif");
break;
default:
alert(res?.status?.description || "Login gagal. Periksa email/password.");
}
} catch (error) {
console.error(error);
alert("Gagal login, silahkan coba lagi");
} finally {
setLoading(false);
}
};
return (
<div className="bg-[#fafeff] h-screen overflow-auto">
<Header />
<div className="py-4 px-4 sm:px-96 pt-20">
<div className="bg-white py-6 px-4 sm:px-96 shadow-md rounded-sm">
<Typography
component="h1"
variant="h4"
sx={{ width: "100%", fontSize: "clamp(2rem, 10vw, 2.15rem)", mb: 4 }}
>
Sign in
</Typography>
<Box
component="form"
onSubmit={handleSubmit}
noValidate
sx={{ display: "flex", flexDirection: "column", width: "100%", gap: 2 }}
>
<FormControl>
<FormLabel htmlFor="email">Email</FormLabel>
<TextField
error={emailError}
helperText={emailErrorMessage}
id="email"
type="email"
name="email"
placeholder="your@email.com"
autoComplete="email"
autoFocus
required
fullWidth
variant="outlined"
color={emailError ? "error" : "primary"}
size="small"
inputProps={{ "aria-label": "email" }}
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</FormControl>
<FormControl>
<Box sx={{ display: "flex", justifyContent: "space-between" }}>
<FormLabel htmlFor="password">Password</FormLabel>
</Box>
<TextField
error={passwordError}
helperText={passwordErrorMessage}
name="password"
placeholder="••••••"
type="password"
id="password"
autoComplete="current-password"
required
fullWidth
variant="outlined"
color={passwordError ? "error" : "primary"}
size="small"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</FormControl>
{/* Role selection */}
<FormControl error={roleError}>
<FormLabel htmlFor="role">Role</FormLabel>
<Select
id="role"
name="role"
value={role}
onChange={handleRoleChange}
displayEmpty
size="small"
>
<MenuItem value="">
<em>Pilih role</em>
</MenuItem>
<MenuItem value="driver">Driver</MenuItem>
<MenuItem value="dispatch">Dispatch</MenuItem>
</Select>
{roleError && (
<Typography variant="caption" color="error" sx={{ mt: 0.5 }}>
{roleErrorMessage || "Please select a role."}
</Typography>
)}
</FormControl>
<Button type="submit" fullWidth variant="contained" disabled={loading}>
{loading ? "Loading..." : "Sign in"}
</Button>
</Box>
</div>
</div>
</div>
);
};
export default Login;
|