product_routing_service.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # app/services/product_routing_service.py
  2. from typing import List
  3. from sqlalchemy.ext.asyncio import AsyncSession
  4. from sqlalchemy import select, delete
  5. from app.core.biz_exception import NotFoundError
  6. from app.models.product_routing import VasProductRouting
  7. from app.schemas.product_routing import VasProductRoutingCreate, VasProductRoutingUpdate
  8. class ProductRoutingService:
  9. @staticmethod
  10. async def create(
  11. db: AsyncSession,
  12. data: VasProductRoutingCreate,
  13. ) -> VasProductRouting:
  14. rec = VasProductRouting(**data.model_dump(exclude_unset=True, by_alias=True))
  15. db.add(rec)
  16. await db.commit()
  17. await db.refresh(rec)
  18. return rec
  19. @staticmethod
  20. async def update(
  21. db: AsyncSession,
  22. id: int,
  23. data: VasProductRoutingUpdate,
  24. ) -> VasProductRouting:
  25. stmt = select(VasProductRouting).where(
  26. VasProductRouting.id == id
  27. )
  28. obj = (await db.execute(stmt)).scalar_one_or_none()
  29. if not obj:
  30. raise NotFoundError("Product routing not exist")
  31. update_data = data.model_dump(exclude_unset=True, by_alias=True)
  32. for k, v in update_data.items():
  33. setattr(obj, k, v)
  34. await db.commit()
  35. await db.refresh(obj)
  36. return obj
  37. @staticmethod
  38. async def list_by_product(
  39. db: AsyncSession,
  40. product_id: int,
  41. ) -> List[VasProductRouting]:
  42. stmt = select(VasProductRouting).where(
  43. VasProductRouting.product_id == product_id
  44. )
  45. result = await db.execute(stmt)
  46. return result.scalars().all()
  47. @staticmethod
  48. async def delete(
  49. db: AsyncSession,
  50. id: int,
  51. ) -> None:
  52. stmt = select(VasProductRouting).where(
  53. VasProductRouting.id == id
  54. )
  55. obj = (await db.execute(stmt)).scalar_one_or_none()
  56. if not obj:
  57. raise NotFoundError("Product routing not exist")
  58. await db.delete(obj)
  59. await db.commit()