import frappe
from custom_ui.db_utils import build_success_response, build_error_response
from erpnext.selling.doctype.quotation.quotation import make_sales_order

@frappe.whitelist()
def create_sales_order_from_estimate(estimate_name):
    """Create a Sales Order from a given Estimate (Quotation)."""
    try:
        estimate = frappe.get_doc("Quotation", estimate_name)
        if estimate.custom_current_status != "Estimate Accepted":
            raise Exception("Estimate must be accepted to create a Sales Order.")
        new_sales_order = make_sales_order(estimate_name)
        new_sales_order.custom_requires_half_payment = estimate.requires_half_payment
        new_sales_order.insert()
        return build_success_response(new_sales_order.as_dict())
    except Exception as e:
        return build_error_response(str(e), 500)