I am trying to redirect user to new sales invoice form with item details from another custom doc. Are these item details sufficient to create the invoice?
let invoice = frappe.model.get_new_doc("Sales Invoice");
invoice.naming_series = "SINV-";
for (let d of frm.doc.items) {
let invoice_item = frappe.model.add_child(invoice, "items")
invoice_item.item_code = d.item;
invoice_item.qty = d.qty;
invoice_item.rate = d.rate;
}
frappe.set_route("Form", invoice.doctype, invoice.name);
I am getting error for mandatory fields on saving the invoice, I thought these would be picked up from defaults like when selecting items manually on the Sales Invoice Form.
To resolve the issue of mandatory fields not being set when creating a new Sales Invoice document programmatically, it is important to ensure that all required fields are either set with default values or explicitly defined in your script. The provided script creates a new Sales Invoice and adds item details, but it encounters errors because some mandatory fields are missing. To fix this, you can set essential fields such as the customer and posting date, which are typically mandatory for a Sales Invoice. Additionally, if there are other necessary fields like warehouse details, you should ensure these are either fetched from the item master or set in the script.
Here’s an improved approach: First, create the Sales Invoice document and set the naming series. Then, assign the customer and posting date. As you loop through the items, add each item to the invoice, ensuring to set the item code, quantity, rate, and any other required fields like the warehouse. You can also set a default taxes and charges template if applicable. Once all fields are set, use the frappe.db.insert method to insert the document into the database. After the document is successfully inserted, use frappe.set_route to redirect the user to the newly created Sales Invoice form. This approach ensures that all mandatory fields are properly set, preventing errors when saving the invoice.