blob: 435faea4c9700ffabf9e320434ebc1fe77123164 [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 _
7from frappe.utils.file_manager import save_file, remove_file
8from frappe.desk.form.load import get_attachments
Gaurav3f046132019-02-19 16:28:22 +05309from erpnext.regional.italy import state_codes
Gauravf1e28e02019-02-13 16:46:24 +053010
11
12def update_itemised_tax_data(doc):
13 if not doc.taxes: return
14
15 itemised_tax = get_itemised_tax(doc.taxes)
16
17 for row in doc.items:
18 tax_rate = 0.0
19 if itemised_tax.get(row.item_code):
20 tax_rate = sum([tax.get('tax_rate', 0) for d, tax in itemised_tax.get(row.item_code).items()])
21
22 row.tax_rate = flt(tax_rate, row.precision("tax_rate"))
23 row.tax_amount = flt((row.net_amount * tax_rate) / 100, row.precision("net_amount"))
24 row.total_amount = flt((row.net_amount + row.tax_amount), row.precision("total_amount"))
25
26@frappe.whitelist()
27def export_invoices(filters=None):
28 saved_xmls = []
29
30 invoices = frappe.get_all("Sales Invoice", filters=get_conditions(filters), fields=["*"])
31
32 for invoice in invoices:
33 attachments = get_e_invoice_attachments(invoice)
34 saved_xmls += [attachment.file_name for attachment in attachments]
35
36 zip_filename = "{0}-einvoices.zip".format(frappe.utils.get_datetime().strftime("%Y%m%d_%H%M%S"))
37
38 download_zip(saved_xmls, zip_filename)
39
40
41@frappe.whitelist()
42def prepare_invoice(invoice, progressive_number):
43 #set company information
44 company = frappe.get_doc("Company", invoice.company)
45
46 invoice.progressive_number = progressive_number
47 invoice.unamended_name = get_unamended_name(invoice)
48 invoice.company_data = company
49 company_address = frappe.get_doc("Address", invoice.company_address)
50 invoice.company_address_data = company_address
51
52 #Set invoice type
53 if invoice.is_return and invoice.return_against:
54 invoice.type_of_document = "TD04" #Credit Note (Nota di Credito)
55 invoice.return_against_unamended = get_unamended_name(frappe.get_doc("Sales Invoice", invoice.return_against))
56 else:
57 invoice.type_of_document = "TD01" #Sales Invoice (Fattura)
58
59 #set customer information
60 invoice.customer_data = frappe.get_doc("Customer", invoice.customer)
61 customer_address = frappe.get_doc("Address", invoice.customer_address)
62 invoice.customer_address_data = customer_address
63
64 if invoice.shipping_address_name:
65 invoice.shipping_address_data = frappe.get_doc("Address", invoice.shipping_address_name)
66
67 if invoice.customer_data.is_public_administration:
68 invoice.transmission_format_code = "FPA12"
69 else:
70 invoice.transmission_format_code = "FPR12"
71
Gaurav2670ad72019-02-19 10:17:17 +053072 invoice.e_invoice_items = [item for item in invoice.items]
73 tax_data = get_invoice_summary(invoice.e_invoice_items, invoice.taxes)
Gauravf1e28e02019-02-13 16:46:24 +053074 invoice.tax_data = tax_data
75
76 #Check if stamp duty (Bollo) of 2 EUR exists.
77 stamp_duty_charge_row = next((tax for tax in invoice.taxes if tax.charge_type == _("Actual") and tax.tax_amount == 2.0 ), None)
78 if stamp_duty_charge_row:
79 invoice.stamp_duty = stamp_duty_charge_row.tax_amount
80
Gaurav2670ad72019-02-19 10:17:17 +053081 for item in invoice.e_invoice_items:
82 if item.tax_rate == 0.0 and item.tax_amount == 0.0:
Gauravf1e28e02019-02-13 16:46:24 +053083 item.tax_exemption_reason = tax_data["0.0"]["tax_exemption_reason"]
84
Rohit Waghchaure1b7059b2019-03-12 17:44:29 +053085 customer_po_data = {}
86 for d in invoice.e_invoice_items:
87 if (d.customer_po_no and d.customer_po_date
88 and d.customer_po_no not in customer_po_data):
89 customer_po_data[d.customer_po_no] = d.customer_po_date
90
91 invoice.customer_po_data = customer_po_data
92
Gauravf1e28e02019-02-13 16:46:24 +053093 return invoice
94
95def get_conditions(filters):
96 filters = json.loads(filters)
97
98 conditions = {"docstatus": 1}
99
100 if filters.get("company"): conditions["company"] = filters["company"]
101 if filters.get("customer"): conditions["customer"] = filters["customer"]
102
103 if filters.get("from_date"): conditions["posting_date"] = (">=", filters["from_date"])
104 if filters.get("to_date"): conditions["posting_date"] = ("<=", filters["to_date"])
105
106 if filters.get("from_date") and filters.get("to_date"):
107 conditions["posting_date"] = ("between", [filters.get("from_date"), filters.get("to_date")])
108
109 return conditions
110
111#TODO: Use function from frappe once PR #6853 is merged.
112def download_zip(files, output_filename):
113 from zipfile import ZipFile
114
115 input_files = [frappe.get_site_path('private', 'files', filename) for filename in files]
116 output_path = frappe.get_site_path('private', 'files', output_filename)
117
118 with ZipFile(output_path, 'w') as output_zip:
119 for input_file in input_files:
120 output_zip.write(input_file, arcname=os.path.basename(input_file))
121
122 with open(output_path, 'rb') as fileobj:
123 filedata = fileobj.read()
124
125 frappe.local.response.filename = output_filename
126 frappe.local.response.filecontent = filedata
127 frappe.local.response.type = "download"
128
129def get_invoice_summary(items, taxes):
130 summary_data = frappe._dict()
131 for tax in taxes:
132 #Include only VAT charges.
133 if tax.charge_type == "Actual":
134 continue
135
Gaurav2670ad72019-02-19 10:17:17 +0530136 #Charges to appear as items in the e-invoice.
137 if tax.charge_type in ["On Previous Row Total", "On Previous Row Amount"]:
138 reference_row = next((row for row in taxes if row.idx == int(tax.row_id or 0)), None)
139 if reference_row:
140 items.append(
141 frappe._dict(
142 idx=len(items)+1,
143 item_code=reference_row.description,
144 item_name=reference_row.description,
rohitwaghchaure9673d0d2019-03-24 12:19:58 +0530145 description=reference_row.description,
Gaurav2670ad72019-02-19 10:17:17 +0530146 rate=reference_row.tax_amount,
147 qty=1.0,
148 amount=reference_row.tax_amount,
149 stock_uom=frappe.db.get_single_value("Stock Settings", "stock_uom") or _("Nos"),
150 tax_rate=tax.rate,
151 tax_amount=(reference_row.tax_amount * tax.rate) / 100,
152 net_amount=reference_row.tax_amount,
153 taxable_amount=reference_row.tax_amount,
154 item_tax_rate="{}",
155 charges=True
156 )
157 )
158
Gauravf1e28e02019-02-13 16:46:24 +0530159 #Check item tax rates if tax rate is zero.
160 if tax.rate == 0:
161 for item in items:
162 item_tax_rate = json.loads(item.item_tax_rate)
163 if tax.account_head in item_tax_rate:
Gaurav2670ad72019-02-19 10:17:17 +0530164 key = cstr(item_tax_rate[tax.account_head])
Gauravf1e28e02019-02-13 16:46:24 +0530165 summary_data.setdefault(key, {"tax_amount": 0.0, "taxable_amount": 0.0, "tax_exemption_reason": "", "tax_exemption_law": ""})
166 summary_data[key]["tax_amount"] += item.tax_amount
167 summary_data[key]["taxable_amount"] += item.net_amount
168 if key == "0.0":
169 summary_data[key]["tax_exemption_reason"] = tax.tax_exemption_reason
170 summary_data[key]["tax_exemption_law"] = tax.tax_exemption_law
171
172 if summary_data == {}: #Implies that Zero VAT has not been set on any item.
173 summary_data.setdefault("0.0", {"tax_amount": 0.0, "taxable_amount": tax.total,
174 "tax_exemption_reason": tax.tax_exemption_reason, "tax_exemption_law": tax.tax_exemption_law})
175
176 else:
177 item_wise_tax_detail = json.loads(tax.item_wise_tax_detail)
178 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 +0530179 key = cstr(tax.rate)
Gauravf1e28e02019-02-13 16:46:24 +0530180 if not summary_data.get(key): summary_data.setdefault(key, {"tax_amount": 0.0, "taxable_amount": 0.0})
181 summary_data[key]["tax_amount"] += rate_item[1][1]
182 summary_data[key]["taxable_amount"] += sum([item.net_amount for item in items if item.item_code == rate_item[0]])
183
Gaurav2670ad72019-02-19 10:17:17 +0530184 for item in items:
185 key = cstr(tax.rate)
186 if item.get("charges"):
187 if not summary_data.get(key): summary_data.setdefault(key, {"taxable_amount": 0.0})
188 summary_data[key]["taxable_amount"] += item.taxable_amount
189
Gauravf1e28e02019-02-13 16:46:24 +0530190 return summary_data
191
192#Preflight for successful e-invoice export.
193def sales_invoice_validate(doc):
194 #Validate company
rohitwaghchaureef3f8642019-02-20 15:47:06 +0530195 if doc.doctype != 'Sales Invoice':
196 return
197
Gauravf1e28e02019-02-13 16:46:24 +0530198 if not doc.company_address:
199 frappe.throw(_("Please set an Address on the Company '%s'" % doc.company), title=_("E-Invoicing Information Missing"))
200 else:
Rohit Waghchaure74cfe572019-02-26 20:08:26 +0530201 validate_address(doc.company_address)
Gauravf1e28e02019-02-13 16:46:24 +0530202
Rohit Waghchaure0f98cb82019-02-26 15:01:30 +0530203 company_fiscal_regime = frappe.get_cached_value("Company", doc.company, 'fiscal_regime')
204 if not company_fiscal_regime:
205 frappe.throw(_("Fiscal Regime is mandatory, kindly set the fiscal regime in the company {0}")
206 .format(doc.company))
207 else:
208 doc.company_fiscal_regime = company_fiscal_regime
209
Gauravbd80fd12019-03-28 12:18:03 +0530210 doc.company_tax_id = frappe.get_cached_value("Company", doc.company, 'tax_id')
211 doc.company_fiscal_code = frappe.get_cached_value("Company", doc.company, 'fiscal_code')
Gauravf1e28e02019-02-13 16:46:24 +0530212 if not doc.company_tax_id and not doc.company_fiscal_code:
213 frappe.throw(_("Please set either the Tax ID or Fiscal Code on Company '%s'" % doc.company), title=_("E-Invoicing Information Missing"))
214
215 #Validate customer details
Gaurav010acf72019-03-28 10:42:23 +0530216 customer = frappe.get_doc("Customer", doc.customer)
217
218 if customer.customer_type == _("Individual"):
219 doc.customer_fiscal_code = customer.fiscal_code
Gauravf1e28e02019-02-13 16:46:24 +0530220 if not doc.customer_fiscal_code:
221 frappe.throw(_("Please set Fiscal Code for the customer '%s'" % doc.customer), title=_("E-Invoicing Information Missing"))
222 else:
Gaurav010acf72019-03-28 10:42:23 +0530223 if customer.is_public_administration:
224 doc.customer_fiscal_code = customer.fiscal_code
Gauravf1e28e02019-02-13 16:46:24 +0530225 if not doc.customer_fiscal_code:
226 frappe.throw(_("Please set Fiscal Code for the public administration '%s'" % doc.customer), title=_("E-Invoicing Information Missing"))
227 else:
Gaurav010acf72019-03-28 10:42:23 +0530228 doc.tax_id = customer.tax_id
Gauravf1e28e02019-02-13 16:46:24 +0530229 if not doc.tax_id:
230 frappe.throw(_("Please set Tax ID for the customer '%s'" % doc.customer), title=_("E-Invoicing Information Missing"))
231
232 if not doc.customer_address:
233 frappe.throw(_("Please set the Customer Address"), title=_("E-Invoicing Information Missing"))
234 else:
Rohit Waghchaure74cfe572019-02-26 20:08:26 +0530235 validate_address(doc.customer_address)
Gauravf1e28e02019-02-13 16:46:24 +0530236
237 if not len(doc.taxes):
238 frappe.throw(_("Please set at least one row in the Taxes and Charges Table"), title=_("E-Invoicing Information Missing"))
239 else:
240 for row in doc.taxes:
241 if row.rate == 0 and row.tax_amount == 0 and not row.tax_exemption_reason:
242 frappe.throw(_("Row {0}: Please set at Tax Exemption Reason in Sales Taxes and Charges".format(row.idx)),
243 title=_("E-Invoicing Information Missing"))
244
Rohit Waghchaure0f98cb82019-02-26 15:01:30 +0530245 for schedule in doc.payment_schedule:
246 if schedule.mode_of_payment and not schedule.mode_of_payment_code:
247 schedule.mode_of_payment_code = frappe.get_cached_value('Mode of Payment',
248 schedule.mode_of_payment, 'mode_of_payment_code')
Gauravf1e28e02019-02-13 16:46:24 +0530249
250#Ensure payment details are valid for e-invoice.
rohitwaghchaurec18e9252019-02-20 17:13:15 +0530251def sales_invoice_on_submit(doc, method):
Gauravf1e28e02019-02-13 16:46:24 +0530252 #Validate payment details
rohitwaghchaurec18e9252019-02-20 17:13:15 +0530253 if get_company_country(doc.company) not in ['Italy',
254 'Italia', 'Italian Republic', 'Repubblica Italiana']:
255 return
256
Gauravf1e28e02019-02-13 16:46:24 +0530257 if not len(doc.payment_schedule):
258 frappe.throw(_("Please set the Payment Schedule"), title=_("E-Invoicing Information Missing"))
259 else:
260 for schedule in doc.payment_schedule:
261 if not schedule.mode_of_payment:
262 frappe.throw(_("Row {0}: Please set the Mode of Payment in Payment Schedule".format(schedule.idx)),
263 title=_("E-Invoicing Information Missing"))
Gaurav2670ad72019-02-19 10:17:17 +0530264 elif not frappe.db.get_value("Mode of Payment", schedule.mode_of_payment, "mode_of_payment_code"):
265 frappe.throw(_("Row {0}: Please set the correct code on Mode of Payment {1}".format(schedule.idx, schedule.mode_of_payment)),
266 title=_("E-Invoicing Information Missing"))
Gauravf1e28e02019-02-13 16:46:24 +0530267
268 prepare_and_attach_invoice(doc)
269
Gauravb30a9b12019-03-01 12:33:19 +0530270def prepare_and_attach_invoice(doc, replace=False):
271 progressive_name, progressive_number = get_progressive_name_and_number(doc, replace)
Gauravf1e28e02019-02-13 16:46:24 +0530272
273 invoice = prepare_invoice(doc, progressive_number)
274 invoice_xml = frappe.render_template('erpnext/regional/italy/e-invoice.xml', context={"doc": invoice}, is_path=True)
Rohit Waghchaure0f98cb82019-02-26 15:01:30 +0530275 invoice_xml = invoice_xml.replace("&", "&amp;")
Gauravf1e28e02019-02-13 16:46:24 +0530276
277 xml_filename = progressive_name + ".xml"
Gauravb30a9b12019-03-01 12:33:19 +0530278 return save_file(xml_filename, invoice_xml, dt=doc.doctype, dn=doc.name, is_private=True)
279
280@frappe.whitelist()
281def generate_single_invoice(docname):
282 doc = frappe.get_doc("Sales Invoice", docname)
283
Rohit Waghchaure1b7059b2019-03-12 17:44:29 +0530284
Gauravb30a9b12019-03-01 12:33:19 +0530285 e_invoice = prepare_and_attach_invoice(doc, True)
286
Rohit Waghchaure1b7059b2019-03-12 17:44:29 +0530287 return e_invoice.file_name
288
289@frappe.whitelist()
290def download_e_invoice_file(file_name):
Gauravb30a9b12019-03-01 12:33:19 +0530291 content = None
Rohit Waghchaure1b7059b2019-03-12 17:44:29 +0530292 with open(frappe.get_site_path('private', 'files', file_name), "r") as f:
Gauravb30a9b12019-03-01 12:33:19 +0530293 content = f.read()
294
Rohit Waghchaure1b7059b2019-03-12 17:44:29 +0530295 frappe.local.response.filename = file_name
Gauravb30a9b12019-03-01 12:33:19 +0530296 frappe.local.response.filecontent = content
297 frappe.local.response.type = "download"
Gauravf1e28e02019-02-13 16:46:24 +0530298
299#Delete e-invoice attachment on cancel.
rohitwaghchaurec18e9252019-02-20 17:13:15 +0530300def sales_invoice_on_cancel(doc, method):
301 if get_company_country(doc.company) not in ['Italy',
302 'Italia', 'Italian Republic', 'Repubblica Italiana']:
303 return
304
Gauravf1e28e02019-02-13 16:46:24 +0530305 for attachment in get_e_invoice_attachments(doc):
306 remove_file(attachment.name, attached_to_doctype=doc.doctype, attached_to_name=doc.name)
307
rohitwaghchaurec18e9252019-02-20 17:13:15 +0530308def get_company_country(company):
309 return frappe.get_cached_value('Company', company, 'country')
310
Gauravf1e28e02019-02-13 16:46:24 +0530311def get_e_invoice_attachments(invoice):
312 out = []
313 attachments = get_attachments(invoice.doctype, invoice.name)
314 company_tax_id = invoice.company_tax_id if invoice.company_tax_id.startswith("IT") else "IT" + invoice.company_tax_id
315
316 for attachment in attachments:
Rohit Waghchaure0f98cb82019-02-26 15:01:30 +0530317 if attachment.file_name and attachment.file_name.startswith(company_tax_id) and attachment.file_name.endswith(".xml"):
Gauravf1e28e02019-02-13 16:46:24 +0530318 out.append(attachment)
319
320 return out
321
Rohit Waghchaure74cfe572019-02-26 20:08:26 +0530322def validate_address(address_name):
323 fields = ["pincode", "city", "country_code"]
324 data = frappe.get_cached_value("Address", address_name, fields, as_dict=1) or {}
Gauravf1e28e02019-02-13 16:46:24 +0530325
Rohit Waghchaure74cfe572019-02-26 20:08:26 +0530326 for field in fields:
327 if not data.get(field):
328 frappe.throw(_("Please set {0} for address {1}".format(field.replace('-',''), address_name)),
329 title=_("E-Invoicing Information Missing"))
Gauravf1e28e02019-02-13 16:46:24 +0530330
331def get_unamended_name(doc):
332 attributes = ["naming_series", "amended_from"]
333 for attribute in attributes:
334 if not hasattr(doc, attribute):
335 return doc.name
336
337 if doc.amended_from:
338 return "-".join(doc.name.split("-")[:-1])
339 else:
340 return doc.name
341
Gauravb30a9b12019-03-01 12:33:19 +0530342def get_progressive_name_and_number(doc, replace=False):
343 if replace:
344 for attachment in get_e_invoice_attachments(doc):
345 remove_file(attachment.name, attached_to_doctype=doc.doctype, attached_to_name=doc.name)
346 filename = attachment.file_name.split(".xml")[0]
347 return filename, filename.split("_")[1]
348
Gauravf1e28e02019-02-13 16:46:24 +0530349 company_tax_id = doc.company_tax_id if doc.company_tax_id.startswith("IT") else "IT" + doc.company_tax_id
350 progressive_name = frappe.model.naming.make_autoname(company_tax_id + "_.#####")
351 progressive_number = progressive_name.split("_")[1]
352
Gaurav3f046132019-02-19 16:28:22 +0530353 return progressive_name, progressive_number
354
Gaurav Naik3bf0acb2019-02-20 12:08:53 +0530355def set_state_code(doc, method):
Rohit Waghchaure74cfe572019-02-26 20:08:26 +0530356 if doc.get('country_code'):
357 doc.country_code = doc.country_code.upper()
358
deepeshgarg0071915e152019-02-21 17:55:57 +0530359 if not doc.get('state'):
360 return
361
Gaurav3f046132019-02-19 16:28:22 +0530362 if not (hasattr(doc, "state_code") and doc.country in ["Italy", "Italia", "Italian Republic", "Repubblica Italiana"]):
363 return
364
365 state_codes_lower = {key.lower():value for key,value in state_codes.items()}
Rohit Waghchaure4ef924d2019-03-01 16:24:54 +0530366
367 state = doc.get('state','').lower()
368 if state_codes_lower.get(state):
369 doc.state_code = state_codes_lower.get(state)