vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 1 | import traceback |
Chillar Anand | 915b343 | 2021-09-02 16:44:59 +0530 | [diff] [blame] | 2 | |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 3 | import frappe |
Subin Tom | 7004944 | 2021-08-31 18:33:16 +0530 | [diff] [blame] | 4 | import taxjar |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 5 | from frappe import _ |
| 6 | from frappe.contacts.doctype.address.address import get_company_address |
Subin Tom | 5c18654 | 2021-09-17 00:10:41 +0530 | [diff] [blame] | 7 | from frappe.utils import cint, flt |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 8 | |
Subin Tom | d2915c6 | 2021-11-08 17:59:03 +0530 | [diff] [blame] | 9 | from erpnext import get_default_company, get_region |
Chillar Anand | 915b343 | 2021-09-02 16:44:59 +0530 | [diff] [blame] | 10 | |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 11 | TAX_ACCOUNT_HEAD = frappe.db.get_single_value("TaxJar Settings", "tax_account_head") |
| 12 | SHIP_ACCOUNT_HEAD = frappe.db.get_single_value("TaxJar Settings", "shipping_account_head") |
| 13 | TAXJAR_CREATE_TRANSACTIONS = frappe.db.get_single_value("TaxJar Settings", "taxjar_create_transactions") |
| 14 | TAXJAR_CALCULATE_TAX = frappe.db.get_single_value("TaxJar Settings", "taxjar_calculate_tax") |
| 15 | SUPPORTED_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 Tom | 7004944 | 2021-08-31 18:33:16 +0530 | [diff] [blame] | 18 | SUPPORTED_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 Menat | b147b85 | 2021-09-01 16:45:57 +0530 | [diff] [blame] | 20 | 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', |
Subin Tom | 7004944 | 2021-08-31 18:33:16 +0530 | [diff] [blame] | 21 | 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY'] |
Subin Tom | e51c4ba | 2021-11-08 15:16:20 +0530 | [diff] [blame] | 22 | |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 23 | |
| 24 | |
| 25 | def 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 Tom | 7004944 | 2021-08-31 18:33:16 +0530 | [diff] [blame] | 36 | 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 |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 41 | |
| 42 | |
| 43 | def 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 Tom | 7004944 | 2021-08-31 18:33:16 +0530 | [diff] [blame] | 70 | if doc.is_return: |
| 71 | client.create_refund(tax_dict) |
Ankush Menat | b147b85 | 2021-09-01 16:45:57 +0530 | [diff] [blame] | 72 | else: |
Subin Tom | 7004944 | 2021-08-31 18:33:16 +0530 | [diff] [blame] | 73 | client.create_order(tax_dict) |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 74 | 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 | |
| 80 | def 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 | |
| 94 | def 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 | |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 105 | shipping = sum([tax.tax_amount for tax in doc.taxes if tax.account_head == SHIP_ACCOUNT_HEAD]) |
| 106 | |
Subin Tom | 0e52731 | 2021-09-16 14:41:38 +0530 | [diff] [blame] | 107 | line_items = [get_line_item_dict(item, doc.docstatus) for item in doc.items] |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 108 | |
Subin Tom | 7004944 | 2021-08-31 18:33:16 +0530 | [diff] [blame] | 109 | 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 Menat | b147b85 | 2021-09-01 16:45:57 +0530 | [diff] [blame] | 114 | |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 115 | 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 Tom | 7004944 | 2021-08-31 18:33:16 +0530 | [diff] [blame] | 127 | 'amount': doc.net_total, |
| 128 | 'plugin': 'erpnext', |
| 129 | 'line_items': line_items |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 130 | } |
Ankush Menat | b147b85 | 2021-09-01 16:45:57 +0530 | [diff] [blame] | 131 | return tax_dict |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 132 | |
Subin Tom | 7004944 | 2021-08-31 18:33:16 +0530 | [diff] [blame] | 133 | def 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 Menat | b147b85 | 2021-09-01 16:45:57 +0530 | [diff] [blame] | 140 | |
Subin Tom | 7004944 | 2021-08-31 18:33:16 +0530 | [diff] [blame] | 141 | return state_code |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 142 | |
Subin Tom | 3bb60a4 | 2021-09-14 22:04:57 +0530 | [diff] [blame] | 143 | def get_line_item_dict(item, docstatus): |
| 144 | tax_dict = dict( |
Subin Tom | 7004944 | 2021-08-31 18:33:16 +0530 | [diff] [blame] | 145 | 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 Menat | b147b85 | 2021-09-01 16:45:57 +0530 | [diff] [blame] | 149 | ) |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 150 | |
Subin Tom | 3bb60a4 | 2021-09-14 22:04:57 +0530 | [diff] [blame] | 151 | if docstatus == 1: |
| 152 | tax_dict.update({ |
| 153 | 'sales_tax':item.get('tax_collectable') |
| 154 | }) |
| 155 | |
| 156 | return tax_dict |
| 157 | |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 158 | def set_sales_tax(doc, method): |
| 159 | if not TAXJAR_CALCULATE_TAX: |
| 160 | return |
| 161 | |
Subin Tom | 45fd819 | 2021-11-08 18:03:44 +0530 | [diff] [blame] | 162 | if get_region(doc.company) != 'United States': |
Subin Tom | e51c4ba | 2021-11-08 15:16:20 +0530 | [diff] [blame] | 163 | return |
| 164 | |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 165 | if not doc.items: |
| 166 | return |
| 167 | |
Subin Tom | 7004944 | 2021-08-31 18:33:16 +0530 | [diff] [blame] | 168 | if check_sales_tax_exemption(doc): |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 169 | 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 Tom | b01fe1c | 2021-09-14 20:42:47 +0530 | [diff] [blame] | 178 | # check if delivering within a nexus |
Subin Tom | 5c18654 | 2021-09-17 00:10:41 +0530 | [diff] [blame] | 179 | check_for_nexus(doc, tax_dict) |
Subin Tom | b01fe1c | 2021-09-14 20:42:47 +0530 | [diff] [blame] | 180 | |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 181 | tax_data = validate_tax_request(tax_dict) |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 182 | 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 Tom | 7004944 | 2021-08-31 18:33:16 +0530 | [diff] [blame] | 201 | # 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 |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 205 | |
| 206 | doc.run_method("calculate_taxes_and_totals") |
| 207 | |
Subin Tom | 5c18654 | 2021-09-17 00:10:41 +0530 | [diff] [blame] | 208 | def 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 Tom | 7004944 | 2021-08-31 18:33:16 +0530 | [diff] [blame] | 219 | def 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 Menat | b147b85 | 2021-09-01 16:45:57 +0530 | [diff] [blame] | 232 | else: |
Subin Tom | 7004944 | 2021-08-31 18:33:16 +0530 | [diff] [blame] | 233 | return False |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 234 | |
| 235 | def 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 | |
| 251 | def 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 | |
| 263 | def 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 Tom | 7004944 | 2021-08-31 18:33:16 +0530 | [diff] [blame] | 268 | elif doc.customer_address: |
Subin Tom | 75e9100 | 2021-11-08 09:49:11 +0530 | [diff] [blame] | 269 | shipping_address = frappe.get_doc("Address", doc.customer_address) |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 270 | else: |
| 271 | shipping_address = get_company_address_details(doc) |
| 272 | |
| 273 | return shipping_address |
| 274 | |
| 275 | |
| 276 | def get_iso_3166_2_state_code(address): |
Deepesh Garg | dcb462f | 2020-08-01 13:47:09 +0530 | [diff] [blame] | 277 | import pycountry |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 278 | 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 | |
| 304 | def 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 |