Move embedded payment rows into Transaction documents with due dates so remaining tuition can be tracked separately from paid amounts.
76 lines
1.6 KiB
JavaScript
76 lines
1.6 KiB
JavaScript
// /components/payments/paymentModel.js
|
|
'use strict';
|
|
|
|
const mongoose = require('mongoose');
|
|
|
|
const { getPayableAmount, normalizeDiscount } = require('../../utils/paymentAmount');
|
|
require('./transactionModel');
|
|
|
|
const paymentSchema = new mongoose.Schema({
|
|
user: {
|
|
type: mongoose.Schema.Types.ObjectId,
|
|
ref: 'User',
|
|
required: true,
|
|
index: true
|
|
},
|
|
classes: [{
|
|
type: mongoose.Schema.Types.ObjectId,
|
|
ref: 'Class'
|
|
}],
|
|
course: {
|
|
type: mongoose.Schema.Types.ObjectId,
|
|
ref: 'Course'
|
|
},
|
|
amount: {
|
|
type: Number,
|
|
required: true,
|
|
min: 0
|
|
},
|
|
discount: {
|
|
type: Number,
|
|
default: 0,
|
|
min: 0
|
|
},
|
|
paidAmount: {
|
|
type: Number,
|
|
default: 0,
|
|
min: 0
|
|
},
|
|
dueDate: {
|
|
type: Date
|
|
},
|
|
status: {
|
|
type: String,
|
|
enum: ['pending', 'partial', 'paid', 'overdue'],
|
|
default: 'pending'
|
|
},
|
|
notes: { type: String, trim: true, maxlength: 5000 }
|
|
}, {
|
|
timestamps: true,
|
|
toJSON: { virtuals: true },
|
|
toObject: { virtuals: true }
|
|
});
|
|
|
|
paymentSchema.virtual('transactions', {
|
|
ref: 'Transaction',
|
|
localField: '_id',
|
|
foreignField: 'payment'
|
|
});
|
|
|
|
paymentSchema.pre('save', function (next) {
|
|
this.discount = normalizeDiscount(this.discount, this.amount);
|
|
const payable = getPayableAmount(this);
|
|
if (this.paidAmount >= payable) {
|
|
this.status = 'paid';
|
|
} else if (this.paidAmount > 0) {
|
|
this.status = 'partial';
|
|
} else if (this.dueDate && new Date() > this.dueDate) {
|
|
this.status = 'overdue';
|
|
} else {
|
|
this.status = 'pending';
|
|
}
|
|
next();
|
|
});
|
|
|
|
module.exports = mongoose.model('Payment', paymentSchema);
|