custom_ui/custom_ui/api/db/estimates.py
2025-12-03 11:51:59 -06:00

221 lines
9.2 KiB
Python

import frappe, json
from frappe.utils.pdf import get_pdf
from custom_ui.db_utils import process_query_conditions, build_datatable_dict, get_count_or_filters, build_success_response, build_error_response
# ===============================================================================
# ESTIMATES & INVOICES API METHODS
# ===============================================================================
@frappe.whitelist()
def get_estimate_table_data(filters={}, sortings=[], page=1, page_size=10):
"""Get paginated estimate table data with filtering and sorting support."""
print("DEBUG: Raw estimate options received:", filters, sortings, page, page_size)
processed_filters, processed_sortings, is_or, page, page_size = process_query_conditions(filters, sortings, page, page_size)
if is_or:
count = frappe.db.sql(*get_count_or_filters("Quotation", processed_filters))[0][0]
else:
count = frappe.db.count("Quotation", filters=processed_filters)
print(f"DEBUG: Number of estimates returned: {count}")
estimates = frappe.db.get_all(
"Quotation",
fields=["*"],
filters=processed_filters if not is_or else None,
or_filters=processed_filters if is_or else None,
limit=page_size,
start=(page - 1) * page_size,
order_by=processed_sortings
)
tableRows = []
for estimate in estimates:
full_address = frappe.db.get_value("Address", estimate.get("custom_installation_address"), "full_address")
tableRow = {}
tableRow["id"] = estimate["name"]
tableRow["address"] = full_address
tableRow["quotation_to"] = estimate.get("quotation_to", "")
tableRow["customer"] = estimate.get("party_name", "")
tableRow["status"] = estimate.get("custom_current_status", "")
tableRow["date"] = estimate.get("transaction_date", "")
tableRow["order_type"] = estimate.get("order_type", "")
tableRow["items"] = estimate.get("items", "")
tableRows.append(tableRow)
table_data_dict = build_datatable_dict(data=tableRows, count=count, page=page, page_size=page_size)
return build_success_response(table_data_dict)
@frappe.whitelist()
def get_quotation_items():
"""Get all available quotation items."""
try:
items = frappe.get_all("Item", fields=["*"], filters={"item_group": "SNW-S"})
return build_success_response(items)
except Exception as e:
return build_error_response(str(e), 500)
@frappe.whitelist()
def get_estimate(estimate_name):
"""Get detailed information for a specific estimate."""
try:
estimate = frappe.get_doc("Quotation", estimate_name)
return build_success_response(estimate.as_dict())
except Exception as e:
return build_error_response(str(e), 500)
@frappe.whitelist()
def get_estimate_items():
items = frappe.db.get_all("Quotation Item", fields=["*"])
return build_success_response(items)
@frappe.whitelist()
def get_estimate_from_address(full_address):
address_name = frappe.db.get_value("Address", {"full_address": full_address}, "name")
quotation_name = frappe.db.get_value("Quotation", {"custom_installation_address": address_name}, "name")
quotation_doc = frappe.get_doc("Quotation", quotation_name)
return build_success_response(quotation_doc.as_dict())
# quotation = frappe.db.sql("""
# SELECT q.name, q.custom_installation_address
# FROM `tabQuotation` q
# JOIN `tabAddress` a
# ON q.custom_installation_address = a.name
# WHERE a.full_address =%s
# """, (full_address,), as_dict=True)
# if quotation:
# return build_success_response(quotation)
# else:
# return build_error_response("No quotation found for the given address.", 404)
# @frappe.whitelist()
# def send_estimate_email(estimate_name):
# print("DEBUG: Queuing email send job for estimate:", estimate_name)
# frappe.enqueue(
# "custom_ui.api.db.estimates.send_estimate_email_job",
# estimate_name=estimate_name,
# queue="long", # or "default"
# timeout=600,
# )
# return build_success_response("Email queued for sending.")
@frappe.whitelist()
def send_estimate_email(estimate_name):
# def send_estimate_email_job(estimate_name):
print("DEBUG: Sending estimate email for:", estimate_name)
quotation = frappe.get_doc("Quotation", estimate_name)
party_exists = frappe.db.exists(quotation.quotation_to, quotation.party_name)
if not party_exists:
return build_error_response("No email found for the customer.", 400)
party = frappe.get_doc(quotation.quotation_to, quotation.party_name)
email = None
if (getattr(party, 'email_id', None)):
email = party.email_id
elif (getattr(party, 'contact_ids', None) and len(party.email_ids) > 0):
primary = next((e for e in party.email_ids if e.is_primary), None)
email = primary.email_id if primary else party.email_ids[0].email_id
if not email and quotation.custom_installation_address:
address = frappe.get_doc("Address", quotation.custom_installation_address)
email = getattr(address, 'email_id', None)
if not email:
return build_error_response("No email found for the customer or address.", 400)
# email = "casey@shilohcode.com"
template_name = "Quote with Actions - SNW"
template = frappe.get_doc("Email Template", template_name)
message = frappe.render_template(template.response, {"doc": quotation})
subject = frappe.render_template(template.subject, {"doc": quotation})
html = frappe.get_print("Quotation", quotation.name, print_format="Quotation - SNW - Standard", letterhead=True)
print("DEBUG: Generated HTML for PDF.")
pdf = get_pdf(html)
print("DEBUG: Generated PDF for email attachment.")
frappe.sendmail(
recipients=email,
subject=subject,
content=message,
doctype="Quotation",
name=quotation.name,
read_receipt=1,
print_letterhead=1,
attachments=[{"fname": f"{quotation.name}.pdf", "fcontent": pdf}]
)
print(f"DEBUG: Email sent to {email} successfully.")
quotation.custom_current_status = "Submitted"
quotation.custom_sent = 1
quotation.save()
quotation.submit()
updated_quotation = frappe.get_doc("Quotation", estimate_name)
print("DEBUG: Quotation submitted successfully.")
return build_success_response(updated_quotation.as_dict())
@frappe.whitelist()
def upsert_estimate(data):
"""Create or update an estimate."""
try:
data = json.loads(data) if isinstance(data, str) else data
print("DEBUG: Upsert estimate data:", data)
estimate_name = data.get("estimate_name")
# If estimate_name exists, update existing estimate
if estimate_name:
print(f"DEBUG: Updating existing estimate: {estimate_name}")
estimate = frappe.get_doc("Quotation", estimate_name)
# Update fields
estimate.custom_installation_address = data.get("address_name")
estimate.party_name = data.get("contact_name")
# Clear existing items and add new ones
estimate.items = []
for item in data.get("items", []):
item = json.loads(item) if isinstance(item, str) else item
estimate.append("items", {
"item_code": item.get("item_code"),
"qty": item.get("qty"),
})
estimate.save()
print(f"DEBUG: Estimate updated: {estimate.name}")
return build_success_response(estimate.as_dict())
# Otherwise, create new estimate
else:
print("DEBUG: Creating new estimate")
print("DEBUG: Retrieved address name:", data.get("address_name"))
new_estimate = frappe.get_doc({
"doctype": "Quotation",
"custom_installation_address": data.get("address_name"),
"contact_email": data.get("contact_email"),
"party_name": data.get("contact_name"),
"company": "Sprinklers Northwest",
"customer_name": data.get("customer_name"),
})
for item in data.get("items", []):
item = json.loads(item) if isinstance(item, str) else item
new_estimate.append("items", {
"item_code": item.get("item_code"),
"qty": item.get("qty"),
})
new_estimate.insert()
print("DEBUG: New estimate created with name:", new_estimate.name)
return build_success_response(new_estimate.as_dict())
except Exception as e:
print(f"DEBUG: Error in upsert_estimate: {str(e)}")
return build_error_response(str(e), 500)
@frappe.whitelist()
def lock_estimate(estimate_name):
"""Lock an estimate to prevent further edits."""
try:
estimate = frappe.get_doc("Quotation", estimate_name)
estimate.submit()
final_estimate = frappe.get_doc("Quotation", estimate_name)
return build_success_response(final_estimate.as_dict())
except Exception as e:
return build_error_response(str(e), 500)