Files
SweetHome/app/utils/ratings.js

97 lines
2.8 KiB
JavaScript
Raw Normal View History

2026-04-26 13:46:30 +03:00
import AuthService from '../services/AuthService';
const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'https://45.93.137.91.nip.io/api';
async function apiFetch(endpoint, options = {}) {
const token = AuthService.getToken();
const headers = {
'Content-Type': 'application/json',
...(token && { Authorization: `Bearer ${token}` }),
...options.headers,
};
2026-04-26 13:46:30 +03:00
const response = await fetch(`${API_BASE}${endpoint}`, {
...options,
headers,
});
2026-04-26 13:46:30 +03:00
if (!response.ok && response.status !== 206) {
const errorText = await response.text().catch(() => '');
throw new Error(`API Error ${response.status}: ${errorText}`);
}
2026-04-26 13:46:30 +03:00
const text = await response.text();
if (!text) return null;
try {
const json = JSON.parse(text);
2026-04-26 13:46:30 +03:00
return json && typeof json === 'object' && 'data' in json ? json.data : json;
} catch {
return text;
}
2026-04-26 13:46:30 +03:00
}
/**
* POST /Rating/AddPropertyRating
* @param {Object} data - { reservationId, cleanRating, servicesRating, ownerBehaviorRating, experienceRating, comment? }
*/
export async function addPropertyRating(data) {
return apiFetch('/Rating/AddPropertyRating', {
method: 'POST',
body: JSON.stringify(data),
});
}
/**
* POST /Rating/AddCustomerRating
* @param {Object} data - { reservationId, furnitureIntegrityRating, termsComplianceRating, renterBehaviorRating, comment? }
*/
export async function addCustomerRating(data) {
return apiFetch('/Rating/AddCustomerRating', {
method: 'POST',
body: JSON.stringify(data),
});
}
/**
* GET /Rating/GetPropertyRatings
* @param {number} propertyId
* @param {number} page - default 1
* @param {number} pageSize - default 10
* @returns {Promise<{ items: Array, totalPages: number, currentPage: number }>}
*/
export async function getPropertyRatings(propertyId, page = 1, pageSize = 10) {
const query = new URLSearchParams({
propertyId: String(propertyId),
page: String(page),
pageSize: String(pageSize),
}).toString();
return apiFetch(`/Rating/GetPropertyRatings?${query}`);
}
/**
* GET /Rating/GetCustomerRatings
* @param {number} renterId
* @param {number} page
* @param {number} pageSize
*/
export async function getCustomerRatings(renterId, page = 1, pageSize = 10) {
const query = new URLSearchParams({
renterId: String(renterId),
page: String(page),
pageSize: String(pageSize),
}).toString();
return apiFetch(`/Rating/GetCustomerRatings?${query}`);
}
/**
* GET /Rating/GetPropertyAverage
* @param {number} propertyId
* @returns {Promise<number>} average rating (0 if none)
*/
export async function getPropertyAverageRating(propertyId) {
const result = await apiFetch(`/Rating/GetPropertyAverage?propertyId=${propertyId}`);
if (typeof result === 'number') return result;
if (result && typeof result.average === 'number') return result.average;
return 0;
}