61 lines
1.8 KiB
JavaScript
61 lines
1.8 KiB
JavaScript
// /components/payments/paymentValidator.js
|
|
'use strict';
|
|
|
|
const AppError = require('../../utils/AppError');
|
|
|
|
const PAYMENT_METHODS = new Set(['online', 'card', 'cash']);
|
|
const TRANSACTION_STATUSES = new Set(['pending', 'paid', 'cancelled', 'reverted']);
|
|
|
|
const passThrough = (req, res, next) => next();
|
|
|
|
const validateTransactionBody = (body, { requireAmount = true } = {}) => {
|
|
const details = {};
|
|
|
|
if (requireAmount && (body.amount === undefined || body.amount === null || Number(body.amount) <= 0)) {
|
|
details.amount = 'مبلغ تراکنش باید بیشتر از صفر باشد';
|
|
} else if (body.amount !== undefined && Number(body.amount) < 0) {
|
|
details.amount = 'مبلغ تراکنش نمیتواند منفی باشد';
|
|
}
|
|
|
|
if (body.status !== undefined && !TRANSACTION_STATUSES.has(body.status)) {
|
|
details.status = 'وضعیت تراکنش نامعتبر است';
|
|
}
|
|
|
|
if (body.method !== undefined && body.method !== '' && !PAYMENT_METHODS.has(body.method)) {
|
|
details.method = 'روش پرداخت نامعتبر است';
|
|
}
|
|
|
|
if (body.notes !== undefined && String(body.notes).length > 5000) {
|
|
details.notes = 'یادداشت نباید بیش از ۵۰۰۰ کاراکتر باشد';
|
|
}
|
|
|
|
if (Object.keys(details).length) {
|
|
throw new AppError('VALIDATION_FAILED', details);
|
|
}
|
|
};
|
|
|
|
const validateAddTransaction = (req, res, next) => {
|
|
try {
|
|
validateTransactionBody(req.body || {}, { requireAmount: true });
|
|
next();
|
|
} catch (err) {
|
|
next(err);
|
|
}
|
|
};
|
|
|
|
const validateUpdateTransaction = (req, res, next) => {
|
|
try {
|
|
validateTransactionBody(req.body || {}, { requireAmount: false });
|
|
next();
|
|
} catch (err) {
|
|
next(err);
|
|
}
|
|
};
|
|
|
|
module.exports = {
|
|
validateCreatePayment: passThrough,
|
|
validateUpdatePayment: passThrough,
|
|
validateAddTransaction,
|
|
validateUpdateTransaction
|
|
};
|