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,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