Files
pfadi-bussle/db/bill.ts
2021-06-16 23:36:28 +02:00

92 lines
2.1 KiB
TypeScript

import * as mongoose from 'mongoose'
import { BILL_STATUS, MILAGE_TARIFS } from './enums'
import { getBillTotal } from '../helpers/bill'
export type AdditionalCost = {
name: string
value: number
}
export type Bill = {
milageStart: number
milageEnd: number
milage?: number
tarif: MILAGE_TARIFS
status: BILL_STATUS
additionalCosts: AdditionalCost[]
}
export type BillDocument = Bill &
mongoose.SchemaTimestampsConfig &
mongoose.Document
export type BillModel = mongoose.Model<BillDocument>
const BillSchema = new mongoose.Schema<BillDocument>(
{
milageStart: {
type: Number,
required: true,
validate: {
validator: function (v: number): boolean {
const bill = this as BillDocument
return v <= bill.milageEnd
},
message: (props: { value: Number }) =>
`${props.value} is bigger than milageEnd!`,
},
},
milageEnd: {
type: Number,
required: true,
validate: {
validator: function (v: number): boolean {
const bill = this as BillDocument
return v >= bill.milageStart
},
message: (props: { value: Number }) =>
`${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 (): number {
const bill = this as BillDocument
return bill.milageEnd - bill.milageStart
})
BillSchema.virtual('total').get(function (): number {
const bill = this as BillDocument
return getBillTotal(bill)
})
export default <BillModel>mongoose.models.Bill ||
mongoose.model<BillDocument, BillModel>('Bill', BillSchema)