Huzaifa1435 commited on
Commit
fa85e0b
·
1 Parent(s): de5ba48

feat: all backend features - wallet commission, phone reveal, ladies rides, notifications, truck/tour support

Browse files
src/controllers/authController.js CHANGED
@@ -4,6 +4,7 @@ const ALLOWED_USER_FIELDS = [
4
  'name',
5
  'phone',
6
  'role',
 
7
  'cnic',
8
  'cnicFrontUrl',
9
  'cnicBackUrl',
@@ -15,6 +16,7 @@ const ALLOWED_USER_FIELDS = [
15
  'vehicleSeats',
16
  'city',
17
  'vehiclePhotoUrl',
 
18
  'emergencyContactName',
19
  'emergencyContactPhone',
20
  'captainVerificationStatus',
@@ -23,6 +25,13 @@ const ALLOWED_USER_FIELDS = [
23
  // Simple in-memory cache for profiles (5 seconds TTL)
24
  const userCache = new Map();
25
 
 
 
 
 
 
 
 
26
  function pickUpdates(body) {
27
  const updates = {};
28
  for (const key of ALLOWED_USER_FIELDS) {
@@ -50,6 +59,15 @@ async function ensureCaptainWallet(uid) {
50
  const syncUser = async (req, res) => {
51
  const { uid } = req.user;
52
  const body = req.body;
 
 
 
 
 
 
 
 
 
53
 
54
  try {
55
  const userRef = db.collection('users').doc(uid);
@@ -68,8 +86,11 @@ const syncUser = async (req, res) => {
68
  name: body.name || req.user.name || '',
69
  phone: body.phone || '',
70
  role: userRole,
 
71
  isVerified: userRole === 'customer' || userRole === 'passenger',
72
- captainVerificationStatus: isCaptain ? 'pending_verification' : null,
 
 
73
  cnicFrontUrl: body.cnicFrontUrl || null,
74
  cnicBackUrl: body.cnicBackUrl || null,
75
  cnic: body.cnic || null,
@@ -81,6 +102,7 @@ const syncUser = async (req, res) => {
81
  vehicleSeats: body.vehicleSeats ? parseInt(body.vehicleSeats, 10) : null,
82
  city: body.city || null,
83
  vehiclePhotoUrl: body.vehiclePhotoUrl || null,
 
84
  emergencyContactName: body.emergencyContactName || null,
85
  emergencyContactPhone: body.emergencyContactPhone || null,
86
  rating: 0.0,
@@ -104,6 +126,28 @@ const syncUser = async (req, res) => {
104
 
105
  // Update existing user
106
  const updates = pickUpdates(body);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
 
108
  if (Object.keys(updates).length > 0) {
109
  if (updates.captainVerificationStatus === 'pending_verification') {
@@ -163,6 +207,15 @@ const getProfile = async (req, res) => {
163
  const updateProfile = async (req, res) => {
164
  const { uid } = req.user;
165
  const updates = pickUpdates(req.body);
 
 
 
 
 
 
 
 
 
166
 
167
  try {
168
  const userRef = db.collection('users').doc(uid);
@@ -175,6 +228,29 @@ const updateProfile = async (req, res) => {
175
  return res.json({ success: true, user: snap.data() });
176
  }
177
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
  if (updates.captainVerificationStatus === 'pending_verification') {
179
  updates.isVerified = false;
180
  }
@@ -220,4 +296,4 @@ const updateFcmToken = async (req, res) => {
220
  }
221
  };
222
 
223
- module.exports = { syncUser, getProfile, updateProfile, updateFcmToken };
 
4
  'name',
5
  'phone',
6
  'role',
7
+ 'gender',
8
  'cnic',
9
  'cnicFrontUrl',
10
  'cnicBackUrl',
 
16
  'vehicleSeats',
17
  'city',
18
  'vehiclePhotoUrl',
19
+ 'captainVehicleType',
20
  'emergencyContactName',
21
  'emergencyContactPhone',
22
  'captainVerificationStatus',
 
25
  // Simple in-memory cache for profiles (5 seconds TTL)
26
  const userCache = new Map();
27
 
28
+ function normalizeGender(value) {
29
+ if (value === undefined || value === null || value === '') return null;
30
+ const gender = String(value).trim().toLowerCase();
31
+ if (gender === 'male' || gender === 'female') return gender;
32
+ return null;
33
+ }
34
+
35
  function pickUpdates(body) {
36
  const updates = {};
37
  for (const key of ALLOWED_USER_FIELDS) {
 
59
  const syncUser = async (req, res) => {
60
  const { uid } = req.user;
61
  const body = req.body;
62
+ const incomingGender = normalizeGender(body.gender);
63
+
64
+ if (body.gender !== undefined && incomingGender === null) {
65
+ return res.status(400).json({
66
+ success: false,
67
+ error: 'gender must be male or female',
68
+ code: 'INVALID_GENDER',
69
+ });
70
+ }
71
 
72
  try {
73
  const userRef = db.collection('users').doc(uid);
 
86
  name: body.name || req.user.name || '',
87
  phone: body.phone || '',
88
  role: userRole,
89
+ gender: incomingGender,
90
  isVerified: userRole === 'customer' || userRole === 'passenger',
91
+ captainVerificationStatus:
92
+ body.captainVerificationStatus ||
93
+ (isCaptain ? 'pending_verification' : null),
94
  cnicFrontUrl: body.cnicFrontUrl || null,
95
  cnicBackUrl: body.cnicBackUrl || null,
96
  cnic: body.cnic || null,
 
102
  vehicleSeats: body.vehicleSeats ? parseInt(body.vehicleSeats, 10) : null,
103
  city: body.city || null,
104
  vehiclePhotoUrl: body.vehiclePhotoUrl || null,
105
+ captainVehicleType: body.captainVehicleType || null,
106
  emergencyContactName: body.emergencyContactName || null,
107
  emergencyContactPhone: body.emergencyContactPhone || null,
108
  rating: 0.0,
 
126
 
127
  // Update existing user
128
  const updates = pickUpdates(body);
129
+ const existing = snap.data() || {};
130
+ const existingStatus = existing.captainVerificationStatus;
131
+ const isStatusLocked =
132
+ existingStatus === 'pending_verification' || existingStatus === 'verified';
133
+
134
+ if (incomingGender) {
135
+ updates.gender = incomingGender;
136
+ }
137
+
138
+ if (isStatusLocked && updates.captainVerificationStatus !== undefined) {
139
+ delete updates.captainVerificationStatus;
140
+ }
141
+
142
+ const nextRole = updates.role || existing.role;
143
+ if (
144
+ nextRole === 'captain' &&
145
+ !isStatusLocked &&
146
+ (!existingStatus || String(existingStatus).trim() === '') &&
147
+ updates.captainVerificationStatus === undefined
148
+ ) {
149
+ updates.captainVerificationStatus = 'pending_verification';
150
+ }
151
 
152
  if (Object.keys(updates).length > 0) {
153
  if (updates.captainVerificationStatus === 'pending_verification') {
 
207
  const updateProfile = async (req, res) => {
208
  const { uid } = req.user;
209
  const updates = pickUpdates(req.body);
210
+ const incomingGender = normalizeGender(req.body.gender);
211
+
212
+ if (req.body.gender !== undefined && incomingGender === null) {
213
+ return res.status(400).json({
214
+ success: false,
215
+ error: 'gender must be male or female',
216
+ code: 'INVALID_GENDER',
217
+ });
218
+ }
219
 
220
  try {
221
  const userRef = db.collection('users').doc(uid);
 
228
  return res.json({ success: true, user: snap.data() });
229
  }
230
 
231
+ const existing = snap.data() || {};
232
+ const existingStatus = existing.captainVerificationStatus;
233
+ const isStatusLocked =
234
+ existingStatus === 'pending_verification' || existingStatus === 'verified';
235
+
236
+ if (incomingGender) {
237
+ updates.gender = incomingGender;
238
+ }
239
+
240
+ if (isStatusLocked && updates.captainVerificationStatus !== undefined) {
241
+ delete updates.captainVerificationStatus;
242
+ }
243
+
244
+ const nextRole = updates.role || existing.role;
245
+ if (
246
+ nextRole === 'captain' &&
247
+ !isStatusLocked &&
248
+ (!existingStatus || String(existingStatus).trim() === '') &&
249
+ updates.captainVerificationStatus === undefined
250
+ ) {
251
+ updates.captainVerificationStatus = 'pending_verification';
252
+ }
253
+
254
  if (updates.captainVerificationStatus === 'pending_verification') {
255
  updates.isVerified = false;
256
  }
 
296
  }
297
  };
298
 
299
+ module.exports = { syncUser, getProfile, updateProfile, updateFcmToken };
src/controllers/dealController.js CHANGED
@@ -17,6 +17,10 @@ function parseCoord(value) {
17
  return Number.isFinite(n) ? n : null;
18
  }
19
 
 
 
 
 
20
  /** Apply seat delta inside a transaction; returns new available seat count. */
21
  function seatUpdateFromRide(ride, delta) {
22
  const totalSeats = ride.totalSeats ?? ride.availableSeats ?? 0;
@@ -150,6 +154,13 @@ const createDeal = async (req, res) => {
150
  const rideRef = db.collection('rides').doc(rideId);
151
  const dealRef = db.collection('deals').doc();
152
  const platformFee = parseFloat(agreedFare) * PLATFORM_FEE_PERCENT;
 
 
 
 
 
 
 
153
 
154
  const dealData = await db.runTransaction(async (t) => {
155
  const ride = await t.get(rideRef);
@@ -176,6 +187,8 @@ const createDeal = async (req, res) => {
176
  customerId: uid,
177
  customerName: userDoc.data().name || 'Guest',
178
  customerPhone: userDoc.data().phone || '',
 
 
179
  agreedFare: parseFloat(agreedFare),
180
  platformFee,
181
  status: DEAL_STATUS.PENDING,
@@ -199,10 +212,10 @@ const createDeal = async (req, res) => {
199
  });
200
 
201
  await pushToUser(dealData.captainId, {
202
- title: 'New ride request',
203
- body: `${dealData.customerName} requested Rs. ${dealData.agreedFare}`,
204
  type: 'new_deal',
205
- data: { rideId, dealId: dealRef.id },
206
  });
207
 
208
  return res.status(201).json({ success: true, dealId: dealRef.id, deal: dealData });
@@ -229,43 +242,48 @@ const confirmDeal = async (req, res) => {
229
  return res.status(400).json({ success: false, error: 'Deal already processed', code: 'INVALID_STATE' });
230
  }
231
 
232
- const rideRef = db.collection('rides').doc(deal.rideId);
233
- const platformFee = deal.platformFee;
 
 
234
 
235
- await deductBalance(uid, platformFee, {
236
- type: 'commission_deduction',
237
- description: '10% commission for confirmed booking',
238
- dealId,
239
- });
 
 
 
 
240
 
241
- const confirmedSnap = await db
242
- .collection('deals')
243
- .where('rideId', '==', deal.rideId)
244
- .where('status', '==', DEAL_STATUS.CONFIRMED)
245
- .get();
246
- const pickupOrder = confirmedSnap.size + 1;
247
 
248
- await db.runTransaction(async (t) => {
249
- const rideDoc = await t.get(rideRef);
250
- if (!rideDoc.exists) throw new Error('Ride not found');
251
- const ride = rideDoc.data();
252
- if (ride.full === true || (ride.availableSeats || 0) <= 0) {
253
- throw new Error('Ride is full');
254
- }
255
- const { available: newSeats } = seatUpdateFromRide(ride, -1);
 
256
 
257
- t.update(dealRef, {
258
- status: DEAL_STATUS.CONFIRMED,
259
- confirmedAt: new Date().toISOString(),
260
- boardingStatus: 'waiting',
261
- pickupOrder,
262
- });
263
- t.update(rideRef, {
264
- availableSeats: newSeats,
265
- full: newSeats <= 0,
266
- status: newSeats <= 0 ? RIDE_STATUS.FILLED : RIDE_STATUS.ACTIVE,
267
- updatedAt: new Date().toISOString(),
268
- });
 
 
269
  });
270
 
271
  await pushToUser(deal.customerId, {
@@ -275,7 +293,12 @@ const confirmDeal = async (req, res) => {
275
  data: { dealId },
276
  });
277
 
278
- return res.json({ success: true, message: 'Deal confirmed' });
 
 
 
 
 
279
  } catch (err) {
280
  return res.status(400).json({ success: false, error: err.message, code: 'CONFIRM_DEAL_ERROR' });
281
  }
@@ -469,10 +492,13 @@ const getDeal = async (req, res) => {
469
 
470
  if (deal.captainId) {
471
  const captain = await db.collection('users').doc(deal.captainId).get();
 
 
 
472
  if (captain.exists) {
473
  deal.captain = {
474
  name: captain.data().name,
475
- phone: captain.data().phone,
476
  rating: captain.data().rating,
477
  vehicleMake: captain.data().vehicleMake,
478
  vehicleModel: captain.data().vehicleModel,
@@ -549,6 +575,9 @@ const getMyBookings = async (req, res) => {
549
  const bookings = [];
550
  for (const doc of snap.docs) {
551
  let deal = { id: doc.id, ...doc.data() };
 
 
 
552
  deal = await populateRide(deal);
553
  bookings.push(deal);
554
  }
@@ -702,6 +731,9 @@ const getRideDeals = async (req, res) => {
702
  const deals = [];
703
  for (const doc of snap.docs) {
704
  const deal = { id: doc.id, ...doc.data() };
 
 
 
705
  if (deal.customerId) {
706
  const customer = await db.collection('users').doc(deal.customerId).get();
707
  if (customer.exists) {
 
17
  return Number.isFinite(n) ? n : null;
18
  }
19
 
20
+ function maskCaptainPhone(phone) {
21
+ return '03**-*****';
22
+ }
23
+
24
  /** Apply seat delta inside a transaction; returns new available seat count. */
25
  function seatUpdateFromRide(ride, delta) {
26
  const totalSeats = ride.totalSeats ?? ride.availableSeats ?? 0;
 
154
  const rideRef = db.collection('rides').doc(rideId);
155
  const dealRef = db.collection('deals').doc();
156
  const platformFee = parseFloat(agreedFare) * PLATFORM_FEE_PERCENT;
157
+ const captainDoc = await rideRef.get();
158
+ if (!captainDoc.exists) {
159
+ return res.status(404).json({ success: false, error: 'Ride not found', code: 'RIDE_NOT_FOUND' });
160
+ }
161
+ const captainId = captainDoc.data().captainId;
162
+ const captainUserDoc = await db.collection('users').doc(captainId).get();
163
+ const captainPhone = captainUserDoc.exists ? (captainUserDoc.data().phone || '') : '';
164
 
165
  const dealData = await db.runTransaction(async (t) => {
166
  const ride = await t.get(rideRef);
 
187
  customerId: uid,
188
  customerName: userDoc.data().name || 'Guest',
189
  customerPhone: userDoc.data().phone || '',
190
+ captainPhone,
191
+ phoneRevealed: false,
192
  agreedFare: parseFloat(agreedFare),
193
  platformFee,
194
  status: DEAL_STATUS.PENDING,
 
212
  });
213
 
214
  await pushToUser(dealData.captainId, {
215
+ title: 'New Booking Request!',
216
+ body: `${dealData.customerName} wants to ride with you. Tap to respond.`,
217
  type: 'new_deal',
218
+ data: { rideId, dealId: dealRef.id, screen: 'my-rides' },
219
  });
220
 
221
  return res.status(201).json({ success: true, dealId: dealRef.id, deal: dealData });
 
242
  return res.status(400).json({ success: false, error: 'Deal already processed', code: 'INVALID_STATE' });
243
  }
244
 
245
+ const commission = parseFloat(deal.agreedFare || 0) * 0.1;
246
+ const walletRef = db.collection('wallets').doc(uid);
247
+ const walletSnap = await walletRef.get();
248
+ const currentBalance = walletSnap.exists ? Number(walletSnap.data().balance || 0) : 0;
249
 
250
+ if (currentBalance < commission) {
251
+ return res.status(400).json({
252
+ success: false,
253
+ code: 'INSUFFICIENT_BALANCE',
254
+ error: 'Insufficient wallet balance to confirm deal',
255
+ required: commission,
256
+ current: currentBalance,
257
+ });
258
+ }
259
 
260
+ const newBalance = currentBalance - commission;
261
+ const now = new Date().toISOString();
 
 
 
 
262
 
263
+ await walletRef.set(
264
+ {
265
+ id: uid,
266
+ userId: uid,
267
+ balance: newBalance,
268
+ updatedAt: now,
269
+ },
270
+ { merge: true },
271
+ );
272
 
273
+ await db.collection('transactions').add({
274
+ walletId: uid,
275
+ type: 'commission',
276
+ amount: -commission,
277
+ reference: dealId,
278
+ description: `10% commission for deal ${dealId}`,
279
+ createdAt: now,
280
+ });
281
+
282
+ await dealRef.update({
283
+ status: DEAL_STATUS.CONFIRMED,
284
+ phoneRevealed: true,
285
+ confirmedAt: now,
286
+ updatedAt: now,
287
  });
288
 
289
  await pushToUser(deal.customerId, {
 
293
  data: { dealId },
294
  });
295
 
296
+ return res.json({
297
+ success: true,
298
+ message: 'Deal confirmed',
299
+ commissionDeducted: commission,
300
+ newBalance,
301
+ });
302
  } catch (err) {
303
  return res.status(400).json({ success: false, error: err.message, code: 'CONFIRM_DEAL_ERROR' });
304
  }
 
492
 
493
  if (deal.captainId) {
494
  const captain = await db.collection('users').doc(deal.captainId).get();
495
+ const phoneRevealed = deal.phoneRevealed === true;
496
+ const fullCaptainPhone = deal.captainPhone || (captain.exists ? captain.data().phone : '');
497
+ deal.captainPhone = phoneRevealed ? fullCaptainPhone : maskCaptainPhone(fullCaptainPhone);
498
  if (captain.exists) {
499
  deal.captain = {
500
  name: captain.data().name,
501
+ phone: deal.captainPhone,
502
  rating: captain.data().rating,
503
  vehicleMake: captain.data().vehicleMake,
504
  vehicleModel: captain.data().vehicleModel,
 
575
  const bookings = [];
576
  for (const doc of snap.docs) {
577
  let deal = { id: doc.id, ...doc.data() };
578
+ const phoneRevealed = deal.phoneRevealed === true;
579
+ const fullCaptainPhone = deal.captainPhone || '';
580
+ deal.captainPhone = phoneRevealed ? fullCaptainPhone : maskCaptainPhone(fullCaptainPhone);
581
  deal = await populateRide(deal);
582
  bookings.push(deal);
583
  }
 
731
  const deals = [];
732
  for (const doc of snap.docs) {
733
  const deal = { id: doc.id, ...doc.data() };
734
+ const phoneRevealed = deal.phoneRevealed === true;
735
+ const fullCaptainPhone = deal.captainPhone || '';
736
+ deal.captainPhone = phoneRevealed ? fullCaptainPhone : maskCaptainPhone(fullCaptainPhone);
737
  if (deal.customerId) {
738
  const customer = await db.collection('users').doc(deal.customerId).get();
739
  if (customer.exists) {
src/controllers/rideController.js CHANGED
@@ -1,5 +1,6 @@
1
  const { db } = require('../config/firebase');
2
  const { getBalance } = require('../utils/walletHelper');
 
3
 
4
  /**
5
  * 1. Post a new ride
@@ -59,9 +60,32 @@ const postRide = async (req, res) => {
59
  startLocation, endLocation,
60
  startLat, startLng, endLat, endLng,
61
  departureTime, totalSeats, suggestedFare,
62
- rideType, acceptsDelivery, vehicleInfo,
 
 
63
  } = req.body;
64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  // Validation
66
  if (!startLocation || !endLocation || !departureTime || !totalSeats || !suggestedFare) {
67
  return res.status(400).json({
@@ -75,7 +99,9 @@ const postRide = async (req, res) => {
75
  const ride = {
76
  captainId: uid,
77
  captainName: userData.name || 'Anonymous',
 
78
  captainRating: userData.rating || 5.0,
 
79
  startLocation: startLocation.trim(),
80
  endLocation: endLocation.trim(),
81
  startLat: parseFloat(startLat) || 0.0,
@@ -83,11 +109,15 @@ const postRide = async (req, res) => {
83
  endLat: parseFloat(endLat) || 0.0,
84
  endLng: parseFloat(endLng) || 0.0,
85
  departureTime: new Date(departureTime).toISOString(),
86
- totalSeats: parseInt(totalSeats),
87
- availableSeats: parseInt(totalSeats),
88
  full: false,
89
  suggestedFare: parseFloat(suggestedFare),
90
  rideType: rideType || 'random',
 
 
 
 
91
  acceptsDelivery: acceptsDelivery || false,
92
  vehicleInfo: vehicleInfo || `${userData.vehicleMake || ''} ${userData.vehicleModel || ''}`.trim() || 'Not Specified',
93
  status: 'active',
@@ -95,9 +125,80 @@ const postRide = async (req, res) => {
95
  updatedAt: new Date().toISOString(),
96
  };
97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  // Database mein add karna
99
  const ref = await db.collection('rides').add(ride);
100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  // Success Response
102
  return res.status(201).json({
103
  success: true,
@@ -120,9 +221,17 @@ const postRide = async (req, res) => {
120
  * 2. Get Active Rides (With Advanced Filtering - No Index Required)
121
  */
122
  const getActiveRides = async (req, res) => {
123
- const { rideType, startLocation } = req.query;
124
 
125
  try {
 
 
 
 
 
 
 
 
126
  // Simple query without complex filters to avoid index requirement
127
  let query = db.collection('rides').where('status', '==', 'active');
128
 
@@ -133,9 +242,31 @@ const getActiveRides = async (req, res) => {
133
  const snap = await query.orderBy('departureTime').get();
134
  let rides = snap.docs.map(d => ({ id: d.id, ...d.data() }));
135
 
136
- // Manual filtering for rideType (avoids composite index)
137
- if (rideType && rideType !== 'all' && rideType !== 'random') {
138
- rides = rides.filter(r => r.rideType === rideType);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
  }
140
 
141
  // Manual filtering for location search (case-insensitive)
@@ -336,5 +467,24 @@ module.exports = {
336
  updateRideStatus,
337
  getMyRides,
338
  getRideById,
339
- updateRideLocation
340
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  const { db } = require('../config/firebase');
2
  const { getBalance } = require('../utils/walletHelper');
3
+ const { pushToUser } = require('../utils/notificationHelper');
4
 
5
  /**
6
  * 1. Post a new ride
 
60
  startLocation, endLocation,
61
  startLat, startLng, endLat, endLng,
62
  departureTime, totalSeats, suggestedFare,
63
+ rideType, vehicleType, rideMode, acceptsDelivery, vehicleInfo,
64
+ tourType, maxPassengers,
65
+ cargoType, weightCapacity, truckSize,
66
  } = req.body;
67
 
68
+ const normalizedRideMode = String(rideMode || 'share').toLowerCase();
69
+ if (!['share', 'solo'].includes(normalizedRideMode)) {
70
+ return res.status(400).json({
71
+ success: false,
72
+ error: 'rideMode must be share or solo',
73
+ code: 'INVALID_RIDE_MODE',
74
+ });
75
+ }
76
+
77
+ const normalizedVehicleType = String(vehicleType || '').toLowerCase();
78
+ const allowedVehicleTypes = ['car', 'bike', 'bus', 'truck', 'shazore', 'tour'];
79
+ const inferredVehicleType = normalizedVehicleType ||
80
+ (rideType === 'tour' ? 'tour' : 'car');
81
+ if (!allowedVehicleTypes.includes(inferredVehicleType)) {
82
+ return res.status(400).json({
83
+ success: false,
84
+ error: 'vehicleType must be one of car, bike, bus, truck, shazore, tour',
85
+ code: 'INVALID_VEHICLE_TYPE',
86
+ });
87
+ }
88
+
89
  // Validation
90
  if (!startLocation || !endLocation || !departureTime || !totalSeats || !suggestedFare) {
91
  return res.status(400).json({
 
99
  const ride = {
100
  captainId: uid,
101
  captainName: userData.name || 'Anonymous',
102
+ captainPhone: userData.phone || '',
103
  captainRating: userData.rating || 5.0,
104
+ captainGender: (userData.gender || '').toString().toLowerCase() || null,
105
  startLocation: startLocation.trim(),
106
  endLocation: endLocation.trim(),
107
  startLat: parseFloat(startLat) || 0.0,
 
109
  endLat: parseFloat(endLat) || 0.0,
110
  endLng: parseFloat(endLng) || 0.0,
111
  departureTime: new Date(departureTime).toISOString(),
112
+ totalSeats: normalizedRideMode === 'solo' ? 1 : parseInt(totalSeats),
113
+ availableSeats: normalizedRideMode === 'solo' ? 1 : parseInt(totalSeats),
114
  full: false,
115
  suggestedFare: parseFloat(suggestedFare),
116
  rideType: rideType || 'random',
117
+ rideMode: normalizedRideMode,
118
+ vehicleType: inferredVehicleType === 'shazore' ? 'truck' : inferredVehicleType,
119
+ isShazoreRide: inferredVehicleType === 'shazore',
120
+ isLadiesRide: ((userData.gender || '').toString().toLowerCase() === 'female'),
121
  acceptsDelivery: acceptsDelivery || false,
122
  vehicleInfo: vehicleInfo || `${userData.vehicleMake || ''} ${userData.vehicleModel || ''}`.trim() || 'Not Specified',
123
  status: 'active',
 
125
  updatedAt: new Date().toISOString(),
126
  };
127
 
128
+ if (inferredVehicleType === 'tour') {
129
+ const normalizedTourType = String(tourType || 'share').toLowerCase();
130
+ if (!['share', 'solo'].includes(normalizedTourType)) {
131
+ return res.status(400).json({
132
+ success: false,
133
+ error: "tourType must be 'share' or 'solo'",
134
+ code: 'INVALID_TOUR_TYPE',
135
+ });
136
+ }
137
+ ride.tourType = normalizedTourType;
138
+ if (normalizedTourType === 'share') {
139
+ const parsedMax = parseInt(maxPassengers, 10);
140
+ if (!Number.isInteger(parsedMax) || parsedMax < 1) {
141
+ return res.status(400).json({
142
+ success: false,
143
+ error: 'maxPassengers is required for share tour',
144
+ code: 'INVALID_MAX_PASSENGERS',
145
+ });
146
+ }
147
+ ride.maxPassengers = parsedMax;
148
+ } else {
149
+ ride.maxPassengers = 1;
150
+ }
151
+ }
152
+
153
+ if (inferredVehicleType === 'truck' || inferredVehicleType === 'shazore') {
154
+ const normalizedTruckSize = String(truckSize || '').toLowerCase();
155
+ if (normalizedTruckSize && !['mini', 'half', 'full'].includes(normalizedTruckSize)) {
156
+ return res.status(400).json({
157
+ success: false,
158
+ error: "truckSize must be mini, half, or full",
159
+ code: 'INVALID_TRUCK_SIZE',
160
+ });
161
+ }
162
+ ride.cargoType = (cargoType || '').toString().trim() || null;
163
+ ride.weightCapacity = weightCapacity != null ? Number(weightCapacity) : null;
164
+ ride.truckSize =
165
+ normalizedTruckSize || (inferredVehicleType === 'shazore' ? 'full' : null);
166
+ if (inferredVehicleType === 'shazore') {
167
+ ride.isShazoreRide = true;
168
+ }
169
+ }
170
+
171
  // Database mein add karna
172
  const ref = await db.collection('rides').add(ride);
173
 
174
+ // Notify nearby customers/passengers (city-filtered when captain city exists)
175
+ try {
176
+ const usersSnap = await db
177
+ .collection('users')
178
+ .where('role', 'in', ['customer', 'passenger'])
179
+ .get();
180
+ const captainCity = (userData.city || '').toString().trim().toLowerCase();
181
+ const targets = usersSnap.docs.filter((doc) => {
182
+ const u = doc.data() || {};
183
+ if (!u.fcmToken) return false;
184
+ if (!captainCity) return true;
185
+ return (u.city || '').toString().trim().toLowerCase() === captainCity;
186
+ });
187
+
188
+ await Promise.all(
189
+ targets.map((doc) =>
190
+ pushToUser(doc.id, {
191
+ title: 'New Ride Available',
192
+ body: `New ride from ${ride.startLocation} to ${ride.endLocation} near you!`,
193
+ type: 'new_ride',
194
+ data: { rideId: ref.id, screen: 'find-ride' },
195
+ }),
196
+ ),
197
+ );
198
+ } catch (notifyErr) {
199
+ console.error('Ride notification error:', notifyErr.message);
200
+ }
201
+
202
  // Success Response
203
  return res.status(201).json({
204
  success: true,
 
221
  * 2. Get Active Rides (With Advanced Filtering - No Index Required)
222
  */
223
  const getActiveRides = async (req, res) => {
224
+ const { rideType, startLocation, rideMode } = req.query;
225
 
226
  try {
227
+ let requesterGender = '';
228
+ if (req.user?.uid) {
229
+ const requesterDoc = await db.collection('users').doc(req.user.uid).get();
230
+ if (requesterDoc.exists) {
231
+ requesterGender = (requesterDoc.data().gender || '').toString().toLowerCase();
232
+ }
233
+ }
234
+
235
  // Simple query without complex filters to avoid index requirement
236
  let query = db.collection('rides').where('status', '==', 'active');
237
 
 
242
  const snap = await query.orderBy('departureTime').get();
243
  let rides = snap.docs.map(d => ({ id: d.id, ...d.data() }));
244
 
245
+ // Manual filtering for vehicle/lady tabs (avoids composite index)
246
+ if (rideType) {
247
+ const rt = String(rideType).toLowerCase();
248
+ if (['car', 'bike', 'bus', 'truck', 'tour'].includes(rt)) {
249
+ rides = rides.filter((r) => (r.vehicleType || '').toString().toLowerCase() === rt);
250
+ } else if (rt === 'shazore') {
251
+ rides = rides.filter((r) => r.isShazoreRide === true);
252
+ } else if (rt === 'ladies') {
253
+ if (requesterGender !== 'female') {
254
+ rides = [];
255
+ } else {
256
+ rides = rides.filter((r) => r.isLadiesRide === true);
257
+ }
258
+ } else if (rt !== 'all' && rt !== 'random') {
259
+ rides = rides.filter((r) => (r.rideType || '').toString().toLowerCase() === rt);
260
+ }
261
+ }
262
+
263
+ if (rideMode) {
264
+ const rm = String(rideMode).toLowerCase();
265
+ if (['solo', 'share'].includes(rm)) {
266
+ rides = rides.filter(
267
+ (r) => (r.rideMode || 'share').toString().toLowerCase() === rm,
268
+ );
269
+ }
270
  }
271
 
272
  // Manual filtering for location search (case-insensitive)
 
467
  updateRideStatus,
468
  getMyRides,
469
  getRideById,
470
+ updateRideLocation,
471
+ };
472
+ const normalizedRideMode = String(rideMode || 'share').toLowerCase();
473
+ if (!['solo', 'share'].includes(normalizedRideMode)) {
474
+ return res.status(400).json({
475
+ success: false,
476
+ error: "rideMode must be 'solo' or 'share'",
477
+ code: 'INVALID_RIDE_MODE',
478
+ });
479
+ }
480
+ const captainVehicleType = String(userData.captainVehicleType || '').toLowerCase();
481
+ if (captainVehicleType) {
482
+ const postingType = inferredVehicleType === 'shazore' ? 'shazore' : inferredVehicleType;
483
+ if (postingType !== captainVehicleType) {
484
+ return res.status(403).json({
485
+ success: false,
486
+ error: `You can only post ${captainVehicleType} rides from this captain profile`,
487
+ code: 'VEHICLE_TYPE_MISMATCH',
488
+ });
489
+ }
490
+ }
src/routes/auth.js CHANGED
@@ -23,6 +23,7 @@ router.patch('/profile/captain', verifyToken, async (req, res) => {
23
  const { db } = require('../config/firebase');
24
  const {
25
  phone,
 
26
  captainVerificationStatus,
27
  cnicFrontUrl,
28
  cnicBackUrl,
@@ -30,6 +31,7 @@ router.patch('/profile/captain', verifyToken, async (req, res) => {
30
  city,
31
  vehicleMake,
32
  vehicleModel,
 
33
  vehicleColor,
34
  vehicleRegistration,
35
  vehicleYear,
@@ -39,15 +41,33 @@ router.patch('/profile/captain', verifyToken, async (req, res) => {
39
  } = req.body;
40
 
41
  try {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  const updateData = {
43
  phone: phone || '',
44
- captainVerificationStatus: captainVerificationStatus || 'pending_verification',
 
 
45
  cnicFrontUrl: cnicFrontUrl || null,
46
  cnicBackUrl: cnicBackUrl || null,
47
  cnic: cnic || null,
48
  city: city || null,
49
  vehicleMake: vehicleMake || null,
50
  vehicleModel: vehicleModel || null,
 
51
  vehicleColor: vehicleColor || null,
52
  vehicleRegistration: vehicleRegistration || null,
53
  vehicleYear: vehicleYear || null,
@@ -64,8 +84,11 @@ router.patch('/profile/captain', verifyToken, async (req, res) => {
64
  delete updateData[key];
65
  }
66
  });
 
 
 
67
 
68
- await db.collection('users').doc(req.user.uid).update(updateData);
69
 
70
  return res.json({
71
  success: true,
@@ -96,4 +119,17 @@ router.patch('/profile', verifyToken, async (req, res) => {
96
  }
97
  });
98
 
99
- module.exports = router;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  const { db } = require('../config/firebase');
24
  const {
25
  phone,
26
+ gender,
27
  captainVerificationStatus,
28
  cnicFrontUrl,
29
  cnicBackUrl,
 
31
  city,
32
  vehicleMake,
33
  vehicleModel,
34
+ captainVehicleType,
35
  vehicleColor,
36
  vehicleRegistration,
37
  vehicleYear,
 
41
  } = req.body;
42
 
43
  try {
44
+ const genderValue = gender == null ? null : String(gender).trim().toLowerCase();
45
+ if (gender !== undefined && !['male', 'female'].includes(genderValue)) {
46
+ return res.status(400).json({
47
+ success: false,
48
+ error: 'gender must be male or female',
49
+ code: 'INVALID_GENDER',
50
+ });
51
+ }
52
+
53
+ const userRef = db.collection('users').doc(req.user.uid);
54
+ const userSnap = await userRef.get();
55
+ const existingStatus = userSnap.exists ? userSnap.data().captainVerificationStatus : null;
56
+ const lockedStatus =
57
+ existingStatus === 'pending_verification' || existingStatus === 'verified';
58
+
59
  const updateData = {
60
  phone: phone || '',
61
+ captainVerificationStatus: lockedStatus
62
+ ? existingStatus
63
+ : (captainVerificationStatus || existingStatus || 'pending_verification'),
64
  cnicFrontUrl: cnicFrontUrl || null,
65
  cnicBackUrl: cnicBackUrl || null,
66
  cnic: cnic || null,
67
  city: city || null,
68
  vehicleMake: vehicleMake || null,
69
  vehicleModel: vehicleModel || null,
70
+ captainVehicleType: normalizedCaptainVehicleType || null,
71
  vehicleColor: vehicleColor || null,
72
  vehicleRegistration: vehicleRegistration || null,
73
  vehicleYear: vehicleYear || null,
 
84
  delete updateData[key];
85
  }
86
  });
87
+ if (gender !== undefined) {
88
+ updateData.gender = genderValue;
89
+ }
90
 
91
+ await userRef.update(updateData);
92
 
93
  return res.json({
94
  success: true,
 
119
  }
120
  });
121
 
122
+ module.exports = router;
123
+ const normalizedCaptainVehicleType = captainVehicleType == null
124
+ ? null
125
+ : String(captainVehicleType).trim().toLowerCase();
126
+ if (
127
+ captainVehicleType !== undefined &&
128
+ !['car', 'bike', 'bus', 'truck', 'shazore', 'tour'].includes(normalizedCaptainVehicleType)
129
+ ) {
130
+ return res.status(400).json({
131
+ success: false,
132
+ error: 'captainVehicleType must be one of car, bike, bus, truck, shazore, tour',
133
+ code: 'INVALID_CAPTAIN_VEHICLE_TYPE',
134
+ });
135
+ }