Compare commits
27
Commits
1bcff0e73a
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
898ff6cf69 | ||
|
|
d140de86a3 | ||
|
|
576ccf5421 | ||
|
|
9b88b342ad | ||
|
|
e63ac1ddf4 | ||
|
|
30ea3aed84 | ||
|
|
fb4a98f83c | ||
|
|
7d70a64cd6 | ||
|
|
95c0532374 | ||
|
|
284594c782 | ||
|
|
8bdd5af719 | ||
|
|
982b9e759f | ||
|
|
acb2e5d623 | ||
|
|
3829851566 | ||
|
|
31ebafb53c | ||
|
|
dd611df7e5 | ||
|
|
61c9012912 | ||
|
|
2b94fdb034 | ||
|
|
86655f2b69 | ||
|
|
1618eae69f | ||
|
|
ca911b97a0 | ||
|
|
a9432b96c0 | ||
|
|
0fe799e008 | ||
|
|
de60d4f163 | ||
|
|
98044a18f2 | ||
|
|
a2f157611d | ||
|
|
39e909ee47 |
@@ -0,0 +1,14 @@
|
||||
node_modules
|
||||
npm-debug.log
|
||||
logs
|
||||
./logs
|
||||
.git
|
||||
.gitignore
|
||||
.github
|
||||
.idea
|
||||
.vscode
|
||||
.env
|
||||
./config/.env
|
||||
Dockerfile*
|
||||
.dockerignore
|
||||
README.md
|
||||
+27
-11
@@ -1,20 +1,36 @@
|
||||
# Use the official Node.js image as a base
|
||||
FROM node:18
|
||||
# Stage 1: Build & install production dependencies
|
||||
FROM node:20-alpine AS dependencies
|
||||
|
||||
# Set the working directory in the container
|
||||
WORKDIR /app
|
||||
|
||||
# Copy package.json and package-lock.json to the container
|
||||
COPY package*.json ./
|
||||
|
||||
# Install dependencies
|
||||
RUN npm install
|
||||
# Configure Liara npm mirror registry
|
||||
RUN npm config set registry https://package-mirror.liara.ir/repository/npm/ --global
|
||||
|
||||
# Copy the rest of the application code
|
||||
COPY . .
|
||||
RUN npm ci --omit=dev --ignore-scripts && npm cache clean --force
|
||||
|
||||
# Expose the application port
|
||||
# Stage 2: Production runner
|
||||
FROM node:20-alpine AS runner
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
ENV NODE_ENV=production
|
||||
ENV PORT=3000
|
||||
|
||||
# Create uploads directory and set ownership for non-root node user
|
||||
RUN mkdir -p /app/uploads && chown -R node:node /app
|
||||
|
||||
# Switch to non-root user
|
||||
USER node
|
||||
|
||||
# Copy production node_modules with ownership
|
||||
COPY --chown=node:node --from=dependencies /app/node_modules ./node_modules
|
||||
|
||||
# Copy application source code with ownership
|
||||
COPY --chown=node:node . .
|
||||
|
||||
# Expose backend port
|
||||
EXPOSE 3000
|
||||
|
||||
# Start the application
|
||||
CMD ["npm", "start"]
|
||||
CMD ["node", "app.js"]
|
||||
|
||||
@@ -11,7 +11,7 @@ const cors = require('cors')
|
||||
|
||||
const app = express()
|
||||
|
||||
const allowedOrigins = ['http://localhost:3000', 'http://localhost:5173', 'https://bm-vue.chbk.app']
|
||||
const allowedOrigins = ['http://localhost:3000', 'http://localhost:5173', 'https://bm-vue.chbk.app', 'https://mbmanager.ir']
|
||||
|
||||
app.use(
|
||||
cors({
|
||||
@@ -31,8 +31,25 @@ app.use(express.json())
|
||||
app.set('view engine', 'ejs')
|
||||
app.use(express.static('views/public'))
|
||||
|
||||
// Health check endpoint
|
||||
app.get(['/health', '/healthz', '/api/health'], (req, res) => {
|
||||
const mongoose = require('mongoose')
|
||||
const isDbConnected = mongoose.connection.readyState === 1
|
||||
res.status(isDbConnected ? 200 : 503).json({
|
||||
status: isDbConnected ? 'healthy' : 'unhealthy',
|
||||
uptime: process.uptime(),
|
||||
timestamp: new Date().toISOString(),
|
||||
service: 'belonging-manager-api',
|
||||
database: isDbConnected ? 'connected' : 'disconnected',
|
||||
})
|
||||
})
|
||||
|
||||
app.use('/api', routerEndpoints)
|
||||
|
||||
const { registerEventHandlers } = require('./events/index')
|
||||
|
||||
registerEventHandlers()
|
||||
|
||||
databaseConnection(app)
|
||||
|
||||
app.use(globalErrorHandler)
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
const catchAsync = require('../../globalErrorHandler/catchAsync')
|
||||
const belongingService = require('./belongingService')
|
||||
|
||||
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.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)
|
||||
|
||||
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)
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
data: belonging,
|
||||
})
|
||||
})
|
||||
|
||||
exports.deleteBelonging = catchAsync(async (req, res, next) => {
|
||||
await belongingService.deleteBelonging(req.params.belongingId)
|
||||
|
||||
res.status(204).json({
|
||||
status: 'success',
|
||||
data: null,
|
||||
})
|
||||
})
|
||||
@@ -1,24 +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.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,153 +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({}, 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({}, 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] || '',
|
||||
documents: belonging.documentUrls,
|
||||
description: belonging.description,
|
||||
unit: belonging.unit,
|
||||
tags: combinedTags,
|
||||
coordinates: belonging.location.coordinates,
|
||||
createdAt: Math.floor(new Date(belonging.createdAt).getTime() / 1000), // Store as timestamp in seconds
|
||||
}
|
||||
|
||||
documents.push(data)
|
||||
}
|
||||
|
||||
await client.collections('belongings').documents().import(documents, { action: 'emplace' })
|
||||
}
|
||||
|
||||
return { totalCount: count }
|
||||
}
|
||||
|
||||
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 }
|
||||
@@ -11,7 +11,7 @@ exports.getCategoryTree = catchAsync(async (req, res, next) => {
|
||||
})
|
||||
|
||||
exports.getAllCategories = catchAsync(async (req, res, next) => {
|
||||
const categories = await categoryService.getAllCategories()
|
||||
const categories = await categoryService.getAllCategories(req.query)
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
@@ -20,6 +20,7 @@ exports.getAllCategories = catchAsync(async (req, res, next) => {
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
exports.createCategory = catchAsync(async (req, res, next) => {
|
||||
const category = await categoryService.createCategory(req.body)
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ const runSeeder = async () => {
|
||||
{ nativeName: 'ساختمان', englishName: 'Building' },
|
||||
{ nativeName: 'زمین', englishName: 'Lot' },
|
||||
{ nativeName: 'کالا', englishName: 'Product' },
|
||||
{ nativeName: 'خودرو', englishName: 'Car' },
|
||||
]
|
||||
|
||||
await Category.deleteMany({})
|
||||
|
||||
@@ -1,9 +1,18 @@
|
||||
const Category = require('./categoryModel')
|
||||
const AppError = require('../../globalErrorHandler/AppError')
|
||||
|
||||
module.exports.getAllCategories = async () => {
|
||||
return Category.find().populate('features')
|
||||
module.exports.getAllCategories = async (query = {}) => {
|
||||
const mongoQuery = {}
|
||||
const search = (query.search || query.query || '').trim()
|
||||
if (search) {
|
||||
mongoQuery.$or = [
|
||||
{ nativeName: { $regex: search, $options: 'i' } },
|
||||
{ englishName: { $regex: search, $options: 'i' } },
|
||||
]
|
||||
}
|
||||
return Category.find(mongoQuery).populate('features')
|
||||
}
|
||||
|
||||
|
||||
module.exports.createCategory = async (data) => {
|
||||
return Category.create(data, null)
|
||||
|
||||
@@ -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
|
||||
@@ -0,0 +1,11 @@
|
||||
const catchAsync = require('../../globalErrorHandler/catchAsync')
|
||||
const dashboardService = require('./dashboardService')
|
||||
|
||||
exports.getDashboardStats = catchAsync(async (req, res, next) => {
|
||||
const stats = await dashboardService.getDashboardStats()
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
data: stats,
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,12 @@
|
||||
const express = require('express')
|
||||
const dashboardController = require('./dashboardController')
|
||||
const loginCheck = require('../../middlewares/loginCheck')
|
||||
|
||||
const router = new express.Router()
|
||||
|
||||
router.use(loginCheck.loginProtect)
|
||||
|
||||
router.get('/stats', dashboardController.getDashboardStats)
|
||||
router.get('/summary', dashboardController.getDashboardStats)
|
||||
|
||||
module.exports = router
|
||||
@@ -0,0 +1,232 @@
|
||||
const Property = require('../property/propertyModel')
|
||||
const Category = require('../category/categoryModel')
|
||||
const PropertyStatus = require('../propertyStatus/propertyStatusModel')
|
||||
const Warehouse = require('../warehouse/warehouseModel')
|
||||
const WarehouseItem = require('../warehouseItem/warehouseItemModel')
|
||||
const WarehouseItemTransaction = require('../warehouseItem/warehouseItemTransactionModel')
|
||||
const User = require('../user/userModel')
|
||||
const Role = require('../role/roleModel')
|
||||
const { getSignedUrl } = require('../file/fileService')
|
||||
|
||||
/**
|
||||
* Aggregates live dashboard statistics across properties, warehouses, inventory, and users
|
||||
*/
|
||||
const getDashboardStats = async () => {
|
||||
// 1. Overview counts
|
||||
const [
|
||||
totalProperties,
|
||||
totalAreaResult,
|
||||
totalWarehouseItems,
|
||||
totalWarehouses,
|
||||
totalWarehouseTransactions,
|
||||
totalUsers,
|
||||
totalCategories,
|
||||
totalRoles,
|
||||
] = await Promise.all([
|
||||
Property.countDocuments({ isActive: { $ne: false } }),
|
||||
Property.aggregate([
|
||||
{ $match: { isActive: { $ne: false }, area: { $gt: 0 } } },
|
||||
{ $group: { _id: null, totalArea: { $sum: '$area' } } },
|
||||
]),
|
||||
WarehouseItem.countDocuments({ isActive: { $ne: false } }),
|
||||
Warehouse.countDocuments(),
|
||||
WarehouseItemTransaction.countDocuments(),
|
||||
User.countDocuments({ isActive: { $ne: false } }),
|
||||
Category.countDocuments(),
|
||||
Role.countDocuments(),
|
||||
])
|
||||
|
||||
const totalArea = totalAreaResult?.[0]?.totalArea || 0
|
||||
|
||||
// 2. Properties grouped by Category
|
||||
const propertiesByCategoryRaw = await Property.aggregate([
|
||||
{ $match: { isActive: { $ne: false } } },
|
||||
{
|
||||
$group: {
|
||||
_id: '$category',
|
||||
count: { $sum: 1 },
|
||||
totalArea: { $sum: { $ifNull: ['$area', 0] } },
|
||||
},
|
||||
},
|
||||
{
|
||||
$lookup: {
|
||||
from: 'categories',
|
||||
localField: '_id',
|
||||
foreignField: '_id',
|
||||
as: 'categoryDoc',
|
||||
},
|
||||
},
|
||||
{ $unwind: { path: '$categoryDoc', preserveNullAndEmptyArrays: true } },
|
||||
{ $sort: { count: -1 } },
|
||||
])
|
||||
|
||||
const propertiesByCategory = propertiesByCategoryRaw.map((item) => ({
|
||||
categoryId: item._id,
|
||||
name: item.categoryDoc?.nativeName || item.categoryDoc?.englishName || 'بدون دستهبندی',
|
||||
englishName: item.categoryDoc?.englishName || 'Uncategorized',
|
||||
count: item.count,
|
||||
totalArea: item.totalArea || 0,
|
||||
percentage: totalProperties > 0 ? Math.round((item.count / totalProperties) * 100) : 0,
|
||||
}))
|
||||
|
||||
// 3. Properties grouped by Status
|
||||
const propertiesByStatusRaw = await Property.aggregate([
|
||||
{ $match: { isActive: { $ne: false } } },
|
||||
{
|
||||
$group: {
|
||||
_id: '$status',
|
||||
count: { $sum: 1 },
|
||||
},
|
||||
},
|
||||
{
|
||||
$lookup: {
|
||||
from: 'propertystatuses',
|
||||
localField: '_id',
|
||||
foreignField: '_id',
|
||||
as: 'statusDoc',
|
||||
},
|
||||
},
|
||||
{ $unwind: { path: '$statusDoc', preserveNullAndEmptyArrays: true } },
|
||||
{ $sort: { count: -1 } },
|
||||
])
|
||||
|
||||
const propertiesByStatus = propertiesByStatusRaw.map((item) => ({
|
||||
statusId: item._id,
|
||||
name: item.statusDoc?.nativeName || item.statusDoc?.englishName || 'نامشخص',
|
||||
englishName: item.statusDoc?.englishName || 'Unknown',
|
||||
color: item.statusDoc?.color || '#3b82f6',
|
||||
count: item.count,
|
||||
percentage: totalProperties > 0 ? Math.round((item.count / totalProperties) * 100) : 0,
|
||||
}))
|
||||
|
||||
// 4. Warehouse transactions summary (IN vs OUT)
|
||||
const warehouseFlowRaw = await WarehouseItemTransaction.aggregate([
|
||||
{
|
||||
$group: {
|
||||
_id: '$type',
|
||||
count: { $sum: 1 },
|
||||
totalQuantity: { $sum: '$quantity' },
|
||||
},
|
||||
},
|
||||
])
|
||||
|
||||
const warehouseFlow = {
|
||||
inCount: warehouseFlowRaw.find((f) => f._id === 'IN')?.count || 0,
|
||||
outCount: warehouseFlowRaw.find((f) => f._id === 'OUT')?.count || 0,
|
||||
inQuantity: warehouseFlowRaw.find((f) => f._id === 'IN')?.totalQuantity || 0,
|
||||
outQuantity: warehouseFlowRaw.find((f) => f._id === 'OUT')?.totalQuantity || 0,
|
||||
}
|
||||
|
||||
// 5. Recent registered properties (Last 6)
|
||||
const recentPropertiesRaw = await Property.find({ isActive: { $ne: false } })
|
||||
.sort({ createdAt: -1 })
|
||||
.limit(6)
|
||||
.populate('category', 'nativeName englishName')
|
||||
.populate('status', 'nativeName englishName color')
|
||||
.lean()
|
||||
|
||||
const recentProperties = await Promise.all(
|
||||
recentPropertiesRaw.map(async (prop) => {
|
||||
let thumb = null
|
||||
if (prop.mainImageUrls && prop.mainImageUrls.length > 0) {
|
||||
thumb = await getSignedUrl(prop.mainImageUrls[0], 'properties').catch(() => null)
|
||||
}
|
||||
return {
|
||||
_id: prop._id,
|
||||
propertyCode: prop.propertyCode || prop._id.toString().slice(-6),
|
||||
name: prop.name || 'ملک بدون عنوان',
|
||||
category: prop.category?.nativeName || 'عمومی',
|
||||
status: prop.status?.nativeName || 'عادی',
|
||||
statusColor: prop.status?.color || '#3b82f6',
|
||||
ownerName: prop.ownerName || '—',
|
||||
area: prop.area || 0,
|
||||
dong: prop.dong || 6,
|
||||
imageUrl: thumb || 'https://cloud.mbmanager.ir/images/item-no-image.png',
|
||||
registrationPlate: prop.registrationPlate || '—',
|
||||
createdAt: prop.createdAt,
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
// 6. Recent warehouse transactions (Last 6)
|
||||
const recentWarehouseTransactionsRaw = await WarehouseItemTransaction.find()
|
||||
.sort({ createdAt: -1 })
|
||||
.limit(6)
|
||||
.populate('item', 'nameFa nameEn code unitFa')
|
||||
.populate('warehouse', 'name location')
|
||||
.lean()
|
||||
|
||||
const recentWarehouseTransactions = recentWarehouseTransactionsRaw.map((tx) => ({
|
||||
_id: tx._id,
|
||||
type: tx.type, // 'IN' | 'OUT'
|
||||
quantity: tx.quantity,
|
||||
unit: tx.unit || tx.item?.unitFa || 'عدد',
|
||||
itemName: tx.item?.nameFa || 'کالای نامشخص',
|
||||
itemCode: tx.item?.code || '—',
|
||||
warehouseName: tx.warehouse?.name || 'انبار مرکزی',
|
||||
reason: tx.reason || (tx.type === 'IN' ? 'ورود به انبار' : 'خروج از انبار'),
|
||||
actorName: tx.actorName || 'کاربر سیستم',
|
||||
date: tx.date || tx.createdAt,
|
||||
}))
|
||||
|
||||
// 7. Monthly Property & Warehouse Trend (Last 6 months)
|
||||
const sixMonthsAgo = new Date()
|
||||
sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 5)
|
||||
sixMonthsAgo.setDate(1)
|
||||
sixMonthsAgo.setHours(0, 0, 0, 0)
|
||||
|
||||
const monthlyPropertiesRaw = await Property.aggregate([
|
||||
{ $match: { createdAt: { $gte: sixMonthsAgo }, isActive: { $ne: false } } },
|
||||
{
|
||||
$group: {
|
||||
_id: {
|
||||
year: { $year: '$createdAt' },
|
||||
month: { $month: '$createdAt' },
|
||||
},
|
||||
count: { $sum: 1 },
|
||||
},
|
||||
},
|
||||
{ $sort: { '_id.year': 1, '_id.month': 1 } },
|
||||
])
|
||||
|
||||
const monthlyWarehouseRaw = await WarehouseItemTransaction.aggregate([
|
||||
{ $match: { createdAt: { $gte: sixMonthsAgo } } },
|
||||
{
|
||||
$group: {
|
||||
_id: {
|
||||
year: { $year: '$createdAt' },
|
||||
month: { $month: '$createdAt' },
|
||||
type: '$type',
|
||||
},
|
||||
count: { $sum: 1 },
|
||||
},
|
||||
},
|
||||
{ $sort: { '_id.year': 1, '_id.month': 1 } },
|
||||
])
|
||||
|
||||
return {
|
||||
overview: {
|
||||
totalProperties,
|
||||
totalArea,
|
||||
totalWarehouseItems,
|
||||
totalWarehouses,
|
||||
totalWarehouseTransactions,
|
||||
totalUsers,
|
||||
totalCategories,
|
||||
totalRoles,
|
||||
},
|
||||
propertiesByCategory,
|
||||
propertiesByStatus,
|
||||
warehouseFlow,
|
||||
recentProperties,
|
||||
recentWarehouseTransactions,
|
||||
monthlyTrend: {
|
||||
properties: monthlyPropertiesRaw,
|
||||
warehouse: monthlyWarehouseRaw,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getDashboardStats,
|
||||
}
|
||||
@@ -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
@@ -2,6 +2,12 @@ const catchAsync = require('../../globalErrorHandler/catchAsync')
|
||||
const fileService = require('./fileService')
|
||||
|
||||
exports.bucketSingleUpload = catchAsync(async (req, res, next) => {
|
||||
if (!req.file) {
|
||||
return res.status(400).json({
|
||||
status: 'fail',
|
||||
message: 'No file uploaded'
|
||||
})
|
||||
}
|
||||
const fileData = await fileService.bucketSingleUpload(req.file, req.params.bucketName)
|
||||
|
||||
res.status(200).json({
|
||||
@@ -71,7 +77,10 @@ exports.getImage = catchAsync(async (req, res, next) => {
|
||||
});
|
||||
|
||||
exports.bucketDeleteFile = catchAsync(async (req, res, next) => {
|
||||
const { fileName } = await fileService.bucketDeleteFile(req.body, req.params.bucketName)
|
||||
const rawTarget = typeof req.body === 'object' && req.body !== null
|
||||
? (req.body.fileName || req.body.url || req.body.data || '')
|
||||
: (req.body || '');
|
||||
const { fileName } = await fileService.bucketDeleteFile(rawTarget, req.params.bucketName)
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
|
||||
@@ -25,11 +25,18 @@ const fileSchema = new mongoose.Schema(
|
||||
)
|
||||
|
||||
fileSchema.virtual('publicUrl').get(function () {
|
||||
return this.fileEndpoint + '/' + this.bucketName + '/' + this.fileName
|
||||
const protocol = process.env.AWS_USE_SSL === 'true' ? 'https://' : 'http://'
|
||||
let endpoint = this.fileEndpoint || process.env.AWS_ENDPOINT || 'localhost'
|
||||
if (!endpoint.startsWith('http://') && !endpoint.startsWith('https://')) {
|
||||
const hostPort = process.env.AWS_PORT ? `${endpoint}:${process.env.AWS_PORT}` : endpoint
|
||||
endpoint = `${protocol}${hostPort}`
|
||||
}
|
||||
return `${endpoint.replace(/\/$/, '')}/${this.bucketName}/${this.fileName}`
|
||||
})
|
||||
|
||||
fileSchema.virtual('privateUrl').get(function () {
|
||||
return process.env.API_URL + '/api/files/get-image/' + this.bucketName + '/' + this.fileName
|
||||
const apiUrl = (process.env.API_URL || '').replace(/\/$/, '')
|
||||
return `${apiUrl}/api/files/get-image/${this.bucketName}/${this.fileName}`
|
||||
})
|
||||
|
||||
const File = mongoose.model('file', fileSchema)
|
||||
|
||||
+115
-18
@@ -52,14 +52,26 @@ const bucketMultiUpload = async (files, bucketName) => {
|
||||
}
|
||||
|
||||
const bucketDeleteFile = async (fileName, bucketName) => {
|
||||
let exportedFileName = getLastUrlSegment(fileName)
|
||||
await deleteObject(exportedFileName, bucketName)
|
||||
await deleteFile(exportedFileName)
|
||||
let raw = typeof fileName === 'object' && fileName !== null
|
||||
? (fileName.fileName || fileName.url || fileName.name || '')
|
||||
: fileName
|
||||
let exportedFileName = getLastUrlSegment(String(raw || ''))
|
||||
if (exportedFileName) {
|
||||
await deleteObject(exportedFileName, bucketName).catch((err) => {
|
||||
console.error('Error deleting object from MinIO bucket:', err)
|
||||
})
|
||||
await deleteFile(exportedFileName).catch((err) => {
|
||||
console.error('Error deleting file record from DB:', err)
|
||||
})
|
||||
}
|
||||
|
||||
return { fileName }
|
||||
return { fileName: exportedFileName }
|
||||
}
|
||||
|
||||
const getLastUrlSegment = (url) => {
|
||||
if (!url || typeof url !== 'string') {
|
||||
return ''
|
||||
}
|
||||
if (!url.includes('/')) {
|
||||
return url
|
||||
}
|
||||
@@ -106,29 +118,114 @@ const bucketGetFiles = async (bucketName) => {
|
||||
return listOfObjects(bucketName)
|
||||
}
|
||||
|
||||
const getSignedUrl = async (fileName, bucketName) => {
|
||||
if (!fileName) {
|
||||
return
|
||||
const parseFileAndBucket = (input, defaultBucket = 'properties') => {
|
||||
if (!input) return { fileName: '', bucketName: defaultBucket }
|
||||
const raw = typeof input === 'object' && input !== null
|
||||
? (input.fileName || input.name || input.url || '')
|
||||
: String(input || '')
|
||||
|
||||
const clean = raw.split('?')[0]
|
||||
const match = clean.match(/(?:^|\/)(properties|documents|temp|belongings|belonging-images|belonging-documents|property-images|property-documents)\/([^/]+)$/i)
|
||||
if (match) {
|
||||
let b = match[1]
|
||||
if (b === 'property-images' || b === 'belonging-images') b = 'properties'
|
||||
if (b === 'property-documents' || b === 'belonging-documents') b = 'documents'
|
||||
return { bucketName: b, fileName: decodeURIComponent(match[2]) }
|
||||
}
|
||||
return signedUrl(bucketName, fileName)
|
||||
const parts = clean.split('/')
|
||||
const fileName = decodeURIComponent(parts.pop() || '')
|
||||
return { bucketName: defaultBucket, fileName }
|
||||
}
|
||||
|
||||
const getMultipleSignedUrls = async (fileNameArray, bucketName) => {
|
||||
const urls = []
|
||||
for (let fileName of fileNameArray) {
|
||||
urls.push({ url: await getSignedUrl(fileName, bucketName), fileName: fileName})
|
||||
const getSignedUrl = async (input, defaultBucket = 'properties') => {
|
||||
if (!input) {
|
||||
return null
|
||||
}
|
||||
return urls
|
||||
const { fileName, bucketName } = parseFileAndBucket(input, defaultBucket)
|
||||
if (!fileName) {
|
||||
return null
|
||||
}
|
||||
try {
|
||||
return await signedUrl(bucketName, fileName)
|
||||
} catch (err) {
|
||||
console.error(`Error generating signed URL for ${bucketName}/${fileName}:`, err.message)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const getMultipleSignedUrls = async (fileNameArray, defaultBucket = 'properties') => {
|
||||
if (!fileNameArray || !Array.isArray(fileNameArray)) {
|
||||
return []
|
||||
}
|
||||
const results = await Promise.all(
|
||||
fileNameArray.map(async (item) => {
|
||||
const { fileName, bucketName } = parseFileAndBucket(item, defaultBucket)
|
||||
if (!fileName) return null
|
||||
const url = await getSignedUrl(item, bucketName)
|
||||
return url ? { url, fileName, bucketName } : null
|
||||
})
|
||||
)
|
||||
return results.filter(Boolean)
|
||||
}
|
||||
|
||||
const moveFromTempToMain = async (files, targetBucket) => {
|
||||
const tempBucket = 'temp'
|
||||
|
||||
for (const file of files) {
|
||||
await copyObject(targetBucket, file, `${tempBucket}/${file}`)
|
||||
|
||||
await removeObject(tempBucket, file)
|
||||
if (!files || !Array.isArray(files) || files.length === 0) {
|
||||
return []
|
||||
}
|
||||
|
||||
const { minioClient } = require('../../utils/upload/bucket')
|
||||
|
||||
const updatedUrls = await Promise.all(
|
||||
files.map(async (item) => {
|
||||
const rawStr = typeof item === 'object' && item !== null ? (item.url || item.fileName || item.name || '') : String(item || '')
|
||||
const fileName = getLastUrlSegment(rawStr)
|
||||
|
||||
if (!fileName) {
|
||||
return null
|
||||
}
|
||||
|
||||
// Already pointing at the target bucket (e.g. re-submitted unchanged on every
|
||||
// property save) - skip the MinIO round-trips entirely, nothing to move.
|
||||
if (rawStr.includes(`/${targetBucket}/`) && !rawStr.includes(`/${tempBucket}/`)) {
|
||||
return rawStr.split('?')[0]
|
||||
}
|
||||
|
||||
try {
|
||||
// Check if object exists in temp bucket
|
||||
const existsInTemp = await minioClient.statObject(tempBucket, fileName).then(() => true).catch(() => false)
|
||||
if (existsInTemp) {
|
||||
// Copy object from temp to targetBucket
|
||||
await copyObject(targetBucket, fileName, `/${tempBucket}/${fileName}`).catch((err) => {
|
||||
console.error(`Failed to copy object "${fileName}" to "${targetBucket}":`, err.message)
|
||||
})
|
||||
// Remove from temp bucket
|
||||
await removeObject(tempBucket, fileName).catch((err) => {
|
||||
console.error(`Failed to remove object "${fileName}" from "${tempBucket}":`, err.message)
|
||||
})
|
||||
// Update File record in database if exists
|
||||
await File.findOneAndUpdate({ fileName }, { bucketName: targetBucket }, null).catch(() => {})
|
||||
}
|
||||
|
||||
// Construct new URL for targetBucket
|
||||
const protocol = process.env.AWS_USE_SSL === 'true' ? 'https://' : 'http://'
|
||||
const endpoint = process.env.AWS_ENDPOINT || 'localhost'
|
||||
const hostPort = (endpoint.includes(':') || !process.env.AWS_PORT) ? endpoint : `${endpoint}:${process.env.AWS_PORT}`
|
||||
const fullHost = hostPort.startsWith('http://') || hostPort.startsWith('https://') ? hostPort : `${protocol}${hostPort}`
|
||||
const newUrl = `${fullHost.replace(/\/$/, '')}/${targetBucket}/${fileName}`
|
||||
|
||||
return newUrl
|
||||
} catch (err) {
|
||||
console.error(`Failed to move file "${fileName}" from ${tempBucket} to ${targetBucket}:`, err.message)
|
||||
if (rawStr.includes(`/${tempBucket}/`)) {
|
||||
return rawStr.replace(`/${tempBucket}/`, `/${targetBucket}/`)
|
||||
}
|
||||
return rawStr
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
return updatedUrls.filter(Boolean)
|
||||
}
|
||||
|
||||
const getImage = async (bucketName, fileName) => {
|
||||
|
||||
@@ -0,0 +1,529 @@
|
||||
/**
|
||||
* System-wide Permission Definitions
|
||||
* Organized by functional category for the Belonging Manager platform.
|
||||
*/
|
||||
|
||||
const permissionsList = [
|
||||
// ─── مدیریت کاربران (User Management) ──────────────────────────────────────
|
||||
{
|
||||
englishName: 'View All Users',
|
||||
nativeName: 'مشاهده لیست کاربران',
|
||||
key: 'getallusers',
|
||||
category: 'کاربران',
|
||||
},
|
||||
{
|
||||
englishName: 'View User Details',
|
||||
nativeName: 'مشاهده جزئیات کاربر',
|
||||
key: 'getuser',
|
||||
category: 'کاربران',
|
||||
},
|
||||
{
|
||||
englishName: 'Create User',
|
||||
nativeName: 'ایجاد کاربر جدید',
|
||||
key: 'createuser',
|
||||
category: 'کاربران',
|
||||
},
|
||||
{
|
||||
englishName: 'Update User',
|
||||
nativeName: 'ویرایش کاربر',
|
||||
key: 'updateuser',
|
||||
category: 'کاربران',
|
||||
},
|
||||
{
|
||||
englishName: 'Delete User',
|
||||
nativeName: 'حذف کاربر',
|
||||
key: 'deleteuser',
|
||||
category: 'کاربران',
|
||||
},
|
||||
|
||||
// ─── مدیریت نقشها و دسترسیها (Roles & Permissions) ────────────────────────
|
||||
{
|
||||
englishName: 'View All Roles',
|
||||
nativeName: 'مشاهده لیست نقشها',
|
||||
key: 'getallroles',
|
||||
category: 'نقشها و دسترسیها',
|
||||
},
|
||||
{
|
||||
englishName: 'View Role Details',
|
||||
nativeName: 'مشاهده جزئیات نقش',
|
||||
key: 'getarole',
|
||||
category: 'نقشها و دسترسیها',
|
||||
},
|
||||
{
|
||||
englishName: 'Create Role',
|
||||
nativeName: 'ایجاد نقش جدید',
|
||||
key: 'createarole',
|
||||
category: 'نقشها و دسترسیها',
|
||||
},
|
||||
{
|
||||
englishName: 'Update Role',
|
||||
nativeName: 'ویرایش نقش و دسترسیها',
|
||||
key: 'updatearole',
|
||||
category: 'نقشها و دسترسیها',
|
||||
},
|
||||
{
|
||||
englishName: 'Delete Role',
|
||||
nativeName: 'حذف نقش',
|
||||
key: 'deletearole',
|
||||
category: 'نقشها و دسترسیها',
|
||||
},
|
||||
{
|
||||
englishName: 'View All Permissions',
|
||||
nativeName: 'مشاهده لیست دسترسیها',
|
||||
key: 'getallpermissions',
|
||||
category: 'نقشها و دسترسیها',
|
||||
},
|
||||
{
|
||||
englishName: 'Create Permission',
|
||||
nativeName: 'ایجاد دسترسی',
|
||||
key: 'createpermission',
|
||||
category: 'نقشها و دسترسیها',
|
||||
},
|
||||
{
|
||||
englishName: 'View Permission',
|
||||
nativeName: 'مشاهده دسترسی',
|
||||
key: 'getpermission',
|
||||
category: 'نقشها و دسترسیها',
|
||||
},
|
||||
{
|
||||
englishName: 'Update Permission',
|
||||
nativeName: 'ویرایش دسترسی',
|
||||
key: 'updatepermission',
|
||||
category: 'نقشها و دسترسیها',
|
||||
},
|
||||
{
|
||||
englishName: 'Delete Permission',
|
||||
nativeName: 'حذف دسترسی',
|
||||
key: 'deletepermission',
|
||||
category: 'نقشها و دسترسیها',
|
||||
},
|
||||
|
||||
// ─── مدیریت املاک و اموال (Property / Belongings) ─────────────────────────
|
||||
{
|
||||
englishName: 'View All Properties',
|
||||
nativeName: 'مشاهده لیست املاک',
|
||||
key: 'getallproperties',
|
||||
category: 'املاک و اموال',
|
||||
},
|
||||
{
|
||||
englishName: 'View Property Details',
|
||||
nativeName: 'مشاهده جزئیات ملک',
|
||||
key: 'getaproperty',
|
||||
category: 'املاک و اموال',
|
||||
},
|
||||
{
|
||||
englishName: 'Create Property',
|
||||
nativeName: 'ایجاد ملک جدید',
|
||||
key: 'createaproperty',
|
||||
category: 'املاک و اموال',
|
||||
},
|
||||
{
|
||||
englishName: 'Update Property',
|
||||
nativeName: 'ویرایش ملک',
|
||||
key: 'updateaproperty',
|
||||
category: 'املاک و اموال',
|
||||
},
|
||||
{
|
||||
englishName: 'Delete Property',
|
||||
nativeName: 'حذف ملک',
|
||||
key: 'deleteaproperty',
|
||||
category: 'املاک و اموال',
|
||||
},
|
||||
{
|
||||
englishName: 'Search Properties',
|
||||
nativeName: 'جستجوی املاک',
|
||||
key: 'searchproperties',
|
||||
category: 'املاک و اموال',
|
||||
},
|
||||
{
|
||||
englishName: 'Index Properties',
|
||||
nativeName: 'ایندکسسازی املاک',
|
||||
key: 'indexproperties',
|
||||
category: 'املاک و اموال',
|
||||
},
|
||||
|
||||
// Aliases for Belongings
|
||||
{
|
||||
englishName: 'View All Belongings',
|
||||
nativeName: 'مشاهده لیست اموال (سازگاری)',
|
||||
key: 'getallbelongings',
|
||||
category: 'املاک و اموال',
|
||||
},
|
||||
{
|
||||
englishName: 'View Belonging Details',
|
||||
nativeName: 'مشاهده جزئیات مال (سازگاری)',
|
||||
key: 'getabelonging',
|
||||
category: 'املاک و اموال',
|
||||
},
|
||||
{
|
||||
englishName: 'Create Belonging',
|
||||
nativeName: 'ایجاد مال (سازگاری)',
|
||||
key: 'createabelonging',
|
||||
category: 'املاک و اموال',
|
||||
},
|
||||
{
|
||||
englishName: 'Update Belonging',
|
||||
nativeName: 'ویرایش مال (سازگاری)',
|
||||
key: 'updateabelonging',
|
||||
category: 'املاک و اموال',
|
||||
},
|
||||
{
|
||||
englishName: 'Delete Belonging',
|
||||
nativeName: 'حذف مال (سازگاری)',
|
||||
key: 'deleteabelonging',
|
||||
category: 'املاک و اموال',
|
||||
},
|
||||
{
|
||||
englishName: 'Search Belongings',
|
||||
nativeName: 'جستجوی اموال (سازگاری)',
|
||||
key: 'searchbelongings',
|
||||
category: 'املاک و اموال',
|
||||
},
|
||||
{
|
||||
englishName: 'Index Belongings',
|
||||
nativeName: 'ایندکسسازی اموال (سازگاری)',
|
||||
key: 'indexbelongings',
|
||||
category: 'املاک و اموال',
|
||||
},
|
||||
|
||||
// ─── دستهبندیها (Categories) ─────────────────────────────────────────────
|
||||
{
|
||||
englishName: 'View All Categories',
|
||||
nativeName: 'مشاهده لیست دستهبندیها',
|
||||
key: 'getallcategories',
|
||||
category: 'دستهبندیها',
|
||||
},
|
||||
{
|
||||
englishName: 'View Category Tree',
|
||||
nativeName: 'مشاهده درخت دستهبندیها',
|
||||
key: 'getcategorytree',
|
||||
category: 'دستهبندیها',
|
||||
},
|
||||
{
|
||||
englishName: 'View Category Details',
|
||||
nativeName: 'مشاهده جزئیات دستهبندی',
|
||||
key: 'getcategory',
|
||||
category: 'دستهبندیها',
|
||||
},
|
||||
{
|
||||
englishName: 'Create Category',
|
||||
nativeName: 'ایجاد دستهبندی جدید',
|
||||
key: 'createcategory',
|
||||
category: 'دستهبندیها',
|
||||
},
|
||||
{
|
||||
englishName: 'Update Category',
|
||||
nativeName: 'ویرایش دستهبندی',
|
||||
key: 'updatecategory',
|
||||
category: 'دستهبندیها',
|
||||
},
|
||||
{
|
||||
englishName: 'Delete Category',
|
||||
nativeName: 'حذف دستهبندی',
|
||||
key: 'deletecategory',
|
||||
category: 'دستهبندیها',
|
||||
},
|
||||
|
||||
// ─── ویژگیها (Features) ──────────────────────────────────────────────────
|
||||
{
|
||||
englishName: 'View All Features',
|
||||
nativeName: 'مشاهده ویژگیها',
|
||||
key: 'getallfeatures',
|
||||
category: 'ویژگیها',
|
||||
},
|
||||
{
|
||||
englishName: 'View Feature Details',
|
||||
nativeName: 'مشاهده جزئیات ویژگی',
|
||||
key: 'getafeature',
|
||||
category: 'ویژگیها',
|
||||
},
|
||||
{
|
||||
englishName: 'Create Feature',
|
||||
nativeName: 'ایجاد ویژگی جدید',
|
||||
key: 'createfeature',
|
||||
category: 'ویژگیها',
|
||||
},
|
||||
{
|
||||
englishName: 'Update Feature',
|
||||
nativeName: 'ویرایش ویژگی',
|
||||
key: 'updateafeature',
|
||||
category: 'ویژگیها',
|
||||
},
|
||||
{
|
||||
englishName: 'Delete Feature',
|
||||
nativeName: 'حذف ویژگی',
|
||||
key: 'deleteafeature',
|
||||
category: 'ویژگیها',
|
||||
},
|
||||
|
||||
// ─── وضعیت املاک (Property Statuses) ──────────────────────────────────────
|
||||
{
|
||||
englishName: 'View All Property Statuses',
|
||||
nativeName: 'مشاهده وضعیتهای ملک',
|
||||
key: 'getallpropertystatuses',
|
||||
category: 'وضعیتهای ملک',
|
||||
},
|
||||
{
|
||||
englishName: 'View Property Status Details',
|
||||
nativeName: 'مشاهده جزئیات وضعیت ملک',
|
||||
key: 'getapropertystatus',
|
||||
category: 'وضعیتهای ملک',
|
||||
},
|
||||
{
|
||||
englishName: 'Create Property Status',
|
||||
nativeName: 'ایجاد وضعیت ملک جدید',
|
||||
key: 'createapropertystatus',
|
||||
category: 'وضعیتهای ملک',
|
||||
},
|
||||
{
|
||||
englishName: 'Update Property Status',
|
||||
nativeName: 'ویرایش وضعیت ملک',
|
||||
key: 'updateapropertystatus',
|
||||
category: 'وضعیتهای ملک',
|
||||
},
|
||||
{
|
||||
englishName: 'Delete Property Status',
|
||||
nativeName: 'حذف وضعیت ملک',
|
||||
key: 'deleteapropertystatus',
|
||||
category: 'وضعیتهای ملک',
|
||||
},
|
||||
{
|
||||
englishName: 'View All Belonging Statuses',
|
||||
nativeName: 'مشاهده وضعیتهای اموال (سازگاری)',
|
||||
key: 'getallbelongingstatuses',
|
||||
category: 'وضعیتهای ملک',
|
||||
},
|
||||
{
|
||||
englishName: 'View Belonging Status Details',
|
||||
nativeName: 'مشاهده جزئیات وضعیت مال (سازگاری)',
|
||||
key: 'getabelongingstatus',
|
||||
category: 'وضعیتهای ملک',
|
||||
},
|
||||
{
|
||||
englishName: 'Create Belonging Status',
|
||||
nativeName: 'ایجاد وضعیت مال (سازگاری)',
|
||||
key: 'createabelongingstatus',
|
||||
category: 'وضعیتهای ملک',
|
||||
},
|
||||
{
|
||||
englishName: 'Update Belonging Status',
|
||||
nativeName: 'ویرایش وضعیت مال (سازگاری)',
|
||||
key: 'updateabelongingstatus',
|
||||
category: 'وضعیتهای ملک',
|
||||
},
|
||||
{
|
||||
englishName: 'Delete Belonging Status',
|
||||
nativeName: 'حذف وضعیت مال (سازگاری)',
|
||||
key: 'deleteabelongingstatus',
|
||||
category: 'وضعیتهای ملک',
|
||||
},
|
||||
|
||||
// ─── مدیریت انبار (Warehouse & Inventory) ──────────────────────────────────
|
||||
{
|
||||
englishName: 'View All Warehouses',
|
||||
nativeName: 'مشاهده انبارها',
|
||||
key: 'getallwarehouses',
|
||||
category: 'مدیریت انبار',
|
||||
},
|
||||
{
|
||||
englishName: 'View Warehouse Details',
|
||||
nativeName: 'مشاهده جزئیات انبار',
|
||||
key: 'getwarehouse',
|
||||
category: 'مدیریت انبار',
|
||||
},
|
||||
{
|
||||
englishName: 'Create Warehouse',
|
||||
nativeName: 'ایجاد انبار جدید',
|
||||
key: 'createwarehouse',
|
||||
category: 'مدیریت انبار',
|
||||
},
|
||||
{
|
||||
englishName: 'Update Warehouse',
|
||||
nativeName: 'ویرایش انبار',
|
||||
key: 'updatewarehouse',
|
||||
category: 'مدیریت انبار',
|
||||
},
|
||||
{
|
||||
englishName: 'Delete Warehouse',
|
||||
nativeName: 'حذف انبار',
|
||||
key: 'deletewarehouse',
|
||||
category: 'مدیریت انبار',
|
||||
},
|
||||
{
|
||||
englishName: 'View Warehouse Items',
|
||||
nativeName: 'مشاهده اقلام انبار',
|
||||
key: 'getallwarehouseitems',
|
||||
category: 'مدیریت انبار',
|
||||
},
|
||||
{
|
||||
englishName: 'View Warehouse Item Details',
|
||||
nativeName: 'مشاهده جزئیات قلم انبار',
|
||||
key: 'getwarehouseitem',
|
||||
category: 'مدیریت انبار',
|
||||
},
|
||||
{
|
||||
englishName: 'Create Warehouse Item',
|
||||
nativeName: 'ایجاد قلم انبار جدید',
|
||||
key: 'createwarehouseitem',
|
||||
category: 'مدیریت انبار',
|
||||
},
|
||||
{
|
||||
englishName: 'Update Warehouse Item',
|
||||
nativeName: 'ویرایش قلم انبار',
|
||||
key: 'updatewarehouseitem',
|
||||
category: 'مدیریت انبار',
|
||||
},
|
||||
{
|
||||
englishName: 'Delete Warehouse Item',
|
||||
nativeName: 'حذف قلم انبار',
|
||||
key: 'deletewarehouseitem',
|
||||
category: 'مدیریت انبار',
|
||||
},
|
||||
{
|
||||
englishName: 'View Warehouse Transactions',
|
||||
nativeName: 'مشاهده تراکنشهای انبار',
|
||||
key: 'getallwarehousetransactions',
|
||||
category: 'مدیریت انبار',
|
||||
},
|
||||
{
|
||||
englishName: 'Create Warehouse Transaction',
|
||||
nativeName: 'ثبت تراکنش انبار',
|
||||
key: 'createwarehousetransaction',
|
||||
category: 'مدیریت انبار',
|
||||
},
|
||||
{
|
||||
englishName: 'Delete Warehouse Transaction',
|
||||
nativeName: 'حذف تراکنش انبار',
|
||||
key: 'deletewarehousetransaction',
|
||||
category: 'مدیریت انبار',
|
||||
},
|
||||
{
|
||||
englishName: 'View Warehouse Stock',
|
||||
nativeName: 'مشاهده موجودی انبار',
|
||||
key: 'getwarehousestock',
|
||||
category: 'مدیریت انبار',
|
||||
},
|
||||
|
||||
// ─── مدیریت فایلها (Files) ────────────────────────────────────────────────
|
||||
{
|
||||
englishName: 'View All Files',
|
||||
nativeName: 'مشاهده لیست فایلها',
|
||||
key: 'getallfiles',
|
||||
category: 'مدیریت فایلها',
|
||||
},
|
||||
{
|
||||
englishName: 'View File Details',
|
||||
nativeName: 'مشاهده جزئیات فایل',
|
||||
key: 'getfile',
|
||||
category: 'مدیریت فایلها',
|
||||
},
|
||||
{
|
||||
englishName: 'Create File Record',
|
||||
nativeName: 'ایجاد رکورد فایل',
|
||||
key: 'createfile',
|
||||
category: 'مدیریت فایلها',
|
||||
},
|
||||
{
|
||||
englishName: 'Update File',
|
||||
nativeName: 'ویرایش فایل',
|
||||
key: 'updatefile',
|
||||
category: 'مدیریت فایلها',
|
||||
},
|
||||
{
|
||||
englishName: 'Delete File',
|
||||
nativeName: 'حذف فایل',
|
||||
key: 'deletefile',
|
||||
category: 'مدیریت فایلها',
|
||||
},
|
||||
{
|
||||
englishName: 'Upload Single File',
|
||||
nativeName: 'آپلود فایل تکی',
|
||||
key: 'uploadsinglefile',
|
||||
category: 'مدیریت فایلها',
|
||||
},
|
||||
{
|
||||
englishName: 'Upload Multiple Files',
|
||||
nativeName: 'آپلود چندتایی فایل',
|
||||
key: 'uploadmultifile',
|
||||
category: 'مدیریت فایلها',
|
||||
},
|
||||
{
|
||||
englishName: 'Get Bucket Files',
|
||||
nativeName: 'مشاهده فایلهای ذخیرهسازی ابری',
|
||||
key: 'getbucketfiles',
|
||||
category: 'مدیریت فایلها',
|
||||
},
|
||||
{
|
||||
englishName: 'Get Images',
|
||||
nativeName: 'مشاهده تصاویر',
|
||||
key: 'getimages',
|
||||
category: 'مدیریت فایلها',
|
||||
},
|
||||
{
|
||||
englishName: 'Delete Bucket Files',
|
||||
nativeName: 'حذف فایل از فضای ابری',
|
||||
key: 'deletebucketfiles',
|
||||
category: 'مدیریت فایلها',
|
||||
},
|
||||
|
||||
// ─── مدیریت تراکنشها (Transactions) ────────────────────────────────────────
|
||||
{
|
||||
englishName: 'View All Transactions',
|
||||
nativeName: 'مشاهده تراکنشها',
|
||||
key: 'getalltransactions',
|
||||
category: 'تراکنشها',
|
||||
},
|
||||
{
|
||||
englishName: 'View Transaction Details',
|
||||
nativeName: 'مشاهده جزئیات تراکنش',
|
||||
key: 'gettransaction',
|
||||
category: 'تراکنشها',
|
||||
},
|
||||
{
|
||||
englishName: 'Create Transaction',
|
||||
nativeName: 'ثبت تراکنش جدید',
|
||||
key: 'createtransaction',
|
||||
category: 'تراکنشها',
|
||||
},
|
||||
{
|
||||
englishName: 'Update Transaction',
|
||||
nativeName: 'ویرایش تراکنش',
|
||||
key: 'updatetransaction',
|
||||
category: 'تراکنشها',
|
||||
},
|
||||
{
|
||||
englishName: 'Delete Transaction',
|
||||
nativeName: 'حذف تراکنش',
|
||||
key: 'deletetransaction',
|
||||
category: 'تراکنشها',
|
||||
},
|
||||
|
||||
// ─── سیستم و داشبورد (Dashboard & System) ──────────────────────────────────
|
||||
{
|
||||
englishName: 'View Dashboard',
|
||||
nativeName: 'مشاهده داشبورد',
|
||||
key: 'viewdashboard',
|
||||
category: 'سیستم و داشبورد',
|
||||
},
|
||||
{
|
||||
englishName: 'Admin Dashboard Access',
|
||||
nativeName: 'دسترسی مدیریت داشبورد',
|
||||
key: 'admindashboard',
|
||||
category: 'سیستم و داشبورد',
|
||||
},
|
||||
{
|
||||
englishName: 'View System Settings',
|
||||
nativeName: 'مشاهده تنظیمات سیستم',
|
||||
key: 'getsettings',
|
||||
category: 'تنظیمات سیستم',
|
||||
},
|
||||
{
|
||||
englishName: 'Update System Settings',
|
||||
nativeName: 'ویرایش تنظیمات سیستم',
|
||||
key: 'updatesettings',
|
||||
category: 'تنظیمات سیستم',
|
||||
},
|
||||
]
|
||||
|
||||
module.exports = permissionsList
|
||||
|
||||
@@ -25,7 +25,7 @@ const permissionSchema = new mongoose.Schema({
|
||||
})
|
||||
|
||||
permissionSchema.pre(/^find/, function (next) {
|
||||
this.find({ active: { $ne: false } })
|
||||
this.find({ isActive: { $ne: false } })
|
||||
next()
|
||||
})
|
||||
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
const Permission = require('./permissionModel')
|
||||
const permissionsList = require('./permissionList')
|
||||
const chalk = require('chalk')
|
||||
|
||||
const runSeeder = async () => {
|
||||
const permissions = []
|
||||
|
||||
await Permission.deleteMany({})
|
||||
console.log(chalk.red('Deleted all permission records.'))
|
||||
|
||||
const permissions = permissionsList.map((p) => ({
|
||||
...p,
|
||||
isActive: true,
|
||||
}))
|
||||
|
||||
await Permission.insertMany(permissions, null)
|
||||
console.log(
|
||||
chalk.green.bold(
|
||||
|
||||
@@ -1,8 +1,52 @@
|
||||
const Permission = require('./permissionModel')
|
||||
const permissionsList = require('./permissionList')
|
||||
const AppError = require('../../globalErrorHandler/AppError')
|
||||
|
||||
module.exports.syncPermissions = async () => {
|
||||
try {
|
||||
let createdCount = 0
|
||||
let updatedCount = 0
|
||||
|
||||
for (const item of permissionsList) {
|
||||
const existing = await Permission.findOne({ key: item.key })
|
||||
if (!existing) {
|
||||
await Permission.create({
|
||||
englishName: item.englishName,
|
||||
nativeName: item.nativeName,
|
||||
key: item.key,
|
||||
category: item.category,
|
||||
isActive: true,
|
||||
})
|
||||
createdCount++
|
||||
} else {
|
||||
let changed = false
|
||||
if (existing.englishName !== item.englishName) {
|
||||
existing.englishName = item.englishName
|
||||
changed = true
|
||||
}
|
||||
if (existing.nativeName !== item.nativeName) {
|
||||
existing.nativeName = item.nativeName
|
||||
changed = true
|
||||
}
|
||||
if (existing.category !== item.category) {
|
||||
existing.category = item.category
|
||||
changed = true
|
||||
}
|
||||
if (changed) {
|
||||
await existing.save()
|
||||
updatedCount++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`[Permissions] Sync complete: ${createdCount} created, ${updatedCount} updated.`)
|
||||
} catch (error) {
|
||||
console.error('[Permissions] Error during sync:', error.message)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports.getAllPermissions = async () => {
|
||||
return Permission.find({})
|
||||
return Permission.find({}).sort({ category: 1, englishName: 1 })
|
||||
}
|
||||
|
||||
module.exports.createPermission = async (data) => {
|
||||
|
||||
@@ -20,7 +20,6 @@ const belongingSchema = new mongoose.Schema(
|
||||
},
|
||||
unit: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
description: String,
|
||||
relatedProjects: [String],
|
||||
@@ -37,7 +36,12 @@ const belongingSchema = new mongoose.Schema(
|
||||
},
|
||||
documentUrls: [String],
|
||||
mainImageUrls: [String],
|
||||
nationalGeoCode: String,
|
||||
tags: [String],
|
||||
status: {
|
||||
type: ObjectID,
|
||||
ref: 'BelongingStatus',
|
||||
},
|
||||
isActive: {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
@@ -61,17 +65,19 @@ const belongingSchema = new mongoose.Schema(
|
||||
}
|
||||
)
|
||||
|
||||
// belongingSchema.plugin(AutoIncrement, { inc_field: 'belongingCode' })
|
||||
belongingSchema.plugin(AutoIncrement, { inc_field: 'belongingCode' })
|
||||
|
||||
belongingSchema.methods.getDocumentsSignedUrls = function () {
|
||||
return getMultipleSignedUrls(this.documentUrls, 'belonging-documents')
|
||||
return getMultipleSignedUrls(this.documentUrls, 'documents')
|
||||
}
|
||||
|
||||
belongingSchema.methods.getMainImagedSignedUrl = function () {
|
||||
return getMultipleSignedUrls(this.mainImageUrls, 'belonging-images')
|
||||
return getMultipleSignedUrls(this.mainImageUrls, 'properties')
|
||||
}
|
||||
|
||||
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,12 @@
|
||||
const propertyService = require('../propertyService')
|
||||
module.exports = (eventEmitter) => {
|
||||
eventEmitter.on('createProperty', async (propertyData) => {
|
||||
try {
|
||||
if (propertyData && propertyData._id) {
|
||||
await propertyService.indexOneProperty(propertyData._id)
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('Error in createProperty event handler:', err.message)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -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,12 @@
|
||||
const propertyService = require('../propertyService')
|
||||
module.exports = (eventEmitter) => {
|
||||
eventEmitter.on('updateProperty', async (propertyData) => {
|
||||
try {
|
||||
if (propertyData && propertyData._id) {
|
||||
await propertyService.indexOneProperty(propertyData._id)
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('Error in updateProperty event handler:', err.message)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -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,96 @@
|
||||
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, searchEngine } = await propertyService.searchProperties(req.query)
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
facets,
|
||||
properties: belongings,
|
||||
totalCount,
|
||||
pagesCount,
|
||||
searchEngine,
|
||||
})
|
||||
})
|
||||
|
||||
exports.searchPropertiesMongo = catchAsync(async (req, res, next) => {
|
||||
const { facets, belongings, totalCount, pagesCount, searchEngine } = await propertyService.searchPropertiesMongo(req.query)
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
facets,
|
||||
properties: belongings,
|
||||
totalCount,
|
||||
pagesCount,
|
||||
searchEngine: searchEngine || 'mongo',
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
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)
|
||||
eventEmitter.emit('updateProperty', property)
|
||||
|
||||
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,147 @@
|
||||
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: Date, // تاریخ ثبت سند (MongoDB Date object)
|
||||
|
||||
// Owner Specifications (مشخصات مالک)
|
||||
ownerName: String,
|
||||
fatherName: String,
|
||||
idCardNumber: String,
|
||||
nationalId: String,
|
||||
issuePlace: String,
|
||||
birthDate: String,
|
||||
nationality: {
|
||||
type: String,
|
||||
default: 'ایران',
|
||||
},
|
||||
ownershipDocs: String,
|
||||
|
||||
// Property Specifications (مشخصات ملک)
|
||||
area: Number, // مساحت عرصه (متر مربع)
|
||||
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' })
|
||||
|
||||
// Pre-validate hook: sanitize location for 2dsphere index
|
||||
propertySchema.pre('validate', function (next) {
|
||||
if (
|
||||
!this.location ||
|
||||
!Array.isArray(this.location.coordinates) ||
|
||||
this.location.coordinates.length !== 2 ||
|
||||
isNaN(this.location.coordinates[0]) ||
|
||||
isNaN(this.location.coordinates[1])
|
||||
) {
|
||||
this.location = undefined
|
||||
} else {
|
||||
this.location.type = 'Point'
|
||||
}
|
||||
next()
|
||||
})
|
||||
|
||||
propertySchema.methods.getDocumentsSignedUrls = function () {
|
||||
return getMultipleSignedUrls(this.documentUrls, 'documents')
|
||||
}
|
||||
|
||||
propertySchema.methods.getMainImagedSignedUrl = function () {
|
||||
return getMultipleSignedUrls(this.mainImageUrls, 'properties')
|
||||
}
|
||||
|
||||
propertySchema.index({ location: '2dsphere' }, { sparse: true })
|
||||
|
||||
const Property = mongoose.model('Property', propertySchema)
|
||||
|
||||
module.exports = Property
|
||||
@@ -0,0 +1,28 @@
|
||||
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/search-mongo', perm.requires('searchproperties', 'searchbelongings'), propertyController.searchPropertiesMongo)
|
||||
|
||||
|
||||
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,153 @@
|
||||
const Property = require('./propertyModel')
|
||||
const Land = require('./landModel')
|
||||
const Building = require('./buildingModel')
|
||||
const Category = require('../category/categoryModel')
|
||||
const PropertyStatus = require('../propertyStatus/propertyStatusModel')
|
||||
const chalk = require('chalk')
|
||||
|
||||
const runSeeder = async () => {
|
||||
const buildingCategory = await Category.findOne({ englishName: 'Building' })
|
||||
const lotCategory = await Category.findOne({ englishName: 'Lot' })
|
||||
const availableStatus = await PropertyStatus.findOne({ englishName: 'available' })
|
||||
const inReviewStatus = await PropertyStatus.findOne({ englishName: 'in_review' })
|
||||
const reservedStatus = await PropertyStatus.findOne({ englishName: 'reserved' })
|
||||
|
||||
const sampleProperties = [
|
||||
{
|
||||
name: 'مجتمع اداری تجاری نگین الهیه',
|
||||
propertyType: 'Building',
|
||||
category: buildingCategory?._id,
|
||||
status: availableStatus?._id,
|
||||
nationalGeoCode: '537123395123439',
|
||||
description: 'مجتمع اداری ۱۰ طبقه با دسترسی عالی به بزرگراه صدر و مترو',
|
||||
area: 1500,
|
||||
dong: 6,
|
||||
ownerName: 'شرکت سرمایهگذاری پارس',
|
||||
registrationPlate: '۱۲۳۴/۵۶',
|
||||
uniqueId: '140201123456789012',
|
||||
serialNumber: 'A/987654',
|
||||
zoningType: 'تجاری - اداری',
|
||||
address: 'تهران، الهیه، خیابان فرشته، پلاک ۱۲',
|
||||
postalCode: '1965834211',
|
||||
location: {
|
||||
type: 'Point',
|
||||
coordinates: [51.4235, 35.7952], // [lng, lat]
|
||||
},
|
||||
tags: ['اداری', 'الهیه', 'مدرن', 'سند تکبرگ'],
|
||||
isActive: true,
|
||||
},
|
||||
{
|
||||
name: 'زمین ویلایی شهرک غرب فاز ۴',
|
||||
propertyType: 'Land',
|
||||
category: lotCategory?._id,
|
||||
status: availableStatus?._id,
|
||||
nationalGeoCode: '536987394852139',
|
||||
description: 'زمین دو کله با بر ۲۵ متر و دستور نقشه ۵ طبقه مسکونی',
|
||||
area: 600,
|
||||
dong: 6,
|
||||
ownerName: 'محسن رضایی',
|
||||
registrationPlate: '۴۵۶۷/۸۹',
|
||||
uniqueId: '140202234567890123',
|
||||
serialNumber: 'B/123456',
|
||||
zoningType: 'مسکونی',
|
||||
address: 'تهران، شهرک غرب، فاز ۴، خیابان فلامک شمالی',
|
||||
postalCode: '1467893214',
|
||||
location: {
|
||||
type: 'Point',
|
||||
coordinates: [51.3712, 35.7725],
|
||||
},
|
||||
tags: ['زمین', 'شهرک غرب', 'دو کله'],
|
||||
isActive: true,
|
||||
},
|
||||
{
|
||||
name: 'برج مسکونی یاس نیاوران',
|
||||
propertyType: 'Building',
|
||||
category: buildingCategory?._id,
|
||||
status: reservedStatus?._id || availableStatus?._id,
|
||||
nationalGeoCode: '539145395412039',
|
||||
description: 'واحد ۳۰۰ متری طبقه ۸ با ویوی ابدی کاخ نیاوران و ۳ پارکینگ سندی',
|
||||
area: 300,
|
||||
dong: 6,
|
||||
ownerName: 'سارا صادقی',
|
||||
registrationPlate: '۷۸۹۰/۱۲',
|
||||
uniqueId: '140203345678901234',
|
||||
serialNumber: 'C/654321',
|
||||
zoningType: 'مسکونی',
|
||||
address: 'تهران، نیاوران، خیابان باهنر، کوچه یاس',
|
||||
postalCode: '1978945612',
|
||||
location: {
|
||||
type: 'Point',
|
||||
coordinates: [51.4678, 35.8156],
|
||||
},
|
||||
tags: ['لوکس', 'نیاوران', 'پنتهاوس'],
|
||||
isActive: true,
|
||||
},
|
||||
{
|
||||
name: 'باغ ویلای قصرالدشت شیراز',
|
||||
propertyType: 'Land',
|
||||
category: lotCategory?._id,
|
||||
status: availableStatus?._id,
|
||||
nationalGeoCode: '645123328456139',
|
||||
description: 'باغ ۲۰۰۰ متری با درختان کهنسال و عمارت دوبلکس ۴۰۰ متری',
|
||||
area: 2000,
|
||||
dong: 6,
|
||||
ownerName: 'علیرضا زندی',
|
||||
registrationPlate: '۳۲۱۴/۵۶',
|
||||
uniqueId: '140204456789012345',
|
||||
serialNumber: 'D/789123',
|
||||
zoningType: 'باغ ویلا',
|
||||
address: 'شیراز، قصرالدشت، خیابان وکلا، کوچه ۱۲',
|
||||
postalCode: '7198765432',
|
||||
location: {
|
||||
type: 'Point',
|
||||
coordinates: [52.4823, 29.6412],
|
||||
},
|
||||
tags: ['شیراز', 'باغ', 'قصرالدشت'],
|
||||
isActive: true,
|
||||
},
|
||||
{
|
||||
name: 'ملک تجاری چهارباغ عباسی اصفهان',
|
||||
propertyType: 'Building',
|
||||
category: buildingCategory?._id,
|
||||
status: inReviewStatus?._id || availableStatus?._id,
|
||||
nationalGeoCode: '584123361456239',
|
||||
description: 'مغازه تجاری دو دهنه بر خیابان اصلی چهارباغ با سند شش دانگ ملکیت',
|
||||
area: 180,
|
||||
dong: 6,
|
||||
ownerName: 'محمد مهدی اصفهانی',
|
||||
registrationPlate: '۹۶۳۲/۱۴',
|
||||
uniqueId: '140205567890123456',
|
||||
serialNumber: 'E/456789',
|
||||
zoningType: 'تجاری',
|
||||
address: 'اصفهان، خیابان چهارباغ عباسی، جنب سینما سپاهان',
|
||||
postalCode: '8145678901',
|
||||
location: {
|
||||
type: 'Point',
|
||||
coordinates: [51.6685, 32.6546],
|
||||
},
|
||||
tags: ['اصفهان', 'تجاری', 'چهارباغ'],
|
||||
isActive: true,
|
||||
},
|
||||
]
|
||||
|
||||
await Property.deleteMany({})
|
||||
console.log(chalk.red('Deleted all property records.'))
|
||||
|
||||
for (const propData of sampleProperties) {
|
||||
if (propData.propertyType === 'Building') {
|
||||
await Building.create(propData)
|
||||
} else if (propData.propertyType === 'Land') {
|
||||
await Land.create(propData)
|
||||
} else {
|
||||
await Property.create(propData)
|
||||
}
|
||||
}
|
||||
|
||||
console.log(
|
||||
chalk.green.bold(
|
||||
`PROPERTIES: Created ${sampleProperties.length} sample property(ies)`
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
module.exports = { runSeeder }
|
||||
@@ -0,0 +1,455 @@
|
||||
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, getSignedUrl } = require('../file/fileService')
|
||||
const { normalizeToDate } = require('../../utils/jalali')
|
||||
|
||||
const sanitizePropertyData = (data) => {
|
||||
const cleanData = { ...data }
|
||||
|
||||
// Remove immutable / system fields
|
||||
delete cleanData._id
|
||||
delete cleanData.createdAt
|
||||
delete cleanData.updatedAt
|
||||
delete cleanData.__v
|
||||
|
||||
// Sanitize category & status ObjectIds
|
||||
if (cleanData.category && !mongoose.Types.ObjectId.isValid(cleanData.category)) {
|
||||
cleanData.category = null
|
||||
} else if (cleanData.category === '') {
|
||||
cleanData.category = null
|
||||
}
|
||||
|
||||
if (cleanData.status && !mongoose.Types.ObjectId.isValid(cleanData.status)) {
|
||||
cleanData.status = null
|
||||
} else if (cleanData.status === '') {
|
||||
cleanData.status = null
|
||||
}
|
||||
|
||||
// Sanitize registrationDate
|
||||
if (cleanData.registrationDate !== undefined) {
|
||||
cleanData.registrationDate = normalizeToDate(cleanData.registrationDate)
|
||||
}
|
||||
|
||||
// Sanitize Location (GeoJSON Point for 2dsphere)
|
||||
if (cleanData.location) {
|
||||
const coords = cleanData.location.coordinates
|
||||
if (Array.isArray(coords) && coords.length === 2 && coords[0] !== null && coords[1] !== null && !isNaN(coords[0]) && !isNaN(coords[1])) {
|
||||
cleanData.location = {
|
||||
type: 'Point',
|
||||
coordinates: [Number(coords[0]), Number(coords[1])]
|
||||
}
|
||||
} else {
|
||||
cleanData.location = undefined
|
||||
}
|
||||
}
|
||||
|
||||
// Sanitize Features
|
||||
if (cleanData.features && Array.isArray(cleanData.features)) {
|
||||
cleanData.features = cleanData.features.filter(
|
||||
(f) => f && f.definition && mongoose.Types.ObjectId.isValid(f.definition)
|
||||
)
|
||||
}
|
||||
|
||||
// Sanitize dong
|
||||
if (cleanData.dong !== undefined && cleanData.dong !== null && cleanData.dong !== '') {
|
||||
const dongNum = Number(cleanData.dong)
|
||||
cleanData.dong = isNaN(dongNum) ? 6 : Math.max(1, Math.min(6, dongNum))
|
||||
}
|
||||
|
||||
// Sanitize numeric fields
|
||||
const numericFields = [
|
||||
'area', 'landArea', 'builtArea', 'floorsCount', 'unitsCount',
|
||||
'constructionYear', 'streetWidth', 'facadeCount', 'landLength', 'landWidth'
|
||||
]
|
||||
numericFields.forEach((field) => {
|
||||
if (cleanData[field] === '' || cleanData[field] === undefined) {
|
||||
cleanData[field] = null
|
||||
} else if (cleanData[field] !== null) {
|
||||
const num = Number(cleanData[field])
|
||||
cleanData[field] = isNaN(num) ? null : num
|
||||
}
|
||||
})
|
||||
|
||||
return cleanData
|
||||
}
|
||||
|
||||
const getAllProperties = async () => {
|
||||
return Property.find({}, null, null).populate('category').populate('status')
|
||||
}
|
||||
|
||||
const createProperty = async (data) => {
|
||||
const cleanData = sanitizePropertyData(data)
|
||||
|
||||
if (cleanData.mainImageUrls && Array.isArray(cleanData.mainImageUrls) && cleanData.mainImageUrls.length > 0) {
|
||||
cleanData.mainImageUrls = await moveFromTempToMain(cleanData.mainImageUrls, 'properties')
|
||||
}
|
||||
if (cleanData.documentUrls && Array.isArray(cleanData.documentUrls) && cleanData.documentUrls.length > 0) {
|
||||
cleanData.documentUrls = await moveFromTempToMain(cleanData.documentUrls, 'documents')
|
||||
}
|
||||
|
||||
if (cleanData.propertyType === 'Land' || cleanData.propertyType === 'زمین') {
|
||||
return Land.create(cleanData)
|
||||
} else if (cleanData.propertyType === 'Building' || cleanData.propertyType === 'ساختمان') {
|
||||
return Building.create(cleanData)
|
||||
}
|
||||
return Property.create(cleanData)
|
||||
}
|
||||
|
||||
const resolvePropertyFilter = (propertyId) => {
|
||||
if (!propertyId) return { _id: null }
|
||||
if (mongoose.Types.ObjectId.isValid(propertyId)) {
|
||||
return { _id: propertyId }
|
||||
}
|
||||
if (!isNaN(propertyId) && String(propertyId).trim() !== '') {
|
||||
return { propertyCode: Number(propertyId) }
|
||||
}
|
||||
return { _id: propertyId }
|
||||
}
|
||||
|
||||
const getProperty = async (propertyId) => {
|
||||
const filter = resolvePropertyFilter(propertyId)
|
||||
let property = await Property.findOne(filter, null, null).populate('category').populate('status')
|
||||
|
||||
if (!property && !filter._id && mongoose.Types.ObjectId.isValid(propertyId)) {
|
||||
property = await Property.findById(propertyId, null, null).populate('category').populate('status')
|
||||
}
|
||||
|
||||
if (!property) {
|
||||
throw new AppError('NoPropertyFound', 404, {})
|
||||
}
|
||||
|
||||
let documentUrls = []
|
||||
let mainImageUrls = []
|
||||
try {
|
||||
if (typeof property.getDocumentsSignedUrls === 'function') {
|
||||
documentUrls = await property.getDocumentsSignedUrls()
|
||||
}
|
||||
if (typeof property.getMainImagedSignedUrl === 'function') {
|
||||
mainImageUrls = await property.getMainImagedSignedUrl()
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('Error fetching signed URLs for property:', e.message)
|
||||
}
|
||||
|
||||
property = JSON.parse(JSON.stringify(property))
|
||||
|
||||
property.signedDocumentUrls = documentUrls || []
|
||||
property.signedMainImageUrls = mainImageUrls || []
|
||||
|
||||
return property
|
||||
}
|
||||
|
||||
const updateProperty = async (propertyId, data) => {
|
||||
const cleanData = sanitizePropertyData(data)
|
||||
|
||||
if (cleanData.mainImageUrls && Array.isArray(cleanData.mainImageUrls) && cleanData.mainImageUrls.length > 0) {
|
||||
cleanData.mainImageUrls = await moveFromTempToMain(cleanData.mainImageUrls, 'properties')
|
||||
}
|
||||
if (cleanData.documentUrls && Array.isArray(cleanData.documentUrls) && cleanData.documentUrls.length > 0) {
|
||||
cleanData.documentUrls = await moveFromTempToMain(cleanData.documentUrls, 'documents')
|
||||
}
|
||||
|
||||
const filter = resolvePropertyFilter(propertyId)
|
||||
const property = await Property.findOneAndUpdate(filter, cleanData, { new: true })
|
||||
|
||||
if (!property) {
|
||||
throw new AppError('NoPropertyFound', 404, {})
|
||||
}
|
||||
|
||||
return property
|
||||
}
|
||||
|
||||
const deleteProperty = async (propertyId) => {
|
||||
const filter = resolvePropertyFilter(propertyId)
|
||||
const property = await Property.findOneAndUpdate(filter, { 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 settingService = require('../setting/settingService')
|
||||
const mongoose = require('mongoose')
|
||||
|
||||
const searchPropertiesMongo = async (inputQuery = {}) => {
|
||||
const page = parseInt(inputQuery.page) || 1
|
||||
const per_page = parseInt(inputQuery.per_page) || parseInt(inputQuery.limit) || 20
|
||||
const mongoQuery = { isActive: { $ne: false } }
|
||||
|
||||
const q = (inputQuery.query || inputQuery.search || inputQuery.q || '').trim()
|
||||
if (q && q !== '*') {
|
||||
const searchRegex = { $regex: q, $options: 'i' }
|
||||
const orConditions = [
|
||||
{ name: searchRegex },
|
||||
{ nationalGeoCode: searchRegex },
|
||||
{ uniqueId: searchRegex },
|
||||
{ serialNumber: searchRegex },
|
||||
{ ownerName: searchRegex },
|
||||
{ registrationPlate: searchRegex },
|
||||
{ description: searchRegex },
|
||||
{ address: searchRegex },
|
||||
{ tags: searchRegex },
|
||||
{ relatedProjects: searchRegex },
|
||||
]
|
||||
|
||||
if (!isNaN(q) && q !== '') {
|
||||
orConditions.push({ propertyCode: Number(q) })
|
||||
}
|
||||
|
||||
if (mongoose.Types.ObjectId.isValid(q)) {
|
||||
orConditions.push({ _id: q })
|
||||
}
|
||||
|
||||
mongoQuery.$or = orConditions
|
||||
}
|
||||
|
||||
if (inputQuery.category && mongoose.Types.ObjectId.isValid(inputQuery.category)) {
|
||||
mongoQuery.category = inputQuery.category
|
||||
}
|
||||
|
||||
if (inputQuery.status && mongoose.Types.ObjectId.isValid(inputQuery.status)) {
|
||||
mongoQuery.status = inputQuery.status
|
||||
}
|
||||
|
||||
let sortObj = { createdAt: -1 }
|
||||
if (inputQuery.sort) {
|
||||
if (typeof inputQuery.sort === 'string') {
|
||||
const parts = inputQuery.sort.split(':')
|
||||
const field = parts[0]
|
||||
const order = parts[1] === 'asc' ? 1 : -1
|
||||
sortObj = { [field]: order }
|
||||
} else if (typeof inputQuery.sort === 'object') {
|
||||
sortObj = inputQuery.sort
|
||||
}
|
||||
}
|
||||
|
||||
const totalCount = await Property.countDocuments(mongoQuery)
|
||||
const properties = await Property.find(mongoQuery)
|
||||
.populate('category')
|
||||
.populate('status')
|
||||
.sort(sortObj)
|
||||
.skip((page - 1) * per_page)
|
||||
.limit(per_page)
|
||||
|
||||
const items = await Promise.all(properties.map(async (prop) => {
|
||||
const combinedTags = Array.isArray(prop.tags) ? prop.tags.join(' ') : (prop.tags || '')
|
||||
let signedThumb = null
|
||||
if (prop.mainImageUrls && prop.mainImageUrls.length > 0) {
|
||||
signedThumb = await getSignedUrl(prop.mainImageUrls[0], 'properties').catch(() => null)
|
||||
}
|
||||
return {
|
||||
_id: prop._id.toString(),
|
||||
id: prop.propertyCode ? prop.propertyCode.toString() : prop._id.toString(),
|
||||
propertyCode: prop.propertyCode,
|
||||
name: prop.name || '',
|
||||
category: prop.category?.englishName || (typeof prop.category === 'string' ? prop.category : ''),
|
||||
nativeCategory: prop.category?.nativeName || '',
|
||||
categoryObj: prop.category,
|
||||
status: prop.status,
|
||||
imageUrl: signedThumb || 'https://cloud.mbmanager.ir/images/item-no-image.png',
|
||||
mainImageUrls: prop.mainImageUrls || [],
|
||||
documents: prop.documentUrls || [],
|
||||
documentUrls: prop.documentUrls || [],
|
||||
description: prop.description || '',
|
||||
nationalGeoCode: prop.nationalGeoCode || '',
|
||||
tags: combinedTags,
|
||||
dong: prop.dong,
|
||||
ownerName: prop.ownerName || '',
|
||||
registrationPlate: prop.registrationPlate || '',
|
||||
uniqueId: prop.uniqueId || '',
|
||||
serialNumber: prop.serialNumber || '',
|
||||
registrationDate: prop.registrationDate,
|
||||
coordinates: prop.location?.coordinates || [0, 0],
|
||||
location: prop.location,
|
||||
createdAt: Math.floor(new Date(prop.createdAt || Date.now()).getTime() / 1000),
|
||||
updatedAt: prop.updatedAt,
|
||||
isActive: prop.isActive !== false,
|
||||
features: prop.features || [],
|
||||
}
|
||||
}))
|
||||
|
||||
const pagesCount = Math.ceil(totalCount / per_page) || 1
|
||||
|
||||
return {
|
||||
facets: [],
|
||||
belongings: items,
|
||||
properties: items,
|
||||
totalCount,
|
||||
pagesCount,
|
||||
searchEngine: 'mongo',
|
||||
}
|
||||
}
|
||||
|
||||
const searchProperties = async (inputQuery) => {
|
||||
try {
|
||||
const setting = await settingService.getSearchSettingByPage('properties')
|
||||
if (setting && setting.searchMethod === 'mongo') {
|
||||
return searchPropertiesMongo(inputQuery)
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('Failed to fetch search setting for properties, attempting typesense:', e.message)
|
||||
}
|
||||
|
||||
try {
|
||||
await ensureCollectionExists(false)
|
||||
const updatedQuery = updateInputQuery({ ...inputQuery }, {})
|
||||
|
||||
const tsFeatures = new TsApiFeatures(client, 'properties', updatedQuery).filter().facet().sort().limitFields().paginate().search()
|
||||
|
||||
let { facets, items, totalCount, pagesCount } = await tsFeatures.execute()
|
||||
|
||||
return { facets, belongings: items, properties: items, totalCount, pagesCount, searchEngine: 'typesense' }
|
||||
} catch (err) {
|
||||
console.warn('Typesense search failed for properties, falling back to MongoDB:', err.message)
|
||||
return searchPropertiesMongo(inputQuery)
|
||||
}
|
||||
}
|
||||
|
||||
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) => {
|
||||
try {
|
||||
await ensureCollectionExists(false)
|
||||
const property = await getProperty(propertyId)
|
||||
|
||||
if (!property) return
|
||||
|
||||
const combinedTags = Array.isArray(property.tags) ? property.tags.join(' ') : (property.tags || '')
|
||||
|
||||
const data = {
|
||||
_id: property._id.toString(),
|
||||
isActive: property.isActive !== false,
|
||||
name: property.name || '',
|
||||
category: property.category?.englishName || (typeof property.category === 'string' ? property.category : ''),
|
||||
nativeCategory: property.category?.nativeName || '',
|
||||
imageUrl: property.mainImageUrls?.[0] || '',
|
||||
documents: property.documentUrls || [],
|
||||
description: property.description || '',
|
||||
nationalGeoCode: property.nationalGeoCode || '',
|
||||
tags: combinedTags,
|
||||
coordinates: (property.location?.coordinates && property.location.coordinates.length === 2 && !isNaN(property.location.coordinates[0]) && !isNaN(property.location.coordinates[1]))
|
||||
? [property.location.coordinates[1], property.location.coordinates[0]] // Typesense geopoint is [lat, lng]
|
||||
: [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)
|
||||
} catch (err) {
|
||||
console.warn(`Typesense indexing skipped for property ${propertyId}:`, err.message)
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
searchPropertiesMongo,
|
||||
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,7 +4,7 @@ const Role = require('./roleModel')
|
||||
const roleService = require('./roleService')
|
||||
|
||||
exports.getAllRoles = catchAsync(async (req, res, next) => {
|
||||
const roles = await roleService.getAllRoles()
|
||||
const roles = await roleService.getAllRoles(req.query)
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
@@ -13,6 +13,7 @@ exports.getAllRoles = catchAsync(async (req, res, next) => {
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
exports.createRole = catchAsync(async (req, res, next) => {
|
||||
const role = await roleService.createRole(req.body)
|
||||
|
||||
|
||||
@@ -1,16 +1,26 @@
|
||||
const Role = require('./roleModel')
|
||||
const AppError = require('../../globalErrorHandler/AppError')
|
||||
|
||||
module.exports.getAllRoles = async () => {
|
||||
return Role.find({}, null, null)
|
||||
module.exports.getAllRoles = async (query = {}) => {
|
||||
const mongoQuery = {}
|
||||
const search = (query.search || query.query || '').trim()
|
||||
if (search) {
|
||||
mongoQuery.$or = [
|
||||
{ nativeName: { $regex: search, $options: 'i' } },
|
||||
{ englishName: { $regex: search, $options: 'i' } },
|
||||
]
|
||||
}
|
||||
return Role.find(mongoQuery).populate('permissions').sort({ createdAt: -1 })
|
||||
}
|
||||
|
||||
|
||||
module.exports.createRole = async (data) => {
|
||||
return await Role.create(data)
|
||||
const role = await Role.create(data)
|
||||
return Role.findById(role._id).populate('permissions')
|
||||
}
|
||||
|
||||
module.exports.getRole = async (roleId) => {
|
||||
const role = await Role.findById(roleId)
|
||||
const role = await Role.findById(roleId).populate('permissions')
|
||||
|
||||
if (!role) {
|
||||
throw new AppError('NoRoleFound', 404, {})
|
||||
@@ -20,7 +30,7 @@ module.exports.getRole = async (roleId) => {
|
||||
}
|
||||
|
||||
module.exports.updateRole = async (roleId, data) => {
|
||||
const role = await Role.findOneAndUpdate({ _id: roleId }, data, { new: true })
|
||||
const role = await Role.findOneAndUpdate({ _id: roleId }, data, { new: true }).populate('permissions')
|
||||
|
||||
if (!role) {
|
||||
throw new AppError('NoRoleFound', 404, {})
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
const catchAsync = require('../../globalErrorHandler/catchAsync')
|
||||
const settingService = require('./settingService')
|
||||
|
||||
exports.getSearchSettings = catchAsync(async (req, res, next) => {
|
||||
const settings = await settingService.getSearchSettings()
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
results: settings.length,
|
||||
data: settings,
|
||||
})
|
||||
})
|
||||
|
||||
exports.getSearchSettingByPage = catchAsync(async (req, res, next) => {
|
||||
const setting = await settingService.getSearchSettingByPage(req.params.pageKey)
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
data: setting,
|
||||
})
|
||||
})
|
||||
|
||||
exports.updateSearchSetting = catchAsync(async (req, res, next) => {
|
||||
const { searchMethod, extraConfig } = req.body
|
||||
const setting = await settingService.setSearchMethod(req.params.pageKey, searchMethod, extraConfig)
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
data: setting,
|
||||
})
|
||||
})
|
||||
|
||||
exports.bulkUpdateSearchSettings = catchAsync(async (req, res, next) => {
|
||||
const { settings } = req.body
|
||||
const results = await settingService.bulkUpdateSearchSettings(settings)
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
results: results.length,
|
||||
data: results,
|
||||
})
|
||||
})
|
||||
|
||||
exports.getSeedStatus = catchAsync(async (req, res, next) => {
|
||||
const status = await settingService.getSeedStatus()
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
data: status,
|
||||
})
|
||||
})
|
||||
|
||||
exports.seedDatabase = catchAsync(async (req, res, next) => {
|
||||
const result = await settingService.seedDatabase(req.user?._id)
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
data: result,
|
||||
})
|
||||
})
|
||||
|
||||
exports.getAutoSaveSetting = catchAsync(async (req, res, next) => {
|
||||
const result = await settingService.getAutoSaveSetting()
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
data: result,
|
||||
})
|
||||
})
|
||||
|
||||
exports.updateAutoSaveSetting = catchAsync(async (req, res, next) => {
|
||||
const { enabled, intervalSeconds } = req.body
|
||||
const result = await settingService.updateAutoSaveSetting({ enabled, intervalSeconds })
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
data: result,
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,46 @@
|
||||
const mongoose = require('mongoose')
|
||||
|
||||
const settingSchema = new mongoose.Schema(
|
||||
{
|
||||
key: {
|
||||
type: String,
|
||||
required: true,
|
||||
unique: true,
|
||||
trim: true,
|
||||
},
|
||||
category: {
|
||||
type: String,
|
||||
default: 'search',
|
||||
},
|
||||
pageKey: {
|
||||
type: String,
|
||||
required: true,
|
||||
trim: true,
|
||||
},
|
||||
title: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
description: {
|
||||
type: String,
|
||||
},
|
||||
searchMethod: {
|
||||
type: String,
|
||||
enum: ['typesense', 'mongo'],
|
||||
default: 'mongo',
|
||||
},
|
||||
extraConfig: {
|
||||
type: mongoose.Schema.Types.Mixed,
|
||||
default: {},
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
}
|
||||
)
|
||||
|
||||
settingSchema.index({ key: 1 }, { unique: true })
|
||||
settingSchema.index({ pageKey: 1 })
|
||||
|
||||
const Setting = mongoose.model('Setting', settingSchema)
|
||||
module.exports = Setting
|
||||
@@ -0,0 +1,58 @@
|
||||
const express = require('express')
|
||||
const settingController = require('./settingController')
|
||||
const perm = require('../../middlewares/permissionMiddleware')
|
||||
const loginCheck = require('../../middlewares/loginCheck')
|
||||
|
||||
const router = new express.Router()
|
||||
|
||||
router.use(loginCheck.loginProtect)
|
||||
|
||||
router.get(
|
||||
'/search-settings',
|
||||
perm.requires('admindashboard', 'viewdashboard', 'getallpermissions'),
|
||||
settingController.getSearchSettings
|
||||
)
|
||||
|
||||
router.get(
|
||||
'/search-settings/:pageKey',
|
||||
perm.requires('admindashboard', 'viewdashboard', 'getallpermissions'),
|
||||
settingController.getSearchSettingByPage
|
||||
)
|
||||
|
||||
router.put(
|
||||
'/search-settings/:pageKey',
|
||||
perm.requires('admindashboard', 'viewdashboard', 'getallpermissions'),
|
||||
settingController.updateSearchSetting
|
||||
)
|
||||
|
||||
router.put(
|
||||
'/search-settings',
|
||||
perm.requires('admindashboard', 'viewdashboard', 'getallpermissions'),
|
||||
settingController.bulkUpdateSearchSettings
|
||||
)
|
||||
|
||||
router.get(
|
||||
'/seed-status',
|
||||
perm.requires('admindashboard', 'viewdashboard', 'getallpermissions'),
|
||||
settingController.getSeedStatus
|
||||
)
|
||||
|
||||
router.post(
|
||||
'/seed-database',
|
||||
perm.requires('admindashboard', 'viewdashboard', 'getallpermissions'),
|
||||
settingController.seedDatabase
|
||||
)
|
||||
|
||||
router.get(
|
||||
'/autosave',
|
||||
perm.requires('admindashboard', 'viewdashboard', 'getallpermissions'),
|
||||
settingController.getAutoSaveSetting
|
||||
)
|
||||
|
||||
router.put(
|
||||
'/autosave',
|
||||
perm.requires('admindashboard', 'viewdashboard', 'getallpermissions'),
|
||||
settingController.updateAutoSaveSetting
|
||||
)
|
||||
|
||||
module.exports = router
|
||||
@@ -0,0 +1,289 @@
|
||||
const Setting = require('./settingModel')
|
||||
const AppError = require('../../globalErrorHandler/AppError')
|
||||
|
||||
const DEFAULT_SEARCH_PAGES = [
|
||||
{
|
||||
pageKey: 'properties',
|
||||
title: 'املاک (Properties)',
|
||||
description: 'جستجوی املاک، کد نوسازی، شناسه ملی جغرافیایی، مشخصات سند، مالک و پلاک ثبتی',
|
||||
defaultMethod: 'typesense',
|
||||
supportedMethods: ['typesense', 'mongo'],
|
||||
endpointTypesense: '/api/properties/admin/search',
|
||||
endpointMongo: '/api/properties/admin/search-mongo',
|
||||
routePath: '/property/list-properties',
|
||||
icon: 'pi pi-file',
|
||||
},
|
||||
{
|
||||
pageKey: 'transactions',
|
||||
title: 'تراکنشهای املاک (Transactions)',
|
||||
description: 'جستجوی تراکنشهای واریز و برداشت، توضیحات، نام کاربر و ملک مرتبط',
|
||||
defaultMethod: 'typesense',
|
||||
supportedMethods: ['typesense', 'mongo'],
|
||||
endpointTypesense: '/api/transactions/admin/search',
|
||||
endpointMongo: '/api/transactions/admin/search-mongo',
|
||||
routePath: '/transactions/list-transactions',
|
||||
icon: 'pi pi-history',
|
||||
},
|
||||
{
|
||||
pageKey: 'warehouseItems',
|
||||
title: 'اقلام انبار (Warehouse Items)',
|
||||
description: 'جستجوی اقلام کالا، نام فارسی، نام انگلیسی، کد کالا و دستهبندی',
|
||||
defaultMethod: 'mongo',
|
||||
supportedMethods: ['mongo', 'typesense'],
|
||||
endpointTypesense: '/api/warehouse-items/admin/items',
|
||||
endpointMongo: '/api/warehouse-items/admin/items',
|
||||
routePath: '/warehouse-items/list',
|
||||
icon: 'pi pi-box',
|
||||
},
|
||||
{
|
||||
pageKey: 'warehouses',
|
||||
title: 'مکانهای انبار (Warehouses)',
|
||||
description: 'جستجوی نام انبار، کد و آدرس انبارها',
|
||||
defaultMethod: 'mongo',
|
||||
supportedMethods: ['mongo', 'typesense'],
|
||||
endpointTypesense: '/api/warehouses/admin/get-all',
|
||||
endpointMongo: '/api/warehouses/admin/get-all',
|
||||
routePath: '/warehouse-items/warehouses',
|
||||
icon: 'pi pi-map',
|
||||
},
|
||||
{
|
||||
pageKey: 'categories',
|
||||
title: 'دستهبندیها (Categories)',
|
||||
description: 'جستجوی دستهبندیهای املاک بر اساس نام فارسی و انگلیسی',
|
||||
defaultMethod: 'mongo',
|
||||
supportedMethods: ['mongo', 'typesense'],
|
||||
endpointTypesense: '/api/categories/admin/get-all',
|
||||
endpointMongo: '/api/categories/admin/get-all',
|
||||
routePath: '/categories/list-categories',
|
||||
icon: 'pi pi-th-large',
|
||||
},
|
||||
{
|
||||
pageKey: 'users',
|
||||
title: 'کاربران (Users)',
|
||||
description: 'جستجوی کاربران سیستم بر اساس نام، ایمیل و نقش کاربری',
|
||||
defaultMethod: 'mongo',
|
||||
supportedMethods: ['mongo', 'typesense'],
|
||||
endpointTypesense: '/api/users/admin/get-all',
|
||||
endpointMongo: '/api/users/admin/get-all',
|
||||
routePath: '/users/list-users',
|
||||
icon: 'pi pi-users',
|
||||
},
|
||||
{
|
||||
pageKey: 'roles',
|
||||
title: 'نقشها و دسترسیها (Roles)',
|
||||
description: 'جستجوی نقشها بر اساس عنوان فارسی و انگلیسی',
|
||||
defaultMethod: 'mongo',
|
||||
supportedMethods: ['mongo', 'typesense'],
|
||||
endpointTypesense: '/api/roles/admin/get-all',
|
||||
endpointMongo: '/api/roles/admin/get-all',
|
||||
routePath: '/roles/list-roles',
|
||||
icon: 'pi pi-shield',
|
||||
},
|
||||
]
|
||||
|
||||
const getSearchSettings = async () => {
|
||||
const dbSettings = await Setting.find({ category: 'search' }).lean()
|
||||
const dbSettingsMap = new Map()
|
||||
|
||||
dbSettings.forEach((s) => {
|
||||
dbSettingsMap.set(s.pageKey, s)
|
||||
})
|
||||
|
||||
return DEFAULT_SEARCH_PAGES.map((pageDef) => {
|
||||
const dbRecord = dbSettingsMap.get(pageDef.pageKey)
|
||||
if (dbRecord) {
|
||||
return {
|
||||
...pageDef,
|
||||
_id: dbRecord._id,
|
||||
searchMethod: dbRecord.searchMethod || pageDef.defaultMethod,
|
||||
isPersisted: true,
|
||||
updatedAt: dbRecord.updatedAt,
|
||||
createdAt: dbRecord.createdAt,
|
||||
}
|
||||
}
|
||||
return {
|
||||
...pageDef,
|
||||
searchMethod: pageDef.defaultMethod,
|
||||
isPersisted: false,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const getSearchSettingByPage = async (pageKey) => {
|
||||
const pageDef = DEFAULT_SEARCH_PAGES.find((p) => p.pageKey === pageKey)
|
||||
if (!pageDef) {
|
||||
throw new AppError('PageNotFound', 404, { message: `Page key ${pageKey} not found in search configurations` })
|
||||
}
|
||||
|
||||
const dbRecord = await Setting.findOne({ pageKey, category: 'search' }).lean()
|
||||
if (dbRecord) {
|
||||
return {
|
||||
...pageDef,
|
||||
_id: dbRecord._id,
|
||||
searchMethod: dbRecord.searchMethod || pageDef.defaultMethod,
|
||||
isPersisted: true,
|
||||
updatedAt: dbRecord.updatedAt,
|
||||
createdAt: dbRecord.createdAt,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...pageDef,
|
||||
searchMethod: pageDef.defaultMethod,
|
||||
isPersisted: false,
|
||||
}
|
||||
}
|
||||
|
||||
const setSearchMethod = async (pageKey, searchMethod, extraConfig = {}) => {
|
||||
if (!['typesense', 'mongo'].includes(searchMethod)) {
|
||||
throw new AppError('InvalidSearchMethod', 400, { message: 'Search method must be either "typesense" or "mongo"' })
|
||||
}
|
||||
|
||||
const pageDef = DEFAULT_SEARCH_PAGES.find((p) => p.pageKey === pageKey) || {
|
||||
pageKey,
|
||||
title: pageKey,
|
||||
description: `Settings for ${pageKey}`,
|
||||
defaultMethod: 'mongo',
|
||||
}
|
||||
|
||||
const setting = await Setting.findOneAndUpdate(
|
||||
{ pageKey, category: 'search' },
|
||||
{
|
||||
key: `search_${pageKey}`,
|
||||
category: 'search',
|
||||
pageKey,
|
||||
title: pageDef.title,
|
||||
description: pageDef.description,
|
||||
searchMethod,
|
||||
extraConfig,
|
||||
},
|
||||
{ upsert: true, new: true, setDefaultsOnInsert: true }
|
||||
)
|
||||
|
||||
return {
|
||||
...pageDef,
|
||||
_id: setting._id,
|
||||
searchMethod: setting.searchMethod,
|
||||
isPersisted: true,
|
||||
updatedAt: setting.updatedAt,
|
||||
createdAt: setting.createdAt,
|
||||
}
|
||||
}
|
||||
|
||||
const seederRunner = require('../../seeder/seederRunner')
|
||||
|
||||
const bulkUpdateSearchSettings = async (settingsArray) => {
|
||||
if (!Array.isArray(settingsArray)) {
|
||||
throw new AppError('InvalidDataFormat', 400, { message: 'Expected an array of settings' })
|
||||
}
|
||||
|
||||
const results = []
|
||||
for (const item of settingsArray) {
|
||||
if (item.pageKey && item.searchMethod) {
|
||||
const updated = await setSearchMethod(item.pageKey, item.searchMethod, item.extraConfig || {})
|
||||
results.push(updated)
|
||||
}
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
const getSeedStatus = async () => {
|
||||
const record = await Setting.findOne({ key: 'system_database_seeded' }).lean()
|
||||
if (record && record.extraConfig && record.extraConfig.isSeeded) {
|
||||
return {
|
||||
isSeeded: true,
|
||||
seededAt: record.extraConfig.seededAt || record.updatedAt,
|
||||
seededBy: record.extraConfig.seededBy || null,
|
||||
}
|
||||
}
|
||||
return {
|
||||
isSeeded: false,
|
||||
seededAt: null,
|
||||
seededBy: null,
|
||||
}
|
||||
}
|
||||
|
||||
const seedDatabase = async (userId = null) => {
|
||||
const currentStatus = await getSeedStatus()
|
||||
if (currentStatus.isSeeded) {
|
||||
throw new AppError('DatabaseAlreadySeeded', 400, {
|
||||
message: 'پایگاه داده قبلاً مقداردهی شده است و امکان مقداردهی مجدد وجود ندارد.',
|
||||
})
|
||||
}
|
||||
|
||||
await seederRunner.run()
|
||||
|
||||
const record = await Setting.findOneAndUpdate(
|
||||
{ key: 'system_database_seeded' },
|
||||
{
|
||||
key: 'system_database_seeded',
|
||||
category: 'system',
|
||||
pageKey: 'system_seeder',
|
||||
title: 'مقداردهی اولیه پایگاه داده',
|
||||
description: 'وضعیت اجرای مقداردهی اولیه دادههای پایه سیستم',
|
||||
extraConfig: {
|
||||
isSeeded: true,
|
||||
seededAt: new Date(),
|
||||
seededBy: userId,
|
||||
},
|
||||
},
|
||||
{ upsert: true, new: true, setDefaultsOnInsert: true }
|
||||
)
|
||||
|
||||
return {
|
||||
isSeeded: true,
|
||||
seededAt: record.extraConfig.seededAt,
|
||||
message: 'پایگاه داده با موفقیت مقداردهی اولیه شد.',
|
||||
}
|
||||
}
|
||||
|
||||
const getAutoSaveSetting = async () => {
|
||||
const record = await Setting.findOne({ key: 'general_autosave' }).lean()
|
||||
if (record && record.extraConfig) {
|
||||
return {
|
||||
enabled: record.extraConfig.enabled !== undefined ? record.extraConfig.enabled : true,
|
||||
intervalSeconds: Number(record.extraConfig.intervalSeconds) || 60,
|
||||
updatedAt: record.updatedAt,
|
||||
}
|
||||
}
|
||||
return {
|
||||
enabled: true,
|
||||
intervalSeconds: 60,
|
||||
}
|
||||
}
|
||||
|
||||
const updateAutoSaveSetting = async ({ enabled = true, intervalSeconds = 60 }) => {
|
||||
const validInterval = Math.max(10, Number(intervalSeconds) || 60)
|
||||
const setting = await Setting.findOneAndUpdate(
|
||||
{ key: 'general_autosave' },
|
||||
{
|
||||
key: 'general_autosave',
|
||||
category: 'general',
|
||||
pageKey: 'general',
|
||||
title: 'تنظیمات ذخیره خودکار (Auto-Save Settings)',
|
||||
description: 'پیکربندی فعالسازی و فاصله زمانی ذخیره خودکار فرمها',
|
||||
extraConfig: {
|
||||
enabled: Boolean(enabled),
|
||||
intervalSeconds: validInterval,
|
||||
},
|
||||
},
|
||||
{ upsert: true, new: true, setDefaultsOnInsert: true }
|
||||
)
|
||||
return {
|
||||
enabled: setting.extraConfig.enabled,
|
||||
intervalSeconds: setting.extraConfig.intervalSeconds,
|
||||
updatedAt: setting.updatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
DEFAULT_SEARCH_PAGES,
|
||||
getSearchSettings,
|
||||
getSearchSettingByPage,
|
||||
setSearchMethod,
|
||||
bulkUpdateSearchSettings,
|
||||
getSeedStatus,
|
||||
seedDatabase,
|
||||
getAutoSaveSetting,
|
||||
updateAutoSaveSetting,
|
||||
}
|
||||
@@ -2,7 +2,7 @@ const catchAsync = require('../../globalErrorHandler/catchAsync')
|
||||
const transactionService = require('./transactionService')
|
||||
|
||||
exports.searchTransactions = catchAsync(async (req, res, next) => {
|
||||
const { facets, transactions, totalCount, pagesCount } = await transactionService.searchTransactions(req.query)
|
||||
const { facets, transactions, totalCount, pagesCount, searchEngine } = await transactionService.searchTransactions(req.query)
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
@@ -10,9 +10,24 @@ exports.searchTransactions = catchAsync(async (req, res, next) => {
|
||||
transactions,
|
||||
totalCount,
|
||||
pagesCount,
|
||||
searchEngine,
|
||||
})
|
||||
})
|
||||
|
||||
exports.searchTransactionsMongo = catchAsync(async (req, res, next) => {
|
||||
const { facets, transactions, totalCount, pagesCount, searchEngine } = await transactionService.searchTransactionsMongo(req.query)
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
facets,
|
||||
transactions,
|
||||
totalCount,
|
||||
pagesCount,
|
||||
searchEngine: searchEngine || 'mongo',
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
exports.indexAllTransactions = catchAsync(async (req, res, next) => {
|
||||
const { indexedCount } = await transactionService.indexAllTransactions()
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -31,6 +31,13 @@ router.get(
|
||||
transactionController.searchTransactions
|
||||
)
|
||||
|
||||
router.get(
|
||||
'/admin/search-mongo',
|
||||
// perm.requires('getallbelongings'),
|
||||
transactionController.searchTransactionsMongo
|
||||
)
|
||||
|
||||
|
||||
router.get(
|
||||
'/admin/get-stock-by-belonging/:belongingId',
|
||||
// perm.requires('getallbelongings'),
|
||||
|
||||
@@ -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,31 +146,138 @@ 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 settingService = require('../setting/settingService')
|
||||
|
||||
const searchTransactionsMongo = async (inputQuery = {}) => {
|
||||
const page = parseInt(inputQuery.page) || 1
|
||||
const per_page = parseInt(inputQuery.per_page) || parseInt(inputQuery.limit) || 20
|
||||
const mongoQuery = {}
|
||||
|
||||
const q = (inputQuery.query || inputQuery.search || inputQuery.q || '').trim()
|
||||
if (q && q !== '*') {
|
||||
const searchRegex = { $regex: q, $options: 'i' }
|
||||
const orConditions = [
|
||||
{ description: searchRegex },
|
||||
{ userName: searchRegex },
|
||||
{ type: searchRegex },
|
||||
{ status: searchRegex },
|
||||
{ source: searchRegex },
|
||||
]
|
||||
|
||||
if (mongoose.Types.ObjectId.isValid(q)) {
|
||||
orConditions.push({ _id: q })
|
||||
orConditions.push({ propertyId: q })
|
||||
orConditions.push({ userId: q })
|
||||
}
|
||||
|
||||
mongoQuery.$or = orConditions
|
||||
}
|
||||
|
||||
if (inputQuery.type) mongoQuery.type = inputQuery.type
|
||||
if (inputQuery.status) mongoQuery.status = inputQuery.status
|
||||
if (inputQuery.source) mongoQuery.source = inputQuery.source
|
||||
if (inputQuery.propertyId && mongoose.Types.ObjectId.isValid(inputQuery.propertyId)) {
|
||||
mongoQuery.propertyId = inputQuery.propertyId
|
||||
}
|
||||
if (inputQuery.userId && mongoose.Types.ObjectId.isValid(inputQuery.userId)) {
|
||||
mongoQuery.userId = inputQuery.userId
|
||||
}
|
||||
|
||||
let sortObj = { createdAt: -1 }
|
||||
if (inputQuery.sort) {
|
||||
if (typeof inputQuery.sort === 'string') {
|
||||
const parts = inputQuery.sort.split(':')
|
||||
const field = parts[0]
|
||||
const order = parts[1] === 'asc' ? 1 : -1
|
||||
sortObj = { [field]: order }
|
||||
} else if (typeof inputQuery.sort === 'object') {
|
||||
sortObj = inputQuery.sort
|
||||
}
|
||||
}
|
||||
|
||||
const totalCount = await Transaction.countDocuments(mongoQuery)
|
||||
const transactions = await Transaction.find(mongoQuery)
|
||||
.populate('propertyId')
|
||||
.populate('userId')
|
||||
.sort(sortObj)
|
||||
.skip((page - 1) * per_page)
|
||||
.limit(per_page)
|
||||
|
||||
const items = transactions.map((t) => {
|
||||
return {
|
||||
_id: t._id.toString(),
|
||||
id: t._id.toString(),
|
||||
type: t.type || '',
|
||||
status: t.status || '',
|
||||
source: t.source || '',
|
||||
value: t.value || 0,
|
||||
description: t.description || '',
|
||||
createdAt: Math.floor(new Date(t.createdAt || t.date || Date.now()).getTime() / 1000),
|
||||
date: t.date,
|
||||
belongingName: t.propertyId?.name || '',
|
||||
belongingId: t.propertyId?._id ? t.propertyId._id.toString() : '',
|
||||
propertyId: t.propertyId,
|
||||
userName: t.userName || t.userId?.name || '',
|
||||
userId: t.userId,
|
||||
}
|
||||
})
|
||||
|
||||
const pagesCount = Math.ceil(totalCount / per_page) || 1
|
||||
|
||||
return {
|
||||
facets: [],
|
||||
transactions: items,
|
||||
totalCount,
|
||||
pagesCount,
|
||||
searchEngine: 'mongo',
|
||||
}
|
||||
}
|
||||
|
||||
const searchTransactions = async (inputQuery) => {
|
||||
inputQuery = updateInputQuery(inputQuery, {})
|
||||
try {
|
||||
const setting = await settingService.getSearchSettingByPage('transactions')
|
||||
if (setting && setting.searchMethod === 'mongo') {
|
||||
return searchTransactionsMongo(inputQuery)
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('Failed to fetch search setting for transactions, attempting typesense:', e.message)
|
||||
}
|
||||
|
||||
const tsFeatures = new TsApiFeatures(client, 'transactions', inputQuery).filter().facet().sort().limitFields().paginate().search()
|
||||
try {
|
||||
await ensureCollectionExists(false)
|
||||
const updatedQuery = updateInputQuery({ ...inputQuery }, {})
|
||||
|
||||
const tsFeatures = new TsApiFeatures(client, 'transactions', updatedQuery).filter().facet().sort().limitFields().paginate().search()
|
||||
|
||||
let { facets, items, totalCount, pagesCount } = await tsFeatures.execute()
|
||||
|
||||
return { facets, transactions: items, totalCount, pagesCount }
|
||||
return { facets, transactions: items, totalCount, pagesCount, searchEngine: 'typesense' }
|
||||
} catch (err) {
|
||||
console.warn('Typesense search failed for transactions, falling back to MongoDB:', err.message)
|
||||
return searchTransactionsMongo(inputQuery)
|
||||
}
|
||||
}
|
||||
|
||||
const updateInputQuery = (inputQuery, extraQueries, features) => {
|
||||
const updateInputQuery = (inputQuery, extraQueries) => {
|
||||
for (const [key, value] of Object.entries(extraQueries)) {
|
||||
inputQuery[key] = value
|
||||
}
|
||||
@@ -189,39 +290,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 }
|
||||
}
|
||||
@@ -255,4 +358,6 @@ module.exports = {
|
||||
getTransactionByBelongingId,
|
||||
indexAllTransactions,
|
||||
searchTransactions,
|
||||
searchTransactionsMongo,
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
const mongoose = require('mongoose')
|
||||
|
||||
const loginAttemptSchema = new mongoose.Schema(
|
||||
{
|
||||
key: {
|
||||
type: String,
|
||||
required: true,
|
||||
unique: true,
|
||||
index: true,
|
||||
},
|
||||
attempts: {
|
||||
type: Number,
|
||||
default: 0,
|
||||
},
|
||||
expiresAt: {
|
||||
type: Date,
|
||||
required: true,
|
||||
index: { expires: 0 },
|
||||
},
|
||||
},
|
||||
{ timestamps: true }
|
||||
)
|
||||
|
||||
const LoginAttempt = mongoose.model('LoginAttempt', loginAttemptSchema)
|
||||
|
||||
module.exports = LoginAttempt
|
||||
@@ -26,6 +26,11 @@ exports.loginUser = catchAsync(async (req, res, next) => {
|
||||
maxAge: maxAge * 1000,
|
||||
path: '/',
|
||||
})
|
||||
res.cookie('bm-token', token, {
|
||||
httpOnly: false,
|
||||
maxAge: maxAge * 1000,
|
||||
path: '/',
|
||||
})
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
@@ -34,20 +39,31 @@ exports.loginUser = catchAsync(async (req, res, next) => {
|
||||
})
|
||||
|
||||
exports.logoutUser = catchAsync(async (req, res, next) => {
|
||||
res.cookie('belonging_token', '', {
|
||||
httpOnly: true,
|
||||
maxAge: 0,
|
||||
path: '/',
|
||||
})
|
||||
const isProduction = process.env.NODE_ENV === 'production'
|
||||
|
||||
// Clear default host cookies
|
||||
res.clearCookie('belonging_token', { path: '/' })
|
||||
res.clearCookie('bm-token', { path: '/' })
|
||||
res.clearCookie('jwt', { path: '/' })
|
||||
|
||||
// Clear domain cookies if in production or mbmanager domain
|
||||
if (isProduction || req.hostname.includes('mbmanager.ir')) {
|
||||
res.clearCookie('belonging_token', { domain: '.mbmanager.ir', path: '/' })
|
||||
res.clearCookie('bm-token', { domain: '.mbmanager.ir', path: '/' })
|
||||
res.clearCookie('jwt', { domain: '.mbmanager.ir', path: '/' })
|
||||
}
|
||||
|
||||
res.cookie('belonging_token', '', { maxAge: 0, expires: new Date(0), path: '/' })
|
||||
res.cookie('bm-token', '', { maxAge: 0, expires: new Date(0), path: '/' })
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
message: 'کاربر خارج شد',
|
||||
message: 'کاربر با موفقیت خارج شد',
|
||||
})
|
||||
})
|
||||
|
||||
exports.getAllUsers = catchAsync(async (req, res, next) => {
|
||||
const users = await userService.getAllUsers()
|
||||
const users = await userService.getAllUsers(req.query)
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
@@ -56,6 +72,7 @@ exports.getAllUsers = catchAsync(async (req, res, next) => {
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
exports.userGetSelf = catchAsync(async (req, res, next) => {
|
||||
const user = req.user
|
||||
if (!user) {
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
const express = require('express')
|
||||
const userController = require('./userController')
|
||||
const loginCheck = require('../../middlewares/loginCheck')
|
||||
const perm = require('../../middlewares/permissionMiddleware')
|
||||
|
||||
const router = new express.Router()
|
||||
|
||||
@@ -12,18 +13,17 @@ router.post('/login-email', userController.loginUser)
|
||||
router.post('/logout', userController.logoutUser)
|
||||
|
||||
router.use(loginCheck.loginProtect)
|
||||
// router.use(loginCheck.adminProtect)
|
||||
|
||||
router.get('/user/get-self', userController.userGetSelf)
|
||||
|
||||
router.get('/', userController.getAllUsers)
|
||||
router.get('/', perm.requires('getallusers'), userController.getAllUsers)
|
||||
|
||||
router.get('/:userId', userController.getUser)
|
||||
router.get('/:userId', perm.requires('getuser'), userController.getUser)
|
||||
|
||||
router.post('/', userController.createUser)
|
||||
router.post('/', perm.requires('createuser'), userController.createUser)
|
||||
|
||||
router.patch('/:userId', userController.updateUser)
|
||||
router.patch('/:userId', perm.requires('updateuser'), userController.updateUser)
|
||||
|
||||
router.delete('/:userId', userController.deleteUser)
|
||||
router.delete('/:userId', perm.requires('deleteuser'), userController.deleteUser)
|
||||
|
||||
module.exports = router
|
||||
|
||||
+148
-44
@@ -1,7 +1,8 @@
|
||||
// userService.js
|
||||
const User = require('./userModel')
|
||||
const Role = require('../role/roleModel')
|
||||
const AppError = require('../../globalErrorHandler/AppError')
|
||||
const redisClient = require('../../setup/redis')
|
||||
const LoginAttempt = require('./loginAttemptModel')
|
||||
const jwt = require('jsonwebtoken')
|
||||
const bcrypt = require('bcryptjs')
|
||||
const maxAge = 60 * 60 * 24 * 90
|
||||
@@ -13,19 +14,19 @@ const signToken = (id) => {
|
||||
}
|
||||
|
||||
const signup = async (name, email, password, passwordConfirm) => {
|
||||
let userExist = await User.findOne({ email }, null, null)
|
||||
let userExist = await User.findOne({ email: email.toLowerCase().trim() }, null, null)
|
||||
|
||||
if (userExist) {
|
||||
throw new AppError('UserAlreadyExist', 500, {})
|
||||
throw new AppError('UserAlreadyExist', 400, {})
|
||||
}
|
||||
|
||||
if (password != passwordConfirm) throw new AppError('PasswordIncorrect', 401, {})
|
||||
if (password !== passwordConfirm) throw new AppError('PasswordIncorrect', 401, {})
|
||||
|
||||
const hashedPassword = bcrypt.hashSync(password, 10)
|
||||
|
||||
const user = await createUser({
|
||||
name,
|
||||
email,
|
||||
email: email.toLowerCase().trim(),
|
||||
password: hashedPassword,
|
||||
passwordConfirm: undefined,
|
||||
})
|
||||
@@ -44,39 +45,39 @@ const signup = async (name, email, password, passwordConfirm) => {
|
||||
}
|
||||
|
||||
const loginAttempt = async (phrase) => {
|
||||
const attemptExist = await redisClient.exists(phrase + '#attempts')
|
||||
const key = phrase + '#attempts'
|
||||
const limit = parseInt(process.env.LOGIN_ATTEMPT_LIMIT) || 10
|
||||
const ttlSeconds = 3600
|
||||
const now = new Date()
|
||||
|
||||
if (attemptExist === 0) {
|
||||
await redisClient.set(
|
||||
phrase + '#attempts',
|
||||
0,
|
||||
{
|
||||
EX: 3600,
|
||||
},
|
||||
null
|
||||
)
|
||||
let attemptRecord = await LoginAttempt.findOne({ key })
|
||||
|
||||
if (attemptRecord && attemptRecord.expiresAt <= now) {
|
||||
await LoginAttempt.deleteOne({ _id: attemptRecord._id })
|
||||
attemptRecord = null
|
||||
}
|
||||
|
||||
// if user phrase(email or phone) exist return error with expire time left for login
|
||||
if (parseInt(await redisClient.get(phrase + '#attempts')) >= parseInt(process.env.LOGIN_ATTEMPT_LIMIT)) {
|
||||
const limitTime = await redisClient.ttl(phrase + '#attempts')
|
||||
if (!attemptRecord) {
|
||||
const expiresAt = new Date(Date.now() + ttlSeconds * 1000)
|
||||
await LoginAttempt.create({
|
||||
key,
|
||||
attempts: 0,
|
||||
expiresAt,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (attemptRecord.attempts >= limit) {
|
||||
const limitTime = Math.max(0, Math.ceil((attemptRecord.expiresAt.getTime() - Date.now()) / 1000))
|
||||
const minutes = (limitTime / 60).toFixed(0)
|
||||
throw new AppError('MaximumLoginReached', 500, {
|
||||
minutes,
|
||||
})
|
||||
}
|
||||
|
||||
if (attemptExist === 1) {
|
||||
const attempts = parseInt(await redisClient.get(phrase + '#attempts'))
|
||||
await redisClient.set(
|
||||
phrase + '#attempts',
|
||||
attempts + 1 + '',
|
||||
{
|
||||
EX: 3600,
|
||||
},
|
||||
null
|
||||
)
|
||||
}
|
||||
attemptRecord.attempts += 1
|
||||
attemptRecord.expiresAt = new Date(Date.now() + ttlSeconds * 1000)
|
||||
await attemptRecord.save()
|
||||
}
|
||||
|
||||
const loginUser = async (email, password) => {
|
||||
@@ -84,56 +85,159 @@ const loginUser = async (email, password) => {
|
||||
throw new AppError('ProvideEmailAndPassword', 400)
|
||||
}
|
||||
|
||||
const user = await User.findOne({ email }, null, null).select('+password')
|
||||
const inputPhrase = email.toLowerCase().trim()
|
||||
|
||||
if (email) {
|
||||
await loginAttempt(email)
|
||||
// ─── 1) Environment-based Super Admin Authentication ────────────────────
|
||||
const superAdminEnabled = process.env.SUPER_ADMIN_ENABLED !== 'false'
|
||||
const superAdminEmail = (process.env.SUPER_ADMIN_EMAIL || process.env.SUPER_ADMIN_USERNAME || 'superadmin@mbmanager.ir').toLowerCase().trim()
|
||||
const superAdminUsername = (process.env.SUPER_ADMIN_USERNAME || 'superadmin').toLowerCase().trim()
|
||||
const superAdminPassword = process.env.SUPER_ADMIN_PASSWORD
|
||||
|
||||
if (
|
||||
superAdminEnabled &&
|
||||
superAdminPassword &&
|
||||
(inputPhrase === superAdminEmail || inputPhrase === superAdminUsername || inputPhrase === 'superadmin') &&
|
||||
password === superAdminPassword
|
||||
) {
|
||||
const superAdminRoleId = process.env.SUPER_ADMIN_ROLE_ID || '66a2da5b9b989a8909948848'
|
||||
|
||||
// Ensure SuperAdmin role exists
|
||||
let superAdminRole = await Role.findById(superAdminRoleId)
|
||||
if (!superAdminRole) {
|
||||
superAdminRole = await Role.findOne({ englishName: 'SuperAdmin' })
|
||||
}
|
||||
if (!superAdminRole) {
|
||||
superAdminRole = await Role.create({
|
||||
_id: superAdminRoleId,
|
||||
englishName: 'SuperAdmin',
|
||||
nativeName: 'ادمین اصلی',
|
||||
permissions: [],
|
||||
isActive: true,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure SuperAdmin user exists in DB
|
||||
let superAdminUser = await User.findOne({
|
||||
$or: [{ email: superAdminEmail }, { _id: '66ddb52302f30f105de39e61' }],
|
||||
})
|
||||
|
||||
if (!superAdminUser) {
|
||||
superAdminUser = await User.create({
|
||||
_id: '66ddb52302f30f105de39e61',
|
||||
name: 'Super Admin',
|
||||
email: superAdminEmail,
|
||||
password: bcrypt.hashSync(superAdminPassword, 10),
|
||||
role: superAdminRole._id,
|
||||
isAdmin: true,
|
||||
isActive: true,
|
||||
})
|
||||
} else {
|
||||
superAdminUser.isAdmin = true
|
||||
superAdminUser.role = superAdminRole._id
|
||||
superAdminUser.isActive = true
|
||||
await superAdminUser.save()
|
||||
}
|
||||
|
||||
const populatedUser = await User.findById(superAdminUser._id).populate('role')
|
||||
return { token: signToken(populatedUser._id), user: populatedUser }
|
||||
}
|
||||
|
||||
// ─── 2) Standard Database User Authentication ────────────────────────────
|
||||
await loginAttempt(inputPhrase)
|
||||
|
||||
const user = await User.findOne({ email: inputPhrase }, null, null).select('+password').populate('role')
|
||||
|
||||
if (!user || !(await bcrypt.compare(password, user.password))) {
|
||||
throw new AppError('IncorrectEmailOrPassword', 401, {})
|
||||
}
|
||||
|
||||
// set user password to undefined before sending data
|
||||
if (user.isActive === false) {
|
||||
throw new AppError('UserIsInactive', 403, {})
|
||||
}
|
||||
|
||||
user.password = undefined
|
||||
return { token: signToken(user._id), user }
|
||||
}
|
||||
|
||||
const getAllUsers = async () => {
|
||||
const users = await User.find({}, null, null)
|
||||
|
||||
return users
|
||||
const getAllUsers = async (query = {}) => {
|
||||
const mongoQuery = {}
|
||||
const search = (query.search || query.query || '').trim()
|
||||
if (search) {
|
||||
mongoQuery.$or = [
|
||||
{ name: { $regex: search, $options: 'i' } },
|
||||
{ email: { $regex: search, $options: 'i' } },
|
||||
]
|
||||
}
|
||||
return User.find(mongoQuery).populate('role').sort({ createdAt: -1 })
|
||||
}
|
||||
|
||||
|
||||
const getUser = async (userId) => {
|
||||
const user = await User.findById({ _id: userId }, null, null)
|
||||
const user = await User.findById(userId).populate('role')
|
||||
|
||||
if (!user) {
|
||||
throw AppError('NoUserFound', 404, {})
|
||||
throw new AppError('NoUserFound', 404, {})
|
||||
}
|
||||
|
||||
return user
|
||||
}
|
||||
|
||||
const createUser = async (data) => {
|
||||
return User.create(data, null)
|
||||
if (!data.email || !data.password || !data.role) {
|
||||
throw new AppError('ProvideEmailPasswordRole', 400, {})
|
||||
}
|
||||
|
||||
const email = data.email.toLowerCase().trim()
|
||||
const existing = await User.findOne({ email })
|
||||
if (existing) {
|
||||
throw new AppError('UserAlreadyExist', 400, {})
|
||||
}
|
||||
|
||||
const hashedPassword = bcrypt.hashSync(data.password, 10)
|
||||
|
||||
const user = await User.create({
|
||||
name: data.name,
|
||||
email,
|
||||
password: hashedPassword,
|
||||
role: data.role,
|
||||
isAdmin: data.isAdmin || false,
|
||||
isActive: data.isActive !== undefined ? data.isActive : true,
|
||||
})
|
||||
|
||||
return User.findById(user._id).populate('role')
|
||||
}
|
||||
|
||||
const updateUser = async (userId, data) => {
|
||||
const user = await User.findOneAndUpdate({ _id: userId }, data, { new: true })
|
||||
const updateData = { ...data }
|
||||
|
||||
if (updateData.email) {
|
||||
updateData.email = updateData.email.toLowerCase().trim()
|
||||
const existing = await User.findOne({ email: updateData.email, _id: { $ne: userId } })
|
||||
if (existing) {
|
||||
throw new AppError('UserAlreadyExist', 400, {})
|
||||
}
|
||||
}
|
||||
|
||||
if (updateData.password && updateData.password.trim().length > 0) {
|
||||
updateData.password = bcrypt.hashSync(updateData.password, 10)
|
||||
} else {
|
||||
delete updateData.password
|
||||
}
|
||||
|
||||
const user = await User.findOneAndUpdate({ _id: userId }, updateData, { new: true }).populate('role')
|
||||
|
||||
if (!user) {
|
||||
throw AppError('NoUserFound', 404, {})
|
||||
throw new AppError('NoUserFound', 404, {})
|
||||
}
|
||||
|
||||
return user
|
||||
}
|
||||
|
||||
const deleteUser = async (userId) => {
|
||||
const user = await User.findOneAndDelete({ _id: userId })
|
||||
const user = await User.findByIdAndUpdate(userId, { isActive: false }, { new: true })
|
||||
|
||||
if (!user) {
|
||||
throw AppError('NoUserFound', 404, {})
|
||||
throw new AppError('NoUserFound', 404, {})
|
||||
}
|
||||
|
||||
return null
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
const catchAsync = require('../../globalErrorHandler/catchAsync')
|
||||
const warehouseService = require('./warehouseService')
|
||||
|
||||
exports.createWarehouse = catchAsync(async (req, res, next) => {
|
||||
const warehouse = await warehouseService.createWarehouse(req.body)
|
||||
res.status(201).json({ status: 'success', data: warehouse })
|
||||
})
|
||||
|
||||
exports.listWarehouses = catchAsync(async (req, res, next) => {
|
||||
const warehouses = await warehouseService.listWarehouses(req.query)
|
||||
res.status(200).json({ status: 'success', results: warehouses.length, data: warehouses })
|
||||
})
|
||||
|
||||
exports.getWarehouse = catchAsync(async (req, res, next) => {
|
||||
const warehouse = await warehouseService.getWarehouse(req.params.warehouseId)
|
||||
res.status(200).json({ status: 'success', data: warehouse })
|
||||
})
|
||||
|
||||
exports.updateWarehouse = catchAsync(async (req, res, next) => {
|
||||
const warehouse = await warehouseService.updateWarehouse(req.params.warehouseId, req.body)
|
||||
res.status(200).json({ status: 'success', data: warehouse })
|
||||
})
|
||||
|
||||
exports.deleteWarehouse = catchAsync(async (req, res, next) => {
|
||||
await warehouseService.deleteWarehouse(req.params.warehouseId)
|
||||
res.status(200).json({ status: 'success', data: null })
|
||||
})
|
||||
@@ -0,0 +1,34 @@
|
||||
const mongoose = require('mongoose')
|
||||
const ObjectID = mongoose.Schema.Types.ObjectId
|
||||
|
||||
const warehouseSchema = new mongoose.Schema(
|
||||
{
|
||||
name: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
code: {
|
||||
type: String,
|
||||
unique: true,
|
||||
},
|
||||
location: {
|
||||
address: String,
|
||||
coordinates: [Number], // [long, lat]
|
||||
},
|
||||
manager: {
|
||||
type: ObjectID,
|
||||
ref: 'User',
|
||||
},
|
||||
description: String,
|
||||
isActive: {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
}
|
||||
)
|
||||
|
||||
const Warehouse = mongoose.model('Warehouse', warehouseSchema)
|
||||
module.exports = Warehouse
|
||||
@@ -0,0 +1,15 @@
|
||||
const express = require('express')
|
||||
const warehouseController = require('./warehouseController')
|
||||
const loginCheck = require('../../middlewares/loginCheck')
|
||||
|
||||
const router = new express.Router()
|
||||
|
||||
router.use(loginCheck.loginProtect)
|
||||
|
||||
router.get('/admin/get-all', warehouseController.listWarehouses)
|
||||
router.post('/admin/create', warehouseController.createWarehouse)
|
||||
router.get('/admin/get-one/:warehouseId', warehouseController.getWarehouse)
|
||||
router.patch('/admin/update/:warehouseId', warehouseController.updateWarehouse)
|
||||
router.delete('/admin/delete/:warehouseId', warehouseController.deleteWarehouse)
|
||||
|
||||
module.exports = router
|
||||
@@ -0,0 +1,176 @@
|
||||
const Warehouse = require('./warehouseModel')
|
||||
const WarehouseItem = require('../warehouseItem/warehouseItemModel')
|
||||
const WarehouseItemTransaction = require('../warehouseItem/warehouseItemTransactionModel')
|
||||
const WarehouseItemStock = require('../warehouseItem/warehouseItemStockModel')
|
||||
const User = require('../user/userModel')
|
||||
const chalk = require('chalk')
|
||||
|
||||
const runSeeder = async () => {
|
||||
// 1. Find or create admin user for actor
|
||||
const adminUser = await User.findOne({ email: 'superadmin@mbmanager.ir' }) || await User.findOne()
|
||||
|
||||
// 2. Warehouses
|
||||
const sampleWarehouses = [
|
||||
{
|
||||
name: 'انبار مرکزی تهران',
|
||||
code: 'WH-TEH-01',
|
||||
location: 'تهران، جاده مخصوص کرج، کیلومتر ۱۱',
|
||||
description: 'انبار اصلی مصالح ساختمانی و تجهیزات مکانیکی',
|
||||
isActive: true,
|
||||
},
|
||||
{
|
||||
name: 'انبار پروژه نیاوران',
|
||||
code: 'WH-NYA-02',
|
||||
location: 'تهران، نیاوران، خیابان باهنر',
|
||||
description: 'انبار پای کار پروژه برج یاس',
|
||||
isActive: true,
|
||||
},
|
||||
{
|
||||
name: 'انبار مصالح اصفهان',
|
||||
code: 'WH-ISF-01',
|
||||
location: 'اصفهان، شهرک صنعتی جی',
|
||||
description: 'انبار پشتیبانی پروژههای مرکزی',
|
||||
isActive: true,
|
||||
},
|
||||
]
|
||||
|
||||
const createdWarehouses = []
|
||||
for (const wh of sampleWarehouses) {
|
||||
let doc = await Warehouse.findOne({ name: wh.name })
|
||||
if (!doc) {
|
||||
doc = await Warehouse.create(wh)
|
||||
}
|
||||
createdWarehouses.push(doc)
|
||||
}
|
||||
|
||||
// 3. Warehouse Items
|
||||
const sampleItems = [
|
||||
{
|
||||
nameFa: 'سیمان تیپ ۲ (کیسه ۵۰ کیلویی)',
|
||||
nameEn: 'Cement Type 2 (50kg)',
|
||||
code: 'CEM-T2-50',
|
||||
unitFa: 'کیسه',
|
||||
unitEn: 'Bag',
|
||||
category: 'مصالح پایه',
|
||||
description: 'سیمان پرتلند تیپ ۲ استاندارد',
|
||||
},
|
||||
{
|
||||
nameFa: 'میلگرد آجدار سایز ۱۶ (A3)',
|
||||
nameEn: 'Rebar A3 Size 16',
|
||||
code: 'REB-16-A3',
|
||||
unitFa: 'شاخه',
|
||||
unitEn: 'Piece',
|
||||
category: 'آهن آلات',
|
||||
description: 'میلگرد شاخه ۱۲ متری فولاد مبارکه',
|
||||
},
|
||||
{
|
||||
nameFa: 'سرامیک پرسلان ۶۰*۱۲۰',
|
||||
nameEn: 'Porcelain Tile 60x120',
|
||||
code: 'TIL-60120-P',
|
||||
unitFa: 'مترمربع',
|
||||
unitEn: 'Sqm',
|
||||
category: 'نازککاری',
|
||||
description: 'سرامیک درجه یک کالیبره مات',
|
||||
},
|
||||
{
|
||||
nameFa: 'لوله پلیاتیلن سایز ۶۳',
|
||||
nameEn: 'PE Pipe Size 63',
|
||||
code: 'PIP-PE-63',
|
||||
unitFa: 'متر',
|
||||
unitEn: 'Meter',
|
||||
category: 'تأسیسات مکانیکی',
|
||||
description: 'لوله آبرسانی ۱۰ بار استاندارد',
|
||||
},
|
||||
{
|
||||
nameFa: 'رنگ اکریلیک پایه آب (حلب ۲۰ لیتری)',
|
||||
nameEn: 'Acrylic Paint 20L',
|
||||
code: 'PNT-ACR-20L',
|
||||
unitFa: 'حلب',
|
||||
unitEn: 'Can',
|
||||
category: 'رنگ و نقاشی',
|
||||
description: 'رنگ مات قابل شستشو درجه یک',
|
||||
},
|
||||
]
|
||||
|
||||
const createdItems = []
|
||||
for (const it of sampleItems) {
|
||||
let doc = await WarehouseItem.findOne({ code: it.code })
|
||||
if (!doc) {
|
||||
doc = await WarehouseItem.create(it)
|
||||
}
|
||||
createdItems.push(doc)
|
||||
}
|
||||
|
||||
// 4. Sample Transactions
|
||||
const txCount = await WarehouseItemTransaction.countDocuments()
|
||||
if (txCount === 0 && adminUser && createdWarehouses.length > 0 && createdItems.length > 0) {
|
||||
const sampleTransactions = [
|
||||
{
|
||||
item: createdItems[0]._id,
|
||||
warehouse: createdWarehouses[0]._id,
|
||||
type: 'IN',
|
||||
quantity: 500,
|
||||
unit: createdItems[0].unitFa,
|
||||
reason: 'خرید مستقیم از کارخانه سیمان تهران',
|
||||
actor: adminUser._id,
|
||||
actorName: adminUser.name || 'مدیر سیستم',
|
||||
note: 'بارگیری از کارخانه با فاکتور شماره ۱۲۸۹',
|
||||
},
|
||||
{
|
||||
item: createdItems[1]._id,
|
||||
warehouse: createdWarehouses[0]._id,
|
||||
type: 'IN',
|
||||
quantity: 120,
|
||||
unit: createdItems[1].unitFa,
|
||||
reason: 'تأمین آهنآلات اسکلت سازه',
|
||||
actor: adminUser._id,
|
||||
actorName: adminUser.name || 'مدیر سیستم',
|
||||
},
|
||||
{
|
||||
item: createdItems[0]._id,
|
||||
warehouse: createdWarehouses[1]._id,
|
||||
type: 'OUT',
|
||||
quantity: 80,
|
||||
unit: createdItems[0].unitFa,
|
||||
reason: 'مصرف در بتنریزی سقف طبقه پنجم',
|
||||
actor: adminUser._id,
|
||||
actorName: adminUser.name || 'مدیر سیستم',
|
||||
},
|
||||
{
|
||||
item: createdItems[2]._id,
|
||||
warehouse: createdWarehouses[0]._id,
|
||||
type: 'IN',
|
||||
quantity: 350,
|
||||
unit: createdItems[2].unitFa,
|
||||
reason: 'خرید مصالح نازککاری',
|
||||
actor: adminUser._id,
|
||||
actorName: adminUser.name || 'مدیر سیستم',
|
||||
},
|
||||
{
|
||||
item: createdItems[3]._id,
|
||||
warehouse: createdWarehouses[1]._id,
|
||||
type: 'IN',
|
||||
quantity: 200,
|
||||
unit: createdItems[3].unitFa,
|
||||
reason: 'تجهیز تأسیسات لولهکشی آب',
|
||||
actor: adminUser._id,
|
||||
actorName: adminUser.name || 'مدیر سیستم',
|
||||
},
|
||||
]
|
||||
|
||||
for (const tx of sampleTransactions) {
|
||||
await WarehouseItemTransaction.create(tx)
|
||||
|
||||
// Update or create stock
|
||||
const delta = tx.type === 'IN' ? tx.quantity : -tx.quantity
|
||||
await WarehouseItemStock.findOneAndUpdate(
|
||||
{ item: tx.item, warehouse: tx.warehouse },
|
||||
{ $inc: { quantity: delta } },
|
||||
{ upsert: true, new: true }
|
||||
)
|
||||
}
|
||||
console.log(chalk.green.bold(`WAREHOUSE: Created ${sampleTransactions.length} sample inventory transactions`))
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { runSeeder }
|
||||
@@ -0,0 +1,62 @@
|
||||
const Warehouse = require('./warehouseModel')
|
||||
const AppError = require('../../globalErrorHandler/AppError')
|
||||
|
||||
const createWarehouse = async (data) => {
|
||||
const warehouse = await Warehouse.create({
|
||||
name: data.name,
|
||||
code: data.code || undefined,
|
||||
location: data.location,
|
||||
manager: data.manager,
|
||||
description: data.description,
|
||||
})
|
||||
return warehouse
|
||||
}
|
||||
|
||||
const listWarehouses = async (query = {}) => {
|
||||
const filter = {}
|
||||
if (query.isActive !== undefined) filter.isActive = query.isActive === 'true'
|
||||
if (query.search) {
|
||||
filter.$or = [
|
||||
{ name: { $regex: query.search, $options: 'i' } },
|
||||
{ code: { $regex: query.search, $options: 'i' } },
|
||||
]
|
||||
}
|
||||
|
||||
const warehouses = await Warehouse.find(filter)
|
||||
.populate('manager', 'name email')
|
||||
.sort({ createdAt: -1 })
|
||||
|
||||
return warehouses
|
||||
}
|
||||
|
||||
const getWarehouse = async (warehouseId) => {
|
||||
const warehouse = await Warehouse.findById(warehouseId).populate('manager', 'name email')
|
||||
if (!warehouse) throw new AppError('انبار یافت نشد', 404, {})
|
||||
return warehouse
|
||||
}
|
||||
|
||||
const updateWarehouse = async (warehouseId, data) => {
|
||||
const allowed = ['name', 'code', 'location', 'manager', 'description', 'isActive']
|
||||
const update = {}
|
||||
allowed.forEach((field) => {
|
||||
if (data[field] !== undefined) update[field] = data[field]
|
||||
})
|
||||
|
||||
const warehouse = await Warehouse.findByIdAndUpdate(warehouseId, update, { new: true, runValidators: true })
|
||||
if (!warehouse) throw new AppError('انبار یافت نشد', 404, {})
|
||||
return warehouse
|
||||
}
|
||||
|
||||
const deleteWarehouse = async (warehouseId) => {
|
||||
const warehouse = await Warehouse.findByIdAndUpdate(warehouseId, { isActive: false }, { new: true })
|
||||
if (!warehouse) throw new AppError('انبار یافت نشد', 404, {})
|
||||
return warehouse
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
createWarehouse,
|
||||
listWarehouses,
|
||||
getWarehouse,
|
||||
updateWarehouse,
|
||||
deleteWarehouse,
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
const catchAsync = require('../../globalErrorHandler/catchAsync')
|
||||
const warehouseItemService = require('./warehouseItemService')
|
||||
|
||||
// ─── ITEMS ────────────────────────────────────────────────────────────────────
|
||||
|
||||
exports.createItem = catchAsync(async (req, res, next) => {
|
||||
const item = await warehouseItemService.createItem(req.body)
|
||||
res.status(201).json({ status: 'success', data: item })
|
||||
})
|
||||
|
||||
exports.listItems = catchAsync(async (req, res, next) => {
|
||||
const result = await warehouseItemService.listItems(req.query)
|
||||
res.status(200).json({ status: 'success', ...result })
|
||||
})
|
||||
|
||||
exports.getItem = catchAsync(async (req, res, next) => {
|
||||
const item = await warehouseItemService.getItem(req.params.itemId)
|
||||
res.status(200).json({ status: 'success', data: item })
|
||||
})
|
||||
|
||||
exports.updateItem = catchAsync(async (req, res, next) => {
|
||||
const item = await warehouseItemService.updateItem(req.params.itemId, req.body)
|
||||
res.status(200).json({ status: 'success', data: item })
|
||||
})
|
||||
|
||||
exports.deleteItem = catchAsync(async (req, res, next) => {
|
||||
await warehouseItemService.deleteItem(req.params.itemId)
|
||||
res.status(200).json({ status: 'success', data: null })
|
||||
})
|
||||
|
||||
// ─── TRANSACTIONS ─────────────────────────────────────────────────────────────
|
||||
|
||||
exports.createTransaction = catchAsync(async (req, res, next) => {
|
||||
const transaction = await warehouseItemService.createTransaction(req.body, req.user)
|
||||
res.status(201).json({ status: 'success', data: transaction })
|
||||
})
|
||||
|
||||
exports.listTransactions = catchAsync(async (req, res, next) => {
|
||||
const result = await warehouseItemService.listTransactions(req.query)
|
||||
res.status(200).json({ status: 'success', ...result })
|
||||
})
|
||||
|
||||
exports.deleteTransaction = catchAsync(async (req, res, next) => {
|
||||
await warehouseItemService.deleteTransaction(req.params.transactionId)
|
||||
res.status(200).json({ status: 'success', data: null })
|
||||
})
|
||||
|
||||
// ─── STOCK ────────────────────────────────────────────────────────────────────
|
||||
|
||||
exports.getStockByItem = catchAsync(async (req, res, next) => {
|
||||
const result = await warehouseItemService.getStockByItem(req.params.itemId)
|
||||
res.status(200).json({ status: 'success', data: result })
|
||||
})
|
||||
|
||||
exports.getStockByWarehouse = catchAsync(async (req, res, next) => {
|
||||
const stocks = await warehouseItemService.getStockByWarehouse(req.params.warehouseId)
|
||||
res.status(200).json({ status: 'success', results: stocks.length, data: stocks })
|
||||
})
|
||||
|
||||
exports.getTotalStock = catchAsync(async (req, res, next) => {
|
||||
const result = await warehouseItemService.getTotalStock()
|
||||
res.status(200).json({ status: 'success', results: result.length, data: result })
|
||||
})
|
||||
@@ -0,0 +1,43 @@
|
||||
const mongoose = require('mongoose')
|
||||
|
||||
const warehouseItemSchema = new mongoose.Schema(
|
||||
{
|
||||
nameFa: {
|
||||
type: String,
|
||||
required: true, // نام فارسی — مثال: سیمان، آجر
|
||||
},
|
||||
nameEn: {
|
||||
type: String,
|
||||
required: true, // English name — e.g. Cement, Brick
|
||||
},
|
||||
code: {
|
||||
type: String,
|
||||
unique: true,
|
||||
sparse: true, // optional unique code, e.g. CEM, BRK
|
||||
},
|
||||
unitFa: {
|
||||
type: String,
|
||||
required: true, // واحد شمارش فارسی — مثال: تن، عدد، متر
|
||||
},
|
||||
unitEn: {
|
||||
type: String,
|
||||
required: true, // English counting unit — e.g. Ton, Piece, Meter
|
||||
},
|
||||
category: {
|
||||
type: String, // e.g. "مصالح ساختمانی", "تأسیسات"
|
||||
},
|
||||
description: String,
|
||||
isActive: {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
}
|
||||
)
|
||||
|
||||
warehouseItemSchema.index({ nameFa: 'text', nameEn: 'text', code: 'text' })
|
||||
|
||||
const WarehouseItem = mongoose.model('WarehouseItem', warehouseItemSchema)
|
||||
module.exports = WarehouseItem
|
||||
@@ -0,0 +1,26 @@
|
||||
const express = require('express')
|
||||
const warehouseItemController = require('./warehouseItemController')
|
||||
const loginCheck = require('../../middlewares/loginCheck')
|
||||
|
||||
const router = new express.Router()
|
||||
|
||||
router.use(loginCheck.loginProtect)
|
||||
|
||||
// ─── Items ────────────────────────────────────────────────────────────────────
|
||||
router.get('/admin/items', warehouseItemController.listItems)
|
||||
router.post('/admin/items', warehouseItemController.createItem)
|
||||
router.get('/admin/items/:itemId', warehouseItemController.getItem)
|
||||
router.patch('/admin/items/:itemId', warehouseItemController.updateItem)
|
||||
router.delete('/admin/items/:itemId', warehouseItemController.deleteItem)
|
||||
|
||||
// ─── Transactions ─────────────────────────────────────────────────────────────
|
||||
router.get('/admin/transactions', warehouseItemController.listTransactions)
|
||||
router.post('/admin/transactions', warehouseItemController.createTransaction)
|
||||
router.delete('/admin/transactions/:transactionId', warehouseItemController.deleteTransaction)
|
||||
|
||||
// ─── Stock ────────────────────────────────────────────────────────────────────
|
||||
router.get('/admin/stock/total', warehouseItemController.getTotalStock)
|
||||
router.get('/admin/stock/by-item/:itemId', warehouseItemController.getStockByItem)
|
||||
router.get('/admin/stock/by-warehouse/:warehouseId', warehouseItemController.getStockByWarehouse)
|
||||
|
||||
module.exports = router
|
||||
@@ -0,0 +1,267 @@
|
||||
const WarehouseItem = require('./warehouseItemModel')
|
||||
const WarehouseItemTransaction = require('./warehouseItemTransactionModel')
|
||||
const WarehouseItemStock = require('./warehouseItemStockModel')
|
||||
const AppError = require('../../globalErrorHandler/AppError')
|
||||
const mongoose = require('mongoose')
|
||||
|
||||
// ─── ITEM CRUD ────────────────────────────────────────────────────────────────
|
||||
|
||||
const createItem = async (data) => {
|
||||
const item = await WarehouseItem.create({
|
||||
nameFa: data.nameFa,
|
||||
nameEn: data.nameEn,
|
||||
code: data.code || undefined,
|
||||
unitFa: data.unitFa,
|
||||
unitEn: data.unitEn,
|
||||
category: data.category,
|
||||
description: data.description,
|
||||
})
|
||||
return item
|
||||
}
|
||||
|
||||
const listItems = async (query = {}) => {
|
||||
const page = parseInt(query.page) || 1
|
||||
const limit = parseInt(query.limit) || 50
|
||||
const skip = (page - 1) * limit
|
||||
|
||||
const filter = {}
|
||||
if (query.search) {
|
||||
filter.$or = [
|
||||
{ nameFa: { $regex: query.search, $options: 'i' } },
|
||||
{ nameEn: { $regex: query.search, $options: 'i' } },
|
||||
{ code: { $regex: query.search, $options: 'i' } },
|
||||
]
|
||||
}
|
||||
if (query.category) filter.category = query.category
|
||||
if (query.isActive !== undefined) filter.isActive = query.isActive === 'true'
|
||||
|
||||
const [items, total] = await Promise.all([
|
||||
WarehouseItem.find(filter).sort({ createdAt: -1 }).skip(skip).limit(limit),
|
||||
WarehouseItem.countDocuments(filter),
|
||||
])
|
||||
|
||||
return { items, total, page, limit, pages: Math.ceil(total / limit) }
|
||||
}
|
||||
|
||||
const getItem = async (itemId) => {
|
||||
const item = await WarehouseItem.findById(itemId)
|
||||
if (!item) throw new AppError('آیتم انبار یافت نشد', 404, {})
|
||||
return item
|
||||
}
|
||||
|
||||
const updateItem = async (itemId, data) => {
|
||||
const allowed = ['nameFa', 'nameEn', 'code', 'unitFa', 'unitEn', 'category', 'description', 'isActive']
|
||||
const update = {}
|
||||
allowed.forEach((field) => {
|
||||
if (data[field] !== undefined) update[field] = data[field]
|
||||
})
|
||||
|
||||
const item = await WarehouseItem.findByIdAndUpdate(itemId, update, { new: true, runValidators: true })
|
||||
if (!item) throw new AppError('آیتم انبار یافت نشد', 404, {})
|
||||
return item
|
||||
}
|
||||
|
||||
const deleteItem = async (itemId) => {
|
||||
const item = await WarehouseItem.findByIdAndUpdate(itemId, { isActive: false }, { new: true })
|
||||
if (!item) throw new AppError('آیتم انبار یافت نشد', 404, {})
|
||||
return item
|
||||
}
|
||||
|
||||
// ─── TRANSACTIONS ─────────────────────────────────────────────────────────────
|
||||
|
||||
const createTransaction = async (data, user) => {
|
||||
const { itemId, warehouseId, type, quantity, reason, note, date } = data
|
||||
|
||||
if (!itemId || !warehouseId || !type || !quantity || !reason) {
|
||||
throw new AppError('اطلاعات ناقص است', 400, {})
|
||||
}
|
||||
|
||||
const item = await WarehouseItem.findById(itemId)
|
||||
if (!item) throw new AppError('آیتم انبار یافت نشد', 404, {})
|
||||
if (!item.isActive) throw new AppError('این آیتم غیرفعال است', 400, {})
|
||||
|
||||
const qty = parseFloat(quantity)
|
||||
if (isNaN(qty) || qty <= 0) throw new AppError('مقدار باید عدد مثبت باشد', 400, {})
|
||||
|
||||
// Prevent negative stock on OUT
|
||||
if (type === 'OUT') {
|
||||
const stock = await WarehouseItemStock.findOne({ item: itemId, warehouse: warehouseId })
|
||||
const currentQty = stock ? stock.quantity : 0
|
||||
if (currentQty < qty) {
|
||||
throw new AppError(
|
||||
`موجودی کافی نیست. موجودی فعلی: ${currentQty} ${item.unitFa}`,
|
||||
400,
|
||||
{ currentQuantity: currentQty, requestedQuantity: qty }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Create the transaction record
|
||||
const transaction = await WarehouseItemTransaction.create({
|
||||
item: itemId,
|
||||
warehouse: warehouseId,
|
||||
type,
|
||||
quantity: qty,
|
||||
unit: item.unitFa,
|
||||
unitEn: item.unitEn,
|
||||
reason,
|
||||
actor: user._id,
|
||||
actorName: user.name,
|
||||
note,
|
||||
date: date || Date.now(),
|
||||
})
|
||||
|
||||
// Update the stock snapshot atomically
|
||||
const delta = type === 'IN' ? qty : -qty
|
||||
await WarehouseItemStock.findOneAndUpdate(
|
||||
{ item: itemId, warehouse: warehouseId },
|
||||
{
|
||||
$inc: { quantity: delta },
|
||||
$set: { unit: item.unitFa, unitEn: item.unitEn },
|
||||
},
|
||||
{ upsert: true, new: true }
|
||||
)
|
||||
|
||||
return transaction
|
||||
}
|
||||
|
||||
const listTransactions = async (query = {}) => {
|
||||
const page = parseInt(query.page) || 1
|
||||
const limit = parseInt(query.limit) || 50
|
||||
const skip = (page - 1) * limit
|
||||
|
||||
const filter = {}
|
||||
if (query.itemId) filter.item = query.itemId
|
||||
if (query.warehouseId) filter.warehouse = query.warehouseId
|
||||
if (query.type) filter.type = query.type
|
||||
if (query.actorId) filter.actor = query.actorId
|
||||
if (query.dateFrom || query.dateTo) {
|
||||
filter.date = {}
|
||||
if (query.dateFrom) filter.date.$gte = new Date(query.dateFrom)
|
||||
if (query.dateTo) filter.date.$lte = new Date(query.dateTo)
|
||||
}
|
||||
|
||||
const [transactions, total] = await Promise.all([
|
||||
WarehouseItemTransaction.find(filter)
|
||||
.sort({ date: -1 })
|
||||
.skip(skip)
|
||||
.limit(limit)
|
||||
.populate('item', 'nameFa nameEn code unitFa unitEn')
|
||||
.populate('warehouse', 'name code location')
|
||||
.populate('actor', 'name email'),
|
||||
WarehouseItemTransaction.countDocuments(filter),
|
||||
])
|
||||
|
||||
return { transactions, total, page, limit, pages: Math.ceil(total / limit) }
|
||||
}
|
||||
|
||||
const deleteTransaction = async (transactionId) => {
|
||||
const transaction = await WarehouseItemTransaction.findById(transactionId)
|
||||
if (!transaction) throw new AppError('تراکنش یافت نشد', 404, {})
|
||||
|
||||
// Reverse the stock effect
|
||||
const delta = transaction.type === 'IN' ? -transaction.quantity : transaction.quantity
|
||||
|
||||
// Check if reversal would cause negative stock (for IN reversals)
|
||||
if (transaction.type === 'IN') {
|
||||
const stock = await WarehouseItemStock.findOne({
|
||||
item: transaction.item,
|
||||
warehouse: transaction.warehouse,
|
||||
})
|
||||
const currentQty = stock ? stock.quantity : 0
|
||||
if (currentQty < transaction.quantity) {
|
||||
throw new AppError(
|
||||
'حذف این تراکنش ممکن نیست: موجودی کافی برای برگشت وجود ندارد',
|
||||
400,
|
||||
{ currentQuantity: currentQty }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
await WarehouseItemStock.findOneAndUpdate(
|
||||
{ item: transaction.item, warehouse: transaction.warehouse },
|
||||
{ $inc: { quantity: delta } }
|
||||
)
|
||||
|
||||
await WarehouseItemTransaction.findByIdAndDelete(transactionId)
|
||||
return null
|
||||
}
|
||||
|
||||
// ─── STOCK QUERIES ────────────────────────────────────────────────────────────
|
||||
|
||||
const getStockByItem = async (itemId) => {
|
||||
const item = await WarehouseItem.findById(itemId)
|
||||
if (!item) throw new AppError('آیتم انبار یافت نشد', 404, {})
|
||||
|
||||
const stocks = await WarehouseItemStock.find({ item: itemId })
|
||||
.populate('warehouse', 'name code location description')
|
||||
.sort({ quantity: -1 })
|
||||
|
||||
const totalQuantity = stocks.reduce((sum, s) => sum + s.quantity, 0)
|
||||
|
||||
return {
|
||||
item,
|
||||
stocks,
|
||||
totalQuantity,
|
||||
unit: item.unitFa,
|
||||
unitEn: item.unitEn,
|
||||
}
|
||||
}
|
||||
|
||||
const getStockByWarehouse = async (warehouseId) => {
|
||||
const stocks = await WarehouseItemStock.find({ warehouse: warehouseId })
|
||||
.populate('item', 'nameFa nameEn code unitFa unitEn category isActive')
|
||||
.sort({ quantity: -1 })
|
||||
|
||||
return stocks
|
||||
}
|
||||
|
||||
const getTotalStock = async () => {
|
||||
const result = await WarehouseItemStock.aggregate([
|
||||
{
|
||||
$group: {
|
||||
_id: '$item',
|
||||
totalQuantity: { $sum: '$quantity' },
|
||||
warehouseCount: { $sum: 1 },
|
||||
unit: { $first: '$unit' },
|
||||
unitEn: { $first: '$unitEn' },
|
||||
},
|
||||
},
|
||||
{
|
||||
$lookup: {
|
||||
from: 'warehouseitems',
|
||||
localField: '_id',
|
||||
foreignField: '_id',
|
||||
as: 'item',
|
||||
},
|
||||
},
|
||||
{ $unwind: '$item' },
|
||||
{ $match: { 'item.isActive': true } },
|
||||
{
|
||||
$project: {
|
||||
_id: 0,
|
||||
item: { _id: '$item._id', nameFa: '$item.nameFa', nameEn: '$item.nameEn', code: '$item.code', category: '$item.category' },
|
||||
totalQuantity: 1,
|
||||
warehouseCount: 1,
|
||||
unit: 1,
|
||||
unitEn: 1,
|
||||
},
|
||||
},
|
||||
{ $sort: { totalQuantity: -1 } },
|
||||
])
|
||||
return result
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
createItem,
|
||||
listItems,
|
||||
getItem,
|
||||
updateItem,
|
||||
deleteItem,
|
||||
createTransaction,
|
||||
listTransactions,
|
||||
deleteTransaction,
|
||||
getStockByItem,
|
||||
getStockByWarehouse,
|
||||
getTotalStock,
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
const mongoose = require('mongoose')
|
||||
const ObjectID = mongoose.Schema.Types.ObjectId
|
||||
|
||||
// Running balance snapshot per (item × warehouse)
|
||||
// Updated atomically on each transaction using $inc
|
||||
// Acts as a fast-read cache — transactions are the source of truth
|
||||
const warehouseItemStockSchema = new mongoose.Schema(
|
||||
{
|
||||
item: {
|
||||
type: ObjectID,
|
||||
ref: 'WarehouseItem',
|
||||
required: true,
|
||||
},
|
||||
warehouse: {
|
||||
type: ObjectID,
|
||||
ref: 'Warehouse',
|
||||
required: true,
|
||||
},
|
||||
quantity: {
|
||||
type: Number,
|
||||
default: 0, // current balance
|
||||
},
|
||||
unit: {
|
||||
type: String,
|
||||
},
|
||||
unitEn: {
|
||||
type: String,
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
}
|
||||
)
|
||||
|
||||
// Guarantee one document per (item, warehouse) combination
|
||||
warehouseItemStockSchema.index({ item: 1, warehouse: 1 }, { unique: true })
|
||||
|
||||
const WarehouseItemStock = mongoose.model('WarehouseItemStock', warehouseItemStockSchema)
|
||||
module.exports = WarehouseItemStock
|
||||
@@ -0,0 +1,65 @@
|
||||
const mongoose = require('mongoose')
|
||||
const ObjectID = mongoose.Schema.Types.ObjectId
|
||||
|
||||
const warehouseItemTransactionSchema = new mongoose.Schema(
|
||||
{
|
||||
item: {
|
||||
type: ObjectID,
|
||||
ref: 'WarehouseItem',
|
||||
required: true,
|
||||
},
|
||||
warehouse: {
|
||||
type: ObjectID,
|
||||
ref: 'Warehouse',
|
||||
required: true,
|
||||
},
|
||||
type: {
|
||||
type: String,
|
||||
enum: ['IN', 'OUT'], // ورود / خروج
|
||||
required: true,
|
||||
},
|
||||
quantity: {
|
||||
type: Number,
|
||||
required: true,
|
||||
min: [0.001, 'مقدار باید بیشتر از صفر باشد'],
|
||||
},
|
||||
unit: {
|
||||
type: String,
|
||||
required: true, // واحد — کپی از آیتم در زمان تراکنش
|
||||
},
|
||||
unitEn: {
|
||||
type: String,
|
||||
},
|
||||
reason: {
|
||||
type: String,
|
||||
required: true, // دلیل تراکنش — مثال: خرید، مصرف در پروژه، برگشت کالا
|
||||
},
|
||||
actor: {
|
||||
type: ObjectID,
|
||||
ref: 'User',
|
||||
required: true,
|
||||
},
|
||||
actorName: {
|
||||
type: String, // ذخیره برای نمایش سریع
|
||||
},
|
||||
note: {
|
||||
type: String, // توضیحات اضافی
|
||||
},
|
||||
date: {
|
||||
type: Date,
|
||||
default: Date.now,
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
}
|
||||
)
|
||||
|
||||
warehouseItemTransactionSchema.index({ item: 1, warehouse: 1 })
|
||||
warehouseItemTransactionSchema.index({ item: 1, type: 1 })
|
||||
warehouseItemTransactionSchema.index({ warehouse: 1, date: -1 })
|
||||
warehouseItemTransactionSchema.index({ actor: 1 })
|
||||
warehouseItemTransactionSchema.index({ date: -1 })
|
||||
|
||||
const WarehouseItemTransaction = mongoose.model('WarehouseItemTransaction', warehouseItemTransactionSchema)
|
||||
module.exports = WarehouseItemTransaction
|
||||
+13
-9
@@ -1,15 +1,19 @@
|
||||
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
|
||||
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
|
||||
SUPER_ADMIN_ENABLED=true
|
||||
SUPER_ADMIN_EMAIL=superadmin@mbmanager.ir
|
||||
SUPER_ADMIN_PASSWORD=SuperAdmin@123456!
|
||||
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
|
||||
@@ -2,7 +2,6 @@ MONGODB_URL=mongodb://admin:*135792468*@localhost:27018/marbm?authSource=admin
|
||||
NODE_ENV=development
|
||||
PORT=3000
|
||||
JWT_SECRET=Y@RJNS@MPL!
|
||||
REDIS_URL= redis://:135792468@localhost:6379/0
|
||||
LOGIN_ATTEMPT_LIMIT=10
|
||||
SUPER_ADMIN_ROLE_ID=66a2da5b9b989a8909948848
|
||||
TYPE_SENSE_URL=localhost:8108
|
||||
|
||||
@@ -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:
|
||||
@@ -0,0 +1,40 @@
|
||||
// events/eventEmitter.js
|
||||
const EventEmitter = require('events')
|
||||
|
||||
class SafeEventEmitter extends EventEmitter {
|
||||
emit(event, ...args) {
|
||||
try {
|
||||
return super.emit(event, ...args)
|
||||
} catch (error) {
|
||||
console.error(`Error emitting event '${event}':`, error)
|
||||
this.emit('error', error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
on(event, listener) {
|
||||
const wrappedListener = async (...args) => {
|
||||
try {
|
||||
await listener(...args)
|
||||
} catch (error) {
|
||||
console.error(`Error in event handler '${event}':`, error)
|
||||
this.emit('error', error)
|
||||
}
|
||||
}
|
||||
return super.on(event, wrappedListener)
|
||||
}
|
||||
}
|
||||
|
||||
const eventEmitter = new SafeEventEmitter()
|
||||
|
||||
// Add default error handler
|
||||
eventEmitter.on('error', (error) => {
|
||||
console.error('Event Error:', {
|
||||
name: error.name,
|
||||
message: error.message,
|
||||
stack: error.stack,
|
||||
timestamp: new Date().toISOString(),
|
||||
})
|
||||
})
|
||||
|
||||
module.exports = { eventEmitter }
|
||||
@@ -0,0 +1,33 @@
|
||||
// events/index.js
|
||||
const { eventEmitter } = require('./eventEmitter')
|
||||
const createProperty = require('../components/property/events/createProperty')
|
||||
const updateProperty = require('../components/property/events/updateProperty')
|
||||
const deleteProperty = require('../components/property/events/deleteProperty')
|
||||
const registerEventHandlers = () => {
|
||||
// Register all event handlers
|
||||
createProperty(eventEmitter)
|
||||
updateProperty(eventEmitter)
|
||||
deleteProperty(eventEmitter)
|
||||
// Add additional error monitoring if needed
|
||||
eventEmitter.on('error', (error) => {
|
||||
console.error('Event handler error:', error)
|
||||
})
|
||||
|
||||
console.log('Event handlers registered successfully')
|
||||
}
|
||||
|
||||
const safeEmit = async (eventName, ...args) => {
|
||||
try {
|
||||
return eventEmitter.emit(eventName, ...args)
|
||||
} catch (error) {
|
||||
console.error(`Error safely emitting ${eventName}:`, error)
|
||||
eventEmitter.emit('error', error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
registerEventHandlers,
|
||||
eventEmitter,
|
||||
safeEmit,
|
||||
}
|
||||
@@ -28,5 +28,45 @@
|
||||
"code": "6",
|
||||
"english": "You need to log in first.",
|
||||
"persian": "لطفا ابتدا وارد شوید."
|
||||
},
|
||||
"UserAlreadyExist": {
|
||||
"code": "7",
|
||||
"english": "A user with this email already exists.",
|
||||
"persian": "کاربری با این آدرس ایمیل قبلاً ثبت شده است."
|
||||
},
|
||||
"NoPermissionAccess": {
|
||||
"code": "8",
|
||||
"english": "You do not have permission to perform this action.",
|
||||
"persian": "شما دسترسی لازم برای انجام این عملیات را ندارید."
|
||||
},
|
||||
"ProvideEmailPasswordRole": {
|
||||
"code": "9",
|
||||
"english": "Please provide email, password, and role.",
|
||||
"persian": "لطفاً ایمیل، رمز عبور و نقش کاربر را مشخص کنید."
|
||||
},
|
||||
"ProvideEmailAndPassword": {
|
||||
"code": "10",
|
||||
"english": "Please provide email and password.",
|
||||
"persian": "لطفاً ایمیل و رمز عبور را وارد کنید."
|
||||
},
|
||||
"IncorrectEmailOrPassword": {
|
||||
"code": "11",
|
||||
"english": "Incorrect email or password.",
|
||||
"persian": "ایمیل یا رمز عبور اشتباه است."
|
||||
},
|
||||
"UserIsInactive": {
|
||||
"code": "12",
|
||||
"english": "Your account has been deactivated.",
|
||||
"persian": "حساب کاربری شما غیرفعال شده است."
|
||||
},
|
||||
"NoRoleFound": {
|
||||
"code": "13",
|
||||
"english": "No role found with that ID.",
|
||||
"persian": "نقش مورد نظر یافت نشد."
|
||||
},
|
||||
"NoPermissionFound": {
|
||||
"code": "14",
|
||||
"english": "No permission found with that ID.",
|
||||
"persian": "دسترسی مورد نظر یافت نشد."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
const { startPropertyIndexCron } = require('./propertyIndexCron')
|
||||
|
||||
const initCronJobs = () => {
|
||||
startPropertyIndexCron()
|
||||
console.log('Cron jobs initialized successfully')
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
initCronJobs,
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
const cron = require('node-cron')
|
||||
const Property = require('../components/property/propertyModel')
|
||||
const propertyService = require('../components/property/propertyService')
|
||||
const { client } = require('../setup/typesense')
|
||||
|
||||
let lastIndexedAt = new Date(0)
|
||||
let lastIndexedCount = null
|
||||
let isIndexing = false
|
||||
|
||||
const checkAndIndexProperties = async () => {
|
||||
if (isIndexing) {
|
||||
console.log('[Property Index Cron] Indexing already in progress. Skipping this run.')
|
||||
return
|
||||
}
|
||||
|
||||
isIndexing = true
|
||||
try {
|
||||
const mongoCount = await Property.countDocuments({ isActive: true })
|
||||
|
||||
// Check Typesense collection document count
|
||||
let typesenseCount = 0
|
||||
let collectionExists = false
|
||||
try {
|
||||
const collection = await client.collections('properties').retrieve()
|
||||
typesenseCount = collection.num_documents || 0
|
||||
collectionExists = true
|
||||
} catch (err) {
|
||||
collectionExists = false
|
||||
}
|
||||
|
||||
// Count new or updated properties in MongoDB since last index
|
||||
const query = {
|
||||
isActive: true,
|
||||
$or: [
|
||||
{ updatedAt: { $gt: lastIndexedAt } },
|
||||
{ createdAt: { $gt: lastIndexedAt } }
|
||||
]
|
||||
}
|
||||
const changedCount = await Property.countDocuments(query)
|
||||
|
||||
const shouldIndex =
|
||||
!collectionExists ||
|
||||
(typesenseCount === 0 && mongoCount > 0) ||
|
||||
mongoCount !== typesenseCount ||
|
||||
(lastIndexedCount !== null && mongoCount !== lastIndexedCount) ||
|
||||
changedCount > 0
|
||||
|
||||
if (shouldIndex) {
|
||||
console.log(
|
||||
`[Property Index Cron] Changes detected (MongoDB: ${mongoCount}, Typesense: ${typesenseCount}, New/Updated: ${changedCount}). Starting indexing...`
|
||||
)
|
||||
const result = await propertyService.indexAllProperties()
|
||||
lastIndexedAt = new Date()
|
||||
lastIndexedCount = mongoCount
|
||||
console.log(`[Property Index Cron] Successfully indexed ${result.totalCount} properties.`)
|
||||
} else {
|
||||
console.log(
|
||||
`[Property Index Cron] No new or updated properties found since ${lastIndexedAt.toISOString()} (MongoDB: ${mongoCount}, Typesense: ${typesenseCount}). Skipping.`
|
||||
)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[Property Index Cron] Error during property indexing check:', err)
|
||||
} finally {
|
||||
isIndexing = false
|
||||
}
|
||||
}
|
||||
|
||||
const startPropertyIndexCron = () => {
|
||||
// Schedule every 5 minutes
|
||||
const task = cron.schedule('*/5 * * * *', async () => {
|
||||
console.log('[Property Index Cron] Running scheduled 5-minute property index check...')
|
||||
await checkAndIndexProperties()
|
||||
})
|
||||
|
||||
console.log('[Property Index Cron] Scheduled to run every 5 minutes (*/5 * * * *)')
|
||||
|
||||
// Initial check after startup
|
||||
setTimeout(() => {
|
||||
checkAndIndexProperties().catch((err) => {
|
||||
console.error('[Property Index Cron] Initial index check failed:', err)
|
||||
})
|
||||
}, 10000)
|
||||
|
||||
return task
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
startPropertyIndexCron,
|
||||
checkAndIndexProperties,
|
||||
}
|
||||
@@ -8,10 +8,15 @@ exports.loginProtect = async (req, res, next) => {
|
||||
let token
|
||||
|
||||
|
||||
token = req.cookies['bm-token']
|
||||
|
||||
if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {
|
||||
token = req.headers.authorization.split(' ')[1]
|
||||
const headerToken = req.headers.authorization.split(' ')[1]
|
||||
if (headerToken && headerToken !== 'undefined' && headerToken !== 'null' && headerToken.trim() !== '') {
|
||||
token = headerToken.trim()
|
||||
}
|
||||
}
|
||||
|
||||
if (!token && req.cookies) {
|
||||
token = req.cookies['bm-token'] || req.cookies['belonging_token'] || req.cookies['jwt']
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
|
||||
@@ -1,30 +1,73 @@
|
||||
const Permission = require('../components/permission/permissionModel')
|
||||
const Role = require('../components/role/roleModel')
|
||||
const AppError = require('../globalErrorHandler/AppError')
|
||||
const catchAsync = require('../globalErrorHandler/catchAsync')
|
||||
const User = require('../components/user/userModel')
|
||||
const ErrorLocalization = require('../globalErrorHandler/errorLocalization')
|
||||
const el = new ErrorLocalization()
|
||||
|
||||
let checker = (arr, target) => arr.includes(target)
|
||||
let checker = (arr, target) => {
|
||||
if (!Array.isArray(arr)) return false
|
||||
return arr.some((item) => {
|
||||
const id = (item?._id || item)?.toString()
|
||||
const key = item?.key
|
||||
return id === target?.toString() || (key && key === target)
|
||||
})
|
||||
}
|
||||
|
||||
const requires = (...permissions) => {
|
||||
return async (req, res, next) => {
|
||||
const role = await Role.findById(req.user.role)
|
||||
const perm = await Permission.findOne({ key: permissions[0] })
|
||||
const rolePerm = role?.permissions || []
|
||||
const userPerm = req.user.extraPermissions || []
|
||||
try {
|
||||
if (!req.user) {
|
||||
return next(new AppError('NotLoggedIn', 401, {}))
|
||||
}
|
||||
|
||||
// some features: permission denied when all roles are not same --> we want to access user with either roles
|
||||
const superAdminRoleId = process.env.SUPER_ADMIN_ROLE_ID || '66a2da5b9b989a8909948848'
|
||||
|
||||
// Super Admin bypass: full access to all endpoints
|
||||
if (
|
||||
!checker(rolePerm, perm?._id) &&
|
||||
!checker(userPerm, perm?._id) &&
|
||||
role._id.toString() !== process.env.SUPER_ADMIN_ROLE_ID
|
||||
req.user.isAdmin === true ||
|
||||
req.user.role?.englishName === 'SuperAdmin' ||
|
||||
req.user.role?._id?.toString() === superAdminRoleId ||
|
||||
req.user.role?.toString() === superAdminRoleId
|
||||
) {
|
||||
throw new AppError('NoPermissionAccess', 403, {})
|
||||
return next()
|
||||
}
|
||||
|
||||
// Retrieve role and its permissions
|
||||
let role = req.user.role
|
||||
if (role && (typeof role === 'string' || !role.permissions || !role.englishName)) {
|
||||
role = await Role.findById(role._id || role).populate('permissions')
|
||||
}
|
||||
|
||||
const rolePermissions = role?.permissions || []
|
||||
const userExtraPermissions = req.user.extraPermissions || []
|
||||
|
||||
// Find target permissions from DB
|
||||
const targetPerms = await Permission.find({ key: { $in: permissions } })
|
||||
const targetIds = targetPerms.map((p) => p._id.toString())
|
||||
const targetKeys = permissions
|
||||
|
||||
// Check if any required permission is present in role or user extra permissions
|
||||
const hasPermission =
|
||||
rolePermissions.some((rp) => {
|
||||
const rpId = (rp._id || rp).toString()
|
||||
const rpKey = rp.key
|
||||
return targetIds.includes(rpId) || targetKeys.includes(rpKey)
|
||||
}) ||
|
||||
userExtraPermissions.some((up) => {
|
||||
const upId = (up._id || up).toString()
|
||||
const upKey = up.key
|
||||
return targetIds.includes(upId) || targetKeys.includes(upKey)
|
||||
})
|
||||
|
||||
if (!hasPermission) {
|
||||
return next(new AppError('NoPermissionAccess', 403, {}))
|
||||
}
|
||||
|
||||
next()
|
||||
} catch (err) {
|
||||
next(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,23 +79,26 @@ const adminCheck = () => {
|
||||
}).populate('role')
|
||||
|
||||
if (!user) {
|
||||
throw new AppError('UserDoesNotExist', 403, {})
|
||||
return next(new AppError('UserDoesNotExist', 403, {}))
|
||||
}
|
||||
|
||||
const perm = await Permission.findOne(
|
||||
{ key: 'admindashboard' },
|
||||
null,
|
||||
null
|
||||
)
|
||||
const superAdminRoleId = process.env.SUPER_ADMIN_ROLE_ID || '66a2da5b9b989a8909948848'
|
||||
|
||||
if (
|
||||
user.isAdmin === true ||
|
||||
user.role?.englishName === 'SuperAdmin' ||
|
||||
user.role?._id?.toString() === superAdminRoleId ||
|
||||
user.role?.toString() === superAdminRoleId
|
||||
) {
|
||||
return next()
|
||||
}
|
||||
|
||||
const perm = await Permission.findOne({ key: 'admindashboard' })
|
||||
let rolePerm = user.role?.permissions || []
|
||||
let userPerm = user.extraPermissions || []
|
||||
// some features: permission denied when all roles are not same --> we want to access user with either roles
|
||||
if (
|
||||
!checker(rolePerm, perm?._id) &&
|
||||
!checker(userPerm, perm?._id) &&
|
||||
user.role?._id.toString() !== process.env.SUPER_ADMIN_ROLE_ID
|
||||
) {
|
||||
throw new AppError('NoPermissionAccess', 403, {})
|
||||
|
||||
if (!checker(rolePerm, perm?._id) && !checker(userPerm, perm?._id)) {
|
||||
return next(new AppError('NoPermissionAccess', 403, {}))
|
||||
}
|
||||
|
||||
next()
|
||||
@@ -61,9 +107,7 @@ const adminCheck = () => {
|
||||
err.message = el.getErrorText(err.name, err.parameters, 'persian')
|
||||
res.status(500).json({
|
||||
status: 'error',
|
||||
message:
|
||||
err.message ||
|
||||
'An error occurred while checking permissions.',
|
||||
message: err.message || 'An error occurred while checking permissions.',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+10
-91
@@ -23,7 +23,7 @@
|
||||
"mongoose": "^8.9.0",
|
||||
"mongoose-sequence": "^6.0.1",
|
||||
"multer": "^1.4.5-lts.1",
|
||||
"redis": "^4.7.0",
|
||||
"node-cron": "^4.6.0",
|
||||
"typesense": "^1.8.2",
|
||||
"validator": "^13.12.0"
|
||||
},
|
||||
@@ -51,59 +51,6 @@
|
||||
"sparse-bitfield": "^3.0.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@redis/bloom": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@redis/bloom/-/bloom-1.2.0.tgz",
|
||||
"integrity": "sha512-HG2DFjYKbpNmVXsa0keLHp/3leGJz1mjh09f2RLGGLQZzSHpkmZWuwJbAvo3QcRY8p80m5+ZdXZdYOSBLlp7Cg==",
|
||||
"peerDependencies": {
|
||||
"@redis/client": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@redis/client": {
|
||||
"version": "1.6.0",
|
||||
"resolved": "https://registry.npmjs.org/@redis/client/-/client-1.6.0.tgz",
|
||||
"integrity": "sha512-aR0uffYI700OEEH4gYnitAnv3vzVGXCFvYfdpu/CJKvk4pHfLPEy/JSZyrpQ+15WhXe1yJRXLtfQ84s4mEXnPg==",
|
||||
"dependencies": {
|
||||
"cluster-key-slot": "1.1.2",
|
||||
"generic-pool": "3.9.0",
|
||||
"yallist": "4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
}
|
||||
},
|
||||
"node_modules/@redis/graph": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@redis/graph/-/graph-1.1.1.tgz",
|
||||
"integrity": "sha512-FEMTcTHZozZciLRl6GiiIB4zGm5z5F3F6a6FZCyrfxdKOhFlGkiAqlexWMBzCi4DcRoyiOsuLfW+cjlGWyExOw==",
|
||||
"peerDependencies": {
|
||||
"@redis/client": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@redis/json": {
|
||||
"version": "1.0.7",
|
||||
"resolved": "https://registry.npmjs.org/@redis/json/-/json-1.0.7.tgz",
|
||||
"integrity": "sha512-6UyXfjVaTBTJtKNG4/9Z8PSpKE6XgSyEb8iwaqDcy+uKrd/DGYHTWkUdnQDyzm727V7p21WUMhsqz5oy65kPcQ==",
|
||||
"peerDependencies": {
|
||||
"@redis/client": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@redis/search": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@redis/search/-/search-1.2.0.tgz",
|
||||
"integrity": "sha512-tYoDBbtqOVigEDMAcTGsRlMycIIjwMCgD8eR2t0NANeQmgK/lvxNAvYyb6bZDD4frHRhIHkJu2TBRvB0ERkOmw==",
|
||||
"peerDependencies": {
|
||||
"@redis/client": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@redis/time-series": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@redis/time-series/-/time-series-1.1.0.tgz",
|
||||
"integrity": "sha512-c1Q99M5ljsIuc4YdaCwfUEXsofakb9c8+Zse2qxTadu8TalLXuAESzLvFAvNVbkmSlvlzIQOLpBCmWI9wTOt+g==",
|
||||
"peerDependencies": {
|
||||
"@redis/client": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/webidl-conversions": {
|
||||
"version": "7.0.3",
|
||||
"resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.3.tgz",
|
||||
@@ -442,14 +389,6 @@
|
||||
"fsevents": "~2.3.2"
|
||||
}
|
||||
},
|
||||
"node_modules/cluster-key-slot": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/cluster-key-slot/-/cluster-key-slot-1.1.2.tgz",
|
||||
"integrity": "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA==",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/color-convert": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
|
||||
@@ -949,14 +888,6 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/generic-pool": {
|
||||
"version": "3.9.0",
|
||||
"resolved": "https://registry.npmjs.org/generic-pool/-/generic-pool-3.9.0.tgz",
|
||||
"integrity": "sha512-hymDOu5B53XvN4QT9dBmZxPX4CWhBPPLguTZ9MMFeFa/Kg0xWVfylOVNlJji/E7yTZWFd/q9GO5TxDLq156D7g==",
|
||||
"engines": {
|
||||
"node": ">= 4"
|
||||
}
|
||||
},
|
||||
"node_modules/get-intrinsic": {
|
||||
"version": "1.2.6",
|
||||
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.6.tgz",
|
||||
@@ -1642,6 +1573,15 @@
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/node-cron": {
|
||||
"version": "4.6.0",
|
||||
"resolved": "https://registry.npmjs.org/node-cron/-/node-cron-4.6.0.tgz",
|
||||
"integrity": "sha512-Si/bzYiKRHOB8/a99T2+SDGN582ONDMSTlJr5oCkT6GtnqPjZ2s10eoQRYkW9ZHwjVxONL+W8Fb+qR0AHMQsdg==",
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/nodemon": {
|
||||
"version": "3.1.9",
|
||||
"resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.9.tgz",
|
||||
@@ -1887,22 +1827,6 @@
|
||||
"node": ">=8.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/redis": {
|
||||
"version": "4.7.0",
|
||||
"resolved": "https://registry.npmjs.org/redis/-/redis-4.7.0.tgz",
|
||||
"integrity": "sha512-zvmkHEAdGMn+hMRXuMBtu4Vo5P6rHQjLoHftu+lBqq8ZTA3RCVC/WzD790bkKKiNFp7d5/9PcSD19fJyyRvOdQ==",
|
||||
"workspaces": [
|
||||
"./packages/*"
|
||||
],
|
||||
"dependencies": {
|
||||
"@redis/bloom": "1.2.0",
|
||||
"@redis/client": "1.6.0",
|
||||
"@redis/graph": "1.1.1",
|
||||
"@redis/json": "1.0.7",
|
||||
"@redis/search": "1.2.0",
|
||||
"@redis/time-series": "1.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/regenerator-runtime": {
|
||||
"version": "0.14.1",
|
||||
"resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.14.1.tgz",
|
||||
@@ -2411,11 +2335,6 @@
|
||||
"engines": {
|
||||
"node": ">=0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/yallist": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
|
||||
"integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -27,7 +27,7 @@
|
||||
"mongoose": "^8.9.0",
|
||||
"mongoose-sequence": "^6.0.1",
|
||||
"multer": "^1.4.5-lts.1",
|
||||
"redis": "^4.7.0",
|
||||
"node-cron": "^4.6.0",
|
||||
"typesense": "^1.8.2",
|
||||
"validator": "^13.12.0"
|
||||
},
|
||||
|
||||
@@ -1,42 +1,29 @@
|
||||
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) => {
|
||||
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)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,8 +1,31 @@
|
||||
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 propertySeeder = require('../components/property/propertySeeder')
|
||||
const warehouseSeeder = require('../components/warehouse/warehouseSeeder')
|
||||
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 propertySeeder.runSeeder()
|
||||
await warehouseSeeder.runSeeder()
|
||||
|
||||
try {
|
||||
await propertyService.indexAllProperties()
|
||||
} catch (err) {
|
||||
console.warn('Typesense property indexing warning during seed:', err.message)
|
||||
}
|
||||
|
||||
try {
|
||||
await transactionService.indexAllTransactions()
|
||||
} catch (err) {
|
||||
console.warn('Typesense transaction indexing warning during seed:', err.message)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
const mongoose = require('mongoose')
|
||||
const redisClient = require('./redis')
|
||||
const port = process.env.PORT || 3000
|
||||
const env = process.env.NODE_ENV || 'development'
|
||||
module.exports = (app) => {
|
||||
@@ -20,14 +19,24 @@ module.exports = (app) => {
|
||||
// Create a document to force MongoDB to actually create the DB and collection
|
||||
await MyModel.create({ name: 'test' })
|
||||
|
||||
redisClient.connect().then((r) => {
|
||||
console.log('Redis connection Established')
|
||||
// Auto-sync permissions defined in permissionList.js
|
||||
const { syncPermissions } = require('../components/permission/permissionService')
|
||||
await syncPermissions()
|
||||
|
||||
// Ensure default MinIO buckets exist (temp, properties, documents)
|
||||
const { ensureBucketsExist } = require('../utils/upload/bucket')
|
||||
await ensureBucketsExist(['temp', 'properties', 'documents']).catch((err) => {
|
||||
console.error('Failed to ensure default MinIO buckets:', err)
|
||||
})
|
||||
|
||||
// Initialize cron jobs
|
||||
const { initCronJobs } = require('../jobs/index')
|
||||
initCronJobs()
|
||||
|
||||
app.listen(port, function () {
|
||||
console.log('Server Started On Port ' + port)
|
||||
})
|
||||
})
|
||||
})
|
||||
.catch(function (err) {
|
||||
console.log(err)
|
||||
})
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
const redis = require('redis')
|
||||
const env = process.env.NODE_ENV || 'development'
|
||||
|
||||
let connectionString
|
||||
if (env === 'development') {
|
||||
connectionString = process.env.REDIS_URL
|
||||
} else if (env === 'test') {
|
||||
connectionString = process.env.TEST_REDIS_URL
|
||||
} else if (env === 'production') {
|
||||
connectionString = process.env.REDIS_URL
|
||||
}
|
||||
const client = redis.createClient({ url: connectionString })
|
||||
|
||||
client.on('error', function (err) {
|
||||
console.log(err)
|
||||
})
|
||||
|
||||
module.exports = client
|
||||
@@ -2,24 +2,35 @@ const express = require('express')
|
||||
const userRoutes = require('../components/user/userRoutes')
|
||||
const roleRoutes = require('../components/role/roleRoutes')
|
||||
const permissionRoutes = require('../components/permission/permissionRoutes')
|
||||
const belongingRoutes = require('../components/belonging/belongingRoutes')
|
||||
const propertyRoutes = require('../components/property/propertyRoutes')
|
||||
const propertyStatusRoutes = require('../components/propertyStatus/propertyStatusRoutes')
|
||||
const categoryRoutes = require('../components/category/categoryRoutes')
|
||||
const transactionRoutes = require('../components/transaction/transactionRoutes')
|
||||
// const codeRoutes = require('../components/code/codeRoutes')
|
||||
// const CRMRoutes = require('../components/pages/crmRoutes')
|
||||
// const LoginRoute = require('../components/pages/loginRoutes')
|
||||
|
||||
const fileRoutes = require('../components/file/fileRoutes')
|
||||
const featureRoutes = require('../components/feature/featureRoutes')
|
||||
const warehouseItemRoutes = require('../components/warehouseItem/warehouseItemRoutes')
|
||||
const warehouseRoutes = require('../components/warehouse/warehouseRoutes')
|
||||
const settingRoutes = require('../components/setting/settingRoutes')
|
||||
const dashboardRoutes = require('../components/dashboard/dashboardRoutes')
|
||||
|
||||
const routerEndpoints = new express.Router()
|
||||
|
||||
routerEndpoints.use('/dashboard', dashboardRoutes)
|
||||
routerEndpoints.use('/users', userRoutes)
|
||||
routerEndpoints.use('/permissions', permissionRoutes)
|
||||
routerEndpoints.use('/belongings', belongingRoutes)
|
||||
routerEndpoints.use('/properties', propertyRoutes)
|
||||
routerEndpoints.use('/belongings', propertyRoutes) // Alias for backward compatibility
|
||||
routerEndpoints.use('/property-statuses', propertyStatusRoutes)
|
||||
routerEndpoints.use('/belonging-statuses', propertyStatusRoutes) // Alias for backward compatibility
|
||||
routerEndpoints.use('/roles', roleRoutes)
|
||||
routerEndpoints.use('/categories', categoryRoutes)
|
||||
routerEndpoints.use('/transactions', transactionRoutes)
|
||||
|
||||
routerEndpoints.use('/files', fileRoutes)
|
||||
routerEndpoints.use('/features', featureRoutes)
|
||||
routerEndpoints.use('/warehouse-items', warehouseItemRoutes)
|
||||
routerEndpoints.use('/warehouses', warehouseRoutes)
|
||||
routerEndpoints.use('/settings', settingRoutes)
|
||||
|
||||
module.exports = routerEndpoints
|
||||
|
||||
|
||||
+8
-3
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
/**
|
||||
* Jalali (Solar Hijri / Shamsi) calendar conversion utilities (Backend)
|
||||
*/
|
||||
|
||||
const persianMonths = [
|
||||
{ value: 1, id: 1, label: 'فروردین', name: 'فروردین' },
|
||||
{ value: 2, id: 2, label: 'اردیبهشت', name: 'اردیبهشت' },
|
||||
{ value: 3, id: 3, label: 'خرداد', name: 'خرداد' },
|
||||
{ value: 4, id: 4, label: 'تیر', name: 'تیر' },
|
||||
{ value: 5, id: 5, label: 'مرداد', name: 'مرداد' },
|
||||
{ value: 6, id: 6, label: 'شهریور', name: 'شهریور' },
|
||||
{ value: 7, id: 7, label: 'مهر', name: 'مهر' },
|
||||
{ value: 8, id: 8, label: 'آبان', name: 'آبان' },
|
||||
{ value: 9, id: 9, label: 'آذر', name: 'آذر' },
|
||||
{ value: 10, id: 10, label: 'دی', name: 'دی' },
|
||||
{ value: 11, id: 11, label: 'بهمن', name: 'بهمن' },
|
||||
{ value: 12, id: 12, label: 'اسفند', name: 'اسفند' }
|
||||
]
|
||||
|
||||
function toEnglishDigits(str) {
|
||||
if (str === null || str === undefined) return ''
|
||||
return String(str)
|
||||
.replace(/[۰-۹]/g, (d) => '۰۱۲۳۴۵۶۷۸۹'.indexOf(d))
|
||||
.replace(/[٠-٩]/g, (d) => '٠١٢٣٤٥٦٧٨٩'.indexOf(d))
|
||||
}
|
||||
|
||||
function jalaliToGregorian(jy, jm, jd) {
|
||||
jy = Number(jy)
|
||||
jm = Number(jm)
|
||||
jd = Number(jd)
|
||||
|
||||
let gy = jy > 979 ? 1600 : 621
|
||||
jy = jy > 979 ? jy - 979 : jy
|
||||
|
||||
let days =
|
||||
365 * jy +
|
||||
Math.floor(jy / 33) * 8 +
|
||||
Math.floor(((jy % 33) + 3) / 4) +
|
||||
78 +
|
||||
jd +
|
||||
(jm < 7 ? (jm - 1) * 31 : (jm - 7) * 30 + 186)
|
||||
|
||||
gy += 400 * Math.floor(days / 146097)
|
||||
days %= 146097
|
||||
|
||||
if (days > 36524) {
|
||||
gy += 100 * Math.floor(--days / 36524)
|
||||
days %= 36524
|
||||
if (days >= 365) days++
|
||||
}
|
||||
|
||||
gy += 4 * Math.floor(days / 1461)
|
||||
days %= 1461
|
||||
|
||||
if (days > 365) {
|
||||
gy += Math.floor((days - 1) / 365)
|
||||
days = (days - 1) % 365
|
||||
}
|
||||
|
||||
let gd = days + 1
|
||||
const isLeap = (gy % 4 === 0 && gy % 100 !== 0) || gy % 400 === 0
|
||||
const sal_a = [0, 31, isLeap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
|
||||
|
||||
let gm
|
||||
for (gm = 0; gm < 13; gm++) {
|
||||
const v = sal_a[gm]
|
||||
if (gd <= v) break
|
||||
gd -= v
|
||||
}
|
||||
|
||||
return { gy, gm, gd }
|
||||
}
|
||||
|
||||
function gregorianToJalali(gy, gm, gd) {
|
||||
gy = Number(gy)
|
||||
gm = Number(gm)
|
||||
gd = Number(gd)
|
||||
|
||||
const g_d_m = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
|
||||
let jy = gy > 1600 ? 979 : 0
|
||||
gy = gy > 1600 ? gy - 1600 : gy - 621
|
||||
|
||||
const gy2 = gm > 2 ? gy + 1 : gy
|
||||
let days =
|
||||
365 * gy +
|
||||
Math.floor((gy2 + 3) / 4) -
|
||||
Math.floor((gy2 + 99) / 100) +
|
||||
Math.floor((gy2 + 399) / 400) -
|
||||
80 +
|
||||
gd +
|
||||
g_d_m[gm - 1]
|
||||
|
||||
jy += 33 * Math.floor(days / 12053)
|
||||
days %= 12053
|
||||
|
||||
jy += 4 * Math.floor(days / 1461)
|
||||
days %= 1461
|
||||
|
||||
if (days > 365) {
|
||||
jy += Math.floor((days - 1) / 365)
|
||||
days = (days - 1) % 365
|
||||
}
|
||||
|
||||
const jm = days < 186 ? 1 + Math.floor(days / 31) : 7 + Math.floor((days - 186) / 30)
|
||||
const jd = 1 + (days < 186 ? days % 31 : (days - 186) % 30)
|
||||
|
||||
return { jy, jm, jd }
|
||||
}
|
||||
|
||||
function jalaliToDate(jy, jm, jd) {
|
||||
const y = parseInt(toEnglishDigits(jy), 10)
|
||||
const m = parseInt(toEnglishDigits(jm), 10)
|
||||
const d = parseInt(toEnglishDigits(jd), 10)
|
||||
|
||||
if (isNaN(y) || isNaN(m) || isNaN(d) || y <= 0 || m < 1 || m > 12 || d < 1 || d > 31) {
|
||||
return null
|
||||
}
|
||||
|
||||
const { gy, gm, gd } = jalaliToGregorian(y, m, d)
|
||||
return new Date(Date.UTC(gy, gm - 1, gd, 12, 0, 0))
|
||||
}
|
||||
|
||||
function parseDateToJalali(dateVal) {
|
||||
if (!dateVal) return null
|
||||
|
||||
if (dateVal instanceof Date || (typeof dateVal === 'string' && (dateVal.includes('T') || dateVal.includes('-')))) {
|
||||
const d = new Date(dateVal)
|
||||
if (!isNaN(d.getTime())) {
|
||||
return gregorianToJalali(d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate())
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof dateVal === 'string' && dateVal.includes('/')) {
|
||||
const clean = toEnglishDigits(dateVal.trim())
|
||||
const parts = clean.split('/')
|
||||
if (parts.length === 3) {
|
||||
const jy = parseInt(parts[0], 10)
|
||||
const jm = parseInt(parts[1], 10)
|
||||
const jd = parseInt(parts[2], 10)
|
||||
if (!isNaN(jy) && !isNaN(jm) && !isNaN(jd)) {
|
||||
return { jy, jm, jd }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
function normalizeToDate(input) {
|
||||
if (!input) return null
|
||||
if (input instanceof Date && !isNaN(input.getTime())) return input
|
||||
if (typeof input === 'string') {
|
||||
const trimmed = input.trim()
|
||||
if (trimmed.includes('/')) {
|
||||
const parts = toEnglishDigits(trimmed).split('/')
|
||||
if (parts.length === 3) {
|
||||
return jalaliToDate(parts[0], parts[1], parts[2])
|
||||
}
|
||||
}
|
||||
const d = new Date(trimmed)
|
||||
if (!isNaN(d.getTime())) return d
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
persianMonths,
|
||||
toEnglishDigits,
|
||||
jalaliToGregorian,
|
||||
gregorianToJalali,
|
||||
jalaliToDate,
|
||||
parseDateToJalali,
|
||||
normalizeToDate,
|
||||
}
|
||||
+34
-4
@@ -1,17 +1,39 @@
|
||||
const minioClient = require('./minio')
|
||||
const fs = require('fs')
|
||||
|
||||
// Ensure buckets exist in MinIO
|
||||
const ensureBucketsExist = async (bucketNames = ['temp', 'properties', 'documents']) => {
|
||||
for (const bucketName of bucketNames) {
|
||||
try {
|
||||
const exists = await minioClient.bucketExists(bucketName).catch(() => false)
|
||||
if (!exists) {
|
||||
await minioClient.makeBucket(bucketName, process.env.AWS_REGION || 'us-east-1')
|
||||
console.log(`MinIO bucket "${bucketName}" created successfully.`)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`Error ensuring MinIO bucket "${bucketName}" exists:`, err.message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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 endpoint = process.env.AWS_ENDPOINT || 'localhost'
|
||||
const hostPort = (endpoint.includes(':') || !process.env.AWS_PORT) ? endpoint : `${endpoint}:${process.env.AWS_PORT}`
|
||||
const fullHost = hostPort.startsWith('http://') || hostPort.startsWith('https://') ? hostPort : `${protocol}${hostPort}`
|
||||
|
||||
uploadedFile.fileURL = fullHost.replace(/\/$/, '') + '/' + bucketName + '/' + file.filename + '-' + file.originalName
|
||||
uploadedFile.fileName = file.filename + '-' + file.originalName
|
||||
|
||||
uploadedFile.fileEndpoint = process.env.AWS_ENDPOINT
|
||||
|
||||
return uploadedFile
|
||||
@@ -45,10 +67,18 @@ exports.deleteObject = (fileName, bucketName) => {
|
||||
return minioClient.removeObject(bucketName, fileName)
|
||||
}
|
||||
|
||||
exports.copyObject = (targetBucket, fileName, sourceBucketAndFile) => {
|
||||
return minioClient.copyObject(targetBucket, fileName, sourceBucketAndFile)
|
||||
exports.copyObject = async (targetBucket, fileName, sourceBucketAndFile) => {
|
||||
const bucketExists = await minioClient.bucketExists(targetBucket).catch(() => false)
|
||||
if (!bucketExists) {
|
||||
await minioClient.makeBucket(targetBucket, process.env.AWS_REGION || 'us-east-1')
|
||||
}
|
||||
const conds = minioClient.CopyConditions ? new minioClient.CopyConditions() : null
|
||||
return minioClient.copyObject(targetBucket, fileName, sourceBucketAndFile, conds)
|
||||
}
|
||||
|
||||
exports.removeObject = (bucketName, fileName) => {
|
||||
return minioClient.removeObject(bucketName, fileName)
|
||||
}
|
||||
|
||||
exports.ensureBucketsExist = ensureBucketsExist
|
||||
exports.minioClient = minioClient
|
||||
|
||||
+12
-18
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user