This commit is contained in:
77
backend/modules/invoicing/services.py
Normal file
77
backend/modules/invoicing/services.py
Normal file
@@ -0,0 +1,77 @@
|
||||
from django.utils import timezone
|
||||
from modules.invoicing.models import Invoice, InvoiceItem
|
||||
from modules.invoicing.utils import generate_invoice_number
|
||||
from django.db import transaction
|
||||
from django.contrib.auth import get_user_model
|
||||
from rest_framework.exceptions import ValidationError
|
||||
import logging
|
||||
from decimal import Decimal
|
||||
from modules.invoicing import tasks # premještamo ovdje ako treba
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class InvoiceService:
|
||||
@staticmethod
|
||||
def create_full_invoice(user=None, **validated_data):
|
||||
# 1. Obavezno dohvati stavke
|
||||
items_data = validated_data.pop('items', [])
|
||||
|
||||
fields_to_remove = ['amount', 'creator', 'invoice_number']
|
||||
for field in fields_to_remove:
|
||||
validated_data.pop(field, None)
|
||||
|
||||
# 2. Sigurna provjera korisnika
|
||||
if not user:
|
||||
User = get_user_model()
|
||||
try:
|
||||
user = User.objects.get(username="paperless_bot")
|
||||
except User.DoesNotExist:
|
||||
raise ValidationError("Sistemski korisnik 'paperless_bot' ne postoji.")
|
||||
|
||||
with transaction.atomic():
|
||||
# 3. Računanje iznosa (sigurno rukovanje s items_data)
|
||||
total = sum(Decimal(item['quantity']) * Decimal(item['unit_price']) for item in items_data)
|
||||
|
||||
# 4. Kreiraj fakturu
|
||||
invoice = Invoice.objects.create(
|
||||
**validated_data,
|
||||
amount=total,
|
||||
creator=user,
|
||||
invoice_number=generate_invoice_number()
|
||||
)
|
||||
|
||||
# 5. Kreiraj stavke
|
||||
for item_data in items_data:
|
||||
InvoiceItem.objects.create(invoice=invoice, **item_data)
|
||||
|
||||
# 6. Pokreni task nakon commit-a
|
||||
transaction.on_commit(lambda: tasks.process_paperless_document_task.delay(invoice.id))
|
||||
|
||||
return invoice
|
||||
|
||||
@staticmethod
|
||||
def create_invoice_entry(data, user=None):
|
||||
"""
|
||||
Kreira financijski zapis (transaction) na temelju validated data.
|
||||
Očekuje se da data['invoice'] može biti instanca ili PK.
|
||||
"""
|
||||
from modules.invoicing.models import InvoiceTransaction, Invoice
|
||||
|
||||
invoice = data.get("invoice")
|
||||
if isinstance(invoice, int):
|
||||
invoice = Invoice.objects.get(pk=invoice)
|
||||
elif hasattr(invoice, "pk") is False:
|
||||
raise ValidationError("Nevažeći invoice.")
|
||||
|
||||
amount = data.get("amount")
|
||||
payment_date = data.get("payment_date", None)
|
||||
work_order = data.get("work_order")
|
||||
|
||||
tx = InvoiceTransaction.objects.create(
|
||||
invoice=invoice,
|
||||
work_order=work_order,
|
||||
invoice_number=invoice.invoice_number,
|
||||
amount=amount,
|
||||
payment_date=payment_date or timezone.now()
|
||||
)
|
||||
return tx
|
||||
Reference in New Issue
Block a user