diff --git a/sps_integration/sps_integration/order_acknowledgement.py b/sps_integration/sps_integration/order_acknowledgement.py index 7d005ab..8fbd2ba 100644 --- a/sps_integration/sps_integration/order_acknowledgement.py +++ b/sps_integration/sps_integration/order_acknowledgement.py @@ -19,16 +19,13 @@ def format_sales_order_ack(data: dict) -> dict: if not order_header or not line_items: frappe.log_error(title="Invalid Order Payload", message=str(data)) - print("Invalid order payload received.") return {} - # Get purchase order date and add 1 day purchase_order_date_str = order_header.get("PurchaseOrderDate", "") try: purchase_order_date = datetime.strptime(purchase_order_date_str, "%Y-%m-%d") acknowledgment_date = (purchase_order_date + timedelta(days=1)).strftime("%Y-%m-%d") except ValueError: - # Default to current date +1 if purchaseOrderDate is invalid or missing acknowledgment_date = (datetime.utcnow() + timedelta(days=1)).strftime("%Y-%m-%d") acknowledgement_payload = { @@ -79,13 +76,10 @@ def format_sales_order_ack(data: dict) -> dict: ) } } - - print("Formatted Sales Order Acknowledgment Payload:", json.dumps(acknowledgement_payload, indent=2)) return acknowledgement_payload except Exception as e: frappe.log_error(title="SO ACK Payload Formatting Error", message=str(e)) - print(f"Error formatting payload: {str(e)}") return {} @@ -93,7 +87,6 @@ def format_sales_order_ack(data: dict) -> dict: def sales_order_acknowledgement(data: dict): """Send Sales Order Acknowledgment to SPS Commerce API.""" try: - print("Fetching SPS Integration Settings...") doc = frappe.get_doc("SPS Integration Settings", "Develop") access_token = doc.get_password("access_token") @@ -105,34 +98,15 @@ def sales_order_acknowledgement(data: dict): formatted_data = format_sales_order_ack(data) if not formatted_data: - print("Error: No data to send in Sales Order Acknowledgment.") return - # Debugging prints - # print("Final JSON Payload:", json.dumps(formatted_data, indent=2)) - # print(f"Request URL: {SPS_API_URL}") - # print(f"Headers: {headers}") - # print(f"Sending Request to SPS Commerce...") - - # Corrected API request (Using json= instead of data=) response = requests.post(url=doc.order_acknowledgement_url, headers=headers, data=json.dumps(formatted_data)) - print(f"Response Status Code: {response.status_code}") - print(f"Response Headers: {response.headers}") - print(f"Response Text: {response.text}") - if response.status_code in [200, 201]: response_json = response.json() frappe.log_error(title="SO Acknowledgment Success", message=f"{response.text}") - print("Sales Order Acknowledgment Successful:", response_json) else: frappe.log_error(title="SO Acknowledgment Failure", message=f"{response.text}") - print("Sales Order Acknowledgment Failed:", response.text) except Exception as e: frappe.log_error(title="SO Acknowledgment Error", message=str(e)) - print(f"Error in Sales Order Acknowledgment: {str(e)}") - - -# format_sales_order_ack(data) -# sales_order_acknowledgement(data) \ No newline at end of file diff --git a/sps_integration/sps_integration/order_sync.py b/sps_integration/sps_integration/order_sync.py index 64d7b3e..dd7fe20 100644 --- a/sps_integration/sps_integration/order_sync.py +++ b/sps_integration/sps_integration/order_sync.py @@ -183,7 +183,7 @@ def create_sps_sales_order(data: dict, setting_doc: str, path: str) -> None: data (dict): Sales order payload. setting_doc (str): SPS Integration Settings document. """ - # print("Initializing Sales Order creation...") + # Extract order details order_header = data.get("Header", {}).get("OrderHeader", {}) @@ -191,7 +191,6 @@ def create_sps_sales_order(data: dict, setting_doc: str, path: str) -> None: consumer_order_number = order_header.get("CustomerOrderNumber") po_date = order_header.get("PurchaseOrderDate") doc = frappe.get_doc("SPS Integration Settings", setting_doc) - # print(f"Extracted CustomerOrderNumber: {consumer_order_number}, Marketplace Order ID: {mo_id}, PO Date: {po_date}") # Get delivery date delivery_date = next( @@ -199,40 +198,29 @@ def create_sps_sales_order(data: dict, setting_doc: str, path: str) -> None: if date.get("DateTimeQualifier") == "001"), None ) - print(f"Extracted Delivery Date: {delivery_date}") # Check if customer exists, otherwise create _, customer_name = check_customer_if_exists(data) - # if not customer_exists: - # print("Customer not found, creating new customer...") - # customer_name = create_customer_if_not_exists(data, setting_doc) - # print(f"New customer created: {customer_name}") - # Check and create contact if not exists contact_name = check_and_create_contact(data, setting_doc) - # print("") - # if contact_name: - # print(f"Contact verified/created: {contact_name}") + # Create addresses if not exists billing_address, shipping_address = create_address_contact(data, customer_name) - print(f"Billing Address: {billing_address}, Shipping Address: {shipping_address}") # Get marketplace details - marketplace_data = frappe.get_list( - "Marketplace", - filters={"is_wholesale": 1}, - fields=["name", "naming_series"], - as_list=True, - ) + marketplace_name = doc.marketplace - if not marketplace_data: + if not marketplace_name: frappe.log_error("SPS Order Error", "No wholesale marketplace found.") - # print("No wholesale marketplace found. Aborting order creation.") return - marketplace_name, series_name = marketplace_data[0] - # print(f"Marketplace found: {marketplace_name}, Series: {series_name}") + + series_name = frappe.get_value( + "Marketplace", + marketplace_name + "naming_series" + ) # Create Sales Order sales_order = frappe.new_doc("Sales Order") @@ -250,8 +238,6 @@ def create_sps_sales_order(data: dict, setting_doc: str, path: str) -> None: if contact_name: sales_order.contact_person = contact_name - # print(f"Created Sales Order Document: {sales_order.customer}") - # Adding items to the sales order for item in data.get("LineItem", []): line_item = item.get("OrderLine", {}) @@ -266,17 +252,12 @@ def create_sps_sales_order(data: dict, setting_doc: str, path: str) -> None: item_row = create_sps_sales_order_item_row(sku, quantity, amount, uom, description, setting_doc) sales_order.append("items", item_row) - # print(f"Added item: {sku}, Quantity: {quantity}, Amount: {amount}") try: - # print("Saving and submitting Sales Order...") - # print(sales_order.__dict__) # Debugging - sales_order.save() sales_order.submit() frappe.db.commit() return sales_order.name - # print(f"Sales order successfully created and submitted: {sales_order.name}") except Exception as e: error_msg = frappe.get_traceback() @@ -284,7 +265,7 @@ def create_sps_sales_order(data: dict, setting_doc: str, path: str) -> None: title="Sales Order Creation Error", message=f"Marketplace: SPS\n\nTraceback:\n{error_msg}", ) - # print(f"Error while creating sales order: {e}") + diff --git a/sps_integration/sps_integration/orders_utills.py b/sps_integration/sps_integration/orders_utills.py index a256781..f612cc3 100644 --- a/sps_integration/sps_integration/orders_utills.py +++ b/sps_integration/sps_integration/orders_utills.py @@ -88,7 +88,10 @@ def get_sps_item_code_if_exists(order_uom: str, description: str, sku: str, sett item_doc.save() frappe.db.commit() except: - print(frappe.get_traceback()) + frappe.log_error( + title="Item creation", + message=f"{frappe.get_traceback()}" + ) return item_doc.name @@ -113,20 +116,6 @@ def create_sps_sales_order_item_row(sku: str, qty: int, amount: float, uom: str, "custom_sku": sku, } -# def get_sps_market_place_order_ID(market_place_order_id: str, setting_doc: str) -> str: -# """Get or create Marketplace Order ID.""" -# if frappe.db.exists("Marketplace Order ID", market_place_order_id): -# return market_place_order_id - -# doc = frappe.new_doc("Marketplace Order ID") -# doc.update({ -# "marketplace_order_id": market_place_order_id, -# "marketplace": frappe.get_value("SPS Integration Settings", setting_doc, "marketplace"), -# }) -# doc.save() -# frappe.db.commit() -# return doc.name - def get_sps_market_place_order_ID(market_place_order_id: str, setting_doc: str) -> str: """Get or create Marketplace Order ID.""" @@ -170,7 +159,6 @@ def get_link_row(docname: str, link_name: str) -> Dict: def check_and_create_contact(data, setting_doc): """Check if contacts exist, else create new contacts""" - print("Checking for contacts in data...") addresses = data.get('Header', {}).get('Address', []) contacts = None @@ -179,47 +167,36 @@ def check_and_create_contact(data, setting_doc): for address in addresses: if address.get("AddressTypeCode") == "BT" and address.get("Contacts"): contacts = address["Contacts"] - print(f"Billing contact found: {contacts}") break # Stop once billing contacts are found if not contacts: for address in addresses: if address.get("AddressTypeCode") == "ST" and address.get("Contacts"): contacts = address["Contacts"] - print(f"Shipping contact found: {contacts}") break # Stop once shipping contacts are found if not contacts: - print("No contacts available in the provided data.") return None # Check if customer exists - print("Checking if customer exists...") customer_exists, customer_name = check_customer_if_exists(data) - print(f"Customer Exists: {customer_exists}, Customer Name: {customer_name}") if customer_exists: # Check if the contact email already exists email_id = contacts[0].get("PrimaryEmail", "") - print(f"Checking if contact email {email_id} exists in the system...") if frappe.db.exists("Contact Email", {"email_id": email_id}): contact_name = frappe.get_value( "Contact Email", {"email_id": email_id}, "parent" ) - print(f"Existing contact found: {contact_name}") else: - print("No existing contact found. Creating a new contact...") - doc = frappe.new_doc("Contact") doc.first_name = customer_name - print(f"Setting contact first name: {customer_name}") if email_id: email_row = { "email_id": email_id, "is_primary": 1 } doc.append("email_ids", email_row) - print(f"Added email: {email_id}") phone_number = contacts[0].get("PrimaryPhone", "") if phone_number: @@ -228,11 +205,9 @@ def check_and_create_contact(data, setting_doc): "is_primary_phone": 1 } doc.append("phone_nos", num_row) - print(f"Added phone number: {phone_number}") link_row = get_link_row("Customer", customer_name) doc.append("links", link_row) - print(f"Linked contact to customer: {customer_name}") doc.save() frappe.db.commit() @@ -253,52 +228,38 @@ def create_customer_if_not_exists(data: dict, setting_doc: str) -> str: Returns: customer_name (str): Return customer name after creation of customer. """ - print("Checking Trading Partner ID in the payload...") trading_id = data.get("Header", {}).get("OrderHeader", {}).get("TradingPartnerId") - print(f"Trading Partner ID: {trading_id}") - print("Fetching addresses from payload...") addresses = data.get("Header", {}).get("Address", []) address_names = [address.get("AddressName") for address in addresses] - print(f"Extracted Address Names: {address_names}") - print("Checking if customer already exists...") if frappe.db.exists("Customer", {"custom_trading_partner_id": trading_id}): customer_name = frappe.get_value( "Customer", {"custom_trading_partner_id": trading_id}, "name" ) - print(f"Customer already exists: {customer_name}") else: - print("Customer does not exist. Creating a new customer...") doc = frappe.new_doc("Customer") doc.custom_trading_partner_id = trading_id doc.customer_name = address_names[0].capitalize() - print(f"Assigned customer name: {doc.customer_name}") doc.customer_type = frappe.get_value( "SPS Integration Settings", setting_doc, "customer_type" ) - print(f"Fetched customer type from settings: {doc.customer_type}") doc.save() frappe.db.commit() - print(f"New customer created: {doc.name}") for address in addresses: address_type = address.get("AddressTypeCode") - print(f"Processing address type: {address_type}") if address_type == "BT": - print("Billing address found, creating or updating address...") doc.customer_primary_contact = create_or_update_address(address, "Billing", doc.name) - print(f"Primary contact assigned: {doc.customer_primary_contact}") doc.save() frappe.db.commit() - print(f"Customer document saved: {doc.name}") return doc.name