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:
@@ -0,0 +1,83 @@
|
||||
const mongoose = require('mongoose')
|
||||
const ObjectID = mongoose.Schema.Types.ObjectId
|
||||
const AutoIncrement = require('mongoose-sequence')(mongoose)
|
||||
const { getMultipleSignedUrls, getSignedUrl } = require('../file/fileService')
|
||||
|
||||
const belongingSchema = new mongoose.Schema(
|
||||
{
|
||||
name: {
|
||||
type: String,
|
||||
required: true,
|
||||
unique: true,
|
||||
},
|
||||
// belongingCode: {
|
||||
// type: Number,
|
||||
// unique: true,
|
||||
// },
|
||||
category: {
|
||||
type: ObjectID,
|
||||
ref: 'Category',
|
||||
},
|
||||
unit: {
|
||||
type: String,
|
||||
},
|
||||
description: String,
|
||||
relatedProjects: [String],
|
||||
location: {
|
||||
type: {
|
||||
type: String,
|
||||
enum: ['Point'], // GeoJSON type
|
||||
required: false,
|
||||
},
|
||||
coordinates: {
|
||||
type: [Number], // Array of numbers: [longitude, latitude]
|
||||
required: false,
|
||||
},
|
||||
},
|
||||
documentUrls: [String],
|
||||
mainImageUrls: [String],
|
||||
nationalGeoCode: String,
|
||||
tags: [String],
|
||||
status: {
|
||||
type: ObjectID,
|
||||
ref: 'BelongingStatus',
|
||||
},
|
||||
isActive: {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
select: false,
|
||||
},
|
||||
features: [
|
||||
{
|
||||
definition: {
|
||||
type: ObjectID,
|
||||
ref: 'Feature',
|
||||
required: true,
|
||||
},
|
||||
value: mongoose.Schema.Types.Mixed,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
toJSON: { virtuals: true },
|
||||
toObject: { virtuals: true },
|
||||
timestamps: true,
|
||||
}
|
||||
)
|
||||
|
||||
belongingSchema.plugin(AutoIncrement, { inc_field: 'belongingCode' })
|
||||
|
||||
belongingSchema.methods.getDocumentsSignedUrls = function () {
|
||||
return getMultipleSignedUrls(this.documentUrls, 'belonging-documents')
|
||||
}
|
||||
|
||||
belongingSchema.methods.getMainImagedSignedUrl = function () {
|
||||
return getMultipleSignedUrls(this.mainImageUrls, 'belonging-images')
|
||||
}
|
||||
|
||||
belongingSchema.index({ location: '2dsphere' }) // Enable geospatial queries
|
||||
|
||||
// belongingSchema.plugin(AutoIncrement, { inc_field: 'numId' })
|
||||
|
||||
const Belonging = mongoose.model('Belonging', belongingSchema)
|
||||
module.exports = Belonging
|
||||
@@ -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,
|
||||
}
|
||||
Reference in New Issue
Block a user