Files
pfadi-bussle/helpers/bill.ts
2021-06-21 23:41:38 +02:00

93 lines
1.7 KiB
TypeScript

import { MILAGE_TARIFS } from '../db/enums'
import { AdditionalCost, Bill } from '../db/bill'
import fetch from './fetch'
function roundToCent(amount: number): number {
return Math.round(amount * 100) / 100
}
export function getMilageCosts({
tarif,
km,
}: {
tarif: MILAGE_TARIFS
km: number
}): number {
if (tarif === MILAGE_TARIFS.NOCHARGE) {
return 0
}
if (km <= 0) {
return 0
}
let rate: number
if (tarif === MILAGE_TARIFS.EXTERN) {
if (km <= 200) {
rate = 0.42
} else if (km <= 1000) {
rate = 0.25
} else if (km <= 2000) {
rate = 0.2
} else {
rate = 0.18
}
}
if (tarif === MILAGE_TARIFS.INTERN) {
if (km <= 200) {
rate = 0.37
} else if (km <= 1000) {
rate = 0.22
} else if (km <= 2000) {
rate = 0.15
} else {
rate = 0.13
}
}
if (rate === undefined) {
throw Error('Unable to determine rate')
}
return roundToCent(km * rate)
}
export function getBillTotal({
tarif,
milage,
additionalCosts,
}: {
tarif: MILAGE_TARIFS
milage?: number
additionalCosts: AdditionalCost[]
}): number {
const milageCosts = getMilageCosts({ tarif, km: milage })
const additionalCostsSum = additionalCosts
.map(({ value }) => value)
.reduce((acc: number, value: number) => acc + value, 0)
return roundToCent(milageCosts + additionalCostsSum)
}
export async function createBill(
bookingUuid: string,
bill: Bill
): Promise<Bill> {
return fetch(`/api/bookings/${bookingUuid}/bill`, {
method: 'POST',
body: bill,
})
}
export async function patchBill(
bookingUuid: string,
bill: Bill
): Promise<Bill> {
return fetch(`/api/bookings/${bookingUuid}/bill`, {
method: 'POST',
body: bill,
})
}