All files / src/routes admin-economy.js

98.87% Statements 176/178
95.7% Branches 156/163
100% Functions 11/11
100% Lines 157/157

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413                            3x 3x 3x 3x 3x 3x                         3x 6x 5x 5x 4x 3x   3x                           1x       1x         3x 20x 19x 19x 19x   19x 19x   19x 19x 2x   17x 17x 1x     16x 16x 16x 15x     15x 15x 15x 15x 15x   15x                                                 14x 14x 14x 14x 14x 14x         5x 5x     14x             1x       1x         3x 12x 11x 11x 11x 10x 2x     8x 8x   8x 2x   6x             7x                   7x 7x 7x 6x 6x   6x     6x 6x   1x       1x       7x   1x       1x         3x 6x 5x 5x 4x 3x   3x         1x       1x         3x 13x 12x 12x 12x   12x 12x 8x 8x 1x 7x   11x 4x 4x 1x 3x     10x 1x   9x                       8x   1x       1x         3x 9x 8x 8x 8x   8x   8x 1x     8x   8x 7x 7x   7x   1x       1x         3x 7x 6x 6x 5x 4x     4x   4x 4x 3x 3x 2x 2x                 4x                 1x       1x         3x 7x 6x 6x 6x     5x 4x 3x   3x                       3x           1x       1x         3x 3x 2x 2x                       1x   1x       1x       3x  
/**
 * Admin economy routes — balance adjustment, backpack, luck, transactions, gacha guarantee.
 *
 * GET    /users/:uniqueId/economy              → Economy snapshot
 * POST   /users/:uniqueId/adjust-balance       → Adjust coins or beans
 * POST   /users/:uniqueId/backpack             → Set backpack item quantity
 * GET    /users/:uniqueId/luck                 → Get luck + pity
 * POST   /users/:uniqueId/luck                 → Update luck/pity
 * GET    /users/:uniqueId/transactions         → Paginated transaction history
 * GET    /users/:uniqueId/guarantee-next-pull  → Check guarantee status
 * POST   /users/:uniqueId/guarantee-next-pull  → Set guaranteed next pull
 * DELETE /users/:uniqueId/guarantee-next-pull  → Revoke guarantee
 */
 
const router = require('express').Router();
const { db } = require('../utils/firebase');
const { requireAdmin } = require('../middleware/auth');
const { generateId, now } = require('../utils/helpers');
const { sendSystemPm } = require('../utils/system-pm');
const log = require('../utils/log');
 
// Admin enforcement: per-handler `requireAdmin`. The earlier
// `router.use('/users', adminGuard)` form matched every `/users...` URL —
// colliding with users.js (profile, follow, etc.), economy.js (gift-wall),
// and any future sibling file under the heavily-shared `/users` namespace.
// It worked by route-registration order only: non-admin /users routes
// register first in src/index.js, so the prefix guard only caught
// fall-through. Inline guards match the convention used across the rest
// of the admin route surface and remove the order-dependent guarantee.
// See project-cross-router-guard-followups.md.
 
