import html import re import xml.etree.ElementTree as ET from datetime import datetime, timezone from typing import Dict, Any, Tuple from sqlalchemy.orm import Session from app.core.config.Config import settings import app.models.db_base from app.models.ProductModel import Product, ProductVariant from app.models.CategoryModel import Category from app.models.BrandModel import Brand _feed_cache = { "xml": None, "generated_at": None, "stats": {} } def clean_html(raw_html: str) -> str: if not raw_html: return "" # Strip HTML tags clean = re.sub(r'<[^>]+>', ' ', raw_html) # Collapse multiple whitespaces clean = re.sub(r'\s+', ' ', clean).strip() return html.escape(clean[:1000]) def generate_google_merchant_xml(db: Session, force_refresh: bool = False) -> Tuple[str, Dict[str, Any]]: global _feed_cache # Return cache if valid within 1 hour and not forced if not force_refresh and _feed_cache["xml"] and _feed_cache["generated_at"]: age_seconds = (datetime.now(timezone.utc) - _feed_cache["generated_at"]).total_seconds() if age_seconds < 3600: return _feed_cache["xml"], _feed_cache["stats"] base_url = settings.MERCHANT_CENTER_STORE_URL.rstrip('/') currency = settings.MERCHANT_CENTER_DEFAULT_CURRENCY store_name = settings.MERCHANT_CENTER_STORE_NAME # Query active products with variants, brand, and category products = db.query(Product).filter( Product.status.in_(["active", "draft"]) ).limit(1000).all() total_count = len(products) eligible_count = 0 missing_image_count = 0 missing_price_count = 0 # Build RSS 2.0 structure rss = ET.Element("rss", { "version": "2.0", "xmlns:g": "http://base.google.com/ns/1.0" }) channel = ET.SubElement(rss, "channel") ET.SubElement(channel, "title").text = f"{store_name} Official Product Feed" ET.SubElement(channel, "link").text = base_url ET.SubElement(channel, "description").text = f"{store_name} unified e-commerce & smartphone/laptop repair spare parts catalog." for prod in products: # Find active variant or first variant variant = prod.variants[0] if prod.variants else None # Price price_val = 0.0 if variant and variant.price is not None: price_val = float(variant.price) elif prod.location_mappings and len(prod.location_mappings) > 0: price_val = float(prod.location_mappings[0].selling_price or 0.0) if price_val <= 0: missing_price_count += 1 continue # Image image_url = None if prod.images and len(prod.images) > 0: first_img = prod.images[0].image_url if first_img.startswith("http"): image_url = first_img else: image_url = f"https://ifixkartbe.trionixsolution.com/uploads/{first_img.lstrip('/')}" else: image_url = f"{base_url}/images/placeholder-product.png" missing_image_count += 1 # Stock availability total_stock = 0 if prod.location_mappings: total_stock = sum(loc.stock_quantity or 0 for loc in prod.location_mappings) elif variant and variant.status == "active": total_stock = 10 # Active sellable fallback availability = "in_stock" if total_stock > 0 else "out_of_stock" # Brand brand_name = prod.brand.name if prod.brand else "iFixKart" # Item XML item = ET.SubElement(channel, "item") ET.SubElement(item, "g:id").text = prod.product_id ET.SubElement(item, "g:title").text = prod.name[:150] ET.SubElement(item, "g:description").text = clean_html(prod.description or prod.name) ET.SubElement(item, "g:link").text = f"{base_url}/product/{prod.slug}" ET.SubElement(item, "g:image_link").text = image_url ET.SubElement(item, "g:availability").text = availability ET.SubElement(item, "g:price").text = f"{price_val:.2f} {currency}" ET.SubElement(item, "g:brand").text = brand_name ET.SubElement(item, "g:condition").text = "new" ET.SubElement(item, "g:identifier_exists").text = "no" # Category mapping cat_name = prod.category.name if prod.category else "Electronics" ET.SubElement(item, "g:google_product_category").text = f"Electronics > Communications > Telephony > Mobile Phone Accessories" ET.SubElement(item, "g:product_type").text = cat_name eligible_count += 1 xml_declaration = '\n' xml_str = xml_declaration + ET.tostring(rss, encoding="utf-8").decode("utf-8") stats = { "total_products": total_count, "eligible_products": eligible_count, "missing_images": missing_image_count, "missing_prices": missing_price_count, "generated_at": datetime.now(timezone.utc).isoformat(), "store_name": store_name, "store_url": base_url, "feed_url": f"{base_url}/api/v1/storefront/feed/google-merchant.xml" } _feed_cache["xml"] = xml_str _feed_cache["generated_at"] = datetime.now(timezone.utc) _feed_cache["stats"] = stats return xml_str, stats