Spaces:
Paused
Paused
File size: 22,663 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 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 | const BookingModel = require('../models/bookingModel');
const ProfessionalModel = require('../models/professionalModel');
const UserModel = require('../models/userModel');
const {
sendNotificationToUser,
sendNewBookingNotification,
sendPriceOfferNotification,
sendBookingAcceptedNotification,
sendJobCompletedByCustomerNotification,
} = require('../utils/notifications');
const { deductCommission } = require('../services/walletService');
const BookingController = {
// POST /api/bookings - Customer creates booking
async createBooking(req, res) {
try {
const customerId = req.user.uid;
const {
professionalId,
serviceType,
proposedPrice,
customerProblem,
customerLocation,
customerAddress,
description,
address,
scheduledTime,
contactMethod,
} = req.body;
if (!professionalId || !serviceType) {
return res.status(400).json({
success: false,
message: 'professionalId and serviceType are required.',
});
}
let proUid = professionalId;
let professional = await ProfessionalModel.getById(professionalId);
if (!professional) {
professional = await ProfessionalModel.getByPhone(professionalId);
if (professional?.uid) proUid = professional.uid;
}
if (!professional) {
return res.status(404).json({
success: false,
message: 'Professional not found.',
});
}
const customerUser = await UserModel.getById(customerId, true);
const proUser = await UserModel.getById(proUid, true);
const proAddress = customerAddress || address || proUser?.address || professional.location?.address || '';
const booking = await BookingModel.create({
customerId,
professionalId: proUid,
serviceType,
proposedPrice: parseFloat(proposedPrice || 0),
customerProblem: customerProblem || description || '',
customerLocation: customerLocation || { lat: 0, lng: 0 },
customerAddress: proAddress,
address: proAddress,
description: description || customerProblem || '',
scheduledTime: scheduledTime || null,
customerPhone: customerUser?.phoneNumber || '',
customerName: customerUser?.displayName || req.user.displayName || 'Customer',
professionalPhone: professional.phoneNumber || professional.phone || '',
professionalLocation: professional.location || null,
contactMethod: req.body?.contactMethod || 'direct_contact',
});
// Send notification to professional
const customerName = customerUser?.displayName || req.user.displayName || 'A customer';
const contactLabel =
contactMethod === 'whatsapp'
? 'WhatsApp Now'
: contactMethod === 'call'
? 'Call Now'
: 'contact request';
await sendNotificationToUser(
proUid,
'π£ New Contact Request!',
`${customerName} tapped ${contactLabel} on your profile.`,
{
type: 'contact_request',
bookingId: booking.bookingId,
contactMethod: contactMethod || '',
customerId,
}
);
return res.status(201).json({
success: true,
message: 'Service request sent successfully.',
data: {
...booking,
status: 'pending_acceptance',
contactInfo: {
phone: professional.phoneNumber || professional.phone || '',
location: professional.location || null,
name: professional.name || proUser?.displayName || 'Professional',
},
phoneRevealed: true,
},
});
} catch (error) {
console.error('createBooking error:', error);
return res.status(500).json({
success: false,
message: 'Failed to create booking.',
});
}
},
// GET /api/bookings/my - Get user's bookings
async getMyBookings(req, res) {
try {
const uid = req.user.uid;
const bookings = await BookingModel.getByUserId(uid);
const enrichedBookings = await Promise.all(bookings.map(async (booking) => {
const isCustomer = booking.customerId === uid;
const otherUserId = isCustomer ? booking.professionalId : booking.customerId;
const otherUser = await UserModel.getById(otherUserId, true);
const showPhone = true;
return {
...booking,
otherUserName: otherUser?.displayName || 'User',
otherUserPhoto: otherUser?.photoURL || '',
otherUserPhone: showPhone ? (otherUser?.phoneNumber || 'Not provided') : 'Hidden until agreement',
isCustomer
};
}));
return res.status(200).json({
success: true,
data: enrichedBookings,
count: enrichedBookings.length
});
} catch (error) {
console.error('getMyBookings error:', error);
return res.status(500).json({
success: false,
message: 'Failed to fetch bookings.'
});
}
},
// GET /api/bookings/:bookingId - Get single booking details
async getBooking(req, res) {
try {
const { bookingId } = req.params;
const uid = req.user.uid;
const booking = await BookingModel.getById(bookingId);
if (!booking) {
return res.status(404).json({
success: false,
message: 'Booking not found.'
});
}
if (booking.customerId !== uid && booking.professionalId !== uid) {
return res.status(403).json({
success: false,
message: 'Access denied.'
});
}
const isCustomer = booking.customerId === uid;
const otherUserId = isCustomer ? booking.professionalId : booking.customerId;
const [otherUser, professionalProfile] = await Promise.all([
UserModel.getById(otherUserId, true),
isCustomer ? ProfessionalModel.getById(booking.professionalId) : Promise.resolve(null)
]);
const showPhone = true;
return res.status(200).json({
success: true,
data: {
...booking,
otherUserName: otherUser?.displayName || 'User',
otherUserPhoto: otherUser?.photoURL || '',
otherUserPhone: showPhone ? (otherUser?.phoneNumber || 'Not provided') : 'Hidden until agreement',
professionalLocation: professionalProfile?.location || null,
isCustomer
}
});
} catch (error) {
console.error('getBooking error:', error);
return res.status(500).json({
success: false,
message: 'Failed to fetch booking.'
});
}
},
// POST /api/bookings/:id/propose-price - Professional proposes price
async proposePrice(req, res) {
try {
const { bookingId } = req.params;
const { price } = req.body;
const professionalId = req.user.uid;
if (!price) {
return res.status(400).json({ success: false, message: 'Price is required.' });
}
const booking = await BookingModel.getById(bookingId);
if (!booking) {
return res.status(404).json({ success: false, message: 'Booking not found.' });
}
if (booking.professionalId !== professionalId) {
return res.status(403).json({ success: false, message: 'Only the assigned professional can propose a price.' });
}
const updatedBooking = await BookingModel.proposePrice(bookingId, parseFloat(price));
// Send notification to customer
const professionalUser = await UserModel.getById(professionalId, true);
const professionalName = professionalUser?.displayName || 'Professional';
await sendPriceOfferNotification(booking.customerId, professionalName, parseFloat(price), bookingId);
return res.status(200).json({
success: true,
message: 'Price proposal sent successfully.',
data: updatedBooking
});
} catch (error) {
console.error('proposePrice error:', error);
return res.status(500).json({ success: false, message: 'Failed to send price proposal.' });
}
},
// POST /api/bookings/:id/counter-price - Customer counters price
async counterPrice(req, res) {
try {
const { bookingId } = req.params;
const { counterPrice } = req.body;
const customerId = req.user.uid;
if (!counterPrice) {
return res.status(400).json({ success: false, message: 'Counter price is required.' });
}
const booking = await BookingModel.getById(bookingId);
if (!booking) {
return res.status(404).json({ success: false, message: 'Booking not found.' });
}
if (booking.customerId !== customerId) {
return res.status(403).json({ success: false, message: 'Only the customer can counter the price.' });
}
const updatedBooking = await BookingModel.counterPrice(bookingId, parseFloat(counterPrice));
// Send notification to professional
const customerUser = await UserModel.getById(customerId, true);
const customerName = customerUser?.displayName || 'Customer';
await sendNotificationToUser(
booking.professionalId,
'πΈ Counter Bid Received',
`${customerName} proposed a counter price of Rs. ${counterPrice}.`,
{ bookingId, type: 'price_update', counterPrice: counterPrice.toString() }
);
return res.status(200).json({
success: true,
message: 'Counter offer proposed successfully.',
data: updatedBooking
});
} catch (error) {
console.error('counterPrice error:', error);
return res.status(500).json({ success: false, message: 'Failed to propose counter offer.' });
}
},
// POST /api/bookings/:id/accept-price - Accepts price
async acceptPrice(req, res) {
try {
const { bookingId } = req.params;
const { price } = req.body;
const uid = req.user.uid;
if (!price) {
return res.status(400).json({ success: false, message: 'Price is required to accept.' });
}
const booking = await BookingModel.getById(bookingId);
if (!booking) {
return res.status(404).json({ success: false, message: 'Booking not found.' });
}
if (booking.customerId !== uid && booking.professionalId !== uid) {
return res.status(403).json({ success: false, message: 'Access denied.' });
}
const updatedBooking = await BookingModel.acceptPrice(bookingId, parseFloat(price));
// Notify other user
const isCustomer = booking.customerId === uid;
const otherUserId = isCustomer ? booking.professionalId : booking.customerId;
const otherUser = await UserModel.getById(otherUserId, true);
const otherName = otherUser?.displayName || (isCustomer ? 'Professional' : 'Customer');
await sendNotificationToUser(
otherUserId,
'π€ Deal Confirmed!',
`${otherName} has accepted the price of Rs. ${price}. Contact details are now available.`,
{ bookingId, type: 'bid_agreed', price: price.toString() }
);
return res.status(200).json({
success: true,
message: 'Price accepted. Deal confirmed and contact details revealed.',
data: updatedBooking
});
} catch (error) {
console.error('acceptPrice error:', error);
return res.status(500).json({ success: false, message: 'Failed to accept price.' });
}
},
// POST /api/bookings/:id/accept - Legacy accept booking
async acceptBooking(req, res) {
try {
const { bookingId } = req.params;
const uid = req.user.uid;
const booking = await BookingModel.getById(bookingId);
if (!booking) {
return res.status(404).json({ success: false, message: 'Booking not found.' });
}
if (booking.customerId !== uid && booking.professionalId !== uid) {
return res.status(403).json({ success: false, message: 'Access denied.' });
}
const price = Number(
req.body?.price ||
booking.proposedPrice ||
booking.counterPrice ||
booking.agreedPrice ||
0
);
if (!price || price <= 0) {
return res.status(400).json({ success: false, message: 'No valid offer price found.' });
}
const updatedBooking = await BookingModel.acceptPrice(bookingId, price);
// Send notification
const isCustomer = booking.customerId === uid;
const otherUserId = isCustomer ? booking.professionalId : booking.customerId;
await sendBookingAcceptedNotification(otherUserId, price, bookingId);
return res.status(200).json({
success: true,
message: 'Booking confirmed. Contact details revealed.',
data: updatedBooking,
});
} catch (error) {
console.error('acceptBooking error:', error);
return res.status(500).json({ success: false, message: 'Failed to accept booking.' });
}
},
// POST /api/bookings/:id/reject - Rejects booking
async rejectBooking(req, res) {
try {
const { bookingId } = req.params;
const uid = req.user.uid;
const booking = await BookingModel.getById(bookingId);
if (!booking) {
return res.status(404).json({ success: false, message: 'Booking not found.' });
}
if (booking.customerId !== uid && booking.professionalId !== uid) {
return res.status(403).json({ success: false, message: 'Access denied.' });
}
await BookingModel.rejectBooking(bookingId);
// Notify other user
const isCustomer = booking.customerId === uid;
const otherUserId = isCustomer ? booking.professionalId : booking.customerId;
const otherUser = await UserModel.getById(otherUserId, true);
if (otherUser?.fcmToken) {
await sendNotificationToUser(
otherUserId,
'β Service Request Cancelled',
`The ${isCustomer ? 'customer' : 'professional'} has cancelled the request.`,
{ bookingId, type: 'booking_cancelled' }
);
}
return res.status(200).json({
success: true,
message: 'Booking rejected.',
data: { bookingId, status: 'rejected' }
});
} catch (error) {
console.error('rejectBooking error:', error);
return res.status(500).json({ success: false, message: 'Failed to reject booking.' });
}
},
// POST /api/bookings/:id/start - Professional starts job
async startJob(req, res) {
try {
const { bookingId } = req.params;
const professionalId = req.user.uid;
const booking = await BookingModel.getById(bookingId);
if (!booking) {
return res.status(404).json({ success: false, message: 'Booking not found.' });
}
if (booking.professionalId !== professionalId) {
return res.status(403).json({ success: false, message: 'Only the assigned professional can start the job.' });
}
if (booking.status !== 'confirmed') {
return res.status(400).json({ success: false, message: `Cannot start job. Current status: ${booking.status}` });
}
const updated = await BookingModel.startJob(bookingId);
// Notify customer
await sendNotificationToUser(
booking.customerId,
'π οΈ Job Started',
'The professional has started working on your request.',
{ bookingId, type: 'job_started' }
);
return res.status(200).json({
success: true,
message: 'Job started successfully.',
data: updated
});
} catch (error) {
console.error('startJob error:', error);
return res.status(500).json({ success: false, message: 'Failed to start job.' });
}
},
// POST /api/bookings/:id/complete - Professional completes job
async completeBooking(req, res) {
try {
const { bookingId } = req.params;
const professionalId = req.user.uid;
const booking = await BookingModel.getById(bookingId);
if (!booking) {
return res.status(404).json({ success: false, message: 'Booking not found.' });
}
if (booking.professionalId !== professionalId) {
return res.status(403).json({ success: false, message: 'Only the assigned professional can complete the job.' });
}
if (booking.status !== 'customer_confirmed') {
return res.status(400).json({ success: false, message: `Cannot complete job. Current status: ${booking.status}` });
}
const updated = await BookingModel.professionalConfirmCompletion(bookingId);
const finalAmount = Number(
booking.agreedPrice || booking.proposedPrice || booking.counterPrice || 0,
);
// Deduct 10% commission
const walletRes = await deductCommission({
professionalId: professionalId,
bookingId,
amount: finalAmount,
});
if (!walletRes.success) {
return res.status(walletRes.statusCode || 500).json({
success: false,
message: walletRes.message || 'Failed to deduct commission after completion.',
});
}
// Notify customer
await sendNotificationToUser(
booking.customerId,
'π Job Completed',
'The professional has marked the job as completed. Thank you for using Service Connect!',
{ bookingId, type: 'job_completed' }
);
return res.status(200).json({
success: true,
message: 'Job completed successfully and commission deducted.',
data: {
...updated,
wallet: walletRes.data,
}
});
} catch (error) {
console.error('completeBooking error:', error);
return res.status(500).json({ success: false, message: 'Failed to complete booking.' });
}
},
// POST /api/bookings/:id/customer-complete - Customer confirms completion
async customerComplete(req, res) {
try {
const { bookingId } = req.params;
const customerId = req.user.uid;
const booking = await BookingModel.getById(bookingId);
if (!booking) {
return res.status(404).json({ success: false, message: 'Booking not found.' });
}
if (booking.customerId !== customerId) {
return res.status(403).json({ success: false, message: 'Only customer can confirm completion.' });
}
if (booking.status !== 'in_progress') {
return res.status(400).json({ success: false, message: `Cannot confirm completion. Current status: ${booking.status}` });
}
const updated = await BookingModel.customerConfirmCompletion(bookingId);
// Send notification to professional
await sendJobCompletedByCustomerNotification(booking.professionalId, booking.customerName || 'Customer', bookingId);
return res.status(200).json({
success: true,
message: 'Customer completion confirmed. Waiting for professional confirmation.',
data: updated,
});
} catch (error) {
console.error('customerComplete error:', error);
return res.status(500).json({ success: false, message: 'Failed to confirm completion.' });
}
},
// DELETE /api/bookings/:bookingId - Cancel booking
async cancelBooking(req, res) {
try {
const { bookingId } = req.params;
const uid = req.user.uid;
const booking = await BookingModel.getById(bookingId);
if (!booking) {
return res.status(404).json({ success: false, message: 'Booking not found.' });
}
if (booking.customerId !== uid) {
return res.status(403).json({ success: false, message: 'Only the customer can cancel the booking request.' });
}
await BookingModel.cancel(bookingId);
// Notify professional
await sendNotificationToUser(
booking.professionalId,
'β Request Cancelled',
'The customer has cancelled their service request.',
{ bookingId, type: 'booking_cancelled' }
);
return res.status(200).json({
success: true,
message: 'Booking request cancelled.',
data: { bookingId, status: 'cancelled' }
});
} catch (error) {
console.error('cancelBooking error:', error);
return res.status(500).json({ success: false, message: 'Failed to cancel booking.' });
}
},
// POST /api/bookings/:bookingId/rate - Customer rates professional
async rateBooking(req, res) {
try {
const { bookingId } = req.params;
const { rating, review } = req.body;
const customerId = req.user.uid;
const booking = await BookingModel.getById(bookingId);
if (!booking) {
return res.status(404).json({ success: false, message: 'Booking not found.' });
}
if (booking.customerId !== customerId) {
return res.status(403).json({ success: false, message: 'Only the customer can rate this booking.' });
}
if (booking.status !== 'completed') {
return res.status(400).json({ success: false, message: 'Booking must be completed before rating.' });
}
if (!rating || rating < 1 || rating > 5) {
return res.status(400).json({ success: false, message: 'Rating must be between 1 and 5.' });
}
await BookingModel.addRating(bookingId, rating, review || '');
await ProfessionalModel.updateRating(booking.professionalId, rating);
return res.status(200).json({
success: true,
message: 'Rating submitted successfully.',
data: { bookingId, rating, review: review || '' }
});
} catch (error) {
console.error('rateBooking error:', error);
return res.status(500).json({ success: false, message: 'Failed to submit rating.' });
}
},
// Legacy support
async getCustomerBookings(req, res) {
return BookingController.getMyBookings(req, res);
},
async getProfessionalBookings(req, res) {
return BookingController.getMyBookings(req, res);
},
// GET /api/bookings/professional/:id
async getProfessionalBookingsById(req, res) {
try {
const { id } = req.params;
const uid = req.user.uid;
if (uid !== id) {
return res.status(403).json({
success: false,
message: 'Access denied.',
});
}
const bookings = await BookingModel.getByProfessionalId(id);
return res.status(200).json({
success: true,
data: bookings,
count: bookings.length,
});
} catch (error) {
console.error('getProfessionalBookingsById error:', error);
return res.status(500).json({
success: false,
message: 'Failed to fetch professional bookings.',
});
}
}
};
module.exports = BookingController;
|