feat: add vendor invoice management UI and comprehensive tests

UI Components:
- Add vendor invoices page route in vendor_pages.py
- Create invoices.html template with stats cards, invoice table,
  settings tab, and create invoice modal
- Add invoices.js Alpine.js component for CRUD operations,
  PDF download, and settings management
- Add Invoices link to vendor sidebar in Sales section

Unit Tests (35 tests):
- VAT calculation (EU rates, regimes, labels)
- Invoice settings CRUD and number generation
- Invoice retrieval, listing, and pagination
- Status management and validation
- Statistics calculation

Integration Tests (34 tests):
- Settings API endpoints (GET/POST/PUT)
- Stats API endpoint
- Invoice list with filtering and pagination
- Invoice detail retrieval
- Invoice creation from orders
- Status update transitions
- PDF generation endpoints
- Authentication/authorization checks

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
2025-12-24 18:59:39 +01:00
parent 319fba5d39
commit e456ae3c73
6 changed files with 2527 additions and 0 deletions

View File

@@ -353,6 +353,33 @@ async def vendor_letzshop_page(
)
# ============================================================================
# INVOICES
# ============================================================================
@router.get(
"/{vendor_code}/invoices", response_class=HTMLResponse, include_in_schema=False
)
async def vendor_invoices_page(
request: Request,
vendor_code: str = Path(..., description="Vendor code"),
current_user: User = Depends(get_current_vendor_from_cookie_or_header),
):
"""
Render invoices management page.
JavaScript loads invoices via API.
"""
return templates.TemplateResponse(
"vendor/invoices.html",
{
"request": request,
"user": current_user,
"vendor_code": vendor_code,
},
)
# ============================================================================
# TEAM MANAGEMENT
# ============================================================================

602
app/templates/vendor/invoices.html vendored Normal file
View File

