import * as mongoose from 'mongoose' import { BILL_STATUS, MILAGE_RATES } from './enums' import { BookingDocument } from './booking' export interface AdditionalCosts { name: string value: number } export interface BillDocument extends mongoose.SchemaTimestampsConfig, mongoose.Document { booking: BookingDocument milageStart: number milageEnd: number milage?: number rate: MILAGE_RATES status: BILL_STATUS additionalCosts: AdditionalCosts[] } export interface BillModel extends mongoose.Model {} const BillSchema = new mongoose.Schema( { booking: { type: mongoose.Schema.Types.ObjectId, ref: 'Booking', required: true, }, milageStart: { type: Number, required: true }, milageEnd: { type: Number, required: true }, rate: { type: Number, enum: Object.values(MILAGE_RATES), default: MILAGE_RATES.EXTERN_UP_TO_200, required: true, }, status: { type: String, enum: Object.values(BILL_STATUS), default: BILL_STATUS.UNINVOICED, required: true, }, additionalCosts: [ { name: { type: String, required: true }, value: { type: Number, required: true }, }, ], }, { timestamps: true, collation: { locale: 'de', strength: 1 } } ) BillSchema.virtual('milage').get(function () { const bill = this as BillDocument if (!bill.milageStart || !bill.milageEnd) { return null } return bill.milageEnd - bill.milageStart }) BillSchema.virtual('total').get(function () { const bill = this as BillDocument if (!bill.milageStart || !bill.milageEnd) { return null } const milageCosts = bill.milage * bill.rate const additionalCostSum = bill.additionalCosts .map(({ value }) => value) .reduce((acc, value) => acc + value, 0) return milageCosts + additionalCostSum }) export default mongoose.models.Bill || mongoose.model('Bill', BillSchema)