26 lines
887 B
Python
26 lines
887 B
Python
import datetime
|
|
from django.apps import apps
|
|
from django.db import transaction
|
|
|
|
def generate_invoice_number():
|
|
"""
|
|
Generira novi broj fakture u formatu INV-YYYY-XXXX.
|
|
Koristi transakciju kako bi se spriječilo dupliciranje brojeva.
|
|
"""
|
|
with transaction.atomic():
|
|
Invoice = apps.get_model('invoicing', 'Invoice')
|
|
|
|
current_year = datetime.date.today().year
|
|
|
|
# Zaključavamo tablicu za čitanje kako bismo izbjegli Race Condition
|
|
last_invoice = Invoice.objects.filter(
|
|
invoice_number__startswith=f"INV-{current_year}-"
|
|
).select_for_update().order_by('-invoice_number').first()
|
|
|
|
if last_invoice:
|
|
last_num = int(last_invoice.invoice_number.split('-')[-1])
|
|
new_num = last_num + 1
|
|
else:
|
|
new_num = 1
|
|
|
|
return f"INV-{current_year}-{new_num:04d}" |