blob: a4e21579e32923fd43247b7bc27ac25c3606e8ca [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 Tom5c186542021-09-17 00:10:41 +05307from frappe.utils import cint, flt
vishdhad3ec1c12020-03-24 11:31:41 +05308
Subin Tomd2915c62021-11-08 17:59:03 +05309from erpnext import get_default_company, get_region
Chillar Anand915b3432021-09-02 16:44:59 +053010
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']
Subin Tome51c4ba2021-11-08 15:16:20 +053022
vishdhad3ec1c12020-03-24 11:31:41 +053023
24
25def get_client():
26 taxjar_settings = frappe.get_single("TaxJar Settings")
27
28 if not taxjar_settings.is_sandbox:
29 api_key = taxjar_settings.api_key and taxjar_settings.get_password("api_key")
30 api_url = taxjar.DEFAULT_API_URL
31 else:
32 api_key = taxjar_settings.sandbox_api_key and taxjar_settings.get_password("sandbox_api_key")
33 api_url = taxjar.SANDBOX_API_URL
34
35 if api_key and api_url:
Subin Tom70049442021-08-31 18:33:16 +053036 client = taxjar.Client(api_key=api_key, api_url=api_url)
37 client.set_api_config('headers', {
38 'x-api-version': '2020-08-07'
39 })
40 return client
vishdhad3ec1c12020-03-24 11:31:41 +053041
42
43def create_transaction(doc, method):
44 """Create an order transaction in TaxJar"""
45
46 if not TAXJAR_CREATE_TRANSACTIONS:
47 return
48
49 client = get_client()
50
51 if not client:
52 return
53
54 sales_tax = sum([tax.tax_amount for tax in doc.taxes if tax.account_head == TAX_ACCOUNT_HEAD])
55
56 if not sales_tax:
57 return
58
59 tax_dict = get_tax_data(doc)
60
61 if not tax_dict:
62 return
63
64 tax_dict['transaction_id'] = doc.name
65 tax_dict['transaction_date'] = frappe.utils.today()
66 tax_dict['sales_tax'] = sales_tax
67 tax_dict['amount'] = doc.total + tax_dict['shipping']
68
69 try:
Subin Tom70049442021-08-31 18:33:16 +053070 if doc.is_return:
71 client.create_refund(tax_dict)
Ankush Menatb147b852021-09-01 16:45:57 +053072 else:
Subin Tom70049442021-08-31 18:33:16 +053073 client.create_order(tax_dict)
vishdhad3ec1c12020-03-24 11:31:41 +053074 except taxjar.exceptions.TaxJarResponseError as err:
75 frappe.throw(_(sanitize_error_response(err)))
76 except Exception as ex:
77 print(traceback.format_exc(ex))
78
79
80def delete_transaction(doc, method):
81 """Delete an existing TaxJar order transaction"""
82
83 if not TAXJAR_CREATE_TRANSACTIONS:
84 return
85
86 client = get_client()
87
88 if not client:
89 return
90
91 client.delete_order(doc.name)
92
93
94def get_tax_data(doc):
95 from_address = get_company_address_details(doc)
96 from_shipping_state = from_address.get("state")
97 from_country_code = frappe.db.get_value("Country", from_address.country, "code")
98 from_country_code = from_country_code.upper()
99
100 to_address = get_shipping_address_details(doc)
101 to_shipping_state = to_address.get("state")
102 to_country_code = frappe.db.get_value("Country", to_address.country, "code")
103 to_country_code = to_country_code.upper()
104
vishdhad3ec1c12020-03-24 11:31:41 +0530105 shipping = sum([tax.tax_amount for tax in doc.taxes if tax.account_head == SHIP_ACCOUNT_HEAD])
106
Subin Tom0e527312021-09-16 14:41:38 +0530107 line_items = [get_line_item_dict(item, doc.docstatus) for item in doc.items]
vishdhad3ec1c12020-03-24 11:31:41 +0530108
Subin Tom70049442021-08-31 18:33:16 +0530109 if from_shipping_state not in SUPPORTED_STATE_CODES:
110 from_shipping_state = get_state_code(from_address, 'Company')
111
112 if to_shipping_state not in SUPPORTED_STATE_CODES:
113 to_shipping_state = get_state_code(to_address, 'Shipping')
Ankush Menatb147b852021-09-01 16:45:57 +0530114
vishdhad3ec1c12020-03-24 11:31:41 +0530115 tax_dict = {
116 'from_country': from_country_code,
117 'from_zip': from_address.pincode,
118 'from_state': from_shipping_state,
119 'from_city': from_address.city,
120 'from_street': from_address.address_line1,
121 'to_country': to_country_code,
122 'to_zip': to_address.pincode,
123 'to_city': to_address.city,
124 'to_street': to_address.address_line1,
125 'to_state': to_shipping_state,
126 'shipping': shipping,
Subin Tom70049442021-08-31 18:33:16 +0530127 'amount': doc.net_total,
128 'plugin': 'erpnext',
129 'line_items': line_items
vishdhad3ec1c12020-03-24 11:31:41 +0530130 }
Ankush Menatb147b852021-09-01 16:45:57 +0530131 return tax_dict
vishdhad3ec1c12020-03-24 11:31:41 +0530132
Subin Tom70049442021-08-31 18:33:16 +0530133def get_state_code(address, location):
134 if address is not None:
135 state_code = get_iso_3166_2_state_code(address)
136 if state_code not in SUPPORTED_STATE_CODES:
137 frappe.throw(_("Please enter a valid State in the {0} Address").format(location))
138 else:
139 frappe.throw(_("Please enter a valid State in the {0} Address").format(location))
Ankush Menatb147b852021-09-01 16:45:57 +0530140
Subin Tom70049442021-08-31 18:33:16 +0530141 return state_code
vishdhad3ec1c12020-03-24 11:31:41 +0530142
Subin Tom3bb60a42021-09-14 22:04:57 +0530143def get_line_item_dict(item, docstatus):
144 tax_dict = dict(
Subin Tom70049442021-08-31 18:33:16 +0530145 id = item.get('idx'),
146 quantity = item.get('qty'),
147 unit_price = item.get('rate'),
148 product_tax_code = item.get('product_tax_category')
Ankush Menatb147b852021-09-01 16:45:57 +0530149 )
vishdhad3ec1c12020-03-24 11:31:41 +0530150
Subin Tom3bb60a42021-09-14 22:04:57 +0530151 if docstatus == 1:
152 tax_dict.update({
153 'sales_tax':item.get('tax_collectable')
154 })
155
156 return tax_dict
157
vishdhad3ec1c12020-03-24 11:31:41 +0530158def set_sales_tax(doc, method):
159 if not TAXJAR_CALCULATE_TAX:
160 return
161
Subin Tom45fd8192021-11-08 18:03:44 +0530162 if get_region(doc.company) != 'United States':
Subin Tome51c4ba2021-11-08 15:16:20 +0530163 return
164
vishdhad3ec1c12020-03-24 11:31:41 +0530165 if not doc.items:
166 return
167
Subin Tom70049442021-08-31 18:33:16 +0530168 if check_sales_tax_exemption(doc):
vishdhad3ec1c12020-03-24 11:31:41 +0530169 return
170
171 tax_dict = get_tax_data(doc)
172
173 if not tax_dict:
174 # Remove existing tax rows if address is changed from a taxable state/country
175 setattr(doc, "taxes", [tax for tax in doc.taxes if tax.account_head != TAX_ACCOUNT_HEAD])
176 return
177
Subin Tomb01fe1c2021-09-14 20:42:47 +0530178 # check if delivering within a nexus
Subin Tom5c186542021-09-17 00:10:41 +0530179 check_for_nexus(doc, tax_dict)
Subin Tomb01fe1c2021-09-14 20:42:47 +0530180
vishdhad3ec1c12020-03-24 11:31:41 +0530181 tax_data = validate_tax_request(tax_dict)
vishdhad3ec1c12020-03-24 11:31:41 +0530182 if tax_data is not None:
183 if not tax_data.amount_to_collect:
184 setattr(doc, "taxes", [tax for tax in doc.taxes if tax.account_head != TAX_ACCOUNT_HEAD])
185 elif tax_data.amount_to_collect > 0:
186 # Loop through tax rows for existing Sales Tax entry
187 # If none are found, add a row with the tax amount
188 for tax in doc.taxes:
189 if tax.account_head == TAX_ACCOUNT_HEAD:
190 tax.tax_amount = tax_data.amount_to_collect
191
192 doc.run_method("calculate_taxes_and_totals")
193 break
194 else:
195 doc.append("taxes", {
196 "charge_type": "Actual",
197 "description": "Sales Tax",
198 "account_head": TAX_ACCOUNT_HEAD,
199 "tax_amount": tax_data.amount_to_collect
200 })
Subin Tom70049442021-08-31 18:33:16 +0530201 # Assigning values to tax_collectable and taxable_amount fields in sales item table
202 for item in tax_data.breakdown.line_items:
203 doc.get('items')[cint(item.id)-1].tax_collectable = item.tax_collectable
204 doc.get('items')[cint(item.id)-1].taxable_amount = item.taxable_amount
vishdhad3ec1c12020-03-24 11:31:41 +0530205
206 doc.run_method("calculate_taxes_and_totals")
207
Subin Tom5c186542021-09-17 00:10:41 +0530208def check_for_nexus(doc, tax_dict):
209 if not frappe.db.get_value('TaxJar Nexus', {'region_code': tax_dict["to_state"]}):
210 for item in doc.get("items"):
211 item.tax_collectable = flt(0)
212 item.taxable_amount = flt(0)
213
214 for tax in doc.taxes:
215 if tax.account_head == TAX_ACCOUNT_HEAD:
216 doc.taxes.remove(tax)
217 return
218
Subin Tom70049442021-08-31 18:33:16 +0530219def check_sales_tax_exemption(doc):
220 # if the party is exempt from sales tax, then set all tax account heads to zero
221 sales_tax_exempted = hasattr(doc, "exempt_from_sales_tax") and doc.exempt_from_sales_tax \
222 or frappe.db.has_column("Customer", "exempt_from_sales_tax") \
223 and frappe.db.get_value("Customer", doc.customer, "exempt_from_sales_tax")
224
225 if sales_tax_exempted:
226 for tax in doc.taxes:
227 if tax.account_head == TAX_ACCOUNT_HEAD:
228 tax.tax_amount = 0
229 break
230 doc.run_method("calculate_taxes_and_totals")
231 return True
Ankush Menatb147b852021-09-01 16:45:57 +0530232 else:
Subin Tom70049442021-08-31 18:33:16 +0530233 return False
vishdhad3ec1c12020-03-24 11:31:41 +0530234
235def validate_tax_request(tax_dict):
236 """Return the sales tax that should be collected for a given order."""
237
238 client = get_client()
239
240 if not client:
241 return
242
243 try:
244 tax_data = client.tax_for_order(tax_dict)
245 except taxjar.exceptions.TaxJarResponseError as err:
246 frappe.throw(_(sanitize_error_response(err)))
247 else:
248 return tax_data
249
250
251def get_company_address_details(doc):
252 """Return default company address details"""
253
254 company_address = get_company_address(get_default_company()).company_address
255
256 if not company_address:
257 frappe.throw(_("Please set a default company address"))
258
259 company_address = frappe.get_doc("Address", company_address)
260 return company_address
261
262
263def get_shipping_address_details(doc):
264 """Return customer shipping address details"""
265
266 if doc.shipping_address_name:
267 shipping_address = frappe.get_doc("Address", doc.shipping_address_name)
Subin Tom70049442021-08-31 18:33:16 +0530268 elif doc.customer_address:
Subin Tom75e91002021-11-08 09:49:11 +0530269 shipping_address = frappe.get_doc("Address", doc.customer_address)
vishdhad3ec1c12020-03-24 11:31:41 +0530270 else:
271 shipping_address = get_company_address_details(doc)
272
273 return shipping_address
274
275
276def get_iso_3166_2_state_code(address):
Deepesh Gargdcb462f2020-08-01 13:47:09 +0530277 import pycountry
vishdhad3ec1c12020-03-24 11:31:41 +0530278 country_code = frappe.db.get_value("Country", address.get("country"), "code")
279
280 error_message = _("""{0} is not a valid state! Check for typos or enter the ISO code for your state.""").format(address.get("state"))
281 state = address.get("state").upper().strip()
282
283 # The max length for ISO state codes is 3, excluding the country code
284 if len(state) <= 3:
285 # PyCountry returns state code as {country_code}-{state-code} (e.g. US-FL)
286 address_state = (country_code + "-" + state).upper()
287
288 states = pycountry.subdivisions.get(country_code=country_code.upper())
289 states = [pystate.code for pystate in states]
290
291 if address_state in states:
292 return state
293
294 frappe.throw(_(error_message))
295 else:
296 try:
297 lookup_state = pycountry.subdivisions.lookup(state)
298 except LookupError:
299 frappe.throw(_(error_message))
300 else:
301 return lookup_state.code.split('-')[1]
302
303
304def sanitize_error_response(response):
305 response = response.full_response.get("detail")
306 response = response.replace("_", " ")
307
308 sanitized_responses = {
309 "to zip": "Zipcode",
310 "to city": "City",
311 "to state": "State",
312 "to country": "Country"
313 }
314
315 for k, v in sanitized_responses.items():
316 response = response.replace(k, v)
317
318 return response