Compare commits
10
Commits
1bcff0e73a
...
2b94fdb034
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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
|
||||||
+26
-11
@@ -1,20 +1,35 @@
|
|||||||
# Use the official Node.js image as a base
|
# Stage 1: Build & install production dependencies
|
||||||
FROM node:18
|
FROM node:20-alpine AS dependencies
|
||||||
|
|
||||||
# Set the working directory in the container
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
# Copy package.json and package-lock.json to the container
|
|
||||||
COPY package*.json ./
|
COPY package*.json ./
|
||||||
|
|
||||||
# Install dependencies
|
RUN npm ci --omit=dev --ignore-scripts && npm cache clean --force
|
||||||
RUN npm install
|
|
||||||
|
|
||||||
# Copy the rest of the application code
|
# Stage 2: Production runner
|
||||||
COPY . .
|
FROM node:20-alpine AS runner
|
||||||
|
|
||||||
# Expose the application port
|
WORKDIR /app
|
||||||
|
|
||||||
|
ENV NODE_ENV=production
|
||||||
|
ENV PORT=3000
|
||||||
|
|
||||||
|
# Install dumb-init for robust signal handling (PID 1)
|
||||||
|
RUN apk add --no-cache dumb-init && 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
|
EXPOSE 3000
|
||||||
|
|
||||||
# Start the application
|
# Run container with dumb-init
|
||||||
CMD ["npm", "start"]
|
ENTRYPOINT ["/usr/bin/dumb-init", "--"]
|
||||||
|
CMD ["node", "app.js"]
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ const cors = require('cors')
|
|||||||
|
|
||||||
const app = express()
|
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(
|
app.use(
|
||||||
cors({
|
cors({
|
||||||
@@ -31,8 +31,25 @@ app.use(express.json())
|
|||||||
app.set('view engine', 'ejs')
|
app.set('view engine', 'ejs')
|
||||||
app.use(express.static('views/public'))
|
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)
|
app.use('/api', routerEndpoints)
|
||||||
|
|
||||||
|
const { registerEventHandlers } = require('./events/index')
|
||||||
|
|
||||||
|
registerEventHandlers()
|
||||||
|
|
||||||
databaseConnection(app)
|
databaseConnection(app)
|
||||||
|
|
||||||
app.use(globalErrorHandler)
|
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 }
|
|
||||||
@@ -6,6 +6,7 @@ const runSeeder = async () => {
|
|||||||
{ nativeName: 'ساختمان', englishName: 'Building' },
|
{ nativeName: 'ساختمان', englishName: 'Building' },
|
||||||
{ nativeName: 'زمین', englishName: 'Lot' },
|
{ nativeName: 'زمین', englishName: 'Lot' },
|
||||||
{ nativeName: 'کالا', englishName: 'Product' },
|
{ nativeName: 'کالا', englishName: 'Product' },
|
||||||
|
{ nativeName: 'خودرو', englishName: 'Car' },
|
||||||
]
|
]
|
||||||
|
|
||||||
await Category.deleteMany({})
|
await Category.deleteMany({})
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -23,7 +23,7 @@ const featureSchema = new mongoose.Schema({
|
|||||||
},
|
},
|
||||||
featureType: {
|
featureType: {
|
||||||
type: String,
|
type: String,
|
||||||
enum: ['string', 'boolean', 'number', 'date'],
|
enum: ['string', 'textarea', 'boolean', 'number', 'date'],
|
||||||
default: 'string',
|
default: 'string',
|
||||||
},
|
},
|
||||||
filterType: {
|
filterType: {
|
||||||
|
|||||||
+591
-743
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,516 @@
|
|||||||
|
/**
|
||||||
|
* 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: 'سیستم و داشبورد',
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
module.exports = permissionsList
|
||||||
@@ -25,7 +25,7 @@ const permissionSchema = new mongoose.Schema({
|
|||||||
})
|
})
|
||||||
|
|
||||||
permissionSchema.pre(/^find/, function (next) {
|
permissionSchema.pre(/^find/, function (next) {
|
||||||
this.find({ active: { $ne: false } })
|
this.find({ isActive: { $ne: false } })
|
||||||
next()
|
next()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,16 @@
|
|||||||
const Permission = require('./permissionModel')
|
const Permission = require('./permissionModel')
|
||||||
|
const permissionsList = require('./permissionList')
|
||||||
const chalk = require('chalk')
|
const chalk = require('chalk')
|
||||||
|
|
||||||
const runSeeder = async () => {
|
const runSeeder = async () => {
|
||||||
const permissions = []
|
|
||||||
|
|
||||||
await Permission.deleteMany({})
|
await Permission.deleteMany({})
|
||||||
console.log(chalk.red('Deleted all permission records.'))
|
console.log(chalk.red('Deleted all permission records.'))
|
||||||
|
|
||||||
|
const permissions = permissionsList.map((p) => ({
|
||||||
|
...p,
|
||||||
|
isActive: true,
|
||||||
|
}))
|
||||||
|
|
||||||
await Permission.insertMany(permissions, null)
|
await Permission.insertMany(permissions, null)
|
||||||
console.log(
|
console.log(
|
||||||
chalk.green.bold(
|
chalk.green.bold(
|
||||||
|
|||||||
@@ -1,8 +1,52 @@
|
|||||||
const Permission = require('./permissionModel')
|
const Permission = require('./permissionModel')
|
||||||
|
const permissionsList = require('./permissionList')
|
||||||
const AppError = require('../../globalErrorHandler/AppError')
|
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 () => {
|
module.exports.getAllPermissions = async () => {
|
||||||
return Permission.find({})
|
return Permission.find({}).sort({ category: 1, englishName: 1 })
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports.createPermission = async (data) => {
|
module.exports.createPermission = async (data) => {
|
||||||
|
|||||||
@@ -20,7 +20,6 @@ const belongingSchema = new mongoose.Schema(
|
|||||||
},
|
},
|
||||||
unit: {
|
unit: {
|
||||||
type: String,
|
type: String,
|
||||||
required: true,
|
|
||||||
},
|
},
|
||||||
description: String,
|
description: String,
|
||||||
relatedProjects: [String],
|
relatedProjects: [String],
|
||||||
@@ -37,7 +36,12 @@ const belongingSchema = new mongoose.Schema(
|
|||||||
},
|
},
|
||||||
documentUrls: [String],
|
documentUrls: [String],
|
||||||
mainImageUrls: [String],
|
mainImageUrls: [String],
|
||||||
|
nationalGeoCode: String,
|
||||||
tags: [String],
|
tags: [String],
|
||||||
|
status: {
|
||||||
|
type: ObjectID,
|
||||||
|
ref: 'BelongingStatus',
|
||||||
|
},
|
||||||
isActive: {
|
isActive: {
|
||||||
type: Boolean,
|
type: Boolean,
|
||||||
default: true,
|
default: true,
|
||||||
@@ -61,7 +65,7 @@ const belongingSchema = new mongoose.Schema(
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
// belongingSchema.plugin(AutoIncrement, { inc_field: 'belongingCode' })
|
belongingSchema.plugin(AutoIncrement, { inc_field: 'belongingCode' })
|
||||||
|
|
||||||
belongingSchema.methods.getDocumentsSignedUrls = function () {
|
belongingSchema.methods.getDocumentsSignedUrls = function () {
|
||||||
return getMultipleSignedUrls(this.documentUrls, 'belonging-documents')
|
return getMultipleSignedUrls(this.documentUrls, 'belonging-documents')
|
||||||
@@ -73,5 +77,7 @@ belongingSchema.methods.getMainImagedSignedUrl = function () {
|
|||||||
|
|
||||||
belongingSchema.index({ location: '2dsphere' }) // Enable geospatial queries
|
belongingSchema.index({ location: '2dsphere' }) // Enable geospatial queries
|
||||||
|
|
||||||
|
// belongingSchema.plugin(AutoIncrement, { inc_field: 'numId' })
|
||||||
|
|
||||||
const Belonging = mongoose.model('Belonging', belongingSchema)
|
const Belonging = mongoose.model('Belonging', belongingSchema)
|
||||||
module.exports = Belonging
|
module.exports = Belonging
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
const mongoose = require('mongoose')
|
||||||
|
const Property = require('./propertyModel')
|
||||||
|
|
||||||
|
const buildingSchema = new mongoose.Schema({
|
||||||
|
builtArea: {
|
||||||
|
type: Number, // مساحت زیربنا به متر مربع
|
||||||
|
},
|
||||||
|
floorsCount: {
|
||||||
|
type: Number, // تعداد طبقات
|
||||||
|
},
|
||||||
|
unitsCount: {
|
||||||
|
type: Number, // تعداد واحدها
|
||||||
|
},
|
||||||
|
constructionYear: {
|
||||||
|
type: Number, // سال ساخت
|
||||||
|
},
|
||||||
|
elevator: {
|
||||||
|
type: Boolean, // آسانسور
|
||||||
|
},
|
||||||
|
parking: {
|
||||||
|
type: Boolean, // پارکینگ
|
||||||
|
},
|
||||||
|
warehouse: {
|
||||||
|
type: Boolean, // انبار
|
||||||
|
},
|
||||||
|
heatingSystem: {
|
||||||
|
type: String, // سیستم گرمایش
|
||||||
|
},
|
||||||
|
coolingSystem: {
|
||||||
|
type: String, // سیستم سرمایش
|
||||||
|
},
|
||||||
|
structureType: {
|
||||||
|
type: String, // نوع سازه (اسکلت فلزی، بتنی، ...)
|
||||||
|
},
|
||||||
|
flooringType: {
|
||||||
|
type: String, // جنس کف (سرامیک، سنگ، لمینت، ...)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const Building = Property.discriminator('Building', buildingSchema)
|
||||||
|
|
||||||
|
module.exports = Building
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
const propertyService = require('../propertyService')
|
||||||
|
module.exports = (eventEmitter) => {
|
||||||
|
eventEmitter.on('createProperty', async (propertyData) => {
|
||||||
|
await propertyService.indexOneProperty(propertyData._id)
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
const propertyService = require('../propertyService')
|
||||||
|
module.exports = (eventEmitter) => {
|
||||||
|
eventEmitter.on('deleteProperty', async (propertyData) => {
|
||||||
|
// Handle property deletion event if needed
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
const mongoose = require('mongoose')
|
||||||
|
const Property = require('./propertyModel')
|
||||||
|
|
||||||
|
const landSchema = new mongoose.Schema({
|
||||||
|
landArea: {
|
||||||
|
type: Number, // مساحت زمین به متر مربع
|
||||||
|
},
|
||||||
|
zoningType: {
|
||||||
|
type: String, // نوع کاربری (مسکونی، کشاورزی، تجاری و ...)
|
||||||
|
},
|
||||||
|
boundaryCoordinates: {
|
||||||
|
type: [[Number]], // مختصات چندضلعی حدود ملک
|
||||||
|
},
|
||||||
|
streetWidth: {
|
||||||
|
type: Number, // عرض گذر (متر)
|
||||||
|
},
|
||||||
|
facadeCount: {
|
||||||
|
type: Number, // تعداد بر
|
||||||
|
},
|
||||||
|
landLength: {
|
||||||
|
type: Number, // طول زمین (متر)
|
||||||
|
},
|
||||||
|
landWidth: {
|
||||||
|
type: Number, // عرض زمین (متر)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const Land = Property.discriminator('Land', landSchema)
|
||||||
|
|
||||||
|
module.exports = Land
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
const catchAsync = require('../../globalErrorHandler/catchAsync')
|
||||||
|
const propertyService = require('./propertyService')
|
||||||
|
const { eventEmitter } = require('../../events/eventEmitter')
|
||||||
|
|
||||||
|
exports.searchProperties = catchAsync(async (req, res, next) => {
|
||||||
|
const { facets, belongings, totalCount, pagesCount } = await propertyService.searchProperties(req.query)
|
||||||
|
|
||||||
|
res.status(200).json({
|
||||||
|
status: 'success',
|
||||||
|
facets,
|
||||||
|
properties: belongings,
|
||||||
|
totalCount,
|
||||||
|
pagesCount,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
exports.indexAllProperties = catchAsync(async (req, res, next) => {
|
||||||
|
const { indexedCount } = await propertyService.indexAllProperties()
|
||||||
|
|
||||||
|
res.status(200).json({
|
||||||
|
status: 'success',
|
||||||
|
indexedCount,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
exports.indexOneProperty = catchAsync(async (req, res, next) => {
|
||||||
|
await propertyService.indexOneProperty(req.params.propertyId)
|
||||||
|
|
||||||
|
res.status(200).json({
|
||||||
|
status: 'success',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
exports.getAllProperties = catchAsync(async (req, res, next) => {
|
||||||
|
const properties = await propertyService.getAllProperties()
|
||||||
|
|
||||||
|
res.status(200).json({
|
||||||
|
status: 'success',
|
||||||
|
results: properties.length,
|
||||||
|
data: properties,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
exports.createProperty = catchAsync(async (req, res, next) => {
|
||||||
|
const property = await propertyService.createProperty(req.body)
|
||||||
|
eventEmitter.emit('createProperty', property)
|
||||||
|
|
||||||
|
res.status(201).json({
|
||||||
|
status: 'success',
|
||||||
|
data: property,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
exports.getProperty = catchAsync(async (req, res, next) => {
|
||||||
|
const property = await propertyService.getProperty(req.params.propertyId)
|
||||||
|
|
||||||
|
res.status(200).json({
|
||||||
|
status: 'success',
|
||||||
|
data: property,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
exports.updateProperty = catchAsync(async (req, res, next) => {
|
||||||
|
const property = await propertyService.updateProperty(req.params.propertyId, req.body)
|
||||||
|
await propertyService.indexAllProperties()
|
||||||
|
|
||||||
|
res.status(200).json({
|
||||||
|
status: 'success',
|
||||||
|
data: property,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
exports.deleteProperty = catchAsync(async (req, res, next) => {
|
||||||
|
await propertyService.deleteProperty(req.params.propertyId)
|
||||||
|
// eventEmitter.emit('deleteProperty')
|
||||||
|
|
||||||
|
res.status(204).json({
|
||||||
|
status: 'success',
|
||||||
|
data: null,
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
const mongoose = require('mongoose')
|
||||||
|
const ObjectID = mongoose.Schema.Types.ObjectId
|
||||||
|
const AutoIncrement = require('mongoose-sequence')(mongoose)
|
||||||
|
const { getMultipleSignedUrls } = require('../file/fileService')
|
||||||
|
|
||||||
|
const propertySchemaOptions = {
|
||||||
|
discriminatorKey: 'propertyType',
|
||||||
|
toJSON: { virtuals: true },
|
||||||
|
toObject: { virtuals: true },
|
||||||
|
timestamps: true,
|
||||||
|
}
|
||||||
|
|
||||||
|
const propertySchema = new mongoose.Schema(
|
||||||
|
{
|
||||||
|
name: {
|
||||||
|
type: String,
|
||||||
|
required: false, // Auto-generated: ownerName + mainNumber/subNumber
|
||||||
|
},
|
||||||
|
category: {
|
||||||
|
type: ObjectID,
|
||||||
|
ref: 'Category',
|
||||||
|
},
|
||||||
|
description: String,
|
||||||
|
relatedProjects: [String],
|
||||||
|
location: {
|
||||||
|
type: {
|
||||||
|
type: String,
|
||||||
|
enum: ['Point'],
|
||||||
|
required: false,
|
||||||
|
},
|
||||||
|
coordinates: {
|
||||||
|
type: [Number], // [longitude, latitude]
|
||||||
|
required: false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
documentUrls: {
|
||||||
|
type: [String],
|
||||||
|
default: [],
|
||||||
|
},
|
||||||
|
mainImageUrls: [String],
|
||||||
|
nationalGeoCode: {
|
||||||
|
type: String,
|
||||||
|
required: true, // شناسه ملی جغرافیایی الزامی است
|
||||||
|
},
|
||||||
|
tags: [String],
|
||||||
|
status: {
|
||||||
|
type: ObjectID,
|
||||||
|
ref: 'PropertyStatus',
|
||||||
|
},
|
||||||
|
isActive: {
|
||||||
|
type: Boolean,
|
||||||
|
default: true,
|
||||||
|
select: false,
|
||||||
|
},
|
||||||
|
// Title Deed General & Administrative (شناسه و اداره ثبت)
|
||||||
|
uniqueId: String, // شناسه یکتا سند مالکیت (۱۸ رقمی)
|
||||||
|
serialNumber: String, // شماره سریال چاپی سند
|
||||||
|
provinceRegistry: String,
|
||||||
|
localRegistryOffice: String,
|
||||||
|
registrationDate: String, // تاریخ ثبت سند
|
||||||
|
|
||||||
|
// Owner Specifications (مشخصات مالک)
|
||||||
|
ownerName: String,
|
||||||
|
fatherName: String,
|
||||||
|
idCardNumber: String,
|
||||||
|
nationalId: String,
|
||||||
|
issuePlace: String,
|
||||||
|
birthDate: String,
|
||||||
|
nationality: {
|
||||||
|
type: String,
|
||||||
|
default: 'ایران',
|
||||||
|
},
|
||||||
|
ownershipDocs: String,
|
||||||
|
|
||||||
|
// Property Specifications (مشخصات ملک)
|
||||||
|
registrationPlate: String,
|
||||||
|
mainNumber: String,
|
||||||
|
subNumber: String,
|
||||||
|
separatedFrom: String,
|
||||||
|
plotNumber: String,
|
||||||
|
registrationSection: String,
|
||||||
|
district: String,
|
||||||
|
blockNumber: String,
|
||||||
|
sideDirection: String,
|
||||||
|
floor: String,
|
||||||
|
zoningType: String,
|
||||||
|
specialStatus: String,
|
||||||
|
documentType: String,
|
||||||
|
address: String,
|
||||||
|
postalCode: String,
|
||||||
|
propertyBoundaries: String,
|
||||||
|
restrictions: String,
|
||||||
|
|
||||||
|
// دانگ: سهم ملک از ۶ دانگ (۱ تا ۶)
|
||||||
|
dong: {
|
||||||
|
type: Number,
|
||||||
|
min: 1,
|
||||||
|
max: 6,
|
||||||
|
default: 6,
|
||||||
|
},
|
||||||
|
|
||||||
|
features: [
|
||||||
|
{
|
||||||
|
definition: {
|
||||||
|
type: ObjectID,
|
||||||
|
ref: 'Feature',
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
value: mongoose.Schema.Types.Mixed,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
propertySchemaOptions
|
||||||
|
)
|
||||||
|
|
||||||
|
propertySchema.plugin(AutoIncrement, { inc_field: 'propertyCode' })
|
||||||
|
|
||||||
|
propertySchema.methods.getDocumentsSignedUrls = function () {
|
||||||
|
return getMultipleSignedUrls(this.documentUrls, 'property-documents')
|
||||||
|
}
|
||||||
|
|
||||||
|
propertySchema.methods.getMainImagedSignedUrl = function () {
|
||||||
|
return getMultipleSignedUrls(this.mainImageUrls, 'property-images')
|
||||||
|
}
|
||||||
|
|
||||||
|
propertySchema.index({ location: '2dsphere' })
|
||||||
|
|
||||||
|
const Property = mongoose.model('Property', propertySchema)
|
||||||
|
|
||||||
|
module.exports = Property
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
const express = require('express')
|
||||||
|
const propertyController = require('./propertyController')
|
||||||
|
const perm = require('../../middlewares/permissionMiddleware')
|
||||||
|
const loginCheck = require('../../middlewares/loginCheck')
|
||||||
|
|
||||||
|
const router = new express.Router()
|
||||||
|
|
||||||
|
router.use(loginCheck.loginProtect)
|
||||||
|
|
||||||
|
router.get('/admin/get-all', perm.requires('getallproperties', 'getallbelongings'), propertyController.getAllProperties)
|
||||||
|
|
||||||
|
router.post('/admin/create', perm.requires('createaproperty', 'createabelonging'), propertyController.createProperty)
|
||||||
|
|
||||||
|
router.post('/admin/index-all', perm.requires('indexproperties', 'indexbelongings'), propertyController.indexAllProperties)
|
||||||
|
|
||||||
|
router.post('/admin/index-one/:propertyId', perm.requires('indexproperties', 'indexbelongings'), propertyController.indexOneProperty)
|
||||||
|
|
||||||
|
router.get('/admin/search', perm.requires('searchproperties', 'searchbelongings'), propertyController.searchProperties)
|
||||||
|
|
||||||
|
router.get('/admin/get-one/:propertyId', perm.requires('getaproperty', 'getabelonging'), propertyController.getProperty)
|
||||||
|
|
||||||
|
router.put('/admin/update/:propertyId', perm.requires('updateaproperty', 'updateabelonging'), propertyController.updateProperty)
|
||||||
|
|
||||||
|
router.delete('/admin/delete/:propertyId', perm.requires('deleteaproperty', 'deleteabelonging'), propertyController.deleteProperty)
|
||||||
|
|
||||||
|
module.exports = router
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
const Property = require('./propertyModel')
|
||||||
|
const Land = require('./landModel')
|
||||||
|
const Building = require('./buildingModel')
|
||||||
|
const AppError = require('../../globalErrorHandler/AppError')
|
||||||
|
const { client } = require('../../setup/typesense')
|
||||||
|
const TsApiFeatures = require('../../utils/TsApiFeatures')
|
||||||
|
|
||||||
|
const getAllProperties = async () => {
|
||||||
|
return Property.find({}, null, null).populate('category').populate('status')
|
||||||
|
}
|
||||||
|
|
||||||
|
const createProperty = async (data) => {
|
||||||
|
if (data.propertyType === 'Land' || data.propertyType === 'زمین') {
|
||||||
|
return Land.create(data)
|
||||||
|
} else if (data.propertyType === 'Building' || data.propertyType === 'ساختمان') {
|
||||||
|
return Building.create(data)
|
||||||
|
}
|
||||||
|
return Property.create(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
const getProperty = async (propertyId) => {
|
||||||
|
let property = await Property.findById(propertyId, null, null).populate('category').populate('status')
|
||||||
|
|
||||||
|
if (!property) {
|
||||||
|
throw new AppError('NoPropertyFound', 404, {})
|
||||||
|
}
|
||||||
|
|
||||||
|
const documentUrls = await property.getDocumentsSignedUrls()
|
||||||
|
const mainImageUrls = await property.getMainImagedSignedUrl()
|
||||||
|
|
||||||
|
property = JSON.parse(JSON.stringify(property))
|
||||||
|
|
||||||
|
property.signedDocumentUrls = documentUrls
|
||||||
|
property.signedMainImageUrls = mainImageUrls
|
||||||
|
|
||||||
|
return property
|
||||||
|
}
|
||||||
|
|
||||||
|
const updateProperty = async (propertyId, data) => {
|
||||||
|
const property = await Property.findOneAndUpdate({ _id: propertyId }, data, { new: true })
|
||||||
|
|
||||||
|
if (!property) {
|
||||||
|
throw new AppError('NoPropertyFound', 404, {})
|
||||||
|
}
|
||||||
|
|
||||||
|
return property
|
||||||
|
}
|
||||||
|
|
||||||
|
const deleteProperty = async (propertyId) => {
|
||||||
|
const property = await Property.findByIdAndUpdate(propertyId, { isActive: false }, { new: true })
|
||||||
|
|
||||||
|
if (!property) {
|
||||||
|
throw new AppError('NoPropertyFound', 404, {})
|
||||||
|
}
|
||||||
|
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
const ensureCollectionExists = async (forceRecreate = false) => {
|
||||||
|
try {
|
||||||
|
const collections = await client.collections().retrieve()
|
||||||
|
const collectionExists = collections.some((collection) => collection.name === 'properties')
|
||||||
|
|
||||||
|
if (collectionExists && forceRecreate) {
|
||||||
|
await client.collections('properties').delete()
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!collectionExists || forceRecreate) {
|
||||||
|
const schema = getTypeSenseSchema()
|
||||||
|
await client.collections().create(schema)
|
||||||
|
console.log('Collection "properties" created successfully')
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Error ensuring properties collection exists:', err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const searchProperties = async (inputQuery) => {
|
||||||
|
await ensureCollectionExists(false)
|
||||||
|
inputQuery = updateInputQuery(inputQuery, {})
|
||||||
|
|
||||||
|
const tsFeatures = new TsApiFeatures(client, 'properties', inputQuery).filter().facet().sort().limitFields().paginate().search()
|
||||||
|
|
||||||
|
let { facets, items, totalCount, pagesCount } = await tsFeatures.execute()
|
||||||
|
|
||||||
|
return { facets, belongings: items, totalCount, pagesCount }
|
||||||
|
}
|
||||||
|
|
||||||
|
const updateInputQuery = (inputQuery, extraQueries) => {
|
||||||
|
for (const [key, value] of Object.entries(extraQueries)) {
|
||||||
|
inputQuery[key] = value
|
||||||
|
}
|
||||||
|
|
||||||
|
inputQuery.query_by = 'name,nationalGeoCode,tags,description,_id'
|
||||||
|
|
||||||
|
return inputQuery
|
||||||
|
}
|
||||||
|
|
||||||
|
const indexAllProperties = async () => {
|
||||||
|
const batchSize = 20
|
||||||
|
const count = await Property.countDocuments({ isActive: true }, null)
|
||||||
|
const rounds = Math.max(1, Math.ceil(count / batchSize))
|
||||||
|
|
||||||
|
await ensureCollectionExists(true)
|
||||||
|
|
||||||
|
for (let i = 1; i <= rounds; i++) {
|
||||||
|
const properties = await Property.find({ isActive: true }, null, null)
|
||||||
|
.populate('category')
|
||||||
|
.skip((i - 1) * batchSize)
|
||||||
|
.limit(batchSize)
|
||||||
|
|
||||||
|
if (properties.length === 0) break
|
||||||
|
|
||||||
|
let documents = []
|
||||||
|
|
||||||
|
for (const property of properties) {
|
||||||
|
const combinedTags = Array.isArray(property.tags) ? property.tags.join(' ') : (property.tags || '')
|
||||||
|
|
||||||
|
const data = {
|
||||||
|
_id: property._id.toString(),
|
||||||
|
isActive: property.isActive,
|
||||||
|
name: property.name || '',
|
||||||
|
category: property.category?.englishName || '',
|
||||||
|
nativeCategory: property.category?.nativeName || '',
|
||||||
|
imageUrl: property.mainImageUrls?.[0] || 'https://cloud.mbmanager.ir/images/item-no-image.png',
|
||||||
|
documents: property.documentUrls || [],
|
||||||
|
description: property.description || '',
|
||||||
|
nationalGeoCode: property.nationalGeoCode || '',
|
||||||
|
tags: combinedTags,
|
||||||
|
coordinates: property.location?.coordinates || [0, 0],
|
||||||
|
createdAt: Math.floor(new Date(property.createdAt || Date.now()).getTime() / 1000),
|
||||||
|
id: property.propertyCode ? property.propertyCode.toString() : property._id.toString(),
|
||||||
|
}
|
||||||
|
|
||||||
|
documents.push(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (documents.length > 0) {
|
||||||
|
await client.collections('properties').documents().import(documents, { action: 'emplace' })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { totalCount: count }
|
||||||
|
}
|
||||||
|
|
||||||
|
const indexOneProperty = async (propertyId) => {
|
||||||
|
await ensureCollectionExists(false)
|
||||||
|
const property = await getProperty(propertyId)
|
||||||
|
|
||||||
|
console.log(`Property ${property._id} indexing`)
|
||||||
|
|
||||||
|
const combinedTags = Array.isArray(property.tags) ? property.tags.join(' ') : (property.tags || '')
|
||||||
|
|
||||||
|
const data = {
|
||||||
|
_id: property._id.toString(),
|
||||||
|
isActive: property.isActive,
|
||||||
|
name: property.name || '',
|
||||||
|
category: property.category?.englishName || '',
|
||||||
|
nativeCategory: property.category?.nativeName || '',
|
||||||
|
imageUrl: property.mainImageUrls?.[0] || '',
|
||||||
|
documents: property.documentUrls || [],
|
||||||
|
description: property.description || '',
|
||||||
|
nationalGeoCode: property.nationalGeoCode || '',
|
||||||
|
tags: combinedTags,
|
||||||
|
coordinates: property.location?.coordinates || [0, 0],
|
||||||
|
createdAt: Math.floor(new Date(property.createdAt || Date.now()).getTime() / 1000),
|
||||||
|
id: property.propertyCode ? property.propertyCode.toString() : property._id.toString(),
|
||||||
|
}
|
||||||
|
|
||||||
|
await client.collections('properties').documents().upsert(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
const getTypeSenseSchema = () => {
|
||||||
|
return {
|
||||||
|
name: 'properties',
|
||||||
|
enable_nested_fields: true,
|
||||||
|
fields: [
|
||||||
|
{ name: '_id', type: 'string', facet: false, infix: false },
|
||||||
|
{ name: 'name', type: 'string', facet: false, infix: true },
|
||||||
|
{ name: 'category', type: 'string', facet: true, infix: true },
|
||||||
|
{ name: 'nativeCategory', type: 'string', facet: false, infix: true },
|
||||||
|
{ name: 'description', type: 'string', facet: false },
|
||||||
|
{ name: 'nationalGeoCode', type: 'string', facet: false, infix: true },
|
||||||
|
{ name: 'tags', type: 'string', facet: false, infix: true },
|
||||||
|
{ name: 'coordinates', type: 'geopoint' },
|
||||||
|
{ name: 'createdAt', type: 'int64', facet: false },
|
||||||
|
{ name: 'imageUrl', type: 'string', facet: false, infix: true },
|
||||||
|
],
|
||||||
|
default_sorting_field: 'createdAt',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
updateProperty,
|
||||||
|
indexAllProperties,
|
||||||
|
getProperty,
|
||||||
|
getAllProperties,
|
||||||
|
createProperty,
|
||||||
|
deleteProperty,
|
||||||
|
searchProperties,
|
||||||
|
indexOneProperty,
|
||||||
|
}
|
||||||
@@ -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 }
|
||||||
@@ -2,15 +2,16 @@ const Role = require('./roleModel')
|
|||||||
const AppError = require('../../globalErrorHandler/AppError')
|
const AppError = require('../../globalErrorHandler/AppError')
|
||||||
|
|
||||||
module.exports.getAllRoles = async () => {
|
module.exports.getAllRoles = async () => {
|
||||||
return Role.find({}, null, null)
|
return Role.find({}).populate('permissions').sort({ createdAt: -1 })
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports.createRole = async (data) => {
|
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) => {
|
module.exports.getRole = async (roleId) => {
|
||||||
const role = await Role.findById(roleId)
|
const role = await Role.findById(roleId).populate('permissions')
|
||||||
|
|
||||||
if (!role) {
|
if (!role) {
|
||||||
throw new AppError('NoRoleFound', 404, {})
|
throw new AppError('NoRoleFound', 404, {})
|
||||||
@@ -20,7 +21,7 @@ module.exports.getRole = async (roleId) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
module.exports.updateRole = async (roleId, data) => {
|
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) {
|
if (!role) {
|
||||||
throw new AppError('NoRoleFound', 404, {})
|
throw new AppError('NoRoleFound', 404, {})
|
||||||
|
|||||||
@@ -34,10 +34,9 @@ const transactionSchema = new mongoose.Schema(
|
|||||||
type: String,
|
type: String,
|
||||||
required: true,
|
required: true,
|
||||||
},
|
},
|
||||||
belongingId: {
|
propertyId: {
|
||||||
type: ObjectID,
|
type: ObjectID,
|
||||||
ref: 'Belonging',
|
ref: 'Property',
|
||||||
required: true,
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -47,14 +46,11 @@ const transactionSchema = new mongoose.Schema(
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
// Add individual indexes for frequently queried fields
|
|
||||||
transactionSchema.index({ type: 1 })
|
transactionSchema.index({ type: 1 })
|
||||||
transactionSchema.index({ status: 1 })
|
transactionSchema.index({ status: 1 })
|
||||||
transactionSchema.index({ value: 1 })
|
transactionSchema.index({ value: 1 })
|
||||||
|
transactionSchema.index({ propertyId: 1, status: 1 })
|
||||||
// Add compound indexes for common query patterns in aggregation
|
transactionSchema.index({ propertyId: 1, type: 1, status: 1 })
|
||||||
transactionSchema.index({ belongingId: 1, status: 1 })
|
|
||||||
transactionSchema.index({ belongingId: 1, type: 1, status: 1 })
|
|
||||||
|
|
||||||
const Transaction = mongoose.model('Transaction', transactionSchema)
|
const Transaction = mongoose.model('Transaction', transactionSchema)
|
||||||
module.exports = Transaction
|
module.exports = Transaction
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
const Transaction = require('./transactionModel')
|
const Transaction = require('./transactionModel')
|
||||||
const Belonging = require('../belonging/belongingModel')
|
const Property = require('../property/propertyModel')
|
||||||
const AppError = require('../../globalErrorHandler/AppError')
|
const AppError = require('../../globalErrorHandler/AppError')
|
||||||
const mongoose = require('mongoose')
|
const mongoose = require('mongoose')
|
||||||
const ObjectID = mongoose.Schema.Types.ObjectId
|
const ObjectID = mongoose.Schema.Types.ObjectId
|
||||||
@@ -17,17 +17,16 @@ const filterObj = (obj, ...allowedFields) => {
|
|||||||
|
|
||||||
const createTransaction = async (data) => {
|
const createTransaction = async (data) => {
|
||||||
if (data.type == 'withdraw') {
|
if (data.type == 'withdraw') {
|
||||||
// Aggregate transactions to calculate inventory
|
|
||||||
const result = await Transaction.aggregate([
|
const result = await Transaction.aggregate([
|
||||||
{
|
{
|
||||||
$match: {
|
$match: {
|
||||||
belongingId: ObjectID,
|
propertyId: ObjectID,
|
||||||
status: 'finished',
|
status: 'finished',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
$group: {
|
$group: {
|
||||||
_id: '$belongingId',
|
_id: '$propertyId',
|
||||||
totalInventory: {
|
totalInventory: {
|
||||||
$sum: '$value',
|
$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({
|
return Transaction.create({
|
||||||
@@ -46,7 +45,7 @@ const createTransaction = async (data) => {
|
|||||||
date: data.Date,
|
date: data.Date,
|
||||||
description: data.description,
|
description: data.description,
|
||||||
userId: data.userId,
|
userId: data.userId,
|
||||||
belongingId: data.belongingId,
|
propertyId: data.propertyId || data.belongingId,
|
||||||
userName: data.userName,
|
userName: data.userName,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -55,28 +54,26 @@ const getUserTransaction = async (userId) => {
|
|||||||
return Transaction.find({ userId }, null, null)
|
return Transaction.find({ userId }, null, null)
|
||||||
}
|
}
|
||||||
|
|
||||||
const getTransactionByBelongingId = async (belongingId) => {
|
const getTransactionByBelongingId = async (propertyId) => {
|
||||||
return Transaction.find({ belongingId }, null, null)
|
return Transaction.find({ propertyId }, null, null)
|
||||||
}
|
}
|
||||||
|
|
||||||
const getBelongingInventory = async (belongingId) => {
|
const getBelongingInventory = async (propertyId) => {
|
||||||
const belonging = await Belonging.findById(belongingId, null, null)
|
const property = await Property.findById(propertyId, null, null)
|
||||||
|
|
||||||
if (!belonging) {
|
if (!property) {
|
||||||
throw new AppError('NoBelongingFound', 404, {})
|
throw new AppError('NoPropertyFound', 404, {})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Simplified aggregation to calculate inventory metrics
|
|
||||||
const result = await Transaction.aggregate([
|
const result = await Transaction.aggregate([
|
||||||
{
|
{
|
||||||
$match: {
|
$match: {
|
||||||
belongingId: belonging._id,
|
propertyId: property._id,
|
||||||
$or: [{ status: 'finished' }, { status: 'pending' }],
|
$or: [{ status: 'finished' }, { status: 'pending' }],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
$facet: {
|
$facet: {
|
||||||
// Calculate total inventory from finished transactions
|
|
||||||
finishedInventory: [
|
finishedInventory: [
|
||||||
{ $match: { status: 'finished' } },
|
{ $match: { status: 'finished' } },
|
||||||
{
|
{
|
||||||
@@ -86,7 +83,6 @@ const getBelongingInventory = async (belongingId) => {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
// Calculate pending deposits
|
|
||||||
pendingDepositsInventory: [
|
pendingDepositsInventory: [
|
||||||
{
|
{
|
||||||
$match: {
|
$match: {
|
||||||
@@ -101,7 +97,6 @@ const getBelongingInventory = async (belongingId) => {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
// Calculate pending withdrawals
|
|
||||||
pendingWithdrawsInventory: [
|
pendingWithdrawsInventory: [
|
||||||
{
|
{
|
||||||
$match: {
|
$match: {
|
||||||
@@ -119,7 +114,6 @@ const getBelongingInventory = async (belongingId) => {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
// Restructure the output to get only the values
|
|
||||||
$project: {
|
$project: {
|
||||||
finishedInventory: { $ifNull: [{ $arrayElemAt: ['$finishedInventory.total', 0] }, 0] },
|
finishedInventory: { $ifNull: [{ $arrayElemAt: ['$finishedInventory.total', 0] }, 0] },
|
||||||
pendingDepositsInventory: { $ifNull: [{ $arrayElemAt: ['$pendingDepositsInventory.total', 0] }, 0] },
|
pendingDepositsInventory: { $ifNull: [{ $arrayElemAt: ['$pendingDepositsInventory.total', 0] }, 0] },
|
||||||
@@ -152,21 +146,27 @@ const deleteTransaction = async (transactionId) => {
|
|||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
const ensureCollectionExists = async () => {
|
const ensureCollectionExists = async (forceRecreate = false) => {
|
||||||
|
try {
|
||||||
const collections = await client.collections().retrieve()
|
const collections = await client.collections().retrieve()
|
||||||
const collectionExists = collections.some((collection) => collection.name === 'transactions')
|
const collectionExists = collections.some((collection) => collection.name === 'transactions')
|
||||||
|
|
||||||
if (collectionExists) {
|
if (collectionExists && forceRecreate) {
|
||||||
await client.collections('transactions').delete()
|
await client.collections('transactions').delete()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!collectionExists || forceRecreate) {
|
||||||
const schema = getTypeSenseSchema()
|
const schema = getTypeSenseSchema()
|
||||||
|
|
||||||
await client.collections().create(schema)
|
await client.collections().create(schema)
|
||||||
console.log('Collection "transactions" created successfully')
|
console.log('Collection "transactions" created successfully')
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Error ensuring transactions collection exists:', err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const searchTransactions = async (inputQuery) => {
|
const searchTransactions = async (inputQuery) => {
|
||||||
|
await ensureCollectionExists(false)
|
||||||
inputQuery = updateInputQuery(inputQuery, {})
|
inputQuery = updateInputQuery(inputQuery, {})
|
||||||
|
|
||||||
const tsFeatures = new TsApiFeatures(client, 'transactions', inputQuery).filter().facet().sort().limitFields().paginate().search()
|
const tsFeatures = new TsApiFeatures(client, 'transactions', inputQuery).filter().facet().sort().limitFields().paginate().search()
|
||||||
@@ -176,7 +176,7 @@ const searchTransactions = async (inputQuery) => {
|
|||||||
return { facets, transactions: items, totalCount, pagesCount }
|
return { facets, transactions: items, totalCount, pagesCount }
|
||||||
}
|
}
|
||||||
|
|
||||||
const updateInputQuery = (inputQuery, extraQueries, features) => {
|
const updateInputQuery = (inputQuery, extraQueries) => {
|
||||||
for (const [key, value] of Object.entries(extraQueries)) {
|
for (const [key, value] of Object.entries(extraQueries)) {
|
||||||
inputQuery[key] = value
|
inputQuery[key] = value
|
||||||
}
|
}
|
||||||
@@ -189,39 +189,41 @@ const updateInputQuery = (inputQuery, extraQueries, features) => {
|
|||||||
const indexAllTransactions = async () => {
|
const indexAllTransactions = async () => {
|
||||||
const batchSize = 20
|
const batchSize = 20
|
||||||
const count = await Transaction.countDocuments({}, null)
|
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++) {
|
for (let i = 1; i <= rounds; i++) {
|
||||||
console.log(`Indexing ${batchSize} transactions, Round ${i}`)
|
|
||||||
|
|
||||||
const transactions = await Transaction.find({}, null, null)
|
const transactions = await Transaction.find({}, null, null)
|
||||||
.skip((i - 1) * batchSize)
|
.skip((i - 1) * batchSize)
|
||||||
.limit(batchSize)
|
.limit(batchSize)
|
||||||
.populate('belongingId')
|
.populate('propertyId')
|
||||||
|
|
||||||
|
if (transactions.length === 0) break
|
||||||
|
|
||||||
let documents = []
|
let documents = []
|
||||||
|
|
||||||
for (const transaction of transactions) {
|
for (const transaction of transactions) {
|
||||||
const data = {
|
const data = {
|
||||||
_id: transaction._id,
|
_id: transaction._id.toString(),
|
||||||
type: transaction.type,
|
type: transaction.type || '',
|
||||||
status: transaction.status,
|
status: transaction.status || '',
|
||||||
source: transaction.source || '',
|
source: transaction.source || '',
|
||||||
value: transaction.value,
|
value: transaction.value || 0,
|
||||||
description: transaction.description,
|
description: transaction.description || '',
|
||||||
createdAt: Math.floor(new Date(transaction.createdAt).getTime() / 1000), // Store as timestamp in seconds
|
createdAt: Math.floor(new Date(transaction.createdAt || Date.now()).getTime() / 1000),
|
||||||
belongingName: transaction.belongingId.name,
|
belongingName: transaction.propertyId?.name || '',
|
||||||
belongingId: transaction.belongingId._id,
|
belongingId: transaction.propertyId?._id ? transaction.propertyId._id.toString() : '',
|
||||||
userName: transaction.userName || '',
|
userName: transaction.userName || '',
|
||||||
}
|
}
|
||||||
|
|
||||||
documents.push(data)
|
documents.push(data)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (documents.length > 0) {
|
||||||
await client.collections('transactions').documents().import(documents, { action: 'emplace' })
|
await client.collections('transactions').documents().import(documents, { action: 'emplace' })
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return { totalCount: count }
|
return { totalCount: count }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
const express = require('express')
|
const express = require('express')
|
||||||
const userController = require('./userController')
|
const userController = require('./userController')
|
||||||
const loginCheck = require('../../middlewares/loginCheck')
|
const loginCheck = require('../../middlewares/loginCheck')
|
||||||
|
const perm = require('../../middlewares/permissionMiddleware')
|
||||||
|
|
||||||
const router = new express.Router()
|
const router = new express.Router()
|
||||||
|
|
||||||
@@ -12,18 +13,17 @@ router.post('/login-email', userController.loginUser)
|
|||||||
router.post('/logout', userController.logoutUser)
|
router.post('/logout', userController.logoutUser)
|
||||||
|
|
||||||
router.use(loginCheck.loginProtect)
|
router.use(loginCheck.loginProtect)
|
||||||
// router.use(loginCheck.adminProtect)
|
|
||||||
|
|
||||||
router.get('/user/get-self', userController.userGetSelf)
|
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
|
module.exports = router
|
||||||
|
|||||||
+138
-43
@@ -1,7 +1,8 @@
|
|||||||
// userService.js
|
// userService.js
|
||||||
const User = require('./userModel')
|
const User = require('./userModel')
|
||||||
|
const Role = require('../role/roleModel')
|
||||||
const AppError = require('../../globalErrorHandler/AppError')
|
const AppError = require('../../globalErrorHandler/AppError')
|
||||||
const redisClient = require('../../setup/redis')
|
const LoginAttempt = require('./loginAttemptModel')
|
||||||
const jwt = require('jsonwebtoken')
|
const jwt = require('jsonwebtoken')
|
||||||
const bcrypt = require('bcryptjs')
|
const bcrypt = require('bcryptjs')
|
||||||
const maxAge = 60 * 60 * 24 * 90
|
const maxAge = 60 * 60 * 24 * 90
|
||||||
@@ -13,19 +14,19 @@ const signToken = (id) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const signup = async (name, email, password, passwordConfirm) => {
|
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) {
|
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 hashedPassword = bcrypt.hashSync(password, 10)
|
||||||
|
|
||||||
const user = await createUser({
|
const user = await createUser({
|
||||||
name,
|
name,
|
||||||
email,
|
email: email.toLowerCase().trim(),
|
||||||
password: hashedPassword,
|
password: hashedPassword,
|
||||||
passwordConfirm: undefined,
|
passwordConfirm: undefined,
|
||||||
})
|
})
|
||||||
@@ -44,39 +45,39 @@ const signup = async (name, email, password, passwordConfirm) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const loginAttempt = async (phrase) => {
|
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) {
|
let attemptRecord = await LoginAttempt.findOne({ key })
|
||||||
await redisClient.set(
|
|
||||||
phrase + '#attempts',
|
if (attemptRecord && attemptRecord.expiresAt <= now) {
|
||||||
0,
|
await LoginAttempt.deleteOne({ _id: attemptRecord._id })
|
||||||
{
|
attemptRecord = null
|
||||||
EX: 3600,
|
|
||||||
},
|
|
||||||
null
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// if user phrase(email or phone) exist return error with expire time left for login
|
if (!attemptRecord) {
|
||||||
if (parseInt(await redisClient.get(phrase + '#attempts')) >= parseInt(process.env.LOGIN_ATTEMPT_LIMIT)) {
|
const expiresAt = new Date(Date.now() + ttlSeconds * 1000)
|
||||||
const limitTime = await redisClient.ttl(phrase + '#attempts')
|
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)
|
const minutes = (limitTime / 60).toFixed(0)
|
||||||
throw new AppError('MaximumLoginReached', 500, {
|
throw new AppError('MaximumLoginReached', 500, {
|
||||||
minutes,
|
minutes,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
if (attemptExist === 1) {
|
attemptRecord.attempts += 1
|
||||||
const attempts = parseInt(await redisClient.get(phrase + '#attempts'))
|
attemptRecord.expiresAt = new Date(Date.now() + ttlSeconds * 1000)
|
||||||
await redisClient.set(
|
await attemptRecord.save()
|
||||||
phrase + '#attempts',
|
|
||||||
attempts + 1 + '',
|
|
||||||
{
|
|
||||||
EX: 3600,
|
|
||||||
},
|
|
||||||
null
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const loginUser = async (email, password) => {
|
const loginUser = async (email, password) => {
|
||||||
@@ -84,56 +85,150 @@ const loginUser = async (email, password) => {
|
|||||||
throw new AppError('ProvideEmailAndPassword', 400)
|
throw new AppError('ProvideEmailAndPassword', 400)
|
||||||
}
|
}
|
||||||
|
|
||||||
const user = await User.findOne({ email }, null, null).select('+password')
|
const inputPhrase = email.toLowerCase().trim()
|
||||||
|
|
||||||
if (email) {
|
// ─── 1) Environment-based Super Admin Authentication ────────────────────
|
||||||
await loginAttempt(email)
|
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))) {
|
if (!user || !(await bcrypt.compare(password, user.password))) {
|
||||||
throw new AppError('IncorrectEmailOrPassword', 401, {})
|
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
|
user.password = undefined
|
||||||
return { token: signToken(user._id), user }
|
return { token: signToken(user._id), user }
|
||||||
}
|
}
|
||||||
|
|
||||||
const getAllUsers = async () => {
|
const getAllUsers = async () => {
|
||||||
const users = await User.find({}, null, null)
|
return User.find({}).populate('role').sort({ createdAt: -1 })
|
||||||
|
|
||||||
return users
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const getUser = async (userId) => {
|
const getUser = async (userId) => {
|
||||||
const user = await User.findById({ _id: userId }, null, null)
|
const user = await User.findById(userId).populate('role')
|
||||||
|
|
||||||
if (!user) {
|
if (!user) {
|
||||||
throw AppError('NoUserFound', 404, {})
|
throw new AppError('NoUserFound', 404, {})
|
||||||
}
|
}
|
||||||
|
|
||||||
return user
|
return user
|
||||||
}
|
}
|
||||||
|
|
||||||
const createUser = async (data) => {
|
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 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) {
|
if (!user) {
|
||||||
throw AppError('NoUserFound', 404, {})
|
throw new AppError('NoUserFound', 404, {})
|
||||||
}
|
}
|
||||||
|
|
||||||
return user
|
return user
|
||||||
}
|
}
|
||||||
|
|
||||||
const deleteUser = async (userId) => {
|
const deleteUser = async (userId) => {
|
||||||
const user = await User.findOneAndDelete({ _id: userId })
|
const user = await User.findByIdAndUpdate(userId, { isActive: false }, { new: true })
|
||||||
|
|
||||||
if (!user) {
|
if (!user) {
|
||||||
throw AppError('NoUserFound', 404, {})
|
throw new AppError('NoUserFound', 404, {})
|
||||||
}
|
}
|
||||||
|
|
||||||
return null
|
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,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
|
NODE_ENV=development
|
||||||
PORT=3000
|
PORT=3000
|
||||||
JWT_SECRET=Y@RJ$WT!@K0NS@MPL!
|
JWT_SECRET=Y@RJ$WT!@K0NS@MPL!
|
||||||
REDIS_URL=redis://:GFis6zU4DXW9Q7NQ@services.irn12.chabokan.net:19794/0
|
|
||||||
LOGIN_ATTEMPT_LIMIT=900
|
LOGIN_ATTEMPT_LIMIT=900
|
||||||
SUPER_ADMIN_ROLE_ID=66a2da5b9b989a8909948848
|
SUPER_ADMIN_ROLE_ID=66a2da5b9b989a8909948848
|
||||||
TYPE_SENSE_URL=bm-typesense.chbk.app
|
SUPER_ADMIN_ENABLED=true
|
||||||
TYPE_SENSE_API_KEY=rHV4vZePdfBYFC9q
|
SUPER_ADMIN_EMAIL=superadmin@mbmanager.ir
|
||||||
AWS_ENDPOINT=bm-minio-2.chbk.app
|
SUPER_ADMIN_PASSWORD=SuperAdmin@123456!
|
||||||
AWS_URL=https://bm-minio-2.chbk.app
|
TYPE_SENSE_URL=localhost:8109
|
||||||
AWS_ACCESS_KEY=lwcAHMbCea4jeKMtj6SOjMtmETY93rBb
|
TYPE_SENSE_PROTOCOL=http
|
||||||
AWS_SECRET_KEY=xXKrceoCV3Wx35d0JmULgNvHJ0UlTQnO
|
TYPE_SENSE_API_KEY=vYQq7pTgl6ACoRy
|
||||||
AWS_REGION=default
|
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
|
API_URL=http://localhost:3000
|
||||||
@@ -2,7 +2,6 @@ MONGODB_URL=mongodb://admin:*135792468*@localhost:27018/marbm?authSource=admin
|
|||||||
NODE_ENV=development
|
NODE_ENV=development
|
||||||
PORT=3000
|
PORT=3000
|
||||||
JWT_SECRET=Y@RJNS@MPL!
|
JWT_SECRET=Y@RJNS@MPL!
|
||||||
REDIS_URL= redis://:135792468@localhost:6379/0
|
|
||||||
LOGIN_ATTEMPT_LIMIT=10
|
LOGIN_ATTEMPT_LIMIT=10
|
||||||
SUPER_ADMIN_ROLE_ID=66a2da5b9b989a8909948848
|
SUPER_ADMIN_ROLE_ID=66a2da5b9b989a8909948848
|
||||||
TYPE_SENSE_URL=localhost:8108
|
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,31 @@
|
|||||||
|
// events/index.js
|
||||||
|
const { eventEmitter } = require('./eventEmitter')
|
||||||
|
const createProperty = require('../components/property/events/createProperty')
|
||||||
|
const deleteProperty = require('../components/property/events/deleteProperty')
|
||||||
|
const registerEventHandlers = () => {
|
||||||
|
// Register all event handlers
|
||||||
|
createProperty(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",
|
"code": "6",
|
||||||
"english": "You need to log in first.",
|
"english": "You need to log in first.",
|
||||||
"persian": "لطفا ابتدا وارد شوید."
|
"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": "دسترسی مورد نظر یافت نشد."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,30 +1,73 @@
|
|||||||
const Permission = require('../components/permission/permissionModel')
|
const Permission = require('../components/permission/permissionModel')
|
||||||
const Role = require('../components/role/roleModel')
|
const Role = require('../components/role/roleModel')
|
||||||
const AppError = require('../globalErrorHandler/AppError')
|
const AppError = require('../globalErrorHandler/AppError')
|
||||||
const catchAsync = require('../globalErrorHandler/catchAsync')
|
|
||||||
const User = require('../components/user/userModel')
|
const User = require('../components/user/userModel')
|
||||||
const ErrorLocalization = require('../globalErrorHandler/errorLocalization')
|
const ErrorLocalization = require('../globalErrorHandler/errorLocalization')
|
||||||
const el = new 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) => {
|
const requires = (...permissions) => {
|
||||||
return async (req, res, next) => {
|
return async (req, res, next) => {
|
||||||
const role = await Role.findById(req.user.role)
|
try {
|
||||||
const perm = await Permission.findOne({ key: permissions[0] })
|
if (!req.user) {
|
||||||
const rolePerm = role?.permissions || []
|
return next(new AppError('NotLoggedIn', 401, {}))
|
||||||
const userPerm = req.user.extraPermissions || []
|
}
|
||||||
|
|
||||||
// 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 (
|
if (
|
||||||
!checker(rolePerm, perm?._id) &&
|
req.user.isAdmin === true ||
|
||||||
!checker(userPerm, perm?._id) &&
|
req.user.role?.englishName === 'SuperAdmin' ||
|
||||||
role._id.toString() !== process.env.SUPER_ADMIN_ROLE_ID
|
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()
|
next()
|
||||||
|
} catch (err) {
|
||||||
|
next(err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -36,23 +79,26 @@ const adminCheck = () => {
|
|||||||
}).populate('role')
|
}).populate('role')
|
||||||
|
|
||||||
if (!user) {
|
if (!user) {
|
||||||
throw new AppError('UserDoesNotExist', 403, {})
|
return next(new AppError('UserDoesNotExist', 403, {}))
|
||||||
}
|
}
|
||||||
|
|
||||||
const perm = await Permission.findOne(
|
const superAdminRoleId = process.env.SUPER_ADMIN_ROLE_ID || '66a2da5b9b989a8909948848'
|
||||||
{ key: 'admindashboard' },
|
|
||||||
null,
|
if (
|
||||||
null
|
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 rolePerm = user.role?.permissions || []
|
||||||
let userPerm = user.extraPermissions || []
|
let userPerm = user.extraPermissions || []
|
||||||
// some features: permission denied when all roles are not same --> we want to access user with either roles
|
|
||||||
if (
|
if (!checker(rolePerm, perm?._id) && !checker(userPerm, perm?._id)) {
|
||||||
!checker(rolePerm, perm?._id) &&
|
return next(new AppError('NoPermissionAccess', 403, {}))
|
||||||
!checker(userPerm, perm?._id) &&
|
|
||||||
user.role?._id.toString() !== process.env.SUPER_ADMIN_ROLE_ID
|
|
||||||
) {
|
|
||||||
throw new AppError('NoPermissionAccess', 403, {})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
next()
|
next()
|
||||||
@@ -61,9 +107,7 @@ const adminCheck = () => {
|
|||||||
err.message = el.getErrorText(err.name, err.parameters, 'persian')
|
err.message = el.getErrorText(err.name, err.parameters, 'persian')
|
||||||
res.status(500).json({
|
res.status(500).json({
|
||||||
status: 'error',
|
status: 'error',
|
||||||
message:
|
message: err.message || 'An error occurred while checking permissions.',
|
||||||
err.message ||
|
|
||||||
'An error occurred while checking permissions.',
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Generated
-91
@@ -23,7 +23,6 @@
|
|||||||
"mongoose": "^8.9.0",
|
"mongoose": "^8.9.0",
|
||||||
"mongoose-sequence": "^6.0.1",
|
"mongoose-sequence": "^6.0.1",
|
||||||
"multer": "^1.4.5-lts.1",
|
"multer": "^1.4.5-lts.1",
|
||||||
"redis": "^4.7.0",
|
|
||||||
"typesense": "^1.8.2",
|
"typesense": "^1.8.2",
|
||||||
"validator": "^13.12.0"
|
"validator": "^13.12.0"
|
||||||
},
|
},
|
||||||
@@ -51,59 +50,6 @@
|
|||||||
"sparse-bitfield": "^3.0.3"
|
"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": {
|
"node_modules/@types/webidl-conversions": {
|
||||||
"version": "7.0.3",
|
"version": "7.0.3",
|
||||||
"resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.3.tgz",
|
"resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.3.tgz",
|
||||||
@@ -442,14 +388,6 @@
|
|||||||
"fsevents": "~2.3.2"
|
"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": {
|
"node_modules/color-convert": {
|
||||||
"version": "2.0.1",
|
"version": "2.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
|
||||||
@@ -949,14 +887,6 @@
|
|||||||
"url": "https://github.com/sponsors/ljharb"
|
"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": {
|
"node_modules/get-intrinsic": {
|
||||||
"version": "1.2.6",
|
"version": "1.2.6",
|
||||||
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.6.tgz",
|
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.6.tgz",
|
||||||
@@ -1887,22 +1817,6 @@
|
|||||||
"node": ">=8.10.0"
|
"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": {
|
"node_modules/regenerator-runtime": {
|
||||||
"version": "0.14.1",
|
"version": "0.14.1",
|
||||||
"resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.14.1.tgz",
|
"resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.14.1.tgz",
|
||||||
@@ -2411,11 +2325,6 @@
|
|||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=0.4"
|
"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=="
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,7 +27,6 @@
|
|||||||
"mongoose": "^8.9.0",
|
"mongoose": "^8.9.0",
|
||||||
"mongoose-sequence": "^6.0.1",
|
"mongoose-sequence": "^6.0.1",
|
||||||
"multer": "^1.4.5-lts.1",
|
"multer": "^1.4.5-lts.1",
|
||||||
"redis": "^4.7.0",
|
|
||||||
"typesense": "^1.8.2",
|
"typesense": "^1.8.2",
|
||||||
"validator": "^13.12.0"
|
"validator": "^13.12.0"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,42 +1,29 @@
|
|||||||
const mongoose = require('mongoose')
|
const mongoose = require('mongoose')
|
||||||
const port = process.env.PORT || 3000
|
|
||||||
const env = process.env.NODE_ENV || 'development'
|
const env = process.env.NODE_ENV || 'development'
|
||||||
const redisClient = require('../setup/redis')
|
|
||||||
const seederRunner = require('./seederRunner')
|
const seederRunner = require('./seederRunner')
|
||||||
const chalk = require('chalk')
|
const chalk = require('chalk')
|
||||||
|
|
||||||
module.exports = (app) => {
|
module.exports = (app) => {
|
||||||
let connectionString
|
let connectionString = process.env.MONGODB_URL
|
||||||
if (env === 'development') {
|
console.log(`Environment: ${env}`)
|
||||||
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)
|
|
||||||
mongoose
|
mongoose
|
||||||
.connect(connectionString, {})
|
.connect(connectionString, {})
|
||||||
.then(function () {
|
.then(async function () {
|
||||||
console.log('MongoDB Database Connected')
|
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(
|
console.log(chalk.red.bold('-------- Running Seeders ---------'))
|
||||||
chalk.red.bold(
|
try {
|
||||||
'-------- Running Seeders ---------'
|
await seederRunner.run()
|
||||||
)
|
console.log(chalk.blue.bold('Seeding and indexing completed successfully.'))
|
||||||
)
|
} catch (err) {
|
||||||
seederRunner.run().then((r) => {
|
console.error('Seeding error:', err)
|
||||||
console.log(chalk.blue.bold('Seeding is done.'))
|
} finally {
|
||||||
process.exit(0)
|
process.exit(0)
|
||||||
})
|
}
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
.catch(function (err) {
|
.catch(function (err) {
|
||||||
console.log(err)
|
console.error('Database connection error:', err)
|
||||||
|
process.exit(1)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,17 @@
|
|||||||
const userSeeder = require('../components/user/userSeeder')
|
const userSeeder = require('../components/user/userSeeder')
|
||||||
const categorySeeder = require('../components/category/categorySeeder')
|
const categorySeeder = require('../components/category/categorySeeder')
|
||||||
const roleSeeder = require('../components/role/roleSeeder')
|
const roleSeeder = require('../components/role/roleSeeder')
|
||||||
|
const featureSeeder = require('../components/feature/featureSeeder')
|
||||||
|
const propertyStatusSeeder = require('../components/propertyStatus/propertyStatusSeeder')
|
||||||
|
const propertyService = require('../components/property/propertyService')
|
||||||
|
const transactionService = require('../components/transaction/transactionService')
|
||||||
|
|
||||||
module.exports.run = async () => {
|
module.exports.run = async () => {
|
||||||
await userSeeder.runSeeder()
|
await userSeeder.runSeeder()
|
||||||
await categorySeeder.runSeeder()
|
await categorySeeder.runSeeder()
|
||||||
await roleSeeder.runSeeder()
|
await roleSeeder.runSeeder()
|
||||||
|
await featureSeeder.runSeeder()
|
||||||
|
await propertyStatusSeeder.runSeeder()
|
||||||
|
await propertyService.indexAllProperties()
|
||||||
|
await transactionService.indexAllTransactions()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
const mongoose = require('mongoose')
|
const mongoose = require('mongoose')
|
||||||
const redisClient = require('./redis')
|
|
||||||
const port = process.env.PORT || 3000
|
const port = process.env.PORT || 3000
|
||||||
const env = process.env.NODE_ENV || 'development'
|
const env = process.env.NODE_ENV || 'development'
|
||||||
module.exports = (app) => {
|
module.exports = (app) => {
|
||||||
@@ -20,14 +19,14 @@ module.exports = (app) => {
|
|||||||
// Create a document to force MongoDB to actually create the DB and collection
|
// Create a document to force MongoDB to actually create the DB and collection
|
||||||
await MyModel.create({ name: 'test' })
|
await MyModel.create({ name: 'test' })
|
||||||
|
|
||||||
redisClient.connect().then((r) => {
|
// Auto-sync permissions defined in permissionList.js
|
||||||
console.log('Redis connection Established')
|
const { syncPermissions } = require('../components/permission/permissionService')
|
||||||
|
await syncPermissions()
|
||||||
|
|
||||||
app.listen(port, function () {
|
app.listen(port, function () {
|
||||||
console.log('Server Started On Port ' + port)
|
console.log('Server Started On Port ' + port)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
|
||||||
.catch(function (err) {
|
.catch(function (err) {
|
||||||
console.log(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,30 @@ const express = require('express')
|
|||||||
const userRoutes = require('../components/user/userRoutes')
|
const userRoutes = require('../components/user/userRoutes')
|
||||||
const roleRoutes = require('../components/role/roleRoutes')
|
const roleRoutes = require('../components/role/roleRoutes')
|
||||||
const permissionRoutes = require('../components/permission/permissionRoutes')
|
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 categoryRoutes = require('../components/category/categoryRoutes')
|
||||||
const transactionRoutes = require('../components/transaction/transactionRoutes')
|
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 fileRoutes = require('../components/file/fileRoutes')
|
||||||
const featureRoutes = require('../components/feature/featureRoutes')
|
const featureRoutes = require('../components/feature/featureRoutes')
|
||||||
|
const warehouseItemRoutes = require('../components/warehouseItem/warehouseItemRoutes')
|
||||||
|
const warehouseRoutes = require('../components/warehouse/warehouseRoutes')
|
||||||
|
|
||||||
const routerEndpoints = new express.Router()
|
const routerEndpoints = new express.Router()
|
||||||
|
|
||||||
routerEndpoints.use('/users', userRoutes)
|
routerEndpoints.use('/users', userRoutes)
|
||||||
routerEndpoints.use('/permissions', permissionRoutes)
|
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('/roles', roleRoutes)
|
||||||
routerEndpoints.use('/categories', categoryRoutes)
|
routerEndpoints.use('/categories', categoryRoutes)
|
||||||
routerEndpoints.use('/transactions', transactionRoutes)
|
routerEndpoints.use('/transactions', transactionRoutes)
|
||||||
|
|
||||||
routerEndpoints.use('/files', fileRoutes)
|
routerEndpoints.use('/files', fileRoutes)
|
||||||
routerEndpoints.use('/features', featureRoutes)
|
routerEndpoints.use('/features', featureRoutes)
|
||||||
|
routerEndpoints.use('/warehouse-items', warehouseItemRoutes)
|
||||||
|
routerEndpoints.use('/warehouses', warehouseRoutes)
|
||||||
|
|
||||||
module.exports = routerEndpoints
|
module.exports = routerEndpoints
|
||||||
|
|||||||
+8
-3
@@ -1,11 +1,16 @@
|
|||||||
const TypeSense = require('typesense')
|
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({
|
let client = new TypeSense.Client({
|
||||||
nodes: [
|
nodes: [
|
||||||
{
|
{
|
||||||
host: process.env.TYPE_SENSE_URL,
|
host: host,
|
||||||
port: '443',
|
port: port,
|
||||||
protocol: 'https',
|
protocol: protocol,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
apiKey: process.env.TYPE_SENSE_API_KEY,
|
apiKey: process.env.TYPE_SENSE_API_KEY,
|
||||||
|
|||||||
@@ -166,8 +166,9 @@ class TsApiFeatures {
|
|||||||
per_page: this.queryOptions.per_page,
|
per_page: this.queryOptions.per_page,
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
const tsProtocol = process.env.TYPE_SENSE_PROTOCOL || 'http'
|
||||||
const config = {
|
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',
|
method: 'POST',
|
||||||
data: {
|
data: {
|
||||||
searches,
|
searches,
|
||||||
|
|||||||
@@ -4,11 +4,18 @@ const fs = require('fs')
|
|||||||
|
|
||||||
// Upload File to s3 bucket
|
// Upload File to s3 bucket
|
||||||
exports.uploadObject = async (file, bucketName) => {
|
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 fileStream = fs.createReadStream(file.path)
|
||||||
|
|
||||||
const uploadedFile = await minioClient.putObject(bucketName, `${file.filename}-${file.originalName}`, fileStream)
|
const uploadedFile = await minioClient.putObject(bucketName, `${file.filename}-${file.originalName}`, fileStream)
|
||||||
|
|
||||||
uploadedFile.fileURL = 'https://' + process.env.AWS_ENDPOINT + '/' + bucketName + '/' + file.filename + '-' + file.originalName
|
const protocol = process.env.AWS_USE_SSL === 'true' ? 'https://' : 'http://'
|
||||||
|
const hostPort = process.env.AWS_PORT ? `${process.env.AWS_ENDPOINT}:${process.env.AWS_PORT}` : process.env.AWS_ENDPOINT
|
||||||
|
uploadedFile.fileURL = protocol + hostPort + '/' + bucketName + '/' + file.filename + '-' + file.originalName
|
||||||
|
|
||||||
uploadedFile.fileName = file.filename + '-' + file.originalName
|
uploadedFile.fileName = file.filename + '-' + file.originalName
|
||||||
|
|
||||||
|
|||||||
+12
-18
@@ -1,30 +1,24 @@
|
|||||||
const Minio = require('minio')
|
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 accessKey = process.env.AWS_ACCESS_KEY
|
||||||
const secretKey = process.env.AWS_SECRET_KEY
|
const secretKey = process.env.AWS_SECRET_KEY
|
||||||
const region = process.env.AWS_REGION
|
const region = process.env.AWS_REGION || 'us-east-1'
|
||||||
const port = parseInt(process.env.AWS_PORT)
|
const port = parseInt(process.env.AWS_PORT) || 9000
|
||||||
|
const useSSL = process.env.AWS_USE_SSL === 'true'
|
||||||
|
|
||||||
let client
|
const clientOptions = {
|
||||||
|
|
||||||
if (process.env.NODE_ENV === 'test') {
|
|
||||||
client = new Minio.Client({
|
|
||||||
endPoint,
|
endPoint,
|
||||||
useSSL: true,
|
useSSL,
|
||||||
accessKey,
|
|
||||||
port,
|
|
||||||
secretKey,
|
|
||||||
region,
|
|
||||||
})
|
|
||||||
} else {
|
|
||||||
client = new Minio.Client({
|
|
||||||
endPoint,
|
|
||||||
useSSL: true,
|
|
||||||
accessKey,
|
accessKey,
|
||||||
secretKey,
|
secretKey,
|
||||||
region,
|
region,
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (port) {
|
||||||
|
clientOptions.port = port
|
||||||
|
}
|
||||||
|
|
||||||
|
const client = new Minio.Client(clientOptions)
|
||||||
|
|
||||||
module.exports = client
|
module.exports = client
|
||||||
|
|||||||
Reference in New Issue
Block a user