blob: 6842fb2a61992455b7d754e2440327d20e1275ac [file] [log] [blame]
Gaurav2670ad72019-02-19 10:17:17 +05301from __future__ import unicode_literals
2
Gauravf1e28e02019-02-13 16:46:24 +05303import frappe, json, os
Gaurav2670ad72019-02-19 10:17:17 +05304from frappe.utils import flt, cstr
Gauravf1e28e02019-02-13 16:46:24 +05305from erpnext.controllers.taxes_and_totals import get_itemised_tax
6from frappe import _
Saurabhacf83792019-02-24 08:57:16 +05307from frappe.core.doctype.file.file import remove_file
Rohit Waghchaure58f489f2019-04-01 17:50:31 +05308from six import string_types
Gauravf1e28e02019-02-13 16:46:24 +05309from frappe.desk.form.load import get_attachments
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):
31 saved_xmls = []
32
33 invoices = frappe.get_all("Sales Invoice", filters=get_conditions(filters), fields=["*"])
34
35 for invoice in invoices:
36 attachments = get_e_invoice_attachments(invoice)
37 saved_xmls += [attachment.file_name for attachment in attachments]
38
39 zip_filename = "{0}-einvoices.zip".format(frappe.utils.get_datetime().strftime("%Y%m%d_%H%M%S"))
40
41 download_zip(saved_xmls, zip_filename)
42
43
44@frappe.whitelist()
45def prepare_invoice(invoice, progressive_number):
46 #set company information
47 company = frappe.get_doc("Company", invoice.company)
48
49 invoice.progressive_number = progressive_number
50 invoice.unamended_name = get_unamended_name(invoice)
51 invoice.company_data = company
52 company_address = frappe.get_doc("Address", invoice.company_address)
53 invoice.company_address_data = company_address
54
55 #Set invoice type
56 if invoice.is_return and invoice.return_against:
57 invoice.type_of_document = "TD04" #Credit Note (Nota di Credito)
58 invoice.return_against_unamended = get_unamended_name(frappe.get_doc("Sales Invoice", invoice.return_against))
59 else:
60 invoice.type_of_document = "TD01" #Sales Invoice (Fattura)
61
62 #set customer information
63 invoice.customer_data = frappe.get_doc("Customer", invoice.customer)
64 customer_address = frappe.get_doc("Address", invoice.customer_address)
65 invoice.customer_address_data = customer_address
66
67 if invoice.shipping_address_name:
68 invoice.shipping_address_data = frappe.get_doc("Address", invoice.shipping_address_name)
69
70 if invoice.customer_data.is_public_administration:
71 invoice.transmission_format_code = "FPA12"
72 else:
73 invoice.transmission_format_code = "FPR12"
74
Gaurav2670ad72019-02-19 10:17:17 +053075 invoice.e_invoice_items = [item for item in invoice.items]
76 tax_data = get_invoice_summary(invoice.e_invoice_items, invoice.taxes)
Gauravf1e28e02019-02-13 16:46:24 +053077 invoice.tax_data = tax_data
78
79 #Check if stamp duty (Bollo) of 2 EUR exists.
Rohit Waghchaure68a14562019-05-22 13:17:46 +053080 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 +053081 if stamp_duty_charge_row:
82 invoice.stamp_duty = stamp_duty_charge_row.tax_amount
83
Gaurav2670ad72019-02-19 10:17:17 +053084 for item in invoice.e_invoice_items:
Nabin Hait34c551d2019-07-03 10:34:31 +053085 if item.tax_rate == 0.0 and item.tax_amount == 0.0 and tax_data.get("0.0"):
Gauravf1e28e02019-02-13 16:46:24 +053086 item.tax_exemption_reason = tax_data["0.0"]["tax_exemption_reason"]
87
Rohit Waghchaure1b7059b2019-03-12 17:44:29 +053088 customer_po_data = {}
89 for d in invoice.e_invoice_items:
90 if (d.customer_po_no and d.customer_po_date
91 and d.customer_po_no not in customer_po_data):
92 customer_po_data[d.customer_po_no] = d.customer_po_date
93
94 invoice.customer_po_data = customer_po_data
95
Gauravf1e28e02019-02-13 16:46:24 +053096 return invoice
97
98def get_conditions(filters):
99 filters = json.loads(filters)
100
101 conditions = {"docstatus": 1}
102
103 if filters.get("company"): conditions["company"] = filters["company"]
104 if filters.get("customer"): conditions["customer"] = filters["customer"]
105
106 if filters.get("from_date"): conditions["posting_date"] = (">=", filters["from_date"])
107 if filters.get("to_date"): conditions["posting_date"] = ("<=", filters["to_date"])
108
109 if filters.get("from_date") and filters.get("to_date"):
110 conditions["posting_date"] = ("between", [filters.get("from_date"), filters.get("to_date")])
111
112 return conditions
113
114#TODO: Use function from frappe once PR #6853 is merged.
115def download_zip(files, output_filename):
116 from zipfile import ZipFile
117
118 input_files = [frappe.get_site_path('private', 'files', filename) for filename in files]
119 output_path = frappe.get_site_path('private', 'files', output_filename)
120
121 with ZipFile(output_path, 'w') as output_zip:
122 for input_file in input_files:
123 output_zip.write(input_file, arcname=os.path.basename(input_file))
124
125 with open(output_path, 'rb') as fileobj:
126 filedata = fileobj.read()
127
128 frappe.local.response.filename = output_filename
129 frappe.local.response.filecontent = filedata
130 frappe.local.response.type = "download"
131
132def get_invoice_summary(items, taxes):
133 summary_data = frappe._dict()
134 for tax in taxes:
135 #Include only VAT charges.
136 if tax.charge_type == "Actual":
137 continue
138
Gaurav2670ad72019-02-19 10:17:17 +0530139 #Charges to appear as items in the e-invoice.
140 if tax.charge_type in ["On Previous Row Total", "On Previous Row Amount"]:
141 reference_row = next((row for row in taxes if row.idx == int(tax.row_id or 0)), None)
142 if reference_row:
143 items.append(
144 frappe._dict(
145 idx=len(items)+1,
146 item_code=reference_row.description,
147 item_name=reference_row.description,
rohitwaghchaure9673d0d2019-03-24 12:19:58 +0530148 description=reference_row.description,
Gaurav2670ad72019-02-19 10:17:17 +0530149 rate=reference_row.tax_amount,
150 qty=1.0,
151 amount=reference_row.tax_amount,
152 stock_uom=frappe.db.get_single_value("Stock Settings", "stock_uom") or _("Nos"),
153 tax_rate=tax.rate,
154 tax_amount=(reference_row.tax_amount * tax.rate) / 100,
155 net_amount=reference_row.tax_amount,
Rohit Waghchaurec10064a2019-09-23 17:39:55 +0530156 taxable_amount=reference_row.tax_amount,
Rohit Waghchaure58f489f2019-04-01 17:50:31 +0530157 item_tax_rate={tax.account_head: tax.rate},
Gaurav2670ad72019-02-19 10:17:17 +0530158 charges=True
159 )
160 )
161
Gauravf1e28e02019-02-13 16:46:24 +0530162 #Check item tax rates if tax rate is zero.
163 if tax.rate == 0:
164 for item in items:
Rohit Waghchaure58f489f2019-04-01 17:50:31 +0530165 item_tax_rate = item.item_tax_rate
166 if isinstance(item.item_tax_rate, string_types):
167 item_tax_rate = json.loads(item.item_tax_rate)
168
169 if item_tax_rate and tax.account_head in item_tax_rate:
Gaurav2670ad72019-02-19 10:17:17 +0530170 key = cstr(item_tax_rate[tax.account_head])
Rohit Waghchaure58f489f2019-04-01 17:50:31 +0530171 if key not in summary_data:
172 summary_data.setdefault(key, {"tax_amount": 0.0, "taxable_amount": 0.0,
173 "tax_exemption_reason": "", "tax_exemption_law": ""})
174
Gauravf1e28e02019-02-13 16:46:24 +0530175 summary_data[key]["tax_amount"] += item.tax_amount
176 summary_data[key]["taxable_amount"] += item.net_amount
177 if key == "0.0":
178 summary_data[key]["tax_exemption_reason"] = tax.tax_exemption_reason
179 summary_data[key]["tax_exemption_law"] = tax.tax_exemption_law
180
Rohit Waghchaurec10064a2019-09-23 17:39:55 +0530181 if summary_data.get("0.0") and tax.charge_type in ["On Previous Row Total",
182 "On Previous Row Amount"]:
183 summary_data[key]["taxable_amount"] = tax.total
184
Gauravf1e28e02019-02-13 16:46:24 +0530185 if summary_data == {}: #Implies that Zero VAT has not been set on any item.
186 summary_data.setdefault("0.0", {"tax_amount": 0.0, "taxable_amount": tax.total,
187 "tax_exemption_reason": tax.tax_exemption_reason, "tax_exemption_law": tax.tax_exemption_law})
188
189 else:
190 item_wise_tax_detail = json.loads(tax.item_wise_tax_detail)
191 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 +0530192 key = cstr(tax.rate)
Gauravf1e28e02019-02-13 16:46:24 +0530193 if not summary_data.get(key): summary_data.setdefault(key, {"tax_amount": 0.0, "taxable_amount": 0.0})
194 summary_data[key]["tax_amount"] += rate_item[1][1]
195 summary_data[key]["taxable_amount"] += sum([item.net_amount for item in items if item.item_code == rate_item[0]])
196
Gaurav2670ad72019-02-19 10:17:17 +0530197 for item in items:
198 key = cstr(tax.rate)
199 if item.get("charges"):
200 if not summary_data.get(key): summary_data.setdefault(key, {"taxable_amount": 0.0})
201 summary_data[key]["taxable_amount"] += item.taxable_amount
202
Gauravf1e28e02019-02-13 16:46:24 +0530203 return summary_data
204
205#Preflight for successful e-invoice export.
206def sales_invoice_validate(doc):
207 #Validate company
rohitwaghchaureef3f8642019-02-20 15:47:06 +0530208 if doc.doctype != 'Sales Invoice':
209 return
210
Gauravf1e28e02019-02-13 16:46:24 +0530211 if not doc.company_address:
212 frappe.throw(_("Please set an Address on the Company '%s'" % doc.company), title=_("E-Invoicing Information Missing"))
213 else:
Rohit Waghchaure74cfe572019-02-26 20:08:26 +0530214 validate_address(doc.company_address)
Gauravf1e28e02019-02-13 16:46:24 +0530215
Rohit Waghchaure0f98cb82019-02-26 15:01:30 +0530216 company_fiscal_regime = frappe.get_cached_value("Company", doc.company, 'fiscal_regime')
217 if not company_fiscal_regime:
218 frappe.throw(_("Fiscal Regime is mandatory, kindly set the fiscal regime in the company {0}")
219 .format(doc.company))
220 else:
221 doc.company_fiscal_regime = company_fiscal_regime
222
Gauravbd80fd12019-03-28 12:18:03 +0530223 doc.company_tax_id = frappe.get_cached_value("Company", doc.company, 'tax_id')
224 doc.company_fiscal_code = frappe.get_cached_value("Company", doc.company, 'fiscal_code')
Gauravf1e28e02019-02-13 16:46:24 +0530225 if not doc.company_tax_id and not doc.company_fiscal_code:
226 frappe.throw(_("Please set either the Tax ID or Fiscal Code on Company '%s'" % doc.company), title=_("E-Invoicing Information Missing"))
227
228 #Validate customer details
Gaurav010acf72019-03-28 10:42:23 +0530229 customer = frappe.get_doc("Customer", doc.customer)
230
Rohit Waghchaure68a14562019-05-22 13:17:46 +0530231 if customer.customer_type == "Individual":
Gaurav010acf72019-03-28 10:42:23 +0530232 doc.customer_fiscal_code = customer.fiscal_code
Gauravf1e28e02019-02-13 16:46:24 +0530233 if not doc.customer_fiscal_code:
234 frappe.throw(_("Please set Fiscal Code for the customer '%s'" % doc.customer), title=_("E-Invoicing Information Missing"))
235 else:
Gaurav010acf72019-03-28 10:42:23 +0530236 if customer.is_public_administration:
237 doc.customer_fiscal_code = customer.fiscal_code
Gauravf1e28e02019-02-13 16:46:24 +0530238 if not doc.customer_fiscal_code:
239 frappe.throw(_("Please set Fiscal Code for the public administration '%s'" % doc.customer), title=_("E-Invoicing Information Missing"))
240 else:
Gaurav010acf72019-03-28 10:42:23 +0530241 doc.tax_id = customer.tax_id
Gauravf1e28e02019-02-13 16:46:24 +0530242 if not doc.tax_id:
243 frappe.throw(_("Please set Tax ID for the customer '%s'" % doc.customer), title=_("E-Invoicing Information Missing"))
244
245 if not doc.customer_address:
246 frappe.throw(_("Please set the Customer Address"), title=_("E-Invoicing Information Missing"))
247 else:
Rohit Waghchaure74cfe572019-02-26 20:08:26 +0530248 validate_address(doc.customer_address)
Gauravf1e28e02019-02-13 16:46:24 +0530249
250 if not len(doc.taxes):
251 frappe.throw(_("Please set at least one row in the Taxes and Charges Table"), title=_("E-Invoicing Information Missing"))
252 else:
253 for row in doc.taxes:
254 if row.rate == 0 and row.tax_amount == 0 and not row.tax_exemption_reason:
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530255 frappe.throw(_("Row {0}: Please set at Tax Exemption Reason in Sales Taxes and Charges").format(row.idx),
Gauravf1e28e02019-02-13 16:46:24 +0530256 title=_("E-Invoicing Information Missing"))
257
Rohit Waghchaure0f98cb82019-02-26 15:01:30 +0530258 for schedule in doc.payment_schedule:
259 if schedule.mode_of_payment and not schedule.mode_of_payment_code:
260 schedule.mode_of_payment_code = frappe.get_cached_value('Mode of Payment',
261 schedule.mode_of_payment, 'mode_of_payment_code')
Gauravf1e28e02019-02-13 16:46:24 +0530262
263#Ensure payment details are valid for e-invoice.
rohitwaghchaurec18e9252019-02-20 17:13:15 +0530264def sales_invoice_on_submit(doc, method):
Gauravf1e28e02019-02-13 16:46:24 +0530265 #Validate payment details
rohitwaghchaurec18e9252019-02-20 17:13:15 +0530266 if get_company_country(doc.company) not in ['Italy',
267 'Italia', 'Italian Republic', 'Repubblica Italiana']:
268 return
269
Gauravf1e28e02019-02-13 16:46:24 +0530270 if not len(doc.payment_schedule):
271 frappe.throw(_("Please set the Payment Schedule"), title=_("E-Invoicing Information Missing"))
272 else:
273 for schedule in doc.payment_schedule:
274 if not schedule.mode_of_payment:
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530275 frappe.throw(_("Row {0}: Please set the Mode of Payment in Payment Schedule").format(schedule.idx),
Gauravf1e28e02019-02-13 16:46:24 +0530276 title=_("E-Invoicing Information Missing"))
Gaurav2670ad72019-02-19 10:17:17 +0530277 elif not frappe.db.get_value("Mode of Payment", schedule.mode_of_payment, "mode_of_payment_code"):
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530278 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 +0530279 title=_("E-Invoicing Information Missing"))
Gauravf1e28e02019-02-13 16:46:24 +0530280
281 prepare_and_attach_invoice(doc)
282
Gauravb30a9b12019-03-01 12:33:19 +0530283def prepare_and_attach_invoice(doc, replace=False):
284 progressive_name, progressive_number = get_progressive_name_and_number(doc, replace)
Gauravf1e28e02019-02-13 16:46:24 +0530285
286 invoice = prepare_invoice(doc, progressive_number)
rohitwaghchaurecdcff6c2019-09-09 10:15:01 +0530287 item_meta = frappe.get_meta("Sales Invoice Item")
288
289 invoice_xml = frappe.render_template('erpnext/regional/italy/e-invoice.xml',
290 context={"doc": invoice, "item_meta": item_meta}, is_path=True)
291
Rohit Waghchaure0f98cb82019-02-26 15:01:30 +0530292 invoice_xml = invoice_xml.replace("&", "&amp;")
Gauravf1e28e02019-02-13 16:46:24 +0530293
294 xml_filename = progressive_name + ".xml"
Saurabhacf83792019-02-24 08:57:16 +0530295
296 _file = frappe.get_doc({
297 "doctype": "File",
298 "file_name": xml_filename,
299 "attached_to_doctype": doc.doctype,
300 "attached_to_name": doc.name,
301 "is_private": True,
302 "content": invoice_xml
303 })
304 _file.save()
Aditya Hase234d3572019-05-01 11:48:10 +0530305 return _file
Gauravb30a9b12019-03-01 12:33:19 +0530306
307@frappe.whitelist()
308def generate_single_invoice(docname):
309 doc = frappe.get_doc("Sales Invoice", docname)
310
Rohit Waghchaure1b7059b2019-03-12 17:44:29 +0530311
Gauravb30a9b12019-03-01 12:33:19 +0530312 e_invoice = prepare_and_attach_invoice(doc, True)
313
Rohit Waghchaure1b7059b2019-03-12 17:44:29 +0530314 return e_invoice.file_name
315
316@frappe.whitelist()
317def download_e_invoice_file(file_name):
Gauravb30a9b12019-03-01 12:33:19 +0530318 content = None
Rohit Waghchaure1b7059b2019-03-12 17:44:29 +0530319 with open(frappe.get_site_path('private', 'files', file_name), "r") as f:
Gauravb30a9b12019-03-01 12:33:19 +0530320 content = f.read()
321
Rohit Waghchaure1b7059b2019-03-12 17:44:29 +0530322 frappe.local.response.filename = file_name
Gauravb30a9b12019-03-01 12:33:19 +0530323 frappe.local.response.filecontent = content
324 frappe.local.response.type = "download"
Gauravf1e28e02019-02-13 16:46:24 +0530325
326#Delete e-invoice attachment on cancel.
rohitwaghchaurec18e9252019-02-20 17:13:15 +0530327def sales_invoice_on_cancel(doc, method):
328 if get_company_country(doc.company) not in ['Italy',
329 'Italia', 'Italian Republic', 'Repubblica Italiana']:
330 return
331
Gauravf1e28e02019-02-13 16:46:24 +0530332 for attachment in get_e_invoice_attachments(doc):
333 remove_file(attachment.name, attached_to_doctype=doc.doctype, attached_to_name=doc.name)
334
rohitwaghchaurec18e9252019-02-20 17:13:15 +0530335def get_company_country(company):
336 return frappe.get_cached_value('Company', company, 'country')
337
Gauravf1e28e02019-02-13 16:46:24 +0530338def get_e_invoice_attachments(invoice):
Mangesh-Khairnar359a73e2019-07-04 11:37:20 +0530339 if not invoice.company_tax_id:
340 return []
341
Gauravf1e28e02019-02-13 16:46:24 +0530342 out = []
343 attachments = get_attachments(invoice.doctype, invoice.name)
344 company_tax_id = invoice.company_tax_id if invoice.company_tax_id.startswith("IT") else "IT" + invoice.company_tax_id
345
346 for attachment in attachments:
Rohit Waghchaure0f98cb82019-02-26 15:01:30 +0530347 if attachment.file_name and attachment.file_name.startswith(company_tax_id) and attachment.file_name.endswith(".xml"):
Gauravf1e28e02019-02-13 16:46:24 +0530348 out.append(attachment)
349
350 return out
351
Rohit Waghchaure74cfe572019-02-26 20:08:26 +0530352def validate_address(address_name):
353 fields = ["pincode", "city", "country_code"]
354 data = frappe.get_cached_value("Address", address_name, fields, as_dict=1) or {}
Gauravf1e28e02019-02-13 16:46:24 +0530355
Rohit Waghchaure74cfe572019-02-26 20:08:26 +0530356 for field in fields:
357 if not data.get(field):
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530358 frappe.throw(_("Please set {0} for address {1}").format(field.replace('-',''), address_name),
Rohit Waghchaure74cfe572019-02-26 20:08:26 +0530359 title=_("E-Invoicing Information Missing"))
Gauravf1e28e02019-02-13 16:46:24 +0530360
361def get_unamended_name(doc):
362 attributes = ["naming_series", "amended_from"]
363 for attribute in attributes:
364 if not hasattr(doc, attribute):
365 return doc.name
366
367 if doc.amended_from:
368 return "-".join(doc.name.split("-")[:-1])
369 else:
370 return doc.name
371
Gauravb30a9b12019-03-01 12:33:19 +0530372def get_progressive_name_and_number(doc, replace=False):
373 if replace:
374 for attachment in get_e_invoice_attachments(doc):
375 remove_file(attachment.name, attached_to_doctype=doc.doctype, attached_to_name=doc.name)
376 filename = attachment.file_name.split(".xml")[0]
377 return filename, filename.split("_")[1]
378
Gauravf1e28e02019-02-13 16:46:24 +0530379 company_tax_id = doc.company_tax_id if doc.company_tax_id.startswith("IT") else "IT" + doc.company_tax_id
380 progressive_name = frappe.model.naming.make_autoname(company_tax_id + "_.#####")
381 progressive_number = progressive_name.split("_")[1]
382
Gaurav3f046132019-02-19 16:28:22 +0530383 return progressive_name, progressive_number
384
Gaurav Naik3bf0acb2019-02-20 12:08:53 +0530385def set_state_code(doc, method):
Rohit Waghchaure74cfe572019-02-26 20:08:26 +0530386 if doc.get('country_code'):
387 doc.country_code = doc.country_code.upper()
388
deepeshgarg0071915e152019-02-21 17:55:57 +0530389 if not doc.get('state'):
390 return
391
Gaurav3f046132019-02-19 16:28:22 +0530392 if not (hasattr(doc, "state_code") and doc.country in ["Italy", "Italia", "Italian Republic", "Repubblica Italiana"]):
393 return
394
395 state_codes_lower = {key.lower():value for key,value in state_codes.items()}
Rohit Waghchaure4ef924d2019-03-01 16:24:54 +0530396
397 state = doc.get('state','').lower()
398 if state_codes_lower.get(state):
399 doc.state_code = state_codes_lower.get(state)