blob: 08573cddcda4fb856f56dbc07dbd718d95d91bab [file] [log] [blame]
Gaurav2670ad72019-02-19 10:17:17 +05301from __future__ import unicode_literals
2
Sagar Vora368cb452021-03-31 12:43:33 +05303import io
4import json
5import frappe
Gaurav2670ad72019-02-19 10:17:17 +05306from frappe.utils import flt, cstr
Gauravf1e28e02019-02-13 16:46:24 +05307from erpnext.controllers.taxes_and_totals import get_itemised_tax
8from frappe import _
Saurabhacf83792019-02-24 08:57:16 +05309from frappe.core.doctype.file.file import remove_file
Rohit Waghchaure58f489f2019-04-01 17:50:31 +053010from six import string_types
Gauravf1e28e02019-02-13 16:46:24 +053011from frappe.desk.form.load import get_attachments
Gaurav3f046132019-02-19 16:28:22 +053012from erpnext.regional.italy import state_codes
Gauravf1e28e02019-02-13 16:46:24 +053013
14
15def update_itemised_tax_data(doc):
16 if not doc.taxes: return
17
hello@openetech.com70214022019-10-16 23:38:51 +053018 if doc.doctype == "Purchase Invoice": return
19
Gauravf1e28e02019-02-13 16:46:24 +053020 itemised_tax = get_itemised_tax(doc.taxes)
21
22 for row in doc.items:
23 tax_rate = 0.0
24 if itemised_tax.get(row.item_code):
25 tax_rate = sum([tax.get('tax_rate', 0) for d, tax in itemised_tax.get(row.item_code).items()])
26
27 row.tax_rate = flt(tax_rate, row.precision("tax_rate"))
28 row.tax_amount = flt((row.net_amount * tax_rate) / 100, row.precision("net_amount"))
29 row.total_amount = flt((row.net_amount + row.tax_amount), row.precision("total_amount"))
30
31@frappe.whitelist()
32def export_invoices(filters=None):
Sagar Vora368cb452021-03-31 12:43:33 +053033 frappe.has_permission('Sales Invoice', throw=True)
Gauravf1e28e02019-02-13 16:46:24 +053034
Sagar Vora368cb452021-03-31 12:43:33 +053035 invoices = frappe.get_all(
36 "Sales Invoice",
37 filters=get_conditions(filters),
38 fields=["name", "company_tax_id"]
39 )
Gauravf1e28e02019-02-13 16:46:24 +053040
Sagar Vora368cb452021-03-31 12:43:33 +053041 attachments = get_e_invoice_attachments(invoices)
Gauravf1e28e02019-02-13 16:46:24 +053042
Sagar Vora368cb452021-03-31 12:43:33 +053043 zip_filename = "{0}-einvoices.zip".format(
44 frappe.utils.get_datetime().strftime("%Y%m%d_%H%M%S"))
Gauravf1e28e02019-02-13 16:46:24 +053045
Sagar Vora368cb452021-03-31 12:43:33 +053046 download_zip(attachments, zip_filename)
Gauravf1e28e02019-02-13 16:46:24 +053047
48
Gauravf1e28e02019-02-13 16:46:24 +053049def prepare_invoice(invoice, progressive_number):
50 #set company information
51 company = frappe.get_doc("Company", invoice.company)
52
53 invoice.progressive_number = progressive_number
54 invoice.unamended_name = get_unamended_name(invoice)
55 invoice.company_data = company
56 company_address = frappe.get_doc("Address", invoice.company_address)
57 invoice.company_address_data = company_address
58
59 #Set invoice type
60 if invoice.is_return and invoice.return_against:
61 invoice.type_of_document = "TD04" #Credit Note (Nota di Credito)
62 invoice.return_against_unamended = get_unamended_name(frappe.get_doc("Sales Invoice", invoice.return_against))
63 else:
64 invoice.type_of_document = "TD01" #Sales Invoice (Fattura)
65
66 #set customer information
67 invoice.customer_data = frappe.get_doc("Customer", invoice.customer)
68 customer_address = frappe.get_doc("Address", invoice.customer_address)
69 invoice.customer_address_data = customer_address
70
71 if invoice.shipping_address_name:
72 invoice.shipping_address_data = frappe.get_doc("Address", invoice.shipping_address_name)
73
74 if invoice.customer_data.is_public_administration:
75 invoice.transmission_format_code = "FPA12"
76 else:
77 invoice.transmission_format_code = "FPR12"
78
Gaurav2670ad72019-02-19 10:17:17 +053079 invoice.e_invoice_items = [item for item in invoice.items]
80 tax_data = get_invoice_summary(invoice.e_invoice_items, invoice.taxes)
Gauravf1e28e02019-02-13 16:46:24 +053081 invoice.tax_data = tax_data
82
83 #Check if stamp duty (Bollo) of 2 EUR exists.
Rohit Waghchaure68a14562019-05-22 13:17:46 +053084 stamp_duty_charge_row = next((tax for tax in invoice.taxes if tax.charge_type == "Actual" and tax.tax_amount == 2.0 ), None)
Gauravf1e28e02019-02-13 16:46:24 +053085 if stamp_duty_charge_row:
86 invoice.stamp_duty = stamp_duty_charge_row.tax_amount
87
Gaurav2670ad72019-02-19 10:17:17 +053088 for item in invoice.e_invoice_items:
Nabin Hait34c551d2019-07-03 10:34:31 +053089 if item.tax_rate == 0.0 and item.tax_amount == 0.0 and tax_data.get("0.0"):
Gauravf1e28e02019-02-13 16:46:24 +053090 item.tax_exemption_reason = tax_data["0.0"]["tax_exemption_reason"]
91
Rohit Waghchaure1b7059b2019-03-12 17:44:29 +053092 customer_po_data = {}
93 for d in invoice.e_invoice_items:
94 if (d.customer_po_no and d.customer_po_date
95 and d.customer_po_no not in customer_po_data):
96 customer_po_data[d.customer_po_no] = d.customer_po_date
97
98 invoice.customer_po_data = customer_po_data
99
Gauravf1e28e02019-02-13 16:46:24 +0530100 return invoice
101
102def get_conditions(filters):
103 filters = json.loads(filters)
104
Sagar Vora368cb452021-03-31 12:43:33 +0530105 conditions = {"docstatus": 1, "company_tax_id": ("!=", "")}
Gauravf1e28e02019-02-13 16:46:24 +0530106
107 if filters.get("company"): conditions["company"] = filters["company"]
108 if filters.get("customer"): conditions["customer"] = filters["customer"]
109
110 if filters.get("from_date"): conditions["posting_date"] = (">=", filters["from_date"])
111 if filters.get("to_date"): conditions["posting_date"] = ("<=", filters["to_date"])
112
113 if filters.get("from_date") and filters.get("to_date"):
114 conditions["posting_date"] = ("between", [filters.get("from_date"), filters.get("to_date")])
115
116 return conditions
117
Sagar Vora368cb452021-03-31 12:43:33 +0530118
Gauravf1e28e02019-02-13 16:46:24 +0530119def download_zip(files, output_filename):
Sagar Vora368cb452021-03-31 12:43:33 +0530120 import zipfile
Gauravf1e28e02019-02-13 16:46:24 +0530121
Sagar Vora368cb452021-03-31 12:43:33 +0530122 zip_stream = io.BytesIO()
123 with zipfile.ZipFile(zip_stream, 'w', zipfile.ZIP_DEFLATED) as zip_file:
124 for file in files:
125 file_path = frappe.utils.get_files_path(
126 file.file_name, is_private=file.is_private)
Gauravf1e28e02019-02-13 16:46:24 +0530127
Sagar Vora368cb452021-03-31 12:43:33 +0530128 zip_file.write(file_path, arcname=file.file_name)
Gauravf1e28e02019-02-13 16:46:24 +0530129
130 frappe.local.response.filename = output_filename
Sagar Vora368cb452021-03-31 12:43:33 +0530131 frappe.local.response.filecontent = zip_stream.getvalue()
Gauravf1e28e02019-02-13 16:46:24 +0530132 frappe.local.response.type = "download"
Sagar Vora368cb452021-03-31 12:43:33 +0530133 zip_stream.close()
Gauravf1e28e02019-02-13 16:46:24 +0530134
135def get_invoice_summary(items, taxes):
136 summary_data = frappe._dict()
137 for tax in taxes:
138 #Include only VAT charges.
139 if tax.charge_type == "Actual":
140 continue
141
Gaurav2670ad72019-02-19 10:17:17 +0530142 #Charges to appear as items in the e-invoice.
143 if tax.charge_type in ["On Previous Row Total", "On Previous Row Amount"]:
144 reference_row = next((row for row in taxes if row.idx == int(tax.row_id or 0)), None)
145 if reference_row:
146 items.append(
147 frappe._dict(
148 idx=len(items)+1,
149 item_code=reference_row.description,
150 item_name=reference_row.description,
rohitwaghchaure9673d0d2019-03-24 12:19:58 +0530151 description=reference_row.description,
Gaurav2670ad72019-02-19 10:17:17 +0530152 rate=reference_row.tax_amount,
153 qty=1.0,
154 amount=reference_row.tax_amount,
155 stock_uom=frappe.db.get_single_value("Stock Settings", "stock_uom") or _("Nos"),
156 tax_rate=tax.rate,
157 tax_amount=(reference_row.tax_amount * tax.rate) / 100,
158 net_amount=reference_row.tax_amount,
Rohit Waghchaurec10064a2019-09-23 17:39:55 +0530159 taxable_amount=reference_row.tax_amount,
Rohit Waghchaure58f489f2019-04-01 17:50:31 +0530160 item_tax_rate={tax.account_head: tax.rate},
Gaurav2670ad72019-02-19 10:17:17 +0530161 charges=True
162 )
163 )
164
Gauravf1e28e02019-02-13 16:46:24 +0530165 #Check item tax rates if tax rate is zero.
166 if tax.rate == 0:
167 for item in items:
Rohit Waghchaure58f489f2019-04-01 17:50:31 +0530168 item_tax_rate = item.item_tax_rate
169 if isinstance(item.item_tax_rate, string_types):
170 item_tax_rate = json.loads(item.item_tax_rate)
171
172 if item_tax_rate and tax.account_head in item_tax_rate:
Gaurav2670ad72019-02-19 10:17:17 +0530173 key = cstr(item_tax_rate[tax.account_head])
Rohit Waghchaure58f489f2019-04-01 17:50:31 +0530174 if key not in summary_data:
175 summary_data.setdefault(key, {"tax_amount": 0.0, "taxable_amount": 0.0,
176 "tax_exemption_reason": "", "tax_exemption_law": ""})
177
Gauravf1e28e02019-02-13 16:46:24 +0530178 summary_data[key]["tax_amount"] += item.tax_amount
179 summary_data[key]["taxable_amount"] += item.net_amount
180 if key == "0.0":
181 summary_data[key]["tax_exemption_reason"] = tax.tax_exemption_reason
182 summary_data[key]["tax_exemption_law"] = tax.tax_exemption_law
183
Rohit Waghchaurec10064a2019-09-23 17:39:55 +0530184 if summary_data.get("0.0") and tax.charge_type in ["On Previous Row Total",
185 "On Previous Row Amount"]:
186 summary_data[key]["taxable_amount"] = tax.total
187
Gauravf1e28e02019-02-13 16:46:24 +0530188 if summary_data == {}: #Implies that Zero VAT has not been set on any item.
189 summary_data.setdefault("0.0", {"tax_amount": 0.0, "taxable_amount": tax.total,
190 "tax_exemption_reason": tax.tax_exemption_reason, "tax_exemption_law": tax.tax_exemption_law})
191
192 else:
193 item_wise_tax_detail = json.loads(tax.item_wise_tax_detail)
194 for rate_item in [tax_item for tax_item in item_wise_tax_detail.items() if tax_item[1][0] == tax.rate]:
Gaurav2670ad72019-02-19 10:17:17 +0530195 key = cstr(tax.rate)
Gauravf1e28e02019-02-13 16:46:24 +0530196 if not summary_data.get(key): summary_data.setdefault(key, {"tax_amount": 0.0, "taxable_amount": 0.0})
197 summary_data[key]["tax_amount"] += rate_item[1][1]
198 summary_data[key]["taxable_amount"] += sum([item.net_amount for item in items if item.item_code == rate_item[0]])
199
Gaurav2670ad72019-02-19 10:17:17 +0530200 for item in items:
201 key = cstr(tax.rate)
202 if item.get("charges"):
203 if not summary_data.get(key): summary_data.setdefault(key, {"taxable_amount": 0.0})
204 summary_data[key]["taxable_amount"] += item.taxable_amount
205
Gauravf1e28e02019-02-13 16:46:24 +0530206 return summary_data
207
208#Preflight for successful e-invoice export.
209def sales_invoice_validate(doc):
210 #Validate company
rohitwaghchaureef3f8642019-02-20 15:47:06 +0530211 if doc.doctype != 'Sales Invoice':
212 return
213
Gauravf1e28e02019-02-13 16:46:24 +0530214 if not doc.company_address:
215 frappe.throw(_("Please set an Address on the Company '%s'" % doc.company), title=_("E-Invoicing Information Missing"))
216 else:
Rohit Waghchaure74cfe572019-02-26 20:08:26 +0530217 validate_address(doc.company_address)
Gauravf1e28e02019-02-13 16:46:24 +0530218
Rohit Waghchaure0f98cb82019-02-26 15:01:30 +0530219 company_fiscal_regime = frappe.get_cached_value("Company", doc.company, 'fiscal_regime')
220 if not company_fiscal_regime:
221 frappe.throw(_("Fiscal Regime is mandatory, kindly set the fiscal regime in the company {0}")
222 .format(doc.company))
223 else:
224 doc.company_fiscal_regime = company_fiscal_regime
225
Gauravbd80fd12019-03-28 12:18:03 +0530226 doc.company_tax_id = frappe.get_cached_value("Company", doc.company, 'tax_id')
227 doc.company_fiscal_code = frappe.get_cached_value("Company", doc.company, 'fiscal_code')
Gauravf1e28e02019-02-13 16:46:24 +0530228 if not doc.company_tax_id and not doc.company_fiscal_code:
229 frappe.throw(_("Please set either the Tax ID or Fiscal Code on Company '%s'" % doc.company), title=_("E-Invoicing Information Missing"))
230
231 #Validate customer details
Gaurav010acf72019-03-28 10:42:23 +0530232 customer = frappe.get_doc("Customer", doc.customer)
233
Rohit Waghchaure68a14562019-05-22 13:17:46 +0530234 if customer.customer_type == "Individual":
Gaurav010acf72019-03-28 10:42:23 +0530235 doc.customer_fiscal_code = customer.fiscal_code
Gauravf1e28e02019-02-13 16:46:24 +0530236 if not doc.customer_fiscal_code:
237 frappe.throw(_("Please set Fiscal Code for the customer '%s'" % doc.customer), title=_("E-Invoicing Information Missing"))
238 else:
Gaurav010acf72019-03-28 10:42:23 +0530239 if customer.is_public_administration:
240 doc.customer_fiscal_code = customer.fiscal_code
Gauravf1e28e02019-02-13 16:46:24 +0530241 if not doc.customer_fiscal_code:
242 frappe.throw(_("Please set Fiscal Code for the public administration '%s'" % doc.customer), title=_("E-Invoicing Information Missing"))
243 else:
Gaurav010acf72019-03-28 10:42:23 +0530244 doc.tax_id = customer.tax_id
Gauravf1e28e02019-02-13 16:46:24 +0530245 if not doc.tax_id:
246 frappe.throw(_("Please set Tax ID for the customer '%s'" % doc.customer), title=_("E-Invoicing Information Missing"))
247
248 if not doc.customer_address:
249 frappe.throw(_("Please set the Customer Address"), title=_("E-Invoicing Information Missing"))
250 else:
Rohit Waghchaure74cfe572019-02-26 20:08:26 +0530251 validate_address(doc.customer_address)
Gauravf1e28e02019-02-13 16:46:24 +0530252
253 if not len(doc.taxes):
254 frappe.throw(_("Please set at least one row in the Taxes and Charges Table"), title=_("E-Invoicing Information Missing"))
255 else:
256 for row in doc.taxes:
257 if row.rate == 0 and row.tax_amount == 0 and not row.tax_exemption_reason:
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530258 frappe.throw(_("Row {0}: Please set at Tax Exemption Reason in Sales Taxes and Charges").format(row.idx),
Gauravf1e28e02019-02-13 16:46:24 +0530259 title=_("E-Invoicing Information Missing"))
260
Rohit Waghchaure0f98cb82019-02-26 15:01:30 +0530261 for schedule in doc.payment_schedule:
262 if schedule.mode_of_payment and not schedule.mode_of_payment_code:
263 schedule.mode_of_payment_code = frappe.get_cached_value('Mode of Payment',
264 schedule.mode_of_payment, 'mode_of_payment_code')
Gauravf1e28e02019-02-13 16:46:24 +0530265
266#Ensure payment details are valid for e-invoice.
rohitwaghchaurec18e9252019-02-20 17:13:15 +0530267def sales_invoice_on_submit(doc, method):
Gauravf1e28e02019-02-13 16:46:24 +0530268 #Validate payment details
rohitwaghchaurec18e9252019-02-20 17:13:15 +0530269 if get_company_country(doc.company) not in ['Italy',
270 'Italia', 'Italian Republic', 'Repubblica Italiana']:
271 return
272
Gauravf1e28e02019-02-13 16:46:24 +0530273 if not len(doc.payment_schedule):
274 frappe.throw(_("Please set the Payment Schedule"), title=_("E-Invoicing Information Missing"))
275 else:
276 for schedule in doc.payment_schedule:
277 if not schedule.mode_of_payment:
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530278 frappe.throw(_("Row {0}: Please set the Mode of Payment in Payment Schedule").format(schedule.idx),
Gauravf1e28e02019-02-13 16:46:24 +0530279 title=_("E-Invoicing Information Missing"))
Gaurav2670ad72019-02-19 10:17:17 +0530280 elif not frappe.db.get_value("Mode of Payment", schedule.mode_of_payment, "mode_of_payment_code"):
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530281 frappe.throw(_("Row {0}: Please set the correct code on Mode of Payment {1}").format(schedule.idx, schedule.mode_of_payment),
Gaurav2670ad72019-02-19 10:17:17 +0530282 title=_("E-Invoicing Information Missing"))
Gauravf1e28e02019-02-13 16:46:24 +0530283
284 prepare_and_attach_invoice(doc)
285
Gauravb30a9b12019-03-01 12:33:19 +0530286def prepare_and_attach_invoice(doc, replace=False):
287 progressive_name, progressive_number = get_progressive_name_and_number(doc, replace)
Gauravf1e28e02019-02-13 16:46:24 +0530288
289 invoice = prepare_invoice(doc, progressive_number)
rohitwaghchaurecdcff6c2019-09-09 10:15:01 +0530290 item_meta = frappe.get_meta("Sales Invoice Item")
291
292 invoice_xml = frappe.render_template('erpnext/regional/italy/e-invoice.xml',
293 context={"doc": invoice, "item_meta": item_meta}, is_path=True)
294
Rohit Waghchaure0f98cb82019-02-26 15:01:30 +0530295 invoice_xml = invoice_xml.replace("&", "&amp;")
Gauravf1e28e02019-02-13 16:46:24 +0530296
297 xml_filename = progressive_name + ".xml"
Saurabhacf83792019-02-24 08:57:16 +0530298
299 _file = frappe.get_doc({
300 "doctype": "File",
301 "file_name": xml_filename,
302 "attached_to_doctype": doc.doctype,
303 "attached_to_name": doc.name,
304 "is_private": True,
305 "content": invoice_xml
306 })
307 _file.save()
Aditya Hase234d3572019-05-01 11:48:10 +0530308 return _file
Gauravb30a9b12019-03-01 12:33:19 +0530309
310@frappe.whitelist()
311def generate_single_invoice(docname):
312 doc = frappe.get_doc("Sales Invoice", docname)
Sagar Vora368cb452021-03-31 12:43:33 +0530313 frappe.has_permission("Sales Invoice", doc=doc, throw=True)
Rohit Waghchaure1b7059b2019-03-12 17:44:29 +0530314
Gauravb30a9b12019-03-01 12:33:19 +0530315 e_invoice = prepare_and_attach_invoice(doc, True)
Sagar Vora368cb452021-03-31 12:43:33 +0530316 return e_invoice.file_url
Gauravb30a9b12019-03-01 12:33:19 +0530317
Sagar Vora368cb452021-03-31 12:43:33 +0530318# Delete e-invoice attachment on cancel.
rohitwaghchaurec18e9252019-02-20 17:13:15 +0530319def sales_invoice_on_cancel(doc, method):
320 if get_company_country(doc.company) not in ['Italy',
321 'Italia', 'Italian Republic', 'Repubblica Italiana']:
322 return
323
Gauravf1e28e02019-02-13 16:46:24 +0530324 for attachment in get_e_invoice_attachments(doc):
325 remove_file(attachment.name, attached_to_doctype=doc.doctype, attached_to_name=doc.name)
326
rohitwaghchaurec18e9252019-02-20 17:13:15 +0530327def get_company_country(company):
328 return frappe.get_cached_value('Company', company, 'country')
329
Sagar Vora368cb452021-03-31 12:43:33 +0530330def get_e_invoice_attachments(invoices):
331 if not isinstance(invoices, list):
332 if not invoices.company_tax_id:
333 return
334
335 invoices = [invoices]
336
337 tax_id_map = {
338 invoice.name: (
339 invoice.company_tax_id
340 if invoice.company_tax_id.startswith("IT")
341 else "IT" + invoice.company_tax_id
342 ) for invoice in invoices
343 }
344
345 attachments = frappe.get_all(
346 "File",
347 fields=("name", "file_name", "attached_to_name", "is_private"),
348 filters= {
349 "attached_to_name": ('in', tax_id_map),
350 "attached_to_doctype": 'Sales Invoice'
351 }
352 )
Mangesh-Khairnar359a73e2019-07-04 11:37:20 +0530353
Gauravf1e28e02019-02-13 16:46:24 +0530354 out = []
Gauravf1e28e02019-02-13 16:46:24 +0530355 for attachment in attachments:
Sagar Vora368cb452021-03-31 12:43:33 +0530356 if (
357 attachment.file_name
358 and attachment.file_name.endswith(".xml")
359 and attachment.file_name.startswith(
360 tax_id_map.get(attachment.attached_to_name))
361 ):
Gauravf1e28e02019-02-13 16:46:24 +0530362 out.append(attachment)
363
364 return out
365
Rohit Waghchaure74cfe572019-02-26 20:08:26 +0530366def validate_address(address_name):
367 fields = ["pincode", "city", "country_code"]
368 data = frappe.get_cached_value("Address", address_name, fields, as_dict=1) or {}
Gauravf1e28e02019-02-13 16:46:24 +0530369
Rohit Waghchaure74cfe572019-02-26 20:08:26 +0530370 for field in fields:
371 if not data.get(field):
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530372 frappe.throw(_("Please set {0} for address {1}").format(field.replace('-',''), address_name),
Rohit Waghchaure74cfe572019-02-26 20:08:26 +0530373 title=_("E-Invoicing Information Missing"))
Gauravf1e28e02019-02-13 16:46:24 +0530374
375def get_unamended_name(doc):
376 attributes = ["naming_series", "amended_from"]
377 for attribute in attributes:
378 if not hasattr(doc, attribute):
379 return doc.name
380
381 if doc.amended_from:
382 return "-".join(doc.name.split("-")[:-1])
383 else:
384 return doc.name
385
Gauravb30a9b12019-03-01 12:33:19 +0530386def get_progressive_name_and_number(doc, replace=False):
387 if replace:
388 for attachment in get_e_invoice_attachments(doc):
389 remove_file(attachment.name, attached_to_doctype=doc.doctype, attached_to_name=doc.name)
390 filename = attachment.file_name.split(".xml")[0]
391 return filename, filename.split("_")[1]
392
Gauravf1e28e02019-02-13 16:46:24 +0530393 company_tax_id = doc.company_tax_id if doc.company_tax_id.startswith("IT") else "IT" + doc.company_tax_id
394 progressive_name = frappe.model.naming.make_autoname(company_tax_id + "_.#####")
395 progressive_number = progressive_name.split("_")[1]
396
Gaurav3f046132019-02-19 16:28:22 +0530397 return progressive_name, progressive_number
398
Gaurav Naik3bf0acb2019-02-20 12:08:53 +0530399def set_state_code(doc, method):
Rohit Waghchaure74cfe572019-02-26 20:08:26 +0530400 if doc.get('country_code'):
401 doc.country_code = doc.country_code.upper()
402
deepeshgarg0071915e152019-02-21 17:55:57 +0530403 if not doc.get('state'):
404 return
405
Gaurav3f046132019-02-19 16:28:22 +0530406 if not (hasattr(doc, "state_code") and doc.country in ["Italy", "Italia", "Italian Republic", "Repubblica Italiana"]):
407 return
408
409 state_codes_lower = {key.lower():value for key,value in state_codes.items()}
Rohit Waghchaure4ef924d2019-03-01 16:24:54 +0530410
411 state = doc.get('state','').lower()
412 if state_codes_lower.get(state):
413 doc.state_code = state_codes_lower.get(state)