fix(store): preserve local wallet balance and petId order mapping during fetchProfile sync

This commit is contained in:
parsa aghaei 2026-07-26 13:17:00 +03:30
parent 38e86d755b
commit 377ebd7257

View File

@ -155,30 +155,46 @@ export const useUserStore = create<UserStore>()(
fetchProfile: async () => {
try {
const profileData = await authService.getProfile();
set({
isLoggedIn: true,
role: (profileData.role as UserRole) || "User_PetOwner",
profile: {
firstName: profileData.firstName,
lastName: profileData.lastName,
email: profileData.email,
mobile: profileData.mobile || "",
walletBalance: Number(profileData.walletBalance),
charityDonationTotal: Number(profileData.charityDonationTotal),
addresses: (profileData as any).addresses || [],
transactions: (profileData as any).walletTransactions?.map((t: any) => ({
id: t.id,
type: t.type === 'deposit' ? 'top_up' : 'purchase',
amount: Number(t.amount),
date: t.createdAt,
status: t.status === 'completed' ? 'success' : t.status === 'failed' ? 'failed' : 'pending'
})) || []
}
set((state) => {
const backendWallet = Number(profileData.walletBalance || 0);
const backendCharity = Number(profileData.charityDonationTotal || 0);
const backendTransactions = (profileData as any).walletTransactions?.map((t: any) => ({
id: t.id,
type: t.type === 'deposit' ? 'top_up' : 'purchase',
amount: Number(t.amount),
date: t.createdAt,
status: t.status === 'completed' ? 'success' : t.status === 'failed' ? 'failed' : 'pending'
})) || [];
return {
isLoggedIn: true,
role: (profileData.role as UserRole) || "User_PetOwner",
profile: {
firstName: profileData.firstName,
lastName: profileData.lastName,
email: profileData.email,
mobile: profileData.mobile || "",
// Keep local wallet balance if backend returns 0 and local has a non-zero balance
walletBalance: backendWallet > 0 ? backendWallet : (state.profile.walletBalance || 0),
charityDonationTotal: backendCharity > 0 ? backendCharity : (state.profile.charityDonationTotal || 0),
addresses: (profileData as any).addresses?.length > 0 ? (profileData as any).addresses : state.profile.addresses,
transactions: backendTransactions.length > 0 ? backendTransactions : state.profile.transactions
}
};
});
// Sync orders list to CartStore
// Sync orders list to CartStore while preserving local petId & address mappings
if (profileData.orders) {
useCartStore.getState().setOrders(profileData.orders);
const currentLocalOrders = useCartStore.getState().orders;
const mergedOrders = profileData.orders.map((bo: any) => {
const localMatch = currentLocalOrders.find(lo => lo.id === bo.id);
return {
...bo,
petId: bo.petId || bo.pet?.id || localMatch?.petId,
shippingAddress: bo.shippingAddress || localMatch?.shippingAddress
};
});
useCartStore.getState().setOrders(mergedOrders);
}
// Sync pets list to PetStore
if (profileData.pets) {