import frappe
from frappe.utils import today
from erpnext.selling.doctype.sales_order.sales_order import make_sales_invoice
        
class SalesOrderService:
    
    @staticmethod
    def create_sales_invoice_from_sales_order(sales_order_name):
        try:
            sales_order_doc = frappe.get_doc("Sales Order", sales_order_name)
            sales_invoice = make_sales_invoice(sales_order_doc.name)
            sales_invoice.project = sales_order_doc.project
            sales_invoice.posting_date = today()
            sales_invoice.due_date = today()
            sales_invoice.remarks = f"Auto-generated from Sales Order {sales_order_doc.name}"
            sales_invoice.job_address = sales_order_doc.custom_job_address
            sales_invoice.project_template = sales_order_doc.custom_project_template
            
            sales_invoice.set_advances()
            sales_invoice.set_missing_values()
            sales_invoice.calculate_taxes_and_totals()
            
            sales_invoice.insert()
            sales_invoice.submit()
            return sales_invoice.name
        except Exception as e:
            print("ERROR creating Sales Invoice from Sales Order:", str(e))
            return None