prof1 / src /models /professionalModel.js
Huzaifa1435's picture
Initial Commit: Clean backend without large files
e3fefe8
Raw History Blame Contribute Delete
6.49 kB
const { db } = require('../config/firebase');
const PROF_PATH = 'professionals';
// Haversine distance in km
function getDistanceKm(lat1, lon1, lat2, lon2) {
const R = 6371;
const dLat = ((lat2 - lat1) * Math.PI) / 180;
const dLon = ((lon2 - lon1) * Math.PI) / 180;
const a =
Math.sin(dLat / 2) ** 2 +
Math.cos((lat1 * Math.PI) / 180) *
Math.cos((lat2 * Math.PI) / 180) *
Math.sin(dLon / 2) ** 2;
return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}
const ProfessionalModel = {
// Get all professionals
async getAll() {
const snapshot = await db.ref(PROF_PATH).once('value');
const data = snapshot.val();
if (!data) return [];
return Object.entries(data).map(([uid, value]) => ({
uid,
...value
}));
},
// Get professional by UID
async getById(uid) {
const snapshot = await db.ref(`${PROF_PATH}/${uid}`).once('value');
const data = snapshot.val();
if (!data) return null;
return {
uid,
...data
};
},
// Get professional by phone number
async getByPhone(phone) {
const all = await this.getAll();
return all.find(p => p.phoneNumber === phone) || null;
},
// Create new professional profile
async create(uid, profileData) {
const { name, services, customServices, description, phoneNumber, photoURL, location, rating, isAvailable, hourlyRate } = profileData;
const professional = {
name: name || '',
services: services || [],
customServices: customServices || [],
description: description || '',
phoneNumber: phoneNumber || '',
photoURL: photoURL || '',
location: location || { lat: 0, lng: 0, address: '' },
walletBalance: profileData.walletBalance !== undefined ? Number(profileData.walletBalance) : 5000,
totalEarnings: profileData.totalEarnings !== undefined ? Number(profileData.totalEarnings) : 0,
completedJobs: profileData.completedJobs !== undefined ? Number(profileData.completedJobs) : 0,
rating: rating || 0,
isAvailable: isAvailable !== false,
hourlyRate: hourlyRate || 500,
profileCompleted: true,
createdAt: Date.now(),
updatedAt: Date.now()
};
await db.ref(`${PROF_PATH}/${uid}`).set(professional);
return {
uid,
...professional
};
},
// Update professional by UID
async updateById(uid, updates) {
const existing = await this.getById(uid);
if (!existing) return null;
const updated = {
...existing,
...updates,
updatedAt: Date.now()
};
await db.ref(`${PROF_PATH}/${uid}`).update({
...updates,
updatedAt: Date.now()
});
return updated;
},
// Update availability
async updateAvailability(uid, isAvailable) {
await db.ref(`${PROF_PATH}/${uid}/isAvailable`).set(isAvailable);
return { uid, isAvailable };
},
// Get nearby professionals sorted by distance
async getNearby({ lat, lng, radiusKm = 10, serviceType }) {
const allPros = await this.getAll();
if (!allPros || allPros.length === 0) return [];
const results = [];
for (const pro of allPros) {
// Filter by availability
if (pro.isAvailable === false) continue;
// Filter by service type
if (serviceType) {
const services = Array.isArray(pro.services) ? pro.services : [];
if (!services.includes(serviceType)) continue;
}
const proLat = pro.location?.lat || 0;
const proLng = pro.location?.lng || 0;
if (!proLat || !proLng) continue;
// Calculate distance
const distance = getDistanceKm(lat, lng, proLat, proLng);
if (distance > radiusKm) continue;
results.push({
uid: pro.uid,
name: pro.name,
services: pro.services || [],
customServices: pro.customServices || [],
location: pro.location,
rating: pro.rating || 0,
distance: parseFloat(distance.toFixed(2)),
isAvailable: true,
photoURL: pro.photoURL || '',
hourlyRate: pro.hourlyRate || 500,
description: pro.description || ''
});
}
// Sort by distance (nearest first)
results.sort((a, b) => a.distance - b.distance);
return results;
},
async upsert(uid, data) {
const existing = await this.getById(uid);
if (!existing) {
return this.create(uid, {
name: data.displayName || data.name || '',
services: data.services || [],
customServices: data.customServices || [],
description: data.description || '',
phoneNumber: data.phoneNumber || '',
location: data.location,
isAvailable: true,
photoURL: data.photoURL || '',
hourlyRate: data.hourlyRate || 500,
walletBalance: 5000,
totalEarnings: 0,
completedJobs: 0
});
}
return this.updateById(uid, {
name: data.name || data.displayName || existing.name,
services: data.services || existing.services,
customServices: data.customServices || existing.customServices,
description: data.description || existing.description,
phoneNumber: data.phoneNumber || existing.phoneNumber,
location: data.location || existing.location,
isAvailable: data.isAvailable !== undefined ? data.isAvailable : existing.isAvailable,
photoURL: data.photoURL || existing.photoURL,
hourlyRate: data.hourlyRate || existing.hourlyRate
});
},
async createProfile(uid, data) {
return this.upsert(uid, data);
},
async updateAvailabilityById(uid, isAvailableNow) {
return this.updateAvailability(uid, isAvailableNow);
},
async addPortfolioImages(uid, urls) {
const existing = await this.getById(uid);
const portfolio = existing?.portfolio || [];
const newPortfolio = [...portfolio, ...urls];
await db.ref(`${PROF_PATH}/${uid}/portfolio`).set(newPortfolio);
return newPortfolio;
},
async incrementCompletedJobs(uid) {
const pro = await this.getById(uid);
const count = (pro?.completedJobs || 0) + 1;
await db.ref(`${PROF_PATH}/${uid}/completedJobs`).set(count);
},
async updateRating(uid, newRating) {
const pro = await this.getById(uid);
if (!pro) return;
let avgRating = newRating;
if (pro.rating > 0) {
avgRating = (pro.rating + newRating) / 2;
}
await db.ref(`${PROF_PATH}/${uid}/rating`).set(avgRating);
}
};
module.exports = ProfessionalModel;