Files
zod-backend/src/customer/services/customer.service.ts
2024-12-30 10:35:36 +03:00

64 lines
2.5 KiB
TypeScript

import { BadRequestException, Injectable, Logger } from '@nestjs/common';
import { OciService } from '~/document/services';
import { User } from '~/user/entities';
import { DeviceService } from '~/user/services';
import { UpdateCustomerRequestDto, UpdateNotificationsSettingsRequestDto } from '../dtos/request';
import { Customer } from '../entities';
import { CustomerRepository } from '../repositories/customer.repository';
@Injectable()
export class CustomerService {
private readonly logger = new Logger(CustomerService.name);
constructor(
private readonly customerRepository: CustomerRepository,
private readonly ociService: OciService,
private readonly deviceService: DeviceService,
) {}
async updateNotificationSettings(userId: string, data: UpdateNotificationsSettingsRequestDto, deviceId: string) {
this.logger.log(`Updating notification settings for user ${userId}`);
const customer = await this.findCustomerById(userId);
const notificationSettings = (await this.customerRepository.updateNotificationSettings(customer, data))
.notificationSettings;
if (data.isPushEnabled && deviceId) {
this.logger.log(`Updating device ${deviceId} with fcmToken`);
await this.deviceService.updateDevice(deviceId, {
fcmToken: data.fcmToken,
userId: userId,
});
}
this.logger.log(`Notification settings updated for user ${userId}`);
return notificationSettings;
}
async updateCustomer(userId: string, data: UpdateCustomerRequestDto): Promise<Customer> {
this.logger.log(`Updating customer ${userId}`);
await this.customerRepository.updateCustomer(userId, data);
this.logger.log(`Customer ${userId} updated successfully`);
return this.findCustomerById(userId);
}
createCustomer(customerData: Partial<Customer>, user: User) {
this.logger.log(`Creating customer for user ${user.id}`);
return this.customerRepository.createCustomer(customerData, user);
}
async findCustomerById(id: string) {
this.logger.log(`Finding customer ${id}`);
const customer = await this.customerRepository.findOne({ id });
if (!customer) {
this.logger.error(`Customer ${id} not found`);
throw new BadRequestException('CUSTOMER.NOT_FOUND');
}
if (customer.profilePicture) {
this.logger.log(`Generating pre-signed url for profile picture of customer ${id}`);
customer.profilePicture.url = await this.ociService.generatePreSignedUrl(customer.profilePicture);
}
this.logger.log(`Customer ${id} found successfully`);
return customer;
}
}