import { Injectable, Logger } from '@nestjs/common'; import { PrismaService } from '../prisma/prisma.service'; import { User } from './user.entity'; import { Yacht } from '../yachts/yacht.entity'; @Injectable() export class UsersService { private readonly logger = new Logger(UsersService.name); constructor(private readonly prisma: PrismaService) {} private toUser(row: { id: number; firstName: string; lastName: string; phone: string; email: string; password: string | null; companyName: string | null; inn: bigint | null; ogrn: bigint | null; yachts?: { id: number; name: string; model: string | null; year: number; length: number; userId: number }[]; }): User { const user: User = { userId: row.id, firstName: row.firstName, lastName: row.lastName, phone: row.phone, email: row.email, password: row.password ?? undefined, companyName: row.companyName ?? undefined, inn: row.inn != null ? Number(row.inn) : undefined, ogrn: row.ogrn != null ? Number(row.ogrn) : undefined, }; if (row.yachts) { user.yachts = row.yachts.map((y) => ({ yachtId: y.id, name: y.name, model: y.model ?? '', year: y.year, length: y.length, userId: y.userId, createdAt: new Date(), updatedAt: new Date(), })) as Yacht[]; } return user; } async findOne( email: string, includeYachts: boolean = false, ): Promise { const user = await this.prisma.user.findFirst({ where: { email }, include: includeYachts ? { yachts: true } : undefined, }); return user ? this.toUser(user) : undefined; } async findByPhone( phone: string, includeYachts: boolean = false, ): Promise { const user = await this.prisma.user.findUnique({ where: { phone }, include: includeYachts ? { yachts: true } : undefined, }); return user ? this.toUser(user) : undefined; } /** Создать пользователя по номеру телефона (при первой авторизации по коду). */ async createByPhone(phone: string): Promise { const created = await this.prisma.user.create({ data: { firstName: '', lastName: '', phone, email: '', }, }); return this.toUser(created); } async findById( userId: number, includeYachts: boolean = false, ): Promise { const user = await this.prisma.user.findUnique({ where: { id: userId }, include: includeYachts ? { yachts: true } : undefined, }); return user ? this.toUser(user) : undefined; } async findAll(includeYachts: boolean = false): Promise { const users = await this.prisma.user.findMany({ include: includeYachts ? { yachts: true } : undefined, }); return users.map((u) => this.toUser(u)); } }