import * as mongoose from 'mongoose' import { BILLING_RATES } from './billingRates' import { PAYMENT_STATE } from './paymentState' import { BookingDocument } from './booking' export interface AdditionalCosts { name: string value: number } export interface BookingBillDocument extends mongoose.SchemaTimestampsConfig, mongoose.Document { booking: BookingDocument milageStart: number milageEnd: number milage?: number rate: BILLING_RATES paymentState: PAYMENT_STATE additionalCosts: AdditionalCosts[] } export interface BookingBillModel extends mongoose.Model {} const BookingBillSchema = 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(BILLING_RATES), default: BILLING_RATES.EXTERN_UP_TO_200, required: true, }, paymentState: { type: String, enum: Object.values(PAYMENT_STATE), default: PAYMENT_STATE.OUTSTANDING, required: true, }, additionalCosts: [ { name: { type: String, required: true }, value: { type: Number, required: true }, }, ], }, { timestamps: true, collation: { locale: 'de', strength: 1 } } ) BookingBillSchema.virtual('milage').get(function () { if (!this.milageStart || !this.milageEnd) { return null } return this.milageEnd - this.milageStart }) BookingBillSchema.virtual('invoiceAmount').get(function () { if (!this.milageStart || !this.milageEnd) { return null } const milageCosts = this.milage * this.rate const additionalCostSum = this.additionalConsts.reduce( (memo: number, { value }) => memo + value, 0 ) return milageCosts + additionalCostSum }) export default mongoose.models.BookingBill || mongoose.model( 'BookingBill', BookingBillSchema )