forked from Yara724/api
76 lines
2.0 KiB
TypeScript
76 lines
2.0 KiB
TypeScript
import {
|
|
HttpException,
|
|
HttpStatus,
|
|
Injectable,
|
|
NotFoundException,
|
|
} from "@nestjs/common";
|
|
import { Types } from "mongoose";
|
|
import { PlateDbService } from "src/plates/entites/db-service/plate.db.service";
|
|
import { AddPlateDto } from "src/profile/dto/user/AddPlateDto";
|
|
import { PlateNormalizerService } from "src/utils/plate-normalizer/plate-normalizer.service";
|
|
|
|
@Injectable()
|
|
export class PlatesService {
|
|
constructor(
|
|
private readonly plateDbService: PlateDbService,
|
|
private readonly plateNormalizer: PlateNormalizerService,
|
|
) {}
|
|
|
|
async addPlate(currentUser, body: AddPlateDto) {
|
|
const { plate, nationalCodeOfInsurer } = body;
|
|
|
|
const normalizedAlphabet = this.plateNormalizer.normalizePlateText(String(plate.centerAlphabet || ""));
|
|
const duplicate = await this.plateDbService.findOne({
|
|
userId: currentUser,
|
|
leftDigits: plate.leftDigits,
|
|
centerAlphabet: normalizedAlphabet,
|
|
centerDigits: plate.centerDigits,
|
|
ir: plate.ir,
|
|
nationalCodeOfInsurer,
|
|
});
|
|
|
|
if (duplicate)
|
|
throw new HttpException("duplicate plate", HttpStatus.CONFLICT);
|
|
|
|
const newPlateData = await this.plateDbService.create({
|
|
...plate,
|
|
centerAlphabet: normalizedAlphabet,
|
|
userId: currentUser,
|
|
nationalCodeOfInsurer: body.nationalCodeOfInsurer,
|
|
});
|
|
|
|
return {
|
|
message: "Plate successfully added",
|
|
plate: newPlateData,
|
|
};
|
|
}
|
|
|
|
private async checkUniquePlate(plate): Promise<boolean> {
|
|
const {
|
|
userId,
|
|
leftDigits,
|
|
centerAlphabet,
|
|
centerDigits,
|
|
ir,
|
|
nationalCodeOfInsurer,
|
|
} = plate;
|
|
|
|
const found = await this.plateDbService.findOne({
|
|
leftDigits,
|
|
centerAlphabet,
|
|
centerDigits,
|
|
userId,
|
|
nationalCodeOfInsurer,
|
|
ir,
|
|
});
|
|
|
|
return !found;
|
|
}
|
|
|
|
async deletePlate(id: Types.ObjectId) {
|
|
const deleted = await this.plateDbService.findAndRemove(id);
|
|
if (!deleted) throw new NotFoundException("Plate not found");
|
|
return { message: "Plate deleted successfully" };
|
|
}
|
|
}
|