I am not yet familiar with server scripts syntax. I tried to write a script that creates a barcode for a new item at insert and i failed. here is what I tried:
def before_insert(doc, method):
try:
if not doc.barcodes:
doc.barcodes = []
# Get the parent item group to help in generating barcodes
parent_item_group = doc.get("parent_item_group")
last_barcode = get_last_barcode(parent_item_group) if parent_item_group else None
if last_barcode:
try:
# Increment the last barcode by 1 for sequential barcodes
new_barcode_numeric = int(last_barcode) + 1
new_barcode = str(new_barcode_numeric)
except ValueError:
new_barcode = generate_unique_barcode()
else:
new_barcode = generate_unique_barcode()
doc.append("barcodes", {"barcode": new_barcode})
barcode_doc = {
"doctype": "Item Barcode",
"item": doc.name, # Link to the created Item
"barcode": new_barcode
}
try:
frappe.get_doc(barcode_doc).insert()
except Exception as e:
raise Exception(f"Error while creating Item Barcode: {str(e)}")
except Exception as e:
raise Exception(f"Error in before_insert: {str(e)}")
I want to optimize this script to successfully automatically create a barcode entry that is a random 11 digits number for every item i create, whether it is a variant or not. How can I do that?