custom_ui/custom_ui/events/sales_order.py
2026-01-09 12:50:46 -06:00

69 lines
2.9 KiB
Python

import frappe
from custom_ui.services import DbService
def on_submit(doc, method):
print("DEBUG: Info from Sales Order")
print(doc.custom_installation_address)
print(doc.company)
print(doc.transaction_date)
print(doc.customer)
# Create Invoice and Project from Sales Order
try:
print("Creating Project from Sales Order", doc.name)
sales_order = frappe.get_doc("Sales Order", doc.name)
if not sales_order.custom_project_template:
return
project_template = DbService.get("Project Template", sales_order.custom_project_template)
new_job = frappe.get_doc({
"doctype": "Project",
"custom_job_address": sales_order.custom_job_address,
"project_name": f"{sales_order.custom_project_template} - {sales_order.custom_job_address}",
"project_template": project_template.name,
"custom_warranty_duration_days": 90,
"sales_order": sales_order.name
})
# attatch the job to the sales_order links
new_job.insert()
frappe.db.commit()
except Exception as e:
print("ERROR creating Project from Sales Order:", str(e))
def create_sales_invoice_from_sales_order(doc, method):
try:
print("DEBUG: after_submit hook triggered for Sales Order:", doc.name)
invoice_ammount = doc.grand_total / 2 if doc.requires_half_payment else doc.grand_total
items = []
for so_item in doc.items:
# proportionally reduce rate if half-payment
rate = so_item.rate / 2 if doc.requires_half_payment else so_item.rate
qty = so_item.qty # usually full qty, but depends on half-payment rules
items.append({
"item_code": so_item.item_code,
"qty": qty,
"rate": rate,
"income_account": so_item.income_account,
"cost_center": so_item.cost_center,
"so_detail": so_item.name # links item to Sales Order
})
invoice = frappe.get_doc({
"doctype": "Sales Invoice",
"customer": doc.customer,
"company": doc.company,
"posting_date": frappe.utils.nowdate(),
"due_date": frappe.utils.nowdate(), # or calculate from payment terms
"currency": doc.currency,
"update_stock": 0,
"items": items,
"sales_order": doc.name, # link invoice to Sales Order
"ignore_pricing_rule": 1,
"payment_schedule": doc.payment_schedule if not half_payment else [] # optional
})
invoice.insert()
invoice.submit()
frappe.db.commit()
return invoice
except Exception as e:
print("ERROR creating Sales Invoice from Sales Order:", str(e))
frappe.log_error(f"Error creating Sales Invoice from Sales Order {doc.name}: {str(e)}", "Sales Order after_submit Error")