import * as mongoose from 'mongoose' import { BILL_STATUS, MILAGE_TARIFS } from './enums' import { getBillTotal } from '../helpers/bill' export interface AdditionalCost { name: string value: number } export interface BillDocument extends mongoose.SchemaTimestampsConfig, mongoose.Document { milageStart: number milageEnd: number milage?: number tarif: MILAGE_TARIFS status: BILL_STATUS additionalCosts: AdditionalCost[] } export interface BillModel extends mongoose.Model {} const BillSchema = new mongoose.Schema( { milageStart: { type: Number, required: true, validate: { validator: function (v: number) { const bill = this as BillDocument return v <= bill.milageEnd }, message: (props) => `${props.value} is bigger than milageEnd!`, }, }, milageEnd: { type: Number, required: true, validate: { validator: function (v: number) { const bill = this as BillDocument return v >= bill.milageStart }, message: (props) => `${props.value} is smaller than milageStart!`, }, }, tarif: { type: String, enum: Object.values(MILAGE_TARIFS), default: MILAGE_TARIFS.EXTERN, required: true, }, additionalCosts: [ { name: { type: String, required: true }, value: { type: Number, required: true }, }, ], status: { type: String, enum: Object.values(BILL_STATUS), default: BILL_STATUS.UNINVOICED, }, }, { timestamps: true, toJSON: { virtuals: true, getters: true }, toObject: { virtuals: true, getters: true }, } ) BillSchema.virtual('milage').get(function () { const bill = this as BillDocument return bill.milageEnd - bill.milageStart }) BillSchema.virtual('total').get(function () { const bill = this as BillDocument return getBillTotal(bill) }) export default mongoose.models.Bill || mongoose.model('Bill', BillSchema)