"""Every delivery option the Site offers, from every carrier configured. The cart asks for all options at once and shows them cheapest first; the customer's choice is quoted again by the server when the cart is approved. A carrier that does not answer leaves its options out instead of blocking the others. """ from concurrent.futures import ThreadPoolExecutor class FreightOptions: name = 'carriers' def __init__(self, carriers): self.carriers = carriers self.by_service = {service: carrier for carrier in carriers for service in carrier.services} @property def services(self): return {service: carrier.services[service] for service, carrier in self.by_service.items()} def carrier(self, name): return next((c for c in self.carriers if c.name == name), None) def quote(self, service, postal_code, metres=None, declared_cents=0): if service == 'pickup': return {'provider': self.name, 'service': 'pickup', 'total_cents': 0, 'postal_code': ''} carrier = self.by_service.get(service) if not carrier: raise ValueError('Esta forma de entrega não está disponível. Escolha outra.') return carrier.quote(service, postal_code, metres, declared_cents) def options(self, postal_code, metres=None, declared_cents=0): """Each service's quote, cheapest first, and why any could not be quoted.""" services = list(self.by_service) with ThreadPoolExecutor(max_workers=max(1, len(services))) as pool: futures = {service: pool.submit(self.quote, service, postal_code, metres, declared_cents) for service in services} found, missing = [], [] for service, future in futures.items(): try: found.append(future.result()) except ValueError as error: missing.append({'service': service, 'description': self.services[service], 'error': str(error)}) found.sort(key=lambda option: (option['total_cents'], option.get('days') or 99)) return {'options': found, 'unavailable': missing}