Files
mbmanager-api/components/transaction/transactionService.js
T

239 lines
7.5 KiB
JavaScript

const Transaction = require('./transactionModel')
const Belonging = require('../belonging/belongingModel')
const AppError = require('../../globalErrorHandler/AppError')
const mongoose = require('mongoose')
const ObjectID = mongoose.Schema.Types.ObjectId
const { client } = require('../../setup/typesense')
const TsApiFeatures = require('../../utils/TsApiFeatures')
const filterObj = (obj, ...allowedFields) => {
const newObj = {}
Object.keys(obj).forEach((el) => {
if (allowedFields.includes(el)) newObj[el] = obj[el]
})
return newObj
}
const createTransaction = async (data) => {
if (data.type == 'withdraw') {
// Aggregate transactions to calculate inventory
const result = await Transaction.aggregate([
{
$match: {
belongingId: ObjectID,
status: 'finished',
},
},
{
$group: {
_id: '$belongingId',
totalInventory: {
$sum: '$value',
},
},
},
])
if (result[0].totalInventory <= 0) throw new AppError('Invalid Transaction', 404, {})
}
return Transaction.create({
type: data.type,
status: data.status,
source: data.source,
value: data.type === 'withdraw' ? data.value * -1 : data.value,
date: data.Date,
description: data.description,
userId: data.userId,
belongingId: data.belongingId,
})
}
const getUserTransaction = async (userId) => {
return Transaction.find({ userId }, null, null)
}
const getTransactionByBelongingId = async (belongingId) => {
return Transaction.find({ belongingId }, null, null)
}
const getBelongingInventory = async (belongingId) => {
const belonging = await Belonging.findById(belongingId, null, null)
if (!belonging) {
throw new AppError('NoBelongingFound', 404, {})
}
// Simplified aggregation to calculate inventory metrics
const result = await Transaction.aggregate([
{
$match: {
belongingId: ObjectID,
$or: [{ status: 'finished' }, { status: 'pending' }],
},
},
{
$facet: {
// Calculate total inventory from finished transactions
finishedInventory: [
{ $match: { status: 'finished' } },
{
$group: {
_id: null,
total: { $sum: '$value' },
},
},
],
// Calculate pending deposits
pendingDepositsInventory: [
{
$match: {
status: 'pending',
type: 'deposit',
},
},
{
$group: {
_id: null,
total: { $sum: '$value' },
},
},
],
// Calculate pending withdrawals
pendingWithdrawsInventory: [
{
$match: {
status: 'pending',
type: 'withdraw',
},
},
{
$group: {
_id: null,
total: { $sum: '$value' },
},
},
],
},
},
{
// Restructure the output to get only the values
$project: {
finishedInventory: { $ifNull: [{ $arrayElemAt: ['$finishedInventory.total', 0] }, 0] },
pendingDepositsInventory: { $ifNull: [{ $arrayElemAt: ['$pendingDepositsInventory.total', 0] }, 0] },
pendingWithdrawsInventory: { $ifNull: [{ $arrayElemAt: ['$pendingWithdrawsInventory.total', 0] }, 0] },
},
},
])
return { belongingCode: belonging.belongingCode, ...result[0] }
}
const updateTransaction = async (transactionId, data) => {
const filteredBody = filterObj(data, 'status')
const transaction = await Transaction.findOneAndUpdate({ _id: transactionId }, filteredBody, { new: true })
if (!transaction) {
throw new AppError('NoTransactionFound', 404, {})
}
return transaction
}
const deleteTransaction = async (transactionId) => {
const transaction = await Transaction.findOneAndDelete({ _id: transactionId })
if (!transaction) {
throw AppError('NoTransactionFound', 404, {})
}
return null
}
const ensureCollectionExists = async () => {
const collections = await client.collections().retrieve()
const collectionExists = collections.some((collection) => collection.name === 'transactions')
if (collectionExists) {
await client.collections('transactions').delete()
}
const schema = getTypeSenseSchema()
await client.collections().create(schema)
console.log('Collection "transactions" created successfully')
}
const searchTransactions = async (inputQuery) => {
const tsFeatures = new TsApiFeatures(client, 'transactions', inputQuery).filter().facet().sort().limitFields().paginate().search()
let { facets, items, totalCount, pagesCount } = await tsFeatures.execute()
return { facets, transactions: items, totalCount, pagesCount }
}
const indexAllTransactions = async () => {
const batchSize = 20
const count = await Transaction.countDocuments({}, null)
const rounds = Math.ceil(count / batchSize)
await ensureCollectionExists()
for (let i = 1; i <= rounds; i++) {
console.log(`Indexing ${batchSize} transactions, Round ${i}`)
const transactions = await Transaction.find({}, null, null)
.skip((i - 1) * batchSize)
.limit(batchSize)
let documents = []
for (const transaction of transactions) {
const data = {
_id: transaction._id,
type: transaction.type,
status: transaction.status,
source: transaction.source,
value: transaction.value,
description: transaction.description,
createdAt: Math.floor(new Date(transaction.createdAt).getTime() / 1000), // Store as timestamp in seconds
}
documents.push(data)
}
await client.collections('transactions').documents().import(documents, { action: 'emplace' })
}
return { totalCount: count }
}
const getTypeSenseSchema = () => {
return {
name: 'transactions',
enable_nested_fields: true,
fields: [
{ name: '_id', type: 'string', facet: false, infix: false },
{ name: 'type', type: 'string', facet: false },
{ name: 'status', type: 'string', facet: false },
{ name: 'source', type: 'string', facet: false },
{ name: 'value', type: 'int64', facet: false },
{ name: 'description', type: 'string', facet: false, infix: true },
{ name: 'createdAt', type: 'int64', facet: false },
],
default_sorting_field: 'createdAt',
}
}
module.exports = {
createTransaction,
getUserTransaction,
getBelongingInventory,
updateTransaction,
deleteTransaction,
getTransactionByBelongingId,
indexAllTransactions,
searchTransactions,
}