blob: 633692dd24b1c7ca5745c73f8b4158113255950f [file] [log] [blame]
vishdhad3ec1c12020-03-24 11:31:41 +05301import traceback
2
3import pycountry
4import taxjar
5
6import frappe
7from erpnext import get_default_company
8from frappe import _
9from frappe.contacts.doctype.address.address import get_company_address
10
11TAX_ACCOUNT_HEAD = frappe.db.get_single_value("TaxJar Settings", "tax_account_head")
12SHIP_ACCOUNT_HEAD = frappe.db.get_single_value("TaxJar Settings", "shipping_account_head")
13TAXJAR_CREATE_TRANSACTIONS = frappe.db.get_single_value("TaxJar Settings", "taxjar_create_transactions")
14TAXJAR_CALCULATE_TAX = frappe.db.get_single_value("TaxJar Settings", "taxjar_calculate_tax")
15SUPPORTED_COUNTRY_CODES = ["AT", "AU", "BE", "BG", "CA", "CY", "CZ", "DE", "DK", "EE", "ES", "FI",
16 "FR", "GB", "GR", "HR", "HU", "IE", "IT", "LT", "LU", "LV", "MT", "NL", "PL", "PT", "RO",
17 "SE", "SI", "SK", "US"]
18
19
20def get_client():
21 taxjar_settings = frappe.get_single("TaxJar Settings")
22
23 if not taxjar_settings.is_sandbox:
24 api_key = taxjar_settings.api_key and taxjar_settings.get_password("api_key")
25 api_url = taxjar.DEFAULT_API_URL
26 else:
27 api_key = taxjar_settings.sandbox_api_key and taxjar_settings.get_password("sandbox_api_key")
28 api_url = taxjar.SANDBOX_API_URL
29
30 if api_key and api_url:
31 return taxjar.Client(api_key=api_key, api_url=api_url)
32
33
34def create_transaction(doc, method):
35 """Create an order transaction in TaxJar"""
36
37 if not TAXJAR_CREATE_TRANSACTIONS:
38 return
39
40 client = get_client()
41
42 if not client:
43 return
44
45 sales_tax = sum([tax.tax_amount for tax in doc.taxes if tax.account_head == TAX_ACCOUNT_HEAD])
46
47 if not sales_tax:
48 return
49
50 tax_dict = get_tax_data(doc)
51
52 if not tax_dict:
53 return
54
55 tax_dict['transaction_id'] = doc.name
56 tax_dict['transaction_date'] = frappe.utils.today()
57 tax_dict['sales_tax'] = sales_tax
58 tax_dict['amount'] = doc.total + tax_dict['shipping']
59
60 try:
61 client.create_order(tax_dict)
62 except taxjar.exceptions.TaxJarResponseError as err:
63 frappe.throw(_(sanitize_error_response(err)))
64 except Exception as ex:
65 print(traceback.format_exc(ex))
66
67
68def delete_transaction(doc, method):
69 """Delete an existing TaxJar order transaction"""
70
71 if not TAXJAR_CREATE_TRANSACTIONS:
72 return
73
74 client = get_client()
75
76 if not client:
77 return
78
79 client.delete_order(doc.name)
80
81
82def get_tax_data(doc):
83 from_address = get_company_address_details(doc)
84 from_shipping_state = from_address.get("state")
85 from_country_code = frappe.db.get_value("Country", from_address.country, "code")
86 from_country_code = from_country_code.upper()
87
88 to_address = get_shipping_address_details(doc)
89 to_shipping_state = to_address.get("state")
90 to_country_code = frappe.db.get_value("Country", to_address.country, "code")
91 to_country_code = to_country_code.upper()
92
93 if to_country_code not in SUPPORTED_COUNTRY_CODES:
94 return
95
96 shipping = sum([tax.tax_amount for tax in doc.taxes if tax.account_head == SHIP_ACCOUNT_HEAD])
97
98 if to_shipping_state is not None:
99 to_shipping_state = get_iso_3166_2_state_code(to_address)
100
101 tax_dict = {
102 'from_country': from_country_code,
103 'from_zip': from_address.pincode,
104 'from_state': from_shipping_state,
105 'from_city': from_address.city,
106 'from_street': from_address.address_line1,
107 'to_country': to_country_code,
108 'to_zip': to_address.pincode,
109 'to_city': to_address.city,
110 'to_street': to_address.address_line1,
111 'to_state': to_shipping_state,
112 'shipping': shipping,
113 'amount': doc.net_total
114 }
115
116 return tax_dict
117
118
119def set_sales_tax(doc, method):
120 if not TAXJAR_CALCULATE_TAX:
121 return
122
123 if not doc.items:
124 return
125
126 # if the party is exempt from sales tax, then set all tax account heads to zero
127 sales_tax_exempted = hasattr(doc, "exempt_from_sales_tax") and doc.exempt_from_sales_tax \
128 or frappe.db.has_column("Customer", "exempt_from_sales_tax") and frappe.db.get_value("Customer", doc.customer, "exempt_from_sales_tax")
129
130 if sales_tax_exempted:
131 for tax in doc.taxes:
132 if tax.account_head == TAX_ACCOUNT_HEAD:
133 tax.tax_amount = 0
134 break
135
136 doc.run_method("calculate_taxes_and_totals")
137 return
138
139 tax_dict = get_tax_data(doc)
140
141 if not tax_dict:
142 # Remove existing tax rows if address is changed from a taxable state/country
143 setattr(doc, "taxes", [tax for tax in doc.taxes if tax.account_head != TAX_ACCOUNT_HEAD])
144 return
145
146 tax_data = validate_tax_request(tax_dict)
147
148 if tax_data is not None:
149 if not tax_data.amount_to_collect:
150 setattr(doc, "taxes", [tax for tax in doc.taxes if tax.account_head != TAX_ACCOUNT_HEAD])
151 elif tax_data.amount_to_collect > 0:
152 # Loop through tax rows for existing Sales Tax entry
153 # If none are found, add a row with the tax amount
154 for tax in doc.taxes:
155 if tax.account_head == TAX_ACCOUNT_HEAD:
156 tax.tax_amount = tax_data.amount_to_collect
157
158 doc.run_method("calculate_taxes_and_totals")
159 break
160 else:
161 doc.append("taxes", {
162 "charge_type": "Actual",
163 "description": "Sales Tax",
164 "account_head": TAX_ACCOUNT_HEAD,
165 "tax_amount": tax_data.amount_to_collect
166 })
167
168 doc.run_method("calculate_taxes_and_totals")
169
170
171def validate_tax_request(tax_dict):
172 """Return the sales tax that should be collected for a given order."""
173
174 client = get_client()
175
176 if not client:
177 return
178
179 try:
180 tax_data = client.tax_for_order(tax_dict)
181 except taxjar.exceptions.TaxJarResponseError as err:
182 frappe.throw(_(sanitize_error_response(err)))
183 else:
184 return tax_data
185
186
187def get_company_address_details(doc):
188 """Return default company address details"""
189
190 company_address = get_company_address(get_default_company()).company_address
191
192 if not company_address:
193 frappe.throw(_("Please set a default company address"))
194
195 company_address = frappe.get_doc("Address", company_address)
196 return company_address
197
198
199def get_shipping_address_details(doc):
200 """Return customer shipping address details"""
201
202 if doc.shipping_address_name:
203 shipping_address = frappe.get_doc("Address", doc.shipping_address_name)
204 else:
205 shipping_address = get_company_address_details(doc)
206
207 return shipping_address
208
209
210def get_iso_3166_2_state_code(address):
211 country_code = frappe.db.get_value("Country", address.get("country"), "code")
212
213 error_message = _("""{0} is not a valid state! Check for typos or enter the ISO code for your state.""").format(address.get("state"))
214 state = address.get("state").upper().strip()
215
216 # The max length for ISO state codes is 3, excluding the country code
217 if len(state) <= 3:
218 # PyCountry returns state code as {country_code}-{state-code} (e.g. US-FL)
219 address_state = (country_code + "-" + state).upper()
220
221 states = pycountry.subdivisions.get(country_code=country_code.upper())
222 states = [pystate.code for pystate in states]
223
224 if address_state in states:
225 return state
226
227 frappe.throw(_(error_message))
228 else:
229 try:
230 lookup_state = pycountry.subdivisions.lookup(state)
231 except LookupError:
232 frappe.throw(_(error_message))
233 else:
234 return lookup_state.code.split('-')[1]
235
236
237def sanitize_error_response(response):
238 response = response.full_response.get("detail")
239 response = response.replace("_", " ")
240
241 sanitized_responses = {
242 "to zip": "Zipcode",
243 "to city": "City",
244 "to state": "State",
245 "to country": "Country"
246 }
247
248 for k, v in sanitized_responses.items():
249 response = response.replace(k, v)
250
251 return response