// ── Economy snapshot ──
router.get('/users/:uniqueId/economy', async (req, res) => {
  if (await requireAdmin(req, res)) return;
  try {
    const snap = await db.doc(`users/${req.params.uniqueId}`).get();
    if (!snap.exists) return res.status(404).json({ error: 'User not found' });
    const user = snap.data();
 
    res.json({
      shyCoins: user.shyCoins ?? user.shy_coins ?? 0,
      shyBeans: user.shyBeans ?? user.shy_beans ?? 0,
      luckScore: user.luckScore ?? user.luck_score ?? 0,
      pityCounter: user.pityCounter ?? user.pity_counter ?? 0,
      isSuperShy: user.isSuperShy ?? user.is_super_shy ?? false,
      superShyExpiry: user.superShyExpiry ?? user.super_shy_expiry ?? null,
      superShyTier: user.superShyTier ?? user.super_shy_tier ?? null,
      loginStreak: user.loginStreak ?? user.login_streak ?? 0,
      lastLoginDate: user.lastLoginDate ?? user.last_login_date ?? null,
      guaranteedNextPullGiftId:
        user.guaranteedNextPullGiftId ?? user.guaranteed_next_pull_gift_id ?? null,
    });
  } catch (err) {
    log.error('admin-economy', 'Error fetching economy snapshot', {
      uid: req.params.uniqueId,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Adjust balance (coins or beans) ──
router.post('/users/:uniqueId/adjust-balance', async (req, res) => {
  if (await requireAdmin(req, res)) return;
  try {
    const body = req.body;
    Iif (!body) return res.status(400).json({ error: 'Invalid JSON body' });
 
    const { reason } = body;
    const currency = (body.currency || '').toLowerCase();
    // Support both signed amount and operation+amount
    let amount = body.amount;
    if (typeof amount !== 'number' || amount === 0) {
      return res.status(400).json({ error: 'amount must be a non-zero number' });
    }
    if (body.operation === 'deduct' && amount > 0) amount = -amount;
    if (!['coins', 'beans'].includes(currency)) {
      return res.status(400).json({ error: 'currency must be "coins" or "beans"' });
    }
 
    const field = currency === 'coins' ? 'shyCoins' : 'shyBeans';
    const snap = await db.doc(`users/${req.params.uniqueId}`).get();
    if (!snap.exists) return res.status(404).json({ error: 'User not found' });
    const user = snap.data();
 
    const currentBalance =
      user[field] ?? (currency === 'coins' ? (user.shy_coins ?? 0) : (user.shy_beans ?? 0));
    const newBalance = Math.max(0, currentBalance + amount);
    const timestamp = now();
    const txId = generateId();
    const logId = generateId();
 
    await Promise.all([
      db.doc(`users/${req.params.uniqueId}`).update({ [field]: newBalance }),
 
      db.doc(`users/${req.params.uniqueId}/transactions/${txId}`).set({
        id: txId,
        userId: req.params.uniqueId,
        type: 'ADMIN_ADJUSTMENT',
        amount: amount,
        currency: currency.toUpperCase(),
        balanceAfter: newBalance,
        details: reason || `Admin adjustment: ${amount > 0 ? '+' : ''}${amount} ${currency}`,
        timestamp: timestamp,
      }),
 
      db.doc(`adminAuditLog/${logId}`).set({
        adminId: req.auth.uid,
        action: 'ADJUST_BALANCE',
        targetUserId: req.params.uniqueId,
        details: `${amount > 0 ? '+' : ''}${amount} ${currency} (${reason || 'no reason'})`,
        createdAt: timestamp,
      }),
    ]);
 
    // Send system PM about balance adjustment. Track failure for admin UI's
    // PartialFailureToast — `pms: { failed, total }` is the standard shape.
    const currencyName = currency === 'coins' ? 'Shy Coins' : 'Shy Beans';
    const absAmount = Math.abs(amount);
    const action = amount > 0 ? 'were added to' : 'were deducted from';
    let pmFailed = 0;
    try {
      await sendSystemPm(
        req.params.uniqueId,
        `${absAmount} ${currencyName} ${action} your account.`,
      );
    } catch (e) {
      log.warn('system-pm', 'Failed to send', { uid: req.params.uniqueId, error: e.message });
      pmFailed = 1;
    }
 
    res.json({
      success: true,
      newBalance,
      currency,
      pms: { failed: pmFailed, total: 1 },
    });
  } catch (err) {
    log.error('admin-economy', 'Error adjusting balance', {
      uid: req.params.uniqueId,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Set backpack item quantity (admin) ──
router.post('/users/:uniqueId/backpack', async (req, res) => {
  if (await requireAdmin(req, res)) return;
  try {
    const body = req.body;
    if (!body?.giftId) return res.status(400).json({ error: 'giftId required' });
    if (typeof body.quantity !== 'number' || body.quantity < 0) {
      return res.status(400).json({ error: 'quantity must be a non-negative number' });
    }
 
    const timestamp = now();
    const backpackRef = db.doc(`users/${req.params.uniqueId}/backpack/${body.giftId}`);
 
    if (body.quantity === 0) {
      await backpackRef.delete();
    } else {
      await backpackRef.set({
        giftId: body.giftId,
        quantity: body.quantity,
        lastAcquired: timestamp,
      });
    }
 
    await db.doc(`adminAuditLog/${generateId()}`).set({
      adminId: req.auth.uid,
      action: 'SET_BACKPACK',
      targetUserId: req.params.uniqueId,
      details: `Set ${body.giftId} quantity to ${body.quantity}`,
      createdAt: timestamp,
    });
 
    // Notify user about backpack change (unless silent). Track failure
    // so admin UI sees `pms: { failed, total }` for partial-failure toast.
    let pmFailed = 0;
    let pmTotal = 0;
    if (!body.silent) {
      pmTotal = 1;
      const name = body.giftName || body.giftId;
      const msg =
        body.quantity === 0
          ? `🎒 "${name}" has been removed from your backpack by the moderation team.`
          : `🎒 Your backpack has been updated: "${name}" quantity set to ${body.quantity}.`;
      try {
        await sendSystemPm(req.params.uniqueId, msg);
      } catch (err) {
        log.error('admin-economy', 'Failed to send backpack PM', {
          uid: req.params.uniqueId,
          error: err.message,
        });
        pmFailed = 1;
      }
    }
 
    res.json({ success: true, pms: { failed: pmFailed, total: pmTotal } });
  } catch (err) {
    log.error('admin-economy', 'Error setting backpack item', {
      uid: req.params.uniqueId,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Get luck + pity ──
router.get('/users/:uniqueId/luck', async (req, res) => {
  if (await requireAdmin(req, res)) return;
  try {
    const snap = await db.doc(`users/${req.params.uniqueId}`).get();
    if (!snap.exists) return res.status(404).json({ error: 'User not found' });
    const user = snap.data();
 
    res.json({
      luckScore: user.luckScore ?? user.luck_score ?? 0,
      pityCounter: user.pityCounter ?? user.pity_counter ?? 0,
    });
  } catch (err) {
    log.error('admin-economy', 'Error fetching luck', {
      uid: req.params.uniqueId,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Update luck/pity ──
router.post('/users/:uniqueId/luck', async (req, res) => {
  if (await requireAdmin(req, res)) return;
  try {
    const body = req.body;
    Iif (!body) return res.status(400).json({ error: 'Invalid JSON body' });
 
    const updates = {};
    if (body.luckScore !== null && body.luckScore !== undefined) {
      const parsed = Number.parseInt(body.luckScore, 10);
      if (Number.isNaN(parsed))
        return res.status(400).json({ error: 'luckScore must be a number' });
      updates.luckScore = Math.max(0, Math.min(100, parsed));
    }
    if (body.pityCounter !== null && body.pityCounter !== undefined) {
      const parsed = Number.parseInt(body.pityCounter, 10);
      if (Number.isNaN(parsed))
        return res.status(400).json({ error: 'pityCounter must be a number' });
      updates.pityCounter = Math.max(0, parsed);
    }
 
    if (Object.keys(updates).length === 0)
      return res.status(400).json({ error: 'No fields to update' });
 
    await Promise.all([
      db.doc(`users/${req.params.uniqueId}`).update(updates),
 
      db.doc(`adminAuditLog/${generateId()}`).set({
        adminId: req.auth.uid,
        action: 'SET_LUCK',
        targetUserId: req.params.uniqueId,
        details: JSON.stringify(body),
        createdAt: now(),
      }),
    ]);
 
    res.json({ success: true });
  } catch (err) {
    log.error('admin-economy', 'Error updating luck', {
      uid: req.params.uniqueId,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Transaction history (admin view — any user) ──
router.get('/users/:uniqueId/transactions', async (req, res) => {
  if (await requireAdmin(req, res)) return;
  try {
    const limit = Math.min(Number.parseInt(req.query.limit, 10) || 50, 200);
    const filterType = req.query.type;
 
    let query = db.collection(`users/${req.params.uniqueId}/transactions`);
 
    if (filterType) {
      query = query.where('type', '==', filterType);
    }
 
    query = query.limit(limit);
 
    const snapshot = await query.get();
    const results = snapshot.docs.map((d) => ({ id: d.id, ...d.data() }));
    results.sort((a, b) => (b.timestamp || 0) - (a.timestamp || 0));
 
    res.json(results);
  } catch (err) {
    log.error('admin-economy', 'Error fetching transactions', {
      uid: req.params.uniqueId,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Gacha guarantee: check ──
router.get('/users/:uniqueId/guarantee-next-pull', async (req, res) => {
  if (await requireAdmin(req, res)) return;
  try {
    const snap = await db.doc(`users/${req.params.uniqueId}`).get();
    if (!snap.exists) return res.status(404).json({ error: 'User not found' });
    const user = snap.data();
 
    const guaranteedGiftId =
      user.guaranteedNextPullGiftId ?? user.guaranteed_next_pull_gift_id ?? null;
 
    let gift = null;
    if (guaranteedGiftId) {
      const giftSnap = await db.doc(`gifts/${guaranteedGiftId}`).get();
      if (giftSnap.exists) {
        const giftData = giftSnap.data();
        gift = {
          id: giftSnap.id,
          name: giftData.name,
          coinValue: giftData.coinValue ?? giftData.coin_value,
          iconUrl: giftData.iconUrl ?? giftData.icon_url,
        };
      }
    }
 
    res.json({
      active: !!guaranteedGiftId,
      guaranteedGiftId,
      giftName: gift?.name ?? null,
      coinValue: gift?.coinValue ?? 0,
      setAt: user.guaranteedNextPullSetAt ?? null,
      gift,
    });
  } catch (err) {
    log.error('admin-economy', 'Error checking guarantee status', {
      uid: req.params.uniqueId,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Gacha guarantee: set ──
router.post('/users/:uniqueId/guarantee-next-pull', async (req, res) => {
  if (await requireAdmin(req, res)) return;
  try {
    const body = req.body;
    if (!body?.giftId) return res.status(400).json({ error: 'giftId required' });
 
    // Verify gift exists
    const giftSnap = await db.doc(`gifts/${body.giftId}`).get();
    if (!giftSnap.exists) return res.status(404).json({ error: 'Gift not found' });
    const gift = giftSnap.data();
 
    await Promise.all([
      db.doc(`users/${req.params.uniqueId}`).update({ guaranteedNextPullGiftId: body.giftId }),
 
      db.doc(`adminAuditLog/${generateId()}`).set({
        adminId: req.auth.uid,
        action: 'SET_GUARANTEE',
        targetUserId: req.params.uniqueId,
        details: `Guaranteed: ${body.giftId}`,
        createdAt: now(),
      }),
    ]);
 
    res.json({
      success: true,
      giftName: gift.name ?? gift.giftName ?? body.giftId,
      coinValue: gift.coinValue ?? gift.coin_value ?? 0,
    });
  } catch (err) {
    log.error('admin-economy', 'Error setting guarantee', {
      uid: req.params.uniqueId,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Gacha guarantee: revoke ──
router.delete('/users/:uniqueId/guarantee-next-pull', async (req, res) => {
  if (await requireAdmin(req, res)) return;
  try {
    await Promise.all([
      db.doc(`users/${req.params.uniqueId}`).update({ guaranteedNextPullGiftId: null }),
 
      db.doc(`adminAuditLog/${generateId()}`).set({
        adminId: req.auth.uid,
        action: 'REVOKE_GUARANTEE',
        targetUserId: req.params.uniqueId,
        details: null,
        createdAt: now(),
      }),
    ]);
 
    res.json({ success: true });
  } catch (err) {
    log.error('admin-economy', 'Error revoking guarantee', {
      uid: req.params.uniqueId,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
module.exports = router;