Corrupted Manual Sales Invoice

Hello,
I have created a manual sales invoice (I want to invoice a commission to a partner). While creating it, there was no problem.
After a while, I wanted to record the payment but I am unable to see the entry:

Now, I cannot even delete this invoice since it is submitted but I cannot even make any changes to it in order to get rid of it.
What has happened here? Any recommendations?

Thanks a lot for your help.
Sabine

Hi Sabine,

Can you check the browser’s javascript console? If there’s an error printed there, please paste it here.

-Anand.

Hi Anand,
sorry for the late reply.

There is the following error code: https://login.nanolive.ch/socket.io/?EIO=3&transport=polling&t=1451467531533-0 Failed to load resource: the server responded with a status of 404 (NOT FOUND)

Many thanks for your help.
Sabine

This error shouldn’t have caused the form to break. You need to look if there are other errors.

Hi Anand,
there are plenty of errors. The one I sent you before ends goes from -0 until this one here:

https://login.nanolive.ch/socket.io/?EIO=3&transport=polling&t=1451900221632-743 Failed to load resource: the server responded with a status of 404 (NOT FOUND)

After that, I found this errors:

jquery.min.js:4 Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience. For more help, check http://xhr.spec.whatwg.org/.
desk:1031 Uncaught TypeError: Cannot read property ‘replace’ of undefined
https://login.nanolive.ch/socket.io/?EIO=3&transport=polling&t=1451900226671-744 Failed to load resource: the server responded with a status of 404 (NOT FOUND)
https://login.nanolive.ch/socket.io/?EIO=3&transport=polling&t=1451900231714-745 Failed to load resource: the server responded with a status of 404 (NOT FOUND)
https://login.nanolive.ch/socket.io/?EIO=3&transport=polling&t=1451900236752-746 Failed to load resource: the server responded with a status of 404 (NOT

This is what’s the cause of the problem. Can you click on that line number and paste what the exact code is that is causing the problem?

Hi Anand,
when clicking on it, I get this code:

// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt

// print heading
cur_frm.pformat.print_heading = ‘Invoice’;

// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt

cur_frm.cscript.tax_table = “Sales Taxes and Charges”;
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt

cur_frm.cscript.tax_table = “Sales Taxes and Charges”;

// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt

// get tax rate
frappe.provide(“erpnext.taxes”);
frappe.provide(“erpnext.taxes.flags”);

frappe.ui.form.on(cur_frm.doctype, {
onload: function(frm) {
if(frm.get_field(“taxes”)) {
frm.set_query(“account_head”, “taxes”, function(doc) {
if(frm.cscript.tax_table == “Sales Taxes and Charges”) {
var account_type = [“Tax”, “Chargeable”, “Expense Account”];
} else {
var account_type = [“Tax”, “Chargeable”, “Income Account”];
}

			return {
				query: "erpnext.controllers.queries.tax_account_query",
				filters: {
					"account_type": account_type,
					"company": doc.company
				}
			}
		});

		frm.set_query("cost_center", "taxes", function(doc) {
			return {
				filters: {
					'company': doc.company,
					"is_group": 0
				}
			}
		});
	}
},
validate: function(frm) {
	// neither is absolutely mandatory
	if(frm.get_docfield("taxes")) {
		frm.get_docfield("taxes", "rate").reqd = 0;
		frm.get_docfield("taxes", "tax_amount").reqd = 0;
	}
	
},
taxes_on_form_rendered: function(frm) {
	erpnext.taxes.set_conditional_mandatory_rate_or_amount(frm);
}

});

cur_frm.cscript.account_head = function(doc, cdt, cdn) {
var d = locals[cdt][cdn];
if(!d.charge_type && d.account_head){
msgprint(“Please select Charge Type first”);
frappe.model.set_value(cdt, cdn, “account_head”, “”);
} else if(d.account_head && d.charge_type!==“Actual”) {
frappe.call({
type:“GET”,
method: “erpnext.controllers.accounts_controller.get_tax_rate”,
args: {“account_head”:d.account_head},
callback: function(r) {
frappe.model.set_value(cdt, cdn, “rate”, r.message || 0);
}
})
}
}

