(
customer, organization, plan, draft=True, amount=100
)
| 27 | |
| 28 | |
| 29 | def get_taxjar_tax_rates( |
| 30 | customer, organization, plan, draft=True, amount=100 |
| 31 | ) -> Tuple[Dict[SubscriptionRecord, Decimal], bool]: |
| 32 | try: |
| 33 | client = taxjar.Client(api_key=settings.TAXJAR_API_KEY) |
| 34 | except Exception: |
| 35 | return 0, False |
| 36 | from_address = organization.get_address() |
| 37 | if not from_address: |
| 38 | return 0, False |
| 39 | to_address = customer.get_shipping_address() |
| 40 | if not to_address: |
| 41 | return 0, False |
| 42 | |
| 43 | # Build cache key from addresses |
| 44 | from_cache_key = ( |
| 45 | f"{from_address.line1 or 'None'}:" |
| 46 | f"{from_address.line2 or 'None'}:{from_address.city or 'None'}:" |
| 47 | f"{from_address.state or 'None'}:{from_address.postal_code or 'None'}:" |
| 48 | f"{from_address.country or 'None'}" |
| 49 | ) |
| 50 | to_cache_key = ( |
| 51 | f"{to_address.line1 or 'None'}:" |
| 52 | f"{to_address.line2 or 'None'}:{to_address.city or 'None'}:" |
| 53 | f"{to_address.state or 'None'}:{to_address.postal_code or 'None'}:" |
| 54 | f"{to_address.country or 'None'}" |
| 55 | ) |
| 56 | cache_key = f"{from_cache_key}:{to_cache_key}" |
| 57 | taxjar_code = plan.taxjar_code or "30070" |
| 58 | |
| 59 | # Check if tax rate is already in cache |
| 60 | plan_cache_key = f"{cache_key}:{taxjar_code}" |
| 61 | tax_rate = cache.get(plan_cache_key) |
| 62 | if tax_rate == "ERROR" and draft: |
| 63 | return 0, False |
| 64 | if tax_rate is not None and draft: |
| 65 | return tax_rate, True |
| 66 | # Query taxjar for tax rate |
| 67 | try: |
| 68 | response = client.tax_for_order( |
| 69 | { |
| 70 | "amount": amount, |
| 71 | "from_country": from_address.country, |
| 72 | "from_zip": from_address.postal_code, |
| 73 | "from_state": from_address.state, |
| 74 | "from_city": from_address.city, |
| 75 | "from_street": from_address.line1, |
| 76 | "to_street": to_address.line1, |
| 77 | "to_city": to_address.city, |
| 78 | "to_state": to_address.state, |
| 79 | "to_country": to_address.country, |
| 80 | "to_zip": to_address.postal_code, |
| 81 | "shipping": 0, |
| 82 | } |
| 83 | ) |
| 84 | except taxjar.exceptions.TaxJarConnectionError as e: |
| 85 | logger.error(f"TaxJarConnectionError: {e.__dict__}") |
| 86 | cache.set(plan_cache_key, "ERROR", 24 * 60 * 60) |
no test coverage detected