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 | SUPPORTED_COUNTRY_CODES = ["AT", "AU", "BE", "BG", "CA", "CY", "CZ", "DE", "DK", "EE", "ES", "FI", |
| 12 | "FR", "GB", "GR", "HR", "HU", "IE", "IT", "LT", "LU", "LV", "MT", "NL", "PL", "PT", "RO", |
| 13 | "SE", "SI", "SK", "US"] |
Subin Tom | 7004944 | 2021-08-31 18:33:16 +0530 | [diff] [blame] | 14 | SUPPORTED_STATE_CODES = ['AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'DC', 'FL', 'GA', 'HI', 'ID', 'IL', |
| 15 | '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] | 16 | '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] | 17 | 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY'] |
Subin Tom | e51c4ba | 2021-11-08 15:16:20 +0530 | [diff] [blame] | 18 | |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 19 | |
| 20 | |
| 21 | def get_client(): |
| 22 | taxjar_settings = frappe.get_single("TaxJar Settings") |
| 23 | |
| 24 | if not taxjar_settings.is_sandbox: |
| 25 | api_key = taxjar_settings.api_key and taxjar_settings.get_password("api_key") |
| 26 | api_url = taxjar.DEFAULT_API_URL |
| 27 | else: |
| 28 | api_key = taxjar_settings.sandbox_api_key and taxjar_settings.get_password("sandbox_api_key") |
| 29 | api_url = taxjar.SANDBOX_API_URL |
| 30 | |
| 31 | if api_key and api_url: |
Subin Tom | 7004944 | 2021-08-31 18:33:16 +0530 | [diff] [blame] | 32 | client = taxjar.Client(api_key=api_key, api_url=api_url) |
| 33 | client.set_api_config('headers', { |
Subin Tom | 1682a26 | 2022-02-22 17:20:48 +0530 | [diff] [blame] | 34 | 'x-api-version': '2022-01-24' |
Subin Tom | 7004944 | 2021-08-31 18:33:16 +0530 | [diff] [blame] | 35 | }) |
| 36 | return client |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 37 | |
| 38 | |
| 39 | def create_transaction(doc, method): |
Subin Tom | 1682a26 | 2022-02-22 17:20:48 +0530 | [diff] [blame] | 40 | TAXJAR_CREATE_TRANSACTIONS = frappe.db.get_single_value("TaxJar Settings", "taxjar_create_transactions") |
| 41 | |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 42 | """Create an order transaction in TaxJar""" |
| 43 | |
| 44 | if not TAXJAR_CREATE_TRANSACTIONS: |
| 45 | return |
| 46 | |
| 47 | client = get_client() |
| 48 | |
| 49 | if not client: |
| 50 | return |
| 51 | |
Subin Tom | 1682a26 | 2022-02-22 17:20:48 +0530 | [diff] [blame] | 52 | TAX_ACCOUNT_HEAD = frappe.db.get_single_value("TaxJar Settings", "tax_account_head") |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 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 Tom | 7004944 | 2021-08-31 18:33:16 +0530 | [diff] [blame] | 69 | if doc.is_return: |
| 70 | client.create_refund(tax_dict) |
Ankush Menat | b147b85 | 2021-09-01 16:45:57 +0530 | [diff] [blame] | 71 | else: |
Subin Tom | 7004944 | 2021-08-31 18:33:16 +0530 | [diff] [blame] | 72 | client.create_order(tax_dict) |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 73 | 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 | |
| 79 | def delete_transaction(doc, method): |
| 80 | """Delete an existing TaxJar order transaction""" |
Subin Tom | 1682a26 | 2022-02-22 17:20:48 +0530 | [diff] [blame] | 81 | TAXJAR_CREATE_TRANSACTIONS = frappe.db.get_single_value("TaxJar Settings", "taxjar_create_transactions") |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 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): |
Subin Tom | 1682a26 | 2022-02-22 17:20:48 +0530 | [diff] [blame] | 95 | SHIP_ACCOUNT_HEAD = frappe.db.get_single_value("TaxJar Settings", "shipping_account_head") |
| 96 | |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 97 | from_address = get_company_address_details(doc) |
| 98 | from_shipping_state = from_address.get("state") |
| 99 | from_country_code = frappe.db.get_value("Country", from_address.country, "code") |
| 100 | from_country_code = from_country_code.upper() |
| 101 | |
| 102 | to_address = get_shipping_address_details(doc) |
| 103 | to_shipping_state = to_address.get("state") |
| 104 | to_country_code = frappe.db.get_value("Country", to_address.country, "code") |
| 105 | to_country_code = to_country_code.upper() |
| 106 | |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 107 | shipping = sum([tax.tax_amount for tax in doc.taxes if tax.account_head == SHIP_ACCOUNT_HEAD]) |
| 108 | |
Subin Tom | 0e52731 | 2021-09-16 14:41:38 +0530 | [diff] [blame] | 109 | 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] | 110 | |
Subin Tom | 7004944 | 2021-08-31 18:33:16 +0530 | [diff] [blame] | 111 | if from_shipping_state not in SUPPORTED_STATE_CODES: |
| 112 | from_shipping_state = get_state_code(from_address, 'Company') |
| 113 | |
| 114 | if to_shipping_state not in SUPPORTED_STATE_CODES: |
| 115 | to_shipping_state = get_state_code(to_address, 'Shipping') |
Ankush Menat | b147b85 | 2021-09-01 16:45:57 +0530 | [diff] [blame] | 116 | |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 117 | tax_dict = { |
Subin Tom | 1682a26 | 2022-02-22 17:20:48 +0530 | [diff] [blame] | 118 | "from_country": from_country_code, |
| 119 | "from_zip": from_address.pincode, |
| 120 | "from_state": from_shipping_state, |
| 121 | "from_city": from_address.city, |
| 122 | "from_street": from_address.address_line1, |
| 123 | "to_country": to_country_code, |
| 124 | "to_zip": to_address.pincode, |
| 125 | "to_city": to_address.city, |
| 126 | "to_street": to_address.address_line1, |
| 127 | "to_state": to_shipping_state, |
| 128 | "shipping": shipping, |
| 129 | "amount": doc.net_total, |
| 130 | "plugin": "erpnext", |
| 131 | "line_items": line_items |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 132 | } |
Ankush Menat | b147b85 | 2021-09-01 16:45:57 +0530 | [diff] [blame] | 133 | return tax_dict |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 134 | |
Subin Tom | 7004944 | 2021-08-31 18:33:16 +0530 | [diff] [blame] | 135 | def get_state_code(address, location): |
| 136 | if address is not None: |
| 137 | state_code = get_iso_3166_2_state_code(address) |
| 138 | if state_code not in SUPPORTED_STATE_CODES: |
| 139 | frappe.throw(_("Please enter a valid State in the {0} Address").format(location)) |
| 140 | else: |
| 141 | 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] | 142 | |
Subin Tom | 7004944 | 2021-08-31 18:33:16 +0530 | [diff] [blame] | 143 | return state_code |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 144 | |
Subin Tom | 3bb60a4 | 2021-09-14 22:04:57 +0530 | [diff] [blame] | 145 | def get_line_item_dict(item, docstatus): |
| 146 | tax_dict = dict( |
Subin Tom | 7004944 | 2021-08-31 18:33:16 +0530 | [diff] [blame] | 147 | id = item.get('idx'), |
| 148 | quantity = item.get('qty'), |
| 149 | unit_price = item.get('rate'), |
| 150 | product_tax_code = item.get('product_tax_category') |
Ankush Menat | b147b85 | 2021-09-01 16:45:57 +0530 | [diff] [blame] | 151 | ) |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 152 | |
Subin Tom | 3bb60a4 | 2021-09-14 22:04:57 +0530 | [diff] [blame] | 153 | if docstatus == 1: |
| 154 | tax_dict.update({ |
| 155 | 'sales_tax':item.get('tax_collectable') |
| 156 | }) |
| 157 | |
| 158 | return tax_dict |
| 159 | |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 160 | def set_sales_tax(doc, method): |
Subin Tom | 1682a26 | 2022-02-22 17:20:48 +0530 | [diff] [blame] | 161 | TAX_ACCOUNT_HEAD = frappe.db.get_single_value("TaxJar Settings", "tax_account_head") |
| 162 | TAXJAR_CALCULATE_TAX = frappe.db.get_single_value("TaxJar Settings", "taxjar_calculate_tax") |
| 163 | |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 164 | if not TAXJAR_CALCULATE_TAX: |
| 165 | return |
| 166 | |
Subin Tom | 45fd819 | 2021-11-08 18:03:44 +0530 | [diff] [blame] | 167 | if get_region(doc.company) != 'United States': |
Subin Tom | e51c4ba | 2021-11-08 15:16:20 +0530 | [diff] [blame] | 168 | return |
| 169 | |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 170 | if not doc.items: |
| 171 | return |
| 172 | |
Subin Tom | 7004944 | 2021-08-31 18:33:16 +0530 | [diff] [blame] | 173 | if check_sales_tax_exemption(doc): |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 174 | return |
| 175 | |
| 176 | tax_dict = get_tax_data(doc) |
| 177 | |
| 178 | if not tax_dict: |
| 179 | # Remove existing tax rows if address is changed from a taxable state/country |
| 180 | setattr(doc, "taxes", [tax for tax in doc.taxes if tax.account_head != TAX_ACCOUNT_HEAD]) |
| 181 | return |
| 182 | |
Subin Tom | b01fe1c | 2021-09-14 20:42:47 +0530 | [diff] [blame] | 183 | # check if delivering within a nexus |
Subin Tom | 5c18654 | 2021-09-17 00:10:41 +0530 | [diff] [blame] | 184 | check_for_nexus(doc, tax_dict) |
Subin Tom | b01fe1c | 2021-09-14 20:42:47 +0530 | [diff] [blame] | 185 | |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 186 | tax_data = validate_tax_request(tax_dict) |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 187 | if tax_data is not None: |
| 188 | if not tax_data.amount_to_collect: |
| 189 | setattr(doc, "taxes", [tax for tax in doc.taxes if tax.account_head != TAX_ACCOUNT_HEAD]) |
| 190 | elif tax_data.amount_to_collect > 0: |
| 191 | # Loop through tax rows for existing Sales Tax entry |
| 192 | # If none are found, add a row with the tax amount |
| 193 | for tax in doc.taxes: |
| 194 | if tax.account_head == TAX_ACCOUNT_HEAD: |
| 195 | tax.tax_amount = tax_data.amount_to_collect |
| 196 | |
| 197 | doc.run_method("calculate_taxes_and_totals") |
| 198 | break |
| 199 | else: |
| 200 | doc.append("taxes", { |
| 201 | "charge_type": "Actual", |
| 202 | "description": "Sales Tax", |
| 203 | "account_head": TAX_ACCOUNT_HEAD, |
| 204 | "tax_amount": tax_data.amount_to_collect |
| 205 | }) |
Subin Tom | 7004944 | 2021-08-31 18:33:16 +0530 | [diff] [blame] | 206 | # Assigning values to tax_collectable and taxable_amount fields in sales item table |
| 207 | for item in tax_data.breakdown.line_items: |
| 208 | doc.get('items')[cint(item.id)-1].tax_collectable = item.tax_collectable |
| 209 | doc.get('items')[cint(item.id)-1].taxable_amount = item.taxable_amount |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 210 | |
| 211 | doc.run_method("calculate_taxes_and_totals") |
| 212 | |
Subin Tom | 5c18654 | 2021-09-17 00:10:41 +0530 | [diff] [blame] | 213 | def check_for_nexus(doc, tax_dict): |
Subin Tom | 1682a26 | 2022-02-22 17:20:48 +0530 | [diff] [blame] | 214 | TAX_ACCOUNT_HEAD = frappe.db.get_single_value("TaxJar Settings", "tax_account_head") |
Subin Tom | 5c18654 | 2021-09-17 00:10:41 +0530 | [diff] [blame] | 215 | if not frappe.db.get_value('TaxJar Nexus', {'region_code': tax_dict["to_state"]}): |
| 216 | for item in doc.get("items"): |
| 217 | item.tax_collectable = flt(0) |
| 218 | item.taxable_amount = flt(0) |
| 219 | |
| 220 | for tax in doc.taxes: |
| 221 | if tax.account_head == TAX_ACCOUNT_HEAD: |
| 222 | doc.taxes.remove(tax) |
| 223 | return |
| 224 | |
Subin Tom | 7004944 | 2021-08-31 18:33:16 +0530 | [diff] [blame] | 225 | def check_sales_tax_exemption(doc): |
| 226 | # if the party is exempt from sales tax, then set all tax account heads to zero |
Subin Tom | 1682a26 | 2022-02-22 17:20:48 +0530 | [diff] [blame] | 227 | TAX_ACCOUNT_HEAD = frappe.db.get_single_value("TaxJar Settings", "tax_account_head") |
| 228 | |
Subin Tom | 7004944 | 2021-08-31 18:33:16 +0530 | [diff] [blame] | 229 | sales_tax_exempted = hasattr(doc, "exempt_from_sales_tax") and doc.exempt_from_sales_tax \ |
| 230 | or frappe.db.has_column("Customer", "exempt_from_sales_tax") \ |
| 231 | and frappe.db.get_value("Customer", doc.customer, "exempt_from_sales_tax") |
| 232 | |
| 233 | if sales_tax_exempted: |
| 234 | for tax in doc.taxes: |
| 235 | if tax.account_head == TAX_ACCOUNT_HEAD: |
| 236 | tax.tax_amount = 0 |
| 237 | break |
| 238 | doc.run_method("calculate_taxes_and_totals") |
| 239 | return True |
Ankush Menat | b147b85 | 2021-09-01 16:45:57 +0530 | [diff] [blame] | 240 | else: |
Subin Tom | 7004944 | 2021-08-31 18:33:16 +0530 | [diff] [blame] | 241 | return False |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 242 | |
| 243 | def validate_tax_request(tax_dict): |
| 244 | """Return the sales tax that should be collected for a given order.""" |
| 245 | |
| 246 | client = get_client() |
| 247 | |
| 248 | if not client: |
| 249 | return |
| 250 | |
| 251 | try: |
| 252 | tax_data = client.tax_for_order(tax_dict) |
| 253 | except taxjar.exceptions.TaxJarResponseError as err: |
| 254 | frappe.throw(_(sanitize_error_response(err))) |
| 255 | else: |
| 256 | return tax_data |
| 257 | |
| 258 | |
| 259 | def get_company_address_details(doc): |
| 260 | """Return default company address details""" |
| 261 | |
| 262 | company_address = get_company_address(get_default_company()).company_address |
| 263 | |
| 264 | if not company_address: |
| 265 | frappe.throw(_("Please set a default company address")) |
| 266 | |
| 267 | company_address = frappe.get_doc("Address", company_address) |
| 268 | return company_address |
| 269 | |
| 270 | |
| 271 | def get_shipping_address_details(doc): |
| 272 | """Return customer shipping address details""" |
| 273 | |
| 274 | if doc.shipping_address_name: |
| 275 | shipping_address = frappe.get_doc("Address", doc.shipping_address_name) |
Subin Tom | 7004944 | 2021-08-31 18:33:16 +0530 | [diff] [blame] | 276 | elif doc.customer_address: |
Subin Tom | 75e9100 | 2021-11-08 09:49:11 +0530 | [diff] [blame] | 277 | shipping_address = frappe.get_doc("Address", doc.customer_address) |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 278 | else: |
| 279 | shipping_address = get_company_address_details(doc) |
| 280 | |
| 281 | return shipping_address |
| 282 | |
| 283 | |
| 284 | def get_iso_3166_2_state_code(address): |
Deepesh Garg | dcb462f | 2020-08-01 13:47:09 +0530 | [diff] [blame] | 285 | import pycountry |
vishdha | d3ec1c1 | 2020-03-24 11:31:41 +0530 | [diff] [blame] | 286 | country_code = frappe.db.get_value("Country", address.get("country"), "code") |
| 287 | |
| 288 | error_message = _("""{0} is not a valid state! Check for typos or enter the ISO code for your state.""").format(address.get("state")) |
| 289 | state = address.get("state").upper().strip() |
| 290 | |
| 291 | # The max length for ISO state codes is 3, excluding the country code |
| 292 | if len(state) <= 3: |
| 293 | # PyCountry returns state code as {country_code}-{state-code} (e.g. US-FL) |
| 294 | address_state = (country_code + "-" + state).upper() |
| 295 | |
| 296 | states = pycountry.subdivisions.get(country_code=country_code.upper()) |
| 297 | states = [pystate.code for pystate in states] |
| 298 | |
| 299 | if address_state in states: |
| 300 | return state |
| 301 | |
| 302 | frappe.throw(_(error_message)) |
| 303 | else: |
| 304 | try: |
| 305 | lookup_state = pycountry.subdivisions.lookup(state) |
| 306 | except LookupError: |
| 307 | frappe.throw(_(error_message)) |
| 308 | else: |
| 309 | return lookup_state.code.split('-')[1] |
| 310 | |
| 311 | |
| 312 | def sanitize_error_response(response): |
| 313 | response = response.full_response.get("detail") |
| 314 | response = response.replace("_", " ") |
| 315 | |
| 316 | sanitized_responses = { |
| 317 | "to zip": "Zipcode", |
| 318 | "to city": "City", |
| 319 | "to state": "State", |
| 320 | "to country": "Country" |
| 321 | } |
| 322 | |
| 323 | for k, v in sanitized_responses.items(): |
| 324 | response = response.replace(k, v) |
| 325 | |
| 326 | return response |