77 lines
2.5 KiB
Python
77 lines
2.5 KiB
Python
import frappe
|
|
import requests
|
|
from frappe import _
|
|
|
|
@frappe.whitelist()
|
|
def sync_custom_fields_to_woocommerce(item_code):
|
|
"""Sync Custom Fields vom Item nach WooCommerce (ACF)"""
|
|
|
|
if not item_code:
|
|
frappe.throw(_("Kein Item Code angegeben"))
|
|
|
|
doc = frappe.get_doc("Item", item_code)
|
|
|
|
if not doc.get("woocommerce_servers"):
|
|
return False
|
|
|
|
# Hier die Felder definieren: ERPNext-Feldname : ACF-Feldname in WordPress
|
|
field_mapping = {
|
|
"custom_zustand2": "zustand2",
|
|
# Weitere Felder hier hinzufügen, z.B.:
|
|
# "custom_mein_feld": "mein_feld",
|
|
# "custom_preisstufe": "preisstufe",
|
|
# "custom_bemerkung": "bemerkung",
|
|
}
|
|
|
|
success_count = 0
|
|
|
|
for wc_link in doc.woocommerce_servers:
|
|
if not wc_link.enable_sync or not wc_link.woocommerce_id:
|
|
continue
|
|
|
|
try:
|
|
wc_server = frappe.get_doc("WooCommerce Server", wc_link.woocommerce_server)
|
|
|
|
base_url = wc_server.woocommerce_server_url.rstrip("/")
|
|
if not base_url.endswith("/wp-json/wc/v3"):
|
|
base_url += "/wp-json/wc/v3"
|
|
|
|
url = f"{base_url}/products/{wc_link.woocommerce_id}"
|
|
auth = (wc_server.api_key, wc_server.api_secret)
|
|
|
|
# Aktuelles Produkt holen
|
|
resp = requests.get(url, auth=auth, timeout=20)
|
|
resp.raise_for_status()
|
|
product = resp.json()
|
|
|
|
# ACF Daten aufbauen / mergen
|
|
acf_data = product.get("acf", {})
|
|
|
|
# Felder übertragen
|
|
for erp_field, acf_field in field_mapping.items():
|
|
value = doc.get(erp_field)
|
|
if value is not None:
|
|
acf_data[acf_field] = value
|
|
|
|
payload = {"acf": acf_data}
|
|
|
|
# Update an WooCommerce
|
|
update_resp = requests.put(url, json=payload, auth=auth, timeout=20)
|
|
update_resp.raise_for_status()
|
|
|
|
success_count += 1
|
|
|
|
except Exception as e:
|
|
frappe.log_error(
|
|
"Fehler beim Sync Custom Fields für Item {}: {}".format(item_code, str(e)),
|
|
"ACF Custom Fields Sync"
|
|
)
|
|
|
|
if success_count > 0:
|
|
frappe.msgprint(
|
|
"Custom Fields fuer {} WooCommerce-Produkt(e) synchronisiert".format(success_count),
|
|
alert=True,
|
|
indicator="green"
|
|
)
|
|
return True
|
|
return False |