backend/src/models/entities/RunnerCard.ts

86 lines
2.1 KiB
TypeScript
Raw Normal View History

2020-12-01 17:16:17 +00:00
import {
IsBoolean,
2021-01-09 10:48:13 +00:00
2020-12-01 17:16:17 +00:00
IsInt,
2021-01-09 10:48:13 +00:00
IsOptional
2020-12-01 17:16:17 +00:00
} from "class-validator";
import { Column, Entity, ManyToOne, OneToMany, PrimaryGeneratedColumn } from "typeorm";
2021-01-09 11:24:05 +00:00
import { RunnerCardIdOutOfRangeError } from '../../errors/RunnerCardErrors';
import { ResponseRunnerCard } from '../responses/ResponseRunnerCard';
2020-12-01 17:16:17 +00:00
import { Runner } from "./Runner";
2020-12-02 14:40:25 +00:00
import { TrackScan } from "./TrackScan";
2020-12-01 17:16:17 +00:00
/**
* Defines the RunnerCard entity.
* A runnerCard is a physical representation for a runner.
* It can be associated with a runner to create scans via the scan station's.
2020-12-01 17:16:17 +00:00
*/
@Entity()
export class RunnerCard {
/**
* Autogenerated unique id (primary key).
*/
@PrimaryGeneratedColumn()
@IsInt()
id: number;
/**
* The card's currently associated runner.
* To increase reusability a card can be reassigned.
2020-12-01 17:16:17 +00:00
*/
@IsOptional()
@ManyToOne(() => Runner, runner => runner.cards, { nullable: true })
2020-12-01 17:16:17 +00:00
runner: Runner;
/**
* Is the card enabled (for fraud reasons)?
2020-12-02 17:05:18 +00:00
* Default: true
2020-12-01 17:16:17 +00:00
*/
@Column()
@IsBoolean()
2020-12-02 17:05:18 +00:00
enabled: boolean = true;
2020-12-02 14:40:25 +00:00
/**
* The card's associated scans.
* Used to link cards to track scans.
2020-12-02 14:40:25 +00:00
*/
@OneToMany(() => TrackScan, scan => scan.track, { nullable: true })
2020-12-02 14:40:25 +00:00
scans: TrackScan[];
2021-01-09 10:48:13 +00:00
/**
* Generates a ean-13 compliant string for barcode generation.
*/
public get code(): string {
2021-01-09 11:24:05 +00:00
const multiply = [1, 3];
let total = 0;
this.paddedId.split('').forEach((letter, index) => {
total += parseInt(letter, 10) * multiply[index % 2];
});
const checkSum = (Math.ceil(total / 10) * 10) - total;
return this.paddedId + checkSum.toString();
}
/**
* Returns this card's id as a string padded to the length of 12 characters with leading zeros.
*/
private get paddedId(): string {
let id: string = this.id.toString();
2021-04-22 17:41:18 +00:00
if (id.length > 11) {
2021-01-09 11:24:05 +00:00
throw new RunnerCardIdOutOfRangeError();
}
2021-04-22 17:41:18 +00:00
while (id.length < 11) { id = '0' + id; }
id = '2' + id;
2021-01-09 11:24:05 +00:00
return id;
2021-01-09 10:48:13 +00:00
}
/**
* Turns this entity into it's response class.
*/
public toResponse() {
return new ResponseRunnerCard(this);
}
2020-12-01 17:16:17 +00:00
}