user address

This commit is contained in:
2025-11-23 00:35:20 +03:30
parent c8b0ee3c56
commit d9dde39a20
8 changed files with 215 additions and 51 deletions
+46
View File
@@ -1,9 +1,11 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { FilterQuery, RequiredEntityData } from '@mikro-orm/core';
import { User } from './entities/user.entity';
import { UserAddress } from './entities/user-address.entity';
import { EntityManager } from '@mikro-orm/postgresql';
import { UpdateUserDto } from './dto/update-user.dto';
import { FindUsersDto } from './dto/find-user.dto';
import { CreateUserAddressDto } from './dto/create-user-address.dto';
import { PaginatedResult } from 'src/common/interfaces/pagination.interface';
import { UserRepository } from './repositories/user.repository';
@@ -137,4 +139,48 @@ export class UserService {
},
};
}
async getUserAddresses(userId: string): Promise<UserAddress[]> {
const user = await this.userRepository.findOne({ id: userId }, { populate: ['addresses'] });
if (!user) {
throw new NotFoundException(`User with ID ${userId} not found.`);
}
// Load addresses if not already loaded
await user.addresses.loadItems();
return user.addresses.getItems();
}
async createUserAddress(userId: string, dto: CreateUserAddressDto): Promise<UserAddress> {
const user = await this.userRepository.findOne({ id: userId });
if (!user) {
throw new NotFoundException(`User with ID ${userId} not found.`);
}
// If setting as default, unset other default addresses
if (dto.isDefault) {
const existingAddresses = await this.em.find(UserAddress, { user: { id: userId }, isDefault: true });
for (const address of existingAddresses) {
address.isDefault = false;
}
await this.em.flush();
}
// Create new address
const address = this.em.create(UserAddress, {
user,
title: dto.title,
address: dto.address,
city: dto.city,
province: dto.province,
postalCode: dto.postalCode,
latitude: dto.latitude,
longitude: dto.longitude,
phone: dto.phone,
isDefault: dto.isDefault ?? false,
});
await this.em.persistAndFlush(address);
return address;
}
}