first stab on bill model

This commit is contained in:
Thomas Ruoff
2020-09-30 00:18:08 +02:00
committed by Thomas Ruoff
parent 7c6dc610b8
commit 2e73875d37
11 changed files with 112 additions and 100 deletions

79
db/bill.ts Normal file
View File

@@ -0,0 +1,79 @@
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<BillDocument> {}
const BillSchema = new mongoose.Schema<BillDocument>(
{
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 <BillModel>mongoose.models.Bill ||
mongoose.model<BillDocument, BillModel>('Bill', BillSchema)