delivery-address.service.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { GenericCrudService } from '@/server/utils/generic-crud.service';
  2. import { DataSource } from 'typeorm';
  3. import { DeliveryAddress } from './delivery-address.entity';
  4. export class DeliveryAddressService extends GenericCrudService<DeliveryAddress> {
  5. constructor(dataSource: DataSource) {
  6. super(dataSource, DeliveryAddress);
  7. }
  8. /**
  9. * 获取用户的收货地址列表
  10. * @param userId 用户ID
  11. * @returns 收货地址列表
  12. */
  13. async findByUser(userId: number): Promise<DeliveryAddress[]> {
  14. return this.repository.find({
  15. where: { userId, state: 1 },
  16. relations: ['user', 'province', 'city', 'district', 'town'],
  17. order: { isDefault: 'DESC', createdAt: 'DESC' }
  18. });
  19. }
  20. /**
  21. * 设置默认地址
  22. * @param id 地址ID
  23. * @param userId 用户ID
  24. * @returns 是否设置成功
  25. */
  26. async setDefault(id: number, userId: number): Promise<boolean> {
  27. await this.repository.manager.transaction(async (transactionalEntityManager) => {
  28. // 先将该用户的所有地址设为非默认
  29. await transactionalEntityManager.update(DeliveryAddress,
  30. { userId },
  31. { isDefault: 0 }
  32. );
  33. // 将指定地址设为默认
  34. await transactionalEntityManager.update(DeliveryAddress,
  35. { id, userId },
  36. { isDefault: 1 }
  37. );
  38. });
  39. return true;
  40. }
  41. /**
  42. * 获取用户的默认地址
  43. * @param userId 用户ID
  44. * @returns 默认地址或null
  45. */
  46. async findDefaultByUser(userId: number): Promise<DeliveryAddress | null> {
  47. return this.repository.findOne({
  48. where: { userId, isDefault: 1, state: 1 },
  49. relations: ['user', 'province', 'city', 'district', 'town']
  50. });
  51. }
  52. }