Spaces:
Paused
Paused
File size: 12,918 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 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 | const ProfessionalModel = require('../models/professionalModel');
const UserModel = require('../models/userModel');
const TransactionModel = require('../models/transactionModel');
const BookingModel = require('../models/bookingModel');
const { uploadMultipleToImgBB } = require('../utils/imgbb');
// Helper: Calculate distance between two coordinates (Haversine formula)
function calculateDistance(lat1, lon1, lat2, lon2) {
const R = 6371; // Earth's radius in km
const dLat = (lat2 - lat1) * Math.PI / 180;
const dLon = (lon2 - lon1) * Math.PI / 180;
const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
Math.sin(dLon/2) * Math.sin(dLon/2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
}
const ProfessionalController = {
// GET /api/professionals/all - Get all professionals (public, hides phone)
async getAll(req, res) {
try {
const professionals = await ProfessionalModel.getAll();
const formatted = professionals.map(pro => ({
uid: pro.uid,
name: pro.name,
services: pro.services || [],
customServices: pro.customServices || [],
location: pro.location || { lat: 0, lng: 0 },
rating: pro.rating || 0,
isAvailable: pro.isAvailable !== false,
photoURL: pro.photoURL || '',
hourlyRate: pro.hourlyRate || 500,
phoneNumber: 'Hidden until agreement',
description: pro.description || ''
}));
return res.json({ success: true, data: formatted, count: formatted.length });
} catch (error) {
console.error('getAll error:', error);
return res.status(500).json({ success: false, message: 'Failed to fetch professionals.' });
}
},
// GET /api/professionals/nearby - Get professionals sorted by distance
async getNearby(req, res) {
try {
const { lat, lng, radius = 10, serviceType } = req.query;
if (!lat || !lng) {
return res.status(400).json({ success: false, message: 'lat and lng are required.' });
}
const customerLat = parseFloat(lat);
const customerLng = parseFloat(lng);
const radiusKm = parseFloat(radius);
const professionals = await ProfessionalModel.getNearby({
lat: customerLat,
lng: customerLng,
radiusKm,
serviceType
});
// Map and hide phone numbers
const formatted = professionals.map(pro => ({
...pro,
phoneNumber: 'Hidden until agreement'
}));
return res.json({ success: true, data: formatted, count: formatted.length });
} catch (error) {
console.error('getNearby error:', error);
return res.status(500).json({ success: false, message: 'Failed to fetch nearby professionals.' });
}
},
// GET /api/professionals/:uid - Get single professional by UID (hides phone unless booking confirmed)
async getByUid(req, res) {
try {
const { uid } = req.params;
const professional = await ProfessionalModel.getById(uid);
if (!professional) {
return res.status(404).json({ success: false, message: 'Professional not found.' });
}
// By default hide phone number unless requested by customer who has a confirmed booking
let phoneRevealed = false;
if (req.user) {
const bookings = await BookingModel.getByUserId(req.user.uid);
phoneRevealed = bookings.some(b =>
b.professionalId === uid &&
['confirmed', 'in_progress', 'completed'].includes(b.status)
);
}
return res.json({
success: true,
data: {
uid: professional.uid,
name: professional.name,
services: professional.services || [],
customServices: professional.customServices || [],
location: professional.location,
rating: professional.rating || 0,
isAvailable: professional.isAvailable !== false,
photoURL: professional.photoURL || '',
hourlyRate: professional.hourlyRate || 500,
description: professional.description || '',
phoneNumber: phoneRevealed ? professional.phoneNumber : 'Hidden until agreement'
}
});
} catch (error) {
console.error('getByUid error:', error);
return res.status(500).json({ success: false, message: 'Failed to fetch professional.' });
}
},
// POST /api/professionals/profile - Create/update professional profile
async upsertProfile(req, res) {
try {
const uid = req.user.uid;
const { name, services, customServices, phoneNumber, location, photoURL, description, hourlyRate } = req.body;
if (!name) {
return res.status(400).json({ success: false, message: 'Name is required.' });
}
if (!phoneNumber) {
return res.status(400).json({ success: false, message: 'Phone number is required.' });
}
const pkPhone = /^(03\d{9}|3\d{9})$/;
if (!pkPhone.test(phoneNumber.replace(/\s|-/g, ''))) {
return res.status(400).json({
success: false,
message: 'Please enter a valid Pakistani mobile number (e.g., 03001234567).',
});
}
if (!services || !Array.isArray(services) || services.length === 0) {
return res.status(400).json({ success: false, message: 'At least one service is required.' });
}
if (!location || location.lat === undefined || location.lng === undefined) {
return res.status(400).json({ success: false, message: 'Location (lat, lng) is required.' });
}
const existing = await ProfessionalModel.getById(uid);
const profileData = {
name,
services,
customServices: customServices || [],
phoneNumber,
location: {
lat: parseFloat(location.lat),
lng: parseFloat(location.lng),
address: location.address || '',
},
description: description || existing?.description || '',
photoURL: photoURL || existing?.photoURL || '',
hourlyRate: hourlyRate ? parseFloat(hourlyRate) : (existing?.hourlyRate || 500),
walletBalance: existing ? existing.walletBalance : 5000,
totalEarnings: existing ? existing.totalEarnings : 0,
completedJobs: existing ? existing.completedJobs : 0,
rating: existing ? existing.rating : 0
};
const saved = await ProfessionalModel.upsert(uid, profileData);
// Update professional details in UserModel as well
await UserModel.upsert(uid, {
displayName: name,
phoneNumber,
photoURL: photoURL || '',
profileCompleted: true,
location: profileData.location
});
return res.status(201).json({
success: true,
message: existing ? 'Profile updated successfully.' : 'Professional profile created successfully.',
data: saved
});
} catch (error) {
console.error('upsertProfile error:', error);
return res.status(500).json({ success: false, message: error.message || 'Failed to save profile.' });
}
},
// POST /api/professionals/availability - Toggle professional availability
async updateAvailability(req, res) {
try {
const uid = req.user.uid;
const { isAvailable } = req.body;
const isAvailableNow = isAvailable === true || isAvailable === 'true';
await ProfessionalModel.updateAvailability(uid, isAvailableNow);
return res.json({
success: true,
data: { isAvailable: isAvailableNow },
message: isAvailableNow ? 'You are now online (visible to customers).' : 'You are now offline (hidden from customers).'
});
} catch (error) {
console.error('updateAvailability error:', error);
return res.status(500).json({ success: false, message: 'Failed to update availability.' });
}
},
// GET /api/professionals/profile - Get own profile (requires auth)
async getOwnProfile(req, res) {
try {
const uid = req.user.uid;
const professional = await ProfessionalModel.getById(uid);
if (!professional) {
return res.json({ success: true, data: { exists: false } });
}
return res.json({
success: true,
data: {
exists: true,
profile: professional
}
});
} catch (error) {
console.error('getOwnProfile error:', error);
return res.status(500).json({ success: false, message: 'Failed to fetch profile.' });
}
},
// GET /api/professionals/wallet - Get wallet balance
async getWallet(req, res) {
try {
const uid = req.user.uid;
const professional = await ProfessionalModel.getById(uid);
if (!professional) {
return res.status(404).json({ success: false, message: 'Professional not found.' });
}
return res.json({
success: true,
data: {
walletBalance: professional.walletBalance || 0,
currency: 'PKR'
}
});
} catch (error) {
return res.status(500).json({ success: false, message: 'Failed to fetch wallet balance.' });
}
},
// GET /api/professionals/transactions - Get transaction history
async getTransactions(req, res) {
try {
const uid = req.user.uid;
const transactions = await TransactionModel.getByProfessionalId(uid);
return res.json({ success: true, data: { transactions } });
} catch (error) {
return res.status(500).json({ success: false, message: 'Failed to fetch transaction history.' });
}
},
// POST /api/professionals/upload-photo - Upload base64 image to ImgBB and update photoURL
async uploadPhoto(req, res) {
try {
const uid = req.user.uid;
const { image } = req.body;
if (!image) {
return res.status(400).json({ success: false, message: 'Image base64 string is required.' });
}
const { uploadToImgBB } = require('../utils/imgbb');
const url = await uploadToImgBB(image, `profile_${uid}_${Date.now()}`);
// Update professional and user models
await ProfessionalModel.updateById(uid, { photoURL: url });
await UserModel.upsert(uid, { photoURL: url });
return res.json({ success: true, data: { photoURL: url }, message: 'Image uploaded successfully.' });
} catch (error) {
console.error('uploadPhoto error:', error);
return res.status(500).json({ success: false, message: 'Failed to upload photo.' });
}
},
// GET /api/professionals/earnings - Get earnings stats
async getEarnings(req, res) {
try {
const uid = req.user.uid;
const professional = await ProfessionalModel.getById(uid);
if (!professional) {
return res.status(404).json({ success: false, message: 'Professional not found.' });
}
const allBookings = await BookingModel.getByUserId(uid);
const completed = allBookings.filter(b => b.status === 'completed');
const active = allBookings.filter(b => ['confirmed', 'in_progress'].includes(b.status));
const transactions = await TransactionModel.getByProfessionalId(uid);
return res.json({
success: true,
data: {
walletBalance: professional.walletBalance || 0,
totalEarnings: professional.totalEarnings || 0,
completedJobs: professional.completedJobs || 0,
activeBookings: active.length,
transactions,
recentBookings: completed.slice(0, 10)
}
});
} catch (error) {
console.error('getEarnings error:', error);
return res.status(500).json({ success: false, message: 'Failed to fetch earnings stats.' });
}
},
// POST /api/professionals/upload-portfolio - Legacy endpoint for portfolio base64 uploads
async uploadPortfolio(req, res) {
try {
const uid = req.user.uid;
const { images } = req.body;
if (!images || !Array.isArray(images) || images.length === 0) {
return res.status(400).json({ success: false, message: 'Array of base64 images is required.' });
}
const urls = await uploadMultipleToImgBB(images);
const portfolio = await ProfessionalModel.addPortfolioImages(uid, urls);
return res.json({ success: true, data: { portfolio }, message: 'Portfolio uploaded successfully.' });
} catch (error) {
console.error('uploadPortfolio error:', error);
return res.status(500).json({ success: false, message: 'Failed to upload portfolio.' });
}
},
// Legacy route maps
async getByPhone(req, res) {
// For compatibility with previous route parameter name
req.params.uid = req.params.phone;
return ProfessionalController.getByUid(req, res);
}
};
module.exports = ProfessionalController;
|