File size: 12,006 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
const { db } = require('../config/firebase');
const { v4: uuidv4 } = require('uuid');
const ProfessionalModel = require('./professionalModel');

const BOOKINGS_PATH = 'bookings';
const USER_BOOKINGS_PATH = 'userBookings'; // Index path to query quickly: userBookings/{uid}/{bookingId} = true
const COMMISSION_RATE = 0.10;

function toMoney(value) {
  return Math.round(Number(value || 0) * 100) / 100;
}

function addHistoryEntry(history, entry) {
  const existing = history && typeof history === 'object' ? history : {};
  const normalized = Array.isArray(existing) ? { ...existing } : { ...existing };
  normalized[`offer_${Date.now()}_${Math.floor(Math.random() * 1000)}`] = entry;
  return normalized;
}

const BookingModel = {
  // Create new booking (customer requested booking)
  async create(data) {
    const bookingId = uuidv4();
    const createdAt = Date.now();
    const price = toMoney(data.proposedPrice || 0);

    const booking = {
      bookingId,
      customerId: data.customerId,
      professionalId: data.professionalId,
      customerProblem: data.customerProblem || data.description || '',
      customerLocation: data.customerLocation || { lat: 0, lng: 0 },
      customerAddress: data.customerAddress || data.address || '',
      scheduledTime: data.scheduledTime || null,
      serviceType: data.serviceType || 'general',
      proposedPrice: price,
      counterPrice: 0,
      agreedPrice: 0,
      status: 'pending_acceptance',
      negotiationHistory: {
        initial: {
          from: 'customer',
          price,
          timestamp: createdAt,
        },
      },
      paymentStatus: 'pending_quote',
      commissionDeducted: false,
      transactionId: '',
      screenshotUrl: '',
      commissionAmount: toMoney(price * COMMISSION_RATE),
      professionalEarnings: toMoney(price * (1 - COMMISSION_RATE)),
      professionalPhone: data.professionalPhone || '',
      professionalLocation: data.professionalLocation || null,
      customerPhone: data.customerPhone || '',
      customerName: data.customerName || '',
      contactMethod: data.contactMethod || 'direct_contact',
      createdAt,
      updatedAt: createdAt,
    };

    await db.ref(`${BOOKINGS_PATH}/${bookingId}`).set(booking);

    await db.ref(`${USER_BOOKINGS_PATH}/${data.customerId}/${bookingId}`).set(true);
    await db.ref(`${USER_BOOKINGS_PATH}/${data.professionalId}/${bookingId}`).set(true);

    return booking;
  },

  // Get booking by ID
  async getById(bookingId) {
    const snapshot = await db.ref(`${BOOKINGS_PATH}/${bookingId}`).once('value');
    const data = snapshot.val();
    if (!data) return null;
    
    return {
      bookingId,
      ...data
    };
  },

  // Get all bookings for a user (customer or professional)
  async getByUserId(uid) {
    const snapshot = await db.ref(`${USER_BOOKINGS_PATH}/${uid}`).once('value');
    const bookingRefs = snapshot.val();
    if (!bookingRefs) return [];
    
    const bookings = [];
    for (const bookingId of Object.keys(bookingRefs)) {
      const booking = await this.getById(bookingId);
      if (booking) {
        bookings.push(booking);
      }
    }
    
    return bookings.sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0));
  },

  async getByCustomerId(customerId) {
    return this.getByUserId(customerId);
  },

  async getByProfessionalPhone(professionalPhone) {
    // Legacy support: finding bookings by professional identifier
    return this.getByUserId(professionalPhone);
  },

  async getByProfessionalId(professionalId) {
    return this.getByUserId(professionalId);
  },

  // Update status directly
  async updateStatus(bookingId, status) {
    await db.ref(`${BOOKINGS_PATH}/${bookingId}/status`).set(status);
    await db.ref(`${BOOKINGS_PATH}/${bookingId}/updatedAt`).set(Date.now());
    return { bookingId, status };
  },

  // Propose price (professional counters)
  async proposePrice(bookingId, price) {
    const booking = await this.getById(bookingId);
    if (!booking) throw new Error('Booking not found');

    const history = addHistoryEntry(booking.negotiationHistory, {
      from: 'professional',
      price: Number(price),
      timestamp: Date.now()
    });

    await db.ref(`${BOOKINGS_PATH}/${bookingId}`).update({
      proposedPrice: Number(price),
      status: 'pending_customer_response',
      negotiationHistory: history,
      updatedAt: Date.now()
    });

    return this.getById(bookingId);
  },

  // Counter price (customer counters)
  async counterPrice(bookingId, price) {
    const booking = await this.getById(bookingId);
    if (!booking) throw new Error('Booking not found');

    const history = addHistoryEntry(booking.negotiationHistory, {
      from: 'customer',
      price: Number(price),
      timestamp: Date.now()
    });

    await db.ref(`${BOOKINGS_PATH}/${bookingId}`).update({
      counterPrice: Number(price),
      status: 'pending_professional_response',
      negotiationHistory: history,
      updatedAt: Date.now()
    });

    return this.getById(bookingId);
  },

  // Accept Price (either customer or professional accepts)
  async acceptPrice(bookingId, acceptedPrice) {
    const booking = await this.getById(bookingId);
    if (!booking) throw new Error('Booking not found');

    const finalPrice = toMoney(acceptedPrice);
    const commission = toMoney(finalPrice * COMMISSION_RATE);
    const earnings = toMoney(finalPrice - commission);
    const professional = await ProfessionalModel.getById(booking.professionalId);
    const proPhone = professional?.phoneNumber || professional?.phone || booking.professionalPhone || '';
    const proLocation = professional?.location || null;

    const history = addHistoryEntry(booking.negotiationHistory, {
      from: 'accepted',
      price: finalPrice,
      action: 'accepted',
      timestamp: Date.now(),
    });

    await db.ref(`${BOOKINGS_PATH}/${bookingId}`).update({
      agreedPrice: finalPrice,
      commissionAmount: commission,
      professionalEarnings: earnings,
      professionalPhone: proPhone,
      professionalLocation: proLocation,
      status: 'confirmed',
      paymentStatus: 'pending_commission',
      commissionDeducted: false,
      confirmedAt: Date.now(),
      negotiationHistory: history,
      updatedAt: Date.now()
    });

    return this.getById(bookingId);
  },

  // Reject Booking
  async rejectBooking(bookingId) {
    const booking = await this.getById(bookingId);
    if (!booking) throw new Error('Booking not found');

    if (
      booking.commissionDeducted === true &&
      Number(booking.commissionAmount || 0) > 0 &&
      booking.professionalId
    ) {
      const proRef = db.ref(`professionals/${booking.professionalId}`);
      const proSnap = await proRef.once('value');
      const pro = proSnap.val() || {};
      const currentWallet = Number(pro.wallet ?? pro.walletBalance ?? 5000);
      const refund = Number(booking.commissionAmount || 0);
      const refundedWallet = toMoney(currentWallet + refund);

      await proRef.update({
        wallet: refundedWallet,
        walletBalance: refundedWallet,
        updatedAt: Date.now(),
      });

      const txId = uuidv4();
      await db.ref(`transactions/${txId}`).set({
        id: txId,
        professionalId: booking.professionalId,
        bookingId,
        amount: refund,
        type: 'commission_refund',
        status: 'completed',
        timestamp: Date.now(),
      });
    }

    return this.updateStatus(bookingId, 'rejected');
  },

  // Cancel Booking
  async cancel(bookingId) {
    return this.updateStatus(bookingId, 'cancelled');
  },

  // Start Job (professional starts)
  async startJob(bookingId) {
    return this.updateStatus(bookingId, 'in_progress');
  },

  // Complete Booking (professional marks completed)
  async completeBooking(bookingId) {
    const booking = await this.getById(bookingId);
    if (!booking) throw new Error('Booking not found');

    await db.ref(`${BOOKINGS_PATH}/${bookingId}`).update({
      status: 'completed',
      completedAt: Date.now(),
      updatedAt: Date.now()
    });

    // Increment completed jobs count on professional profile
    await ProfessionalModel.incrementCompletedJobs(booking.professionalId);

    return this.getById(bookingId);
  },

  async customerConfirmCompletion(bookingId) {
    const booking = await this.getById(bookingId);
    if (!booking) throw new Error('Booking not found');
    await db.ref(`${BOOKINGS_PATH}/${bookingId}`).update({
      status: 'customer_confirmed',
      customerConfirmedAt: Date.now(),
      updatedAt: Date.now(),
    });
    return this.getById(bookingId);
  },

  async professionalConfirmCompletion(bookingId) {
    const booking = await this.getById(bookingId);
    if (!booking) throw new Error('Booking not found');
    await db.ref(`${BOOKINGS_PATH}/${bookingId}`).update({
      status: 'completed',
      completedAt: Date.now(),
      professionalConfirmedAt: Date.now(),
      updatedAt: Date.now(),
    });
    await ProfessionalModel.incrementCompletedJobs(booking.professionalId);
    return this.getById(bookingId);
  },

  // Confirm Payment (verified screenshot/txn ID)
  async confirmPayment(bookingId, transactionId, screenshotUrl) {
    const booking = await this.getById(bookingId);
    if (!booking) throw new Error('Booking not found');

    const commission = booking.commissionAmount || 0;
    const earnings = booking.professionalEarnings || 0;
    const proId = booking.professionalId;

    // Deduct 10% commission from professional's wallet in RTDB
    const walletRef = db.ref(`professionals/${proId}/walletBalance`);
    const transactionResult = await walletRef.transaction((current) => {
      const currVal = typeof current === 'number' ? current : (current ? Number(current) : 0);
      if (isNaN(currVal)) return 0;
      if (currVal - commission < 0) {
        // Return undefined to abort transaction if balance is insufficient
        return;
      }
      return currVal - commission;
    }, { applyLocally: false });

    if (!transactionResult.committed) {
      throw new Error('Insufficient professional wallet balance for commission deduction. Professional must recharge wallet.');
    }

    const newBalance = transactionResult.snapshot.val();

    // Add 90% earnings to professional's totalEarnings in RTDB
    const earningsRef = db.ref(`professionals/${proId}/totalEarnings`);
    await earningsRef.transaction((current) => {
      const currVal = typeof current === 'number' ? current : (current ? Number(current) : 0);
      return currVal + earnings;
    });

    // Create a transaction record in transactions
    const txId = uuidv4();
    const txData = {
      professionalId: proId,
      bookingId,
      amount: commission,
      type: 'commission_deduction',
      timestamp: Date.now()
    };
    await db.ref(`transactions/${txId}`).set(txData);

    // Update booking values
    await db.ref(`${BOOKINGS_PATH}/${bookingId}`).update({
      status: 'confirmed',
      paymentStatus: 'completed',
      transactionId,
      screenshotUrl,
      updatedAt: Date.now()
    });

    return {
      newBalance,
      commission,
      professionalEarnings: earnings
    };
  },

  // Add rating after job completion
  async addRating(bookingId, rating, review) {
    await db.ref(`${BOOKINGS_PATH}/${bookingId}/customerRating`).set(rating);
    if (review) {
      await db.ref(`${BOOKINGS_PATH}/${bookingId}/customerReview`).set(review);
    }
    await db.ref(`${BOOKINGS_PATH}/${bookingId}/updatedAt`).set(Date.now());
  },

  async getActiveBookingsForUser(uid) {
    const all = await this.getByUserId(uid);
    const activeStatuses = ['pending_acceptance', 'pending_customer_response', 'pending_professional_response', 'pending_payment', 'confirmed', 'in_progress', 'customer_confirmed'];
    
    return all
      .filter(b => activeStatuses.includes(b.status))
      .sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0));
  }
};

module.exports = BookingModel;