[fix] link address via owner, if created in portal #3540
diff --git a/erpnext/utilities/doctype/address/address.py b/erpnext/utilities/doctype/address/address.py
index e2ca74f..b3f6717 100644
--- a/erpnext/utilities/doctype/address/address.py
+++ b/erpnext/utilities/doctype/address/address.py
@@ -21,6 +21,8 @@
 			throw(_("Address Title is mandatory."))
 
 	def validate(self):
+		self.link_fields = ("customer", "supplier", "sales_partner", "lead")
+		self.link_address()
 		self.validate_primary_address()
 		self.validate_shipping_address()
 
@@ -30,7 +32,7 @@
 			self._unset_other("is_primary_address")
 
 		elif self.is_shipping_address != 1:
-			for fieldname in ["customer", "supplier", "sales_partner", "lead"]:
+			for fieldname in self.link_fields:
 				if self.get(fieldname):
 					if not frappe.db.sql("""select name from `tabAddress` where is_primary_address=1
 						and `%s`=%s and name!=%s""" % (fieldname, "%s", "%s"),
@@ -38,6 +40,24 @@
 							self.is_primary_address = 1
 					break
 
+	def link_address(self):
+		"""Link address based on owner"""
+		linked = False
+		for fieldname in self.link_fields:
+			if self.get(fieldname):
+				linked = True
+				break
+
+		if not linked:
+			contact = frappe.db.get_value("Contact", {"email_id": self.owner},
+				("name", "customer", "supplier"), as_dict = True)
+			if contact:
+				self.customer = contact.customer
+				self.supplier = contact.supplier
+
+			self.lead = frappe.db.get_value("Lead", {"email_id": self.owner})
+
+
 	def validate_shipping_address(self):
 		"""Validate that there can only be one shipping address for particular customer, supplier"""
 		if self.is_shipping_address == 1:
@@ -103,5 +123,3 @@
 			return doc.lead == lead
 
 	return False
-
-