blob: c82557b9de09f8526bbf6bf2b126f8bafc84f86d [file] [log] [blame]
Sagar Voraba76f872021-03-29 20:18:45 +05301import io
2import json
Chillar Anand915b3432021-09-02 16:44:59 +05303
Sagar Voraba76f872021-03-29 20:18:45 +05304import frappe
Gauravf1e28e02019-02-13 16:46:24 +05305from frappe import _
Chillar Anand915b3432021-09-02 16:44:59 +05306from frappe.utils import cstr, flt
Saqib6cf92542021-08-24 15:26:44 +05307from frappe.utils.file_manager import remove_file
Chillar Anand915b3432021-09-02 16:44:59 +05308
9from erpnext.controllers.taxes_and_totals import get_itemised_tax
Gaurav3f046132019-02-19 16:28:22 +053010from erpnext.regional.italy import state_codes
Gauravf1e28e02019-02-13 16:46:24 +053011
12
13def update_itemised_tax_data(doc):
14 if not doc.taxes: return
15
hello@openetech.com70214022019-10-16 23:38:51 +053016 if doc.doctype == "Purchase Invoice": return
17
Gauravf1e28e02019-02-13 16:46:24 +053018 itemised_tax = get_itemised_tax(doc.taxes)
19
20 for row in doc.items:
21 tax_rate = 0.0
22 if itemised_tax.get(row.item_code):
23 tax_rate = sum([tax.get('tax_rate', 0) for d, tax in itemised_tax.get(row.item_code).items()])
24
25 row.tax_rate = flt(tax_rate, row.precision("tax_rate"))
26 row.tax_amount = flt((row.net_amount * tax_rate) / 100, row.precision("net_amount"))
27 row.total_amount = flt((row.net_amount + row.tax_amount), row.precision("total_amount"))
28
29@frappe.whitelist()
30def export_invoices(filters=None):
Sagar Voraba76f872021-03-29 20:18:45 +053031 frappe.has_permission('Sales Invoice', throw=True)
Gauravf1e28e02019-02-13 16:46:24 +053032
Sagar Voraba76f872021-03-29 20:18:45 +053033 invoices = frappe.get_all(
34 "Sales Invoice",
35 filters=get_conditions(filters),
36 fields=["name", "company_tax_id"]
37 )
Gauravf1e28e02019-02-13 16:46:24 +053038
Sagar Voraba76f872021-03-29 20:18:45 +053039 attachments = get_e_invoice_attachments(invoices)
Gauravf1e28e02019-02-13 16:46:24 +053040
Sagar Voraba76f872021-03-29 20:18:45 +053041 zip_filename = "{0}-einvoices.zip".format(
42 frappe.utils.get_datetime().strftime("%Y%m%d_%H%M%S"))
Gauravf1e28e02019-02-13 16:46:24 +053043
Sagar Voraba76f872021-03-29 20:18:45 +053044 download_zip(attachments, zip_filename)
Gauravf1e28e02019-02-13 16:46:24 +053045
46
Gauravf1e28e02019-02-13 16:46:24 +053047def prepare_invoice(invoice, progressive_number):
48 #set company information
49 company = frappe.get_doc("Company", invoice.company)
50
51 invoice.progressive_number = progressive_number
52 invoice.unamended_name = get_unamended_name(invoice)
53 invoice.company_data = company
54 company_address = frappe.get_doc("Address", invoice.company_address)
55 invoice.company_address_data = company_address
56
57 #Set invoice type
Saqib Ansari032246d2021-04-09 12:08:24 +053058 if not invoice.type_of_document:
59 if invoice.is_return and invoice.return_against:
60 invoice.type_of_document = "TD04" #Credit Note (Nota di Credito)
61 invoice.return_against_unamended = get_unamended_name(frappe.get_doc("Sales Invoice", invoice.return_against))
62 else:
63 invoice.type_of_document = "TD01" #Sales Invoice (Fattura)
Gauravf1e28e02019-02-13 16:46:24 +053064
65 #set customer information
66 invoice.customer_data = frappe.get_doc("Customer", invoice.customer)
67 customer_address = frappe.get_doc("Address", invoice.customer_address)
68 invoice.customer_address_data = customer_address
69
70 if invoice.shipping_address_name:
71 invoice.shipping_address_data = frappe.get_doc("Address", invoice.shipping_address_name)
72
73 if invoice.customer_data.is_public_administration:
74 invoice.transmission_format_code = "FPA12"
75 else:
76 invoice.transmission_format_code = "FPR12"
77
Gaurav2670ad72019-02-19 10:17:17 +053078 invoice.e_invoice_items = [item for item in invoice.items]
79 tax_data = get_invoice_summary(invoice.e_invoice_items, invoice.taxes)
Gauravf1e28e02019-02-13 16:46:24 +053080 invoice.tax_data = tax_data
81
82 #Check if stamp duty (Bollo) of 2 EUR exists.
Rohit Waghchaure68a14562019-05-22 13:17:46 +053083 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 +053084 if stamp_duty_charge_row:
85 invoice.stamp_duty = stamp_duty_charge_row.tax_amount
86
Gaurav2670ad72019-02-19 10:17:17 +053087 for item in invoice.e_invoice_items:
Nabin Hait34c551d2019-07-03 10:34:31 +053088 if item.tax_rate == 0.0 and item.tax_amount == 0.0 and tax_data.get("0.0"):
Gauravf1e28e02019-02-13 16:46:24 +053089 item.tax_exemption_reason = tax_data["0.0"]["tax_exemption_reason"]
90
Rohit Waghchaure1b7059b2019-03-12 17:44:29 +053091 customer_po_data = {}
92 for d in invoice.e_invoice_items:
93 if (d.customer_po_no and d.customer_po_date
94 and d.customer_po_no not in customer_po_data):
95 customer_po_data[d.customer_po_no] = d.customer_po_date
96
97 invoice.customer_po_data = customer_po_data
98
Gauravf1e28e02019-02-13 16:46:24 +053099 return invoice
100
101def get_conditions(filters):
102 filters = json.loads(filters)
103
Sagar Voraba76f872021-03-29 20:18:45 +0530104 conditions = {"docstatus": 1, "company_tax_id": ("!=", "")}
Gauravf1e28e02019-02-13 16:46:24 +0530105
106 if filters.get("company"): conditions["company"] = filters["company"]
107 if filters.get("customer"): conditions["customer"] = filters["customer"]
108
109 if filters.get("from_date"): conditions["posting_date"] = (">=", filters["from_date"])
110 if filters.get("to_date"): conditions["posting_date"] = ("<=", filters["to_date"])
111
112 if filters.get("from_date") and filters.get("to_date"):
113 conditions["posting_date"] = ("between", [filters.get("from_date"), filters.get("to_date")])
114
115 return conditions
116
Sagar Voraba76f872021-03-29 20:18:45 +0530117
Gauravf1e28e02019-02-13 16:46:24 +0530118def download_zip(files, output_filename):
Sagar Voraba76f872021-03-29 20:18:45 +0530119 import zipfile
Gauravf1e28e02019-02-13 16:46:24 +0530120
Sagar Voraba76f872021-03-29 20:18:45 +0530121 zip_stream = io.BytesIO()
122 with zipfile.ZipFile(zip_stream, 'w', zipfile.ZIP_DEFLATED) as zip_file:
123 for file in files:
124 file_path = frappe.utils.get_files_path(
125 file.file_name, is_private=file.is_private)
Gauravf1e28e02019-02-13 16:46:24 +0530126
Sagar Voraba76f872021-03-29 20:18:45 +0530127 zip_file.write(file_path, arcname=file.file_name)
Gauravf1e28e02019-02-13 16:46:24 +0530128
129 frappe.local.response.filename = output_filename
Sagar Voraba76f872021-03-29 20:18:45 +0530130 frappe.local.response.filecontent = zip_stream.getvalue()
Gauravf1e28e02019-02-13 16:46:24 +0530131 frappe.local.response.type = "download"
Sagar Voraba76f872021-03-29 20:18:45 +0530132 zip_stream.close()
Gauravf1e28e02019-02-13 16:46:24 +0530133
134def get_invoice_summary(items, taxes):
135 summary_data = frappe._dict()
136 for tax in taxes:
137 #Include only VAT charges.
138 if tax.charge_type == "Actual":
139 continue
140
Gaurav2670ad72019-02-19 10:17:17 +0530141 #Charges to appear as items in the e-invoice.
142 if tax.charge_type in ["On Previous Row Total", "On Previous Row Amount"]:
143 reference_row = next((row for row in taxes if row.idx == int(tax.row_id or 0)), None)
144 if reference_row:
145 items.append(
146 frappe._dict(
147 idx=len(items)+1,
148 item_code=reference_row.description,
149 item_name=reference_row.description,
rohitwaghchaure9673d0d2019-03-24 12:19:58 +0530150 description=reference_row.description,
Gaurav2670ad72019-02-19 10:17:17 +0530151 rate=reference_row.tax_amount,
152 qty=1.0,
153 amount=reference_row.tax_amount,
154 stock_uom=frappe.db.get_single_value("Stock Settings", "stock_uom") or _("Nos"),
155 tax_rate=tax.rate,
156 tax_amount=(reference_row.tax_amount * tax.rate) / 100,
157 net_amount=reference_row.tax_amount,
Rohit Waghchaurec10064a2019-09-23 17:39:55 +0530158 taxable_amount=reference_row.tax_amount,
Rohit Waghchaure58f489f2019-04-01 17:50:31 +0530159 item_tax_rate={tax.account_head: tax.rate},
Gaurav2670ad72019-02-19 10:17:17 +0530160 charges=True
161 )
162 )
163
Gauravf1e28e02019-02-13 16:46:24 +0530164 #Check item tax rates if tax rate is zero.
165 if tax.rate == 0:
166 for item in items:
Rohit Waghchaure58f489f2019-04-01 17:50:31 +0530167 item_tax_rate = item.item_tax_rate
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530168 if isinstance(item.item_tax_rate, str):
Rohit Waghchaure58f489f2019-04-01 17:50:31 +0530169 item_tax_rate = json.loads(item.item_tax_rate)
170
171 if item_tax_rate and tax.account_head in item_tax_rate:
Gaurav2670ad72019-02-19 10:17:17 +0530172 key = cstr(item_tax_rate[tax.account_head])
Rohit Waghchaure58f489f2019-04-01 17:50:31 +0530173 if key not in summary_data:
174 summary_data.setdefault(key, {"tax_amount": 0.0, "taxable_amount": 0.0,
175 "tax_exemption_reason": "", "tax_exemption_law": ""})
176
Gauravf1e28e02019-02-13 16:46:24 +0530177 summary_data[key]["tax_amount"] += item.tax_amount
178 summary_data[key]["taxable_amount"] += item.net_amount
179 if key == "0.0":
180 summary_data[key]["tax_exemption_reason"] = tax.tax_exemption_reason
181 summary_data[key]["tax_exemption_law"] = tax.tax_exemption_law
182
Rohit Waghchaurec10064a2019-09-23 17:39:55 +0530183 if summary_data.get("0.0") and tax.charge_type in ["On Previous Row Total",
184 "On Previous Row Amount"]:
185 summary_data[key]["taxable_amount"] = tax.total
186
Gauravf1e28e02019-02-13 16:46:24 +0530187 if summary_data == {}: #Implies that Zero VAT has not been set on any item.
188 summary_data.setdefault("0.0", {"tax_amount": 0.0, "taxable_amount": tax.total,
189 "tax_exemption_reason": tax.tax_exemption_reason, "tax_exemption_law": tax.tax_exemption_law})
190
191 else:
192 item_wise_tax_detail = json.loads(tax.item_wise_tax_detail)
193 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 +0530194 key = cstr(tax.rate)
Gauravf1e28e02019-02-13 16:46:24 +0530195 if not summary_data.get(key): summary_data.setdefault(key, {"tax_amount": 0.0, "taxable_amount": 0.0})
196 summary_data[key]["tax_amount"] += rate_item[1][1]
197 summary_data[key]["taxable_amount"] += sum([item.net_amount for item in items if item.item_code == rate_item[0]])
198
Gaurav2670ad72019-02-19 10:17:17 +0530199 for item in items:
200 key = cstr(tax.rate)
201 if item.get("charges"):
202 if not summary_data.get(key): summary_data.setdefault(key, {"taxable_amount": 0.0})
203 summary_data[key]["taxable_amount"] += item.taxable_amount
204
Gauravf1e28e02019-02-13 16:46:24 +0530205 return summary_data
206
207#Preflight for successful e-invoice export.
208def sales_invoice_validate(doc):
209 #Validate company
rohitwaghchaureef3f8642019-02-20 15:47:06 +0530210 if doc.doctype != 'Sales Invoice':
211 return
212
Gauravf1e28e02019-02-13 16:46:24 +0530213 if not doc.company_address:
214 frappe.throw(_("Please set an Address on the Company '%s'" % doc.company), title=_("E-Invoicing Information Missing"))
215 else:
Rohit Waghchaure74cfe572019-02-26 20:08:26 +0530216 validate_address(doc.company_address)
Gauravf1e28e02019-02-13 16:46:24 +0530217
Rohit Waghchaure0f98cb82019-02-26 15:01:30 +0530218 company_fiscal_regime = frappe.get_cached_value("Company", doc.company, 'fiscal_regime')
219 if not company_fiscal_regime:
220 frappe.throw(_("Fiscal Regime is mandatory, kindly set the fiscal regime in the company {0}")
221 .format(doc.company))
222 else:
223 doc.company_fiscal_regime = company_fiscal_regime
224
Gauravbd80fd12019-03-28 12:18:03 +0530225 doc.company_tax_id = frappe.get_cached_value("Company", doc.company, 'tax_id')
226 doc.company_fiscal_code = frappe.get_cached_value("Company", doc.company, 'fiscal_code')
Gauravf1e28e02019-02-13 16:46:24 +0530227 if not doc.company_tax_id and not doc.company_fiscal_code:
228 frappe.throw(_("Please set either the Tax ID or Fiscal Code on Company '%s'" % doc.company), title=_("E-Invoicing Information Missing"))
229
230 #Validate customer details
Gaurav010acf72019-03-28 10:42:23 +0530231 customer = frappe.get_doc("Customer", doc.customer)
232
Rohit Waghchaure68a14562019-05-22 13:17:46 +0530233 if customer.customer_type == "Individual":
Gaurav010acf72019-03-28 10:42:23 +0530234 doc.customer_fiscal_code = customer.fiscal_code
Gauravf1e28e02019-02-13 16:46:24 +0530235 if not doc.customer_fiscal_code:
236 frappe.throw(_("Please set Fiscal Code for the customer '%s'" % doc.customer), title=_("E-Invoicing Information Missing"))
237 else:
Gaurav010acf72019-03-28 10:42:23 +0530238 if customer.is_public_administration:
239 doc.customer_fiscal_code = customer.fiscal_code
Gauravf1e28e02019-02-13 16:46:24 +0530240 if not doc.customer_fiscal_code:
241 frappe.throw(_("Please set Fiscal Code for the public administration '%s'" % doc.customer), title=_("E-Invoicing Information Missing"))
242 else:
Gaurav010acf72019-03-28 10:42:23 +0530243 doc.tax_id = customer.tax_id
Gauravf1e28e02019-02-13 16:46:24 +0530244 if not doc.tax_id:
245 frappe.throw(_("Please set Tax ID for the customer '%s'" % doc.customer), title=_("E-Invoicing Information Missing"))
246
247 if not doc.customer_address:
248 frappe.throw(_("Please set the Customer Address"), title=_("E-Invoicing Information Missing"))
249 else:
Rohit Waghchaure74cfe572019-02-26 20:08:26 +0530250 validate_address(doc.customer_address)
Gauravf1e28e02019-02-13 16:46:24 +0530251
252 if not len(doc.taxes):
253 frappe.throw(_("Please set at least one row in the Taxes and Charges Table"), title=_("E-Invoicing Information Missing"))
254 else:
255 for row in doc.taxes:
256 if row.rate == 0 and row.tax_amount == 0 and not row.tax_exemption_reason:
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530257 frappe.throw(_("Row {0}: Please set at Tax Exemption Reason in Sales Taxes and Charges").format(row.idx),
Gauravf1e28e02019-02-13 16:46:24 +0530258 title=_("E-Invoicing Information Missing"))
259
Rohit Waghchaure0f98cb82019-02-26 15:01:30 +0530260 for schedule in doc.payment_schedule:
261 if schedule.mode_of_payment and not schedule.mode_of_payment_code:
262 schedule.mode_of_payment_code = frappe.get_cached_value('Mode of Payment',
263 schedule.mode_of_payment, 'mode_of_payment_code')
Gauravf1e28e02019-02-13 16:46:24 +0530264
265#Ensure payment details are valid for e-invoice.
rohitwaghchaurec18e9252019-02-20 17:13:15 +0530266def sales_invoice_on_submit(doc, method):
Gauravf1e28e02019-02-13 16:46:24 +0530267 #Validate payment details
rohitwaghchaurec18e9252019-02-20 17:13:15 +0530268 if get_company_country(doc.company) not in ['Italy',
269 'Italia', 'Italian Republic', 'Repubblica Italiana']:
270 return
271
Gauravf1e28e02019-02-13 16:46:24 +0530272 if not len(doc.payment_schedule):
273 frappe.throw(_("Please set the Payment Schedule"), title=_("E-Invoicing Information Missing"))
274 else:
275 for schedule in doc.payment_schedule:
276 if not schedule.mode_of_payment:
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530277 frappe.throw(_("Row {0}: Please set the Mode of Payment in Payment Schedule").format(schedule.idx),
Gauravf1e28e02019-02-13 16:46:24 +0530278 title=_("E-Invoicing Information Missing"))
Gaurav2670ad72019-02-19 10:17:17 +0530279 elif not frappe.db.get_value("Mode of Payment", schedule.mode_of_payment, "mode_of_payment_code"):
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530280 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 +0530281 title=_("E-Invoicing Information Missing"))
Gauravf1e28e02019-02-13 16:46:24 +0530282
283 prepare_and_attach_invoice(doc)
284
Gauravb30a9b12019-03-01 12:33:19 +0530285def prepare_and_attach_invoice(doc, replace=False):
286 progressive_name, progressive_number = get_progressive_name_and_number(doc, replace)
Gauravf1e28e02019-02-13 16:46:24 +0530287
288 invoice = prepare_invoice(doc, progressive_number)
rohitwaghchaurecdcff6c2019-09-09 10:15:01 +0530289 item_meta = frappe.get_meta("Sales Invoice Item")
290
291 invoice_xml = frappe.render_template('erpnext/regional/italy/e-invoice.xml',
292 context={"doc": invoice, "item_meta": item_meta}, is_path=True)
293
Rohit Waghchaure0f98cb82019-02-26 15:01:30 +0530294 invoice_xml = invoice_xml.replace("&", "&amp;")
Gauravf1e28e02019-02-13 16:46:24 +0530295
296 xml_filename = progressive_name + ".xml"
Saurabhacf83792019-02-24 08:57:16 +0530297
298 _file = frappe.get_doc({
299 "doctype": "File",
300 "file_name": xml_filename,
301 "attached_to_doctype": doc.doctype,
302 "attached_to_name": doc.name,
303 "is_private": True,
304 "content": invoice_xml
305 })
306 _file.save()
Aditya Hase234d3572019-05-01 11:48:10 +0530307 return _file
Gauravb30a9b12019-03-01 12:33:19 +0530308
309@frappe.whitelist()
310def generate_single_invoice(docname):
311 doc = frappe.get_doc("Sales Invoice", docname)
Sagar Voraba76f872021-03-29 20:18:45 +0530312 frappe.has_permission("Sales Invoice", doc=doc, throw=True)
Rohit Waghchaure1b7059b2019-03-12 17:44:29 +0530313
Gauravb30a9b12019-03-01 12:33:19 +0530314 e_invoice = prepare_and_attach_invoice(doc, True)
Sagar Voraba76f872021-03-29 20:18:45 +0530315 return e_invoice.file_url
Gauravb30a9b12019-03-01 12:33:19 +0530316
Sagar Voraba76f872021-03-29 20:18:45 +0530317# Delete e-invoice attachment on cancel.
rohitwaghchaurec18e9252019-02-20 17:13:15 +0530318def sales_invoice_on_cancel(doc, method):
319 if get_company_country(doc.company) not in ['Italy',
320 'Italia', 'Italian Republic', 'Repubblica Italiana']:
321 return
322
Gauravf1e28e02019-02-13 16:46:24 +0530323 for attachment in get_e_invoice_attachments(doc):
324 remove_file(attachment.name, attached_to_doctype=doc.doctype, attached_to_name=doc.name)
325
rohitwaghchaurec18e9252019-02-20 17:13:15 +0530326def get_company_country(company):
327 return frappe.get_cached_value('Company', company, 'country')
328
Sagar Voraba76f872021-03-29 20:18:45 +0530329def get_e_invoice_attachments(invoices):
330 if not isinstance(invoices, list):
331 if not invoices.company_tax_id:
332 return
333
334 invoices = [invoices]
335
336 tax_id_map = {
337 invoice.name: (
338 invoice.company_tax_id
339 if invoice.company_tax_id.startswith("IT")
340 else "IT" + invoice.company_tax_id
341 ) for invoice in invoices
342 }
343
344 attachments = frappe.get_all(
345 "File",
346 fields=("name", "file_name", "attached_to_name", "is_private"),
347 filters= {
348 "attached_to_name": ('in', tax_id_map),
349 "attached_to_doctype": 'Sales Invoice'
350 }
351 )
Mangesh-Khairnar359a73e2019-07-04 11:37:20 +0530352
Gauravf1e28e02019-02-13 16:46:24 +0530353 out = []
Gauravf1e28e02019-02-13 16:46:24 +0530354 for attachment in attachments:
Sagar Voraba76f872021-03-29 20:18:45 +0530355 if (
356 attachment.file_name
357 and attachment.file_name.endswith(".xml")
358 and attachment.file_name.startswith(
359 tax_id_map.get(attachment.attached_to_name))
360 ):
Gauravf1e28e02019-02-13 16:46:24 +0530361 out.append(attachment)
362
363 return out
364
Rohit Waghchaure74cfe572019-02-26 20:08:26 +0530365def validate_address(address_name):
366 fields = ["pincode", "city", "country_code"]
367 data = frappe.get_cached_value("Address", address_name, fields, as_dict=1) or {}
Gauravf1e28e02019-02-13 16:46:24 +0530368
Rohit Waghchaure74cfe572019-02-26 20:08:26 +0530369 for field in fields:
370 if not data.get(field):
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530371 frappe.throw(_("Please set {0} for address {1}").format(field.replace('-',''), address_name),
Rohit Waghchaure74cfe572019-02-26 20:08:26 +0530372 title=_("E-Invoicing Information Missing"))
Gauravf1e28e02019-02-13 16:46:24 +0530373
374def get_unamended_name(doc):
375 attributes = ["naming_series", "amended_from"]
376 for attribute in attributes:
377 if not hasattr(doc, attribute):
378 return doc.name
379
380 if doc.amended_from:
381 return "-".join(doc.name.split("-")[:-1])
382 else:
383 return doc.name
384
Gauravb30a9b12019-03-01 12:33:19 +0530385def get_progressive_name_and_number(doc, replace=False):
386 if replace:
387 for attachment in get_e_invoice_attachments(doc):
388 remove_file(attachment.name, attached_to_doctype=doc.doctype, attached_to_name=doc.name)
389 filename = attachment.file_name.split(".xml")[0]
390 return filename, filename.split("_")[1]
391
Gauravf1e28e02019-02-13 16:46:24 +0530392 company_tax_id = doc.company_tax_id if doc.company_tax_id.startswith("IT") else "IT" + doc.company_tax_id
393 progressive_name = frappe.model.naming.make_autoname(company_tax_id + "_.#####")
394 progressive_number = progressive_name.split("_")[1]
395
Gaurav3f046132019-02-19 16:28:22 +0530396 return progressive_name, progressive_number
397
Gaurav Naik3bf0acb2019-02-20 12:08:53 +0530398def set_state_code(doc, method):
Rohit Waghchaure74cfe572019-02-26 20:08:26 +0530399 if doc.get('country_code'):
400 doc.country_code = doc.country_code.upper()
401
deepeshgarg0071915e152019-02-21 17:55:57 +0530402 if not doc.get('state'):
403 return
404
Gaurav3f046132019-02-19 16:28:22 +0530405 if not (hasattr(doc, "state_code") and doc.country in ["Italy", "Italia", "Italian Republic", "Repubblica Italiana"]):
406 return
407
408 state_codes_lower = {key.lower():value for key,value in state_codes.items()}
Rohit Waghchaure4ef924d2019-03-01 16:24:54 +0530409
410 state = doc.get('state','').lower()
411 if state_codes_lower.get(state):
412 doc.state_code = state_codes_lower.get(state)