big update

This commit is contained in:
Casey 2026-01-15 17:31:53 -06:00
parent 73d235b7bc
commit 0380dd10d8
18 changed files with 951 additions and 490 deletions

View file

@ -1,7 +1,7 @@
import frappe
import json
from custom_ui.db_utils import build_error_response, build_success_response, process_filters, process_sorting
from custom_ui.services import DbService, ClientService, AddressService
from custom_ui.services import DbService, ClientService, AddressService, ContactService
@frappe.whitelist()
def get_week_bid_meetings(week_start, week_end):
@ -17,8 +17,10 @@ def get_week_bid_meetings(week_start, week_end):
order_by="start_time asc"
)
for meeting in meetings:
address_doc = frappe.get_doc("Address", meeting["address"])
address_doc = AddressService.get_or_throw(meeting["address"])
meeting["address"] = address_doc.as_dict()
contact_doc = ContactService.get_or_throw(meeting["contact"]) if meeting.get("contact") else None
meeting["contact"] = contact_doc.as_dict() if contact_doc else None
return build_success_response(meetings)
except Exception as e:
frappe.log_error(message=str(e), title="Get Week On-Site Meetings Failed")
@ -60,6 +62,13 @@ def get_unscheduled_bid_meetings():
filters={"status": "Unscheduled"},
order_by="creation desc"
)
for meeting in meetings:
address_doc = AddressService.get_or_throw(meeting["address"])
meeting["address"] = address_doc.as_dict()
# client_doc = ClientService.get_client_doctype(meeting["party_name"])
# meeting["client"] = client_doc.as_dict() if client_doc else None
contact_doc = ContactService.get_or_throw(meeting["contact"]) if meeting.get("contact") else None
meeting["contact"] = contact_doc.as_dict() if contact_doc else None
return build_success_response(meetings)
except Exception as e:
frappe.log_error(message=str(e), title="Get Unscheduled On-Site Meetings Failed")
@ -75,8 +84,11 @@ def get_bid_meeting(name):
# Get the full address data
if meeting_dict.get("address"):
address_doc = frappe.get_doc("Address", meeting_dict["address"])
address_doc = AddressService.get_or_throw(meeting_dict["address"])
meeting_dict["address"] = address_doc.as_dict()
if meeting_dict.get("contact"):
contact_doc = ContactService.get_or_throw(meeting_dict["contact"])
meeting_dict["contact"] = contact_doc.as_dict()
return build_success_response(meeting_dict)
except frappe.DoesNotExistError:
@ -127,37 +139,30 @@ def create_bid_meeting(data):
@frappe.whitelist()
def update_bid_meeting(name, data):
"""Update an existing On-Site Meeting."""
defualts = {
"address": None,
"start_time": None,
"end_time": None,
"notes": None,
"assigned_employee": None,
"completed_by": None,
"contact": None,
"status": None
}
try:
if isinstance(data, str):
data = json.loads(data)
# Ensure we always have the expected keys so fields can be cleared
data = {**defualts, **(data or {})}
meeting = frappe.get_doc("On-Site Meeting", name)
# Only update fields that are explicitly provided in the data
for key, value in data.items():
# Allow explicitly clearing date/time and assignment fields
if key in ["start_time", "end_time", "assigned_employee", "completed_by"] and value is None:
meeting.set(key, None)
continue
if value is not None:
if key == "address":
value = frappe.db.get_value("Address", {"full_address": value}, "name")
elif key in ["assigned_employee", "completed_by"]:
value = frappe.db.get_value("Employee", {"employee_name": value}, "name")
print(f"DEBUG: Updating field '{key}' to value '{value}'")
if key == "address" and value is not None:
# Convert full address to address name
value = frappe.db.get_value("Address", {"full_address": value}, "name")
meeting.set(key, value)
elif key in ["assigned_employee", "completed_by"] and value is not None:
# Convert employee name to employee ID
value = frappe.db.get_value("Employee", {"employee_name": value}, "name")
meeting.set(key, value)
else:
# For all other fields, set the value as-is (including None to clear fields)
meeting.set(key, value)
print(f"DEBUG: Field '{key}' updated to '{meeting.get(key)}'")
meeting.save()
frappe.db.commit()
return build_success_response(meeting.as_dict())
except frappe.DoesNotExistError:
return build_error_response(f"On-Site Meeting '{name}' does not exist.", 404)

View file