cur_frm.cscript.validate_taxes_and_charges = function(cdt, cdn) {
var d = locals[cdt][cdn];
var msg = “”;
if(!d.charge_type && (d.row_id || d.rate || d.tax_amount)) {
msg = __(“Please select Charge Type first”);
d.row_id = “”;
d.rate = d.tax_amount = 0.0;
} else if((d.charge_type == ‘Actual’ || d.charge_type == ‘On Net Total’) && d.row_id) {
msg = __(“Can refer row only if the charge type is ‘On Previous Row Amount’ or ‘Previous Row Total’”);
d.row_id = “”;
} else if((d.charge_type == ‘On Previous Row Amount’ || d.charge_type == ‘On Previous Row Total’) && d.row_id) {
if (d.idx == 1) {
msg = __(“Cannot select charge type as ‘On Previous Row Amount’ or ‘On Previous Row Total’ for first row”);
d.charge_type = ‘’;
} else if (!d.row_id) {
msg = __(“Please specify a valid Row ID for row {0} in table {1}”, [d.idx, __(d.doctype)]);
d.row_id = “”;
} else if(d.row_id && d.row_id >= d.idx) {
msg = __(“Cannot refer row number greater than or equal to current row number for this Charge type”);
d.row_id = “”;
}
}
if(msg) {
validated = false;
refresh_field(“taxes”);
frappe.throw(msg);
}

}

cur_frm.cscript.validate_inclusive_tax = function(tax) {
var actual_type_error = function() {
var msg = __(“Actual type tax cannot be included in Item rate in row {0}”, [tax.idx])
frappe.throw(msg);
};

var on_previous_row_error = function(row_range) {
	var msg = __("For row {0} in {1}. To include {2} in Item rate, rows {3} must also be included",
		[tax.idx, __(tax.doctype), tax.charge_type, row_range])
	frappe.throw(msg);
};

if(cint(tax.included_in_print_rate)) {
	if(tax.charge_type == "Actual") {
		// inclusive tax cannot be of type Actual
		actual_type_error();
	} else if(tax.charge_type == "On Previous Row Amount" &&
		!cint(this.frm.doc["taxes"][tax.row_id - 1].included_in_print_rate)) {
			// referred row should also be an inclusive tax
			on_previous_row_error(tax.row_id);
	} else if(tax.charge_type == "On Previous Row Total") {
		var taxes_not_included = $.map(this.frm.doc["taxes"].slice(0, tax.row_id),
			function(t) { return cint(t.included_in_print_rate) ? null : t; });
		if(taxes_not_included.length > 0) {
			// all rows above this tax should be inclusive
			on_previous_row_error(tax.row_id == 1 ? "1" : "1 - " + tax.row_id);
		}
	} else if(tax.category == "Valuation") {
		frappe.throw(__("Valuation type charges can not marked as Inclusive"));
	}
}

}

if(!erpnext.taxes.flags[cur_frm.cscript.tax_table]) {
erpnext.taxes.flags[cur_frm.cscript.tax_table] = true;

frappe.ui.form.on(cur_frm.cscript.tax_table, "row_id", function(frm, cdt, cdn) {
	cur_frm.cscript.validate_taxes_and_charges(cdt, cdn);
});

frappe.ui.form.on(cur_frm.cscript.tax_table, "rate", function(frm, cdt, cdn) {
	cur_frm.cscript.validate_taxes_and_charges(cdt, cdn);
});

frappe.ui.form.on(cur_frm.cscript.tax_table, "tax_amount", function(frm, cdt, cdn) {
	cur_frm.cscript.validate_taxes_and_charges(cdt, cdn);
});

frappe.ui.form.on(cur_frm.cscript.tax_table, "charge_type", function(frm, cdt, cdn) {
	cur_frm.cscript.validate_taxes_and_charges(cdt, cdn);
	erpnext.taxes.set_conditional_mandatory_rate_or_amount(frm);
});

frappe.ui.form.on(cur_frm.cscript.tax_table, "included_in_print_rate", function(frm, cdt, cdn) {
	var tax = frappe.get_doc(cdt, cdn);
	try {
		cur_frm.cscript.validate_taxes_and_charges(cdt, cdn);
		cur_frm.cscript.validate_inclusive_tax(tax);
	} catch(e) {
		tax.included_in_print_rate = 0;
		refresh_field("included_in_print_rate", tax.name, tax.parentfield);
		throw e;
	}
});

}

erpnext.taxes.set_conditional_mandatory_rate_or_amount = function(frm) {
var grid_row = frm.open_grid_row();
if(grid_row.doc.charge_type===“Actual”) {
grid_row.toggle_display(“tax_amount”, true);
grid_row.toggle_reqd(“tax_amount”, true);
grid_row.toggle_display(“rate”, false);
grid_row.toggle_reqd(“rate”, false);
} else {
grid_row.toggle_display(“rate”, true);
grid_row.toggle_reqd(“rate”, true);
grid_row.toggle_display(“tax_amount”, false);
grid_row.toggle_reqd(“tax_amount”, false);
}
}

