chore: move api to another component
This commit is contained in:
@@ -6,29 +6,9 @@ import { ProfileImage } from './personalInformation/ProfileImage';
|
||||
import { InfoRowDisplay } from './personalInformation/InfoRowDisplay';
|
||||
import { InfoRowEdit } from './personalInformation/InfoRowEdit';
|
||||
import { PageWrapper } from '../PageWrapper';
|
||||
import { Gender, type InfoRowData } from '../../types';
|
||||
import axios, { isAxiosError } from 'axios';
|
||||
import apiClient from '@/lib/apiClient';
|
||||
|
||||
interface GetProfileApiResponse {
|
||||
success: boolean;
|
||||
message?: string;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
nationalCode?: string;
|
||||
gender?: Gender;
|
||||
countryCode?: string;
|
||||
profileImageUrl?: string;
|
||||
}
|
||||
|
||||
interface SaveProfileApiResponse {
|
||||
success: boolean;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
interface TokenApiResponse {
|
||||
access_token: string;
|
||||
}
|
||||
import { useManualApi } from '@/hooks/useApi';
|
||||
import { Gender, type InfoRowData } from '../../types/settingsType';
|
||||
import { fetchProfile, saveProfile, getToken } from '../../api/settingsApi';
|
||||
|
||||
export function PersonalInformation() {
|
||||
const { t } = useTranslation('setting');
|
||||
@@ -42,71 +22,60 @@ export function PersonalInformation() {
|
||||
country: '',
|
||||
});
|
||||
const [originalData, setOriginalData] = useState<InfoRowData | null>(null);
|
||||
// const [token, setToken] = useState<string | null>(null);
|
||||
const [tokenError, setTokenError] = useState<string | null>(null);
|
||||
const [saveError, setSaveError] = useState<string | null>(null);
|
||||
const storedToken = localStorage.getItem('authToken');
|
||||
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [fetchError, setFetchError] = useState<string | null>(null);
|
||||
const {
|
||||
data: profileData,
|
||||
loading: isLoadingProfile,
|
||||
error: fetchProfileError,
|
||||
execute: executeFetchProfile,
|
||||
} = useManualApi(fetchProfile);
|
||||
|
||||
const {
|
||||
data: saveData,
|
||||
loading: isSavingProfile,
|
||||
error: saveProfileError,
|
||||
execute: executeSaveProfile,
|
||||
} = useManualApi(saveProfile);
|
||||
|
||||
const {
|
||||
data: tokenData,
|
||||
loading: isGettingToken,
|
||||
error: tokenError,
|
||||
execute: executeGetToken,
|
||||
} = useManualApi(getToken);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchProfile = async () => {
|
||||
setIsLoading(true);
|
||||
setFetchError(null);
|
||||
try {
|
||||
const res = await apiClient.post<GetProfileApiResponse>(
|
||||
'/Profile/GetProfile',
|
||||
{},
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${storedToken}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
if (res.data?.success) {
|
||||
const profile = res.data;
|
||||
const fetchedData = {
|
||||
firstName: profile.firstName ?? '',
|
||||
lastName: profile.lastName ?? '',
|
||||
nationalCode: profile.nationalCode ?? '',
|
||||
gender: Object.values(Gender).includes(profile.gender as Gender)
|
||||
? (profile.gender as Gender)
|
||||
: Gender.None,
|
||||
country: profile.countryCode ?? '',
|
||||
};
|
||||
setData(fetchedData);
|
||||
setOriginalData(fetchedData);
|
||||
setUploadedImageUrl(profile.profileImageUrl || null);
|
||||
} else {
|
||||
throw new Error(res.data.message || t('settingForm.failRetrieve'));
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
let message = t('settingForm.errorFetch');
|
||||
if (error instanceof Error) {
|
||||
message = error.message;
|
||||
}
|
||||
setFetchError(message);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
executeFetchProfile();
|
||||
}, []);
|
||||
|
||||
if (storedToken) {
|
||||
fetchProfile();
|
||||
} else {
|
||||
setIsLoading(false);
|
||||
setFetchError(t('settingForm.notLoggedIn'));
|
||||
useEffect(() => {
|
||||
if (profileData?.success) {
|
||||
const fetchedData = {
|
||||
firstName: profileData.firstName ?? '',
|
||||
lastName: profileData.lastName ?? '',
|
||||
nationalCode: profileData.nationalCode ?? '',
|
||||
gender: Object.values(Gender).includes(profileData.gender as Gender)
|
||||
? (profileData.gender as Gender)
|
||||
: Gender.None,
|
||||
country: profileData.countryCode ?? '',
|
||||
};
|
||||
setData(fetchedData);
|
||||
setOriginalData(fetchedData);
|
||||
setUploadedImageUrl(profileData.profileImageUrl || null);
|
||||
}
|
||||
}, [storedToken, t]);
|
||||
}, [profileData]);
|
||||
|
||||
const initials = `${data?.firstName?.trim()[0] || ''}${
|
||||
data?.lastName?.trim()[0] || ''
|
||||
}`;
|
||||
useEffect(() => {
|
||||
if (saveData?.success) {
|
||||
setIsEditing(false);
|
||||
setOriginalData(data);
|
||||
}
|
||||
}, [saveData, data]);
|
||||
|
||||
const initials = `${data?.firstName?.trim()[0] || ''}${data?.lastName?.trim()[0] || ''}`;
|
||||
|
||||
const handleEditClick = () => {
|
||||
setIsEditing(true);
|
||||
setSaveError(null);
|
||||
setOriginalData(data);
|
||||
};
|
||||
|
||||
@@ -115,85 +84,21 @@ export function PersonalInformation() {
|
||||
if (originalData) {
|
||||
setData(originalData);
|
||||
}
|
||||
setSaveError(null);
|
||||
};
|
||||
|
||||
const handleSaveClick = async () => {
|
||||
if (!data) return;
|
||||
setSaveError(null);
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('FirstName', data.firstName || '');
|
||||
formData.append('LastName', data.lastName || '');
|
||||
formData.append('NationalCode', data.nationalCode || '');
|
||||
formData.append('Gender', String(data.gender ?? Gender.None));
|
||||
formData.append('CountryCode', data.country || '');
|
||||
|
||||
if (uploadedImageUrl && uploadedImageUrl.startsWith('data:')) {
|
||||
const response = await fetch(uploadedImageUrl);
|
||||
const blob = await response.blob();
|
||||
formData.append('Image', blob, 'profile.jpg');
|
||||
}
|
||||
|
||||
const res = await apiClient.post<SaveProfileApiResponse>(
|
||||
'Profile/SaveProfilePersonalInforamtion',
|
||||
formData,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${storedToken}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (res.data.success) {
|
||||
setIsEditing(false);
|
||||
setOriginalData(data);
|
||||
} else {
|
||||
throw new Error(res.data.message || t('settingForm.unknownError'));
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
let message = t('settingForm.checkConnection');
|
||||
if (error instanceof Error) {
|
||||
message = error.message;
|
||||
}
|
||||
setSaveError(message);
|
||||
}
|
||||
executeSaveProfile({ data, imageUrl: uploadedImageUrl });
|
||||
};
|
||||
|
||||
const apiUrl = 'https://accounts.business-harmony.com';
|
||||
const tokenEndpoint = `${apiUrl}/connect/token`;
|
||||
const getToken = async () => {
|
||||
setTokenError(null);
|
||||
try {
|
||||
const body = new URLSearchParams();
|
||||
body.set('grant_type', 'password');
|
||||
body.set('username', 'zareian.1381@gmail.com');
|
||||
body.set('password', '123@Qweasd');
|
||||
body.set('client_id', 'harmony_identity');
|
||||
body.set('scope', 'openid harmony_identity profile offline_access');
|
||||
const response = await axios.post<TokenApiResponse>(
|
||||
tokenEndpoint,
|
||||
body.toString(),
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
},
|
||||
);
|
||||
if (response.data?.access_token) {
|
||||
localStorage.setItem('authToken', response.data.access_token);
|
||||
} else {
|
||||
throw new Error('No access token in response');
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
let message = 'Failed to get token';
|
||||
if (isAxiosError(error) && error.response) {
|
||||
message = `Request failed with status ${error.response.status}`;
|
||||
} else if (error instanceof Error) {
|
||||
message = error.message;
|
||||
}
|
||||
setTokenError(message);
|
||||
}
|
||||
const handleGetTokenClick = async () => {
|
||||
executeGetToken();
|
||||
};
|
||||
|
||||
const getErrorMessage = (error: unknown): string | null => {
|
||||
if (!error) return null;
|
||||
if (error instanceof Error) return error.message;
|
||||
return String(error);
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -222,12 +127,12 @@ export function PersonalInformation() {
|
||||
<Button
|
||||
variant="contained"
|
||||
color="secondary"
|
||||
onClick={getToken}
|
||||
onClick={handleGetTokenClick}
|
||||
size="large"
|
||||
sx={{ textTransform: 'none' }}
|
||||
disabled={isLoading}
|
||||
disabled={isLoadingProfile || isGettingToken || isSavingProfile}
|
||||
>
|
||||
Get Token
|
||||
{isGettingToken ? <CircularProgress size={24} /> : 'Get Token'}
|
||||
</Button>
|
||||
{isEditing ? (
|
||||
<>
|
||||
@@ -240,6 +145,7 @@ export function PersonalInformation() {
|
||||
textTransform: 'none',
|
||||
width: { xs: '100%', sm: 'auto' },
|
||||
}}
|
||||
disabled={isSavingProfile}
|
||||
>
|
||||
{t('settingForm.rejectButton')}
|
||||
</Button>
|
||||
@@ -251,8 +157,13 @@ export function PersonalInformation() {
|
||||
textTransform: 'none',
|
||||
width: { xs: '100%', sm: 'auto' },
|
||||
}}
|
||||
disabled={isSavingProfile}
|
||||
>
|
||||
{t('settingForm.saveButton')}
|
||||
{isSavingProfile ? (
|
||||
<CircularProgress size={24} color="inherit" />
|
||||
) : (
|
||||
t('settingForm.saveButton')
|
||||
)}
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
@@ -260,27 +171,33 @@ export function PersonalInformation() {
|
||||
onClick={handleEditClick}
|
||||
size="large"
|
||||
variant="outlined"
|
||||
sx={{
|
||||
borderRadius: 1,
|
||||
}}
|
||||
disabled={isLoading}
|
||||
sx={{ borderRadius: 1 }}
|
||||
disabled={isLoadingProfile}
|
||||
>
|
||||
{t('settingForm.editButton')}
|
||||
</Button>
|
||||
)}
|
||||
</Box>
|
||||
{saveError && (
|
||||
{getErrorMessage(saveProfileError) && (
|
||||
<Typography
|
||||
color="error"
|
||||
sx={{ mt: 1, textAlign: 'right', width: '100%' }}
|
||||
>
|
||||
{saveError}
|
||||
{getErrorMessage(saveProfileError)}
|
||||
</Typography>
|
||||
)}
|
||||
{tokenData?.success && (
|
||||
<Typography
|
||||
color="green"
|
||||
sx={{ mt: 1, textAlign: 'right', width: '100%' }}
|
||||
>
|
||||
Token fetched and stored successfully!
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
}
|
||||
>
|
||||
{isLoading ? (
|
||||
{isLoadingProfile ? (
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
@@ -292,14 +209,19 @@ export function PersonalInformation() {
|
||||
>
|
||||
<CircularProgress />
|
||||
</Box>
|
||||
) : fetchError ? (
|
||||
) : fetchProfileError ? (
|
||||
<Box sx={{ textAlign: 'center', p: 4 }}>
|
||||
<Typography color="error">{fetchError}</Typography>
|
||||
<Typography color="error">
|
||||
{getErrorMessage(fetchProfileError) ||
|
||||
t('settingForm.errorFetch')}
|
||||
</Typography>
|
||||
</Box>
|
||||
) : (
|
||||
<>
|
||||
{tokenError && (
|
||||
<Box sx={{ mt: 2, color: 'red' }}>Error: {tokenError}</Box>
|
||||
{getErrorMessage(tokenError) && (
|
||||
<Box sx={{ p: 2, mx: { xs: 2, sm: 3, md: 4 }, color: 'red' }}>
|
||||
Error: {getErrorMessage(tokenError)}
|
||||
</Box>
|
||||
)}
|
||||
<Box
|
||||
sx={{
|
||||
|
||||
Reference in New Issue
Block a user