REFACTOR: Belonging → Property system migration + utilities update
Property system: - Rename belonging → property throughout (model, controller, routes, service) - Add property sub-models: buildingModel, landModel, belongingModel - Add property lifecycle events: createProperty, deleteProperty - Add propertyStatus component (model, controller, routes, service, seeder) - Add commodity and commodityTransaction model stubs Infrastructure: - Update transactionModel and transactionService - Update events/index.js for new property events - Update seeder (seederDBConnection, seederRunner) - Update typesense client configuration - Update upload utilities (bucket, minio) - Update featureModel and featureSeeder - Update categorySeeder - Update TsApiFeatures utility - Remove docker-compose.yml (moved to root) - Remove legacy belonging component files
This commit is contained in:
@@ -1,81 +0,0 @@
|
||||
const catchAsync = require('../../globalErrorHandler/catchAsync')
|
||||
const belongingService = require('./belongingService')
|
||||
const { eventEmitter } = require('../../events/eventEmitter')
|
||||
|
||||
exports.searchBelongings = catchAsync(async (req, res, next) => {
|
||||
const { facets, belongings, totalCount, pagesCount } = await belongingService.searchBelongings(req.query)
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
facets,
|
||||
belongings,
|
||||
totalCount,
|
||||
pagesCount,
|
||||
})
|
||||
})
|
||||
|
||||
exports.indexAllBelongings = catchAsync(async (req, res, next) => {
|
||||
const { indexedCount } = await belongingService.indexAllBelongings()
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
indexedCount,
|
||||
})
|
||||
})
|
||||
|
||||
exports.indexOneBelonging = catchAsync(async (req, res, next) => {
|
||||
await belongingService.indexOneBelonging()
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
})
|
||||
})
|
||||
|
||||
exports.getAllBelongings = catchAsync(async (req, res, next) => {
|
||||
const belongings = await belongingService.getAllBelongings()
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
results: belongings.length,
|
||||
data: belongings,
|
||||
})
|
||||
})
|
||||
|
||||
exports.createBelonging = catchAsync(async (req, res, next) => {
|
||||
const belonging = await belongingService.createBelonging(req.body)
|
||||
eventEmitter.emit('createBelonging', belonging)
|
||||
|
||||
res.status(201).json({
|
||||
status: 'success',
|
||||
data: belonging,
|
||||
})
|
||||
})
|
||||
|
||||
exports.getBelonging = catchAsync(async (req, res, next) => {
|
||||
const belonging = await belongingService.getBelonging(req.params.belongingId)
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
data: belonging,
|
||||
})
|
||||
})
|
||||
|
||||
exports.updateBelonging = catchAsync(async (req, res, next) => {
|
||||
const belonging = await belongingService.updateBelonging(req.params.belongingId, req.body)
|
||||
await belongingService.indexAllBelongings()
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
data: belonging,
|
||||
})
|
||||
})
|
||||
|
||||
exports.deleteBelonging = catchAsync(async (req, res, next) => {
|
||||
await belongingService.deleteBelonging(req.params.belongingId)
|
||||
// eventEmitter.emit('deleteBelonging')
|
||||
|
||||
res.status(204).json({
|
||||
status: 'success',
|
||||
data: null,
|
||||
})
|
||||
})
|
||||
@@ -1,26 +0,0 @@
|
||||
const express = require('express')
|
||||
const belongingController = require('./belongingController')
|
||||
const perm = require('../../middlewares/permissionMiddleware')
|
||||
const loginCheck = require('../../middlewares/loginCheck')
|
||||
|
||||
const router = new express.Router()
|
||||
|
||||
router.use(loginCheck.loginProtect)
|
||||
|
||||
router.get('/admin/get-all', perm.requires('getallbelongings'), belongingController.getAllBelongings)
|
||||
|
||||
router.post('/admin/create', perm.requires('createabelonging'), belongingController.createBelonging)
|
||||
|
||||
router.post('/admin/index-all', perm.requires('indexbelongings'), belongingController.indexAllBelongings)
|
||||
|
||||
router.post('/admin/index-one/:belongingId', perm.requires('indexbelongings'), belongingController.indexOneBelonging)
|
||||
|
||||
router.get('/admin/search', perm.requires('searchbelongings'), belongingController.searchBelongings)
|
||||
|
||||
router.get('/admin/get-one/:belongingId', perm.requires('getabelonging'), belongingController.getBelonging)
|
||||
|
||||
router.put('/admin/update/:belongingId', perm.requires('updateabelonging'), belongingController.updateBelonging)
|
||||
|
||||
router.delete('/admin/delete/:belongingId', perm.requires('deleteabelonging'), belongingController.deleteBelonging)
|
||||
|
||||
module.exports = router
|
||||
@@ -1,182 +0,0 @@
|
||||
const Belonging = require('./belongingModel')
|
||||
const AppError = require('../../globalErrorHandler/AppError')
|
||||
const { client } = require('../../setup/typesense')
|
||||
const TsApiFeatures = require('../../utils/TsApiFeatures')
|
||||
|
||||
const getAllBelongings = async () => {
|
||||
return Belonging.find({}, null, null).populate('category')
|
||||
}
|
||||
|
||||
const createBelonging = async (data) => {
|
||||
return Belonging.create(data, null)
|
||||
}
|
||||
|
||||
const getBelonging = async (belongingId) => {
|
||||
let belonging = await Belonging.findById(belongingId, null, null)
|
||||
|
||||
if (!belonging) {
|
||||
throw new AppError('NoBelongingFound', 404, {})
|
||||
}
|
||||
|
||||
const documentUrls = await belonging.getDocumentsSignedUrls()
|
||||
const mainImageUrls = await belonging.getMainImagedSignedUrl()
|
||||
|
||||
belonging = JSON.parse(JSON.stringify(belonging))
|
||||
|
||||
belonging.signedDocumentUrls = documentUrls
|
||||
belonging.signedMainImageUrls = mainImageUrls
|
||||
|
||||
return belonging
|
||||
}
|
||||
|
||||
const updateBelonging = async (belongingId, data) => {
|
||||
const belonging = await Belonging.findOneAndUpdate({ _id: belongingId }, data, { new: true })
|
||||
|
||||
if (!belonging) {
|
||||
throw new AppError('NoBelongingFound', 404, {})
|
||||
}
|
||||
|
||||
return belonging
|
||||
}
|
||||
|
||||
const deleteBelonging = async (belongingId) => {
|
||||
const belonging = await Belonging.findByIdAndUpdate(belongingId, { isActive: false }, { new: true })
|
||||
|
||||
if (!belonging) {
|
||||
throw new AppError('NoBelongingFound', 404, {})
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
const ensureCollectionExists = async () => {
|
||||
const collections = await client.collections().retrieve()
|
||||
const collectionExists = collections.some((collection) => collection.name === 'belongings')
|
||||
|
||||
if (collectionExists) {
|
||||
await client.collections('belongings').delete()
|
||||
}
|
||||
|
||||
const schema = getTypeSenseSchema()
|
||||
|
||||
await client.collections().create(schema)
|
||||
console.log('Collection "belongings" created successfully')
|
||||
}
|
||||
|
||||
const searchBelongings = async (inputQuery) => {
|
||||
inputQuery = updateInputQuery(inputQuery, {})
|
||||
|
||||
const tsFeatures = new TsApiFeatures(client, 'belongings', inputQuery).filter().facet().sort().limitFields().paginate().search()
|
||||
|
||||
let { facets, items, totalCount, pagesCount } = await tsFeatures.execute()
|
||||
|
||||
return { facets, belongings: items, totalCount, pagesCount }
|
||||
}
|
||||
|
||||
const updateInputQuery = (inputQuery, extraQueries, features) => {
|
||||
for (const [key, value] of Object.entries(extraQueries)) {
|
||||
inputQuery[key] = value
|
||||
}
|
||||
|
||||
inputQuery.query_by = 'name,unit,tags,description,_id'
|
||||
|
||||
return inputQuery
|
||||
}
|
||||
|
||||
const indexAllBelongings = async () => {
|
||||
const batchSize = 20
|
||||
const count = await Belonging.countDocuments({isActive: true}, null)
|
||||
const rounds = Math.ceil(count / batchSize)
|
||||
|
||||
await ensureCollectionExists()
|
||||
|
||||
for (let i = 1; i <= rounds; i++) {
|
||||
console.log(`Indexing ${batchSize} belongings, Round ${i}`)
|
||||
|
||||
const belongings = await Belonging.find({isActive: true}, null, null)
|
||||
.populate('category')
|
||||
.skip((i - 1) * batchSize)
|
||||
.limit(batchSize)
|
||||
|
||||
let documents = []
|
||||
|
||||
for (const belonging of belongings) {
|
||||
|
||||
const combinedTags = belonging.tags.join(' ');
|
||||
|
||||
const data = {
|
||||
_id: belonging._id,
|
||||
isActive: belonging.isActive,
|
||||
// belongingCode: belonging.belongingCode,
|
||||
name: belonging.name,
|
||||
category: belonging.category?.englishName || '',
|
||||
nativeCategory: belonging.category?.nativeName || '',
|
||||
imageUrl: belonging.mainImageUrls[0] || 'https://cloud.mbmanager.ir/images/item-no-image.png',
|
||||
documents: belonging.documentUrls || [] ,
|
||||
description: belonging.description || '',
|
||||
unit: belonging.unit || '',
|
||||
tags: combinedTags || '',
|
||||
coordinates: belonging.location.coordinates || [0, 0],
|
||||
createdAt: Math.floor(new Date(belonging.createdAt).getTime() / 1000), // Store as timestamp in seconds
|
||||
id: belonging.belongingCode.toString(),
|
||||
}
|
||||
|
||||
documents.push(data)
|
||||
}
|
||||
|
||||
await client.collections('belongings').documents().import(documents, { action: 'emplace' })
|
||||
}
|
||||
|
||||
return { totalCount: count }
|
||||
}
|
||||
|
||||
const indexOneBelonging = async (belongingId) => {
|
||||
const belonging = await getBelonging(belongingId)
|
||||
|
||||
console.log(`Belonging ${belonging._id} indexing`)
|
||||
|
||||
const combinedTags = belonging.tags.join(' ');
|
||||
|
||||
const data = {
|
||||
_id: belonging._id,
|
||||
isActive: belonging.isActive,
|
||||
// belongingCode: belonging.belongingCode,
|
||||
name: belonging.name,
|
||||
category: belonging.category?.englishName || '',
|
||||
nativeCategory: belonging.category?.nativeName || '',
|
||||
imageUrl: belonging.mainImageUrls[0] || '',
|
||||
documents: belonging.documentUrls || [] ,
|
||||
description: belonging.description || '',
|
||||
unit: belonging.unit || '',
|
||||
tags: combinedTags || '',
|
||||
coordinates: belonging.location.coordinates || [0, 0],
|
||||
createdAt: Math.floor(new Date(belonging.createdAt).getTime() / 1000), // Store as timestamp in seconds
|
||||
id: belonging.belongingCode.toString(),
|
||||
}
|
||||
|
||||
await client.collections('belongings').documents().upsert(data)
|
||||
|
||||
}
|
||||
|
||||
const getTypeSenseSchema = () => {
|
||||
return {
|
||||
name: 'belongings',
|
||||
enable_nested_fields: true,
|
||||
fields: [
|
||||
{ name: '_id', type: 'string', facet: false, infix: false },
|
||||
{ name: 'name', type: 'string', facet: false, infix: true },
|
||||
// { name: 'belongingCode', type: 'int64', facet: false },
|
||||
{ name: 'category', type: 'string', facet: true, infix: true },
|
||||
{ name: 'nativeCategory', type: 'string', facet: false, infix: true },
|
||||
{ name: 'description', type: 'string', facet: false },
|
||||
{ name: 'unit', type: 'string', facet: false, infix: true },
|
||||
{ name: 'tags', type: 'string', facet: false, infix: true },
|
||||
{ name: 'coordinates', type: 'geopoint' },
|
||||
{ name: 'createdAt', type: 'int64', facet: false },
|
||||
{ name: 'imageUrl', type: 'string', facet: false, infix: true },
|
||||
],
|
||||
default_sorting_field: 'createdAt',
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { updateBelonging, indexAllBelongings, getBelonging, getAllBelongings, createBelonging, deleteBelonging, searchBelongings, indexOneBelonging }
|
||||
@@ -1,6 +0,0 @@
|
||||
const belongingService = require('../belongingService')
|
||||
module.exports = (eventEmitter) => {
|
||||
eventEmitter.on('createBelonging', async (belongingData) => {
|
||||
await belongingService.indexOneBelonging(belongingData._id)
|
||||
})
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
const belongingService = require('../belongingService')
|
||||
module.exports = (eventEmitter) => {
|
||||
eventEmitter.on('deleteBelonging', async (belongingData) => {
|
||||
await belongingService.indexAllBelongings()
|
||||
})
|
||||
}
|
||||
@@ -6,6 +6,7 @@ const runSeeder = async () => {
|
||||
{ nativeName: 'ساختمان', englishName: 'Building' },
|
||||
{ nativeName: 'زمین', englishName: 'Lot' },
|
||||
{ nativeName: 'کالا', englishName: 'Product' },
|
||||
{ nativeName: 'خودرو', englishName: 'Car' },
|
||||
]
|
||||
|
||||
await Category.deleteMany({})
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
const mongoose = require('mongoose')
|
||||
const ObjectID = mongoose.Schema.Types.ObjectId
|
||||
|
||||
const commoditySchema = new mongoose.Schema(
|
||||
{
|
||||
name: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
code: {
|
||||
type: String,
|
||||
unique: true,
|
||||
},
|
||||
category: {
|
||||
type: ObjectID,
|
||||
ref: 'Category',
|
||||
},
|
||||
count: {
|
||||
type: Number,
|
||||
default: 0,
|
||||
},
|
||||
unit: {
|
||||
type: String,
|
||||
required: true, // e.g. عدد، کیلوگرم، متر، ...
|
||||
},
|
||||
warehouse: {
|
||||
type: ObjectID,
|
||||
ref: 'Warehouse',
|
||||
},
|
||||
description: String,
|
||||
isActive: {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
}
|
||||
)
|
||||
|
||||
const Commodity = mongoose.model('Commodity', commoditySchema)
|
||||
module.exports = Commodity
|
||||
@@ -0,0 +1,48 @@
|
||||
const mongoose = require('mongoose')
|
||||
const ObjectID = mongoose.Schema.Types.ObjectId
|
||||
|
||||
const commodityTransactionSchema = new mongoose.Schema(
|
||||
{
|
||||
commodity: {
|
||||
type: ObjectID,
|
||||
ref: 'Commodity',
|
||||
required: true,
|
||||
},
|
||||
type: {
|
||||
type: String,
|
||||
enum: ['IN', 'OUT', 'TRANSFER'], // ورود، خروج، انتقال بین انبارها
|
||||
required: true,
|
||||
},
|
||||
count: {
|
||||
type: Number,
|
||||
required: true,
|
||||
},
|
||||
unit: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
sourceWarehouse: {
|
||||
type: ObjectID,
|
||||
ref: 'Warehouse',
|
||||
},
|
||||
destinationWarehouse: {
|
||||
type: ObjectID,
|
||||
ref: 'Warehouse',
|
||||
},
|
||||
user: {
|
||||
type: ObjectID,
|
||||
ref: 'User',
|
||||
},
|
||||
date: {
|
||||
type: Date,
|
||||
default: Date.now,
|
||||
},
|
||||
description: String,
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
}
|
||||
)
|
||||
|
||||
const CommodityTransaction = mongoose.model('CommodityTransaction', commodityTransactionSchema)
|
||||
module.exports = CommodityTransaction
|
||||
@@ -23,7 +23,7 @@ const featureSchema = new mongoose.Schema({
|
||||
},
|
||||
featureType: {
|
||||
type: String,
|
||||
enum: ['string', 'boolean', 'number', 'date'],
|
||||
enum: ['string', 'textarea', 'boolean', 'number', 'date'],
|
||||
default: 'string',
|
||||
},
|
||||
filterType: {
|
||||
|
||||
+591
-743
File diff suppressed because it is too large
Load Diff
@@ -38,6 +38,10 @@ const belongingSchema = new mongoose.Schema(
|
||||
mainImageUrls: [String],
|
||||
nationalGeoCode: String,
|
||||
tags: [String],
|
||||
status: {
|
||||
type: ObjectID,
|
||||
ref: 'BelongingStatus',
|
||||
},
|
||||
isActive: {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
@@ -0,0 +1,42 @@
|
||||
const mongoose = require('mongoose')
|
||||
const Property = require('./propertyModel')
|
||||
|
||||
const buildingSchema = new mongoose.Schema({
|
||||
builtArea: {
|
||||
type: Number, // مساحت زیربنا به متر مربع
|
||||
},
|
||||
floorsCount: {
|
||||
type: Number, // تعداد طبقات
|
||||
},
|
||||
unitsCount: {
|
||||
type: Number, // تعداد واحدها
|
||||
},
|
||||
constructionYear: {
|
||||
type: Number, // سال ساخت
|
||||
},
|
||||
elevator: {
|
||||
type: Boolean, // آسانسور
|
||||
},
|
||||
parking: {
|
||||
type: Boolean, // پارکینگ
|
||||
},
|
||||
warehouse: {
|
||||
type: Boolean, // انبار
|
||||
},
|
||||
heatingSystem: {
|
||||
type: String, // سیستم گرمایش
|
||||
},
|
||||
coolingSystem: {
|
||||
type: String, // سیستم سرمایش
|
||||
},
|
||||
structureType: {
|
||||
type: String, // نوع سازه (اسکلت فلزی، بتنی، ...)
|
||||
},
|
||||
flooringType: {
|
||||
type: String, // جنس کف (سرامیک، سنگ، لمینت، ...)
|
||||
},
|
||||
})
|
||||
|
||||
const Building = Property.discriminator('Building', buildingSchema)
|
||||
|
||||
module.exports = Building
|
||||
@@ -0,0 +1,6 @@
|
||||
const propertyService = require('../propertyService')
|
||||
module.exports = (eventEmitter) => {
|
||||
eventEmitter.on('createProperty', async (propertyData) => {
|
||||
await propertyService.indexOneProperty(propertyData._id)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
const propertyService = require('../propertyService')
|
||||
module.exports = (eventEmitter) => {
|
||||
eventEmitter.on('deleteProperty', async (propertyData) => {
|
||||
// Handle property deletion event if needed
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
const mongoose = require('mongoose')
|
||||
const Property = require('./propertyModel')
|
||||
|
||||
const landSchema = new mongoose.Schema({
|
||||
landArea: {
|
||||
type: Number, // مساحت زمین به متر مربع
|
||||
},
|
||||
zoningType: {
|
||||
type: String, // نوع کاربری (مسکونی، کشاورزی، تجاری و ...)
|
||||
},
|
||||
boundaryCoordinates: {
|
||||
type: [[Number]], // مختصات چندضلعی حدود ملک
|
||||
},
|
||||
streetWidth: {
|
||||
type: Number, // عرض گذر (متر)
|
||||
},
|
||||
facadeCount: {
|
||||
type: Number, // تعداد بر
|
||||
},
|
||||
landLength: {
|
||||
type: Number, // طول زمین (متر)
|
||||
},
|
||||
landWidth: {
|
||||
type: Number, // عرض زمین (متر)
|
||||
},
|
||||
})
|
||||
|
||||
const Land = Property.discriminator('Land', landSchema)
|
||||
|
||||
module.exports = Land
|
||||
@@ -0,0 +1,81 @@
|
||||
const catchAsync = require('../../globalErrorHandler/catchAsync')
|
||||
const propertyService = require('./propertyService')
|
||||
const { eventEmitter } = require('../../events/eventEmitter')
|
||||
|
||||
exports.searchProperties = catchAsync(async (req, res, next) => {
|
||||
const { facets, belongings, totalCount, pagesCount } = await propertyService.searchProperties(req.query)
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
facets,
|
||||
properties: belongings,
|
||||
totalCount,
|
||||
pagesCount,
|
||||
})
|
||||
})
|
||||
|
||||
exports.indexAllProperties = catchAsync(async (req, res, next) => {
|
||||
const { indexedCount } = await propertyService.indexAllProperties()
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
indexedCount,
|
||||
})
|
||||
})
|
||||
|
||||
exports.indexOneProperty = catchAsync(async (req, res, next) => {
|
||||
await propertyService.indexOneProperty(req.params.propertyId)
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
})
|
||||
})
|
||||
|
||||
exports.getAllProperties = catchAsync(async (req, res, next) => {
|
||||
const properties = await propertyService.getAllProperties()
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
results: properties.length,
|
||||
data: properties,
|
||||
})
|
||||
})
|
||||
|
||||
exports.createProperty = catchAsync(async (req, res, next) => {
|
||||
const property = await propertyService.createProperty(req.body)
|
||||
eventEmitter.emit('createProperty', property)
|
||||
|
||||
res.status(201).json({
|
||||
status: 'success',
|
||||
data: property,
|
||||
})
|
||||
})
|
||||
|
||||
exports.getProperty = catchAsync(async (req, res, next) => {
|
||||
const property = await propertyService.getProperty(req.params.propertyId)
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
data: property,
|
||||
})
|
||||
})
|
||||
|
||||
exports.updateProperty = catchAsync(async (req, res, next) => {
|
||||
const property = await propertyService.updateProperty(req.params.propertyId, req.body)
|
||||
await propertyService.indexAllProperties()
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
data: property,
|
||||
})
|
||||
})
|
||||
|
||||
exports.deleteProperty = catchAsync(async (req, res, next) => {
|
||||
await propertyService.deleteProperty(req.params.propertyId)
|
||||
// eventEmitter.emit('deleteProperty')
|
||||
|
||||
res.status(204).json({
|
||||
status: 'success',
|
||||
data: null,
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,130 @@
|
||||
const mongoose = require('mongoose')
|
||||
const ObjectID = mongoose.Schema.Types.ObjectId
|
||||
const AutoIncrement = require('mongoose-sequence')(mongoose)
|
||||
const { getMultipleSignedUrls } = require('../file/fileService')
|
||||
|
||||
const propertySchemaOptions = {
|
||||
discriminatorKey: 'propertyType',
|
||||
toJSON: { virtuals: true },
|
||||
toObject: { virtuals: true },
|
||||
timestamps: true,
|
||||
}
|
||||
|
||||
const propertySchema = new mongoose.Schema(
|
||||
{
|
||||
name: {
|
||||
type: String,
|
||||
required: false, // Auto-generated: ownerName + mainNumber/subNumber
|
||||
},
|
||||
category: {
|
||||
type: ObjectID,
|
||||
ref: 'Category',
|
||||
},
|
||||
description: String,
|
||||
relatedProjects: [String],
|
||||
location: {
|
||||
type: {
|
||||
type: String,
|
||||
enum: ['Point'],
|
||||
required: false,
|
||||
},
|
||||
coordinates: {
|
||||
type: [Number], // [longitude, latitude]
|
||||
required: false,
|
||||
},
|
||||
},
|
||||
documentUrls: {
|
||||
type: [String],
|
||||
default: [],
|
||||
},
|
||||
mainImageUrls: [String],
|
||||
nationalGeoCode: {
|
||||
type: String,
|
||||
required: true, // شناسه ملی جغرافیایی الزامی است
|
||||
},
|
||||
tags: [String],
|
||||
status: {
|
||||
type: ObjectID,
|
||||
ref: 'PropertyStatus',
|
||||
},
|
||||
isActive: {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
select: false,
|
||||
},
|
||||
// Title Deed General & Administrative (شناسه و اداره ثبت)
|
||||
uniqueId: String, // شناسه یکتا سند مالکیت (۱۸ رقمی)
|
||||
serialNumber: String, // شماره سریال چاپی سند
|
||||
provinceRegistry: String,
|
||||
localRegistryOffice: String,
|
||||
registrationDate: String, // تاریخ ثبت سند
|
||||
|
||||
// Owner Specifications (مشخصات مالک)
|
||||
ownerName: String,
|
||||
fatherName: String,
|
||||
idCardNumber: String,
|
||||
nationalId: String,
|
||||
issuePlace: String,
|
||||
birthDate: String,
|
||||
nationality: {
|
||||
type: String,
|
||||
default: 'ایران',
|
||||
},
|
||||
ownershipDocs: String,
|
||||
|
||||
// Property Specifications (مشخصات ملک)
|
||||
registrationPlate: String,
|
||||
mainNumber: String,
|
||||
subNumber: String,
|
||||
separatedFrom: String,
|
||||
plotNumber: String,
|
||||
registrationSection: String,
|
||||
district: String,
|
||||
blockNumber: String,
|
||||
sideDirection: String,
|
||||
floor: String,
|
||||
zoningType: String,
|
||||
specialStatus: String,
|
||||
documentType: String,
|
||||
address: String,
|
||||
postalCode: String,
|
||||
propertyBoundaries: String,
|
||||
restrictions: String,
|
||||
|
||||
// دانگ: سهم ملک از ۶ دانگ (۱ تا ۶)
|
||||
dong: {
|
||||
type: Number,
|
||||
min: 1,
|
||||
max: 6,
|
||||
default: 6,
|
||||
},
|
||||
|
||||
features: [
|
||||
{
|
||||
definition: {
|
||||
type: ObjectID,
|
||||
ref: 'Feature',
|
||||
required: true,
|
||||
},
|
||||
value: mongoose.Schema.Types.Mixed,
|
||||
},
|
||||
],
|
||||
},
|
||||
propertySchemaOptions
|
||||
)
|
||||
|
||||
propertySchema.plugin(AutoIncrement, { inc_field: 'propertyCode' })
|
||||
|
||||
propertySchema.methods.getDocumentsSignedUrls = function () {
|
||||
return getMultipleSignedUrls(this.documentUrls, 'property-documents')
|
||||
}
|
||||
|
||||
propertySchema.methods.getMainImagedSignedUrl = function () {
|
||||
return getMultipleSignedUrls(this.mainImageUrls, 'property-images')
|
||||
}
|
||||
|
||||
propertySchema.index({ location: '2dsphere' })
|
||||
|
||||
const Property = mongoose.model('Property', propertySchema)
|
||||
|
||||
module.exports = Property
|
||||
@@ -0,0 +1,26 @@
|
||||
const express = require('express')
|
||||
const propertyController = require('./propertyController')
|
||||
const perm = require('../../middlewares/permissionMiddleware')
|
||||
const loginCheck = require('../../middlewares/loginCheck')
|
||||
|
||||
const router = new express.Router()
|
||||
|
||||
router.use(loginCheck.loginProtect)
|
||||
|
||||
router.get('/admin/get-all', perm.requires('getallproperties', 'getallbelongings'), propertyController.getAllProperties)
|
||||
|
||||
router.post('/admin/create', perm.requires('createaproperty', 'createabelonging'), propertyController.createProperty)
|
||||
|
||||
router.post('/admin/index-all', perm.requires('indexproperties', 'indexbelongings'), propertyController.indexAllProperties)
|
||||
|
||||
router.post('/admin/index-one/:propertyId', perm.requires('indexproperties', 'indexbelongings'), propertyController.indexOneProperty)
|
||||
|
||||
router.get('/admin/search', perm.requires('searchproperties', 'searchbelongings'), propertyController.searchProperties)
|
||||
|
||||
router.get('/admin/get-one/:propertyId', perm.requires('getaproperty', 'getabelonging'), propertyController.getProperty)
|
||||
|
||||
router.put('/admin/update/:propertyId', perm.requires('updateaproperty', 'updateabelonging'), propertyController.updateProperty)
|
||||
|
||||
router.delete('/admin/delete/:propertyId', perm.requires('deleteaproperty', 'deleteabelonging'), propertyController.deleteProperty)
|
||||
|
||||
module.exports = router
|
||||
@@ -0,0 +1,202 @@
|
||||
const Property = require('./propertyModel')
|
||||
const Land = require('./landModel')
|
||||
const Building = require('./buildingModel')
|
||||
const AppError = require('../../globalErrorHandler/AppError')
|
||||
const { client } = require('../../setup/typesense')
|
||||
const TsApiFeatures = require('../../utils/TsApiFeatures')
|
||||
|
||||
const getAllProperties = async () => {
|
||||
return Property.find({}, null, null).populate('category').populate('status')
|
||||
}
|
||||
|
||||
const createProperty = async (data) => {
|
||||
if (data.propertyType === 'Land' || data.propertyType === 'زمین') {
|
||||
return Land.create(data)
|
||||
} else if (data.propertyType === 'Building' || data.propertyType === 'ساختمان') {
|
||||
return Building.create(data)
|
||||
}
|
||||
return Property.create(data)
|
||||
}
|
||||
|
||||
const getProperty = async (propertyId) => {
|
||||
let property = await Property.findById(propertyId, null, null).populate('category').populate('status')
|
||||
|
||||
if (!property) {
|
||||
throw new AppError('NoPropertyFound', 404, {})
|
||||
}
|
||||
|
||||
const documentUrls = await property.getDocumentsSignedUrls()
|
||||
const mainImageUrls = await property.getMainImagedSignedUrl()
|
||||
|
||||
property = JSON.parse(JSON.stringify(property))
|
||||
|
||||
property.signedDocumentUrls = documentUrls
|
||||
property.signedMainImageUrls = mainImageUrls
|
||||
|
||||
return property
|
||||
}
|
||||
|
||||
const updateProperty = async (propertyId, data) => {
|
||||
const property = await Property.findOneAndUpdate({ _id: propertyId }, data, { new: true })
|
||||
|
||||
if (!property) {
|
||||
throw new AppError('NoPropertyFound', 404, {})
|
||||
}
|
||||
|
||||
return property
|
||||
}
|
||||
|
||||
const deleteProperty = async (propertyId) => {
|
||||
const property = await Property.findByIdAndUpdate(propertyId, { isActive: false }, { new: true })
|
||||
|
||||
if (!property) {
|
||||
throw new AppError('NoPropertyFound', 404, {})
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
const ensureCollectionExists = async (forceRecreate = false) => {
|
||||
try {
|
||||
const collections = await client.collections().retrieve()
|
||||
const collectionExists = collections.some((collection) => collection.name === 'properties')
|
||||
|
||||
if (collectionExists && forceRecreate) {
|
||||
await client.collections('properties').delete()
|
||||
}
|
||||
|
||||
if (!collectionExists || forceRecreate) {
|
||||
const schema = getTypeSenseSchema()
|
||||
await client.collections().create(schema)
|
||||
console.log('Collection "properties" created successfully')
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error ensuring properties collection exists:', err)
|
||||
}
|
||||
}
|
||||
|
||||
const searchProperties = async (inputQuery) => {
|
||||
await ensureCollectionExists(false)
|
||||
inputQuery = updateInputQuery(inputQuery, {})
|
||||
|
||||
const tsFeatures = new TsApiFeatures(client, 'properties', inputQuery).filter().facet().sort().limitFields().paginate().search()
|
||||
|
||||
let { facets, items, totalCount, pagesCount } = await tsFeatures.execute()
|
||||
|
||||
return { facets, belongings: items, totalCount, pagesCount }
|
||||
}
|
||||
|
||||
const updateInputQuery = (inputQuery, extraQueries) => {
|
||||
for (const [key, value] of Object.entries(extraQueries)) {
|
||||
inputQuery[key] = value
|
||||
}
|
||||
|
||||
inputQuery.query_by = 'name,nationalGeoCode,tags,description,_id'
|
||||
|
||||
return inputQuery
|
||||
}
|
||||
|
||||
const indexAllProperties = async () => {
|
||||
const batchSize = 20
|
||||
const count = await Property.countDocuments({ isActive: true }, null)
|
||||
const rounds = Math.max(1, Math.ceil(count / batchSize))
|
||||
|
||||
await ensureCollectionExists(true)
|
||||
|
||||
for (let i = 1; i <= rounds; i++) {
|
||||
const properties = await Property.find({ isActive: true }, null, null)
|
||||
.populate('category')
|
||||
.skip((i - 1) * batchSize)
|
||||
.limit(batchSize)
|
||||
|
||||
if (properties.length === 0) break
|
||||
|
||||
let documents = []
|
||||
|
||||
for (const property of properties) {
|
||||
const combinedTags = Array.isArray(property.tags) ? property.tags.join(' ') : (property.tags || '')
|
||||
|
||||
const data = {
|
||||
_id: property._id.toString(),
|
||||
isActive: property.isActive,
|
||||
name: property.name || '',
|
||||
category: property.category?.englishName || '',
|
||||
nativeCategory: property.category?.nativeName || '',
|
||||
imageUrl: property.mainImageUrls?.[0] || 'https://cloud.mbmanager.ir/images/item-no-image.png',
|
||||
documents: property.documentUrls || [],
|
||||
description: property.description || '',
|
||||
nationalGeoCode: property.nationalGeoCode || '',
|
||||
tags: combinedTags,
|
||||
coordinates: property.location?.coordinates || [0, 0],
|
||||
createdAt: Math.floor(new Date(property.createdAt || Date.now()).getTime() / 1000),
|
||||
id: property.propertyCode ? property.propertyCode.toString() : property._id.toString(),
|
||||
}
|
||||
|
||||
documents.push(data)
|
||||
}
|
||||
|
||||
if (documents.length > 0) {
|
||||
await client.collections('properties').documents().import(documents, { action: 'emplace' })
|
||||
}
|
||||
}
|
||||
|
||||
return { totalCount: count }
|
||||
}
|
||||
|
||||
const indexOneProperty = async (propertyId) => {
|
||||
await ensureCollectionExists(false)
|
||||
const property = await getProperty(propertyId)
|
||||
|
||||
console.log(`Property ${property._id} indexing`)
|
||||
|
||||
const combinedTags = Array.isArray(property.tags) ? property.tags.join(' ') : (property.tags || '')
|
||||
|
||||
const data = {
|
||||
_id: property._id.toString(),
|
||||
isActive: property.isActive,
|
||||
name: property.name || '',
|
||||
category: property.category?.englishName || '',
|
||||
nativeCategory: property.category?.nativeName || '',
|
||||
imageUrl: property.mainImageUrls?.[0] || '',
|
||||
documents: property.documentUrls || [],
|
||||
description: property.description || '',
|
||||
nationalGeoCode: property.nationalGeoCode || '',
|
||||
tags: combinedTags,
|
||||
coordinates: property.location?.coordinates || [0, 0],
|
||||
createdAt: Math.floor(new Date(property.createdAt || Date.now()).getTime() / 1000),
|
||||
id: property.propertyCode ? property.propertyCode.toString() : property._id.toString(),
|
||||
}
|
||||
|
||||
await client.collections('properties').documents().upsert(data)
|
||||
}
|
||||
|
||||
const getTypeSenseSchema = () => {
|
||||
return {
|
||||
name: 'properties',
|
||||
enable_nested_fields: true,
|
||||
fields: [
|
||||
{ name: '_id', type: 'string', facet: false, infix: false },
|
||||
{ name: 'name', type: 'string', facet: false, infix: true },
|
||||
{ name: 'category', type: 'string', facet: true, infix: true },
|
||||
{ name: 'nativeCategory', type: 'string', facet: false, infix: true },
|
||||
{ name: 'description', type: 'string', facet: false },
|
||||
{ name: 'nationalGeoCode', type: 'string', facet: false, infix: true },
|
||||
{ name: 'tags', type: 'string', facet: false, infix: true },
|
||||
{ name: 'coordinates', type: 'geopoint' },
|
||||
{ name: 'createdAt', type: 'int64', facet: false },
|
||||
{ name: 'imageUrl', type: 'string', facet: false, infix: true },
|
||||
],
|
||||
default_sorting_field: 'createdAt',
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
updateProperty,
|
||||
indexAllProperties,
|
||||
getProperty,
|
||||
getAllProperties,
|
||||
createProperty,
|
||||
deleteProperty,
|
||||
searchProperties,
|
||||
indexOneProperty,
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
const catchAsync = require('../../globalErrorHandler/catchAsync')
|
||||
const propertyStatusService = require('./propertyStatusService')
|
||||
|
||||
exports.getAllStatuses = catchAsync(async (req, res, next) => {
|
||||
const statuses = await propertyStatusService.getAllStatuses()
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
results: statuses.length,
|
||||
data: statuses,
|
||||
})
|
||||
})
|
||||
|
||||
exports.getStatus = catchAsync(async (req, res, next) => {
|
||||
const status = await propertyStatusService.getStatus(req.params.statusId)
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
data: status,
|
||||
})
|
||||
})
|
||||
|
||||
exports.createStatus = catchAsync(async (req, res, next) => {
|
||||
const status = await propertyStatusService.createStatus(req.body)
|
||||
|
||||
res.status(201).json({
|
||||
status: 'success',
|
||||
data: status,
|
||||
})
|
||||
})
|
||||
|
||||
exports.updateStatus = catchAsync(async (req, res, next) => {
|
||||
const status = await propertyStatusService.updateStatus(req.params.statusId, req.body)
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
data: status,
|
||||
})
|
||||
})
|
||||
|
||||
exports.deleteStatus = catchAsync(async (req, res, next) => {
|
||||
await propertyStatusService.deleteStatus(req.params.statusId)
|
||||
|
||||
res.status(204).json({
|
||||
status: 'success',
|
||||
data: null,
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,28 @@
|
||||
const mongoose = require('mongoose')
|
||||
|
||||
const propertyStatusSchema = new mongoose.Schema(
|
||||
{
|
||||
nativeName: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
englishName: {
|
||||
type: String,
|
||||
required: true,
|
||||
unique: true,
|
||||
},
|
||||
// Color token for UI badge (success/info/warn/danger/secondary/contrast)
|
||||
color: {
|
||||
type: String,
|
||||
default: 'secondary',
|
||||
},
|
||||
},
|
||||
{
|
||||
toJSON: { virtuals: true },
|
||||
toObject: { virtuals: true },
|
||||
timestamps: true,
|
||||
}
|
||||
)
|
||||
|
||||
const PropertyStatus = mongoose.model('PropertyStatus', propertyStatusSchema)
|
||||
module.exports = PropertyStatus
|
||||
@@ -0,0 +1,20 @@
|
||||
const express = require('express')
|
||||
const propertyStatusController = require('./propertyStatusController')
|
||||
const perm = require('../../middlewares/permissionMiddleware')
|
||||
const loginCheck = require('../../middlewares/loginCheck')
|
||||
|
||||
const router = new express.Router()
|
||||
|
||||
router.use(loginCheck.loginProtect)
|
||||
|
||||
router.get('/admin/get-all', perm.requires('getallpropertystatuses', 'getallbelongingstatuses'), propertyStatusController.getAllStatuses)
|
||||
|
||||
router.get('/admin/get-one/:statusId', perm.requires('getapropertystatus', 'getabelongingstatus'), propertyStatusController.getStatus)
|
||||
|
||||
router.post('/admin/create', perm.requires('createapropertystatus', 'createabelongingstatus'), propertyStatusController.createStatus)
|
||||
|
||||
router.put('/admin/update/:statusId', perm.requires('updateapropertystatus', 'updateabelongingstatus'), propertyStatusController.updateStatus)
|
||||
|
||||
router.delete('/admin/delete/:statusId', perm.requires('deleteapropertystatus', 'deleteabelongingstatus'), propertyStatusController.deleteStatus)
|
||||
|
||||
module.exports = router
|
||||
@@ -0,0 +1,32 @@
|
||||
const PropertyStatus = require('./propertyStatusModel')
|
||||
const chalk = require('chalk')
|
||||
|
||||
const runSeeder = async () => {
|
||||
const statuses = [
|
||||
// ── اصلی ────────────────────────────────────────────────────────────
|
||||
{ nativeName: 'موجود', englishName: 'available', color: 'success' },
|
||||
{ nativeName: 'فروخته شده', englishName: 'sold', color: 'contrast' },
|
||||
{ nativeName: 'قولنامه', englishName: 'reserved', color: 'warn' },
|
||||
{ nativeName: 'بلاک', englishName: 'blocked', color: 'danger' },
|
||||
|
||||
// ── تکمیلی ──────────────────────────────────────────────────────────
|
||||
{ nativeName: 'در حال بررسی', englishName: 'in_review', color: 'info' },
|
||||
{ nativeName: 'رهن', englishName: 'mortgaged', color: 'warn' },
|
||||
{ nativeName: 'وراثتی', englishName: 'inherited', color: 'secondary' },
|
||||
{ nativeName: 'مشاع', englishName: 'joint', color: 'secondary' },
|
||||
{ nativeName: 'توقیف', englishName: 'seized', color: 'danger' },
|
||||
{ nativeName: 'در دست ساخت', englishName: 'under_construction', color: 'info' },
|
||||
]
|
||||
|
||||
await PropertyStatus.deleteMany({})
|
||||
console.log(chalk.red('Deleted all property status records.'))
|
||||
|
||||
await PropertyStatus.create(statuses)
|
||||
console.log(
|
||||
chalk.green.bold(
|
||||
`PROPERTY STATUS: Created ${statuses.length} status(es)`
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
module.exports = { runSeeder }
|
||||
@@ -0,0 +1,42 @@
|
||||
const PropertyStatus = require('./propertyStatusModel')
|
||||
const AppError = require('../../globalErrorHandler/AppError')
|
||||
|
||||
const getAllStatuses = async () => {
|
||||
return PropertyStatus.find({})
|
||||
}
|
||||
|
||||
const getStatus = async (statusId) => {
|
||||
const status = await PropertyStatus.findById(statusId)
|
||||
|
||||
if (!status) {
|
||||
throw new AppError('NoPropertyStatusFound', 404, {})
|
||||
}
|
||||
|
||||
return status
|
||||
}
|
||||
|
||||
const createStatus = async (data) => {
|
||||
return PropertyStatus.create(data)
|
||||
}
|
||||
|
||||
const updateStatus = async (statusId, data) => {
|
||||
const status = await PropertyStatus.findByIdAndUpdate(statusId, data, { new: true, runValidators: true })
|
||||
|
||||
if (!status) {
|
||||
throw new AppError('NoPropertyStatusFound', 404, {})
|
||||
}
|
||||
|
||||
return status
|
||||
}
|
||||
|
||||
const deleteStatus = async (statusId) => {
|
||||
const status = await PropertyStatus.findByIdAndDelete(statusId)
|
||||
|
||||
if (!status) {
|
||||
throw new AppError('NoPropertyStatusFound', 404, {})
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
module.exports = { getAllStatuses, getStatus, createStatus, updateStatus, deleteStatus }
|
||||
@@ -34,10 +34,9 @@ const transactionSchema = new mongoose.Schema(
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
belongingId: {
|
||||
propertyId: {
|
||||
type: ObjectID,
|
||||
ref: 'Belonging',
|
||||
required: true,
|
||||
ref: 'Property',
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -47,14 +46,11 @@ const transactionSchema = new mongoose.Schema(
|
||||
}
|
||||
)
|
||||
|
||||
// Add individual indexes for frequently queried fields
|
||||
transactionSchema.index({ type: 1 })
|
||||
transactionSchema.index({ status: 1 })
|
||||
transactionSchema.index({ value: 1 })
|
||||
|
||||
// Add compound indexes for common query patterns in aggregation
|
||||
transactionSchema.index({ belongingId: 1, status: 1 })
|
||||
transactionSchema.index({ belongingId: 1, type: 1, status: 1 })
|
||||
transactionSchema.index({ propertyId: 1, status: 1 })
|
||||
transactionSchema.index({ propertyId: 1, type: 1, status: 1 })
|
||||
|
||||
const Transaction = mongoose.model('Transaction', transactionSchema)
|
||||
module.exports = Transaction
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
const Transaction = require('./transactionModel')
|
||||
const Belonging = require('../belonging/belongingModel')
|
||||
const Property = require('../property/propertyModel')
|
||||
const AppError = require('../../globalErrorHandler/AppError')
|
||||
const mongoose = require('mongoose')
|
||||
const ObjectID = mongoose.Schema.Types.ObjectId
|
||||
@@ -17,17 +17,16 @@ const filterObj = (obj, ...allowedFields) => {
|
||||
|
||||
const createTransaction = async (data) => {
|
||||
if (data.type == 'withdraw') {
|
||||
// Aggregate transactions to calculate inventory
|
||||
const result = await Transaction.aggregate([
|
||||
{
|
||||
$match: {
|
||||
belongingId: ObjectID,
|
||||
propertyId: ObjectID,
|
||||
status: 'finished',
|
||||
},
|
||||
},
|
||||
{
|
||||
$group: {
|
||||
_id: '$belongingId',
|
||||
_id: '$propertyId',
|
||||
totalInventory: {
|
||||
$sum: '$value',
|
||||
},
|
||||
@@ -35,7 +34,7 @@ const createTransaction = async (data) => {
|
||||
},
|
||||
])
|
||||
|
||||
if (result[0].totalInventory <= 0) throw new AppError('Invalid Transaction', 404, {})
|
||||
if (result[0]?.totalInventory <= 0) throw new AppError('Invalid Transaction', 404, {})
|
||||
}
|
||||
|
||||
return Transaction.create({
|
||||
@@ -46,7 +45,7 @@ const createTransaction = async (data) => {
|
||||
date: data.Date,
|
||||
description: data.description,
|
||||
userId: data.userId,
|
||||
belongingId: data.belongingId,
|
||||
propertyId: data.propertyId || data.belongingId,
|
||||
userName: data.userName,
|
||||
})
|
||||
}
|
||||
@@ -55,28 +54,26 @@ const getUserTransaction = async (userId) => {
|
||||
return Transaction.find({ userId }, null, null)
|
||||
}
|
||||
|
||||
const getTransactionByBelongingId = async (belongingId) => {
|
||||
return Transaction.find({ belongingId }, null, null)
|
||||
const getTransactionByBelongingId = async (propertyId) => {
|
||||
return Transaction.find({ propertyId }, null, null)
|
||||
}
|
||||
|
||||
const getBelongingInventory = async (belongingId) => {
|
||||
const belonging = await Belonging.findById(belongingId, null, null)
|
||||
const getBelongingInventory = async (propertyId) => {
|
||||
const property = await Property.findById(propertyId, null, null)
|
||||
|
||||
if (!belonging) {
|
||||
throw new AppError('NoBelongingFound', 404, {})
|
||||
if (!property) {
|
||||
throw new AppError('NoPropertyFound', 404, {})
|
||||
}
|
||||
|
||||
// Simplified aggregation to calculate inventory metrics
|
||||
const result = await Transaction.aggregate([
|
||||
{
|
||||
$match: {
|
||||
belongingId: belonging._id,
|
||||
propertyId: property._id,
|
||||
$or: [{ status: 'finished' }, { status: 'pending' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
$facet: {
|
||||
// Calculate total inventory from finished transactions
|
||||
finishedInventory: [
|
||||
{ $match: { status: 'finished' } },
|
||||
{
|
||||
@@ -86,7 +83,6 @@ const getBelongingInventory = async (belongingId) => {
|
||||
},
|
||||
},
|
||||
],
|
||||
// Calculate pending deposits
|
||||
pendingDepositsInventory: [
|
||||
{
|
||||
$match: {
|
||||
@@ -101,7 +97,6 @@ const getBelongingInventory = async (belongingId) => {
|
||||
},
|
||||
},
|
||||
],
|
||||
// Calculate pending withdrawals
|
||||
pendingWithdrawsInventory: [
|
||||
{
|
||||
$match: {
|
||||
@@ -119,7 +114,6 @@ const getBelongingInventory = async (belongingId) => {
|
||||
},
|
||||
},
|
||||
{
|
||||
// Restructure the output to get only the values
|
||||
$project: {
|
||||
finishedInventory: { $ifNull: [{ $arrayElemAt: ['$finishedInventory.total', 0] }, 0] },
|
||||
pendingDepositsInventory: { $ifNull: [{ $arrayElemAt: ['$pendingDepositsInventory.total', 0] }, 0] },
|
||||
@@ -152,21 +146,27 @@ const deleteTransaction = async (transactionId) => {
|
||||
return null
|
||||
}
|
||||
|
||||
const ensureCollectionExists = async () => {
|
||||
const collections = await client.collections().retrieve()
|
||||
const collectionExists = collections.some((collection) => collection.name === 'transactions')
|
||||
const ensureCollectionExists = async (forceRecreate = false) => {
|
||||
try {
|
||||
const collections = await client.collections().retrieve()
|
||||
const collectionExists = collections.some((collection) => collection.name === 'transactions')
|
||||
|
||||
if (collectionExists) {
|
||||
await client.collections('transactions').delete()
|
||||
if (collectionExists && forceRecreate) {
|
||||
await client.collections('transactions').delete()
|
||||
}
|
||||
|
||||
if (!collectionExists || forceRecreate) {
|
||||
const schema = getTypeSenseSchema()
|
||||
await client.collections().create(schema)
|
||||
console.log('Collection "transactions" created successfully')
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error ensuring transactions collection exists:', err)
|
||||
}
|
||||
|
||||
const schema = getTypeSenseSchema()
|
||||
|
||||
await client.collections().create(schema)
|
||||
console.log('Collection "transactions" created successfully')
|
||||
}
|
||||
|
||||
const searchTransactions = async (inputQuery) => {
|
||||
await ensureCollectionExists(false)
|
||||
inputQuery = updateInputQuery(inputQuery, {})
|
||||
|
||||
const tsFeatures = new TsApiFeatures(client, 'transactions', inputQuery).filter().facet().sort().limitFields().paginate().search()
|
||||
@@ -176,7 +176,7 @@ const searchTransactions = async (inputQuery) => {
|
||||
return { facets, transactions: items, totalCount, pagesCount }
|
||||
}
|
||||
|
||||
const updateInputQuery = (inputQuery, extraQueries, features) => {
|
||||
const updateInputQuery = (inputQuery, extraQueries) => {
|
||||
for (const [key, value] of Object.entries(extraQueries)) {
|
||||
inputQuery[key] = value
|
||||
}
|
||||
@@ -189,38 +189,40 @@ const updateInputQuery = (inputQuery, extraQueries, features) => {
|
||||
const indexAllTransactions = async () => {
|
||||
const batchSize = 20
|
||||
const count = await Transaction.countDocuments({}, null)
|
||||
const rounds = Math.ceil(count / batchSize)
|
||||
const rounds = Math.max(1, Math.ceil(count / batchSize))
|
||||
|
||||
await ensureCollectionExists()
|
||||
await ensureCollectionExists(true)
|
||||
|
||||
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)
|
||||
.populate('belongingId')
|
||||
.populate('propertyId')
|
||||
|
||||
if (transactions.length === 0) break
|
||||
|
||||
let documents = []
|
||||
|
||||
for (const transaction of transactions) {
|
||||
const data = {
|
||||
_id: transaction._id,
|
||||
type: transaction.type,
|
||||
status: transaction.status,
|
||||
_id: transaction._id.toString(),
|
||||
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
|
||||
belongingName: transaction.belongingId.name,
|
||||
belongingId: transaction.belongingId._id,
|
||||
value: transaction.value || 0,
|
||||
description: transaction.description || '',
|
||||
createdAt: Math.floor(new Date(transaction.createdAt || Date.now()).getTime() / 1000),
|
||||
belongingName: transaction.propertyId?.name || '',
|
||||
belongingId: transaction.propertyId?._id ? transaction.propertyId._id.toString() : '',
|
||||
userName: transaction.userName || '',
|
||||
}
|
||||
|
||||
documents.push(data)
|
||||
}
|
||||
|
||||
await client.collections('transactions').documents().import(documents, { action: 'emplace' })
|
||||
if (documents.length > 0) {
|
||||
await client.collections('transactions').documents().import(documents, { action: 'emplace' })
|
||||
}
|
||||
}
|
||||
|
||||
return { totalCount: count }
|
||||
|
||||
Reference in New Issue
Block a user