Problem Statement: Update ledger closing balance of a Customer to Customer document using server script triggered on save of GL Entry
Script used:
Server Script
Script Type: Document Event
Reference Document Type: GL Entry, Journal Entry, or Payment Entry
def update_customer_outstanding_balance(doc, method):
try:
# Only proceed if the document is related to a customer and the company is defined
if doc.party_type == "Customer" and doc.party and doc.company:
# Fetch the total outstanding balance for the customer filtered by company, including opening balance
outstanding_balance = frappe.db.sql("""
SELECT SUM(debit - credit) AS outstanding_balance
FROM `tabGL Entry`
WHERE party_type = 'Customer'
AND party = %s
AND company = %s
AND is_cancelled = 0
AND (is_opening = 'Yes' OR is_opening IS NULL) -- Include opening entries
""", (doc.party, doc.company), as_dict=True)
# If balance exists, update custom_outstanding field in Customer doctype
if outstanding_balance and outstanding_balance[0].outstanding_balance is not None:
frappe.db.set_value('Customer', doc.party, 'custom_outstanding', outstanding_balance[0].outstanding_balance)
frappe.logger().info(f"Updated custom_outstanding for {doc.party}: {outstanding_balance[0].outstanding_balance}")
else:
# Set to 0 if no balance is found
frappe.db.set_value('Customer', doc.party, 'custom_outstanding', 0)
frappe.logger().info(f"Set custom_outstanding to 0 for {doc.party}")