Okay, here is the Python code.
Important Considerations Before Running:
- BACKUP YOUR DATABASE: Before running any script that modifies data, always back up your ERPNext database.
- TEST ON A DEVELOPMENT/STAGING INSTANCE: Never run such scripts directly on a live production instance without thorough testing on a copy of your data.
- Understand the Logic: Make sure you understand what the script does, especially regarding how it matches items and the implications of submitting a Purchase Receipt.
- Permissions: If running from
bench execute or a scheduled script, the user context might matter for permissions. Using ignore_permissions=True during save() is a common practice for backend scripts, but be mindful of security.
import frappe
# --- Configuration ---
# !!! REPLACE THESE WITH YOUR ACTUAL DOCUMENT NAMES !!!
pr_name = "GRN-2025-0002"
po_name = "PO-2025-0019"
# --- End Configuration ---
def link_pr_to_po_and_update_status(pr_name, po_name):
"""
Links items from a Purchase Receipt (PR) to a Purchase Order (PO)
based on item_code, and then updates the PO's status.
"""
if not frappe.db:
print("ERROR: Frappe context not available. Are you running this via 'bench execute'?")
return
# Ensure we are in a transaction if running from console/scheduled script
# This helps frappe.db.commit() work as expected in non-request contexts.
if not getattr(frappe.flags, 'in_migrate', False) and not getattr(frappe.flags, 'in_install', False):
frappe.flags.in_commit = True
try:
pr = frappe.get_doc("Purchase Receipt", pr_name)
po = frappe.get_doc("Purchase Order", po_name)
# 1. Build a map of PO item_code to a list of *available* PO item child doc names (IDs)
po_items_to_match_map = {}
for po_item in po.items:
if po_item.received_qty < po_item.qty: # Only consider open PO items
po_items_to_match_map.setdefault(po_item.item_code, []).append({
"name": po_item.name,
"pending_qty": po_item.qty - po_item.received_qty
})
if not po_items_to_match_map:
print(f"No items in PO {po.name} are pending receipt or available for matching.")
# You might want to exit or handle this case differently
# return # Or raise an exception
# 2. Match PR items with PO items
linked_items_changed = False
for pr_item in pr.items:
if pr_item.purchase_order_item:
print(f"PR Item {pr_item.item_code} (ID: {pr_item.name}, Qty: {pr_item.qty}) is already linked to PO Item {pr_item.purchase_order_item}. Skipping.")
continue
if pr_item.item_code in po_items_to_match_map and po_items_to_match_map[pr_item.item_code]:
po_item_detail_to_link = None
# Try to find a PO line that can satisfy the PR item's quantity
for i, po_item_candidate in enumerate(list(po_items_to_match_map[pr_item.item_code])): # Iterate over a copy
# For this script, we'll link if PR qty can be fulfilled,
# or take the first available if not.
# A more complex logic would split PRs or PO lines.
# This simple script assumes one PR item links to one PO item line.
if pr_item.qty <= po_item_candidate["pending_qty"]:
po_item_detail_to_link = po_items_to_match_map[pr_item.item_code].pop(i)
break
if not po_item_detail_to_link and po_items_to_match_map[pr_item.item_code]:
# If no exact qty match, take the first available
po_item_detail_to_link = po_items_to_match_map[pr_item.item_code].pop(0)
if po_item_detail_to_link:
po_item_name_to_link = po_item_detail_to_link["name"]
print(f"Linking PR Item {pr_item.item_code} (ID: {pr_item.name}, Qty: {pr_item.qty}) to PO Item ID {po_item_name_to_link} from PO {po.name}")
frappe.db.set_value("Purchase Receipt Item", pr_item.name, {
"purchase_order": po.name,
"purchase_order_item": po_item_name_to_link
})
linked_items_changed = True
else:
print(f"Could not find an available PO item line for PR Item {pr_item.item_code} (ID: {pr_item.name}) in PO {po.name}.")
else:
print(f"No matching PO item found for PR Item {pr_item.item_code} (ID: {pr_item.name}) in PO {po.name}, or no lines available for this item code.")
# 3. Commit DB changes for PR items if any were made
if linked_items_changed:
frappe.db.commit()
print("PR item links updated in the database.")
# Reload PR to ensure links are reflected in the doc object for submission
pr.reload()
# If PR is in Draft, submit it to trigger PO quantity updates
if pr.docstatus == 0: # Draft
print(f"Purchase Receipt {pr.name} is in Draft. Submitting to update PO item quantities...")
pr.submit()
print(f"Purchase Receipt {pr.name} submitted.")
frappe.db.commit() # Commit the PR submission
elif pr.docstatus == 1: # Submitted
print(f"Purchase Receipt {pr.name} is already submitted. Links were changed directly.")
# If PR was already submitted, PO item received quantities might need manual re-sync
# or a cancel & amend of PR for standard flow.
# For now, we assume the linking is what was desired and PO status update will proceed.
# A more robust solution here might involve calling `pr.update_purchase_order_qty()`
# if you are certain of the implications and item states.
# 4. Update PO status
po.reload() # Reload PO to get latest item statuses (e.g., received_qty)
print(f"Attempting to update status for PO {po.name}...")
# The set_status method calculates and potentially saves the PO.
# update=True tells it to save if status changes.
# update_modified=False avoids changing "Last Modified On" just for a status update.
po.set_status(update=True, update_modified=False)
# Check if set_status actually triggered a save or if we need to do it.
# po.get_doc_before_save() is populated if there are pending changes.
# However, set_status(update=True) might have already saved.
# A direct po.save() can be used to be certain if status logic requires it
# and set_status itself doesn't always save.
if po.is_dirty(): # Checks if document has unsaved changes
print(f"PO {po.name} has pending changes. Saving...")
po.save(ignore_permissions=True) # Use ignore_permissions for backend scripts
frappe.db.commit()
print(f"PO {po.name} saved.")
print(f"PO {po.name} final status: {po.status}")
frappe.msgprint(f"Process completed for PR {pr_name} and PO {po.name}. PO status: {po.status}")
except frappe.DoesNotExistError:
err_msg = f"Error: Purchase Receipt '{pr_name}' or Purchase Order '{po_name}' not found."
print(err_msg)
frappe.log_error(frappe.get_traceback(), f"Script Error: {err_msg}")
frappe.msgprint(err_msg, title="Document Not Found", indicator="red")
except Exception as e:
print(f"An error occurred: {str(e)}")
frappe.log_error(frappe.get_traceback(), "Script Execution Error")
frappe.msgprint(f"An error occurred: {str(e)}", title="Script Error", indicator="red")
finally:
# Reset the flag if it was set by this script
if hasattr(frappe.flags, 'in_commit_by_script') and frappe.flags.in_commit_by_script:
frappe.flags.in_commit = False
delattr(frappe.flags, 'in_commit_by_script')
elif not getattr(frappe.flags, 'in_migrate', False) and not getattr(frappe.flags, 'in_install', False) and hasattr(frappe.flags, 'in_commit'):
# If script set it directly, and it wasn't for migrate/install
# This part is a bit tricky as frappe.flags.in_commit behavior can be nuanced.
# For typical `bench execute`, it's often handled.
pass
# Make sure any uncommitted changes (if not handled by specific commits above) are committed.
# However, it's generally better to commit after specific successful operations.
# If an error occurred before a commit, you might not want to commit partial changes.
# frappe.db.commit() # Consider if a final commit is always needed here.
# --- How to run ---
# 1. Save this code as a .py file (e.g., link_pr_po.py) in your frappe-bench/apps/your_custom_app/your_custom_app/utils/ (or any other accessible path).
# 2. Open bench console: `bench console`
# 3. Import and run:
# from your_custom_app.utils.link_pr_po import link_pr_to_po_and_update_status # Adjust path as needed
# link_pr_to_po_and_update_status("GRN-2025-0002", "PO-2025-0019") # Use your actual IDs
#
# Or, directly using `bench execute`:
# `bench --site your_site_name execute path.to.your.script.link_pr_to_po_and_update_status --args '["GRN-2025-0002", "PO-2025-0019"]'`
# (Make sure the function can be imported by bench execute if it's not in a top-level script file recognized directly)
# Example of direct execution (if the script is self-contained and not relying on being a module function):
if __name__ == "__main__":
# This block is useful if you run the script directly like `python your_script.py`
# BUT, for ERPNext, you usually need the Frappe context, so `bench execute` is preferred.
# For `bench execute`, the function `link_pr_to_po_and_update_status` would be called directly.
# If you intend to call it from bench execute, the script should primarily define the function,
# and the execution call would be separate.
# However, if you want to make the script runnable with `bench execute path_to_script.py`
# and have it use the configured pr_name and po_name at the top:
# Check if running in Frappe context (e.g., via bench execute)
if frappe._dict(pr_name=pr_name, po_name=po_name): # A simple check
print(f"Executing script with PR: {pr_name}, PO: {po_name}")
link_pr_to_po_and_update_status(pr_name, po_name)
else:
print("This script is intended to be run within a Frappe environment (e.g., using 'bench execute').")
print("Please set pr_name and po_name at the top of the script.")