Files
mbmanager-api/components/property/propertyService.js
T
2026-08-19 04:58:14 +03:30

218 lines
7.9 KiB
JavaScript

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 { moveFromTempToMain } = require('../file/fileService')
const getAllProperties = async () => {
return Property.find({}, null, null).populate('category').populate('status')
}
const createProperty = async (data) => {
if (data.mainImageUrls && Array.isArray(data.mainImageUrls) && data.mainImageUrls.length > 0) {
data.mainImageUrls = await moveFromTempToMain(data.mainImageUrls, 'properties')
}
if (data.documentUrls && Array.isArray(data.documentUrls) && data.documentUrls.length > 0) {
data.documentUrls = await moveFromTempToMain(data.documentUrls, 'documents')
}
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) => {
if (data.mainImageUrls && Array.isArray(data.mainImageUrls) && data.mainImageUrls.length > 0) {
data.mainImageUrls = await moveFromTempToMain(data.mainImageUrls, 'properties')
}
if (data.documentUrls && Array.isArray(data.documentUrls) && data.documentUrls.length > 0) {
data.documentUrls = await moveFromTempToMain(data.documentUrls, 'documents')
}
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,
}