@@ -0,0 +1,602 @@
{# app/templates/vendor/invoices.html #}
{% extends "vendor/base.html" %}
{% block title %}Invoices{% endblock %}
{% block alpine_data %}vendorInvoices(){% endblock %}
{% block extra_scripts %}
<script src="/static/vendor/js/invoices.js"></script>
{% endblock %}
{% block content %}
<!-- Page Header -->
<div class="flex items-center justify-between my-6">
<div>
<h2 class="text-2xl font-semibold text-gray-700 dark:text-gray-200">
Invoices
</h2>
<p class="text-sm text-gray-600 dark:text-gray-400 mt-1">
Create and manage invoices for your orders
</p>
</div>
<div class="flex gap-2">
<button
@click="openCreateModal()"
:disabled="!hasSettings"
class="flex items-center px-4 py-2 text-sm font-medium leading-5 text-white transition-colors duration-150 bg-purple-600 border border-transparent rounded-lg hover:bg-purple-700 focus:outline-none focus:shadow-outline-purple disabled:opacity-50 disabled:cursor-not-allowed"
:title="!hasSettings ? 'Configure invoice settings first' : 'Create new invoice'"
>
<span x-html="$icon('plus', 'w-4 h-4 mr-2')"></span>
Create Invoice
</button>
<button
@click="refreshData()"
:disabled="loading"
class="flex items-center px-4 py-2 text-sm font-medium leading-5 text-gray-700 dark:text-gray-300 transition-colors duration-150 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none disabled:opacity-50"
>
<span x-show="!loading" x-html="$icon('refresh', 'w-4 h-4 mr-2')"></span>
<span x-show="loading" x-html="$icon('spinner', 'w-4 h-4 mr-2')"></span>
Refresh
</button>
</div>
</div>
<!-- Success Message -->
<div x-show="successMessage" x-transition class="mb-6 p-4 bg-green-100 dark:bg-green-900/30 border border-green-400 dark:border-green-600 text-green-700 dark:text-green-300 rounded-lg flex items-start">
<span x-html="$icon('check-circle', 'w-5 h-5 mr-3 mt-0.5 flex-shrink-0')"></span>
<div>
<p class="font-semibold" x-text="successMessage"></p>
</div>
<button @click="successMessage = ''" class="ml-auto text-green-700 dark:text-green-300 hover:text-green-900">
<span x-html="$icon('x', 'w-4 h-4')"></span>
</button>
</div>
<!-- Error Message -->
<div x-show="error" x-transition class="mb-6 p-4 bg-red-100 dark:bg-red-900/30 border border-red-400 dark:border-red-600 text-red-700 dark:text-red-300 rounded-lg flex items-start">
<span x-html="$icon('exclamation', 'w-5 h-5 mr-3 mt-0.5 flex-shrink-0')"></span>
<div>
<p class="font-semibold">Error</p>
<p class="text-sm" x-text="error"></p>
</div>
<button @click="error = ''" class="ml-auto text-red-700 dark:text-red-300 hover:text-red-900">
<span x-html="$icon('x', 'w-4 h-4')"></span>
</button>
</div>
<!-- Settings Warning -->
<div x-show="!hasSettings && !loading" x-transition class="mb-6 p-4 bg-yellow-100 dark:bg-yellow-900/30 border border-yellow-400 dark:border-yellow-600 text-yellow-700 dark:text-yellow-300 rounded-lg">
<div class="flex items-start">
<span x-html="$icon('exclamation', 'w-5 h-5 mr-3 mt-0.5 flex-shrink-0')"></span>
<div class="flex-1">
<p class="font-semibold">Invoice Settings Required</p>
<p class="text-sm mt-1">Configure your company details and invoice preferences before creating invoices.</p>
<button
@click="activeTab = 'settings'"
class="mt-3 inline-flex items-center px-3 py-1.5 text-sm font-medium text-yellow-800 bg-yellow-200 rounded-lg hover:bg-yellow-300"
>
<span x-html="$icon('cog', 'w-4 h-4 mr-2')"></span>
Configure Settings
</button>
</div>
</div>
</div>
<!-- Tabs -->
<div class="mb-6">
<div class="flex border-b border-gray-200 dark:border-gray-700">
<button
@click="activeTab = 'invoices'"
:class="activeTab === 'invoices' ? 'border-purple-600 text-purple-600' : 'border-transparent text-gray-500 hover:text-gray-700 dark:hover:text-gray-300'"
class="px-4 py-2 text-sm font-medium border-b-2 transition-colors"
>
<span class="flex items-center">
<span x-html="$icon('document-text', 'w-4 h-4 mr-2')"></span>
Invoices
<span x-show="stats.total_invoices > 0" class="ml-2 px-2 py-0.5 text-xs bg-purple-100 dark:bg-purple-900 text-purple-600 dark:text-purple-300 rounded-full" x-text="stats.total_invoices"></span>
</span>
</button>
<button
@click="activeTab = 'settings'"
:class="activeTab === 'settings' ? 'border-purple-600 text-purple-600' : 'border-transparent text-gray-500 hover:text-gray-700 dark:hover:text-gray-300'"
class="px-4 py-2 text-sm font-medium border-b-2 transition-colors"
>
<span class="flex items-center">
<span x-html="$icon('cog', 'w-4 h-4 mr-2')"></span>
Settings
<span x-show="!hasSettings" class="ml-2 w-2 h-2 bg-yellow-500 rounded-full"></span>
</span>
</button>
</div>
</div>
<!-- Invoices Tab -->
<div x-show="activeTab === 'invoices'" x-transition>
<!-- Stats Cards -->
<div class="grid gap-6 mb-8 md:grid-cols-4">
<div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
<div class="p-3 mr-4 text-blue-500 bg-blue-100 rounded-full dark:bg-blue-900">
<span x-html="$icon('document-text', 'w-5 h-5')"></span>
</div>
<div>
<p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">Total Invoices</p>
<p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="stats.total_invoices"></p>
</div>
</div>
<div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
<div class="p-3 mr-4 text-gray-500 bg-gray-100 rounded-full dark:bg-gray-700">
<span x-html="$icon('pencil', 'w-5 h-5')"></span>
</div>
<div>
<p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">Draft</p>
<p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="stats.draft_count"></p>
</div>
</div>
<div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
<div class="p-3 mr-4 text-orange-500 bg-orange-100 rounded-full dark:bg-orange-900">
<span x-html="$icon('paper-airplane', 'w-5 h-5')"></span>
</div>
<div>
<p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">Issued</p>
<p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="stats.issued_count"></p>
</div>
</div>
<div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
<div class="p-3 mr-4 text-green-500 bg-green-100 rounded-full dark:bg-green-900">
<span x-html="$icon('check-circle', 'w-5 h-5')"></span>
</div>
<div>
<p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">Paid</p>
<p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="stats.paid_count"></p>
</div>
</div>
</div>
<!-- Filters -->
<div class="mb-4 flex flex-wrap gap-4">
<select
x-model="filters.status"
@change="loadInvoices()"
class="px-3 py-2 text-sm text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-md focus:border-purple-400 focus:outline-none"
>
<option value="">All Status</option>
<option value="draft">Draft</option>
<option value="issued">Issued</option>
<option value="paid">Paid</option>
<option value="cancelled">Cancelled</option>
</select>
</div>
<!-- Invoices Table -->
<div class="w-full overflow-hidden rounded-lg shadow-xs">
<div class="w-full overflow-x-auto">
<table class="w-full whitespace-no-wrap">
<thead>
<tr class="text-xs font-semibold tracking-wide text-left text-gray-500 uppercase border-b dark:border-gray-700 bg-gray-50 dark:text-gray-400 dark:bg-gray-800">
<th class="px-4 py-3">Invoice #</th>
<th class="px-4 py-3">Customer</th>
<th class="px-4 py-3">Date</th>
<th class="px-4 py-3">Amount</th>
<th class="px-4 py-3">Status</th>
<th class="px-4 py-3">Actions</th>
</tr>
</thead>
<tbody class="bg-white divide-y dark:divide-gray-700 dark:bg-gray-800">
<template x-if="loading && invoices.length === 0">
<tr>
<td colspan="6" class="px-4 py-8 text-center text-gray-500 dark:text-gray-400">
<span x-html="$icon('spinner', 'w-6 h-6 mx-auto mb-2')"></span>
<p>Loading invoices...</p>
</td>
</tr>
</template>
<template x-if="!loading && invoices.length === 0">
<tr>
<td colspan="6" class="px-4 py-8 text-center text-gray-500 dark:text-gray-400">
<span x-html="$icon('document-text', 'w-12 h-12 mx-auto mb-2 text-gray-300')"></span>
<p class="font-medium">No invoices yet</p>
<p class="text-sm mt-1" x-show="hasSettings">Click "Create Invoice" to generate your first invoice</p>
<p class="text-sm mt-1" x-show="!hasSettings">Configure invoice settings first to get started</p>
</td>
</tr>
</template>
<template x-for="invoice in invoices" :key="invoice.id">
<tr class="text-gray-700 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700">
<td class="px-4 py-3">
<div class="flex items-center text-sm">
<div>
<p class="font-semibold" x-text="invoice.invoice_number"></p>
<p class="text-xs text-gray-500" x-text="'Order #' + (invoice.order_id || 'N/A')"></p>
</div>
</div>
</td>
<td class="px-4 py-3 text-sm">
<p x-text="invoice.buyer_name || 'N/A'"></p>
</td>
<td class="px-4 py-3 text-sm">
<span x-text="formatDate(invoice.invoice_date)"></span>
</td>
<td class="px-4 py-3 text-sm font-semibold">
<span x-text="formatCurrency(invoice.total_cents, invoice.currency)"></span>
</td>
<td class="px-4 py-3 text-xs">
<span
class="px-2 py-1 font-semibold leading-tight rounded-full"
:class="{
'text-gray-700 bg-gray-100 dark:bg-gray-700 dark:text-gray-300': invoice.status === 'draft',
'text-orange-700 bg-orange-100 dark:bg-orange-700 dark:text-orange-100': invoice.status === 'issued',
'text-green-700 bg-green-100 dark:bg-green-700 dark:text-green-100': invoice.status === 'paid',
'text-red-700 bg-red-100 dark:bg-red-700 dark:text-red-100': invoice.status === 'cancelled'
}"
x-text="invoice.status.toUpperCase()"
></span>
</td>
<td class="px-4 py-3">
<div class="flex items-center space-x-2 text-sm">
<button
@click="downloadPDF(invoice)"
class="flex items-center justify-center px-2 py-1 text-sm text-purple-600 transition-colors duration-150 rounded-md hover:bg-purple-100 dark:hover:bg-purple-900"
title="Download PDF"
>
<span x-html="$icon('download', 'w-4 h-4')"></span>
</button>
<button
x-show="invoice.status === 'draft'"
@click="updateStatus(invoice, 'issued')"
class="flex items-center justify-center px-2 py-1 text-sm text-blue-600 transition-colors duration-150 rounded-md hover:bg-blue-100 dark:hover:bg-blue-900"
title="Mark as Issued"
>
<span x-html="$icon('paper-airplane', 'w-4 h-4')"></span>
</button>
<button
x-show="invoice.status === 'issued'"
@click="updateStatus(invoice, 'paid')"
class="flex items-center justify-center px-2 py-1 text-sm text-green-600 transition-colors duration-150 rounded-md hover:bg-green-100 dark:hover:bg-green-900"
title="Mark as Paid"
>
<span x-html="$icon('check', 'w-4 h-4')"></span>
</button>
<button
x-show="invoice.status !== 'cancelled' && invoice.status !== 'paid'"
@click="updateStatus(invoice, 'cancelled')"
class="flex items-center justify-center px-2 py-1 text-sm text-red-600 transition-colors duration-150 rounded-md hover:bg-red-100 dark:hover:bg-red-900"
title="Cancel Invoice"
>
<span x-html="$icon('x', 'w-4 h-4')"></span>
</button>
</div>
</td>
</tr>
</template>
</tbody>
</table>
</div>
<!-- Pagination -->
<div x-show="totalInvoices > perPage" class="grid px-4 py-3 text-xs font-semibold tracking-wide text-gray-500 uppercase border-t dark:border-gray-700 bg-gray-50 sm:grid-cols-9 dark:text-gray-400 dark:bg-gray-800">
<span class="flex items-center col-span-3">
Showing <span x-text="((page - 1) * perPage) + 1" class="mx-1"></span>-<span x-text="Math.min(page * perPage, totalInvoices)" class="mx-1"></span> of <span x-text="totalInvoices" class="mx-1"></span>
</span>
<span class="col-span-2"></span>
<span class="flex col-span-4 mt-2 sm:mt-auto sm:justify-end">
<nav aria-label="Table navigation">
<ul class="inline-flex items-center">
<li>
<button
@click="page--; loadInvoices()"
:disabled="page <= 1"
class="px-3 py-1 rounded-md rounded-l-lg focus:outline-none focus:shadow-outline-purple disabled:opacity-50"
>
<span x-html="$icon('chevron-left', 'w-4 h-4')"></span>
</button>
</li>
<li>
<button
@click="page++; loadInvoices()"
:disabled="page * perPage >= totalInvoices"
class="px-3 py-1 rounded-md rounded-r-lg focus:outline-none focus:shadow-outline-purple disabled:opacity-50"
>
<span x-html="$icon('chevron-right', 'w-4 h-4')"></span>
</button>
</li>
</ul>
</nav>
</span>
</div>
</div>
</div>
<!-- Settings Tab -->
<div x-show="activeTab === 'settings'" x-transition>
<div class="bg-white rounded-lg shadow-xs dark:bg-gray-800">
<div class="p-6">
<h3 class="mb-4 text-lg font-semibold text-gray-700 dark:text-gray-200">
Invoice Settings
</h3>
<p class="text-sm text-gray-600 dark:text-gray-400 mb-6">
Configure your company details and preferences for invoice generation.
</p>
<form @submit.prevent="saveSettings()">
<!-- Company Information -->
<div class="mb-8">
<h4 class="text-md font-medium text-gray-700 dark:text-gray-300 mb-4 pb-2 border-b dark:border-gray-700">
Company Information
</h4>
<div class="grid gap-6 md:grid-cols-2">
<div class="md:col-span-2">
<label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-2">
Company Name <span class="text-red-500">*</span>
</label>
<input
type="text"
x-model="settingsForm.company_name"
required
placeholder="Your Company S.A."
class="block w-full px-3 py-2 text-sm text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md focus:border-purple-400 focus:outline-none"
/>
</div>
<div class="md:col-span-2">
<label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-2">
Address
</label>
<input
type="text"
x-model="settingsForm.company_address"
placeholder="123 Main Street"
class="block w-full px-3 py-2 text-sm text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md focus:border-purple-400 focus:outline-none"
/>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-2">
City
</label>
<input
type="text"
x-model="settingsForm.company_city"
placeholder="Luxembourg"
class="block w-full px-3 py-2 text-sm text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md focus:border-purple-400 focus:outline-none"
/>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-2">
Postal Code
</label>
<input
type="text"
x-model="settingsForm.company_postal_code"
placeholder="L-1234"
class="block w-full px-3 py-2 text-sm text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md focus:border-purple-400 focus:outline-none"
/>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-2">
Country
</label>
<select
x-model="settingsForm.company_country"
class="block w-full px-3 py-2 text-sm text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md focus:border-purple-400 focus:outline-none"
>
<option value="LU">Luxembourg</option>
<option value="DE">Germany</option>
<option value="FR">France</option>
<option value="BE">Belgium</option>
</select>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-2">
VAT Number
</label>
<input
type="text"
x-model="settingsForm.vat_number"
placeholder="LU12345678"
class="block w-full px-3 py-2 text-sm text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md focus:border-purple-400 focus:outline-none"
/>
</div>
</div>
</div>
<!-- Invoice Numbering -->
<div class="mb-8">
<h4 class="text-md font-medium text-gray-700 dark:text-gray-300 mb-4 pb-2 border-b dark:border-gray-700">
Invoice Numbering
</h4>
<div class="grid gap-6 md:grid-cols-2">
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-2">
Invoice Prefix
</label>
<input
type="text"
x-model="settingsForm.invoice_prefix"
placeholder="INV"
class="block w-full px-3 py-2 text-sm text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md focus:border-purple-400 focus:outline-none"
/>
<p class="mt-1 text-xs text-gray-500">Example: INV-2024-00001</p>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-2">
Default VAT Rate (%)
</label>
<select
x-model="settingsForm.default_vat_rate"
class="block w-full px-3 py-2 text-sm text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md focus:border-purple-400 focus:outline-none"
>
<option value="17.00">17% (Standard)</option>
<option value="14.00">14% (Intermediate)</option>
<option value="8.00">8% (Reduced)</option>
<option value="3.00">3% (Super-reduced)</option>
<option value="0.00">0% (Exempt)</option>
</select>
</div>
</div>
</div>
<!-- Bank Details -->
<div class="mb-8">
<h4 class="text-md font-medium text-gray-700 dark:text-gray-300 mb-4 pb-2 border-b dark:border-gray-700">
Bank Details
</h4>
<div class="grid gap-6 md:grid-cols-2">
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-2">
Bank Name
</label>
<input
type="text"
x-model="settingsForm.bank_name"
placeholder="BCEE Luxembourg"
class="block w-full px-3 py-2 text-sm text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md focus:border-purple-400 focus:outline-none"
/>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-2">
IBAN
</label>
<input
type="text"
x-model="settingsForm.bank_iban"
placeholder="LU00 0000 0000 0000 0000"
class="block w-full px-3 py-2 text-sm text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md focus:border-purple-400 focus:outline-none"
/>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-2">
BIC/SWIFT
</label>
<input
type="text"
x-model="settingsForm.bank_bic"
placeholder="BCEELULL"
class="block w-full px-3 py-2 text-sm text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md focus:border-purple-400 focus:outline-none"
/>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-2">
Payment Terms
</label>
<input
type="text"
x-model="settingsForm.payment_terms"
placeholder="Net 30 days"
class="block w-full px-3 py-2 text-sm text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md focus:border-purple-400 focus:outline-none"
/>
</div>
</div>
</div>
<!-- Footer -->
<div class="mb-8">
<h4 class="text-md font-medium text-gray-700 dark:text-gray-300 mb-4 pb-2 border-b dark:border-gray-700">
Invoice Footer
</h4>
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-2">
Footer Text
</label>
<textarea
x-model="settingsForm.footer_text"
rows="3"
placeholder="Thank you for your business!"
class="block w-full px-3 py-2 text-sm text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md focus:border-purple-400 focus:outline-none"
></textarea>
</div>
</div>
<!-- Save Button -->
<div class="flex justify-end">
<button
type="submit"
:disabled="savingSettings"
class="flex items-center px-4 py-2 text-sm font-medium leading-5 text-white transition-colors duration-150 bg-purple-600 border border-transparent rounded-lg hover:bg-purple-700 focus:outline-none focus:shadow-outline-purple disabled:opacity-50"
>
<span x-show="!savingSettings" x-html="$icon('save', 'w-4 h-4 mr-2')"></span>
<span x-show="savingSettings" x-html="$icon('spinner', 'w-4 h-4 mr-2')"></span>
<span x-text="savingSettings ? 'Saving...' : 'Save Settings'"></span>
</button>
</div>
</form>
</div>
</div>
</div>
<!-- Create Invoice Modal -->
<div
x-show="showCreateModal"
x-transition:enter="transition ease-out duration-150"
x-transition:enter-start="opacity-0"
x-transition:enter-end="opacity-100"
x-transition:leave="transition ease-in duration-150"
x-transition:leave-start="opacity-100"
x-transition:leave-end="opacity-0"
class="fixed inset-0 z-30 flex items-end bg-black bg-opacity-50 sm:items-center sm:justify-center"
@click.self="showCreateModal = false"
>
<div
x-transition:enter="transition ease-out duration-150"
x-transition:enter-start="opacity-0 transform translate-y-1/2"
x-transition:enter-end="opacity-100"
x-transition:leave="transition ease-in duration-150"
x-transition:leave-start="opacity-100"
x-transition:leave-end="opacity-0 transform translate-y-1/2"
class="w-full px-6 py-4 overflow-hidden bg-white rounded-t-lg dark:bg-gray-800 sm:rounded-lg sm:m-4 sm:max-w-md"
@click.stop
>
<header class="flex justify-between items-center mb-4">
<h3 class="text-lg font-semibold text-gray-700 dark:text-gray-200">Create Invoice</h3>
<button @click="showCreateModal = false" class="text-gray-400 hover:text-gray-600">
<span x-html="$icon('x', 'w-5 h-5')"></span>
</button>
</header>
<form @submit.prevent="createInvoice()">
<div class="mb-4">
<label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-2">
Order ID <span class="text-red-500">*</span>
</label>
<input
type="number"
x-model="createForm.order_id"
required
placeholder="Enter order ID"
class="block w-full px-3 py-2 text-sm text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md focus:border-purple-400 focus:outline-none"
/>
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
Enter the order ID to generate an invoice for
</p>
</div>
<div class="mb-6">
<label class="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-2">
Notes (Optional)
</label>
<textarea
x-model="createForm.notes"
rows="3"
placeholder="Any additional notes for the invoice..."
class="block w-full px-3 py-2 text-sm text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md focus:border-purple-400 focus:outline-none"
></textarea>
</div>
<div class="flex justify-end gap-3">
<button
type="button"
@click="showCreateModal = false"
class="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50"
>
Cancel
</button>
<button
type="submit"
:disabled="creatingInvoice"
class="flex items-center px-4 py-2 text-sm font-medium text-white bg-purple-600 rounded-lg hover:bg-purple-700 disabled:opacity-50"
>
<span x-show="creatingInvoice" x-html="$icon('spinner', 'w-4 h-4 mr-2')"></span>
<span x-text="creatingInvoice ? 'Creating...' : 'Create Invoice'"></span>
</button>
</div>
</form>
</div>
</div>
{% endblock %}

