File size: 6,491 Bytes
e3fefe8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 | 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; |