blob: 29fd81cab739f2f7e6b9045687217224ac21d1ca [file] [log] [blame]
vishdhad3ec1c12020-03-24 11:31:41 +05301import traceback
Chillar Anand915b3432021-09-02 16:44:59 +05302
vishdhad3ec1c12020-03-24 11:31:41 +05303import frappe
Subin Tom70049442021-08-31 18:33:16 +05304import taxjar
vishdhad3ec1c12020-03-24 11:31:41 +05305from frappe import _
6from frappe.contacts.doctype.address.address import get_company_address
Subin Tom70049442021-08-31 18:33:16 +05307from frappe.utils import cint
vishdhad3ec1c12020-03-24 11:31:41 +05308
Chillar Anand915b3432021-09-02 16:44:59 +05309from erpnext import get_default_company
10
vishdhad3ec1c12020-03-24 11:31:41 +053011TAX_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"]
Subin Tom70049442021-08-31 18:33:16 +053018SUPPORTED_STATE_CODES = ['AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'DC', 'FL', 'GA', 'HI', 'ID', 'IL',
19 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE',
Ankush Menatb147b852021-09-01 16:45:57 +053020 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD',
Subin Tom70049442021-08-31 18:33:16 +053021 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY']
vishdhad3ec1c12020-03-24 11:31:41 +053022
23
24def get_client():
25 taxjar_settings = frappe.get_single("TaxJar Settings")
26
27 if not taxjar_settings.is_sandbox:
28 api_key = taxjar_settings.api_key and taxjar_settings.get_password("api_key")
29 api_url = taxjar.DEFAULT_API_URL
30 else:
31 api_key = taxjar_settings.sandbox_api_key and taxjar_settings.get_password("sandbox_api_key")
32 api_url = taxjar.SANDBOX_API_URL
33
34 if api_key and api_url:
Subin Tom70049442021-08-31 18:33:16 +053035 client = taxjar.Client(api_key=api_key, api_url=api_url)
36 client.set_api_config('headers', {
37 'x-api-version': '2020-08-07'
38 })
39 return client
vishdhad3ec1c12020-03-24 11:31:41 +053040
41
42def create_transaction(doc, method):
43 """Create an order transaction in TaxJar"""
44
45 if not TAXJAR_CREATE_TRANSACTIONS:
46 return
47
48 client = get_client()
49
50 if not client:
51 return
52
53 sales_tax = sum([tax.tax_amount for tax in doc.taxes if tax.account_head == TAX_ACCOUNT_HEAD])
54
55 if not sales_tax:
56 return
57
58 tax_dict = get_tax_data(doc)
59
60 if not tax_dict:
61 return
62
63 tax_dict['transaction_id'] = doc.name
64 tax_dict['transaction_date'] = frappe.utils.today()
65 tax_dict['sales_tax'] = sales_tax
66 tax_dict['amount'] = doc.total + tax_dict['shipping']
67
68 try:
Subin Tom70049442021-08-31 18:33:16 +053069 if doc.is_return:
70 client.create_refund(tax_dict)
Ankush Menatb147b852021-09-01 16:45:57 +053071 else:
Subin Tom70049442021-08-31 18:33:16 +053072 client.create_order(tax_dict)
vishdhad3ec1c12020-03-24 11:31:41 +053073 except taxjar.exceptions.TaxJarResponseError as err:
74 frappe.throw(_(sanitize_error_response(err)))
75 except Exception as ex:
76 print(traceback.format_exc(ex))
77
78
79def delete_transaction(doc, method):
80 """Delete an existing TaxJar order transaction"""
81
82 if not TAXJAR_CREATE_TRANSACTIONS:
83 return
84
85 client = get_client()
86
87 if not client:
88 return
89
90 client.delete_order(doc.name)
91
92
93def get_tax_data(doc):
94 from_address = get_company_address_details(doc)
95 from_shipping_state = from_address.get("state")
96 from_country_code = frappe.db.get_value("Country", from_address.country, "code")
97 from_country_code = from_country_code.upper()
98
99 to_address = get_shipping_address_details(doc)
100 to_shipping_state = to_address.get("state")
101 to_country_code = frappe.db.get_value("Country", to_address.country, "code")
102 to_country_code = to_country_code.upper()
103
vishdhad3ec1c12020-03-24 11:31:41 +0530104 shipping = sum([tax.tax_amount for tax in doc.taxes if tax.account_head == SHIP_ACCOUNT_HEAD])
105
Subin Tom3bb60a42021-09-14 22:04:57 +0530106 line_items = [get_line_item_dict(item,doc.docstatus) for item in doc.items]
vishdhad3ec1c12020-03-24 11:31:41 +0530107
Subin Tom70049442021-08-31 18:33:16 +0530108 if from_shipping_state not in SUPPORTED_STATE_CODES:
109 from_shipping_state = get_state_code(from_address, 'Company')
110
111 if to_shipping_state not in SUPPORTED_STATE_CODES:
112 to_shipping_state = get_state_code(to_address, 'Shipping')
Ankush Menatb147b852021-09-01 16:45:57 +0530113
vishdhad3ec1c12020-03-24 11:31:41 +0530114 tax_dict = {
115 'from_country': from_country_code,
116 'from_zip': from_address.pincode,
117 'from_state': from_shipping_state,
118 'from_city': from_address.city,
119 'from_street': from_address.address_line1,
120 'to_country': to_country_code,
121 'to_zip': to_address.pincode,
122 'to_city': to_address.city,
123 'to_street': to_address.address_line1,
124 'to_state': to_shipping_state,
125 'shipping': shipping,
Subin Tom70049442021-08-31 18:33:16 +0530126 'amount': doc.net_total,
127 'plugin': 'erpnext',
128 'line_items': line_items
vishdhad3ec1c12020-03-24 11:31:41 +0530129 }
Ankush Menatb147b852021-09-01 16:45:57 +0530130 return tax_dict
vishdhad3ec1c12020-03-24 11:31:41 +0530131
Subin Tom70049442021-08-31 18:33:16 +0530132def get_state_code(address, location):
133 if address is not None:
134 state_code = get_iso_3166_2_state_code(address)
135 if state_code not in SUPPORTED_STATE_CODES:
136 frappe.throw(_("Please enter a valid State in the {0} Address").format(location))
137 else:
138 frappe.throw(_("Please enter a valid State in the {0} Address").format(location))
Ankush Menatb147b852021-09-01 16:45:57 +0530139
Subin Tom70049442021-08-31 18:33:16 +0530140 return state_code
vishdhad3ec1c12020-03-24 11:31:41 +0530141
Subin Tom3bb60a42021-09-14 22:04:57 +0530142def get_line_item_dict(item, docstatus):
143 tax_dict = dict(
Subin Tom70049442021-08-31 18:33:16 +0530144 id = item.get('idx'),
145 quantity = item.get('qty'),
146 unit_price = item.get('rate'),
147 product_tax_code = item.get('product_tax_category')
Ankush Menatb147b852021-09-01 16:45:57 +0530148 )
vishdhad3ec1c12020-03-24 11:31:41 +0530149
Subin Tom3bb60a42021-09-14 22:04:57 +0530150 if docstatus == 1:
151 tax_dict.update({
152 'sales_tax':item.get('tax_collectable')
153 })
154
155 return tax_dict
156
vishdhad3ec1c12020-03-24 11:31:41 +0530157def set_sales_tax(doc, method):
158 if not TAXJAR_CALCULATE_TAX:
159 return
160
161 if not doc.items:
162 return
163
Subin Tom70049442021-08-31 18:33:16 +0530164 if check_sales_tax_exemption(doc):
vishdhad3ec1c12020-03-24 11:31:41 +0530165 return
166
167 tax_dict = get_tax_data(doc)
168
169 if not tax_dict:
170 # Remove existing tax rows if address is changed from a taxable state/country
171 setattr(doc, "taxes", [tax for tax in doc.taxes if tax.account_head != TAX_ACCOUNT_HEAD])
172 return
173
Subin Tomb01fe1c2021-09-14 20:42:47 +0530174 # check if delivering within a nexus
175 nexus_list = frappe.get_doc('TaxJar Settings').get("nexus")
176 if tax_dict["to_state"] not in [nex.region_code for nex in nexus_list]:
177 return
178
vishdhad3ec1c12020-03-24 11:31:41 +0530179 tax_data = validate_tax_request(tax_dict)
vishdhad3ec1c12020-03-24 11:31:41 +0530180 if tax_data is not None:
181 if not tax_data.amount_to_collect:
182 setattr(doc, "taxes", [tax for tax in doc.taxes if tax.account_head != TAX_ACCOUNT_HEAD])
183 elif tax_data.amount_to_collect > 0:
184 # Loop through tax rows for existing Sales Tax entry
185 # If none are found, add a row with the tax amount
186 for tax in doc.taxes:
187 if tax.account_head == TAX_ACCOUNT_HEAD:
188 tax.tax_amount = tax_data.amount_to_collect
189
190 doc.run_method("calculate_taxes_and_totals")
191 break
192 else:
193 doc.append("taxes", {
194 "charge_type": "Actual",
195 "description": "Sales Tax",
196 "account_head": TAX_ACCOUNT_HEAD,
197 "tax_amount": tax_data.amount_to_collect
198 })
Subin Tom70049442021-08-31 18:33:16 +0530199 # Assigning values to tax_collectable and taxable_amount fields in sales item table
200 for item in tax_data.breakdown.line_items:
201 doc.get('items')[cint(item.id)-1].tax_collectable = item.tax_collectable
202 doc.get('items')[cint(item.id)-1].taxable_amount = item.taxable_amount
vishdhad3ec1c12020-03-24 11:31:41 +0530203
204 doc.run_method("calculate_taxes_and_totals")
205
Subin Tom70049442021-08-31 18:33:16 +0530206def check_sales_tax_exemption(doc):
207 # if the party is exempt from sales tax, then set all tax account heads to zero
208 sales_tax_exempted = hasattr(doc, "exempt_from_sales_tax") and doc.exempt_from_sales_tax \
209 or frappe.db.has_column("Customer", "exempt_from_sales_tax") \
210 and frappe.db.get_value("Customer", doc.customer, "exempt_from_sales_tax")
211
212 if sales_tax_exempted:
213 for tax in doc.taxes:
214 if tax.account_head == TAX_ACCOUNT_HEAD:
215 tax.tax_amount = 0
216 break
217 doc.run_method("calculate_taxes_and_totals")
218 return True
Ankush Menatb147b852021-09-01 16:45:57 +0530219 else:
Subin Tom70049442021-08-31 18:33:16 +0530220 return False
vishdhad3ec1c12020-03-24 11:31:41 +0530221
222def validate_tax_request(tax_dict):
223 """Return the sales tax that should be collected for a given order."""
224
225 client = get_client()
226
227 if not client:
228 return
229
230 try:
231 tax_data = client.tax_for_order(tax_dict)
232 except taxjar.exceptions.TaxJarResponseError as err:
233 frappe.throw(_(sanitize_error_response(err)))
234 else:
235 return tax_data
236
237
238def get_company_address_details(doc):
239 """Return default company address details"""
240
241 company_address = get_company_address(get_default_company()).company_address
242
243 if not company_address:
244 frappe.throw(_("Please set a default company address"))
245
246 company_address = frappe.get_doc("Address", company_address)
247 return company_address
248
249
250def get_shipping_address_details(doc):
251 """Return customer shipping address details"""
252
253 if doc.shipping_address_name:
254 shipping_address = frappe.get_doc("Address", doc.shipping_address_name)
Subin Tom70049442021-08-31 18:33:16 +0530255 elif doc.customer_address:
256 shipping_address = frappe.get_doc("Address", doc.customer_address_name)
vishdhad3ec1c12020-03-24 11:31:41 +0530257 else:
258 shipping_address = get_company_address_details(doc)
259
260 return shipping_address
261
262
263def get_iso_3166_2_state_code(address):
Deepesh Gargdcb462f2020-08-01 13:47:09 +0530264 import pycountry
vishdhad3ec1c12020-03-24 11:31:41 +0530265 country_code = frappe.db.get_value("Country", address.get("country"), "code")
266
267 error_message = _("""{0} is not a valid state! Check for typos or enter the ISO code for your state.""").format(address.get("state"))
268 state = address.get("state").upper().strip()
269
270 # The max length for ISO state codes is 3, excluding the country code
271 if len(state) <= 3:
272 # PyCountry returns state code as {country_code}-{state-code} (e.g. US-FL)
273 address_state = (country_code + "-" + state).upper()
274
275 states = pycountry.subdivisions.get(country_code=country_code.upper())
276 states = [pystate.code for pystate in states]
277
278 if address_state in states:
279 return state
280
281 frappe.throw(_(error_message))
282 else:
283 try:
284 lookup_state = pycountry.subdivisions.lookup(state)
285 except LookupError:
286 frappe.throw(_(error_message))
287 else:
288 return lookup_state.code.split('-')[1]
289
290
291def sanitize_error_response(response):
292 response = response.full_response.get("detail")
293 response = response.replace("_", " ")
294
295 sanitized_responses = {
296 "to zip": "Zipcode",
297 "to city": "City",
298 "to state": "State",
299 "to country": "Country"
300 }
301
302 for k, v in sanitized_responses.items():
303 response = response.replace(k, v)
304
305 return response