blob: 2a98df2e263baae1b228cd8eeac64ee3571e4e01 [file] [log] [blame]
Abhishek Balam6e9e7b42020-10-14 19:31:37 +05301import frappe
Abhishek Balam2f528c12020-10-14 19:48:57 +05302from frappe import _
Abhishek Balam6e9e7b42020-10-14 19:31:37 +05303from frappe.contacts.doctype.address.address import Address
4from frappe.contacts.address_and_contact import set_link_title
5from frappe.core.doctype.dynamic_link.dynamic_link import deduplicate_dynamic_links
Abhishek Balam89419c92020-10-14 20:09:05 +05306from frappe.contacts.doctype.address.address import get_address_templates
Abhishek Balam6e9e7b42020-10-14 19:31:37 +05307
8class CustomAddress(Address):
9 def validate(self):
10 self.link_address()
11 self.validate_reference()
12 super(CustomAddress, self).validate_preferred_address()
13 set_link_title(self)
14 deduplicate_dynamic_links(self)
15
Abhishek Balam6e9e7b42020-10-14 19:31:37 +053016 def link_address(self):
17 """Link address based on owner"""
18 if not self.links and not self.is_your_company_address:
19 contact_name = frappe.db.get_value("Contact", {"email_id": self.owner})
20 if contact_name:
21 contact = frappe.get_cached_doc('Contact', contact_name)
22 print('here', str(contact))
23 for link in contact.links:
24 self.append('links', dict(link_doctype=link.link_doctype, link_name=link.link_name))
25 return True
Abhishek Balam2f528c12020-10-14 19:48:57 +053026 return False
Abhishek Balam6e9e7b42020-10-14 19:31:37 +053027
Abhishek Balam2f528c12020-10-14 19:48:57 +053028 def validate_reference(self):
29 if self.is_your_company_address:
30 print('here')
31 if not [row for row in self.links if row.link_doctype == "Company"]:
32 frappe.throw(_("Address needs to be linked to a Company. Please add a row for Company in the Links table below."),
33 title =_("Company not Linked"))
Abhishek Balam89419c92020-10-14 20:09:05 +053034
35@frappe.whitelist()
36def get_shipping_address(company, address = None):
37 filters = [
38 ["Dynamic Link", "link_doctype", "=", "Company"],
39 ["Dynamic Link", "link_name", "=", company],
40 ["Address", "is_your_company_address", "=", 1]
41 ]
42 fields = ["*"]
43 if address and frappe.db.get_value('Dynamic Link',
44 {'parent': address, 'link_name': company}):
45 filters.append(["Address", "name", "=", address])
46
47 address = frappe.get_all("Address", filters=filters, fields=fields) or {}
48
49 if address:
50 address_as_dict = address[0]
51 name, address_template = get_address_templates(address_as_dict)
52 return address_as_dict.get("name"), frappe.render_template(address_template, address_as_dict)