feat: Use customer-specific invoices endpoint

v1.3.146:
- Changed to /customers/{customerNumber}/invoices/sent
- More direct approach - fetches only that customer's invoices
- Removed unnecessary customer filtering step
- Still applies 13-month date filter
This commit is contained in:
Christian 2026-01-27 07:24:35 +01:00
parent e14aff89d7
commit 0d9f5a4332
2 changed files with 41 additions and 69 deletions

View File

@ -1 +1 @@
1.3.145 1.3.146

View File

@ -458,88 +458,60 @@ class EconomicService:
logger.info(f"📅 Will filter invoices from {start_date} onwards (13 months for yearly billed items)") logger.info(f"📅 Will filter invoices from {start_date} onwards (13 months for yearly billed items)")
async with aiohttp.ClientSession() as session: async with aiohttp.ClientSession() as session:
# Fetch from multiple endpoints to get all invoice types # Try customer-specific invoices endpoint first
# Then filter by customer and date in code # Format: /customers/{customerNumber}/invoices/sent
all_invoices = [] all_invoices = []
# Check drafts, booked, paid, unpaid endpoints logger.info(f"📋 Fetching invoices for customer {customer_number} from customer-specific endpoint")
endpoints_to_try = [ endpoint = f"{self.api_url}/customers/{customer_number}/invoices/sent"
f"{self.api_url}/invoices/drafts",
f"{self.api_url}/invoices/booked",
f"{self.api_url}/invoices/paid",
f"{self.api_url}/invoices/unpaid",
]
for endpoint in endpoints_to_try: try:
logger.info(f"📋 Fetching invoices from {endpoint}") # Pagination: Keep fetching until no more pages
page = 0
try: while True:
# Pagination: Keep fetching until no more pages async with session.get(
page = 0 endpoint,
while True: params={"pagesize": 1000, "skippages": page},
async with session.get( headers=self._get_headers()
endpoint, ) as response:
params={"pagesize": 1000, "skippages": page}, logger.info(f"🔍 [API] Response status from {endpoint} (page {page}): {response.status}")
headers=self._get_headers()
) as response: if response.status == 200:
logger.info(f"🔍 [API] Response status from {endpoint} (page {page}): {response.status}") data = await response.json()
invoices_from_endpoint = data.get('collection', [])
logger.info(f"✅ Fetched {len(invoices_from_endpoint)} invoices from {endpoint} page {page}")
if response.status == 200: if not invoices_from_endpoint:
data = await response.json()
invoices_from_endpoint = data.get('collection', [])
logger.info(f"✅ Fetched {len(invoices_from_endpoint)} invoices from {endpoint} page {page}")
if not invoices_from_endpoint:
# No more invoices on this page
break
# Add invoices (track unique by invoice number to avoid duplicates)
existing_invoice_numbers = {inv.get('draftInvoiceNumber') or inv.get('bookedInvoiceNumber') for inv in all_invoices if inv.get('draftInvoiceNumber') or inv.get('bookedInvoiceNumber')}
for inv in invoices_from_endpoint:
inv_num = inv.get('draftInvoiceNumber') or inv.get('bookedInvoiceNumber')
if inv_num and inv_num not in existing_invoice_numbers:
all_invoices.append(inv)
existing_invoice_numbers.add(inv_num)
elif not inv_num:
# Include if no invoice number
all_invoices.append(inv)
# Check if we got full page (1000) - if so, there might be more pages
if len(invoices_from_endpoint) < 1000:
break # Last page
page += 1
else:
error_text = await response.text()
logger.warning(f"⚠️ Endpoint {endpoint} returned {response.status}: {error_text[:200]}")
break break
except Exception as e:
logger.error(f"❌ Error fetching from {endpoint}: {e}") all_invoices.extend(invoices_from_endpoint)
if len(invoices_from_endpoint) < 1000:
break # Last page
page += 1
else:
error_text = await response.text()
logger.warning(f"⚠️ Customer-specific endpoint returned {response.status}: {error_text[:200]}")
break
except Exception as e:
logger.error(f"❌ Error fetching from customer endpoint: {e}")
if not all_invoices: if not all_invoices:
logger.warning(f"⚠️ No invoices found in e-conomic") logger.warning(f"⚠️ No invoices found for customer {customer_number}")
return [] return []
logger.info(f"✅ Found {len(all_invoices)} total invoices") logger.info(f"✅ Found {len(all_invoices)} invoices for customer {customer_number}")
# Filter invoices for this customer # Debug: log response structure
customer_invoices = [ if all_invoices:
inv for inv in all_invoices logger.info(f"🔍 [API] First invoice structure keys: {list(all_invoices[0].keys())}")
if inv.get('customer', {}).get('customerNumber') == customer_number logger.info(f"🔍 [API] First invoice date: {all_invoices[0].get('date')}")
]
logger.info(f"📊 Filtered to {len(customer_invoices)} invoices for customer {customer_number}")
# Debug: log response structure if we have invoices
if customer_invoices:
logger.info(f"🔍 [API] First invoice structure keys: {list(customer_invoices[0].keys())}")
logger.info(f"🔍 [API] First invoice date: {customer_invoices[0].get('date')}")
# Apply date filter (13 months back) # Apply date filter (13 months back)
from dateutil.parser import parse as parse_date from dateutil.parser import parse as parse_date
filtered_by_date = [] filtered_by_date = []
for inv in customer_invoices: for inv in all_invoices:
invoice_date_str = inv.get('date') invoice_date_str = inv.get('date')
if invoice_date_str: if invoice_date_str:
try: try: