| const path = require('path'); |
| const mongoose = require('mongoose'); |
| const { getBalanceConfig } = require('@librechat/api'); |
| const { User, Balance } = require('@librechat/data-schemas').createModels(mongoose); |
| require('module-alias')({ base: path.resolve(__dirname, '..', 'api') }); |
| const { askQuestion, silentExit } = require('./helpers'); |
| const connect = require('./connect'); |
|
|
| (async () => { |
| await connect(); |
|
|
| |
| |
| |
| console.purple('--------------------------'); |
| console.purple('Set balance to a user account!'); |
| console.purple('--------------------------'); |
| |
| |
| |
| let email = ''; |
| let amount = ''; |
| |
| if (process.argv.length >= 3) { |
| email = process.argv[2]; |
| amount = process.argv[3]; |
| } else { |
| console.orange('Usage: npm run set-balance <email> <amount>'); |
| console.orange('Note: if you do not pass in the arguments, you will be prompted for them.'); |
| console.purple('--------------------------'); |
| |
| } |
|
|
| const balanceConfig = getBalanceConfig(); |
| if (!balanceConfig?.enabled) { |
| console.red( |
| 'Error: Balance is not enabled. Use librechat.yaml to enable it', |
| ); |
| silentExit(1); |
| } |
|
|
| |
| |
| |
| if (!email) { |
| email = await askQuestion('Email:'); |
| } |
| |
| if (!email.includes('@')) { |
| console.red('Error: Invalid email address!'); |
| silentExit(1); |
| } |
|
|
| |
| const user = await User.findOne({ email }).lean(); |
| if (!user) { |
| console.red('Error: No user with that email was found!'); |
| silentExit(1); |
| } else { |
| console.purple(`Found user: ${user.email}`); |
| } |
|
|
| let balance = await Balance.findOne({ user: user._id }).lean(); |
| if (!balance) { |
| console.purple('User has no balance!'); |
| } else { |
| console.purple(`Current Balance: ${balance.tokenCredits}`); |
| } |
|
|
| if (!amount) { |
| amount = await askQuestion('amount:'); |
| } |
| |
| if (!amount) { |
| console.red('Error: Please specify an amount!'); |
| silentExit(1); |
| } |
|
|
| |
| |
| |
| let result; |
| try { |
| result = await Balance.findOneAndUpdate( |
| { user: user._id }, |
| { tokenCredits: amount }, |
| { upsert: true, new: true }, |
| ).lean(); |
| } catch (error) { |
| console.red('Error: ' + error.message); |
| console.error(error); |
| silentExit(1); |
| } |
|
|
| |
| if (result?.tokenCredits == null) { |
| console.red('Error: Something went wrong while updating the balance!'); |
| console.error(result); |
| silentExit(1); |
| } |
|
|
| |
| console.green('Balance set successfully!'); |
| console.purple(`New Balance: ${result.tokenCredits}`); |
| silentExit(0); |
| })(); |
|
|
| process.on('uncaughtException', (err) => { |
| if (!err.message.includes('fetch failed')) { |
| console.error('There was an uncaught error:'); |
| console.error(err); |
| } |
|
|
| if (err.message.includes('fetch failed')) { |
| return; |
| } else { |
| process.exit(1); |
| } |
| }); |
|
|