desker/apps/api/src/users/users.service.ts

88 lines
2.2 KiB
TypeScript

import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { UpdateUserDto } from './dto/update-user.dto';
import * as bcrypt from 'bcrypt';
import { JwtService } from '@nestjs/jwt';
@Injectable()
export class UsersService {
constructor(
private prisma: PrismaService,
private jwtService: JwtService,
) {}
async findAll(organizationId: string) {
return this.prisma.user.findMany({
where: { organizationId },
select: {
id: true,
email: true,
name: true,
avatarUrl: true,
avatarId: true,
role: true,
createdAt: true,
updatedAt: true,
},
orderBy: { email: 'asc' },
});
}
async findOne(id: string, organizationId: string) {
const user = await this.prisma.user.findFirst({
where: { id, organizationId },
select: {
id: true,
email: true,
name: true,
avatarUrl: true,
avatarId: true,
role: true,
createdAt: true,
updatedAt: true,
},
});
if (!user) {
throw new NotFoundException(`User with ID ${id} not found`);
}
return user;
}
async update(id: string, organizationId: string, updateUserDto: UpdateUserDto) {
const user = await this.findOne(id, organizationId);
const data: any = { ...updateUserDto };
if (data.password) {
data.password = await bcrypt.hash(data.password, 10);
}
return this.prisma.user.update({
where: { id: user.id },
data,
select: {
id: true,
email: true,
name: true,
avatarUrl: true,
avatarId: true,
role: true,
updatedAt: true,
},
});
}
async updateProfile(id: string, organizationId: string, updateUserDto: UpdateUserDto) {
// Basic user info update - can't change role via profile update
const { role, ...updateData } = updateUserDto;
return this.update(id, organizationId, updateData);
}
async createInvite(organizationId: string, role: string = 'EMPLOYEE') {
const payload = { organizationId, role, type: 'INVITE' };
const token = this.jwtService.sign(payload, { expiresIn: '7d' });
return { token };
}
}