Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -236,8 +236,8 @@ function LocalProvider({ children }) {

// =====================================================================
// Chế độ API (VITE_USE_API=true)
// Luồng backend đã có → gọi API. Luồng backend chưa có (trả kho, lịch trả kho,
// thông báo, đổi tên hiển thị) → lưu trong trình duyệt theo từng tài khoản ("overlay").
// Hồ sơ, mật khẩu, hỗ trợ và trả kho gọi API thật.
// Thông báo phía khách và dữ liệu phụ dùng overlay riêng theo từng tài khoản.
// =====================================================================
function readSession() {
const s = readJson(SESSION_KEY);
Expand Down Expand Up @@ -308,7 +308,7 @@ function ApiProvider({ children }) {
const [reservationDetails, contractDetails, ticketDetails] = await Promise.all([
Promise.all(reservations.filter((r) => r.status !== "CANCELLED").map((r) => api.reservation(r.reservationId).catch(() => null))),
Promise.all(contracts.map((c) => api.contract(c.contractId).catch(() => ({ ...c, payments: [], renewals: [] })))),
Promise.all(tickets.map((t) => api.ticket(t.ticketId).catch(() => t))),
Promise.all(tickets.map((t) => api.ticket(t.ticketId))),
]);
if (!refs.current.session) return;
const next = {
Expand Down Expand Up @@ -352,19 +352,33 @@ function ApiProvider({ children }) {
[endSession],
);

const loadProfile = useCallback(async () => {
const current = refs.current.session;
if (!current) return;
const profile = await api.getProfile();
if (refs.current.session?.token !== current.token) return;
const next = { ...refs.current.session, user: { ...refs.current.session.user, ...profile } };
refs.current.session = next;
writeJson(SESSION_KEY, next);
setSession(next);
// Tên lấy từ máy chủ; bỏ tên cũ chỉ lưu trong trình duyệt.
updateOverlay(o => ({ ...o, name: null }));
}, [updateOverlay]);

const loadAll = useCallback(async () => {
setLoadError(null);
try {
await loadCatalog();
if (refs.current.session) {
await loadProfile();
if (isAdminRoles(refs.current.session.roles) || isOpsRoles(refs.current.session.roles) || isBusinessRoles(refs.current.session.roles)) setRemote(EMPTY_REMOTE);
else await loadCustomer();
}
} catch (e) {
if (e instanceof ApiError && e.status === 401) endSession("expired");
else setLoadError(e?.message || "Không tải được dữ liệu.");
}
}, [loadCatalog, loadCustomer, endSession]);
}, [loadCatalog, loadCustomer, loadProfile, endSession]);

useEffect(() => {
loadAll();
Expand Down Expand Up @@ -402,12 +416,13 @@ function ApiProvider({ children }) {
refs.current.overlay = saved;
setOverlay(saved);
setSession(next);
await loadProfile();
if (isAdminRoles(next.roles) || isOpsRoles(next.roles) || isBusinessRoles(next.roles)) {
refs.current.remote = EMPTY_REMOTE;
setRemote(EMPTY_REMOTE);
} else await loadCustomer();
},
[loadCustomer],
[loadCustomer, loadProfile],
);

const login = useCallback(
Expand Down Expand Up @@ -607,20 +622,25 @@ function ApiProvider({ children }) {
return { ok: true };
}
case "CHANGE_PASSWORD": {
await api.changePassword({ currentPassword: p.current_password, newPassword: p.new_password });
notify("Đã đổi mật khẩu thành công.");
try {
await api.changePassword({ currentPassword: p.current, newPassword: p.next });
} catch (e) {
if (e instanceof ApiError && e.data?.code === "BAD_PASSWORD") return fail(e.message, "BAD_PASSWORD");
throw e;
}
return { ok: true };
}
case "UPDATE_NAME": {
const profile = await api.updateProfile({ fullName: p.name, phone: session?.user?.phone || null });
if (session) {
const updatedUser = { ...session.user, fullName: profile.fullName };
const updatedSession = { ...session, user: updatedUser };
const profile = await api.updateProfile({ fullName: String(p.name || "").trim() });
const current = refs.current.session;
if (current) {
const updatedUser = { ...current.user, ...profile };
const updatedSession = { ...current, user: updatedUser };
writeJson(SESSION_KEY, updatedSession);
refs.current.session = updatedSession;
setSession(updatedSession);
}
runLocal(type, p);
updateOverlay(o => ({ ...o, name: null }));
return { ok: true, name: profile.fullName };
}
case "REQUEST_RETURN": {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useState } from "react";
import React, { useRef, useState } from "react";
import { Button, Dialog, Field, PageHeader } from "../../../shared/components/UI.jsx";
import { go } from "../../../app/router.js";
import { maskPhone } from "../../../shared/utils/format.js";
Expand All @@ -12,13 +12,28 @@ export default function CustomerProfilePage() {
const [pw, setPw] = useState({ current: "", next: "", confirm: "" });
const [pwErrors, setPwErrors] = useState({});
const [dialog, setDialog] = useState(null);
const [savingName, setSavingName] = useState(false);
const [savingPassword, setSavingPassword] = useState(false);
const namePending = useRef(false);
const passwordPending = useRef(false);

const saveName = async (e) => {
e.preventDefault();
const res = await dispatch("UPDATE_NAME", { name });
if (!res.ok) return setNameError(res.error);
setName(res.name);
setDialog({ title: "Đã lưu tên", message: "Tên hiển thị của bạn đã được cập nhật." });
if (namePending.current) return;
const fullName = name.trim();
if (fullName.length < 2 || fullName.length > 100) return setNameError("Tên hiển thị phải từ 2 đến 100 ký tự.");
namePending.current = true;
setSavingName(true);
setNameError("");
try {
const res = await dispatch("UPDATE_NAME", { name: fullName });
if (!res.ok) return setNameError(res.error);
setName(res.name);
setDialog({ title: "Đã lưu tên", message: "Tên hiển thị của bạn đã được cập nhật." });
} finally {
namePending.current = false;
setSavingName(false);
}
};

const setPwField = (k, v) => {
Expand All @@ -27,6 +42,7 @@ export default function CustomerProfilePage() {
};
const changePassword = async (e) => {
e.preventDefault();
if (passwordPending.current) return;
const err = {};
if (!pw.current) err.current = "Vui lòng nhập mật khẩu hiện tại.";
if (!pw.next) err.next = "Vui lòng nhập mật khẩu mới.";
Expand All @@ -38,10 +54,18 @@ export default function CustomerProfilePage() {
err.confirmHint = "Nhập lại đúng mật khẩu mới để tiếp tục.";
}
if (Object.keys(err).length) return setPwErrors(err);
const res = await dispatch("CHANGE_PASSWORD", { current: pw.current, next: pw.next });
if (!res.ok) return setPwErrors(res.code === "BAD_PASSWORD" ? { current: res.error } : res.code === "UNSUPPORTED" ? { form: res.error } : { next: res.error });
setPw({ current: "", next: "", confirm: "" });
setDialog({ title: "Đổi mật khẩu thành công", message: "Mật khẩu mới của bạn đã được cập nhật." });
passwordPending.current = true;
setSavingPassword(true);
setPwErrors({});
try {
const res = await dispatch("CHANGE_PASSWORD", { current: pw.current, next: pw.next });
if (!res.ok) return setPwErrors(res.code === "BAD_PASSWORD" ? { current: res.error } : { form: res.error });
setPw({ current: "", next: "", confirm: "" });
setDialog({ title: "Đổi mật khẩu thành công", message: "Mật khẩu mới của bạn đã được cập nhật." });
} finally {
passwordPending.current = false;
setSavingPassword(false);
}
};

return (
Expand All @@ -51,7 +75,7 @@ export default function CustomerProfilePage() {
<form className="panel form-card" onSubmit={saveName} noValidate>
<h2>Thông tin cá nhân</h2>
<Field label="Tên tài khoản (hiển thị)" error={nameError}>
<input autoComplete="name" maxLength={100} value={name} onChange={(e) => { setName(e.target.value); setNameError(""); }} />
<input autoComplete="name" maxLength={100} disabled={savingName} value={name} onChange={(e) => { setName(e.target.value); setNameError(""); }} />
</Field>
<Field label="Email">
<input readOnly value={user.email} />
Expand All @@ -61,24 +85,24 @@ export default function CustomerProfilePage() {
</Field>
<h3>Thông báo</h3>
<p className="muted">Nhận nhắc lịch hẹn, hạn hợp đồng và cập nhật thanh toán trong ứng dụng.</p>
<Button type="submit">Lưu tên tài khoản</Button>
<Button type="submit" disabled={savingName}>{savingName ? "Đang lưu…" : "Lưu tên tài khoản"}</Button>
</form>

<form className="panel form-card" onSubmit={changePassword} noValidate>
<h2>Đổi mật khẩu</h2>
<Field label="Mật khẩu hiện tại" error={pwErrors.current}>
<input type="password" autoComplete="current-password" value={pw.current} onChange={(e) => setPwField("current", e.target.value)} />
<input type="password" autoComplete="current-password" disabled={savingPassword} value={pw.current} onChange={(e) => setPwField("current", e.target.value)} />
</Field>
<Field label="Mật khẩu mới" error={pwErrors.next}>
<input type="password" autoComplete="new-password" value={pw.next} onChange={(e) => setPwField("next", e.target.value)} />
<input type="password" autoComplete="new-password" disabled={savingPassword} value={pw.next} onChange={(e) => setPwField("next", e.target.value)} />
</Field>
<Field label="Xác nhận mật khẩu mới" error={pwErrors.confirm}>
<input type="password" autoComplete="new-password" value={pw.confirm} onChange={(e) => setPwField("confirm", e.target.value)} />
<input type="password" autoComplete="new-password" disabled={savingPassword} value={pw.confirm} onChange={(e) => setPwField("confirm", e.target.value)} />
</Field>
{pwErrors.confirmHint && <p className="field__error field__error--plain">{pwErrors.confirmHint}</p>}
{!supports.changePassword && <p className="hint">Đổi mật khẩu đang tạm ngưng trên hệ thống. Liên hệ quản trị viên SafeSpace nếu cần đặt lại mật khẩu.</p>}
{pwErrors.form && <p className="field__error field__error--plain">{pwErrors.form}</p>}
<Button type="submit" disabled={!supports.changePassword}>Cập nhật mật khẩu</Button>
<Button type="submit" disabled={!supports.changePassword || savingPassword}>{savingPassword ? "Đang cập nhật…" : "Cập nhật mật khẩu"}</Button>
</form>
</div>
<Button
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ export function composeData({ catalog, remote, overlay: ov, session, timeoutSeco
username: session.user.username,
full_name: overlay.name || session.user.fullName,
email: session.user.email,
phone: overlay.phone || "",
phone: session.user.phone ?? overlay.phone ?? "",
}
: null;
const base = {
Expand Down
Loading