update change pincode

This commit is contained in:
wayanrivan
2025-04-28 16:41:42 +07:00
parent 1f1679c185
commit 8bdad1bb3f
3 changed files with 141 additions and 49 deletions

View File

@ -2,6 +2,7 @@ interface apiConfigProps {
service_dashboard: string;
service_customer: string;
service_master_data: string;
service_master_data2: string;
service_transaction: string;
service_wallet: string;
transaction: string;
@ -18,7 +19,7 @@ const apiConfig: apiConfigProps = {
// service_dashboard: `${API_URL}${import.meta.env.VITE_ENV != 'development' ? '/d' : ''}`,
service_dashboard: `${API_URL}/d`,
service_customer: `${API_URL}/c`,
// service_master_data: `${API_URL}/m`
service_master_data2: `${API_URL}/m`,
service_master_data: `${API_URL}/t`,
service_transaction: `${API_URL}/tt`,
service_wallet: `${API_URL}/w`,

View File

@ -1,34 +1,45 @@
import { useState, useContext, useCallback, MouseEvent } from 'react';
import { AccountUserProfileContext } from '../hooks';
import { toast } from 'sonner';
import { useAuthContext } from '@/auth';
import { getAuth,useAuthContext } from '@/auth';
import { KeenIcon } from '@/components';
import clsx from 'clsx';
type PasswordType = 'password';
type PasswordType = 'current' | 'new' | 'retype';
const PinCode = () => {
const { setPincode } = useContext(AccountUserProfileContext);
const { getUser } = useAuthContext();
const [currentPincode, setCurrentPincode] = useState('');
const [newPincode, setNewPincode] = useState('');
const [retypePincode, setRetypePincode] = useState('');
const [errorRetype, setErrorRetype] = useState('');
const [isSubmitting, setIsSubmitting] = useState(false);
const [showPassword, setShowPassword] = useState({
password: false,
current: false,
new: false,
retype: false,
});
const handleResetPassword = useCallback(async () => {
const user: any = await getUser();
if (newPincode !== retypePincode) {
toast.error('New Pin Code and Retype Pin Code do not match.');
setErrorRetype('New Pin Code and Retype Pin Code do not match.');
return;
}
setIsSubmitting(true);
try {
await setPincode({
currentpincode: currentPincode,
newpincode: newPincode,
retypepincode: retypePincode,
});
setCurrentPincode('');
setNewPincode('');
toast.success('Pin code updated successfully');
setRetypePincode('');
setErrorRetype(''); // Clear error after success
} catch (error: any) {
const errorMessage =
error?.response?.data?.message ||
@ -38,14 +49,26 @@ const PinCode = () => {
} finally {
setIsSubmitting(false);
}
}, [newPincode, setPincode, getUser]);
}, [currentPincode, newPincode, retypePincode, setPincode]);
const isButtonDisabled = isSubmitting || !newPincode;
const isButtonDisabled = isSubmitting || !currentPincode || !newPincode || !retypePincode;
const togglePassword = useCallback((event: MouseEvent<HTMLButtonElement>, key: PasswordType) => {
const togglePassword = useCallback(
(event: MouseEvent<HTMLButtonElement>, key: PasswordType) => {
event.preventDefault();
setShowPassword((prev) => ({ ...prev, [key]: !prev[key] }));
}, []);
},
[]
);
const handleRetypeChange = (value: string) => {
setRetypePincode(value);
if (newPincode && value && newPincode !== value) {
setErrorRetype('New Pin Code and Retype Pin Code do not match.');
} else {
setErrorRetype('');
}
};
return (
<div className="card pb-2.5">
@ -53,30 +76,97 @@ const PinCode = () => {
<h3 className="card-title">Pin Code</h3>
</div>
<div className="card-body grid gap-5">
{/* Current Pin Code */}
<div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
<label className="form-label max-w-56">New Pin Code</label>
<label className="form-label max-w-56">Current Pin Code</label>
<div className="input relative">
<input
className="form-control pr-10" // untuk kasih jarak buat tombol mata
placeholder="New Pin Code"
value={newPincode}
onChange={(e) => setNewPincode(e.target.value)} // ✅ fix
className="form-control pr-10"
placeholder="Current Pin Code"
value={currentPincode}
onChange={(e) => setCurrentPincode(e.target.value)}
disabled={isSubmitting}
type={showPassword.password ? 'text' : 'password'}
type={showPassword.current ? 'text' : 'password'}
/>
<button
className="btn btn-icon absolute right-2 top-1/2 transform -translate-y-1/2"
onClick={(e) => togglePassword(e, 'password')}
onClick={(e) => togglePassword(e, 'current')}
type="button"
>
<KeenIcon
icon={showPassword.password ? 'eye-slash' : 'eye'}
icon={showPassword.current ? 'eye-slash' : 'eye'}
className="text-gray-500"
/>
</button>
</div>
</div>
{/* New Pin Code */}
<div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
<label className="form-label max-w-56">New Pin Code</label>
<div className="input relative">
<input
className="form-control pr-10"
placeholder="New Pin Code"
value={newPincode}
onChange={(e) => {
setNewPincode(e.target.value);
// Kalau retype sudah diisi, cek lagi error
if (retypePincode) {
if (e.target.value !== retypePincode) {
setErrorRetype('New Pin Code and Retype Pin Code do not match.');
} else {
setErrorRetype('');
}
}
}}
disabled={isSubmitting}
type={showPassword.new ? 'text' : 'password'}
/>
<button
className="btn btn-icon absolute right-2 top-1/2 transform -translate-y-1/2"
onClick={(e) => togglePassword(e, 'new')}
type="button"
>
<KeenIcon
icon={showPassword.new ? 'eye-slash' : 'eye'}
className="text-gray-500"
/>
</button>
</div>
</div>
{/* Retype Pin Code */}
<div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
<label className="form-label max-w-56">Retype Pin Code</label>
<div className="input relative w-full">
<input
className={`form-control pr-10 ${errorRetype ? 'border-red-500' : ''}`}
placeholder="Retype Pin Code"
value={retypePincode}
onChange={(e) => handleRetypeChange(e.target.value)}
disabled={isSubmitting}
type={showPassword.retype ? 'text' : 'password'}
/>
<button
className="btn btn-icon absolute right-2 top-1/2 transform -translate-y-1/2"
onClick={(e) => togglePassword(e, 'retype')}
type="button"
>
<KeenIcon
icon={showPassword.retype ? 'eye-slash' : 'eye'}
className="text-gray-500"
/>
</button>
</div>
</div>
{/* Error message under Retype */}
{errorRetype && (
<div className="text-red-500 text-sm -mt-4 ml-[calc(14rem+10px)]">{errorRetype}</div>
)}
{/* Submit button */}
<div className="flex justify-end">
<button
className="btn btn-primary"

View File

@ -2,8 +2,7 @@ import React, { createContext, useState } from 'react';
import { apiConfig } from '@/config/api.config';
import { useCallApi } from '@/hooks';
import { toast } from 'sonner';
import axios from 'axios';
import { useAuthContext } from '@/auth';
import { getAuth,useAuthContext } from '@/auth';
interface Password {
password: string;
@ -18,15 +17,17 @@ interface Profile {
username: string;
}
interface PinCode {
interface PinCodePayload {
currentpincode: string;
newpincode: string;
retypepincode: string;
}
interface ContextProps {
password: Password | null;
profile: Profile | null;
pincode: PinCode | null;
setPincode: (pincode: PinCode) => Promise<void>;
pincode: PinCodePayload | null;
setPincode: (pincode: PinCodePayload) => Promise<void>;
setPassword: (password: Password) => Promise<void>;
setProfile: (profile: Profile) => Promise<void>;
}
@ -37,42 +38,36 @@ const initialProps: ContextProps = {
pincode: null,
setPassword: async () => {},
setProfile: async () => {},
setPincode: async () => {}
setPincode: async () => {},
};
const AccountUserProfileContext = createContext<ContextProps>(initialProps);
const API_URL = apiConfig.service_dashboard;
const API_URL2 = apiConfig.service_master_data2;
const AccountUserProfileContextProvider = ({ children }: { children: React.ReactNode }) => {
/* state */
const { login } = useAuthContext();
const [profile, setProfileState] = useState<Profile | null>(null);
const [password, setPasswordState] = useState<Password | null>(null);
const [pinCode, setPincodeState] = useState<PinCode | null>(null);
const [alert, setAlert] = useState({
show: false,
message: ''
});
const [pinCode, setPincodeState] = useState<PinCodePayload | null>(null);
const [alert, setAlert] = useState({ show: false, message: '' });
const { PutData, PostData } = useCallApi();
// Helper function to handle API errors
const handleError = (error: any, defaultMessage: string) => {
const errorMessage = error?.response?.data?.message || error?.message || defaultMessage;
setAlert({ show: true, message: errorMessage });
toast.error(errorMessage);
};
// Function to handle password update
const handleSetPassword = async (newPassword: Password) => {
setPasswordState(newPassword);
try {
// Validate the current password
const validate = await PostData(`${API_URL}/login`, {
password: newPassword.current_password,
username: newPassword.username
username: newPassword.username,
});
if (!validate || !validate.status) {
@ -80,10 +75,9 @@ const AccountUserProfileContextProvider = ({ children }: { children: React.React
return;
}
// Update the password
const response = await PutData(`${API_URL}/user/update_password`, {
password: newPassword.password,
retype_password: newPassword.retype_password
retype_password: newPassword.retype_password,
});
if (response && response.status) {
@ -96,30 +90,37 @@ const AccountUserProfileContextProvider = ({ children }: { children: React.React
}
};
// Function to handle profile update
const handleSetProfile = async (newProfile: Profile) => {
try {
setProfileState(newProfile);
const response = await PutData(`${API_URL}/user/update_profile/`, {
await PutData(`${API_URL}/user/update_profile/`, {
name: newProfile.name,
email: newProfile.email,
username: newProfile.username
username: newProfile.username,
});
toast.success('Profile updated successfully.');
} catch (error: any) {
handleError(error, 'Failed to update Profile. Please try again.');
handleError(error, 'Failed to update profile. Please try again.');
}
};
// Function to handle pin code update
const handleSetPinCode = async (newPinCode: PinCode) => {
const handleSetPinCode = async (newPinCode: PinCodePayload) => {
try {
setPincodeState(newPinCode);
const customerid = getAuth()?.user?.customer?.id;
const response = await PutData(`${API_URL2}/customer/pin/${customerid}`, {
old_pin: newPinCode.currentpincode,
new_pin: newPinCode.newpincode,
retype_new_pin: newPinCode.retypepincode,
});
// You can make an API call here to update the pin code in the backend if needed
if (response && response.status) {
toast.success('Pin code updated successfully.');
} else {
toast.error(response?.message || 'Failed to update pin code.');
}
} catch (error: any) {
handleError(error, 'Failed to update Pin Code. Please try again.');
}
@ -133,7 +134,7 @@ const AccountUserProfileContextProvider = ({ children }: { children: React.React
pincode: pinCode,
setPassword: handleSetPassword,
setProfile: handleSetProfile,
setPincode: handleSetPinCode
setPincode: handleSetPinCode,
}}
>
{children}