File size: 5,451 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
const jwt = require('jsonwebtoken');
const { dbGet, dbGetAll, dbSet, dbDelete } = require('../config/firebase');

const ADMIN_TOKEN_SECRET = process.env.ADMIN_JWT_SECRET || process.env.JWT_SECRET || 'service-connect-secret-change-in-production';
const ADMIN_TOKEN_EXPIRES = process.env.ADMIN_TOKEN_EXPIRES || '8h';

const AdminModel = {
  createToken(username) {
    return jwt.sign({ username, role: 'admin' }, ADMIN_TOKEN_SECRET, { expiresIn: ADMIN_TOKEN_EXPIRES });
  },

  verifyToken(token) {
    return jwt.verify(token, ADMIN_TOKEN_SECRET);
  },

  async getStats() {
    const professionals = await dbGetAll('professionals');
    const users = await dbGetAll('users') || [];
    const bookings = await dbGetAll('bookings') || [];
    const completed = bookings.filter((b) => b.status === 'completed');

    // Calculate commission as 10% of agreed/proposed price of completed bookings
    const commissionFromBookings = completed.reduce((sum, b) => {
      const price = b.agreedPrice || b.proposedPrice || 0;
      return sum + (price * 0.10);
    }, 0);

    return {
      totalProfessionals: professionals.length,
      totalCustomers: users.filter((u) => u.role === 'customer').length,
      totalBookings: bookings.length,
      totalCompletedJobs: completed.length,
      totalPendingJobs: bookings.filter((b) => ['pending_acceptance', 'pending_payment', 'confirmed', 'in_progress', 'pending_customer_response', 'pending_professional_response'].includes(b.status)).length,
      totalCommission: parseFloat(commissionFromBookings.toFixed(2)),
    };
  },

  async listProfessionals() {
    const professionals = await dbGetAll('professionals') || [];
    const users = await dbGetAll('users') || [];
    return professionals.map((pro) => {
      const user = users.find((u) => u.uid === pro.uid) || {};
      return {
        ...pro,
        displayName: user.displayName || 'Professional',
        email: user.email || '',
        phoneNumber: user.phoneNumber || '',
        rating: user.rating || pro.rating || 0,
        totalJobs: pro.completedJobs || 0,
      };
    });
  },

  async listCustomers() {
    const users = await dbGetAll('users') || [];
    const bookings = await dbGetAll('bookings') || [];
    const customers = users.filter((user) => user.role === 'customer');
    return customers.map((c) => {
      const count = bookings.filter((b) => b.customerId === c.uid).length;
      return {
        ...c,
        totalBookings: count,
      };
    });
  },

  async listBookings() {
    const bookings = await dbGetAll('bookings') || [];
    const users = await dbGetAll('users') || [];
    return bookings.map((b) => {
      const customer = users.find((u) => u.uid === b.customerId) || {};
      const professional = users.find((u) => u.uid === b.professionalId) || {};
      return {
        ...b,
        customerName: customer.displayName || 'Customer',
        professionalName: professional.displayName || 'Professional',
      };
    });
  },

  async listTransactions() {
    const transactions = await dbGetAll('transactions') || [];
    const users = await dbGetAll('users') || [];
    return transactions.map((tx) => {
      const pro = users.find((u) => u.uid === tx.professionalId) || {};
      return {
        ...tx,
        professionalName: pro.displayName || 'Professional',
      };
    });
  },

  async deleteUser(uid) {
    const bookings = await dbGetAll('bookings') || [];
    const payments = await dbGetAll('payments') || [];
    const transactions = await dbGetAll('transactions') || [];
    const bookingIds = bookings.filter((b) => b.customerId === uid || b.professionalId === uid).map((b) => b.bookingId);

    for (const bookingId of bookingIds) {
      await dbDelete(`bookings/${bookingId}`);
    }

    for (const payment of payments.filter((p) => p.customerId === uid || p.professionalId === uid)) {
      await dbDelete(`payments/${payment.paymentId}`);
    }

    for (const transaction of transactions.filter((t) => t.customerId === uid || t.professionalId === uid)) {
      await dbDelete(`transactions/${transaction._key || transaction.transactionId}`);
    }

    await dbDelete(`users/${uid}`);
    await dbDelete(`professionals/${uid}`);
  },

  async deleteBooking(bookingId) {
    const payments = await dbGetAll('payments') || [];
    const transactions = await dbGetAll('transactions') || [];

    await dbDelete(`bookings/${bookingId}`);
    for (const payment of payments.filter((p) => p.bookingId === bookingId)) {
      await dbDelete(`payments/${payment.paymentId}`);
    }
    for (const transaction of transactions.filter((t) => t.bookingId === bookingId)) {
      await dbDelete(`transactions/${transaction._key || transaction.transactionId}`);
    }
  },

  async clearAllData() {
    const users = await dbGetAll('users') || [];
    const keepAdminIds = new Set(
      users
        .filter((u) => u.role === 'admin' || String(u.displayName || '').toLowerCase() === 'huzaifa')
        .map((u) => u.uid),
    );

    const keysToClear = [
      'bookings',
      'payments',
      'transactions',
      'professionals',
      'chats',
      'userBookings',
      'locationTracking',
    ];
    for (const key of keysToClear) {
      await dbDelete(key);
    }

    for (const user of users) {
      if (!user?.uid) continue;
      if (keepAdminIds.has(user.uid)) continue;
      await dbDelete(`users/${user.uid}`);
    }
  },
};

module.exports = AdminModel;