Huzaifa1435 commited on
Commit
fc5fe50
·
verified ·
1 Parent(s): 366364c

Update src/controllers/dealController.js

Browse files
Files changed (1) hide show
  1. src/controllers/dealController.js +179 -145
src/controllers/dealController.js CHANGED
@@ -3,8 +3,7 @@ const { deductBalance, addBalance } = require('../utils/walletHelper');
3
  const { pushToUser } = require('../utils/notificationHelper');
4
  const { RIDE_STATUS, DEAL_STATUS, ACTIVE_DEAL_STATUSES } = require('../constants/statuses');
5
  const { labelFromLocation } = require('../utils/locationLabelHelper');
6
- // Cleanup helpers are now called from a separate scheduled job only
7
- // const { maybeCleanupExpiredRides, maybeAutoArchiveConfirmedDeals, maybeCleanupOldCompletedDeals } = require('../utils/throttledCleanup');
8
  const { seatUpdateFromRide } = require('../utils/seatHelper');
9
  const {
10
  sanitizeString,
@@ -15,9 +14,8 @@ const {
15
  const { CAPTAIN_STARTER_BALANCE } = require('../utils/walletHelper');
16
 
17
  const PLATFORM_FEE_PERCENT = 0.05;
18
- const BOOKING_RETENTION_MS = 24 * 60 * 60 * 1000; // 24 hours – completed bookings disappear after 1 day
19
 
20
- // ---------- Helpers ----------
21
  function generalPickupArea(address) {
22
  if (!address || typeof address !== 'string') return 'Along route';
23
  const parts = address.split(',').map((p) => p.trim()).filter(Boolean);
@@ -57,13 +55,10 @@ async function syncRideStatusFromDeals(rideId) {
57
  return;
58
  }
59
 
60
- const openDeals = deals.filter((d) =>
61
- [DEAL_STATUS.PENDING, DEAL_STATUS.CONFIRMED].includes(d.status),
62
- );
63
  const availableSeats = ride.availableSeats ?? ride.totalSeats ?? 0;
64
 
65
  await rideRef.update({
66
- status: availableSeats <= 0 && openDeals.length === 0 ? RIDE_STATUS.FILLED : RIDE_STATUS.ACTIVE,
67
  full: availableSeats <= 0,
68
  updatedAt: new Date().toISOString(),
69
  });
@@ -87,14 +82,8 @@ async function maybeCompleteRide(rideId) {
87
  });
88
  }
89
 
90
- /**
91
- * Populate a single deal with its ride data.
92
- * Used inside Promise.all for parallel fetching.
93
- */
94
  async function populateRide(deal) {
95
  if (!deal.rideId) return deal;
96
- // If ride data already exists (denormalized), skip fetch
97
- if (deal.ride) return deal;
98
  const rideDoc = await db.collection('rides').doc(deal.rideId).get();
99
  if (!rideDoc.exists) return deal;
100
  const ride = rideDoc.data();
@@ -188,6 +177,11 @@ async function getCaptainReviewSummary(captainId, limit = 5) {
188
  }
189
 
190
  // ---------- REUSABLE CONFIRM TRANSACTION ----------
 
 
 
 
 
191
  async function _executeConfirmTransaction(dealId, actorUid, options = {}) {
192
  const { skipOwnershipCheck = false } = options;
193
 
@@ -199,12 +193,16 @@ async function _executeConfirmTransaction(dealId, actorUid, options = {}) {
199
  const isCaptain = preDeal.captainId === actorUid;
200
  const isCustomer = preDeal.customerId === actorUid;
201
 
 
202
  if (!skipOwnershipCheck && !isCaptain && !isCustomer) {
203
  throw Object.assign(new Error('Not your deal'), { code: 'UNAUTHORIZED' });
204
  }
 
 
205
  if (!skipOwnershipCheck && isCustomer && preDeal.lastCounterBy !== 'captain') {
206
  throw Object.assign(new Error('Only captain can confirm this deal'), { code: 'UNAUTHORIZED' });
207
  }
 
208
  if (preDeal.status !== DEAL_STATUS.PENDING) {
209
  throw Object.assign(new Error('Deal already processed'), { code: 'INVALID_STATE' });
210
  }
@@ -234,8 +232,14 @@ async function _executeConfirmTransaction(dealId, actorUid, options = {}) {
234
  const rideDoc = await t.get(rideRef);
235
  if (!rideDoc.exists) throw new Error('Ride not found');
236
  const ride = rideDoc.data();
 
 
 
 
 
 
237
  const available = ride.availableSeats ?? ride.totalSeats ?? 0;
238
- if (available <= 0) {
239
  throw Object.assign(new Error('Ride is full'), { code: 'RIDE_FULL', statusCode: 400 });
240
  }
241
 
@@ -299,6 +303,8 @@ async function _executeConfirmTransaction(dealId, actorUid, options = {}) {
299
  });
300
 
301
  await syncRideStatusFromDeals(preDeal.rideId);
 
 
302
  const notifyRecipient = (isCustomer || skipOwnershipCheck) ? captainId : customerId;
303
  await pushToUser(notifyRecipient, {
304
  title: 'Booking confirmed',
@@ -309,11 +315,11 @@ async function _executeConfirmTransaction(dealId, actorUid, options = {}) {
309
 
310
  return { commission, newBalance };
311
  }
312
-
313
- // ---------- CONTROLLER ENDPOINTS ----------
314
 
315
  /**
316
- * createDeal – stores ride snapshot (denormalized) and auto-confirms if fare matches
 
317
  */
318
  const createDeal = async (req, res) => {
319
  const uid = req.user.uid;
@@ -360,6 +366,7 @@ const createDeal = async (req, res) => {
360
  if (!rideDoc.exists) {
361
  return res.status(404).json({ success: false, error: 'Ride not found', code: 'RIDE_NOT_FOUND' });
362
  }
 
363
  const rideData = rideDoc.data();
364
  const isSelfBooking = rideData.captainId === uid;
365
  if (isSelfBooking) {
@@ -389,32 +396,10 @@ const createDeal = async (req, res) => {
389
  const captainUserDoc = await db.collection('users').doc(captainId).get();
390
  const captainPhone = captainUserDoc.exists ? (captainUserDoc.data().phone || '') : '';
391
 
 
392
  const suggestedFare = Number(rideData.suggestedFare || 0);
393
  const isNegotiated = parseFloat(agreedFare) !== suggestedFare;
394
 
395
- // Build denormalized ride snapshot
396
- const rideSnapshot = {
397
- id: rideId,
398
- startLocation: rideData.startLocation,
399
- endLocation: rideData.endLocation,
400
- exactLocation: rideData.exactLocation,
401
- exactDropLocation: rideData.exactDropLocation,
402
- startLat: rideData.startLat,
403
- startLng: rideData.startLng,
404
- endLat: rideData.endLat,
405
- endLng: rideData.endLng,
406
- departureTime: rideData.departureTime,
407
- captainName: rideData.captainName,
408
- captainId: rideData.captainId,
409
- vehicleInfo: rideData.vehicleInfo,
410
- vehiclePhotoUrl: rideData.vehiclePhotoUrl,
411
- suggestedFare: rideData.suggestedFare,
412
- status: rideData.status,
413
- availableSeats: rideData.availableSeats,
414
- totalSeats: rideData.totalSeats,
415
- full: rideData.full === true || (rideData.availableSeats || 0) <= 0,
416
- };
417
-
418
  const dealData = await db.runTransaction(async (t) => {
419
  const ride = await t.get(rideRef);
420
  if (!ride.exists) throw new Error('Ride not found');
@@ -439,7 +424,6 @@ const createDeal = async (req, res) => {
439
  const data = {
440
  id: dealRef.id,
441
  rideId,
442
- ride: rideSnapshot, // denormalized
443
  captainId: rideData.captainId,
444
  customerId: uid,
445
  customerName: userDoc.data().name || 'Guest',
@@ -448,7 +432,7 @@ const createDeal = async (req, res) => {
448
  phoneRevealed: false,
449
  agreedFare: parseFloat(agreedFare),
450
  platformFee,
451
- status: DEAL_STATUS.PENDING,
452
  customerMessage: sanitizedMessage,
453
  passengerPickupLat: pickupLat,
454
  passengerPickupLng: pickupLng,
@@ -468,22 +452,27 @@ const createDeal = async (req, res) => {
468
  return data;
469
  });
470
 
471
- // Auto-confirm if fare matches
 
472
  if (!isNegotiated) {
473
  try {
474
  await _executeConfirmTransaction(dealRef.id, uid, { skipOwnershipCheck: true });
475
  console.log(`✅ Auto-confirmed deal ${dealRef.id} (fare matched)`);
476
  } catch (err) {
 
477
  console.warn(`⚠️ Auto-confirm failed for deal ${dealRef.id}: ${err.message}`);
 
478
  await pushToUser(captainId, {
479
  title: 'Booking received but not confirmed',
480
  body: 'A passenger booked your ride, but your wallet balance is insufficient to confirm. Please add balance.',
481
  type: 'wallet_insufficient',
482
  data: { dealId: dealRef.id, rideId },
483
  });
 
484
  }
485
  }
486
 
 
487
  await pushToUser(captainId, {
488
  title: isNegotiated ? 'New Booking Request!' : 'New Booking Confirmed!',
489
  body: `${dealData.customerName} wants to ride with you.${isNegotiated ? ' Tap to respond.' : ' It is confirmed.'}`,
@@ -497,6 +486,10 @@ const createDeal = async (req, res) => {
497
  }
498
  };
499
 
 
 
 
 
500
  const confirmDeal = async (req, res) => {
501
  const { dealId } = req.params;
502
  const uid = req.user.uid;
@@ -510,7 +503,7 @@ const confirmDeal = async (req, res) => {
510
  newBalance: result.newBalance,
511
  });
512
  } catch (err) {
513
- const status = err.statusCode || 400;
514
  return res.status(status).json({
515
  success: false,
516
  error: err.message,
@@ -521,6 +514,9 @@ const confirmDeal = async (req, res) => {
521
  }
522
  };
523
 
 
 
 
524
  const cancelDeal = async (req, res) => {
525
  const { dealId } = req.params;
526
  const uid = req.user.uid;
@@ -583,6 +579,9 @@ const cancelDeal = async (req, res) => {
583
  }
584
  };
585
 
 
 
 
586
  const counterDeal = async (req, res) => {
587
  const { dealId } = req.params;
588
  const uid = req.user.uid;
@@ -615,7 +614,7 @@ const counterDeal = async (req, res) => {
615
  lastCounterBy: isCaptain ? 'captain' : 'customer',
616
  lastCounterAt: now,
617
  updatedAt: now,
618
- isNegotiated: true,
619
  };
620
  if (message != null && String(message).trim().length > 0) {
621
  if (exceedsMaxLength(message, MAX_CUSTOMER_MESSAGE)) {
@@ -649,6 +648,9 @@ const counterDeal = async (req, res) => {
649
  }
650
  };
651
 
 
 
 
652
  const startDeal = async (req, res) => {
653
  const { dealId } = req.params;
654
  const uid = req.user.uid;
@@ -668,6 +670,7 @@ const startDeal = async (req, res) => {
668
  }
669
 
670
  const startedAt = new Date().toISOString();
 
671
  await dealRef.update({
672
  status: DEAL_STATUS.STARTED,
673
  startedAt,
@@ -692,6 +695,9 @@ const startDeal = async (req, res) => {
692
  }
693
  };
694
 
 
 
 
695
  const completeDeal = async (req, res) => {
696
  const { dealId } = req.params;
697
  const uid = req.user.uid;
@@ -752,8 +758,15 @@ const completeDeal = async (req, res) => {
752
  }
753
  };
754
 
 
 
 
755
  const getDeal = async (req, res) => {
756
  try {
 
 
 
 
757
  const doc = await db.collection('deals').doc(req.params.dealId).get();
758
  if (!doc.exists) {
759
  return res.status(404).json({ success: false, error: 'Deal not found', code: 'DEAL_NOT_FOUND' });
@@ -801,6 +814,9 @@ const getDeal = async (req, res) => {
801
  }
802
  };
803
 
 
 
 
804
  const rateDeal = async (req, res) => {
805
  const { dealId } = req.params;
806
  const uid = req.user.uid;
@@ -888,79 +904,69 @@ const rateDeal = async (req, res) => {
888
  };
889
 
890
  /**
891
- * ✅ getMyBookings – optimized: skips ride fetch for denormalized deals, clean cursor pagination
892
  */
893
  const getMyBookings = async (req, res) => {
894
  try {
895
- const limit = Math.min(parseInt(req.query.limit) || 20, 50);
896
-
897
- // Build base query ordered by createdAt descending
898
- let query = db.collection('deals')
 
 
899
  .where('customerId', '==', req.user.uid)
900
  .orderBy('createdAt', 'desc')
901
- .limit(limit);
902
-
903
- // ✅ FIXED: Use createdAt ISO string directly as cursor value.
904
- // Firestore allows startAfter() with a raw field value when the query
905
- // is ordered by that field — no second round-trip needed.
906
- if (req.query.startAfter) {
907
- query = query.startAfter(req.query.startAfter);
908
- }
909
 
910
- const snap = await query.get();
911
  const now = Date.now();
912
- const dealsToPopulate = [];
913
-
914
- for (const doc of snap.docs) {
915
- const deal = { id: doc.id, ...doc.data() };
916
- const status = (deal.status || '').toString().toLowerCase();
917
-
918
- // ✅ Exclude terminal deals older than BOOKING_RETENTION_MS (24 hours)
919
- if ([DEAL_STATUS.COMPLETED, DEAL_STATUS.CANCELLED].includes(status)) {
920
- // Prefer completedAt, then updatedAt, then createdAt
921
- const terminalAtRaw = deal.completedAt || deal.updatedAt || deal.createdAt || null;
922
- const terminalAt = terminalAtRaw ? new Date(terminalAtRaw).getTime() : NaN;
923
- if (Number.isFinite(terminalAt) && now - terminalAt > BOOKING_RETENTION_MS) {
924
- continue; // Skip – older than retention window
925
- }
926
- }
927
- dealsToPopulate.push(deal);
928
- }
929
-
930
- // ✅ OPTIMIZED: Skip populateRide() for deals that already carry a denormalized
931
- // ride snapshot (set at deal creation time). Only fetch from Firestore for
932
- // legacy deals that lack the embedded snapshot.
933
- const populatedDeals = await Promise.all(
934
- dealsToPopulate.map(deal => (deal.ride ? Promise.resolve(deal) : populateRide(deal)))
 
 
 
 
 
935
  );
936
 
937
- const bookings = populatedDeals.map(deal => {
938
- const phoneRevealed = deal.phoneRevealed === true;
939
- const fullCaptainPhone = deal.captainPhone || '';
940
- deal.captainPhone = phoneRevealed ? fullCaptainPhone : maskCaptainPhone(fullCaptainPhone);
941
- return normalizeBooking(deal);
942
- });
943
-
944
- const hasMore = snap.docs.length === limit && bookings.length > 0;
945
- const nextCursor = snap.docs.length > 0 ? snap.docs[snap.docs.length - 1].data().createdAt : null;
946
-
947
- return res.json({
948
- success: true,
949
- bookings,
950
- hasMore,
951
- nextCursor,
952
- });
953
  } catch (err) {
 
954
  return res.status(500).json({ success: false, error: err.message, code: 'GET_MY_BOOKINGS_ERROR' });
955
  }
956
  };
957
 
958
  /**
959
- * ✅ getMyDeals – parallel ride fetch, no pagination (can be added later)
960
  */
961
  const getMyDeals = async (req, res) => {
962
  try {
 
 
 
 
963
  const captainId = req.user.uid;
 
964
  const snap = await db
965
  .collection('deals')
966
  .where('captainId', '==', captainId)
@@ -968,49 +974,59 @@ const getMyDeals = async (req, res) => {
968
  .get();
969
 
970
  const now = Date.now();
971
- const deals = [];
972
- for (const doc of snap.docs) {
973
- let deal = { id: doc.id, ...doc.data() };
974
- const status = (deal.status || '').toString().toLowerCase();
975
-
976
- if ([DEAL_STATUS.COMPLETED, DEAL_STATUS.CANCELLED].includes(status)) {
977
- const terminalAtRaw = deal.completedAt || deal.updatedAt || deal.createdAt || null;
978
- const terminalAt = terminalAtRaw ? new Date(terminalAtRaw).getTime() : NaN;
979
- if (Number.isFinite(terminalAt) && Date.now() - terminalAt > BOOKING_RETENTION_MS) {
980
- continue;
981
- }
982
- }
983
- deals.push(deal);
984
- }
985
 
986
- const populatedDeals = await Promise.all(deals.map(async (deal) => {
987
- deal = await populateRide(deal);
988
- if (deal.customerId) {
989
- const customer = await db.collection('users').doc(deal.customerId).get();
990
- if (customer.exists) {
991
- const customerData = customer.data();
992
- deal.customer = {
993
- name: customerData.name || 'Customer',
994
- phone: customerData.phone || '',
995
- rating: customerData.rating || 0,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
996
  };
997
- deal.customerName = customerData.name || 'Customer';
998
- deal.customerPhone = customerData.phone || '';
999
- }
1000
- }
1001
- return deal;
1002
- }));
1003
-
1004
- const result = populatedDeals.map(deal => ({
1005
- ...deal,
1006
- tabStatus: normalizeBooking(deal).tabStatus,
1007
- displayStatus: deal.status,
1008
- }));
1009
 
1010
  return res.json({
1011
  success: true,
1012
- deals: result,
1013
- count: result.length,
1014
  });
1015
  } catch (err) {
1016
  console.error('Error in getMyDeals:', err);
@@ -1022,6 +1038,9 @@ const getMyDeals = async (req, res) => {
1022
  }
1023
  };
1024
 
 
 
 
1025
  const getConfirmedPassengers = async (req, res) => {
1026
  const { rideId } = req.params;
1027
  const uid = req.user.uid;
@@ -1102,6 +1121,9 @@ const getConfirmedPassengers = async (req, res) => {
1102
  }
1103
  };
1104
 
 
 
 
1105
  const updateBoardingStatus = async (req, res) => {
1106
  const { dealId } = req.params;
1107
  const uid = req.user.uid;
@@ -1155,9 +1177,16 @@ const updateBoardingStatus = async (req, res) => {
1155
  }
1156
  };
1157
 
 
 
 
1158
  const getRideDeals = async (req, res) => {
1159
  const { rideId } = req.params;
1160
  try {
 
 
 
 
1161
  const rideDoc = await db.collection('rides').doc(rideId).get();
1162
  if (!rideDoc.exists) {
1163
  return res.status(404).json({ success: false, error: 'Ride not found', code: 'RIDE_NOT_FOUND' });
@@ -1172,9 +1201,9 @@ const getRideDeals = async (req, res) => {
1172
  .orderBy('createdAt', 'desc')
1173
  .get();
1174
 
1175
- const deals = snap.docs.map(doc => ({ id: doc.id, ...doc.data() }));
1176
-
1177
- const populatedDeals = await Promise.all(deals.map(async (deal) => {
1178
  const phoneRevealed = deal.phoneRevealed === true;
1179
  const fullCaptainPhone = deal.captainPhone || '';
1180
  deal.captainPhone = phoneRevealed ? fullCaptainPhone : maskCaptainPhone(fullCaptainPhone);
@@ -1190,12 +1219,11 @@ const getRideDeals = async (req, res) => {
1190
  deal.customerPhone = customerPhone;
1191
  }
1192
  }
1193
- return deal;
1194
- }));
1195
-
1196
  return res.json({
1197
  success: true,
1198
- deals: populatedDeals,
1199
  ride: {
1200
  totalSeats: rideDoc.data().totalSeats,
1201
  availableSeats: rideDoc.data().availableSeats,
@@ -1207,6 +1235,9 @@ const getRideDeals = async (req, res) => {
1207
  }
1208
  };
1209
 
 
 
 
1210
  const notifyDealMessage = async (req, res) => {
1211
  const { dealId } = req.params;
1212
  const uid = req.user.uid;
@@ -1238,6 +1269,9 @@ const notifyDealMessage = async (req, res) => {
1238
  }
1239
  };
1240
 
 
 
 
1241
  const getCaptainProfile = async (req, res) => {
1242
  const captainId = req.params.captainId || req.query.captainId;
1243
  if (!captainId) {
 
3
  const { pushToUser } = require('../utils/notificationHelper');
4
  const { RIDE_STATUS, DEAL_STATUS, ACTIVE_DEAL_STATUSES } = require('../constants/statuses');
5
  const { labelFromLocation } = require('../utils/locationLabelHelper');
6
+ const { maybeCleanupExpiredRides, maybeAutoArchiveConfirmedDeals, maybeCleanupOldCompletedDeals } = require('../utils/throttledCleanup');
 
7
  const { seatUpdateFromRide } = require('../utils/seatHelper');
8
  const {
9
  sanitizeString,
 
14
  const { CAPTAIN_STARTER_BALANCE } = require('../utils/walletHelper');
15
 
16
  const PLATFORM_FEE_PERCENT = 0.05;
17
+ const BOOKING_RETENTION_MS = 6 * 60 * 60 * 1000; // 6 hours
18
 
 
19
  function generalPickupArea(address) {
20
  if (!address || typeof address !== 'string') return 'Along route';
21
  const parts = address.split(',').map((p) => p.trim()).filter(Boolean);
 
55
  return;
56
  }
57
 
 
 
 
58
  const availableSeats = ride.availableSeats ?? ride.totalSeats ?? 0;
59
 
60
  await rideRef.update({
61
+ status: availableSeats <= 0 ? RIDE_STATUS.FILLED : RIDE_STATUS.ACTIVE,
62
  full: availableSeats <= 0,
63
  updatedAt: new Date().toISOString(),
64
  });
 
82
  });
83
  }
84
 
 
 
 
 
85
  async function populateRide(deal) {
86
  if (!deal.rideId) return deal;
 
 
87
  const rideDoc = await db.collection('rides').doc(deal.rideId).get();
88
  if (!rideDoc.exists) return deal;
89
  const ride = rideDoc.data();
 
177
  }
178
 
179
  // ---------- REUSABLE CONFIRM TRANSACTION ----------
180
+ /**
181
+ * Internal function to execute the confirm transaction.
182
+ * Can be called by confirmDeal (captain/customer manual) or auto-confirm.
183
+ * Throws error if insufficient balance, ride full, etc.
184
+ */
185
  async function _executeConfirmTransaction(dealId, actorUid, options = {}) {
186
  const { skipOwnershipCheck = false } = options;
187
 
 
193
  const isCaptain = preDeal.captainId === actorUid;
194
  const isCustomer = preDeal.customerId === actorUid;
195
 
196
+ // Allow actor if they are captain or customer (or skip check for auto)
197
  if (!skipOwnershipCheck && !isCaptain && !isCustomer) {
198
  throw Object.assign(new Error('Not your deal'), { code: 'UNAUTHORIZED' });
199
  }
200
+
201
+ // For manual confirm: if customer (not captain) confirms, only if lastCounterBy === 'captain'
202
  if (!skipOwnershipCheck && isCustomer && preDeal.lastCounterBy !== 'captain') {
203
  throw Object.assign(new Error('Only captain can confirm this deal'), { code: 'UNAUTHORIZED' });
204
  }
205
+
206
  if (preDeal.status !== DEAL_STATUS.PENDING) {
207
  throw Object.assign(new Error('Deal already processed'), { code: 'INVALID_STATE' });
208
  }
 
232
  const rideDoc = await t.get(rideRef);
233
  if (!rideDoc.exists) throw new Error('Ride not found');
234
  const ride = rideDoc.data();
235
+ if (ride.status !== RIDE_STATUS.ACTIVE && ride.status !== RIDE_STATUS.FILLED) {
236
+ throw Object.assign(new Error('Ride is no longer available'), {
237
+ code: 'RIDE_UNAVAILABLE',
238
+ statusCode: 400,
239
+ });
240
+ }
241
  const available = ride.availableSeats ?? ride.totalSeats ?? 0;
242
+ if (ride.full === true || available <= 0 || ride.status === RIDE_STATUS.FILLED) {
243
  throw Object.assign(new Error('Ride is full'), { code: 'RIDE_FULL', statusCode: 400 });
244
  }
245
 
 
303
  });
304
 
305
  await syncRideStatusFromDeals(preDeal.rideId);
306
+
307
+ // Notify the other party
308
  const notifyRecipient = (isCustomer || skipOwnershipCheck) ? captainId : customerId;
309
  await pushToUser(notifyRecipient, {
310
  title: 'Booking confirmed',
 
315
 
316
  return { commission, newBalance };
317
  }
318
+ // ------------------------------------------------
 
319
 
320
  /**
321
+ * ✅ FIXED: createDeal - Allow captain to book own ride (testing mode)
322
+ * ✅ Auto-confirm if agreedFare === suggestedFare
323
  */
324
  const createDeal = async (req, res) => {
325
  const uid = req.user.uid;
 
366
  if (!rideDoc.exists) {
367
  return res.status(404).json({ success: false, error: 'Ride not found', code: 'RIDE_NOT_FOUND' });
368
  }
369
+
370
  const rideData = rideDoc.data();
371
  const isSelfBooking = rideData.captainId === uid;
372
  if (isSelfBooking) {
 
396
  const captainUserDoc = await db.collection('users').doc(captainId).get();
397
  const captainPhone = captainUserDoc.exists ? (captainUserDoc.data().phone || '') : '';
398
 
399
+ // Determine if fare matches (no negotiation)
400
  const suggestedFare = Number(rideData.suggestedFare || 0);
401
  const isNegotiated = parseFloat(agreedFare) !== suggestedFare;
402
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
403
  const dealData = await db.runTransaction(async (t) => {
404
  const ride = await t.get(rideRef);
405
  if (!ride.exists) throw new Error('Ride not found');
 
424
  const data = {
425
  id: dealRef.id,
426
  rideId,
 
427
  captainId: rideData.captainId,
428
  customerId: uid,
429
  customerName: userDoc.data().name || 'Guest',
 
432
  phoneRevealed: false,
433
  agreedFare: parseFloat(agreedFare),
434
  platformFee,
435
+ status: DEAL_STATUS.PENDING, // will be updated to CONFIRMED if auto-confirm
436
  customerMessage: sanitizedMessage,
437
  passengerPickupLat: pickupLat,
438
  passengerPickupLng: pickupLng,
 
452
  return data;
453
  });
454
 
455
+ // ✅ AUTO-CONFIRM if fare matches and NOT a self-booking OR even if self-booking, we allow
456
+ // (For self-booking, we still auto-confirm if fare matches)
457
  if (!isNegotiated) {
458
  try {
459
  await _executeConfirmTransaction(dealRef.id, uid, { skipOwnershipCheck: true });
460
  console.log(`✅ Auto-confirmed deal ${dealRef.id} (fare matched)`);
461
  } catch (err) {
462
+ // If insufficient balance or other error, keep deal pending.
463
  console.warn(`⚠️ Auto-confirm failed for deal ${dealRef.id}: ${err.message}`);
464
+ // We might want to notify captain to add balance
465
  await pushToUser(captainId, {
466
  title: 'Booking received but not confirmed',
467
  body: 'A passenger booked your ride, but your wallet balance is insufficient to confirm. Please add balance.',
468
  type: 'wallet_insufficient',
469
  data: { dealId: dealRef.id, rideId },
470
  });
471
+ // Keep deal as PENDING
472
  }
473
  }
474
 
475
+ // Always notify captain about new booking (even if auto-confirmed)
476
  await pushToUser(captainId, {
477
  title: isNegotiated ? 'New Booking Request!' : 'New Booking Confirmed!',
478
  body: `${dealData.customerName} wants to ride with you.${isNegotiated ? ' Tap to respond.' : ' It is confirmed.'}`,
 
486
  }
487
  };
488
 
489
+ /**
490
+ * ✅ FIXED: confirmDeal - Captain or customer can confirm (with proper checks)
491
+ * Uses reusable _executeConfirmTransaction
492
+ */
493
  const confirmDeal = async (req, res) => {
494
  const { dealId } = req.params;
495
  const uid = req.user.uid;
 
503
  newBalance: result.newBalance,
504
  });
505
  } catch (err) {
506
+ const status = err.statusCode || (err.code === 'RIDE_FULL' || err.code === 'INSUFFICIENT_BALANCE' ? 400 : 400);
507
  return res.status(status).json({
508
  success: false,
509
  error: err.message,
 
514
  }
515
  };
516
 
517
+ /**
518
+ * cancelDeal - unchanged except maybe small fix
519
+ */
520
  const cancelDeal = async (req, res) => {
521
  const { dealId } = req.params;
522
  const uid = req.user.uid;
 
579
  }
580
  };
581
 
582
+ /**
583
+ * counterDeal - unchanged
584
+ */
585
  const counterDeal = async (req, res) => {
586
  const { dealId } = req.params;
587
  const uid = req.user.uid;
 
614
  lastCounterBy: isCaptain ? 'captain' : 'customer',
615
  lastCounterAt: now,
616
  updatedAt: now,
617
+ isNegotiated: true, // counter always means negotiated
618
  };
619
  if (message != null && String(message).trim().length > 0) {
620
  if (exceedsMaxLength(message, MAX_CUSTOMER_MESSAGE)) {
 
648
  }
649
  };
650
 
651
+ /**
652
+ * startDeal - unchanged
653
+ */
654
  const startDeal = async (req, res) => {
655
  const { dealId } = req.params;
656
  const uid = req.user.uid;
 
670
  }
671
 
672
  const startedAt = new Date().toISOString();
673
+
674
  await dealRef.update({
675
  status: DEAL_STATUS.STARTED,
676
  startedAt,
 
695
  }
696
  };
697
 
698
+ /**
699
+ * completeDeal - unchanged
700
+ */
701
  const completeDeal = async (req, res) => {
702
  const { dealId } = req.params;
703
  const uid = req.user.uid;
 
758
  }
759
  };
760
 
761
+ /**
762
+ * getDeal - unchanged
763
+ */
764
  const getDeal = async (req, res) => {
765
  try {
766
+ await maybeCleanupExpiredRides();
767
+ await maybeAutoArchiveConfirmedDeals();
768
+ await maybeCleanupOldCompletedDeals();
769
+
770
  const doc = await db.collection('deals').doc(req.params.dealId).get();
771
  if (!doc.exists) {
772
  return res.status(404).json({ success: false, error: 'Deal not found', code: 'DEAL_NOT_FOUND' });
 
814
  }
815
  };
816
 
817
+ /**
818
+ * rateDeal - unchanged
819
+ */
820
  const rateDeal = async (req, res) => {
821
  const { dealId } = req.params;
822
  const uid = req.user.uid;
 
904
  };
905
 
906
  /**
907
+ * 🔥 OPTIMIZED: getMyBookings - Uses Promise.all for parallel processing
908
  */
909
  const getMyBookings = async (req, res) => {
910
  try {
911
+ await maybeCleanupExpiredRides();
912
+ await maybeAutoArchiveConfirmedDeals();
913
+ await maybeCleanupOldCompletedDeals();
914
+
915
+ const snap = await db
916
+ .collection('deals')
917
  .where('customerId', '==', req.user.uid)
918
  .orderBy('createdAt', 'desc')
919
+ .get();
 
 
 
 
 
 
 
920
 
 
921
  const now = Date.now();
922
+
923
+ // 🔥 OPTIMIZED: Parallel processing with Promise.all
924
+ const bookings = await Promise.all(
925
+ snap.docs
926
+ .filter((doc) => {
927
+ const deal = { id: doc.id, ...doc.data() };
928
+ const status = (deal.status || '').toString().toLowerCase();
929
+
930
+ // Filter out old terminal deals
931
+ if ([DEAL_STATUS.COMPLETED, DEAL_STATUS.CANCELLED].includes(status)) {
932
+ const terminalAtRaw = deal.completedAt || deal.updatedAt || deal.createdAt || null;
933
+ const terminalAt = terminalAtRaw ? new Date(terminalAtRaw).getTime() : NaN;
934
+ if (Number.isFinite(terminalAt) && now - terminalAt > BOOKING_RETENTION_MS) {
935
+ return false;
936
+ }
937
+ }
938
+ return true;
939
+ })
940
+ .map(async (doc) => {
941
+ let deal = { id: doc.id, ...doc.data() };
942
+
943
+ const phoneRevealed = deal.phoneRevealed === true;
944
+ const fullCaptainPhone = deal.captainPhone || '';
945
+ deal.captainPhone = phoneRevealed ? fullCaptainPhone : maskCaptainPhone(fullCaptainPhone);
946
+
947
+ deal = await populateRide(deal);
948
+ return normalizeBooking(deal);
949
+ })
950
  );
951
 
952
+ return res.json({ success: true, bookings });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
953
  } catch (err) {
954
+ console.error('Error in getMyBookings:', err);
955
  return res.status(500).json({ success: false, error: err.message, code: 'GET_MY_BOOKINGS_ERROR' });
956
  }
957
  };
958
 
959
  /**
960
+ * 🔥 OPTIMIZED: getMyDeals - Uses Promise.all for parallel processing
961
  */
962
  const getMyDeals = async (req, res) => {
963
  try {
964
+ await maybeCleanupExpiredRides();
965
+ await maybeAutoArchiveConfirmedDeals();
966
+ await maybeCleanupOldCompletedDeals();
967
+
968
  const captainId = req.user.uid;
969
+
970
  const snap = await db
971
  .collection('deals')
972
  .where('captainId', '==', captainId)
 
974
  .get();
975
 
976
  const now = Date.now();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
977
 
978
+ // 🔥 OPTIMIZED: Parallel processing with Promise.all
979
+ const deals = await Promise.all(
980
+ snap.docs
981
+ .filter((doc) => {
982
+ const deal = { id: doc.id, ...doc.data() };
983
+ const status = (deal.status || '').toString().toLowerCase();
984
+
985
+ // Filter out old terminal deals
986
+ if ([DEAL_STATUS.COMPLETED, DEAL_STATUS.CANCELLED].includes(status)) {
987
+ const terminalAtRaw = deal.completedAt || deal.updatedAt || deal.createdAt || null;
988
+ const terminalAt = terminalAtRaw ? new Date(terminalAtRaw).getTime() : NaN;
989
+ if (Number.isFinite(terminalAt) && now - terminalAt > BOOKING_RETENTION_MS) {
990
+ return false;
991
+ }
992
+ }
993
+ return true;
994
+ })
995
+ .map(async (doc) => {
996
+ let deal = { id: doc.id, ...doc.data() };
997
+ const status = (deal.status || '').toString().toLowerCase();
998
+
999
+ // Populate ride details
1000
+ deal = await populateRide(deal);
1001
+
1002
+ // Get customer info if available
1003
+ if (deal.customerId) {
1004
+ const customer = await db.collection('users').doc(deal.customerId).get();
1005
+ if (customer.exists) {
1006
+ const customerData = customer.data();
1007
+ deal.customer = {
1008
+ name: customerData.name || 'Customer',
1009
+ phone: customerData.phone || '',
1010
+ rating: customerData.rating || 0,
1011
+ };
1012
+ deal.customerName = customerData.name || 'Customer';
1013
+ deal.customerPhone = customerData.phone || '';
1014
+ }
1015
+ }
1016
+
1017
+ // Format for display
1018
+ return {
1019
+ ...deal,
1020
+ tabStatus: normalizeBooking(deal).tabStatus,
1021
+ displayStatus: status,
1022
  };
1023
+ })
1024
+ );
 
 
 
 
 
 
 
 
 
 
1025
 
1026
  return res.json({
1027
  success: true,
1028
+ deals,
1029
+ count: deals.length,
1030
  });
1031
  } catch (err) {
1032
  console.error('Error in getMyDeals:', err);
 
1038
  }
1039
  };
1040
 
1041
+ /**
1042
+ * getConfirmedPassengers - unchanged
1043
+ */
1044
  const getConfirmedPassengers = async (req, res) => {
1045
  const { rideId } = req.params;
1046
  const uid = req.user.uid;
 
1121
  }
1122
  };
1123
 
1124
+ /**
1125
+ * updateBoardingStatus - unchanged
1126
+ */
1127
  const updateBoardingStatus = async (req, res) => {
1128
  const { dealId } = req.params;
1129
  const uid = req.user.uid;
 
1177
  }
1178
  };
1179
 
1180
+ /**
1181
+ * getRideDeals - unchanged but added cleanup calls
1182
+ */
1183
  const getRideDeals = async (req, res) => {
1184
  const { rideId } = req.params;
1185
  try {
1186
+ await maybeCleanupExpiredRides();
1187
+ await maybeAutoArchiveConfirmedDeals();
1188
+ await maybeCleanupOldCompletedDeals();
1189
+
1190
  const rideDoc = await db.collection('rides').doc(rideId).get();
1191
  if (!rideDoc.exists) {
1192
  return res.status(404).json({ success: false, error: 'Ride not found', code: 'RIDE_NOT_FOUND' });
 
1201
  .orderBy('createdAt', 'desc')
1202
  .get();
1203
 
1204
+ const deals = [];
1205
+ for (const doc of snap.docs) {
1206
+ const deal = { id: doc.id, ...doc.data() };
1207
  const phoneRevealed = deal.phoneRevealed === true;
1208
  const fullCaptainPhone = deal.captainPhone || '';
1209
  deal.captainPhone = phoneRevealed ? fullCaptainPhone : maskCaptainPhone(fullCaptainPhone);
 
1219
  deal.customerPhone = customerPhone;
1220
  }
1221
  }
1222
+ deals.push(deal);
1223
+ }
 
1224
  return res.json({
1225
  success: true,
1226
+ deals,
1227
  ride: {
1228
  totalSeats: rideDoc.data().totalSeats,
1229
  availableSeats: rideDoc.data().availableSeats,
 
1235
  }
1236
  };
1237
 
1238
+ /**
1239
+ * notifyDealMessage - unchanged
1240
+ */
1241
  const notifyDealMessage = async (req, res) => {
1242
  const { dealId } = req.params;
1243
  const uid = req.user.uid;
 
1269
  }
1270
  };
1271
 
1272
+ /**
1273
+ * getCaptainProfile - unchanged
1274
+ */
1275
  const getCaptainProfile = async (req, res) => {
1276
  const captainId = req.params.captainId || req.query.captainId;
1277
  if (!captainId) {