mirror of
https://github.com/tomru/pfadi-bussle.git
synced 2026-03-03 06:27:11 +01:00
100 lines
2.4 KiB
TypeScript
100 lines
2.4 KiB
TypeScript
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
|
|
total: number
|
|
status: BILL_STATUS
|
|
additionalCosts: AdditionalCosts[]
|
|
}
|
|
|
|
export interface BillModel extends mongoose.Model<BillDocument> {}
|
|
|
|
const BillSchema = new mongoose.Schema<BillDocument>(
|
|
{
|
|
booking: {
|
|
type: mongoose.Schema.Types.ObjectId,
|
|
ref: 'Booking',
|
|
required: true,
|
|
},
|
|
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!`,
|
|
},
|
|
},
|
|
rate: {
|
|
type: String,
|
|
enum: Object.values(MILAGE_RATES),
|
|
default: MILAGE_RATES.EXTERN_UP_TO_200,
|
|
required: true,
|
|
},
|
|
additionalCosts: [
|
|
{
|
|
name: { type: String, required: true },
|
|
value: { type: Number, required: true },
|
|
},
|
|
],
|
|
total: {
|
|
type: Number,
|
|
required: true,
|
|
},
|
|
status: {
|
|
type: String,
|
|
enum: Object.values(BILL_STATUS),
|
|
default: BILL_STATUS.UNINVOICED,
|
|
},
|
|
},
|
|
{ timestamps: true, collation: { locale: 'de', strength: 1 } }
|
|
)
|
|
|
|
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
|
|
|
|
const milageCosts = bill.milage * bill.rate
|
|
const additionalCostSum = bill.additionalCosts
|
|
.map(({ value }) => value)
|
|
.reduce((acc, value) => acc + value, 0)
|
|
|
|
return milageCosts + additionalCostSum
|
|
})
|
|
|
|
export default <BillModel>mongoose.models.Bill ||
|
|
mongoose.model<BillDocument, BillModel>('Bill', BillSchema)
|