Files
ns_erpnext_app/ns_app/api/customer.py
2026-02-13 10:59:38 -05:00

88 lines
2.8 KiB
Python

import frappe
from frappe import _
@frappe.whitelist()
def create_customer_full(**data):
frappe.only_for(["System Manager", "Sales User", "Sales Manager"])
required = [
"customer_name",
"customer_type",
"customer_group",
"mobile_no",
"address_line1",
"pincode",
"country"
]
for field in required:
if not data.get(field):
frappe.throw(_(f"Missing required field: {field}"))
# Prevent duplicates
if frappe.db.exists("Customer", {"customer_name": data["customer_name"]}):
frappe.throw(_("Customer already exists"))
try:
frappe.db.begin()
if data.get("custom_auto_pay_enabled") and not data.get("custom_auto_pay_id"):
frappe.throw("Auto Pay ID is required when Auto Pay is enabled.")
customer = frappe.get_doc({
"doctype": "Customer",
"customer_name": data["customer_name"],
"customer_type": data["customer_type"],
"customer_group": data["customer_group"],
"territory": "United States",
"custom_auto_pay_status": 1 if data.get("custom_auto_pay_enabled") else 0,
"custom_auto_pay_id": data.get("custom_auto_pay_id") if data.get("custom_auto_pay_enabled") else "",
"custom_send_via": data.get("custom_send_via"),
}).insert(ignore_permissions=True)
contact = frappe.get_doc({
"doctype": "Contact",
"first_name": data["customer_name"]
if data["customer_type"] == "Individual"
else data["customer_name"],
"email_ids": [{
"email_id": data.get("email_id"),
"is_primary": 1
}] if data.get("email_id") else [],
"phone_nos": [{
"phone": data["mobile_no"],
"is_primary_phone": 1
}],
"links": [{
"link_doctype": "Customer",
"link_name": customer.name
}]
}).insert(ignore_permissions=True)
address = frappe.get_doc({
"doctype": "Address",
"address_title": customer.name,
"address_type": "Billing",
"address_line1": data["address_line1"],
"address_line2": data.get("address_line2"),
"city": data.get("city"),
"state": data.get("state"),
"pincode": data["pincode"],
"country": data["country"],
"links": [{
"link_doctype": "Customer",
"link_name": customer.name
}]
}).insert(ignore_permissions=True)
frappe.db.commit()
return customer.name
except Exception:
frappe.db.rollback()
frappe.log_error(frappe.get_traceback(), "NS App: Create Customer Failed")
raise