BuyingAgent/backend/app/services/import_service.py

95 lines
3.9 KiB
Python
Raw Permalink Normal View History

from app.errors import AppError
from app.services.ingestion_service import IngestionService
from app.sources.base import ProductSource
class ImportService:
def __init__(self, ingestion: IngestionService) -> None:
self.ingestion = ingestion
def import_product(self, source: ProductSource, external_id: str) -> None:
product = source.get_product(external_id)
try:
self.ingestion.create_product(
{
"id": product.id,
"category": product.category,
"brand": product.brand,
"name": product.name,
"model": product.model,
}
)
except AppError as exc:
if exc.status_code != 409:
raise
for variant in product.variants:
try:
self.ingestion.create_variant(
product.id,
{
"id": variant.id,
"name": variant.name,
"manufacturer_sku": variant.manufacturer_sku,
"identifiers": variant.identifiers,
},
)
except AppError as exc:
if exc.status_code != 409:
raise
for attribute in variant.attributes:
try:
self.ingestion.add_attribute(
variant.id,
{
"id": attribute.id,
"attribute": attribute.attribute,
"raw_value": attribute.raw_value,
"normalized_value": attribute.normalized_value,
"unit": attribute.unit,
"normalization_status": attribute.normalization_status,
"normalizer_version": attribute.normalizer_version,
"confidence": attribute.confidence,
"source_id": source.source_key,
"source_reference": attribute.source_reference,
"observed_at": attribute.observed_at,
"normalization_error": attribute.normalization_error,
},
)
except AppError as exc:
if exc.status_code != 409:
raise
for offer in source.get_offers(external_id):
try:
self.ingestion.create_offer(
offer.variant_id,
{
"id": offer.id,
"source_id": source.source_key,
"external_id": offer.external_id,
"seller": offer.seller,
"url": offer.url,
"market": offer.market,
"currency": offer.currency,
"condition": offer.condition,
},
)
except AppError as exc:
if exc.status_code != 409:
raise
for price in source.get_price_history(offer.external_id):
self.ingestion.add_price(
offer.id,
{
"id": price.id,
"source_id": source.source_key,
"external_observation_id": price.external_observation_id,
"observed_at": price.observed_at,
"item_price": price.item_price,
"shipping_price": price.shipping_price,
"currency": price.currency,
"availability": price.availability,
"raw_payload": price.raw_payload,
"confidence": price.confidence,
},
)