@ -205,19 +205,20 @@ def get_clients_table_data(filters={}, sortings=[], page=1, page_size=10):
addresses = [frappe.get_doc("Address", addr["name"]).as_dict() for addr in address_names]
tableRows = []
for address in addresses:
is_lead = False
is_lead = address.customer_type == "Lead"
print("##########IS LEAD:", is_lead)
tableRow = {}
links = address.links
customer_links = [link for link in links if link.link_doctype == "Customer"] if links else None
customer_name = address.get("custom_customer_to_bill", None)
if not customer_links:
customer_links = [link for link in links if link.link_doctype == "Lead"] if links else None
is_lead = True if customer_links else False
if not customer_name and not customer_links:
# customer_links = [link for link in links if link.link_doctype == "Customer"] if links else None
customer_name = address.get("customer_name")
# if not customer_links:
# customer_links = [link for link in links if link.link_doctype == "Lead"] if links else None
# is_lead = True if customer_links else False
# if not customer_name and not customer_links:
# customer_name = frappe.get_value("Lead", address.get("customer_name"), "custom_customer_name")
if is_lead:
# print("DEBUG: No customer to bill. Customer links found:", customer_links)
customer_name = frappe.get_value("Lead", address.get("customer_name"), "custom_customer_name")
elif not customer_name and customer_links:
print("DEBUG: No customer to bill. Customer links found:", customer_links)
customer_name = frappe.get_value("Lead", customer_links[0].link_name, "custom_customer_name") if is_lead else customer_links[0].link_name
tableRow["id"] = address["name"]
tableRow["customer_name"] = customer_name
tableRow["address"] = (
@ -225,6 +226,7 @@ def get_clients_table_data(filters={}, sortings=[], page=1, page_size=10):
f"{' ' + address['address_line2'] if address['address_line2'] else ''} "
f"{address['city']}, {address['state']} {address['pincode']}"
)
print("########IS LEAD @TABLE ROW:", is_lead)
tableRow["client_type"] = "Lead" if is_lead else "Customer"
# tableRow["appointment_scheduled_status"] = address.custom_onsite_meeting_scheduled
# tableRow["estimate_sent_status"] = address.custom_estimate_sent_status
@ -308,6 +310,7 @@ def upsert_client(data):
"phone": primary_contact.get("phone_number"),
"custom_customer_name": customer_name,
"customer_type": customer_type,
"address_type": "Billing",
"companies": [{ "company": data.get("company_name")
}]
}

View file

@ -4,7 +4,7 @@ from custom_ui.api.db.general import get_doc_history
from custom_ui.db_utils import process_query_conditions, build_datatable_dict, get_count_or_filters, build_success_response, build_error_response
from werkzeug.wrappers import Response
from custom_ui.api.db.clients import check_if_customer, convert_lead_to_customer
from custom_ui.services import DbService, ClientService, AddressService
from custom_ui.services import DbService, ClientService, AddressService, ContactService
# ===============================================================================
# ESTIMATES & INVOICES API METHODS
@ -145,17 +145,18 @@ def send_estimate_email(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:
if not DbService.exists("Contact", quotation.contact_person):
return build_error_response("No email found for the customer.", 400)
party = frappe.get_doc(quotation.quotation_to, quotation.party_name)
party = ContactService.get_or_throw(quotation.contact_person)
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
email = quotation.contact_email or None
if not email:
if (getattr(party, 'email_id', None)):
email = party.email_id
elif (getattr(party, 'email_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_job_address:
address = frappe.get_doc("Address", quotation.custom_job_address)
@ -383,9 +384,10 @@ def upsert_estimate(data):
try:
data = json.loads(data) if isinstance(data, str) else data
print("DEBUG: Upsert estimate data:", data)
address_doc = AddressService.get_or_throw(data.get("address_name"))
estimate_name = data.get("estimate_name")
client_doctype = ClientService.get_client_doctype(data.get("customer"))
client_doctype = ClientService.get_client_doctype(address_doc.customer_name)
print("DEBUG: Retrieved client doctype:", client_doctype)
project_template = data.get("project_template", None)
# If estimate_name exists, update existing estimate
@ -430,17 +432,16 @@ def upsert_estimate(data):
else:
print("DEBUG: Creating new estimate")
print("DEBUG: Retrieved address name:", data.get("address_name"))
client_doctype = ClientService.get_client_doctype(data.get("customer"))
new_estimate = frappe.get_doc({
"doctype": "Quotation",
"custom_requires_half_payment": data.get("requires_half_payment", 0),
"custom_job_address": data.get("address_name"),
"custom_current_status": "Draft",
"contact_email": data.get("contact_email"),
"party_name": data.get("customer"),
"quotation_to": client_doctype,
"party_name": data.get("contact_name"),
"quotation_to": "Contact",
"company": data.get("company"),
"customer": data.get("customer"),
"actual_customer_name": address_doc.customer_name,
"customer_type": client_doctype,
"customer_address": data.get("address_name"),
"contact_person": data.get("contact_name"),
@ -457,9 +458,12 @@ def upsert_estimate(data):
"discount_amount": item.get("discount_amount") or item.get("discountAmount", 0),
"discount_percentage": item.get("discount_percentage") or item.get("discountPercentage", 0)
})
# Iterate through every field and print it out, I need to see if there is any field that is a Dynamic link saying Customer
for fieldname, value in new_estimate.as_dict().items():
print(f"DEBUG: Field '{fieldname}': {value}")
new_estimate.insert()
AddressService.append_link(data.get("address_name"), "quotations", "quotation", new_estimate.name)
ClientService.append_link(data.get("customer"), "quotations", "quotation", new_estimate.name)
# AddressService.append_link(data.get("address_name"), "quotations", "quotation", new_estimate.name)
# ClientService.append_link(data.get("customer"), "quotations", "quotation", new_estimate.name)
print("DEBUG: New estimate created with name:", new_estimate.name)
return build_success_response(new_estimate.as_dict())
except Exception as e: