from datetime import datetime from .extensions import db from .models import FuelStationCompany, FuelStationPoint def sync_station_catalog(companies): added = updated = 0 incoming_keys = {row["ure_key"] for row in companies} for source in companies: row = dict(source) point_rows = row.pop("points", []) with db.session.no_autoflush: company = FuelStationCompany.query.filter_by(ure_key=row["ure_key"]).first() if company is None: company = FuelStationCompany(**row, active=True) db.session.add(company); db.session.flush(); added += 1 else: for key, value in row.items(): setattr(company, key, value) company.active = True company.fetched_at = datetime.utcnow(); updated += 1 existing = {p.ure_dkn: p for p in company.points.all()} incoming = set() for data in point_rows: key = data["ure_dkn"]; incoming.add(key) point = existing.get(key) if point is None: point = FuelStationPoint(station_company_id=company.id, ure_dkn=key); db.session.add(point) for field, value in data.items(): setattr(point, field, value) for key, point in existing.items(): if key not in incoming: db.session.delete(point) company.station_count = len(incoming) FuelStationCompany.query.filter(~FuelStationCompany.ure_key.in_(incoming_keys)).update({FuelStationCompany.active: False}, synchronize_session=False) db.session.flush() return added, updated