// For customizing print
cur_frm.pformat.total = function(doc) { return ‘’; }
cur_frm.pformat.discount_amount = function(doc) { return ‘’; }
cur_frm.pformat.grand_total = function(doc) { return ‘’; }
cur_frm.pformat.rounded_total = function(doc) { return ‘’; }
cur_frm.pformat.in_words = function(doc) { return ‘’; }

cur_frm.pformat.taxes= function(doc){
//function to make row of table
var make_row = function(title, val, bold, is_negative) {
var bstart = ‘’; var bend = ‘’;
return ‘’ + (bold?bstart:‘’) + title + (bold?bend:‘’) + ‘’
+ ‘’ + (is_negative ? '- ’ : ‘’)
+ format_currency(val, doc.currency) + ‘’;
}

function print_hide(fieldname) {
	var doc_field = frappe.meta.get_docfield(doc.doctype, fieldname, doc.name);
	return doc_field.print_hide;
}

out ='';
if (!doc.print_without_amount) {
	var cl = doc.taxes || [];

	// outer table
	var out='<div><table class="noborder" style="width:100%"><tr><td style="width: 60%"></td><td>';

	// main table

	out +='<table class="noborder" style="width:100%">';

	if(!print_hide('total')) {
		out += make_row('Total', doc.total, 1);
	}

	// Discount Amount on net total
	if(!print_hide('discount_amount') && doc.apply_discount_on == "Net Total" && doc.discount_amount)
		out += make_row('Discount Amount', doc.discount_amount, 0, 1);

	// add rows
	if(cl.length){
		for(var i=0;i<cl.length;i++) {
			if(cl[i].tax_amount!=0 && !cl[i].included_in_print_rate)
				out += make_row(cl[i].description, cl[i].tax_amount, 0);
		}
	}

	// Discount Amount on grand total
	if(!print_hide('discount_amount') && doc.apply_discount_on == "Grand Total" && doc.discount_amount)
		out += make_row('Discount Amount', doc.discount_amount, 0, 1);

	// grand total
	if(!print_hide('grand_total'))
		out += make_row('Grand Total', doc.grand_total, 1);

	if(!print_hide('rounded_total'))
		out += make_row('Rounded Total', doc.rounded_total, 1);

	if(doc.in_words && !print_hide('in_words')) {
		out +='</table></td></tr>';
		out += '<tr><td colspan = "2">';
		out += '<table><tr><td style="width:25%;"><b>In Words</b></td>';
		out += '<td style="width:50%;">' + doc.in_words + '</td></tr>';
	}
	out += '</table></td></tr></table></div>';
}
return out;

}

frappe.provide(“erpnext.selling”);
frappe.require(“assets/erpnext/js/controllers/transaction.js”);

cur_frm.email_field = “contact_email”;

erpnext.selling.SellingController = erpnext.TransactionController.extend({
onload: function() {
this._super();
this.setup_queries();
},

setup_queries: function() {
	var me = this;

	this.frm.add_fetch("sales_partner", "commission_rate", "commission_rate");

	$.each([["customer_address", "customer_filter"],
		["shipping_address_name", "customer_filter"],
		["contact_person", "customer_filter"],
		["customer", "customer"],
		["lead", "lead"]],
		function(i, opts) {
			if(me.frm.fields_dict[opts[0]])
				me.frm.set_query(opts[0], erpnext.queries[opts[1]]);
		});

	if(this.frm.fields_dict.taxes_and_charges) {
		this.frm.set_query("taxes_and_charges", function() {
			return {
				filters: [
					['Sales Taxes and Charges Template', 'company', '=', me.frm.doc.company],
					['Sales Taxes and Charges Template', 'docstatus', '!=', 2]
				]
			}
		});
	}

	if(this.frm.fields_dict.selling_price_list) {
		this.frm.set_query("selling_price_list", function() {
			return { filters: { selling: 1 } };
		});
	}

	if(!this.frm.fields_dict["items"]) {
		return;
	}

	if(this.frm.fields_dict["items"].grid.get_field('item_code')) {
		this.frm.set_query("item_code", "items", function() {
			return {
				query: "erpnext.controllers.queries.item_query",
				filters: (me.frm.doc.order_type === "Maintenance" ?
					{'is_service_item': 1}:
					{'is_sales_item': 1	})
			}
		});
	}

	if(this.frm.fields_dict["items"].grid.get_field('batch_no')) {
		this.frm.set_query("batch_no", "items", function(doc, cdt, cdn) {
			var item = frappe.get_doc(cdt, cdn);
			if(!item.item_code) {
				frappe.throw(__("Please enter Item Code to get batch no"));
			} else {
				filters = {
					'item_code': item.item_code,
					'posting_date': me.frm.doc.posting_date || nowdate(),
				}
				if(item.warehouse) filters["warehouse"] = item.warehouse

				return {
					query : "erpnext.controllers.queries.get_batch_no",
					filters: filters
				}
			}
		});
	}

	if(this.frm.fields_dict.sales_team && this.frm.fields_dict.sales_team.grid.get_field("sales_person")) {
		this.frm.set_query("sales_person", "sales_team", erpnext.queries.not_a_group_filter);
	}
},

refresh: function() {
	this._super();
	this.frm.toggle_display("customer_name",
		(this.frm.doc.customer_name && this.frm.doc.customer_name!==this.frm.doc.customer));
	if(this.frm.fields_dict.packed_items) {
		var packing_list_exists = (this.frm.doc.packed_items || []).length;
		this.frm.toggle_display("packing_list", packing_list_exists ? true : false);
	}
	this.toggle_editable_price_list_rate();
},

customer: function() {
	var me = this;
	erpnext.utils.get_party_details(this.frm, null, null, function(){me.apply_pricing_rule()});
},

customer_address: function() {
	erpnext.utils.get_address_display(this.frm, "customer_address");
},

shipping_address_name: function() {
	erpnext.utils.get_address_display(this.frm, "shipping_address_name", "shipping_address");
},

sales_partner: function() {
	this.apply_pricing_rule();
},

campaign: function() {
	this.apply_pricing_rule();
},

selling_price_list: function() {
	this.apply_price_list();
},

price_list_rate: function(doc, cdt, cdn) {
	var item = frappe.get_doc(cdt, cdn);
	frappe.model.round_floats_in(item, ["price_list_rate", "discount_percentage"]);

	item.rate = flt(item.price_list_rate * (1 - item.discount_percentage / 100.0),
		precision("rate", item));

	this.calculate_taxes_and_totals();
},

discount_percentage: function(doc, cdt, cdn) {
	var item = frappe.get_doc(cdt, cdn);
	if(!item.price_list_rate) {
		item.discount_percentage = 0.0;
	} else {
		this.price_list_rate(doc, cdt, cdn);
	}
},

commission_rate: function() {
	this.calculate_commission();
	refresh_field("total_commission");
},

total_commission: function() {
	if(this.frm.doc.base_net_total) {
		frappe.model.round_floats_in(this.frm.doc, ["base_net_total", "total_commission"]);

		if(this.frm.doc.base_net_total < this.frm.doc.total_commission) {
			var msg = (__("[Error]") + " " +
				__(frappe.meta.get_label(this.frm.doc.doctype, "total_commission",
					this.frm.doc.name)) + " > " +
				__(frappe.meta.get_label(this.frm.doc.doctype, "base_net_total", this.frm.doc.name)));
			msgprint(msg);
			throw msg;
		}

		this.frm.set_value("commission_rate",
			flt(this.frm.doc.total_commission * 100.0 / this.frm.doc.base_net_total));
	}
},

allocated_percentage: function(doc, cdt, cdn) {
	var sales_person = frappe.get_doc(cdt, cdn);

	if(sales_person.allocated_percentage) {
		sales_person.allocated_percentage = flt(sales_person.allocated_percentage,
			precision("allocated_percentage", sales_person));
		sales_person.allocated_amount = flt(this.frm.doc.base_net_total *
			sales_person.allocated_percentage / 100.0,
			precision("allocated_amount", sales_person));

		refresh_field(["allocated_percentage", "allocated_amount"], sales_person.name,
			sales_person.parentfield);
	}
},

warehouse: function(doc, cdt, cdn) {
	var me = this;
	this.batch_no(doc, cdt, cdn);
	var item = frappe.get_doc(cdt, cdn);
	if(item.item_code && item.warehouse) {
		return this.frm.call({
			method: "erpnext.stock.get_item_details.get_available_qty",
			child: item,
			args: {
				item_code: item.item_code,
				warehouse: item.warehouse,
			},
		});
	}
},

toggle_editable_price_list_rate: function() {
	var df = frappe.meta.get_docfield(this.frm.doc.doctype + " Item", "price_list_rate", this.frm.doc.name);
	var editable_price_list_rate = cint(frappe.defaults.get_default("editable_price_list_rate"));

	if(df && editable_price_list_rate) {
		df.read_only = 0;
	}
},

calculate_commission: function() {
	if(this.frm.fields_dict.commission_rate) {
		if(this.frm.doc.commission_rate > 100) {
			var msg = __(frappe.meta.get_label(this.frm.doc.doctype, "commission_rate", this.frm.doc.name)) +
				" " + __("cannot be greater than 100");
			msgprint(msg);
			throw msg;
		}

		this.frm.doc.total_commission = flt(this.frm.doc.base_net_total * this.frm.doc.commission_rate / 100.0,
			precision("total_commission"));
	}
},

calculate_contribution: function() {
	var me = this;
	$.each(this.frm.doc.doctype.sales_team || [], function(i, sales_person) {
			frappe.model.round_floats_in(sales_person);
			if(sales_person.allocated_percentage) {
				sales_person.allocated_amount = flt(
					me.frm.doc.base_net_total * sales_person.allocated_percentage / 100.0,
					precision("allocated_amount", sales_person));
			}
		});
},

shipping_rule: function() {
	var me = this;
	if(this.frm.doc.shipping_rule) {
		return this.frm.call({
			doc: this.frm.doc,
			method: "apply_shipping_rule",
			callback: function(r) {
				if(!r.exc) {
					me.calculate_taxes_and_totals();
				}
			}
		})
	}
},

batch_no: function(doc, cdt, cdn) {
	var me = this;
	var item = frappe.get_doc(cdt, cdn);

	if(item.warehouse && item.item_code && item.batch_no) {
	    return this.frm.call({
	        method: "erpnext.stock.get_item_details.get_batch_qty",
	        child: item,
	        args: {
	           "batch_no": item.batch_no,
	           "warehouse": item.warehouse,
	           "item_code": item.item_code
	        },
	         "fieldname": "actual_batch_qty"
	    });
	}
},

set_dynamic_labels: function() {
	this._super();
	this.set_product_bundle_help(this.frm.doc);
},

set_product_bundle_help: function(doc) {
	if(!cur_frm.fields_dict.packing_list) return;
	if ((doc.packed_items || []).length) {
		$(cur_frm.fields_dict.packing_list.row.wrapper).toggle(true);

		if (inList(['Delivery Note', 'Sales Invoice'], doc.doctype)) {
			help_msg = "<div class='alert alert-warning'>" +
				__("For 'Product Bundle' items, Warehouse, Serial No and Batch No will be considered from the 'Packing List' table. If Warehouse and Batch No are same for all packing items for any 'Product Bundle' item, those values can be entered in the main Item table, values will be copied to 'Packing List' table.")+
			"</div>";
			frappe.meta.get_docfield(doc.doctype, 'product_bundle_help', doc.name).options = help_msg;
		}
	} else {
		$(cur_frm.fields_dict.packing_list.row.wrapper).toggle(false);
		if (inList(['Delivery Note', 'Sales Invoice'], doc.doctype)) {
			frappe.meta.get_docfield(doc.doctype, 'product_bundle_help', doc.name).options = '';
		}
	}
	refresh_field('product_bundle_help');
}

});

frappe.ui.form.on(cur_frm.doctype,“project_name”, function(frm) {
if(in_list([“Delivery Note”, “Sales Invoice”], frm.doc.doctype)) {
frappe.call({
method:‘erpnext.projects.doctype.project.project.get_cost_center_name’ ,
args: { project_name: frm.doc.project_name },
callback: function(r, rt) {
if(!r.exc) {
$.each(frm.doc[“items”] || [], function(i, row) {
frappe.model.set_value(row.doctype, row.name, “cost_center”, r.message);
msgprint(__(“Cost Center For Item with Item Code '”+row.item_name+"’ has been Changed to "+ r.message));
})
}
}
})
}
});

frappe.provide(“erpnext.accounts”);
erpnext.accounts.SalesInvoiceController = erpnext.selling.SellingController.extend({
onload: function() {
var me = this;
this._super();

	if(!this.frm.doc.__islocal && !this.frm.doc.customer && this.frm.doc.debit_to) {
		// show debit_to in print format
		this.frm.set_df_property("debit_to", "print_hide", 0);
	}

	// toggle to pos view if is_pos is 1 in user_defaults
	if ((is_null(this.frm.doc.is_pos) && cint(frappe.defaults.get_user_default("is_pos"))===1) || this.frm.doc.is_pos) {
		if(this.frm.doc.__islocal && !this.frm.doc.amended_from && !this.frm.doc.customer) {
			this.frm.set_value("is_pos", 1);
			this.is_pos(function() {
				if (cint(frappe.defaults.get_user_defaults("fs_pos_view"))===1)
					erpnext.pos.toggle(me.frm, true);
			});
		}
	}

	erpnext.queries.setup_queries(this.frm, "Warehouse", function() {
		return erpnext.queries.warehouse(me.frm.doc);
	});
},

refresh: function(doc, dt, dn) {
	this._super();

	if(cur_frm.msgbox && cur_frm.msgbox.$wrapper.is(":visible")) {
		// hide new msgbox
		cur_frm.msgbox.hide();
	}

	cur_frm.dashboard.reset();

	this.frm.toggle_reqd("due_date", !this.frm.doc.is_return);

	this.show_general_ledger();

	if(doc.update_stock) this.show_stock_ledger();

	if(doc.docstatus==1 && !doc.is_return) {
		
		var is_delivered_by_supplier = false;
		
		is_delivered_by_supplier = cur_frm.doc.items.some(function(item){
			return item.is_delivered_by_supplier ? true : false;
		})
		
		cur_frm.add_custom_button(doc.update_stock ? __('Sales Return') : __('Credit Note'),
			this.make_sales_return);

		if(cint(doc.update_stock)!=1) {
			// show Make Delivery Note button only if Sales Invoice is not created from Delivery Note
			var from_delivery_note = false;
			from_delivery_note = cur_frm.doc.items
				.some(function(item) {
					return item.delivery_note ? true : false;
				});

			if(!from_delivery_note && !is_delivered_by_supplier) {
				cur_frm.add_custom_button(__('Delivery'), cur_frm.cscript['Make Delivery Note']).addClass("btn-primary");
			}
		}

		if(doc.outstanding_amount!=0 && !cint(doc.is_return)) {
			cur_frm.add_custom_button(__('Payment'), cur_frm.cscript.make_bank_entry).addClass("btn-primary");
		}

	}

	// Show buttons only when pos view is active
	if (cint(doc.docstatus==0) && cur_frm.page.current_view_name!=="pos" && !doc.is_return) {
		cur_frm.cscript.sales_order_btn();
		cur_frm.cscript.delivery_note_btn();
	}

	this.set_default_print_format();
},

set_default_print_format: function() {
	// set default print format to POS type
	if(cur_frm.doc.is_pos) {
		if(cur_frm.pos_print_format) {
			cur_frm.meta._default_print_format = cur_frm.meta.default_print_format;
			cur_frm.meta.default_print_format = cur_frm.pos_print_format;
		}
	} else {
		if(cur_frm.meta._default_print_format) {
			cur_frm.meta.default_print_format = cur_frm.meta._default_print_format;
			cur_frm.meta._default_print_format = null;
		}
	}
},

sales_order_btn: function() {
	this.$sales_order_btn = cur_frm.add_custom_button(__('From Sales Order'),
		function() {
			frappe.model.map_current_doc({
				method: "erpnext.selling.doctype.sales_order.sales_order.make_sales_invoice",
				source_doctype: "Sales Order",
				get_query_filters: {
					docstatus: 1,
					status: ["not in", ["Stopped", "Closed"]],
					per_billed: ["<", 99.99],
					customer: cur_frm.doc.customer || undefined,
					company: cur_frm.doc.company
				}
			})
		});
},

delivery_note_btn: function() {
	this.$delivery_note_btn = cur_frm.add_custom_button(__('From Delivery Note'),
		function() {
			frappe.model.map_current_doc({
				method: "erpnext.stock.doctype.delivery_note.delivery_note.make_sales_invoice",
				source_doctype: "Delivery Note",
				get_query: function() {
					var filters = {
						company: cur_frm.doc.company
					};
					if(cur_frm.doc.customer) filters["customer"] = cur_frm.doc.customer;
					return {
						query: "erpnext.controllers.queries.get_delivery_notes_to_be_billed",
						filters: filters
					};
				}
			});
		});
},

tc_name: function() {
	this.get_terms();
},

is_pos: function(doc, dt, dn, callback_fn) {
	cur_frm.cscript.hide_fields(this.frm.doc);
	if(cur_frm.doc.__missing_values_set) return;
	if(cint(this.frm.doc.is_pos)) {
		if(!this.frm.doc.company) {
			this.frm.set_value("is_pos", 0);
			msgprint(__("Please specify Company to proceed"));
		} else {
			var me = this;
			return this.frm.call({
				doc: me.frm.doc,
				method: "set_missing_values",
				callback: function(r) {
					if(!r.exc) {
						if(r.message && r.message.print_format) {
							cur_frm.pos_print_format = r.message.print_format;
						}
						cur_frm.doc.__missing_values_set = true;
						me.frm.script_manager.trigger("update_stock");
						frappe.model.set_default_values(me.frm.doc);
						me.set_dynamic_labels();
						me.calculate_taxes_and_totals();
						if(callback_fn) callback_fn();
						frappe.after_ajax(function() {
							cur_frm.doc.__missing_values_set = false;
						})
					}
				}
			});
		}
	}
},

customer: function() {
	var me = this;
	if(this.frm.updating_party_details) return;

	erpnext.utils.get_party_details(this.frm,
		"erpnext.accounts.party.get_party_details", {
			posting_date: this.frm.doc.posting_date,
			party: this.frm.doc.customer,
			party_type: "Customer",
			account: this.frm.doc.debit_to,
			price_list: this.frm.doc.selling_price_list,
		}, function() {
		me.apply_pricing_rule();
	})
},

debit_to: function() {
	var me = this;
	if(this.frm.doc.debit_to) {
		me.frm.call({
			method: "frappe.client.get_value",
			args: {
				doctype: "Account",
				fieldname: "account_currency",
				filters: { name: me.frm.doc.debit_to },
			},
			callback: function(r, rt) {
				if(r.message) {
					me.frm.set_value("party_account_currency", r.message.account_currency);
					me.set_dynamic_labels();
				}
			}
		});
	}
},

allocated_amount: function() {
	this.calculate_total_advance();
	this.frm.refresh_fields();
},

write_off_outstanding_amount_automatically: function() {
	if(cint(this.frm.doc.write_off_outstanding_amount_automatically)) {
		frappe.model.round_floats_in(this.frm.doc, ["grand_total", "paid_amount"]);
		// this will make outstanding amount 0
		this.frm.set_value("write_off_amount",
			flt(this.frm.doc.grand_total - this.frm.doc.paid_amount - this.frm.doc.total_advance, precision("write_off_amount"))
		);
		this.frm.toggle_enable("write_off_amount", false);

	} else {
		this.frm.toggle_enable("write_off_amount", true);
	}

	this.calculate_outstanding_amount(false);
	this.frm.refresh_fields();
},

write_off_amount: function() {
	this.set_in_company_currency(this.frm.doc, ["write_off_amount"]);
	this.write_off_outstanding_amount_automatically();
},

paid_amount: function() {
	this.set_in_company_currency(this.frm.doc, ["paid_amount"]);
	this.write_off_outstanding_amount_automatically();
},

items_add: function(doc, cdt, cdn) {
	var row = frappe.get_doc(cdt, cdn);
	this.frm.script_manager.copy_from_first_row("items", row, ["income_account", "cost_center"]);
},

set_dynamic_labels: function() {
	this._super();
	this.hide_fields(this.frm.doc);
},

items_on_form_rendered: function() {
	erpnext.setup_serial_no();
},

make_sales_return: function() {
	frappe.model.open_mapped_doc({
		method: "erpnext.accounts.doctype.sales_invoice.sales_invoice.make_sales_return",
		frm: cur_frm
	})
}

});

// for backward compatibility: combine new and previous states
$.extend(cur_frm.cscript, new erpnext.accounts.SalesInvoiceController({frm: cur_frm}));

// Hide Fields
// ------------
cur_frm.cscript.hide_fields = function(doc) {
par_flds = [‘project_name’, ‘due_date’, ‘is_opening’, ‘source’, ‘total_advance’, ‘get_advances_received’,
‘advances’, ‘sales_partner’, ‘commission_rate’, ‘total_commission’, ‘advances’, ‘from_date’, ‘to_date’];

if(cint(doc.is_pos) == 1) {
	hide_field(par_flds);
} else {
	for (i in par_flds) {
		var docfield = frappe.meta.docfield_map[doc.doctype][par_flds[i]];
		if(!docfield.hidden) unhide_field(par_flds[i]);
	}
}

item_flds_stock = ['serial_no', 'batch_no', 'actual_qty', 'expense_account', 'warehouse', 'expense_account', 'warehouse']
cur_frm.fields_dict['items'].grid.set_column_disp(item_flds_stock,
	(cint(doc.update_stock)==1 ? true : false));

// India related fields
if (frappe.boot.sysdefaults.country == 'India') unhide_field(['c_form_applicable', 'c_form_no']);
else hide_field(['c_form_applicable', 'c_form_no']);

this.frm.toggle_enable("write_off_amount", !!!cint(doc.write_off_outstanding_amount_automatically));

cur_frm.refresh_fields();

}

cur_frm.cscript.mode_of_payment = function(doc) {
if(doc.is_pos) {
return cur_frm.call({
method: “erpnext.accounts.doctype.sales_invoice.sales_invoice.get_bank_cash_account”,
args: {
“mode_of_payment”: doc.mode_of_payment,
“company”: doc.company
},
callback: function(r, rt) {
if(r.message) {
cur_frm.set_value(“cash_bank_account”, r.message[“account”]);
}

		 }
	});
 }

}

cur_frm.cscript.update_stock = function(doc, dt, dn) {
cur_frm.cscript.hide_fields(doc, dt, dn);
}

cur_frm.cscript[‘Make Delivery Note’] = function() {
frappe.model.open_mapped_doc({
method: “erpnext.accounts.doctype.sales_invoice.sales_invoice.make_delivery_note”,
frm: cur_frm
})
}

cur_frm.cscript.make_bank_entry = function() {
return frappe.call({
method: “erpnext.accounts.doctype.journal_entry.journal_entry.get_payment_entry_against_invoice”,
args: {
“dt”: “Sales Invoice”,
“dn”: cur_frm.doc.name
},
callback: function(r) {
var doclist = frappe.model.sync(r.message);
frappe.set_route(“Form”, doclist[0].doctype, doclist[0].name);
}
});
}

cur_frm.fields_dict.cash_bank_account.get_query = function(doc) {
return {
filters: [
[“Account”, “account_type”, “in”, [“Cash”, “Bank”]],
[“Account”, “root_type”, “=”, “Asset”],
[“Account”, “is_group”, “=”,0],
[“Account”, “company”, “=”, doc.company]
]
}
}

cur_frm.fields_dict.write_off_account.get_query = function(doc) {
return{
filters:{
‘report_type’: ‘Profit and Loss’,
‘is_group’: 0,
‘company’: doc.company
}
}
}

// Write off cost center
//-----------------------
cur_frm.fields_dict.write_off_cost_center.get_query = function(doc) {
return{
filters:{
‘is_group’: 0,
‘company’: doc.company
}
}
}

//project name
//--------------------------
cur_frm.fields_dict[‘project_name’].get_query = function(doc, cdt, cdn) {
return{
query: “erpnext.controllers.queries.get_project_name”,
filters: {‘customer’: doc.customer}
}
}

// Income Account in Details Table
// --------------------------------
cur_frm.set_query(“income_account”, “items”, function(doc) {
return{
query: “erpnext.controllers.queries.get_income_account”,
filters: {‘company’: doc.company}
}
});

// expense account
if (sys_defaults.auto_accounting_for_stock) {
cur_frm.fields_dict[‘items’].grid.get_field(‘expense_account’).get_query = function(doc) {
return {
filters: {
‘report_type’: ‘Profit and Loss’,
‘company’: doc.company,
“is_group”: 0
}
}
}
}

// Cost Center in Details Table
// -----------------------------
cur_frm.fields_dict[“items”].grid.get_field(“cost_center”).get_query = function(doc) {
return {
filters: {
‘company’: doc.company,
“is_group”: 0
}
}
}

cur_frm.cscript.income_account = function(doc, cdt, cdn) {
erpnext.utils.copy_value_in_all_row(doc, cdt, cdn, “items”, “income_account”);
}

cur_frm.cscript.expense_account = function(doc, cdt, cdn) {
erpnext.utils.copy_value_in_all_row(doc, cdt, cdn, “items”, “expense_account”);
}

cur_frm.cscript.cost_center = function(doc, cdt, cdn) {
erpnext.utils.copy_value_in_all_row(doc, cdt, cdn, “items”, “cost_center”);
}

cur_frm.cscript.on_submit = function(doc, cdt, cdn) {
$.each(doc[“items”], function(i, row) {
if(row.delivery_note) frappe.model.clear_doc(“Delivery Note”, row.delivery_note)
})

if(cur_frm.doc.is_pos) {
	cur_frm.msgbox = frappe.msgprint('<a class="btn btn-primary" \
		onclick="cur_frm.print_preview.printit(true)" style="margin-right: 5px;">Print</a>\
		<a class="btn btn-default" href="#Form/Sales Invoice/New Sales Invoice">New</a>');

} else if(cint(frappe.boot.notification_settings.sales_invoice)) {
	cur_frm.email_doc(frappe.boot.notification_settings.sales_invoice_message);
}

}

cur_frm.set_query(“debit_to”, function(doc) {
// filter on Account
if (doc.customer) {
return {
filters: {
‘account_type’: ‘Receivable’,
‘is_group’: 0,
‘company’: doc.company
}
}
} else {
return {
filters: {
‘report_type’: ‘Balance Sheet’,
‘is_group’: 0,
‘company’: doc.company
}
}
}
});

frappe.ui.form.on(“Sales Invoice”, “refresh”, function(frm){
var sales_order = frm.doc.items[0].sales_order.replace(“M”, “M-”);
if (!frm.doc.__islocal && sales_order && frm.doc.name!==sales_order){
frappe.call({
method: ‘frappe.model.rename_doc.rename_doc’,
args: {
doctype: frm.doctype,
old: frm.docname,
“new”: sales_order,
“merge”: false
},
});
}
});

Hello, are there any news? THank you!

@Sabine can’t begin where to look at that code. You have to be really specific about your problem if you need help!

I was told to click on the error and paste what come out. I’m sorry that it is that long. I just really would like to know why the invoice became corrupted. I cannot solve it myself. Sorry