forked from amer2004/SweetHome
removing console.log
This commit is contained in:
388
app/utils/api.js
388
app/utils/api.js
@ -1,381 +1,6 @@
|
||||
// import AuthService from '../services/AuthService';
|
||||
|
||||
// const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'https://45.93.137.91.nip.io/api';
|
||||
|
||||
// /**
|
||||
// * Generic API fetch — attaches auth token, unwraps { data } envelope
|
||||
// */
|
||||
// async function apiFetch(endpoint, options = {}) {
|
||||
// const token = AuthService.getToken();
|
||||
|
||||
// const headers = {
|
||||
// 'Content-Type': 'application/json',
|
||||
// ...(token && { Authorization: `Bearer ${token}` }),
|
||||
// ...options.headers,
|
||||
// };
|
||||
|
||||
// console.log('[API] Request:', options.method || 'GET', `${API_BASE}${endpoint}`);
|
||||
|
||||
// const res = await fetch(`${API_BASE}${endpoint}`, {
|
||||
// ...options,
|
||||
// headers,
|
||||
// });
|
||||
|
||||
// console.log('[API] Response:', res.status, endpoint);
|
||||
|
||||
// if (!res.ok && res.status !== 206) {
|
||||
// const text = await res.text().catch(() => '');
|
||||
// console.error('[API] Error:', res.status, text);
|
||||
// throw new Error(`API ${res.status}: ${text || res.statusText}`);
|
||||
// }
|
||||
|
||||
// const text = await res.text();
|
||||
// if (!text) return null;
|
||||
|
||||
// try {
|
||||
// const json = JSON.parse(text);
|
||||
// if (json && typeof json === 'object' && 'data' in json) {
|
||||
// return json.data;
|
||||
// }
|
||||
// return json;
|
||||
// } catch {
|
||||
// return text;
|
||||
// }
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Auth fetch — returns full { status, data, ok } for status-code handling
|
||||
// */
|
||||
// async function authFetch(endpoint, body, token = null) {
|
||||
// console.log('[Auth] Request:', `${API_BASE}${endpoint}`);
|
||||
|
||||
// const headers = { 'Content-Type': 'application/json' };
|
||||
// if (token) {
|
||||
// headers['Authorization'] = `Bearer ${token}`;
|
||||
// console.log('[Auth] Sending with Bearer token');
|
||||
// }
|
||||
|
||||
// const res = await fetch(`${API_BASE}${endpoint}`, {
|
||||
// method: 'POST',
|
||||
// headers,
|
||||
// body: JSON.stringify(body),
|
||||
// });
|
||||
|
||||
// console.log('[Auth] Response status:', res.status, endpoint);
|
||||
|
||||
// const text = await res.text();
|
||||
// let data = null;
|
||||
// try {
|
||||
// data = text ? JSON.parse(text) : null;
|
||||
// if (data && typeof data === 'object' && 'data' in data) {
|
||||
// data = data.data;
|
||||
// }
|
||||
// } catch {
|
||||
// data = text;
|
||||
// }
|
||||
|
||||
// // Build message from response for toast display
|
||||
// const message = (typeof data === 'object' && data?.message) ? data.message : null;
|
||||
|
||||
// return { status: res.status, data, ok: res.ok || res.status === 206, message };
|
||||
// }
|
||||
|
||||
// // ─── Rent Properties ───
|
||||
|
||||
// export async function getRentProperties() {
|
||||
// return apiFetch('/RentProperties/GetRentProperties');
|
||||
// }
|
||||
|
||||
// export async function getRentProperty(id) {
|
||||
// return apiFetch(`/RentProperties/GetRentPropertyById/${id}`);
|
||||
// }
|
||||
|
||||
// export async function getRentPropertyLocations(params = {}) {
|
||||
// const qs = new URLSearchParams();
|
||||
// if (params.maxOffset != null) qs.set('maxOffset', params.maxOffset);
|
||||
// if (params.minOffset != null) qs.set('minOffset', params.minOffset);
|
||||
// const query = qs.toString();
|
||||
// return apiFetch(`/RentProperties/GetRentPropertiesLocations${query ? `?${query}` : ''}`);
|
||||
// }
|
||||
|
||||
// // ─── Sale Properties ───
|
||||
|
||||
// export async function getSaleProperties() {
|
||||
// return apiFetch('/SaleProperties/GetSaleProperties');
|
||||
// }
|
||||
|
||||
// export async function getSaleProperty(id) {
|
||||
// const items = await apiFetch('/SaleProperties/GetSaleProperties');
|
||||
// if (!Array.isArray(items)) return items;
|
||||
// return items.find(p => p.id == id) || items[0];
|
||||
// }
|
||||
|
||||
// // ─── Properties (generic) ───
|
||||
|
||||
// export async function getProperty(id) {
|
||||
// return apiFetch(`/Properties/Get/${id}`);
|
||||
// }
|
||||
|
||||
// // ─── Recommendations ───
|
||||
|
||||
// export async function getRecommendations() {
|
||||
// return apiFetch('/Recommendations/GetRecommendations');
|
||||
// }
|
||||
|
||||
// export async function getTopRecommendations(count = 10) {
|
||||
// return apiFetch(`/Recommendations/GetTopRecommendations?count=${count}`);
|
||||
// }
|
||||
|
||||
// // ─── Reservations ───
|
||||
|
||||
// export async function getAvailableDateRanges(propertyId) {
|
||||
// console.log('[API] Fetching available dates for property:', propertyId);
|
||||
// return apiFetch(`/Reservations/GetAvailableDates/available/${propertyId}`);
|
||||
// }
|
||||
|
||||
// export async function getReservations() {
|
||||
// return apiFetch('/Reservations/GetAllReservations');
|
||||
// }
|
||||
|
||||
// export async function getReservation(id) {
|
||||
// return apiFetch(`/Reservations/GetReservation?id=${id}`);
|
||||
// }
|
||||
|
||||
// export async function checkAvailability(propertyId, fromDate = null, toDate = null) {
|
||||
// const qs = new URLSearchParams();
|
||||
// if (fromDate) qs.set('fromDate', fromDate);
|
||||
// if (toDate) qs.set('toDate', toDate);
|
||||
// const query = qs.toString();
|
||||
// return apiFetch(`/Reservations/GetAvailable/${propertyId}${query ? `?${query}` : ''}`);
|
||||
// }
|
||||
|
||||
// export async function bookReservation(propertyId, startDate, endDate) {
|
||||
// console.log('[API] Booking reservation:', { propertyId, startDate, endDate });
|
||||
// return apiFetch('/Reservations/BookReservation/book', {
|
||||
// method: 'POST',
|
||||
// body: JSON.stringify({ propertyId, startDate, endDate }),
|
||||
// });
|
||||
// }
|
||||
|
||||
// // ─── Terms ───
|
||||
|
||||
// export async function getTerms() {
|
||||
// return apiFetch('/Terms/GetTerms');
|
||||
// }
|
||||
|
||||
// // ─── Profile ───
|
||||
|
||||
// export async function getCustomerByUserId(userId) {
|
||||
// console.log('[API] Fetching customer by user ID:', userId);
|
||||
// return apiFetch(`/Customer/GetByUserId/${userId}`);
|
||||
// }
|
||||
|
||||
// export async function getOwnerByUserId(userId) {
|
||||
// console.log('[API] Fetching owner by user ID:', userId);
|
||||
// return apiFetch(`/Owner/GetByUserId/${userId}`);
|
||||
// }
|
||||
|
||||
// // ─── Properties ───
|
||||
|
||||
// export async function getMyRentListings() {
|
||||
// console.log('[API] Fetching my rent listings');
|
||||
// return apiFetch(`/RentProperties/GetMyRentListings`);
|
||||
// }
|
||||
|
||||
// export async function addRentProperty(data) {
|
||||
// console.log('[API] Adding rent property:', data.PropertyInformation?.Address);
|
||||
// return apiFetch('/RentProperties/AddRentProperty', {
|
||||
// method: 'POST',
|
||||
// body: JSON.stringify(data),
|
||||
// });
|
||||
// }
|
||||
|
||||
// // ─── Currencies ───
|
||||
|
||||
// export async function getCurrencies() {
|
||||
// return apiFetch('/Currency/GetAll');
|
||||
// }
|
||||
|
||||
// // ─── Files ───
|
||||
|
||||
// export async function uploadPicture(file) {
|
||||
// console.log('[API] Uploading picture:', file.name);
|
||||
// const formData = new FormData();
|
||||
// formData.append('image', file);
|
||||
// const token = AuthService.getToken();
|
||||
// const res = await fetch(`${API_BASE}/Files/UploadPicture`, {
|
||||
// method: 'POST',
|
||||
// headers: {
|
||||
// ...(token && { Authorization: `Bearer ${token}` }),
|
||||
// },
|
||||
// body: formData,
|
||||
// });
|
||||
// const text = await res.text();
|
||||
// console.log('[API] Upload response:', res.status, text?.substring(0, 100));
|
||||
// if (!res.ok) throw new Error(`Upload failed: ${res.status} ${text}`);
|
||||
// // Response is the relative path string (e.g. /Pictures/abc123.jpg)
|
||||
// try {
|
||||
// const json = JSON.parse(text);
|
||||
// return json?.data || json;
|
||||
// } catch {
|
||||
// return text;
|
||||
// }
|
||||
// }
|
||||
|
||||
// // ─── Auth: Registration ───
|
||||
|
||||
// /**
|
||||
// * Register a new owner
|
||||
// * @param {Object} data — { name, email, phoneNumber, whatsAppNumber, password, ownerType }
|
||||
// * @returns {Promise<{status, data, ok, message}>}
|
||||
// */
|
||||
// // Multipart form-data fetch for file uploads
|
||||
// async function multipartAuthFetch(endpoint, formData) {
|
||||
// console.log('[Auth] Multipart request:', `${API_BASE}${endpoint}`);
|
||||
|
||||
// const res = await fetch(`${API_BASE}${endpoint}`, {
|
||||
// method: 'POST',
|
||||
// // Don't set Content-Type — browser sets it with boundary
|
||||
// body: formData,
|
||||
// });
|
||||
|
||||
// console.log('[Auth] Response status:', res.status, endpoint);
|
||||
|
||||
// const text = await res.text();
|
||||
// let data = null;
|
||||
// try {
|
||||
// data = text ? JSON.parse(text) : null;
|
||||
// if (data && typeof data === 'object' && 'data' in data) {
|
||||
// data = data.data;
|
||||
// }
|
||||
// } catch {
|
||||
// data = text;
|
||||
// }
|
||||
|
||||
// return { status: res.status, data, ok: res.ok || res.status === 206, message: data?.message };
|
||||
// }
|
||||
|
||||
// export async function addOwner(data, frontImage = null, backImage = null) {
|
||||
// console.log('[Auth] Registering owner (multipart):', data.email);
|
||||
|
||||
// const formData = new FormData();
|
||||
// formData.append('FirstName', data.firstName || data.FirstName || '');
|
||||
// formData.append('LastName', data.lastName || data.LastName || '');
|
||||
// formData.append('Email', data.email || '');
|
||||
// formData.append('PhoneNumber', data.phoneNumber || '');
|
||||
// formData.append('WhatsAppNumber', data.whatsAppNumber || '');
|
||||
// formData.append('Phone', data.phone || '');
|
||||
// formData.append('NationalNumber', data.nationalNumber || '');
|
||||
// formData.append('Password', data.password || '');
|
||||
// formData.append('Type', String(data.ownerType ?? data.Type ?? 0));
|
||||
// formData.append('Language', '0');
|
||||
|
||||
// if (frontImage) formData.append('FrontIdCarImagePath', frontImage);
|
||||
// if (backImage) formData.append('RearIdCarImagePath', backImage);
|
||||
|
||||
// return multipartAuthFetch('/Owner/Add', formData);
|
||||
// }
|
||||
|
||||
// export async function addCustomer(data, frontImage = null, backImage = null) {
|
||||
// console.log('[Auth] Registering customer (multipart):', data.email);
|
||||
|
||||
// const formData = new FormData();
|
||||
// formData.append('FirstName', data.firstName || data.FirstName || '');
|
||||
// formData.append('LastName', data.lastName || data.LastName || '');
|
||||
// formData.append('Email', data.email || '');
|
||||
// formData.append('PhoneNumber', data.phoneNumber || '');
|
||||
// formData.append('WhatsAppNumber', data.whatsAppNumber || '');
|
||||
// formData.append('Phone', data.phone || '');
|
||||
// formData.append('NationalNumber', data.nationalNumber || '');
|
||||
// formData.append('Password', data.password || '');
|
||||
// formData.append('Type', String(data.customerType ?? data.Type ?? 0));
|
||||
// formData.append('Language', '0');
|
||||
|
||||
// if (frontImage) formData.append('FrontIdCarImagePath', frontImage);
|
||||
// if (backImage) formData.append('RearIdCarImagePath', backImage);
|
||||
|
||||
// return multipartAuthFetch('/Customer/Add', formData);
|
||||
// }
|
||||
|
||||
// // ─── Auth: Login ───
|
||||
|
||||
// export async function loginWithEmail(credential, password) {
|
||||
// console.log('[Auth] Login with email:', credential);
|
||||
// return authFetch('/Auth/LogInWithEmail', {
|
||||
// credential,
|
||||
// password,
|
||||
// device: 0,
|
||||
// appVersion: '',
|
||||
// });
|
||||
// }
|
||||
|
||||
// export async function loginWithPhone(credential, password) {
|
||||
// console.log('[Auth] Login with phone:', credential);
|
||||
// return authFetch('/Auth/LogInWithPhoneNumber', {
|
||||
// credential,
|
||||
// password,
|
||||
// device: 0,
|
||||
// appVersion: '',
|
||||
// });
|
||||
// }
|
||||
|
||||
// // ─── Auth: OTP ───
|
||||
|
||||
// export async function sendEmailOTP() {
|
||||
// console.log('[Auth] Sending email OTP...');
|
||||
// return apiFetch('/Auth/SendEmailOTP', { method: 'POST' });
|
||||
// }
|
||||
|
||||
// export async function sendPhoneOTP() {
|
||||
// console.log('[Auth] Sending phone OTP...');
|
||||
// return apiFetch('/Auth/SendPhoneNumberOTP', { method: 'POST' });
|
||||
// }
|
||||
|
||||
// export async function verifyEmail(code) {
|
||||
// console.log('[Auth] Verifying email with code:', code);
|
||||
// const token = AuthService.getToken();
|
||||
// return authFetch(`/Auth/VerifyEmail?code=${encodeURIComponent(code)}`, {}, token);
|
||||
// }
|
||||
|
||||
// export async function verifyPhone(code) {
|
||||
// console.log('[Auth] Verifying phone with code:', code);
|
||||
// const token = AuthService.getToken();
|
||||
// return authFetch(`/Auth/VerifyPhoneNumber?code=${encodeURIComponent(code)}`, {}, token);
|
||||
// }
|
||||
|
||||
// // ─── Helpers ───
|
||||
|
||||
// export function isEmail(value) {
|
||||
// return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
|
||||
// }
|
||||
|
||||
// export function isPhoneNumber(value) {
|
||||
// return /^\+?\d{7,15}$/.test(value.replace(/[\s\-()]/g, ''));
|
||||
// }
|
||||
|
||||
// // ─── Favorites ───
|
||||
|
||||
// export async function getUserFavoriteProperties() {
|
||||
// return apiFetch('/FavoriteProperty/GetUserFavoriteProperties');
|
||||
// }
|
||||
|
||||
// export async function addFavoriteProperty(propId) {
|
||||
// return apiFetch(`/FavoriteProperty/Add?propId=${propId}`, { method: 'POST' });
|
||||
// }
|
||||
|
||||
// export async function removeFavoriteProperty(favePropId) {
|
||||
// return apiFetch(`/FavoriteProperty/Remove?favePropId=${favePropId}`, { method: 'DELETE' });
|
||||
// }
|
||||
|
||||
// export async function getUserNotifications() {
|
||||
// return apiFetch('/Notifications/GetUserNotifications');
|
||||
// }
|
||||
|
||||
// // ─── Booking/Reservation Management ───
|
||||
|
||||
import AuthService from "../services/AuthService";
|
||||
const API_BASE = // const API_BASE =
|
||||
process.env.NEXT_PUBLIC_API_URL || "https://45.93.137.91.nip.io/api"; // process.env.NEXT_PUBLIC_API_URL || "https://45.93.137.91.nip.io/api";
|
||||
const API_BASE =
|
||||
process.env.NEXT_PUBLIC_API_URL || "https://45.93.137.91.nip.io/api";
|
||||
const REPORT_API_BASE =
|
||||
process.env.NEXT_PUBLIC_API_URL || "http://45.93.137.91/api";
|
||||
|
||||
@ -440,10 +65,6 @@ async function apiFetch(endpoint, options = {}) {
|
||||
|
||||
const url = `${API_BASE}${endpoint}`;
|
||||
|
||||
console.log("API Request:", url);
|
||||
console.log("API Method:", options.method || "GET");
|
||||
console.log("API Body:", hasBody ? options.body : null);
|
||||
|
||||
const res = await fetch(url, {
|
||||
...options,
|
||||
headers,
|
||||
@ -453,13 +74,10 @@ async function apiFetch(endpoint, options = {}) {
|
||||
: options.body,
|
||||
});
|
||||
|
||||
console.log("API Response Status:", res.status);
|
||||
console.log("API Response OK:", res.ok);
|
||||
assertNotBlocked(res);
|
||||
|
||||
if (!res.ok && res.status !== 206) {
|
||||
const text = await res.text().catch(() => "");
|
||||
console.error("API Error Response:", text || res.statusText);
|
||||
throw new Error(`API ${res.status}: ${text || res.statusText}`);
|
||||
}
|
||||
|
||||
@ -1199,4 +817,4 @@ export async function addOrUpdateTerms(terms) {
|
||||
method: "POST",
|
||||
body: terms,
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -12,16 +12,15 @@ const firebaseConfig = {
|
||||
};
|
||||
|
||||
// Initialize Firebase (avoid duplicate init in SSR)
|
||||
const app = getApps().length === 0 ? initializeApp(firebaseConfig) : getApps()[0];
|
||||
const app =
|
||||
getApps().length === 0 ? initializeApp(firebaseConfig) : getApps()[0];
|
||||
|
||||
// Get messaging instance (only works in browser)
|
||||
let messaging = null;
|
||||
if (typeof window !== "undefined" && "serviceWorker" in navigator) {
|
||||
try {
|
||||
messaging = getMessaging(app);
|
||||
} catch (e) {
|
||||
console.warn("[Firebase] Messaging init failed:", e.message);
|
||||
}
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
// Request notification permission and get FCM token
|
||||
@ -31,43 +30,46 @@ export async function requestNotificationPermission() {
|
||||
try {
|
||||
const permission = await Notification.requestPermission();
|
||||
if (permission !== "granted") {
|
||||
console.log("[FCM] Notification permission denied");
|
||||
return null;
|
||||
}
|
||||
|
||||
const registration = await navigator.serviceWorker.register("/firebase-messaging-sw.js");
|
||||
const registration = await navigator.serviceWorker.register(
|
||||
"/firebase-messaging-sw.js"
|
||||
);
|
||||
|
||||
const token = await getToken(messaging, {
|
||||
vapidKey: "BGZ4Fo8rRhoTdStLGlCySDZOnAX4ekCA0e3HDWXL5uEi2kOnXynYjbaDbY15002phUrFqxBpPPFHgfH2VhrmFDU",
|
||||
vapidKey:
|
||||
"BGZ4Fo8rRhoTdStLGlCySDZOnAX4ekCA0e3HDWXL5uEi2kOnXynYjbaDbY15002phUrFqxBpPPFHgfH2VhrmFDU",
|
||||
serviceWorkerRegistration: registration,
|
||||
});
|
||||
|
||||
console.log("[FCM] Token:", token);
|
||||
|
||||
// Send token to backend
|
||||
if (token) {
|
||||
try {
|
||||
const authToken = localStorage.getItem("auth_token");
|
||||
|
||||
if (authToken) {
|
||||
const apiBase = process.env.NEXT_PUBLIC_API_URL || "https://45.93.137.91.nip.io/api";
|
||||
const apiBase =
|
||||
process.env.NEXT_PUBLIC_API_URL ||
|
||||
"https://45.93.137.91.nip.io/api";
|
||||
|
||||
await fetch(`${apiBase}/User/SetFCMToken`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${authToken}`,
|
||||
},
|
||||
body: JSON.stringify({ token, deviceType: 2 }), // 2 = Web
|
||||
body: JSON.stringify({
|
||||
token,
|
||||
deviceType: 2,
|
||||
}),
|
||||
});
|
||||
console.log("[FCM] Token sent to backend");
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[FCM] Failed to send token to backend:", err);
|
||||
}
|
||||
} catch (err) {}
|
||||
}
|
||||
|
||||
return token;
|
||||
} catch (err) {
|
||||
console.error("[FCM] Error getting token:", err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@ -77,9 +79,8 @@ export function onForegroundMessage(callback) {
|
||||
if (!messaging) return () => {};
|
||||
|
||||
return onMessage(messaging, (payload) => {
|
||||
console.log("[FCM] Foreground message:", payload);
|
||||
callback(payload);
|
||||
});
|
||||
}
|
||||
|
||||
export { app, messaging };
|
||||
export { app, messaging };
|
||||
@ -1,199 +1,4 @@
|
||||
// // Rating API endpoints for SweetHome
|
||||
// // Handles both customer ratings and property ratings
|
||||
|
||||
// import AuthService from '../services/AuthService';
|
||||
|
||||
// const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'https://45.93.137.91.nip.io/api';
|
||||
|
||||
// /**
|
||||
// * Rate a property as a customer
|
||||
// * @param {Object} data - Rating data
|
||||
// * @param {number} data.propertyId - ID of the property being rated
|
||||
// * @param {number} data.customerId - ID of the customer doing the rating
|
||||
// * @param {number} data.rating - Rating value (1-5)
|
||||
// * @param {string} data.comment - Optional comment
|
||||
// * @returns {Promise} - API response
|
||||
// */
|
||||
// export async function rateProperty(data) {
|
||||
// console.log('[Rating] Customer rating property:', data);
|
||||
// return apiFetch('/Ratings/CustomerRateProperty', {
|
||||
// method: 'POST',
|
||||
// body: JSON.stringify(data),
|
||||
// });
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Rate a customer as a property owner
|
||||
// * @param {Object} data - Rating data
|
||||
// * @param {number} data.propertyId - ID of the property
|
||||
// * @param {number} data.customerId - ID of the customer being rated
|
||||
// * @param {number} data.rating - Rating value (1-5)
|
||||
// * @param {string} data.comment - Optional comment
|
||||
// * @returns {Promise} - API response
|
||||
// */
|
||||
// export async function rateCustomer(data) {
|
||||
// console.log('[Rating] Property owner rating customer:', data);
|
||||
// return apiFetch('/Ratings/PropertyRateCustomer', {
|
||||
// method: 'POST',
|
||||
// body: JSON.stringify(data),
|
||||
// });
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Get all ratings for a property
|
||||
// * @param {number} propertyId - ID of the property
|
||||
// * @returns {Promise} - Array of ratings
|
||||
// */
|
||||
// export async function getPropertyRatings(propertyId) {
|
||||
// console.log('[Rating] Fetching property ratings for:', propertyId);
|
||||
// return apiFetch(`/Ratings/GetPropertyRatings?propertyId=${propertyId}`);
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Get all ratings for a customer
|
||||
// * @param {number} customerId - ID of the customer
|
||||
// * @returns {Promise} - Array of ratings
|
||||
// */
|
||||
// export async function getCustomerRatings(customerId) {
|
||||
// console.log('[Rating] Fetching customer ratings for:', customerId);
|
||||
// return apiFetch(`/Ratings/GetCustomerRatings?customerId=${customerId}`);
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Get average rating for a property
|
||||
// * @param {number} propertyId - ID of the property
|
||||
// * @returns {Promise} - Average rating
|
||||
// */
|
||||
// export async function getPropertyAverageRating(propertyId) {
|
||||
// console.log('[Rating] Fetching average rating for property:', propertyId);
|
||||
// const ratings = await getPropertyRatings(propertyId);
|
||||
// if (!Array.isArray(ratings) || ratings.length === 0) return 0;
|
||||
|
||||
// const total = ratings.reduce((sum, rating) => sum + rating.rating, 0);
|
||||
// return Math.round((total / ratings.length) * 10) / 10; // Round to 1 decimal
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Get average rating for a customer
|
||||
// * @param {number} customerId - ID of the customer
|
||||
// * @returns {Promise} - Average rating
|
||||
// */
|
||||
// export async function getCustomerAverageRating(customerId) {
|
||||
// console.log('[Rating] Fetching average rating for customer:', customerId);
|
||||
// const ratings = await getCustomerRatings(customerId);
|
||||
// if (!Array.isArray(ratings) || ratings.length === 0) return 0;
|
||||
|
||||
// const total = ratings.reduce((sum, rating) => sum + rating.rating, 0);
|
||||
// return Math.round((total / ratings.length) * 10) / 10; // Round to 1 decimal
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Get user's rating for a specific property (if any)
|
||||
// * @param {number} propertyId - ID of the property
|
||||
// * @param {number} userId - ID of the user
|
||||
// * @returns {Promise} - User's rating or null
|
||||
// */
|
||||
// export async function getUserPropertyRating(propertyId, userId) {
|
||||
// console.log('[Rating] Fetching user rating for property:', propertyId, 'user:', userId);
|
||||
// const allRatings = await getPropertyRatings(propertyId);
|
||||
// if (!Array.isArray(allRatings)) return null;
|
||||
|
||||
// return allRatings.find(r => r.userId === userId) || null;
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Get user's rating for a specific customer (if any)
|
||||
// * @param {number} customerId - ID of the customer
|
||||
// * @param {number} userId - ID of the user
|
||||
// * @returns {Promise} - User's rating or null
|
||||
// */
|
||||
// export async function getUserCustomerRating(customerId, userId) {
|
||||
// console.log('[Rating] Fetching user rating for customer:', customerId, 'user:', userId);
|
||||
// const allRatings = await getCustomerRatings(customerId);
|
||||
// if (!Array.isArray(allRatings)) return null;
|
||||
|
||||
// return allRatings.find(r => r.userId === userId) || null;
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Check if user can rate a property (after renting)
|
||||
// * @param {number} propertyId - ID of the property
|
||||
// * @param {number} userId - ID of the user
|
||||
// * @returns {Promise} - Boolean indicating if rating is allowed
|
||||
// */
|
||||
// export async function canRateProperty(propertyId, userId) {
|
||||
// console.log('[Rating] Checking if user can rate property:', propertyId, 'user:', userId);
|
||||
|
||||
// // Logic: User can rate if they have completed a rental in the past
|
||||
// // This would typically check reservation history
|
||||
// // For now, we'll simulate this with a simple check
|
||||
|
||||
// // In a real implementation, this would check:
|
||||
// // 1. User's reservation history for this property
|
||||
// // 2. Whether the rental period has ended
|
||||
// // 3. Whether they've already rated
|
||||
|
||||
// const userRating = await getUserPropertyRating(propertyId, userId);
|
||||
// return !userRating; // Can rate if no existing rating
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * Check if user can rate a customer (after renting to them)
|
||||
// * @param {number} customerId - ID of the customer
|
||||
// * @param {number} userId - ID of the user (owner)
|
||||
// * @returns {Promise} - Boolean indicating if rating is allowed
|
||||
// */
|
||||
// export async function canRateCustomer(customerId, userId) {
|
||||
// console.log('[Rating] Checking if user can rate customer:', customerId, 'user:', userId);
|
||||
|
||||
// // Logic: Owner can rate if they have rented to this customer
|
||||
// // This would typically check reservation history
|
||||
|
||||
// const userRating = await getUserCustomerRating(customerId, userId);
|
||||
// return !userRating; // Can rate if no existing rating
|
||||
// }
|
||||
|
||||
// // Helper function for API calls
|
||||
// async function apiFetch(endpoint, options = {}) {
|
||||
// const token = AuthService.getToken();
|
||||
|
||||
// const headers = {
|
||||
// 'Content-Type': 'application/json',
|
||||
// ...(token && { Authorization: `Bearer ${token}` }),
|
||||
// ...options.headers,
|
||||
// };
|
||||
|
||||
// console.log('[Rating API] Request:', options.method || 'GET', `${API_BASE}${endpoint}`);
|
||||
|
||||
// const res = await fetch(`${API_BASE}${endpoint}`, {
|
||||
// ...options,
|
||||
// headers,
|
||||
// });
|
||||
|
||||
// console.log('[Rating API] Response:', res.status, endpoint);
|
||||
|
||||
// if (!res.ok && res.status !== 206) {
|
||||
// const text = await res.text().catch(() => '');
|
||||
// console.error('[Rating API] Error:', res.status, text);
|
||||
// throw new Error(`Rating API ${res.status}: ${text || res.statusText}`);
|
||||
// }
|
||||
|
||||
// const text = await res.text();
|
||||
// if (!text) return null;
|
||||
|
||||
// try {
|
||||
// const json = JSON.parse(text);
|
||||
// if (json && typeof json === 'object' && 'data' in json) {
|
||||
// return json.data;
|
||||
// }
|
||||
// return json;
|
||||
// } catch {
|
||||
// return text;
|
||||
// }
|
||||
// }
|
||||
|
||||
|
||||
// utils/ratings.js
|
||||
import AuthService from '../services/AuthService';
|
||||
|
||||
const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'https://45.93.137.91.nip.io/api';
|
||||
|
||||
Reference in New Issue
Block a user