import { Injectable, NotFoundException } from '@nestjs/common'; import { BankCard, Cash, User } from '@prisma/client'; import { PrismaService } from '@/modules/prisma/prisma.service'; import { CashDto, CreateCashDto, EditCashDto } from './dto'; @Injectable() export class CashService { constructor(private readonly prismaService: PrismaService) {} public async createCash(userId: User['id'], dto: CreateCashDto): Promise { const { balance, name } = dto; return this.prismaService.cash.create({ data: { name, balance, user: { connect: { id: userId }, }, }, }); } public async getCashById(userId: User['id'], cashId: Cash['id']): Promise { const cash = await this.prismaService.cash.findUnique({ where: { id: cashId, userId, }, }); if (!cash) { throw new NotFoundException('Кэш не найден'); } return cash; } public async getAllCashByUserId(userId: User['id']): Promise { return this.prismaService.cash.findMany({ where: { userId }, orderBy: { createdAt: 'asc' }, }); } public async editCash(userId: User['id'], cashId: Cash['id'], dto: EditCashDto): Promise { const { balance, name } = dto; const cash = await this.getCashById(userId, cashId); return this.prismaService.cash.update({ where: { id: cashId }, data: { name: name ?? cash.name, balance: balance ?? cash.balance, }, }); } public async deleteCash(userId: User['id'], cashId: Cash['id']): Promise { const cash = await this.getCashById(userId, cashId); return this.prismaService.cash.delete({ where: { id: cash.id }, }); } public async addExpense(userId: User['id'], cashId: BankCard['id'], amount: number) { const cash = await this.getCashById(userId, cashId); await this.editCash(userId, cash.id, { balance: cash.balance - amount }); } }