111 lines
2.8 KiB
JavaScript
111 lines
2.8 KiB
JavaScript
const BaseFinancialRepository = require('./BaseFinancialRepository');
|
|
const logger = require('../../../src/utils/logger');
|
|
|
|
/**
|
|
* Payment Repository
|
|
*
|
|
* Manages payment tracking for invoices.
|
|
*/
|
|
class PaymentRepository extends BaseFinancialRepository {
|
|
constructor() {
|
|
super('pg_fn_payments');
|
|
}
|
|
|
|
/**
|
|
* Find payments for a unit
|
|
* @param {string} unitId - Unit ID
|
|
* @param {Object} options - Query options
|
|
* @returns {Promise<Array>} Array of payments
|
|
*/
|
|
async findByUnitId(unitId, options = {}) {
|
|
try {
|
|
return await this.findAll({ unit_id: unitId }, {
|
|
orderBy: 'payment_date',
|
|
orderDirection: 'desc',
|
|
...options
|
|
});
|
|
} catch (error) {
|
|
logger.error('Error finding payments by unit:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Find payments for a site
|
|
* @param {string} siteId - Site ID
|
|
* @returns {Promise<Array>} Array of payments
|
|
*/
|
|
async findBySiteId(siteId) {
|
|
try {
|
|
return await this.findAll({ site_id: siteId }, {
|
|
orderBy: 'payment_date',
|
|
orderDirection: 'desc'
|
|
});
|
|
} catch (error) {
|
|
logger.error('Error finding payments by site:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Find payments for an invoice
|
|
* @param {string} invoiceId - Invoice ID
|
|
* @returns {Promise<Array>} Array of payments
|
|
*/
|
|
async findByInvoiceId(invoiceId) {
|
|
try {
|
|
return await this.findAll({ invoice_id: invoiceId }, { orderBy: 'payment_date' });
|
|
} catch (error) {
|
|
logger.error('Error finding payments by invoice:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Create payment record
|
|
* @param {Object} paymentData - Payment data
|
|
* @returns {Promise<Object>} Created payment
|
|
*/
|
|
async createPayment(paymentData) {
|
|
try {
|
|
// Validate required fields
|
|
if (!paymentData.site_id || !paymentData.unit_id || !paymentData.payment_amount ||
|
|
!paymentData.payment_method) {
|
|
throw new Error('Missing required fields for payment');
|
|
}
|
|
|
|
// Set defaults
|
|
const payment = {
|
|
...paymentData,
|
|
payment_date: paymentData.payment_date || new Date().toISOString().split('T')[0],
|
|
created_at: new Date().toISOString()
|
|
};
|
|
|
|
return await this.create(payment);
|
|
} catch (error) {
|
|
logger.error('Error creating payment:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get total payments for a unit
|
|
* @param {string} unitId - Unit ID
|
|
* @returns {Promise<number>} Total payment amount
|
|
*/
|
|
async getTotalPayments(unitId) {
|
|
try {
|
|
const payments = await this.findByUnitId(unitId);
|
|
return payments.reduce((total, payment) => {
|
|
return total + parseFloat(payment.payment_amount || 0);
|
|
}, 0);
|
|
} catch (error) {
|
|
logger.error('Error calculating total payments:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
}
|
|
|
|
module.exports = PaymentRepository;
|
|
|
|
|