View File

@@ -128,6 +128,17 @@ Follows same pattern as admin sidebar
<span class="ml-4">Messages</span>
</a>
</li>
<li class="relative px-6 py-3">
<span x-show="currentPage === 'invoices'"
class="absolute inset-y-0 left-0 w-1 bg-purple-600 rounded-tr-lg rounded-br-lg"
aria-hidden="true"></span>
<a class="inline-flex items-center w-full text-sm font-semibold transition-colors duration-150 hover:text-gray-800 dark:hover:text-gray-200"
:class="currentPage === 'invoices' ? 'text-gray-800 dark:text-gray-100' : ''"
:href="`/vendor/${vendorCode}/invoices`">
<span x-html="$icon('document-text', 'w-5 h-5')"></span>
<span class="ml-4">Invoices</span>
</a>
</li>
</ul>
<!-- Settings Section -->

398
static/vendor/js/invoices.js vendored Normal file
View File

@@ -0,0 +1,398 @@
// static/vendor/js/invoices.js
/**
* Vendor invoice management page logic
*/
console.log('[VENDOR INVOICES] Loading...');
function vendorInvoices() {
console.log('[VENDOR INVOICES] vendorInvoices() called');
return {
// Inherit base layout state
...data(),
// Set page identifier
currentPage: 'invoices',
// Tab state
activeTab: 'invoices',
// Loading states
loading: false,
savingSettings: false,
creatingInvoice: false,
downloadingPdf: false,
// Messages
error: '',
successMessage: '',
// Settings
hasSettings: false,
settings: null,
settingsForm: {
company_name: '',
company_address: '',
company_city: '',
company_postal_code: '',
company_country: 'LU',
vat_number: '',
invoice_prefix: 'INV',
default_vat_rate: '17.00',
bank_name: '',
bank_iban: '',
bank_bic: '',
payment_terms: 'Net 30 days',
footer_text: ''
},
// Stats
stats: {
total_invoices: 0,
total_revenue_cents: 0,
draft_count: 0,
issued_count: 0,
paid_count: 0,
cancelled_count: 0
},
// Invoices list
invoices: [],
totalInvoices: 0,
page: 1,
perPage: 20,
filters: {
status: ''
},
// Create invoice modal
showCreateModal: false,
createForm: {
order_id: '',
notes: ''
},
async init() {
// Guard against multiple initialization
if (window._vendorInvoicesInitialized) {
return;
}
window._vendorInvoicesInitialized = true;
// Call parent init first to set vendorCode from URL
const parentInit = data().init;
if (parentInit) {
await parentInit.call(this);
}
await this.loadSettings();
await this.loadStats();
await this.loadInvoices();
},
/**
* Load invoice settings
*/
async loadSettings() {
try {
const response = await apiClient.get('/vendor/invoices/settings');
if (response) {
this.settings = response;
this.hasSettings = true;
// Populate form with existing settings
this.settingsForm = {
company_name: response.company_name || '',
company_address: response.company_address || '',
company_city: response.company_city || '',
company_postal_code: response.company_postal_code || '',
company_country: response.company_country || 'LU',
vat_number: response.vat_number || '',
invoice_prefix: response.invoice_prefix || 'INV',
default_vat_rate: response.default_vat_rate?.toString() || '17.00',
bank_name: response.bank_name || '',
bank_iban: response.bank_iban || '',
bank_bic: response.bank_bic || '',
payment_terms: response.payment_terms || 'Net 30 days',
footer_text: response.footer_text || ''
};
} else {
this.hasSettings = false;
}
} catch (error) {
// 404 means not configured yet, which is fine
if (error.status !== 404) {
console.error('[VENDOR INVOICES] Failed to load settings:', error);
}
this.hasSettings = false;
}
},
/**
* Load invoice statistics
*/
async loadStats() {
try {
const response = await apiClient.get('/vendor/invoices/stats');
this.stats = {
total_invoices: response.total_invoices || 0,
total_revenue_cents: response.total_revenue_cents || 0,
draft_count: response.draft_count || 0,
issued_count: response.issued_count || 0,
paid_count: response.paid_count || 0,
cancelled_count: response.cancelled_count || 0
};
} catch (error) {
console.error('[VENDOR INVOICES] Failed to load stats:', error);
}
},
/**
* Load invoices list
*/
async loadInvoices() {
this.loading = true;
this.error = '';
try {
const params = new URLSearchParams({
page: this.page.toString(),
per_page: this.perPage.toString()
});
if (this.filters.status) {
params.append('status', this.filters.status);
}
const response = await apiClient.get(`/vendor/invoices?${params}`);
this.invoices = response.items || [];
this.totalInvoices = response.total || 0;
} catch (error) {
console.error('[VENDOR INVOICES] Failed to load invoices:', error);
this.error = error.message || 'Failed to load invoices';
} finally {
this.loading = false;
}
},
/**
* Refresh all data
*/
async refreshData() {
await this.loadSettings();
await this.loadStats();
await this.loadInvoices();
this.successMessage = 'Data refreshed';
setTimeout(() => this.successMessage = '', 3000);
},
/**
* Save invoice settings
*/
async saveSettings() {
if (!this.settingsForm.company_name) {
this.error = 'Company name is required';
return;
}
this.savingSettings = true;
this.error = '';
try {
const payload = {
company_name: this.settingsForm.company_name,
company_address: this.settingsForm.company_address || null,
company_city: this.settingsForm.company_city || null,
company_postal_code: this.settingsForm.company_postal_code || null,
company_country: this.settingsForm.company_country || 'LU',
vat_number: this.settingsForm.vat_number || null,
invoice_prefix: this.settingsForm.invoice_prefix || 'INV',
default_vat_rate: parseFloat(this.settingsForm.default_vat_rate) || 17.0,
bank_name: this.settingsForm.bank_name || null,
bank_iban: this.settingsForm.bank_iban || null,
bank_bic: this.settingsForm.bank_bic || null,
payment_terms: this.settingsForm.payment_terms || null,
footer_text: this.settingsForm.footer_text || null
};
let response;
if (this.hasSettings) {
// Update existing settings
response = await apiClient.put('/vendor/invoices/settings', payload);
} else {
// Create new settings
response = await apiClient.post('/vendor/invoices/settings', payload);
}
this.settings = response;
this.hasSettings = true;
this.successMessage = 'Settings saved successfully';
} catch (error) {
console.error('[VENDOR INVOICES] Failed to save settings:', error);
this.error = error.message || 'Failed to save settings';
} finally {
this.savingSettings = false;
setTimeout(() => this.successMessage = '', 5000);
}
},
/**
* Open create invoice modal
*/
openCreateModal() {
if (!this.hasSettings) {
this.error = 'Please configure invoice settings first';
this.activeTab = 'settings';
return;
}
this.createForm = {
order_id: '',
notes: ''
};
this.showCreateModal = true;
},
/**
* Create invoice from order
*/
async createInvoice() {
if (!this.createForm.order_id) {
this.error = 'Please enter an order ID';
return;
}
this.creatingInvoice = true;
this.error = '';
try {
const payload = {
order_id: parseInt(this.createForm.order_id),
notes: this.createForm.notes || null
};
const response = await apiClient.post('/vendor/invoices', payload);
this.showCreateModal = false;
this.successMessage = `Invoice ${response.invoice_number} created successfully`;
await this.loadStats();
await this.loadInvoices();
} catch (error) {
console.error('[VENDOR INVOICES] Failed to create invoice:', error);
this.error = error.message || 'Failed to create invoice';
} finally {
this.creatingInvoice = false;
setTimeout(() => this.successMessage = '', 5000);
}
},
/**
* Update invoice status
*/
async updateStatus(invoice, newStatus) {
const statusLabels = {
'issued': 'mark as issued',
'paid': 'mark as paid',
'cancelled': 'cancel'
};
if (!confirm(`Are you sure you want to ${statusLabels[newStatus] || newStatus} this invoice?`)) {
return;
}
try {
await apiClient.put(`/vendor/invoices/${invoice.id}/status`, {
status: newStatus
});
this.successMessage = `Invoice ${invoice.invoice_number} status updated to ${newStatus}`;
await this.loadStats();
await this.loadInvoices();
} catch (error) {
console.error('[VENDOR INVOICES] Failed to update status:', error);
this.error = error.message || 'Failed to update invoice status';
}
setTimeout(() => this.successMessage = '', 5000);
},
/**
* Download invoice PDF
*/
async downloadPDF(invoice) {
this.downloadingPdf = true;
try {
// Get the token for authentication
const token = localStorage.getItem('wizamart_token') || localStorage.getItem('vendor_token');
if (!token) {
throw new Error('Not authenticated');
}
const response = await fetch(`/api/v1/vendor/invoices/${invoice.id}/pdf`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`
}
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.detail || 'Failed to download PDF');
}
// Get filename from Content-Disposition header
const contentDisposition = response.headers.get('Content-Disposition');
let filename = `invoice-${invoice.invoice_number}.pdf`;
if (contentDisposition) {
const match = contentDisposition.match(/filename="(.+)"/);
if (match) {
filename = match[1];
}
}
// Download the file
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
this.successMessage = `Downloaded: ${filename}`;
} catch (error) {
console.error('[VENDOR INVOICES] Failed to download PDF:', error);
this.error = error.message || 'Failed to download PDF';
} finally {
this.downloadingPdf = false;
setTimeout(() => this.successMessage = '', 5000);
}
},
/**
* Format date for display
*/
formatDate(dateStr) {
if (!dateStr) return 'N/A';
const date = new Date(dateStr);
return date.toLocaleDateString('en-GB', {
day: '2-digit',
month: 'short',
year: 'numeric'
});
},
/**
* Format currency for display
*/
formatCurrency(cents, currency = 'EUR') {
if (cents === null || cents === undefined) return 'N/A';
const amount = cents / 100;
return new Intl.NumberFormat('de-LU', {
style: 'currency',
currency: currency
}).format(amount);
}
};
}

View File

@@ -0,0 +1,867 @@
# tests/integration/api/v1/vendor/test_invoices.py
"""Integration tests for vendor invoice management endpoints.
Tests the /api/v1/vendor/invoices/* endpoints.
All endpoints require vendor JWT authentication.
"""
from decimal import Decimal
import pytest
from models.database.customer import Customer
from models.database.invoice import Invoice, InvoiceStatus, VendorInvoiceSettings
from models.database.order import Order
@pytest.mark.integration
@pytest.mark.api
@pytest.mark.vendor
class TestVendorInvoiceSettingsAPI:
"""Test vendor invoice settings endpoints at /api/v1/vendor/invoices/settings."""
def test_get_settings_not_configured(self, client, vendor_user_headers):
"""Test getting settings when not configured returns null."""
response = client.get(
"/api/v1/vendor/invoices/settings",
headers=vendor_user_headers,
)
assert response.status_code == 200
assert response.json() is None
def test_create_settings_success(self, client, vendor_user_headers):
"""Test creating invoice settings successfully."""
settings_data = {
"company_name": "Test Company S.A.",
"company_address": "123 Test Street",
"company_city": "Luxembourg",
"company_postal_code": "L-1234",
"company_country": "LU",
"vat_number": "LU12345678",
"invoice_prefix": "INV",
"default_vat_rate": 17.0,
"bank_name": "BCEE",
"bank_iban": "LU123456789012345678",
"bank_bic": "BCEELULL",
"payment_terms": "Net 30 days",
}
response = client.post(
"/api/v1/vendor/invoices/settings",
headers=vendor_user_headers,
json=settings_data,
)
assert response.status_code == 201, f"Failed: {response.json()}"
data = response.json()
assert data["company_name"] == "Test Company S.A."
assert data["company_country"] == "LU"
assert data["invoice_prefix"] == "INV"
def test_create_settings_minimal(self, client, vendor_user_headers):
"""Test creating settings with minimal required data."""
settings_data = {
"company_name": "Minimal Company",
}
response = client.post(
"/api/v1/vendor/invoices/settings",
headers=vendor_user_headers,
json=settings_data,
)
assert response.status_code == 201
data = response.json()
assert data["company_name"] == "Minimal Company"
# Defaults should be applied
assert data["invoice_prefix"] == "INV"
def test_create_settings_duplicate_fails(
self, client, vendor_user_headers, db, test_vendor_with_vendor_user
):
"""Test creating duplicate settings fails."""
# Create settings directly in DB
settings = VendorInvoiceSettings(
vendor_id=test_vendor_with_vendor_user.id,
company_name="Existing Company",
company_country="LU",
)
db.add(settings)
db.commit()
response = client.post(
"/api/v1/vendor/invoices/settings",
headers=vendor_user_headers,
json={"company_name": "New Company"},
)
# ValidationException returns 422
assert response.status_code == 422
def test_get_settings_success(
self, client, vendor_user_headers, db, test_vendor_with_vendor_user
):
"""Test getting existing settings."""
# Create settings
settings = VendorInvoiceSettings(
vendor_id=test_vendor_with_vendor_user.id,
company_name="Get Settings Company",
company_country="LU",
invoice_prefix="FAC",
)
db.add(settings)
db.commit()
response = client.get(
"/api/v1/vendor/invoices/settings",
headers=vendor_user_headers,
)
assert response.status_code == 200
data = response.json()
assert data["company_name"] == "Get Settings Company"
assert data["invoice_prefix"] == "FAC"
def test_update_settings_success(
self, client, vendor_user_headers, db, test_vendor_with_vendor_user
):
"""Test updating invoice settings."""
# Create settings
settings = VendorInvoiceSettings(
vendor_id=test_vendor_with_vendor_user.id,
company_name="Original Company",
company_country="LU",
)
db.add(settings)
db.commit()
update_data = {
"company_name": "Updated Company",
"bank_iban": "LU999888777666555444",
}
response = client.put(
"/api/v1/vendor/invoices/settings",
headers=vendor_user_headers,
json=update_data,
)
assert response.status_code == 200
data = response.json()
assert data["company_name"] == "Updated Company"
assert data["bank_iban"] == "LU999888777666555444"
def test_update_settings_not_found(self, client, vendor_user_headers):
"""Test updating non-existent settings returns error."""
response = client.put(
"/api/v1/vendor/invoices/settings",
headers=vendor_user_headers,
json={"company_name": "Updated"},
)
assert response.status_code == 404
def test_settings_without_auth_returns_unauthorized(self, client):
"""Test accessing settings without auth returns 401."""
response = client.get("/api/v1/vendor/invoices/settings")
assert response.status_code == 401
@pytest.mark.integration
@pytest.mark.api
@pytest.mark.vendor
class TestVendorInvoiceStatsAPI:
"""Test vendor invoice statistics endpoint at /api/v1/vendor/invoices/stats."""
def test_get_stats_empty(self, client, vendor_user_headers):
"""Test getting stats when no invoices exist."""
response = client.get(
"/api/v1/vendor/invoices/stats",
headers=vendor_user_headers,
)
assert response.status_code == 200
data = response.json()
assert data["total_invoices"] == 0
assert data["total_revenue_cents"] == 0
assert data["draft_count"] == 0
assert data["paid_count"] == 0
def test_get_stats_with_invoices(
self, client, vendor_user_headers, db, test_vendor_with_vendor_user
):
"""Test getting stats with existing invoices."""
from datetime import datetime, UTC
# Create invoices
for i, status in enumerate([InvoiceStatus.DRAFT, InvoiceStatus.PAID]):
invoice = Invoice(
vendor_id=test_vendor_with_vendor_user.id,
invoice_number=f"INV0000{i+1}",
invoice_date=datetime.now(UTC),
status=status.value,
seller_details={"company_name": "Test"},
buyer_details={"name": "Buyer"},
line_items=[],
vat_rate=Decimal("17.00"),
subtotal_cents=10000 * (i + 1),
vat_amount_cents=1700 * (i + 1),
total_cents=11700 * (i + 1),
)
db.add(invoice)
db.commit()
response = client.get(
"/api/v1/vendor/invoices/stats",
headers=vendor_user_headers,
)
assert response.status_code == 200
data = response.json()
assert data["total_invoices"] == 2
assert data["draft_count"] == 1
assert data["paid_count"] == 1
def test_stats_without_auth_returns_unauthorized(self, client):
"""Test accessing stats without auth returns 401."""
response = client.get("/api/v1/vendor/invoices/stats")
assert response.status_code == 401
@pytest.mark.integration
@pytest.mark.api
@pytest.mark.vendor
class TestVendorInvoiceListAPI:
"""Test vendor invoice list endpoint at /api/v1/vendor/invoices."""
def test_list_invoices_empty(self, client, vendor_user_headers):
"""Test listing invoices when none exist."""
response = client.get(
"/api/v1/vendor/invoices",
headers=vendor_user_headers,
)
assert response.status_code == 200
data = response.json()
assert data["items"] == []
assert data["total"] == 0
assert data["page"] == 1
def test_list_invoices_success(
self, client, vendor_user_headers, db, test_vendor_with_vendor_user
):
"""Test listing invoices successfully."""
from datetime import datetime, UTC
# Create invoices
for i in range(3):
invoice = Invoice(
vendor_id=test_vendor_with_vendor_user.id,
invoice_number=f"INV0000{i+1}",
invoice_date=datetime.now(UTC),
status=InvoiceStatus.DRAFT.value,
seller_details={"company_name": "Test"},
buyer_details={"name": f"Buyer {i+1}"},
line_items=[],
vat_rate=Decimal("17.00"),
subtotal_cents=10000,
vat_amount_cents=1700,
total_cents=11700,
)
db.add(invoice)
db.commit()
response = client.get(
"/api/v1/vendor/invoices",
headers=vendor_user_headers,
)
assert response.status_code == 200
data = response.json()
assert len(data["items"]) == 3
assert data["total"] == 3
def test_list_invoices_with_status_filter(
self, client, vendor_user_headers, db, test_vendor_with_vendor_user
):
"""Test filtering invoices by status."""
from datetime import datetime, UTC
# Create invoices with different statuses
for status in [InvoiceStatus.DRAFT, InvoiceStatus.ISSUED, InvoiceStatus.PAID]:
invoice = Invoice(
vendor_id=test_vendor_with_vendor_user.id,
invoice_number=f"INV-{status.value.upper()}",
invoice_date=datetime.now(UTC),
status=status.value,
seller_details={"company_name": "Test"},
buyer_details={"name": "Buyer"},
line_items=[],
vat_rate=Decimal("17.00"),
subtotal_cents=10000,
vat_amount_cents=1700,
total_cents=11700,
)
db.add(invoice)
db.commit()
# Filter by paid status
response = client.get(
"/api/v1/vendor/invoices?status=paid",
headers=vendor_user_headers,
)
assert response.status_code == 200
data = response.json()
assert data["total"] == 1
assert data["items"][0]["status"] == "paid"
def test_list_invoices_pagination(
self, client, vendor_user_headers, db, test_vendor_with_vendor_user
):
"""Test invoice list pagination."""
from datetime import datetime, UTC
# Create 5 invoices
for i in range(5):
invoice = Invoice(
vendor_id=test_vendor_with_vendor_user.id,
invoice_number=f"INV0000{i+1}",
invoice_date=datetime.now(UTC),
status=InvoiceStatus.DRAFT.value,
seller_details={"company_name": "Test"},
buyer_details={"name": "Buyer"},
line_items=[],
vat_rate=Decimal("17.00"),
subtotal_cents=10000,
vat_amount_cents=1700,
total_cents=11700,
)
db.add(invoice)
db.commit()
# Get first page with 2 items
response = client.get(
"/api/v1/vendor/invoices?page=1&per_page=2",
headers=vendor_user_headers,
)
assert response.status_code == 200
data = response.json()
assert len(data["items"]) == 2
assert data["total"] == 5
assert data["page"] == 1
assert data["pages"] == 3
def test_list_invoices_without_auth_returns_unauthorized(self, client):
"""Test listing invoices without auth returns 401."""
response = client.get("/api/v1/vendor/invoices")
assert response.status_code == 401
@pytest.mark.integration
@pytest.mark.api
@pytest.mark.vendor
class TestVendorInvoiceDetailAPI:
"""Test vendor invoice detail endpoint at /api/v1/vendor/invoices/{id}."""
def test_get_invoice_success(
self, client, vendor_user_headers, db, test_vendor_with_vendor_user
):
"""Test getting invoice by ID."""
from datetime import datetime, UTC
invoice = Invoice(
vendor_id=test_vendor_with_vendor_user.id,
invoice_number="INV00001",
invoice_date=datetime.now(UTC),
status=InvoiceStatus.DRAFT.value,
seller_details={"company_name": "Seller Co"},
buyer_details={"name": "John Doe"},
line_items=[
{
"description": "Product A",
"quantity": 2,
"unit_price_cents": 5000,
"total_cents": 10000,
}
],
vat_rate=Decimal("17.00"),
subtotal_cents=10000,
vat_amount_cents=1700,
total_cents=11700,
)
db.add(invoice)
db.commit()
db.refresh(invoice)
response = client.get(
f"/api/v1/vendor/invoices/{invoice.id}",
headers=vendor_user_headers,
)
assert response.status_code == 200
data = response.json()
assert data["invoice_number"] == "INV00001"
assert data["total_cents"] == 11700
assert len(data["line_items"]) == 1
def test_get_invoice_not_found(self, client, vendor_user_headers):
"""Test getting non-existent invoice returns 404."""
response = client.get(
"/api/v1/vendor/invoices/99999",
headers=vendor_user_headers,
)
assert response.status_code == 404
def test_get_invoice_without_auth_returns_unauthorized(self, client):
"""Test getting invoice without auth returns 401."""
response = client.get("/api/v1/vendor/invoices/1")
assert response.status_code == 401
@pytest.mark.integration
@pytest.mark.api
@pytest.mark.vendor
class TestVendorInvoiceCreateAPI:
"""Test vendor invoice creation endpoint at /api/v1/vendor/invoices."""
def test_create_invoice_success(
self,
client,
vendor_user_headers,
db,
test_vendor_with_vendor_user,
):
"""Test creating invoice from order."""
from datetime import datetime, UTC
now = datetime.now(UTC)
# Create invoice settings first
settings = VendorInvoiceSettings(
vendor_id=test_vendor_with_vendor_user.id,
company_name="Test Company",
company_country="LU",
invoice_prefix="INV",
invoice_next_number=1,
)
db.add(settings)
db.commit()
# Create a customer first
customer = Customer(
vendor_id=test_vendor_with_vendor_user.id,
email="test@example.com",
hashed_password="$2b$12$test_hashed_password",
first_name="John",
last_name="Doe",
customer_number="CUST-001",
)
db.add(customer)
db.commit()
db.refresh(customer)
# Create an order
order = Order(
vendor_id=test_vendor_with_vendor_user.id,
customer_id=customer.id,
order_number="ORD-001",
channel="direct",
order_date=now,
customer_first_name="John",
customer_last_name="Doe",
customer_email="test@example.com",
ship_first_name="John",
ship_last_name="Doe",
ship_address_line_1="123 Test St",
ship_city="Luxembourg",
ship_postal_code="L-1234",
ship_country_iso="LU",
bill_first_name="John",
bill_last_name="Doe",
bill_address_line_1="123 Test St",
bill_city="Luxembourg",
bill_postal_code="L-1234",
bill_country_iso="LU",
currency="EUR",
status="completed",
subtotal_cents=10000,
total_amount_cents=11700,
)
db.add(order)
db.commit()
db.refresh(order)
# Create invoice (without order items - service handles empty items)
response = client.post(
"/api/v1/vendor/invoices",
headers=vendor_user_headers,
json={"order_id": order.id, "notes": "Test invoice"},
)
assert response.status_code == 201, f"Failed: {response.json()}"
data = response.json()
assert data["order_id"] == order.id
assert data["invoice_number"] == "INV00001"
assert data["status"] == "draft"
assert data["notes"] == "Test invoice"
def test_create_invoice_without_settings_fails(
self, client, vendor_user_headers, db, test_vendor_with_vendor_user
):
"""Test creating invoice without settings configured fails."""
from datetime import datetime, UTC
now = datetime.now(UTC)
# Create a customer first
customer = Customer(
vendor_id=test_vendor_with_vendor_user.id,
email="jane@example.com",
hashed_password="$2b$12$test_hashed_password",
first_name="Jane",
last_name="Doe",
customer_number="CUST-002",
)
db.add(customer)
db.commit()
db.refresh(customer)
# Create an order without settings
order = Order(
vendor_id=test_vendor_with_vendor_user.id,
customer_id=customer.id,
order_number="ORD-002",
channel="direct",
order_date=now,
customer_first_name="Jane",
customer_last_name="Doe",
customer_email="jane@example.com",
ship_first_name="Jane",
ship_last_name="Doe",
ship_address_line_1="456 Test Ave",
ship_city="Luxembourg",
ship_postal_code="L-5678",
ship_country_iso="LU",
bill_first_name="Jane",
bill_last_name="Doe",
bill_address_line_1="456 Test Ave",
bill_city="Luxembourg",
bill_postal_code="L-5678",
bill_country_iso="LU",
currency="EUR",
status="completed",
subtotal_cents=10000,
total_amount_cents=11700,
)
db.add(order)
db.commit()
db.refresh(order)
response = client.post(
"/api/v1/vendor/invoices",
headers=vendor_user_headers,
json={"order_id": order.id},
)
assert response.status_code == 404 # Settings not found
def test_create_invoice_order_not_found(
self, client, vendor_user_headers, db, test_vendor_with_vendor_user
):
"""Test creating invoice for non-existent order fails."""
# Create settings
settings = VendorInvoiceSettings(
vendor_id=test_vendor_with_vendor_user.id,
company_name="Test Company",
company_country="LU",
)
db.add(settings)
db.commit()
response = client.post(
"/api/v1/vendor/invoices",
headers=vendor_user_headers,
json={"order_id": 99999},
)
assert response.status_code == 404
def test_create_invoice_without_auth_returns_unauthorized(self, client):
"""Test creating invoice without auth returns 401."""
response = client.post(
"/api/v1/vendor/invoices",
json={"order_id": 1},
)
assert response.status_code == 401
@pytest.mark.integration
@pytest.mark.api
@pytest.mark.vendor
class TestVendorInvoiceStatusAPI:
"""Test vendor invoice status update endpoint."""
def test_update_status_to_issued(
self, client, vendor_user_headers, db, test_vendor_with_vendor_user
):
"""Test updating invoice status to issued."""
from datetime import datetime, UTC
invoice = Invoice(
vendor_id=test_vendor_with_vendor_user.id,
invoice_number="INV00001",
invoice_date=datetime.now(UTC),
status=InvoiceStatus.DRAFT.value,
seller_details={"company_name": "Test"},
buyer_details={"name": "Buyer"},
line_items=[],
vat_rate=Decimal("17.00"),
subtotal_cents=10000,
vat_amount_cents=1700,
total_cents=11700,
)
db.add(invoice)
db.commit()
db.refresh(invoice)
response = client.put(
f"/api/v1/vendor/invoices/{invoice.id}/status",
headers=vendor_user_headers,
json={"status": "issued"},
)
assert response.status_code == 200
data = response.json()
assert data["status"] == "issued"
def test_update_status_to_paid(
self, client, vendor_user_headers, db, test_vendor_with_vendor_user
):
"""Test updating invoice status to paid."""
from datetime import datetime, UTC
invoice = Invoice(
vendor_id=test_vendor_with_vendor_user.id,
invoice_number="INV00001",
invoice_date=datetime.now(UTC),
status=InvoiceStatus.ISSUED.value,
seller_details={"company_name": "Test"},
buyer_details={"name": "Buyer"},
line_items=[],
vat_rate=Decimal("17.00"),
subtotal_cents=10000,
vat_amount_cents=1700,
total_cents=11700,
)
db.add(invoice)
db.commit()
db.refresh(invoice)
response = client.put(
f"/api/v1/vendor/invoices/{invoice.id}/status",
headers=vendor_user_headers,
json={"status": "paid"},
)
assert response.status_code == 200
data = response.json()
assert data["status"] == "paid"
def test_update_status_to_cancelled(
self, client, vendor_user_headers, db, test_vendor_with_vendor_user
):
"""Test cancelling an invoice."""
from datetime import datetime, UTC
invoice = Invoice(
vendor_id=test_vendor_with_vendor_user.id,
invoice_number="INV00001",
invoice_date=datetime.now(UTC),
status=InvoiceStatus.DRAFT.value,
seller_details={"company_name": "Test"},
buyer_details={"name": "Buyer"},
line_items=[],
vat_rate=Decimal("17.00"),
subtotal_cents=10000,
vat_amount_cents=1700,
total_cents=11700,
)
db.add(invoice)
db.commit()
db.refresh(invoice)
response = client.put(
f"/api/v1/vendor/invoices/{invoice.id}/status",
headers=vendor_user_headers,
json={"status": "cancelled"},
)
assert response.status_code == 200
data = response.json()
assert data["status"] == "cancelled"
def test_update_cancelled_invoice_fails(
self, client, vendor_user_headers, db, test_vendor_with_vendor_user
):
"""Test updating cancelled invoice fails."""
from datetime import datetime, UTC
invoice = Invoice(
vendor_id=test_vendor_with_vendor_user.id,
invoice_number="INV00001",
invoice_date=datetime.now(UTC),
status=InvoiceStatus.CANCELLED.value,
seller_details={"company_name": "Test"},
buyer_details={"name": "Buyer"},
line_items=[],
vat_rate=Decimal("17.00"),
subtotal_cents=10000,
vat_amount_cents=1700,
total_cents=11700,
)
db.add(invoice)
db.commit()
db.refresh(invoice)
response = client.put(
f"/api/v1/vendor/invoices/{invoice.id}/status",
headers=vendor_user_headers,
json={"status": "issued"},
)
# ValidationException returns 422
assert response.status_code == 422
def test_update_status_invalid_status(
self, client, vendor_user_headers, db, test_vendor_with_vendor_user
):
"""Test updating with invalid status fails."""
from datetime import datetime, UTC
invoice = Invoice(
vendor_id=test_vendor_with_vendor_user.id,
invoice_number="INV00001",
invoice_date=datetime.now(UTC),
status=InvoiceStatus.DRAFT.value,
seller_details={"company_name": "Test"},
buyer_details={"name": "Buyer"},
line_items=[],
vat_rate=Decimal("17.00"),
subtotal_cents=10000,
vat_amount_cents=1700,
total_cents=11700,
)
db.add(invoice)
db.commit()
db.refresh(invoice)
response = client.put(
f"/api/v1/vendor/invoices/{invoice.id}/status",
headers=vendor_user_headers,
json={"status": "invalid_status"},
)
# ValidationException returns 422
assert response.status_code == 422
def test_update_status_not_found(self, client, vendor_user_headers):
"""Test updating non-existent invoice fails."""
response = client.put(
"/api/v1/vendor/invoices/99999/status",
headers=vendor_user_headers,
json={"status": "issued"},
)
assert response.status_code == 404
def test_update_status_without_auth_returns_unauthorized(self, client):
"""Test updating status without auth returns 401."""
response = client.put(
"/api/v1/vendor/invoices/1/status",
json={"status": "issued"},
)
assert response.status_code == 401
@pytest.mark.integration
@pytest.mark.api
@pytest.mark.vendor
class TestVendorInvoicePDFAPI:
"""Test vendor invoice PDF endpoints."""
@pytest.mark.skip(reason="WeasyPrint not installed in test environment")
def test_generate_pdf_success(
self, client, vendor_user_headers, db, test_vendor_with_vendor_user
):
"""Test generating PDF for an invoice."""
from datetime import datetime, UTC
# Create settings
settings = VendorInvoiceSettings(
vendor_id=test_vendor_with_vendor_user.id,
company_name="PDF Test Company",
company_country="LU",
)
db.add(settings)
db.commit()
invoice = Invoice(
vendor_id=test_vendor_with_vendor_user.id,
invoice_number="INV00001",
invoice_date=datetime.now(UTC),
status=InvoiceStatus.DRAFT.value,
seller_details={"company_name": "PDF Test Company"},
buyer_details={"name": "Buyer"},
line_items=[
{
"description": "Test Item",
"quantity": 1,
"unit_price_cents": 10000,
"total_cents": 10000,
}
],
vat_rate=Decimal("17.00"),
subtotal_cents=10000,
vat_amount_cents=1700,
total_cents=11700,
)
db.add(invoice)
db.commit()
db.refresh(invoice)
response = client.post(
f"/api/v1/vendor/invoices/{invoice.id}/pdf",
headers=vendor_user_headers,
)
assert response.status_code == 200
def test_generate_pdf_not_found(self, client, vendor_user_headers):
"""Test generating PDF for non-existent invoice fails."""
response = client.post(
"/api/v1/vendor/invoices/99999/pdf",
headers=vendor_user_headers,
)
assert response.status_code == 404
def test_download_pdf_not_found(self, client, vendor_user_headers):
"""Test downloading PDF for non-existent invoice fails."""
response = client.get(
"/api/v1/vendor/invoices/99999/pdf",
headers=vendor_user_headers,
)
assert response.status_code == 404
def test_pdf_endpoints_without_auth_returns_unauthorized(self, client):
"""Test PDF endpoints without auth return 401."""
response = client.post("/api/v1/vendor/invoices/1/pdf")
assert response.status_code == 401
response = client.get("/api/v1/vendor/invoices/1/pdf")
assert response.status_code == 401

View File

@@ -0,0 +1,622 @@
# tests/unit/services/test_invoice_service.py
"""Unit tests for InvoiceService."""
import uuid
from decimal import Decimal
import pytest
from app.exceptions import ValidationException
from app.exceptions.invoice import (
InvoiceNotFoundException,
InvoiceSettingsNotFoundException,
)
from app.services.invoice_service import (
EU_VAT_RATES,
InvoiceService,
LU_VAT_RATES,
)
from models.database.invoice import (
Invoice,
InvoiceStatus,
VATRegime,
VendorInvoiceSettings,
)
from models.schema.invoice import (
VendorInvoiceSettingsCreate,
VendorInvoiceSettingsUpdate,
)
@pytest.mark.unit
@pytest.mark.invoice
class TestInvoiceServiceVATCalculation:
"""Test suite for InvoiceService VAT calculation methods."""
def setup_method(self):
"""Initialize service instance before each test."""
self.service = InvoiceService()
# ==================== VAT Rate Lookup Tests ====================
def test_get_vat_rate_for_luxembourg(self):
"""Test Luxembourg VAT rate is 17%."""
rate = self.service.get_vat_rate_for_country("LU")
assert rate == Decimal("17.00")
def test_get_vat_rate_for_germany(self):
"""Test Germany VAT rate is 19%."""
rate = self.service.get_vat_rate_for_country("DE")
assert rate == Decimal("19.00")
def test_get_vat_rate_for_france(self):
"""Test France VAT rate is 20%."""
rate = self.service.get_vat_rate_for_country("FR")
assert rate == Decimal("20.00")
def test_get_vat_rate_for_non_eu_country(self):
"""Test non-EU country returns 0% VAT."""
rate = self.service.get_vat_rate_for_country("US")
assert rate == Decimal("0.00")
def test_get_vat_rate_lowercase_country(self):
"""Test VAT rate lookup works with lowercase country codes."""
rate = self.service.get_vat_rate_for_country("de")
assert rate == Decimal("19.00")
# ==================== VAT Rate Label Tests ====================
def test_get_vat_rate_label_luxembourg(self):
"""Test VAT rate label for Luxembourg."""
label = self.service.get_vat_rate_label("LU", Decimal("17.00"))
assert "Luxembourg" in label
assert "17" in label
def test_get_vat_rate_label_germany(self):
"""Test VAT rate label for Germany."""
label = self.service.get_vat_rate_label("DE", Decimal("19.00"))
assert "Germany" in label
assert "19" in label
# ==================== VAT Regime Determination Tests ====================
def test_determine_vat_regime_domestic(self):
"""Test domestic sales (same country) use domestic VAT."""
regime, rate, dest = self.service.determine_vat_regime(
seller_country="LU",
buyer_country="LU",
buyer_vat_number=None,
seller_oss_registered=False,
)
assert regime == VATRegime.DOMESTIC
assert rate == Decimal("17.00")
assert dest is None
def test_determine_vat_regime_reverse_charge(self):
"""Test B2B with valid VAT number uses reverse charge."""
regime, rate, dest = self.service.determine_vat_regime(
seller_country="LU",
buyer_country="DE",
buyer_vat_number="DE123456789",
seller_oss_registered=False,
)
assert regime == VATRegime.REVERSE_CHARGE
assert rate == Decimal("0.00")
assert dest == "DE"
def test_determine_vat_regime_oss_registered(self):
"""Test B2C cross-border with OSS uses destination VAT."""
regime, rate, dest = self.service.determine_vat_regime(
seller_country="LU",
buyer_country="DE",
buyer_vat_number=None,
seller_oss_registered=True,
)
assert regime == VATRegime.OSS
assert rate == Decimal("19.00") # German VAT
assert dest == "DE"
def test_determine_vat_regime_no_oss(self):
"""Test B2C cross-border without OSS uses origin VAT."""
regime, rate, dest = self.service.determine_vat_regime(
seller_country="LU",
buyer_country="DE",
buyer_vat_number=None,
seller_oss_registered=False,
)
assert regime == VATRegime.ORIGIN
assert rate == Decimal("17.00") # Luxembourg VAT
assert dest == "DE"
def test_determine_vat_regime_non_eu_exempt(self):
"""Test non-EU sales are VAT exempt."""
regime, rate, dest = self.service.determine_vat_regime(
seller_country="LU",
buyer_country="US",
buyer_vat_number=None,
seller_oss_registered=True,
)
assert regime == VATRegime.EXEMPT
assert rate == Decimal("0.00")
assert dest == "US"
@pytest.mark.unit
@pytest.mark.invoice
class TestInvoiceServiceSettings:
"""Test suite for InvoiceService settings management."""
def setup_method(self):
"""Initialize service instance before each test."""
self.service = InvoiceService()
# ==================== Get Settings Tests ====================
def test_get_settings_not_found(self, db, test_vendor):
"""Test getting settings for vendor without settings returns None."""
settings = self.service.get_settings(db, test_vendor.id)
assert settings is None
def test_get_settings_or_raise_not_found(self, db, test_vendor):
"""Test get_settings_or_raise raises when settings don't exist."""
with pytest.raises(InvoiceSettingsNotFoundException):
self.service.get_settings_or_raise(db, test_vendor.id)
# ==================== Create Settings Tests ====================
def test_create_settings_success(self, db, test_vendor):
"""Test creating invoice settings successfully."""
data = VendorInvoiceSettingsCreate(
company_name="Test Company S.A.",
company_address="123 Test Street",
company_city="Luxembourg",
company_postal_code="L-1234",
company_country="LU",
vat_number="LU12345678",
)
settings = self.service.create_settings(db, test_vendor.id, data)
assert settings.vendor_id == test_vendor.id
assert settings.company_name == "Test Company S.A."
assert settings.company_country == "LU"
assert settings.vat_number == "LU12345678"
assert settings.invoice_prefix == "INV"
assert settings.invoice_next_number == 1
def test_create_settings_with_custom_prefix(self, db, test_vendor):
"""Test creating settings with custom invoice prefix."""
data = VendorInvoiceSettingsCreate(
company_name="Custom Prefix Company",
invoice_prefix="FAC",
invoice_number_padding=6,
)
settings = self.service.create_settings(db, test_vendor.id, data)
assert settings.invoice_prefix == "FAC"
assert settings.invoice_number_padding == 6
def test_create_settings_duplicate_raises(self, db, test_vendor):
"""Test creating duplicate settings raises ValidationException."""
data = VendorInvoiceSettingsCreate(company_name="First Settings")
self.service.create_settings(db, test_vendor.id, data)
with pytest.raises(ValidationException) as exc_info:
self.service.create_settings(db, test_vendor.id, data)
assert "already exist" in str(exc_info.value)
# ==================== Update Settings Tests ====================
def test_update_settings_success(self, db, test_vendor):
"""Test updating invoice settings."""
# Create initial settings
create_data = VendorInvoiceSettingsCreate(
company_name="Original Company"
)
self.service.create_settings(db, test_vendor.id, create_data)
# Update settings
update_data = VendorInvoiceSettingsUpdate(
company_name="Updated Company",
bank_iban="LU123456789012345678",
)
settings = self.service.update_settings(db, test_vendor.id, update_data)
assert settings.company_name == "Updated Company"
assert settings.bank_iban == "LU123456789012345678"
def test_update_settings_not_found(self, db, test_vendor):
"""Test updating non-existent settings raises exception."""
update_data = VendorInvoiceSettingsUpdate(company_name="Updated")
with pytest.raises(InvoiceSettingsNotFoundException):
self.service.update_settings(db, test_vendor.id, update_data)
# ==================== Invoice Number Generation Tests ====================
def test_get_next_invoice_number(self, db, test_vendor):
"""Test invoice number generation and increment."""
create_data = VendorInvoiceSettingsCreate(
company_name="Test Company",
invoice_prefix="INV",
invoice_number_padding=5,
)
settings = self.service.create_settings(db, test_vendor.id, create_data)
# Generate first invoice number
num1 = self.service._get_next_invoice_number(db, settings)
assert num1 == "INV00001"
assert settings.invoice_next_number == 2
# Generate second invoice number
num2 = self.service._get_next_invoice_number(db, settings)
assert num2 == "INV00002"
assert settings.invoice_next_number == 3
@pytest.mark.unit
@pytest.mark.invoice
class TestInvoiceServiceCRUD:
"""Test suite for InvoiceService CRUD operations."""
def setup_method(self):
"""Initialize service instance before each test."""
self.service = InvoiceService()
# ==================== Get Invoice Tests ====================
def test_get_invoice_not_found(self, db, test_vendor):
"""Test getting non-existent invoice returns None."""
invoice = self.service.get_invoice(db, test_vendor.id, 99999)
assert invoice is None
def test_get_invoice_or_raise_not_found(self, db, test_vendor):
"""Test get_invoice_or_raise raises for non-existent invoice."""
with pytest.raises(InvoiceNotFoundException):
self.service.get_invoice_or_raise(db, test_vendor.id, 99999)
def test_get_invoice_wrong_vendor(self, db, test_vendor, test_invoice_settings):
"""Test cannot get invoice from different vendor."""
# Create an invoice
invoice = Invoice(
vendor_id=test_vendor.id,
invoice_number="INV00001",
invoice_date=test_invoice_settings.created_at,
seller_details={"company_name": "Test"},
buyer_details={"name": "Buyer"},
line_items=[],
vat_rate=Decimal("17.00"),
subtotal_cents=10000,
vat_amount_cents=1700,
total_cents=11700,
)
db.add(invoice)
db.commit()
# Try to get with different vendor ID
result = self.service.get_invoice(db, 99999, invoice.id)
assert result is None
# ==================== List Invoices Tests ====================
def test_list_invoices_empty(self, db, test_vendor):
"""Test listing invoices when none exist."""
invoices, total = self.service.list_invoices(db, test_vendor.id)
assert invoices == []
assert total == 0
def test_list_invoices_with_status_filter(
self, db, test_vendor, test_invoice_settings
):
"""Test listing invoices filtered by status."""
# Create invoices with different statuses
for status in [InvoiceStatus.DRAFT, InvoiceStatus.ISSUED, InvoiceStatus.PAID]:
invoice = Invoice(
vendor_id=test_vendor.id,
invoice_number=f"INV-{status.value}",
invoice_date=test_invoice_settings.created_at,
status=status.value,
seller_details={"company_name": "Test"},
buyer_details={"name": "Buyer"},
line_items=[],
vat_rate=Decimal("17.00"),
subtotal_cents=10000,
vat_amount_cents=1700,
total_cents=11700,
)
db.add(invoice)
db.commit()
# Filter by draft
drafts, total = self.service.list_invoices(
db, test_vendor.id, status="draft"
)
assert total == 1
assert all(inv.status == "draft" for inv in drafts)
def test_list_invoices_pagination(self, db, test_vendor, test_invoice_settings):
"""Test invoice listing pagination."""
# Create 5 invoices
for i in range(5):
invoice = Invoice(
vendor_id=test_vendor.id,
invoice_number=f"INV0000{i+1}",
invoice_date=test_invoice_settings.created_at,
seller_details={"company_name": "Test"},
buyer_details={"name": "Buyer"},
line_items=[],
vat_rate=Decimal("17.00"),
subtotal_cents=10000,
vat_amount_cents=1700,
total_cents=11700,
)
db.add(invoice)
db.commit()
# Get first page
page1, total = self.service.list_invoices(
db, test_vendor.id, page=1, per_page=2
)
assert len(page1) == 2
assert total == 5
# Get second page
page2, _ = self.service.list_invoices(
db, test_vendor.id, page=2, per_page=2
)
assert len(page2) == 2
@pytest.mark.unit
@pytest.mark.invoice
class TestInvoiceServiceStatusManagement:
"""Test suite for InvoiceService status management."""
def setup_method(self):
"""Initialize service instance before each test."""
self.service = InvoiceService()
def test_update_status_draft_to_issued(
self, db, test_vendor, test_invoice_settings
):
"""Test updating invoice status from draft to issued."""
invoice = Invoice(
vendor_id=test_vendor.id,
invoice_number="INV00001",
invoice_date=test_invoice_settings.created_at,
status=InvoiceStatus.DRAFT.value,
seller_details={"company_name": "Test"},
buyer_details={"name": "Buyer"},
line_items=[],
vat_rate=Decimal("17.00"),
subtotal_cents=10000,
vat_amount_cents=1700,
total_cents=11700,
)
db.add(invoice)
db.commit()
updated = self.service.update_status(
db, test_vendor.id, invoice.id, "issued"
)
assert updated.status == "issued"
def test_update_status_issued_to_paid(
self, db, test_vendor, test_invoice_settings
):
"""Test updating invoice status from issued to paid."""
invoice = Invoice(
vendor_id=test_vendor.id,
invoice_number="INV00001",
invoice_date=test_invoice_settings.created_at,
status=InvoiceStatus.ISSUED.value,
seller_details={"company_name": "Test"},
buyer_details={"name": "Buyer"},
line_items=[],
vat_rate=Decimal("17.00"),
subtotal_cents=10000,
vat_amount_cents=1700,
total_cents=11700,
)
db.add(invoice)
db.commit()
updated = self.service.update_status(
db, test_vendor.id, invoice.id, "paid"
)
assert updated.status == "paid"
def test_update_status_cancelled_cannot_change(
self, db, test_vendor, test_invoice_settings
):
"""Test that cancelled invoices cannot have status changed."""
invoice = Invoice(
vendor_id=test_vendor.id,
invoice_number="INV00001",
invoice_date=test_invoice_settings.created_at,
status=InvoiceStatus.CANCELLED.value,
seller_details={"company_name": "Test"},
buyer_details={"name": "Buyer"},
line_items=[],
vat_rate=Decimal("17.00"),
subtotal_cents=10000,
vat_amount_cents=1700,
total_cents=11700,
)
db.add(invoice)
db.commit()
with pytest.raises(ValidationException) as exc_info:
self.service.update_status(db, test_vendor.id, invoice.id, "issued")
assert "cancelled" in str(exc_info.value).lower()
def test_update_status_invalid_status(
self, db, test_vendor, test_invoice_settings
):
"""Test updating with invalid status raises ValidationException."""
invoice = Invoice(
vendor_id=test_vendor.id,
invoice_number="INV00001",
invoice_date=test_invoice_settings.created_at,
status=InvoiceStatus.DRAFT.value,
seller_details={"company_name": "Test"},
buyer_details={"name": "Buyer"},
line_items=[],
vat_rate=Decimal("17.00"),
subtotal_cents=10000,
vat_amount_cents=1700,
total_cents=11700,
)
db.add(invoice)
db.commit()
with pytest.raises(ValidationException) as exc_info:
self.service.update_status(
db, test_vendor.id, invoice.id, "invalid_status"
)
assert "Invalid status" in str(exc_info.value)
def test_mark_as_issued(self, db, test_vendor, test_invoice_settings):
"""Test mark_as_issued helper method."""
invoice = Invoice(
vendor_id=test_vendor.id,
invoice_number="INV00001",
invoice_date=test_invoice_settings.created_at,
status=InvoiceStatus.DRAFT.value,
seller_details={"company_name": "Test"},
buyer_details={"name": "Buyer"},
line_items=[],
vat_rate=Decimal("17.00"),
subtotal_cents=10000,
vat_amount_cents=1700,
total_cents=11700,
)
db.add(invoice)
db.commit()
updated = self.service.mark_as_issued(db, test_vendor.id, invoice.id)
assert updated.status == InvoiceStatus.ISSUED.value
def test_mark_as_paid(self, db, test_vendor, test_invoice_settings):
"""Test mark_as_paid helper method."""
invoice = Invoice(
vendor_id=test_vendor.id,
invoice_number="INV00001",
invoice_date=test_invoice_settings.created_at,
status=InvoiceStatus.ISSUED.value,
seller_details={"company_name": "Test"},
buyer_details={"name": "Buyer"},
line_items=[],
vat_rate=Decimal("17.00"),
subtotal_cents=10000,
vat_amount_cents=1700,
total_cents=11700,
)
db.add(invoice)
db.commit()
updated = self.service.mark_as_paid(db, test_vendor.id, invoice.id)
assert updated.status == InvoiceStatus.PAID.value
def test_cancel_invoice(self, db, test_vendor, test_invoice_settings):
"""Test cancel_invoice helper method."""
invoice = Invoice(
vendor_id=test_vendor.id,
invoice_number="INV00001",
invoice_date=test_invoice_settings.created_at,
status=InvoiceStatus.DRAFT.value,
seller_details={"company_name": "Test"},
buyer_details={"name": "Buyer"},
line_items=[],
vat_rate=Decimal("17.00"),
subtotal_cents=10000,
vat_amount_cents=1700,
total_cents=11700,
)
db.add(invoice)
db.commit()
updated = self.service.cancel_invoice(db, test_vendor.id, invoice.id)
assert updated.status == InvoiceStatus.CANCELLED.value
@pytest.mark.unit
@pytest.mark.invoice
class TestInvoiceServiceStatistics:
"""Test suite for InvoiceService statistics."""
def setup_method(self):
"""Initialize service instance before each test."""
self.service = InvoiceService()
def test_get_invoice_stats_empty(self, db, test_vendor):
"""Test stats when no invoices exist."""
stats = self.service.get_invoice_stats(db, test_vendor.id)
assert stats["total_invoices"] == 0
assert stats["total_revenue_cents"] == 0
assert stats["draft_count"] == 0
assert stats["paid_count"] == 0
def test_get_invoice_stats_with_invoices(
self, db, test_vendor, test_invoice_settings
):
"""Test stats calculation with multiple invoices."""
# Create invoices
statuses = [
(InvoiceStatus.DRAFT.value, 10000),
(InvoiceStatus.ISSUED.value, 20000),
(InvoiceStatus.PAID.value, 30000),
(InvoiceStatus.CANCELLED.value, 5000),
]
for i, (status, total) in enumerate(statuses):
invoice = Invoice(
vendor_id=test_vendor.id,
invoice_number=f"INV0000{i+1}",
invoice_date=test_invoice_settings.created_at,
status=status,
seller_details={"company_name": "Test"},
buyer_details={"name": "Buyer"},
line_items=[],
vat_rate=Decimal("17.00"),
subtotal_cents=total,
vat_amount_cents=int(total * 0.17),
total_cents=total + int(total * 0.17),
)
db.add(invoice)
db.commit()
stats = self.service.get_invoice_stats(db, test_vendor.id)
assert stats["total_invoices"] == 4
# Revenue only counts issued and paid
expected_revenue = 20000 + int(20000 * 0.17) + 30000 + int(30000 * 0.17)
assert stats["total_revenue_cents"] == expected_revenue
assert stats["draft_count"] == 1
assert stats["paid_count"] == 1
# ==================== Fixtures ====================
@pytest.fixture
def test_invoice_settings(db, test_vendor):
"""Create test invoice settings."""
settings = VendorInvoiceSettings(
vendor_id=test_vendor.id,
company_name="Test Invoice Company",
company_country="LU",
invoice_prefix="INV",
invoice_next_number=1,
invoice_number_padding=5,
)
db.add(settings)
db.commit()
db.refresh(settings)
return settings