This commit is contained in:
26
backend/modules/invoicing/utils.py
Normal file
26
backend/modules/invoicing/utils.py
Normal file
@@ -0,0 +1,26 @@
|
||||
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}"
|
||||
Reference in New Issue
Block a user