File size: 3,466 Bytes
de5ba48
 
 
ef60d4f
de5ba48
 
 
 
c5452f2
de5ba48
 
 
 
ef60d4f
 
c5452f2
 
 
de5ba48
 
 
 
ef60d4f
 
 
c5452f2
 
 
 
 
 
 
 
 
 
ef60d4f
 
 
 
c5452f2
 
ef60d4f
 
 
 
 
de5ba48
 
 
 
 
 
 
 
0d4e43d
de5ba48
 
 
 
 
 
 
0d4e43d
de5ba48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d4e43d
de5ba48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d4e43d
de5ba48
 
 
 
 
 
ef60d4f
de5ba48
 
 
 
 
 
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
const { db } = require('../config/firebase');

const MIN_CAPTAIN_BALANCE = 200;
const CAPTAIN_STARTER_BALANCE = 5000;

async function ensureWallet(uid) {
  const ref = db.collection('wallets').doc(uid);
  const doc = await ref.get();
  const now = new Date().toISOString();
  if (!doc.exists) {
    const wallet = {
      id: uid,
      userId: uid,
      balance: CAPTAIN_STARTER_BALANCE,
      starterBalanceApplied: true,
      starterBalanceAmount: CAPTAIN_STARTER_BALANCE,
      createdAt: now,
      updatedAt: now,
    };
    await ref.set(wallet);
    return wallet;
  }

  const data = doc.data() || {};
  const currentBalance = Number(data.balance || 0);
  const starterMissing = data.starterBalanceApplied !== true;
  const legacyZeroWallet =
    currentBalance <= 0 && data.starterBalanceAmount !== CAPTAIN_STARTER_BALANCE;
  if (starterMissing || legacyZeroWallet) {
    const txSnap = await db
      .collection('transactions')
      .where('walletId', '==', uid)
      .limit(1)
      .get();
    if (!txSnap.empty && !starterMissing) return { id: uid, ...data };
    const updated = {
      ...data,
      balance: CAPTAIN_STARTER_BALANCE,
      starterBalanceApplied: true,
      starterBalanceAmount: CAPTAIN_STARTER_BALANCE,
      updatedAt: now,
    };
    await ref.set(updated, { merge: true });
    return { id: uid, ...updated };
  }

  return { id: uid, ...doc.data() };
}

async function getBalance(uid) {
  const wallet = await ensureWallet(uid);
  return wallet.balance || 0;
}

async function recordTransaction({ walletId, type, amount, description, dealId, reference, balanceAfter }) {
  await db.collection('transactions').add({
    walletId,
    type,
    amount: Math.abs(amount),
    description: description || type,
    dealId: dealId || null,
    reference: reference || null,
    balanceAfter: balanceAfter ?? null,
    createdAt: new Date().toISOString(),
  });
}

async function addBalance(uid, amount, meta = {}) {
  const ref = db.collection('wallets').doc(uid);
  await ensureWallet(uid);
  let newBalance = 0;
  await db.runTransaction(async (t) => {
    const snap = await t.get(ref);
    newBalance = (snap.data().balance || 0) + amount;
    t.update(ref, {
      balance: newBalance,
      updatedAt: new Date().toISOString(),
    });
  });
  await recordTransaction({
    walletId: uid,
    type: meta.type || 'topup',
    amount,
    description: meta.description || 'Wallet top-up',
    reference: meta.reference,
    balanceAfter: newBalance,
  });
  return newBalance;
}

async function deductBalance(uid, amount, meta = {}) {
  const ref = db.collection('wallets').doc(uid);
  await ensureWallet(uid);
  let newBalance = 0;
  await db.runTransaction(async (t) => {
    const snap = await t.get(ref);
    const current = snap.data().balance || 0;
    if (current < amount) {
      throw new Error(`Insufficient wallet balance (Rs. ${current}). Need Rs. ${amount}.`);
    }
    newBalance = current - amount;
    t.update(ref, {
      balance: newBalance,
      updatedAt: new Date().toISOString(),
    });
  });
  await recordTransaction({
    walletId: uid,
    type: meta.type || 'commission_deduction',
    amount,
    description: meta.description || 'Wallet deduction',
    dealId: meta.dealId,
    balanceAfter: newBalance,
  });
  return newBalance;
}

module.exports = {
  MIN_CAPTAIN_BALANCE,
  CAPTAIN_STARTER_BALANCE,
  ensureWallet,
  getBalance,
  recordTransaction,
  addBalance,
  deductBalance,
};