40 lines
1.5 KiB
TypeScript
40 lines
1.5 KiB
TypeScript
import { Result } from "src/common/errors/result-error.factory";
|
|
import { toDateFromString } from "src/common/utils/date-utils";
|
|
import { ExpenseDto } from "src/time-and-attendance/expenses/expense-create.dto";
|
|
import { NormalizedExpense } from "src/time-and-attendance/utils/type.utils";
|
|
|
|
//makes sure that comments are the right length the date is of Date type
|
|
export const normalizeAndParseExpenseDto = async (dto: ExpenseDto): Promise<Result<NormalizedExpense, string>> => {
|
|
const mileage = parseOptionalNumber(dto.mileage, "mileage");
|
|
const amount = parseOptionalNumber(dto.amount, "amount");
|
|
|
|
const comment = truncate280(dto.comment);
|
|
const supervisor_comment = dto.supervisor_comment && dto.supervisor_comment.trim()
|
|
? truncate280(dto.supervisor_comment.trim()) : undefined;
|
|
|
|
const date = toDateFromString(dto.date);
|
|
|
|
return {
|
|
success: true,
|
|
data: {
|
|
date,
|
|
comment,
|
|
supervisor_comment,
|
|
amount,
|
|
mileage,
|
|
}
|
|
};
|
|
}
|
|
|
|
//makes sure that a string cannot exceed 280 chars
|
|
export const truncate280 = (input: string): string => {
|
|
return input.length > 280 ? input.slice(0, 280) : input;
|
|
}
|
|
|
|
//makes sure that the type of data of numeric values is valid
|
|
export const parseOptionalNumber = (value: unknown, field: string) => {
|
|
if (value == null) return undefined;
|
|
const parsed = Number(value);
|
|
if (Number.isNaN(parsed)) throw new Error(`Invalid value for ${field}`);
|
|
return parsed;
|
|
}; |