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:
2026-08-11 20:35:47 +03:30
parent a9432b96c0
commit ca911b97a0
35 changed files with 1504 additions and 1223 deletions
@@ -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,
})
})
-26
View File
@@ -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
-182
View File
@@ -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()
})
}
+1
View File
@@ -6,6 +6,7 @@ const runSeeder = async () => {
{ nativeName: 'ساختمان', englishName: 'Building' },
{ nativeName: 'زمین', englishName: 'Lot' },
{ nativeName: 'کالا', englishName: 'Product' },
{ nativeName: 'خودرو', englishName: 'Car' },
]
await Category.deleteMany({})
+42
View File
@@ -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
+1 -1
View File
@@ -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: {
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,
+42
View File
@@ -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
})
}
+30
View File
@@ -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
+81
View File
@@ -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,
})
})
+130
View File
@@ -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
+26
View File
@@ -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
+202
View File
@@ -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 }
+4 -8
View File
@@ -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
+37 -35
View File
@@ -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 ensureCollectionExists = async (forceRecreate = false) => {
try {
const collections = await client.collections().retrieve()
const collectionExists = collections.some((collection) => collection.name === 'transactions')
if (collectionExists) {
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 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,39 +189,41 @@ 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)
}
if (documents.length > 0) {
await client.collections('transactions').documents().import(documents, { action: 'emplace' })
}
}
return { totalCount: count }
}
+11 -9
View File
@@ -1,15 +1,17 @@
MONGODB_URL=mongodb://root:yBi0FXMb1rWNhFxu@services.irn12.chabokan.net:58178/my-app?authSource=admin
MONGODB_URL=mongodb://admin:*135792468*@localhost:27018/marbm?authSource=admin
NODE_ENV=development
PORT=3000
JWT_SECRET=Y@RJ$WT!@K0NS@MPL!
REDIS_URL=redis://:GFis6zU4DXW9Q7NQ@services.irn12.chabokan.net:19794/0
REDIS_URL=redis://:135792468@localhost:6380/0
LOGIN_ATTEMPT_LIMIT=900
SUPER_ADMIN_ROLE_ID=66a2da5b9b989a8909948848
TYPE_SENSE_URL=bm-typesense.chbk.app
TYPE_SENSE_API_KEY=rHV4vZePdfBYFC9q
AWS_ENDPOINT=bm-minio-2.chbk.app
AWS_URL=https://bm-minio-2.chbk.app
AWS_ACCESS_KEY=lwcAHMbCea4jeKMtj6SOjMtmETY93rBb
AWS_SECRET_KEY=xXKrceoCV3Wx35d0JmULgNvHJ0UlTQnO
AWS_REGION=default
TYPE_SENSE_URL=localhost:8109
TYPE_SENSE_PROTOCOL=http
TYPE_SENSE_API_KEY=vYQq7pTgl6ACoRy
AWS_ENDPOINT=localhost
AWS_PORT=9002
AWS_USE_SSL=false
AWS_ACCESS_KEY=admin
AWS_SECRET_KEY=135792468
AWS_REGION=us-east-1
API_URL=http://localhost:3000
-56
View File
@@ -1,56 +0,0 @@
services:
# api-server:
# build: ./
# ports:
# - 3000:4000
# environment:
# - MONGODB_URL=mongodb://admin:*135792468*@bm_mongo:27017/marbm?authSource=admin
# - NODE_ENV=development
# - PORT=3000
# - REDIS_URL=redis://:135792468@bm_redis:6379/0
bm_minio:
image: minio/minio
ports:
- 9000:9000
- 9001:9001
environment:
MINIO_ROOT_USER: admin
MINIO_ROOT_PASSWORD: 135792468
volumes:
- bm_minio:/upload/
command: server /data --console-address ":9001"
bm_mongo:
image: mongo:8.0
ports:
- 27018:27017
environment:
- MONGO_INITDB_ROOT_USERNAME=admin
- MONGO_INITDB_ROOT_PASSWORD=*135792468*
- MONGO_INITDB_DATABASE=test
volumes:
- bm_mongo:/data/db
bm_redis:
image: redis
command: redis-server --save 20 1 --loglevel warning --requirepass 135792468
volumes:
- bm_redis:/data/
ports:
- 6379:6379
bm_typesense:
image: typesense/typesense:27.1
command: ./typesense-server
ports:
- '8108:8108'
environment:
TYPESENSE_API_KEY: vYQq7pTgl6ACoRy
TYPESENSE_DATA_DIR: /data
volumes:
- bm_typesense:/data
volumes:
bm_mongo:
bm_redis:
bm_minio:
bm_typesense:
+4 -8
View File
@@ -1,23 +1,19 @@
// events/index.js
const { eventEmitter } = require('./eventEmitter')
const createBelonging = require('../components/belonging/events/createBelonging')
const deleteBelonging = require('../components/belonging/events/deleteBelonging')
const createProperty = require('../components/property/events/createProperty')
const deleteProperty = require('../components/property/events/deleteProperty')
const registerEventHandlers = () => {
// Register all event handlers
createBelonging(eventEmitter)
deleteBelonging(eventEmitter)
createProperty(eventEmitter)
deleteProperty(eventEmitter)
// Add additional error monitoring if needed
eventEmitter.on('error', (error) => {
// You can add additional error handling here
// For example, sending to a monitoring service
console.error('Event handler error:', error)
})
// Log when events are registered (optional)
console.log('Event handlers registered successfully')
}
// Helper function to safely emit events (can be used in other files)
const safeEmit = async (eventName, ...args) => {
try {
return eventEmitter.emit(eventName, ...args)
+15 -25
View File
@@ -1,42 +1,32 @@
const mongoose = require('mongoose')
const port = process.env.PORT || 3000
const env = process.env.NODE_ENV || 'development'
const redisClient = require('../setup/redis')
const seederRunner = require('./seederRunner')
const chalk = require('chalk')
module.exports = (app) => {
let connectionString
if (env === 'development') {
connectionString = process.env.MONGODB_URL
} else if (env === 'test') {
connectionString = process.env.MONGODB_URL
} else if (env === 'production') {
connectionString = process.env.MONGODB_URL
}
console.log(env)
let connectionString = process.env.MONGODB_URL
console.log(`Environment: ${env}`)
mongoose
.connect(connectionString, {})
.then(function () {
.then(async function () {
console.log('MongoDB Database Connected')
redisClient.connect().then((r) => {
await redisClient.connect().catch((err) => console.log('Redis connect warning:', err.message))
console.log('Redis connection Established')
app.listen(port, function () {
console.log('Server Started On Port ' + port)
console.log(
chalk.red.bold(
'-------- Running Seeders ---------'
)
)
seederRunner.run().then((r) => {
console.log(chalk.blue.bold('Seeding is done.'))
console.log(chalk.red.bold('-------- Running Seeders ---------'))
try {
await seederRunner.run()
console.log(chalk.blue.bold('Seeding and indexing completed successfully.'))
} catch (err) {
console.error('Seeding error:', err)
} finally {
process.exit(0)
})
})
})
}
})
.catch(function (err) {
console.log(err)
console.error('Database connection error:', err)
process.exit(1)
})
}
+9
View File
@@ -1,8 +1,17 @@
const userSeeder = require('../components/user/userSeeder')
const categorySeeder = require('../components/category/categorySeeder')
const roleSeeder = require('../components/role/roleSeeder')
const featureSeeder = require('../components/feature/featureSeeder')
const propertyStatusSeeder = require('../components/propertyStatus/propertyStatusSeeder')
const propertyService = require('../components/property/propertyService')
const transactionService = require('../components/transaction/transactionService')
module.exports.run = async () => {
await userSeeder.runSeeder()
await categorySeeder.runSeeder()
await roleSeeder.runSeeder()
await featureSeeder.runSeeder()
await propertyStatusSeeder.runSeeder()
await propertyService.indexAllProperties()
await transactionService.indexAllTransactions()
}
+8 -3
View File
@@ -1,11 +1,16 @@
const TypeSense = require('typesense')
const tsUrlParts = (process.env.TYPE_SENSE_URL || 'localhost:8108').split(':')
const host = tsUrlParts[0] || 'localhost'
const port = tsUrlParts[1] || process.env.TYPE_SENSE_PORT || '8108'
const protocol = process.env.TYPE_SENSE_PROTOCOL || 'http'
let client = new TypeSense.Client({
nodes: [
{
host: process.env.TYPE_SENSE_URL,
port: '443',
protocol: 'https',
host: host,
port: port,
protocol: protocol,
},
],
apiKey: process.env.TYPE_SENSE_API_KEY,
+2 -1
View File
@@ -166,8 +166,9 @@ class TsApiFeatures {
per_page: this.queryOptions.per_page,
})
})
const tsProtocol = process.env.TYPE_SENSE_PROTOCOL || 'http'
const config = {
url: 'https://' + process.env.TYPE_SENSE_URL + '/multi_search?x-typesense-api-key=' + process.env.TYPE_SENSE_API_KEY,
url: tsProtocol + '://' + process.env.TYPE_SENSE_URL + '/multi_search?x-typesense-api-key=' + process.env.TYPE_SENSE_API_KEY,
method: 'POST',
data: {
searches,
+8 -1
View File
@@ -4,11 +4,18 @@ const fs = require('fs')
// Upload File to s3 bucket
exports.uploadObject = async (file, bucketName) => {
const bucketExists = await minioClient.bucketExists(bucketName).catch(() => false)
if (!bucketExists) {
await minioClient.makeBucket(bucketName, process.env.AWS_REGION || 'us-east-1')
}
const fileStream = fs.createReadStream(file.path)
const uploadedFile = await minioClient.putObject(bucketName, `${file.filename}-${file.originalName}`, fileStream)
uploadedFile.fileURL = 'https://' + process.env.AWS_ENDPOINT + '/' + bucketName + '/' + file.filename + '-' + file.originalName
const protocol = process.env.AWS_USE_SSL === 'true' ? 'https://' : 'http://'
const hostPort = process.env.AWS_PORT ? `${process.env.AWS_ENDPOINT}:${process.env.AWS_PORT}` : process.env.AWS_ENDPOINT
uploadedFile.fileURL = protocol + hostPort + '/' + bucketName + '/' + file.filename + '-' + file.originalName
uploadedFile.fileName = file.filename + '-' + file.originalName
+12 -18
View File
@@ -1,30 +1,24 @@
const Minio = require('minio')
const endPoint = process.env.AWS_ENDPOINT
const endPoint = process.env.AWS_ENDPOINT || 'localhost'
const accessKey = process.env.AWS_ACCESS_KEY
const secretKey = process.env.AWS_SECRET_KEY
const region = process.env.AWS_REGION
const port = parseInt(process.env.AWS_PORT)
const region = process.env.AWS_REGION || 'us-east-1'
const port = parseInt(process.env.AWS_PORT) || 9000
const useSSL = process.env.AWS_USE_SSL === 'true'
let client
if (process.env.NODE_ENV === 'test') {
client = new Minio.Client({
const clientOptions = {
endPoint,
useSSL: true,
accessKey,
port,
secretKey,
region,
})
} else {
client = new Minio.Client({
endPoint,
useSSL: true,
useSSL,
accessKey,
secretKey,
region,
})
}
if (port) {
clientOptions.port = port
}
const client = new Minio.Client(clientOptions)
module.exports = client