Fetch defaults in purchase common and sales common related doctypes and fix minor utf-8 issues

This commit is contained in:
Anand Doshi 2012-02-07 10:48:11 +05:30
parent 99e7f3d7a4
commit d008964fd6
33 changed files with 3288 additions and 3044 deletions

View File

@ -5,145 +5,145 @@
{ {
'creation': '2010-08-08 17:09:35', 'creation': '2010-08-08 17:09:35',
'docstatus': 0, 'docstatus': 0,
'modified': '2011-10-12 12:10:15', 'modified': '2012-02-06 15:25:06',
'modified_by': 'Administrator', 'modified_by': u'Administrator',
'owner': 'Administrator' 'owner': u'Administrator'
}, },
# These values are common for all Table Mapper Detail # These values are common for all Table Mapper Detail
{ {
'doctype': 'Table Mapper Detail', 'doctype': u'Table Mapper Detail',
'name': '__common__', 'name': '__common__',
'parent': 'Purchase Order-Payable Voucher', 'parent': u'Purchase Order-Payable Voucher',
'parentfield': 'table_mapper_details', 'parentfield': u'table_mapper_details',
'parenttype': 'DocType Mapper' 'parenttype': u'DocType Mapper'
}, },
# These values are common for all Field Mapper Detail # These values are common for all Field Mapper Detail
{ {
'doctype': 'Field Mapper Detail', 'doctype': u'Field Mapper Detail',
'name': '__common__', 'name': '__common__',
'parent': 'Purchase Order-Payable Voucher', 'parent': u'Purchase Order-Payable Voucher',
'parentfield': 'field_mapper_details', 'parentfield': u'field_mapper_details',
'parenttype': 'DocType Mapper' 'parenttype': u'DocType Mapper'
}, },
# These values are common for all DocType Mapper # These values are common for all DocType Mapper
{ {
'doctype': u'DocType Mapper', 'doctype': u'DocType Mapper',
'from_doctype': 'Purchase Order', 'from_doctype': u'Purchase Order',
'module': 'Accounts', 'module': u'Accounts',
'name': '__common__', 'name': '__common__',
'ref_doc_submitted': 1, 'ref_doc_submitted': 1,
'to_doctype': 'Payable Voucher' 'to_doctype': u'Payable Voucher'
}, },
# DocType Mapper, Purchase Order-Payable Voucher # DocType Mapper, Purchase Order-Payable Voucher
{ {
'doctype': u'DocType Mapper', 'doctype': u'DocType Mapper',
'name': 'Purchase Order-Payable Voucher' 'name': u'Purchase Order-Payable Voucher'
}, },
# Field Mapper Detail # Field Mapper Detail
{ {
'doctype': 'Field Mapper Detail', 'doctype': u'Field Mapper Detail',
'from_field': 'eval: flt(obj.qty) - flt(obj.billed_qty)', 'from_field': u'eval: flt(obj.qty) - flt(obj.billed_qty)',
'map': 'Yes', 'map': u'Yes',
'match_id': 1, 'match_id': 1,
'to_field': 'qty' 'to_field': u'qty'
}, },
# Field Mapper Detail # Field Mapper Detail
{ {
'doctype': 'Field Mapper Detail', 'doctype': u'Field Mapper Detail',
'from_field': 'purchase_rate', 'from_field': u'purchase_rate',
'map': 'Yes', 'map': u'Yes',
'match_id': 1, 'match_id': 1,
'to_field': 'rate' 'to_field': u'rate'
}, },
# Field Mapper Detail # Field Mapper Detail
{ {
'doctype': 'Field Mapper Detail', 'doctype': u'Field Mapper Detail',
'from_field': 'eval: (flt(obj.qty) - flt(obj.billed_qty)) * flt(obj.purchase_rate)', 'from_field': u'eval: (flt(obj.qty) - flt(obj.billed_qty)) * flt(obj.purchase_rate)',
'map': 'Yes', 'map': u'Yes',
'match_id': 1, 'match_id': 1,
'to_field': 'amount' 'to_field': u'amount'
}, },
# Field Mapper Detail # Field Mapper Detail
{ {
'doctype': 'Field Mapper Detail', 'doctype': u'Field Mapper Detail',
'from_field': 'eval: (flt(obj.qty) - flt(obj.billed_qty)) * flt(obj.import_rate)', 'from_field': u'eval: (flt(obj.qty) - flt(obj.billed_qty)) * flt(obj.import_rate)',
'map': 'Yes', 'map': u'Yes',
'match_id': 1, 'match_id': 1,
'to_field': 'import_amount' 'to_field': u'import_amount'
}, },
# Field Mapper Detail # Field Mapper Detail
{ {
'doctype': 'Field Mapper Detail', 'doctype': u'Field Mapper Detail',
'from_field': 'parent', 'from_field': u'parent',
'map': 'Yes', 'map': u'Yes',
'match_id': 1, 'match_id': 1,
'to_field': 'purchase_order' 'to_field': u'purchase_order'
}, },
# Field Mapper Detail # Field Mapper Detail
{ {
'doctype': 'Field Mapper Detail', 'doctype': u'Field Mapper Detail',
'from_field': 'name', 'from_field': u'name',
'map': 'Yes', 'map': u'Yes',
'match_id': 1, 'match_id': 1,
'to_field': 'po_detail' 'to_field': u'po_detail'
}, },
# Field Mapper Detail # Field Mapper Detail
{ {
'doctype': 'Field Mapper Detail', 'doctype': u'Field Mapper Detail',
'from_field': 'naming_series', 'from_field': u'naming_series',
'map': 'No', 'map': u'No',
'match_id': 0, 'match_id': 0,
'to_field': 'naming_series' 'to_field': u'naming_series'
}, },
# Field Mapper Detail # Field Mapper Detail
{ {
'doctype': 'Field Mapper Detail', 'doctype': u'Field Mapper Detail',
'from_field': 'total_tax', 'from_field': u'total_tax',
'map': 'Yes', 'map': u'Yes',
'match_id': 0, 'match_id': 0,
'to_field': 'total_tax' 'to_field': u'total_tax'
}, },
# Table Mapper Detail # Table Mapper Detail
{ {
'doctype': 'Table Mapper Detail', 'doctype': u'Table Mapper Detail',
'from_table': 'Purchase Order', 'from_table': u'Purchase Order',
'match_id': 0, 'match_id': 0,
'to_table': 'Payable Voucher', 'to_table': u'Payable Voucher',
'validation_logic': 'docstatus =1' 'validation_logic': u'docstatus =1'
}, },
# Table Mapper Detail # Table Mapper Detail
{ {
'doctype': 'Table Mapper Detail', 'doctype': u'Table Mapper Detail',
'from_field': 'po_details', 'from_field': u'po_details',
'from_table': 'PO Detail', 'from_table': u'PO Detail',
'match_id': 1, 'match_id': 1,
'to_field': 'entries', 'to_field': u'entries',
'to_table': 'PV Detail', 'to_table': u'PV Detail',
'validation_logic': 'ifnull(billed_qty,0) < qty and docstatus = 1' 'validation_logic': u'ifnull(billed_qty,0) < qty and docstatus = 1'
}, },
# Table Mapper Detail # Table Mapper Detail
{ {
'doctype': 'Table Mapper Detail', 'doctype': u'Table Mapper Detail',
'from_field': 'purchase_tax_details', 'from_field': u'purchase_tax_details',
'from_table': 'Purchase Tax Detail', 'from_table': u'Purchase Tax Detail',
'match_id': 2, 'match_id': 2,
'to_field': 'purchase_tax_details', 'to_field': u'purchase_tax_details',
'to_table': 'Purchase Tax Detail', 'to_table': u'Purchase Tax Detail',
'validation_logic': 'docstatus =1' 'validation_logic': u'docstatus =1'
} }
] ]

View File

@ -5,181 +5,181 @@
{ {
'creation': '2010-08-08 17:09:35', 'creation': '2010-08-08 17:09:35',
'docstatus': 0, 'docstatus': 0,
'modified': '2011-10-12 10:49:26', 'modified': '2012-02-06 15:26:25',
'modified_by': 'Administrator', 'modified_by': u'Administrator',
'owner': 'Administrator' 'owner': u'Administrator'
}, },
# These values are common for all Table Mapper Detail # These values are common for all Table Mapper Detail
{ {
'doctype': 'Table Mapper Detail', 'doctype': u'Table Mapper Detail',
'name': '__common__', 'name': '__common__',
'parent': 'Purchase Receipt-Payable Voucher', 'parent': u'Purchase Receipt-Payable Voucher',
'parentfield': 'table_mapper_details', 'parentfield': u'table_mapper_details',
'parenttype': 'DocType Mapper' 'parenttype': u'DocType Mapper'
}, },
# These values are common for all Field Mapper Detail # These values are common for all Field Mapper Detail
{ {
'doctype': 'Field Mapper Detail', 'doctype': u'Field Mapper Detail',
'name': '__common__', 'name': '__common__',
'parent': 'Purchase Receipt-Payable Voucher', 'parent': u'Purchase Receipt-Payable Voucher',
'parentfield': 'field_mapper_details', 'parentfield': u'field_mapper_details',
'parenttype': 'DocType Mapper' 'parenttype': u'DocType Mapper'
}, },
# These values are common for all DocType Mapper # These values are common for all DocType Mapper
{ {
'doctype': u'DocType Mapper', 'doctype': u'DocType Mapper',
'from_doctype': 'Purchase Receipt', 'from_doctype': u'Purchase Receipt',
'module': 'Accounts', 'module': u'Accounts',
'name': '__common__', 'name': '__common__',
'ref_doc_submitted': 1, 'ref_doc_submitted': 1,
'to_doctype': 'Payable Voucher' 'to_doctype': u'Payable Voucher'
}, },
# DocType Mapper, Purchase Receipt-Payable Voucher # DocType Mapper, Purchase Receipt-Payable Voucher
{ {
'doctype': u'DocType Mapper', 'doctype': u'DocType Mapper',
'name': 'Purchase Receipt-Payable Voucher' 'name': u'Purchase Receipt-Payable Voucher'
}, },
# Field Mapper Detail # Field Mapper Detail
{ {
'doctype': 'Field Mapper Detail', 'doctype': u'Field Mapper Detail',
'from_field': 'eval: flt(obj.qty) - flt(obj.billed_qty)', 'from_field': u'eval: flt(obj.qty) - flt(obj.billed_qty)',
'map': 'Yes', 'map': u'Yes',
'match_id': 1, 'match_id': 1,
'to_field': 'qty' 'to_field': u'qty'
}, },
# Field Mapper Detail # Field Mapper Detail
{ {
'doctype': 'Field Mapper Detail', 'doctype': u'Field Mapper Detail',
'from_field': 'purchase_rate', 'from_field': u'purchase_rate',
'map': 'Yes', 'map': u'Yes',
'match_id': 1, 'match_id': 1,
'to_field': 'rate' 'to_field': u'rate'
}, },
# Field Mapper Detail # Field Mapper Detail
{ {
'doctype': 'Field Mapper Detail', 'doctype': u'Field Mapper Detail',
'from_field': 'eval: (flt(obj.qty) - flt(obj.billed_qty)) * flt(obj.purchase_rate)', 'from_field': u'eval: (flt(obj.qty) - flt(obj.billed_qty)) * flt(obj.purchase_rate)',
'map': 'Yes', 'map': u'Yes',
'match_id': 1, 'match_id': 1,
'to_field': 'amount' 'to_field': u'amount'
}, },
# Field Mapper Detail # Field Mapper Detail
{ {
'doctype': 'Field Mapper Detail', 'doctype': u'Field Mapper Detail',
'from_field': 'eval: (flt(obj.qty) - flt(obj.billed_qty)) * flt(obj.import_rate)', 'from_field': u'eval: (flt(obj.qty) - flt(obj.billed_qty)) * flt(obj.import_rate)',
'map': 'Yes', 'map': u'Yes',
'match_id': 1, 'match_id': 1,
'to_field': 'import_amount' 'to_field': u'import_amount'
}, },
# Field Mapper Detail # Field Mapper Detail
{ {
'doctype': 'Field Mapper Detail', 'doctype': u'Field Mapper Detail',
'from_field': 'parent', 'from_field': u'parent',
'map': 'Yes', 'map': u'Yes',
'match_id': 1, 'match_id': 1,
'to_field': 'purchase_receipt' 'to_field': u'purchase_receipt'
}, },
# Field Mapper Detail # Field Mapper Detail
{ {
'doctype': 'Field Mapper Detail', 'doctype': u'Field Mapper Detail',
'from_field': 'prevdoc_docname', 'from_field': u'prevdoc_docname',
'map': 'Yes', 'map': u'Yes',
'match_id': 1, 'match_id': 1,
'to_field': 'purchase_order' 'to_field': u'purchase_order'
}, },
# Field Mapper Detail # Field Mapper Detail
{ {
'doctype': 'Field Mapper Detail', 'doctype': u'Field Mapper Detail',
'from_field': 'name', 'from_field': u'name',
'map': 'Yes', 'map': u'Yes',
'match_id': 1, 'match_id': 1,
'to_field': 'pr_detail' 'to_field': u'pr_detail'
}, },
# Field Mapper Detail # Field Mapper Detail
{ {
'doctype': 'Field Mapper Detail', 'doctype': u'Field Mapper Detail',
'from_field': 'prevdoc_detail_docname', 'from_field': u'prevdoc_detail_docname',
'map': 'Yes', 'map': u'Yes',
'match_id': 1, 'match_id': 1,
'to_field': 'po_detail' 'to_field': u'po_detail'
}, },
# Field Mapper Detail # Field Mapper Detail
{ {
'doctype': 'Field Mapper Detail', 'doctype': u'Field Mapper Detail',
'from_field': 'naming_series', 'from_field': u'naming_series',
'map': 'No', 'map': u'No',
'match_id': 0, 'match_id': 0,
'to_field': 'naming_series' 'to_field': u'naming_series'
}, },
# Field Mapper Detail # Field Mapper Detail
{ {
'doctype': 'Field Mapper Detail', 'doctype': u'Field Mapper Detail',
'from_field': 'net_total', 'from_field': u'net_total',
'map': 'Yes', 'map': u'Yes',
'match_id': 0, 'match_id': 0,
'to_field': 'net_total' 'to_field': u'net_total'
}, },
# Field Mapper Detail # Field Mapper Detail
{ {
'doctype': 'Field Mapper Detail', 'doctype': u'Field Mapper Detail',
'from_field': 'grand_total', 'from_field': u'grand_total',
'map': 'Yes', 'map': u'Yes',
'match_id': 0, 'match_id': 0,
'to_field': 'grand_total' 'to_field': u'grand_total'
}, },
# Field Mapper Detail # Field Mapper Detail
{ {
'doctype': 'Field Mapper Detail', 'doctype': u'Field Mapper Detail',
'from_field': 'total_tax', 'from_field': u'total_tax',
'map': 'Yes', 'map': u'Yes',
'match_id': 0, 'match_id': 0,
'to_field': 'total_tax' 'to_field': u'total_tax'
}, },
# Table Mapper Detail # Table Mapper Detail
{ {
'doctype': 'Table Mapper Detail', 'doctype': u'Table Mapper Detail',
'from_field': 'purchase_receipt_details', 'from_field': u'purchase_receipt_details',
'from_table': 'Purchase Receipt Detail', 'from_table': u'Purchase Receipt Detail',
'match_id': 1, 'match_id': 1,
'to_field': 'entries', 'to_field': u'entries',
'to_table': 'PV Detail', 'to_table': u'PV Detail',
'validation_logic': 'ifnull(billed_qty,0) < qty' 'validation_logic': u'ifnull(billed_qty,0) < qty'
}, },
# Table Mapper Detail # Table Mapper Detail
{ {
'doctype': 'Table Mapper Detail', 'doctype': u'Table Mapper Detail',
'from_table': 'Purchase Receipt', 'from_table': u'Purchase Receipt',
'match_id': 0, 'match_id': 0,
'to_table': 'Payable Voucher', 'to_table': u'Payable Voucher',
'validation_logic': 'docstatus=1' 'validation_logic': u'docstatus=1'
}, },
# Table Mapper Detail # Table Mapper Detail
{ {
'doctype': 'Table Mapper Detail', 'doctype': u'Table Mapper Detail',
'from_field': 'purchase_tax_details', 'from_field': u'purchase_tax_details',
'from_table': 'Purchase Tax Detail', 'from_table': u'Purchase Tax Detail',
'match_id': 2, 'match_id': 2,
'to_field': 'purchase_tax_details', 'to_field': u'purchase_tax_details',
'to_table': 'Purchase Tax Detail', 'to_table': u'Purchase Tax Detail',
'validation_logic': 'docstatus=1' 'validation_logic': u'docstatus=1'
} }
] ]

View File

@ -1,156 +1,177 @@
cur_frm.cscript.onload = function(doc, cdt, cdn) { cur_frm.cscript.onload = function(doc, cdt, cdn) {
var cp = locals['Control Panel']['Control Panel']; var cp = locals['Control Panel']['Control Panel'];
if (!doc.voucher_date) doc.voucher_date = dateutil.obj_to_str(new Date()); if (!doc.voucher_date) doc.voucher_date = dateutil.obj_to_str(new Date());
if(cp.country == 'India') {
unhide_field(['tds_applicable','tds_category','Get TDS','tax_code','rate','ded_amount','supplier_account']);
}
else {
hide_field(['tds_applicable','tds_category','Get TDS','tax_code','rate','ded_amount','supplier_account']);
}
cur_frm.cscript.load_defaults(doc, cdt, cdn);
if(cp.country == 'India') {
unhide_field(['tds_applicable','tds_category','Get TDS','tax_code','rate','ded_amount','supplier_account']);
}
else {
hide_field(['tds_applicable','tds_category','Get TDS','tax_code','rate','ded_amount','supplier_account']);
}
} }
cur_frm.cscript.load_defaults = function(doc, cdt, cdn) {
if(!cur_frm.doc.__islocal || !cur_frm.doc.company) { return; }
doc = locals[doc.doctype][doc.name];
var fields_to_refresh = LocalDB.set_default_values(doc);
if(fields_to_refresh) { refresh_many(fields_to_refresh); }
fields_to_refresh = null;
var children = getchildren('Journal Voucher Detail', doc.name, 'entries');
if(!children) { return; }
for(var i=0; i<children.length; i++) {
LocalDB.set_default_values(children[i]);
}
refresh_field('entries');
}
cur_frm.cscript.is_opening = function(doc, cdt, cdn) { cur_frm.cscript.is_opening = function(doc, cdt, cdn) {
hide_field('aging_date'); hide_field('aging_date');
if (doc.is_opening == 'Yes') unhide_field('aging_date'); if (doc.is_opening == 'Yes') unhide_field('aging_date');
if(doc.docstatus==1) { unhide_field('View Ledger Entry'); } if(doc.docstatus==1) { unhide_field('View Ledger Entry'); }
else hide_field('View Ledger Entry'); else hide_field('View Ledger Entry');
} }
cur_frm.cscript.refresh = cur_frm.cscript.is_opening; cur_frm.cscript.refresh = cur_frm.cscript.is_opening;
cur_frm.fields_dict['entries'].grid.get_field('account').get_query = function(doc) { cur_frm.fields_dict['entries'].grid.get_field('account').get_query = function(doc) {
return "SELECT `tabAccount`.name FROM `tabAccount` WHERE `tabAccount`.company='"+doc.company+"' AND tabAccount.group_or_ledger = 'Ledger' AND tabAccount.docstatus != 2 AND `tabAccount`.%(key)s LIKE '%s' ORDER BY `tabAccount`.name DESC LIMIT 50"; return "SELECT `tabAccount`.name FROM `tabAccount` WHERE `tabAccount`.company='"+doc.company+"' AND tabAccount.group_or_ledger = 'Ledger' AND tabAccount.docstatus != 2 AND `tabAccount`.%(key)s LIKE '%s' ORDER BY `tabAccount`.name DESC LIMIT 50";
} }
cur_frm.fields_dict["entries"].grid.get_field("cost_center").get_query = function(doc, cdt, cdn) { cur_frm.fields_dict["entries"].grid.get_field("cost_center").get_query = function(doc, cdt, cdn) {
return 'SELECT `tabCost Center`.`name` FROM `tabCost Center` WHERE `tabCost Center`.`company_name` = "' +doc.company+'" AND `tabCost Center`.%(key)s LIKE "%s" AND `tabCost Center`.`group_or_ledger` = "Ledger" AND `tabCost Center`.docstatus != 2 ORDER BY `tabCost Center`.`name` ASC LIMIT 50'; return 'SELECT `tabCost Center`.`name` FROM `tabCost Center` WHERE `tabCost Center`.`company_name` = "' +doc.company+'" AND `tabCost Center`.%(key)s LIKE "%s" AND `tabCost Center`.`group_or_ledger` = "Ledger" AND `tabCost Center`.docstatus != 2 ORDER BY `tabCost Center`.`name` ASC LIMIT 50';
} }
// Restrict Voucher based on Account // Restrict Voucher based on Account
// --------------------------------- // ---------------------------------
cur_frm.fields_dict['entries'].grid.get_field('against_voucher').get_query = function(doc) { cur_frm.fields_dict['entries'].grid.get_field('against_voucher').get_query = function(doc) {
var d = locals[this.doctype][this.docname]; var d = locals[this.doctype][this.docname];
return "SELECT `tabPayable Voucher`.name, `tabPayable Voucher`.credit_to, `tabPayable Voucher`.outstanding_amount,`tabPayable Voucher`.bill_no, `tabPayable Voucher`.bill_date FROM `tabPayable Voucher` WHERE `tabPayable Voucher`.credit_to='"+d.account+"' AND `tabPayable Voucher`.outstanding_amount > 0 AND `tabPayable Voucher`.docstatus = 1 AND `tabPayable Voucher`.%(key)s LIKE '%s' ORDER BY `tabPayable Voucher`.name DESC LIMIT 200"; return "SELECT `tabPayable Voucher`.name, `tabPayable Voucher`.credit_to, `tabPayable Voucher`.outstanding_amount,`tabPayable Voucher`.bill_no, `tabPayable Voucher`.bill_date FROM `tabPayable Voucher` WHERE `tabPayable Voucher`.credit_to='"+d.account+"' AND `tabPayable Voucher`.outstanding_amount > 0 AND `tabPayable Voucher`.docstatus = 1 AND `tabPayable Voucher`.%(key)s LIKE '%s' ORDER BY `tabPayable Voucher`.name DESC LIMIT 200";
} }
cur_frm.fields_dict['entries'].grid.get_field('against_invoice').get_query = function(doc) { cur_frm.fields_dict['entries'].grid.get_field('against_invoice').get_query = function(doc) {
var d = locals[this.doctype][this.docname]; var d = locals[this.doctype][this.docname];
return "SELECT `tabReceivable Voucher`.name, `tabReceivable Voucher`.debit_to, `tabReceivable Voucher`.outstanding_amount FROM `tabReceivable Voucher` WHERE `tabReceivable Voucher`.debit_to='"+d.account+"' AND `tabReceivable Voucher`.outstanding_amount > 0 AND `tabReceivable Voucher`.docstatus = 1 AND `tabReceivable Voucher`.%(key)s LIKE '%s' ORDER BY `tabReceivable Voucher`.name DESC LIMIT 200"; return "SELECT `tabReceivable Voucher`.name, `tabReceivable Voucher`.debit_to, `tabReceivable Voucher`.outstanding_amount FROM `tabReceivable Voucher` WHERE `tabReceivable Voucher`.debit_to='"+d.account+"' AND `tabReceivable Voucher`.outstanding_amount > 0 AND `tabReceivable Voucher`.docstatus = 1 AND `tabReceivable Voucher`.%(key)s LIKE '%s' ORDER BY `tabReceivable Voucher`.name DESC LIMIT 200";
} }
// TDS Account Head // TDS Account Head
cur_frm.fields_dict['tax_code'].get_query = function(doc) { cur_frm.fields_dict['tax_code'].get_query = function(doc) {
return "SELECT `tabTDS Category Account`.account_head FROM `tabTDS Category Account` WHERE `tabTDS Category Account`.parent = '"+doc.tds_category+"' AND `tabTDS Category Account`.company='"+doc.company+"' AND `tabTDS Category Account`.account_head LIKE '%s' ORDER BY `tabTDS Category Account`.account_head DESC LIMIT 50"; return "SELECT `tabTDS Category Account`.account_head FROM `tabTDS Category Account` WHERE `tabTDS Category Account`.parent = '"+doc.tds_category+"' AND `tabTDS Category Account`.company='"+doc.company+"' AND `tabTDS Category Account`.account_head LIKE '%s' ORDER BY `tabTDS Category Account`.account_head DESC LIMIT 50";
} }
//Set debit and credit to zero on adding new row //Set debit and credit to zero on adding new row
//---------------------------------------------- //----------------------------------------------
cur_frm.fields_dict['entries'].grid.onrowadd = function(doc, cdt, cdn){ cur_frm.fields_dict['entries'].grid.onrowadd = function(doc, cdt, cdn){
var d = locals[cdt][cdn]; var d = locals[cdt][cdn];
if(d.idx == 1){ if(d.idx == 1){
d.debit = 0; d.debit = 0;
d.credit = 0; d.credit = 0;
} }
} }
// Get Outstanding of Payable & Receivable Voucher // Get Outstanding of Payable & Receivable Voucher
// ----------------------------------------------- // -----------------------------------------------
cur_frm.cscript.against_voucher = function(doc,cdt,cdn) { cur_frm.cscript.against_voucher = function(doc,cdt,cdn) {
var d = locals[cdt][cdn]; var d = locals[cdt][cdn];
if (d.against_voucher && !flt(d.debit)) { if (d.against_voucher && !flt(d.debit)) {
args = {'doctype': 'Payable Voucher', 'docname': d.against_voucher } args = {'doctype': 'Payable Voucher', 'docname': d.against_voucher }
get_server_fields('get_outstanding',docstring(args),'entries',doc,cdt,cdn,1,function(r,rt) { cur_frm.cscript.update_totals(doc); }); get_server_fields('get_outstanding',docstring(args),'entries',doc,cdt,cdn,1,function(r,rt) { cur_frm.cscript.update_totals(doc); });
} }
} }
cur_frm.cscript.against_invoice = function(doc,cdt,cdn) { cur_frm.cscript.against_invoice = function(doc,cdt,cdn) {
var d = locals[cdt][cdn]; var d = locals[cdt][cdn];
if (d.against_invoice && !flt(d.credit)) { if (d.against_invoice && !flt(d.credit)) {
args = {'doctype': 'Receivable Voucher', 'docname': d.against_invoice } args = {'doctype': 'Receivable Voucher', 'docname': d.against_invoice }
get_server_fields('get_outstanding',docstring(args),'entries',doc,cdt,cdn,1,function(r,rt) { cur_frm.cscript.update_totals(doc); }); get_server_fields('get_outstanding',docstring(args),'entries',doc,cdt,cdn,1,function(r,rt) { cur_frm.cscript.update_totals(doc); });
} }
} }
// Update Totals // Update Totals
// --------------- // ---------------
cur_frm.cscript.update_totals = function(doc) { cur_frm.cscript.update_totals = function(doc) {
var td=0.0; var tc =0.0; var td=0.0; var tc =0.0;
var el = getchildren('Journal Voucher Detail', doc.name, 'entries'); var el = getchildren('Journal Voucher Detail', doc.name, 'entries');
for(var i in el) { for(var i in el) {
td += flt(el[i].debit); td += flt(el[i].debit);
tc += flt(el[i].credit); tc += flt(el[i].credit);
} }
var doc = locals[doc.doctype][doc.name]; var doc = locals[doc.doctype][doc.name];
tc += flt(doc.ded_amount) tc += flt(doc.ded_amount)
doc.total_debit = td; doc.total_debit = td;
doc.total_credit = tc; doc.total_credit = tc;
doc.difference = flt(td - tc); doc.difference = flt(td - tc);
refresh_many(['total_debit','total_credit','difference']); refresh_many(['total_debit','total_credit','difference']);
} }
cur_frm.cscript.debit = function(doc,dt,dn) { cur_frm.cscript.update_totals(doc); } cur_frm.cscript.debit = function(doc,dt,dn) { cur_frm.cscript.update_totals(doc); }
cur_frm.cscript.credit = function(doc,dt,dn) { cur_frm.cscript.update_totals(doc); } cur_frm.cscript.credit = function(doc,dt,dn) { cur_frm.cscript.update_totals(doc); }
cur_frm.cscript.ded_amount = function(doc,dt,dn) { cur_frm.cscript.update_totals(doc); } cur_frm.cscript.ded_amount = function(doc,dt,dn) { cur_frm.cscript.update_totals(doc); }
cur_frm.cscript.rate = function(doc,dt,dn) { cur_frm.cscript.rate = function(doc,dt,dn) {
doc.ded_amount = doc.total_debit*doc.rate/100; doc.ded_amount = doc.total_debit*doc.rate/100;
refresh_field('ded_amount'); refresh_field('ded_amount');
cur_frm.cscript.update_totals(doc); cur_frm.cscript.update_totals(doc);
} }
cur_frm.cscript['Get Balance'] = function(doc,dt,dn) { cur_frm.cscript['Get Balance'] = function(doc,dt,dn) {
cur_frm.cscript.update_totals(doc); cur_frm.cscript.update_totals(doc);
$c_obj(make_doclist(dt,dn), 'get_balance', '', function(r, rt){ $c_obj(make_doclist(dt,dn), 'get_balance', '', function(r, rt){
cur_frm.refresh(); cur_frm.refresh();
}); });
} }
// Get balance // Get balance
// ----------- // -----------
cur_frm.cscript.account = function(doc,dt,dn) { cur_frm.cscript.account = function(doc,dt,dn) {
var d = locals[dt][dn]; var d = locals[dt][dn];
$c_obj('GL Control','get_bal',d.account+'~~~'+doc.fiscal_year, function(r,rt) { d.balance = r.message; refresh_field('balance',d.name,'entries'); }); $c_obj('GL Control','get_bal',d.account+'~~~'+doc.fiscal_year, function(r,rt) { d.balance = r.message; refresh_field('balance',d.name,'entries'); });
} }
cur_frm.cscript.validate = function(doc,cdt,cdn) { cur_frm.cscript.validate = function(doc,cdt,cdn) {
cur_frm.cscript.update_totals(doc); cur_frm.cscript.update_totals(doc);
} }
// TDS // TDS
// -------- // --------
cur_frm.cscript['Get TDS'] = function(doc, dt, dn) { cur_frm.cscript['Get TDS'] = function(doc, dt, dn) {
$c_obj(make_doclist(dt,dn), 'get_tds', '', function(r, rt){ $c_obj(make_doclist(dt,dn), 'get_tds', '', function(r, rt){
cur_frm.refresh(); cur_frm.refresh();
cur_frm.cscript.update_totals(doc); cur_frm.cscript.update_totals(doc);
}); });
} }
// ***************** Get Print Heading based on Receivable Voucher ***************** // ***************** Get Print Heading based on Receivable Voucher *****************
cur_frm.fields_dict['select_print_heading'].get_query = function(doc, cdt, cdn) { cur_frm.fields_dict['select_print_heading'].get_query = function(doc, cdt, cdn) {
return 'SELECT `tabPrint Heading`.name FROM `tabPrint Heading` WHERE `tabPrint Heading`.docstatus !=2 AND `tabPrint Heading`.name LIKE "%s" ORDER BY `tabPrint Heading`.name ASC LIMIT 50'; return 'SELECT `tabPrint Heading`.name FROM `tabPrint Heading` WHERE `tabPrint Heading`.docstatus !=2 AND `tabPrint Heading`.name LIKE "%s" ORDER BY `tabPrint Heading`.name ASC LIMIT 50';
} }
cur_frm.cscript.select_print_heading = function(doc,cdt,cdn){ cur_frm.cscript.select_print_heading = function(doc,cdt,cdn){
if(doc.select_print_heading){ if(doc.select_print_heading){
// print heading // print heading
cur_frm.pformat.print_heading = doc.select_print_heading; cur_frm.pformat.print_heading = doc.select_print_heading;
} }
else else
cur_frm.pformat.print_heading = "Journal Voucher"; cur_frm.pformat.print_heading = "Journal Voucher";
} }
/****************** Get Accounting Entry *****************/ /****************** Get Accounting Entry *****************/
cur_frm.cscript['View Ledger Entry'] = function(doc,cdt,cdn){ cur_frm.cscript['View Ledger Entry'] = function(doc,cdt,cdn){
var callback = function(report){ var callback = function(report){
report.set_filter('GL Entry', 'Voucher No',doc.name); report.set_filter('GL Entry', 'Voucher No',doc.name);
report.dt.run(); report.dt.run();
} }
loadreport('GL Entry','General Ledger', callback); loadreport('GL Entry','General Ledger', callback);
} }

View File

@ -7,99 +7,102 @@ $import(Purchase Common)
// On Load // On Load
// -------- // --------
cur_frm.cscript.onload = function(doc,dt,dn) { cur_frm.cscript.onload = function(doc,dt,dn) {
var cp = locals['Control Panel']['Control Panel']; var cp = locals['Control Panel']['Control Panel'];
if(!doc.voucher_date) set_multiple(dt,dn,{voucher_date:get_today()}); if(!doc.voucher_date) set_multiple(dt,dn,{voucher_date:get_today()});
if(!doc.posting_date) set_multiple(dt,dn,{posting_date:get_today()}); if(!doc.posting_date) set_multiple(dt,dn,{posting_date:get_today()});
if(cp.country == 'India') { if(cp.country == 'India') {
unhide_field(['TDS','tds_applicable','tds_category','Get TDS','tax_code','rate','ded_amount','total_tds_on_voucher','tds_amount_on_advance']); unhide_field(['TDS','tds_applicable','tds_category','Get TDS','tax_code','rate','ded_amount','total_tds_on_voucher','tds_amount_on_advance']);
} }
else { else {
hide_field(['TDS','tds_applicable','tds_category','Get TDS','tax_code','rate','ded_amount','total_tds_on_voucher','tds_amount_on_advance']); hide_field(['TDS','tds_applicable','tds_category','Get TDS','tax_code','rate','ded_amount','total_tds_on_voucher','tds_amount_on_advance']);
} }
if(doc.__islocal){ if(doc.__islocal){
hide_field(['supplier_address', 'contact_person', 'supplier_name', 'address_display', 'contact_display', 'contact_mobile', 'contact_email']); hide_field(['supplier_address', 'contact_person', 'supplier_name', 'address_display', 'contact_display', 'contact_mobile', 'contact_email']);
} }
// defined in purchase_common.js
cur_frm.cscript.update_item_details(doc, cdt, cdn);
} }
//Onload post render //Onload post render
//------------------------ //------------------------
cur_frm.cscript.onload_post_render = function(doc, dt, dn) { cur_frm.cscript.onload_post_render = function(doc, dt, dn) {
if(doc.__islocal && doc.supplier) cur_frm.cscript.supplier(doc,dt,dn); if(doc.__islocal && doc.supplier) cur_frm.cscript.supplier(doc,dt,dn);
} }
// Refresh // Refresh
// -------- // --------
cur_frm.cscript.refresh = function(doc, dt, dn) { cur_frm.cscript.refresh = function(doc, dt, dn) {
cur_frm.clear_custom_buttons(); cur_frm.clear_custom_buttons();
// Show / Hide button // Show / Hide button
if(doc.docstatus==1 && doc.outstanding_amount > 0) if(doc.docstatus==1 && doc.outstanding_amount > 0)
cur_frm.add_custom_button('Make Payment Entry', cur_frm.cscript['Make Bank Voucher']); cur_frm.add_custom_button('Make Payment Entry', cur_frm.cscript['Make Bank Voucher']);
if(doc.docstatus==1) { if(doc.docstatus==1) {
unhide_field(['Repair Outstanding Amt']); unhide_field(['Repair Outstanding Amt']);
cur_frm.add_custom_button('View Ledger', cur_frm.cscript['View Ledger Entry']); cur_frm.add_custom_button('View Ledger', cur_frm.cscript['View Ledger Entry']);
} else hide_field(['Repair Outstanding Amt']); } else hide_field(['Repair Outstanding Amt']);
cur_frm.cscript.is_opening(doc, dt, dn); cur_frm.cscript.is_opening(doc, dt, dn);
} }
//Supplier //Supplier
cur_frm.cscript.supplier = function(doc,dt,dn) { cur_frm.cscript.supplier = function(doc,dt,dn) {
var callback = function(r,rt) { var callback = function(r,rt) {
var doc = locals[cur_frm.doctype][cur_frm.docname]; var doc = locals[cur_frm.doctype][cur_frm.docname];
get_server_fields('get_credit_to','','',doc, dt, dn, 0, callback2); get_server_fields('get_credit_to','','',doc, dt, dn, 0, callback2);
} }
var callback2 = function(r,rt){ var callback2 = function(r,rt){
var doc = locals[cur_frm.doctype][cur_frm.docname]; var doc = locals[cur_frm.doctype][cur_frm.docname];
var el = getchildren('PV Detail',doc.name,'entries'); var el = getchildren('PV Detail',doc.name,'entries');
for(var i in el){ for(var i in el){
if(el[i].item_code && (!el[i].expense_head || !el[i].cost_center)){ if(el[i].item_code && (!el[i].expense_head || !el[i].cost_center)){
args = "{'item_code':'" + el[i].item_code + "','expense_head':'" + el[i].expense_head + "','cost_center':'" + el[i].cost_center + "'}"; args = "{'item_code':'" + el[i].item_code + "','expense_head':'" + el[i].expense_head + "','cost_center':'" + el[i].cost_center + "'}";
get_server_fields('get_default_values', args, 'entries', doc, el[i].doctype, el[i].name, 1); get_server_fields('get_default_values', args, 'entries', doc, el[i].doctype, el[i].name, 1);
} }
} }
cur_frm.cscript.calc_amount(doc, 1); cur_frm.cscript.calc_amount(doc, 1);
} }
if(doc.supplier) get_server_fields('get_default_supplier_address', JSON.stringify({supplier: doc.supplier}),'', doc, dt, dn, 1,callback); if(doc.supplier) get_server_fields('get_default_supplier_address', JSON.stringify({supplier: doc.supplier}),'', doc, dt, dn, 1,callback);
if(doc.supplier) unhide_field(['supplier_address','contact_person','supplier_name','address_display','contact_display','contact_mobile','contact_email']); if(doc.supplier) unhide_field(['supplier_address','contact_person','supplier_name','address_display','contact_display','contact_mobile','contact_email']);
} }
cur_frm.cscript.supplier_address = cur_frm.cscript.contact_person = function(doc,dt,dn) { cur_frm.cscript.supplier_address = cur_frm.cscript.contact_person = function(doc,dt,dn) {
if(doc.supplier) get_server_fields('get_supplier_address', JSON.stringify({supplier: doc.supplier, address: doc.supplier_address, contact: doc.contact_person}),'', doc, dt, dn, 1); if(doc.supplier) get_server_fields('get_supplier_address', JSON.stringify({supplier: doc.supplier, address: doc.supplier_address, contact: doc.contact_person}),'', doc, dt, dn, 1);
} }
cur_frm.fields_dict.supplier_address.on_new = function(dn) { cur_frm.fields_dict.supplier_address.on_new = function(dn) {
locals['Address'][dn].supplier = locals[cur_frm.doctype][cur_frm.docname].supplier; locals['Address'][dn].supplier = locals[cur_frm.doctype][cur_frm.docname].supplier;
locals['Address'][dn].supplier_name = locals[cur_frm.doctype][cur_frm.docname].supplier_name; locals['Address'][dn].supplier_name = locals[cur_frm.doctype][cur_frm.docname].supplier_name;
} }
cur_frm.fields_dict.contact_person.on_new = function(dn) { cur_frm.fields_dict.contact_person.on_new = function(dn) {
locals['Contact'][dn].supplier = locals[cur_frm.doctype][cur_frm.docname].supplier; locals['Contact'][dn].supplier = locals[cur_frm.doctype][cur_frm.docname].supplier;
locals['Contact'][dn].supplier_name = locals[cur_frm.doctype][cur_frm.docname].supplier_name; locals['Contact'][dn].supplier_name = locals[cur_frm.doctype][cur_frm.docname].supplier_name;
} }
cur_frm.cscript.credit_to = function(doc,dt,dn) { cur_frm.cscript.credit_to = function(doc,dt,dn) {
var callback = function(r,rt) { var callback = function(r,rt) {
var doc = locals[cur_frm.doctype][cur_frm.docname]; var doc = locals[cur_frm.doctype][cur_frm.docname];
if(doc.supplier) get_server_fields('get_default_supplier_address', JSON.stringify({supplier: doc.supplier}),'', doc, dt, dn, 1); if(doc.supplier) get_server_fields('get_default_supplier_address', JSON.stringify({supplier: doc.supplier}),'', doc, dt, dn, 1);
if(doc.supplier) unhide_field(['supplier_address','contact_person','supplier_name','address_display','contact_display','contact_mobile','contact_email']); if(doc.supplier) unhide_field(['supplier_address','contact_person','supplier_name','address_display','contact_display','contact_mobile','contact_email']);
cur_frm.refresh(); cur_frm.refresh();
} }
get_server_fields('get_cust','','',doc,dt,dn,1,callback); get_server_fields('get_cust','','',doc,dt,dn,1,callback);
} }
@ -107,43 +110,43 @@ cur_frm.cscript.credit_to = function(doc,dt,dn) {
//Set expense_head and cost center on adding new row //Set expense_head and cost center on adding new row
//---------------------------------------------- //----------------------------------------------
cur_frm.fields_dict['entries'].grid.onrowadd = function(doc, cdt, cdn){ cur_frm.fields_dict['entries'].grid.onrowadd = function(doc, cdt, cdn){
cl = getchildren('PV Detail', doc.name, cur_frm.cscript.fname, doc.doctype); cl = getchildren('PV Detail', doc.name, cur_frm.cscript.fname, doc.doctype);
acc = ''; acc = '';
cc = ''; cc = '';
for(var i = 0; i<cl.length; i++) { for(var i = 0; i<cl.length; i++) {
if (cl[i].idx == 1){ if (cl[i].idx == 1){
acc = cl[i].expense_head; acc = cl[i].expense_head;
cc = cl[i].cost_center; cc = cl[i].cost_center;
} }
else{ else{
if (! cl[i].expense_head) { cl[i].expense_head = acc; refresh_field('expense_head', cl[i].name, 'entries');} if (! cl[i].expense_head) { cl[i].expense_head = acc; refresh_field('expense_head', cl[i].name, 'entries');}
if (! cl[i].cost_center) {cl[i].cost_center = cc; refresh_field('cost_center', cl[i].name, 'entries');} if (! cl[i].cost_center) {cl[i].cost_center = cc; refresh_field('cost_center', cl[i].name, 'entries');}
} }
} }
} }
cur_frm.cscript.is_opening = function(doc, dt, dn) { cur_frm.cscript.is_opening = function(doc, dt, dn) {
hide_field('aging_date'); hide_field('aging_date');
if (doc.is_opening == 'Yes') unhide_field('aging_date'); if (doc.is_opening == 'Yes') unhide_field('aging_date');
} }
// Recalculate Button // Recalculate Button
// ------------------- // -------------------
cur_frm.cscript['Recalculate'] = function(doc, dt, dn) { cur_frm.cscript['Recalculate'] = function(doc, dt, dn) {
cur_frm.cscript['Calculate Tax'](doc,cdt,cdn); cur_frm.cscript['Calculate Tax'](doc,cdt,cdn);
calc_total_advance(doc,cdt,cdn); calc_total_advance(doc,cdt,cdn);
} }
// Get Items Button // Get Items Button
// ----------------- // -----------------
cur_frm.cscript['Get Items'] = function(doc, dt, dn) { cur_frm.cscript['Get Items'] = function(doc, dt, dn) {
var callback = function(r,rt) { var callback = function(r,rt) {
unhide_field(['supplier_address', 'contact_person', 'supplier_name', 'address_display', 'contact_display', 'contact_mobile','contact_email']); unhide_field(['supplier_address', 'contact_person', 'supplier_name', 'address_display', 'contact_display', 'contact_mobile','contact_email']);
refresh_many(['credit_to','supplier','supplier_address','contact_person','supplier_name', 'address_display', 'contact_display','contact_mobile', 'contact_email','entries', 'purchase_receipt_main', 'purchase_order_main', 'purchase_tax_details']); refresh_many(['credit_to','supplier','supplier_address','contact_person','supplier_name', 'address_display', 'contact_display','contact_mobile', 'contact_email','entries', 'purchase_receipt_main', 'purchase_order_main', 'purchase_tax_details']);
} }
$c_obj(make_doclist(dt,dn),'pull_details','',callback); $c_obj(make_doclist(dt,dn),'pull_details','',callback);
} }
// ========== PV Details Table ============ // ========== PV Details Table ============
@ -151,17 +154,17 @@ cur_frm.cscript['Get Items'] = function(doc, dt, dn) {
// Item Code // Item Code
// ---------- // ----------
cur_frm.cscript.item_code = function(doc,cdt,cdn){ cur_frm.cscript.item_code = function(doc,cdt,cdn){
var d = locals[cdt][cdn]; var d = locals[cdt][cdn];
if(d.item_code){ if(d.item_code){
get_server_fields('get_item_details',d.item_code,'entries',doc,cdt,cdn,1); get_server_fields('get_item_details',d.item_code,'entries',doc,cdt,cdn,1);
} }
} }
// Rate in Deduct Taxes (TDS) // Rate in Deduct Taxes (TDS)
// -------------------------- // --------------------------
cur_frm.cscript.rate = function(doc,dt,dn) { cur_frm.cscript.rate = function(doc,dt,dn) {
//This is done as Purchase tax detail and PV detail both contain the same fieldname 'rate' //This is done as Purchase tax detail and PV detail both contain the same fieldname 'rate'
if(dt != 'Purchase Tax Detail') cur_frm.cscript.calc_amount(doc, 2); if(dt != 'Purchase Tax Detail') cur_frm.cscript.calc_amount(doc, 2);
} }
// Amount // Amount
@ -171,41 +174,41 @@ cur_frm.cscript.ded_amount = function(doc,dt,dn) {calculate_outstanding(doc);}
// Get TDS Button // Get TDS Button
// --------------- // ---------------
cur_frm.cscript['Get TDS'] = function(doc, dt, dn) { cur_frm.cscript['Get TDS'] = function(doc, dt, dn) {
var callback = function(r,rt) { var callback = function(r,rt) {
cur_frm.refresh(); cur_frm.refresh();
refresh_field('ded_amount'); refresh_field('ded_amount');
//cur_frm.cscript.calc_total(locals[dt][dn]); //cur_frm.cscript.calc_total(locals[dt][dn]);
} }
$c_obj(make_doclist(dt,dn), 'get_tds', '', callback); $c_obj(make_doclist(dt,dn), 'get_tds', '', callback);
} }
// ===================== Advance Allocation ================== // ===================== Advance Allocation ==================
cur_frm.cscript.allocated_amount = function(doc,cdt,cdn){ cur_frm.cscript.allocated_amount = function(doc,cdt,cdn){
var d = locals[cdt][cdn]; var d = locals[cdt][cdn];
if (d.allocated_amount && d.tds_amount){ if (d.allocated_amount && d.tds_amount){
d.tds_allocated=flt(d.tds_amount*(d.allocated_amount/d.advance_amount)) d.tds_allocated=flt(d.tds_amount*(d.allocated_amount/d.advance_amount))
refresh_field('tds_allocated', d.name, 'advance_allocation_details'); refresh_field('tds_allocated', d.name, 'advance_allocation_details');
} }
tot_tds=0 tot_tds=0
el = getchildren('Advance Allocation Detail',doc.name,'advance_allocation_details') el = getchildren('Advance Allocation Detail',doc.name,'advance_allocation_details')
for(var i in el){ for(var i in el){
tot_tds += el[i].tds_allocated tot_tds += el[i].tds_allocated
} }
doc.tds_amount_on_advance = tot_tds doc.tds_amount_on_advance = tot_tds
refresh_field('tds_amount_on_advance'); refresh_field('tds_amount_on_advance');
calc_total_advance(doc, cdt, cdn); calc_total_advance(doc, cdt, cdn);
} }
// Make Journal Voucher // Make Journal Voucher
// -------------------- // --------------------
cur_frm.cscript['Make Bank Voucher'] = function() { cur_frm.cscript['Make Bank Voucher'] = function() {
$c('accounts.get_default_bank_account', { company: cur_frm.doc.company }, function(r, rt) { $c('accounts.get_default_bank_account', { company: cur_frm.doc.company }, function(r, rt) {
if(!r.exc) { if(!r.exc) {
cur_frm.cscript.make_jv(cur_frm.doc, null, null, r.message); cur_frm.cscript.make_jv(cur_frm.doc, null, null, r.message);
} }
}); });
} }
@ -213,49 +216,49 @@ cur_frm.cscript['Make Bank Voucher'] = function() {
cur_frm.fields_dict['supplier_address'].get_query = function(doc, cdt, cdn) { cur_frm.fields_dict['supplier_address'].get_query = function(doc, cdt, cdn) {
return 'SELECT name,address_line1,city FROM tabAddress WHERE supplier = "'+ doc.supplier +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50'; return 'SELECT name,address_line1,city FROM tabAddress WHERE supplier = "'+ doc.supplier +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
} }
cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) { cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE supplier = "'+ doc.supplier +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50'; return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE supplier = "'+ doc.supplier +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
} }
// Item Code // Item Code
// ---------- // ----------
cur_frm.fields_dict['entries'].grid.get_field("item_code").get_query = function(doc, cdt, cdn) { cur_frm.fields_dict['entries'].grid.get_field("item_code").get_query = function(doc, cdt, cdn) {
return 'SELECT tabItem.name, tabItem.description FROM tabItem WHERE tabItem.is_purchase_item="Yes" AND (IFNULL(`tabItem`.`end_of_life`,"") = "" OR `tabItem`.`end_of_life` ="0000-00-00" OR `tabItem`.`end_of_life` > NOW()) AND tabItem.%(key)s LIKE "%s" LIMIT 50' return 'SELECT tabItem.name, tabItem.description FROM tabItem WHERE tabItem.is_purchase_item="Yes" AND (IFNULL(`tabItem`.`end_of_life`,"") = "" OR `tabItem`.`end_of_life` ="0000-00-00" OR `tabItem`.`end_of_life` > NOW()) AND tabItem.%(key)s LIKE "%s" LIMIT 50'
} }
// Credit To // Credit To
// ---------- // ----------
cur_frm.fields_dict['credit_to'].get_query = function(doc) { cur_frm.fields_dict['credit_to'].get_query = function(doc) {
return 'SELECT tabAccount.name FROM tabAccount WHERE tabAccount.debit_or_credit="Credit" AND tabAccount.is_pl_account="No" AND tabAccount.group_or_ledger="Ledger" AND tabAccount.docstatus != 2 AND tabAccount.company="'+doc.company+'" AND tabAccount.%(key)s LIKE "%s"' return 'SELECT tabAccount.name FROM tabAccount WHERE tabAccount.debit_or_credit="Credit" AND tabAccount.is_pl_account="No" AND tabAccount.group_or_ledger="Ledger" AND tabAccount.docstatus != 2 AND tabAccount.company="'+doc.company+'" AND tabAccount.%(key)s LIKE "%s"'
} }
// Purchase Order // Purchase Order
// --------------- // ---------------
cur_frm.fields_dict['purchase_order_main'].get_query = function(doc) { cur_frm.fields_dict['purchase_order_main'].get_query = function(doc) {
if (doc.supplier){ if (doc.supplier){
return 'SELECT `tabPurchase Order`.`name` FROM `tabPurchase Order` WHERE `tabPurchase Order`.`docstatus` = 1 AND `tabPurchase Order`.supplier = "'+ doc.supplier +'" AND `tabPurchase Order`.`status` != "Stopped" AND ifnull(`tabPurchase Order`.`per_billed`,0) < 100 AND `tabPurchase Order`.`company` = "' + doc.company + '" AND `tabPurchase Order`.%(key)s LIKE "%s" ORDER BY `tabPurchase Order`.`name` DESC LIMIT 50' return 'SELECT `tabPurchase Order`.`name` FROM `tabPurchase Order` WHERE `tabPurchase Order`.`docstatus` = 1 AND `tabPurchase Order`.supplier = "'+ doc.supplier +'" AND `tabPurchase Order`.`status` != "Stopped" AND ifnull(`tabPurchase Order`.`per_billed`,0) < 100 AND `tabPurchase Order`.`company` = "' + doc.company + '" AND `tabPurchase Order`.%(key)s LIKE "%s" ORDER BY `tabPurchase Order`.`name` DESC LIMIT 50'
} else { } else {
return 'SELECT `tabPurchase Order`.`name` FROM `tabPurchase Order` WHERE `tabPurchase Order`.`docstatus` = 1 AND `tabPurchase Order`.`status` != "Stopped" AND ifnull(`tabPurchase Order`.`per_billed`, 0) < 100 AND `tabPurchase Order`.`company` = "' + doc.company + '" AND `tabPurchase Order`.%(key)s LIKE "%s" ORDER BY `tabPurchase Order`.`name` DESC LIMIT 50' return 'SELECT `tabPurchase Order`.`name` FROM `tabPurchase Order` WHERE `tabPurchase Order`.`docstatus` = 1 AND `tabPurchase Order`.`status` != "Stopped" AND ifnull(`tabPurchase Order`.`per_billed`, 0) < 100 AND `tabPurchase Order`.`company` = "' + doc.company + '" AND `tabPurchase Order`.%(key)s LIKE "%s" ORDER BY `tabPurchase Order`.`name` DESC LIMIT 50'
} }
} }
// Purchase Receipt // Purchase Receipt
// ----------------- // -----------------
cur_frm.fields_dict['purchase_receipt_main'].get_query = function(doc) { cur_frm.fields_dict['purchase_receipt_main'].get_query = function(doc) {
if (doc.supplier){ if (doc.supplier){
return 'SELECT `tabPurchase Receipt`.`name` FROM `tabPurchase Receipt` WHERE `tabPurchase Receipt`.`docstatus` = 1 AND `tabPurchase Receipt`.supplier = "'+ doc.supplier +'" AND `tabPurchase Receipt`.`status` != "Stopped" AND ifnull(`tabPurchase Receipt`.`per_billed`, 0) < 100 AND `tabPurchase Receipt`.`company` = "' + doc.company + '" AND `tabPurchase Receipt`.%(key)s LIKE "%s" ORDER BY `tabPurchase Receipt`.`name` DESC LIMIT 50' return 'SELECT `tabPurchase Receipt`.`name` FROM `tabPurchase Receipt` WHERE `tabPurchase Receipt`.`docstatus` = 1 AND `tabPurchase Receipt`.supplier = "'+ doc.supplier +'" AND `tabPurchase Receipt`.`status` != "Stopped" AND ifnull(`tabPurchase Receipt`.`per_billed`, 0) < 100 AND `tabPurchase Receipt`.`company` = "' + doc.company + '" AND `tabPurchase Receipt`.%(key)s LIKE "%s" ORDER BY `tabPurchase Receipt`.`name` DESC LIMIT 50'
} else { } else {
return 'SELECT `tabPurchase Receipt`.`name` FROM `tabPurchase Receipt` WHERE `tabPurchase Receipt`.`docstatus` = 1 AND `tabPurchase Receipt`.`status` != "Stopped" AND ifnull(`tabPurchase Receipt`.`per_billed`, 0) < 100 AND `tabPurchase Receipt`.`company` = "' + doc.company + '" AND `tabPurchase Receipt`.%(key)s LIKE "%s" ORDER BY `tabPurchase Receipt`.`name` DESC LIMIT 50' return 'SELECT `tabPurchase Receipt`.`name` FROM `tabPurchase Receipt` WHERE `tabPurchase Receipt`.`docstatus` = 1 AND `tabPurchase Receipt`.`status` != "Stopped" AND ifnull(`tabPurchase Receipt`.`per_billed`, 0) < 100 AND `tabPurchase Receipt`.`company` = "' + doc.company + '" AND `tabPurchase Receipt`.%(key)s LIKE "%s" ORDER BY `tabPurchase Receipt`.`name` DESC LIMIT 50'
} }
} }
// Get Print Heading // Get Print Heading
cur_frm.fields_dict['select_print_heading'].get_query = function(doc, cdt, cdn) { cur_frm.fields_dict['select_print_heading'].get_query = function(doc, cdt, cdn) {
return 'SELECT `tabPrint Heading`.name FROM `tabPrint Heading` WHERE `tabPrint Heading`.docstatus !=2 AND `tabPrint Heading`.name LIKE "%s" ORDER BY `tabPrint Heading`.name ASC LIMIT 50'; return 'SELECT `tabPrint Heading`.name FROM `tabPrint Heading` WHERE `tabPrint Heading`.docstatus !=2 AND `tabPrint Heading`.name LIKE "%s" ORDER BY `tabPrint Heading`.name ASC LIMIT 50';
} }
@ -263,45 +266,45 @@ cur_frm.fields_dict['select_print_heading'].get_query = function(doc, cdt, cdn)
// Expense Head // Expense Head
// ------------- // -------------
cur_frm.fields_dict['entries'].grid.get_field("expense_head").get_query = function(doc) { cur_frm.fields_dict['entries'].grid.get_field("expense_head").get_query = function(doc) {
return 'SELECT tabAccount.name FROM tabAccount WHERE tabAccount.debit_or_credit="Debit" AND tabAccount.group_or_ledger="Ledger" AND tabAccount.docstatus != 2 AND tabAccount.company="'+doc.company+'" AND tabAccount.%(key)s LIKE "%s"'; return 'SELECT tabAccount.name FROM tabAccount WHERE tabAccount.debit_or_credit="Debit" AND tabAccount.group_or_ledger="Ledger" AND tabAccount.docstatus != 2 AND tabAccount.company="'+doc.company+'" AND tabAccount.%(key)s LIKE "%s"';
} }
cur_frm.cscript.expense_head = function(doc, cdt, cdn){ cur_frm.cscript.expense_head = function(doc, cdt, cdn){
var d = locals[cdt][cdn]; var d = locals[cdt][cdn];
if(d.idx == 1 && d.expense_head){ if(d.idx == 1 && d.expense_head){
var cl = getchildren('PV Detail', doc.name, 'entries', doc.doctype); var cl = getchildren('PV Detail', doc.name, 'entries', doc.doctype);
for(var i = 0; i < cl.length; i++){ for(var i = 0; i < cl.length; i++){
if(!cl[i].expense_head) cl[i].expense_head = d.expense_head; if(!cl[i].expense_head) cl[i].expense_head = d.expense_head;
} }
} }
refresh_field('entries'); refresh_field('entries');
} }
// Cost Center // Cost Center
//------------- //-------------
cur_frm.fields_dict['entries'].grid.get_field("cost_center").get_query = function(doc) { cur_frm.fields_dict['entries'].grid.get_field("cost_center").get_query = function(doc) {
return 'SELECT `tabCost Center`.`name` FROM `tabCost Center` WHERE `tabCost Center`.`company_name` = "' +doc.company+'" AND `tabCost Center`.%(key)s LIKE "%s" AND `tabCost Center`.`group_or_ledger` = "Ledger" AND `tabCost Center`.docstatus != 2 ORDER BY `tabCost Center`.`name` ASC LIMIT 50'; return 'SELECT `tabCost Center`.`name` FROM `tabCost Center` WHERE `tabCost Center`.`company_name` = "' +doc.company+'" AND `tabCost Center`.%(key)s LIKE "%s" AND `tabCost Center`.`group_or_ledger` = "Ledger" AND `tabCost Center`.docstatus != 2 ORDER BY `tabCost Center`.`name` ASC LIMIT 50';
} }
cur_frm.cscript.cost_center = function(doc, cdt, cdn){ cur_frm.cscript.cost_center = function(doc, cdt, cdn){
var d = locals[cdt][cdn]; var d = locals[cdt][cdn];
if(d.idx == 1 && d.cost_center){ if(d.idx == 1 && d.cost_center){
var cl = getchildren('PV Detail', doc.name, 'entries', doc.doctype); var cl = getchildren('PV Detail', doc.name, 'entries', doc.doctype);
for(var i = 0; i < cl.length; i++){ for(var i = 0; i < cl.length; i++){
if(!cl[i].cost_center) cl[i].cost_center = d.cost_center; if(!cl[i].cost_center) cl[i].cost_center = d.cost_center;
} }
} }
refresh_field('entries'); refresh_field('entries');
} }
// TDS Account Head // TDS Account Head
cur_frm.fields_dict['tax_code'].get_query = function(doc) { cur_frm.fields_dict['tax_code'].get_query = function(doc) {
return "SELECT `tabTDS Category Account`.account_head FROM `tabTDS Category Account` WHERE `tabTDS Category Account`.parent = '"+doc.tds_category+"' AND `tabTDS Category Account`.company='"+doc.company+"' AND `tabTDS Category Account`.account_head LIKE '%s' ORDER BY `tabTDS Category Account`.account_head DESC LIMIT 50"; return "SELECT `tabTDS Category Account`.account_head FROM `tabTDS Category Account` WHERE `tabTDS Category Account`.parent = '"+doc.tds_category+"' AND `tabTDS Category Account`.company='"+doc.company+"' AND `tabTDS Category Account`.account_head LIKE '%s' ORDER BY `tabTDS Category Account`.account_head DESC LIMIT 50";
} }
cur_frm.cscript.tax_code = function(doc, dt, dn) { cur_frm.cscript.tax_code = function(doc, dt, dn) {
get_server_fields('get_tds_rate','','',doc, dt, dn, 0); get_server_fields('get_tds_rate','','',doc, dt, dn, 0);
} }
/* ***************************** UTILITY FUNCTIONS ************************ */ /* ***************************** UTILITY FUNCTIONS ************************ */
@ -309,69 +312,69 @@ cur_frm.cscript.tax_code = function(doc, dt, dn) {
// Calculate Advance // Calculate Advance
// ------------------ // ------------------
var calc_total_advance = function(doc,cdt,cdn) { var calc_total_advance = function(doc,cdt,cdn) {
var doc = locals[doc.doctype][doc.name]; var doc = locals[doc.doctype][doc.name];
var el = getchildren('Advance Allocation Detail',doc.name,'advance_allocation_details') var el = getchildren('Advance Allocation Detail',doc.name,'advance_allocation_details')
var tot_tds=0; var tot_tds=0;
var total_advance = 0; var total_advance = 0;
for(var i in el) { for(var i in el) {
if (! el[i].allocated_amount == 0) { if (! el[i].allocated_amount == 0) {
total_advance += flt(el[i].allocated_amount); total_advance += flt(el[i].allocated_amount);
tot_tds += flt(el[i].tds_allocated) tot_tds += flt(el[i].tds_allocated)
} }
} }
doc.total_amount_to_pay = flt(doc.grand_total) - flt(doc.ded_amount); doc.total_amount_to_pay = flt(doc.grand_total) - flt(doc.ded_amount);
doc.tds_amount_on_advance = flt(tot_tds); doc.tds_amount_on_advance = flt(tot_tds);
doc.total_advance = flt(total_advance); doc.total_advance = flt(total_advance);
doc.outstanding_amount = flt(doc.total_amount_to_pay) - flt(total_advance); doc.outstanding_amount = flt(doc.total_amount_to_pay) - flt(total_advance);
refresh_many(['total_advance','outstanding_amount','tds_amount_on_advance', 'total_amount_to_pay']); refresh_many(['total_advance','outstanding_amount','tds_amount_on_advance', 'total_amount_to_pay']);
} }
// Make JV // Make JV
// -------- // --------
cur_frm.cscript.make_jv = function(doc, dt, dn, bank_account) { cur_frm.cscript.make_jv = function(doc, dt, dn, bank_account) {
var jv = LocalDB.create('Journal Voucher'); var jv = LocalDB.create('Journal Voucher');
jv = locals['Journal Voucher'][jv]; jv = locals['Journal Voucher'][jv];
jv.voucher_type = 'Bank Voucher'; jv.voucher_type = 'Bank Voucher';
jv.remark = repl('Payment against voucher %(vn)s for %(rem)s', {vn:doc.name, rem:doc.remarks}); jv.remark = repl('Payment against voucher %(vn)s for %(rem)s', {vn:doc.name, rem:doc.remarks});
jv.total_debit = doc.outstanding_amount; jv.total_debit = doc.outstanding_amount;
jv.total_credit = doc.outstanding_amount; jv.total_credit = doc.outstanding_amount;
jv.fiscal_year = doc.fiscal_year; jv.fiscal_year = doc.fiscal_year;
jv.company = doc.company; jv.company = doc.company;
// debit to creditor // debit to creditor
var d1 = LocalDB.add_child(jv, 'Journal Voucher Detail', 'entries'); var d1 = LocalDB.add_child(jv, 'Journal Voucher Detail', 'entries');
d1.account = doc.credit_to; d1.account = doc.credit_to;
d1.debit = doc.outstanding_amount; d1.debit = doc.outstanding_amount;
d1.against_voucher = doc.name; d1.against_voucher = doc.name;
// credit to bank // credit to bank
var d1 = LocalDB.add_child(jv, 'Journal Voucher Detail', 'entries'); var d1 = LocalDB.add_child(jv, 'Journal Voucher Detail', 'entries');
d1.account = bank_account; d1.account = bank_account;
d1.credit = doc.outstanding_amount; d1.credit = doc.outstanding_amount;
loaddoc('Journal Voucher', jv.name); loaddoc('Journal Voucher', jv.name);
} }
// ***************** Get project name ***************** // ***************** Get project name *****************
cur_frm.fields_dict['entries'].grid.get_field('project_name').get_query = function(doc, cdt, cdn) { cur_frm.fields_dict['entries'].grid.get_field('project_name').get_query = function(doc, cdt, cdn) {
return 'SELECT `tabProject`.name FROM `tabProject` WHERE `tabProject`.status = "Open" AND `tabProject`.name LIKE "%s" ORDER BY `tabProject`.name ASC LIMIT 50'; return 'SELECT `tabProject`.name FROM `tabProject` WHERE `tabProject`.status = "Open" AND `tabProject`.name LIKE "%s" ORDER BY `tabProject`.name ASC LIMIT 50';
} }
cur_frm.cscript.select_print_heading = function(doc,cdt,cdn){ cur_frm.cscript.select_print_heading = function(doc,cdt,cdn){
if(doc.select_print_heading){ if(doc.select_print_heading){
// print heading // print heading
cur_frm.pformat.print_heading = doc.select_print_heading; cur_frm.pformat.print_heading = doc.select_print_heading;
} }
else else
cur_frm.pformat.print_heading = "Purchase Invoice"; cur_frm.pformat.print_heading = "Purchase Invoice";
} }
/****************** Get Accounting Entry *****************/ /****************** Get Accounting Entry *****************/
cur_frm.cscript['View Ledger Entry'] = function(){ cur_frm.cscript['View Ledger Entry'] = function(){
var callback = function(report){ var callback = function(report){
report.set_filter('GL Entry', 'Voucher No',cur_frm.doc.name); report.set_filter('GL Entry', 'Voucher No',cur_frm.doc.name);
report.dt.run(); report.dt.run();
} }
loadreport('GL Entry','General Ledger', callback); loadreport('GL Entry','General Ledger', callback);
} }

View File

@ -92,7 +92,19 @@ class DocType(TransactionBase):
# Get Item Details # Get Item Details
# ----------------- # -----------------
def get_item_details(self,arg): def get_item_details(self, arg=None):
if arg:
return self.get_pv_details(arg)
else:
for doc in self.doclist:
if doc.fields.get('item_code'):
ret = self.get_pv_details(doc.item_code)
for r in ret:
if not doc.fields.get(r):
doc.fields[r] = ret[r]
def get_pv_details(self, arg):
item_det = sql("select item_name, brand, description, item_group,purchase_account,cost_center from tabItem where name=%s",arg,as_dict=1) item_det = sql("select item_name, brand, description, item_group,purchase_account,cost_center from tabItem where name=%s",arg,as_dict=1)
tax = sql("select tax_type, tax_rate from `tabItem Tax` where parent = %s" , arg) tax = sql("select tax_type, tax_rate from `tabItem Tax` where parent = %s" , arg)
t = {} t = {}
@ -110,6 +122,8 @@ class DocType(TransactionBase):
'item_tax_rate' : str(t) 'item_tax_rate' : str(t)
} }
return ret return ret
# Advance Allocation # Advance Allocation
# ------------------- # -------------------

View File

@ -25,6 +25,9 @@ cur_frm.cscript.onload = function(doc,dt,dn) {
if(doc.is_pos ==1) cur_frm.cscript.is_pos(doc, dt, dn); if(doc.is_pos ==1) cur_frm.cscript.is_pos(doc, dt, dn);
hide_field(['customer_address', 'contact_person', 'customer_name', 'address_display', 'contact_display', 'contact_mobile', 'contact_email', 'territory', 'customer_group']); hide_field(['customer_address', 'contact_person', 'customer_name', 'address_display', 'contact_display', 'contact_mobile', 'contact_email', 'territory', 'customer_group']);
// defined in sales_common.js
cur_frm.cscript.update_item_details(doc, cdt, cdn);
} }
} }

View File

@ -147,8 +147,22 @@ class DocType(TransactionBase):
# Item Details # Item Details
# ------------- # -------------
def get_item_details(self, item_code): def get_item_details(self, item_code=None):
ret = get_obj('Sales Common').get_item_details(item_code, self) if item_code:
ret = get_obj('Sales Common').get_item_details(item_code, self)
return self.get_pos_details(item_code, ret)
else:
obj = get_obj('Sales Common')
for doc in self.doclist:
if doc.fields.get('item_code'):
ret = obj.get_item_details(doc.item_code, self)
ret = self.get_pos_details(item_code, ret)
for r in ret:
if not doc.fields.get(r):
doc.fields[r] = ret[r]
def get_pos_details(self, item_code, ret):
if item_code and cint(self.doc.is_pos) == 1: if item_code and cint(self.doc.is_pos) == 1:
dtl = webnotes.conn.sql("select income_account, warehouse, cost_center from `tabPOS Setting` where user = '%s' and company = '%s'" % (session['user'], self.doc.company), as_dict=1) dtl = webnotes.conn.sql("select income_account, warehouse, cost_center from `tabPOS Setting` where user = '%s' and company = '%s'" % (session['user'], self.doc.company), as_dict=1)
if not dtl: if not dtl:
@ -160,7 +174,8 @@ class DocType(TransactionBase):
actual_qty = webnotes.conn.sql("select actual_qty from `tabBin` where item_code = '%s' and warehouse = '%s'" % (item_code, ret['warehouse'])) actual_qty = webnotes.conn.sql("select actual_qty from `tabBin` where item_code = '%s' and warehouse = '%s'" % (item_code, ret['warehouse']))
ret['actual_qty']= actual_qty and flt(actual_qty[0][0]) or 0 ret['actual_qty']= actual_qty and flt(actual_qty[0][0]) or 0
return ret return ret
# Fetch ref rate from item master as per selected price list # Fetch ref rate from item master as per selected price list
def get_adj_percent(self, arg=''): def get_adj_percent(self, arg=''):
get_obj('Sales Common').get_adj_percent(self) get_obj('Sales Common').get_adj_percent(self)

View File

@ -3,76 +3,78 @@ cur_frm.cscript.fname = "indent_details";
$import(Purchase Common) $import(Purchase Common)
$import(SMS Control) $import(SMS Control)
cur_frm.cscript.indent_doctype_label = get_doctype_label('Indent'); cur_frm.cscript.indent_doctype_label = get_doctype_label('Indent');
//========================== On Load ================================================= //========================== On Load =================================================
cur_frm.cscript.onload = function(doc, cdt, cdn) { cur_frm.cscript.onload = function(doc, cdt, cdn) {
if (!doc.transaction_date) doc.transaction_date = dateutil.obj_to_str(new Date()) if (!doc.transaction_date) doc.transaction_date = dateutil.obj_to_str(new Date())
if (!doc.status) doc.status = 'Draft'; if (!doc.status) doc.status = 'Draft';
// defined in purchase_common.js
//cur_frm.cscript.update_item_details(doc, cdt, cdn);
} }
cur_frm.cscript.onload_post_render = function(doc, cdt, cdn) { cur_frm.cscript.onload_post_render = function(doc, cdt, cdn) {
// second call // second call
if(doc.__islocal){ if(doc.__islocal){
cur_frm.cscript.get_item_defaults(doc); cur_frm.cscript.get_item_defaults(doc);
} }
} }
cur_frm.cscript.get_item_defaults = function(doc) { cur_frm.cscript.get_item_defaults = function(doc) {
var ch = getchildren( 'Indent Detail', doc.name, 'indent_details'); var ch = getchildren( 'Indent Detail', doc.name, 'indent_details');
if (flt(ch.length) > 0){ if (flt(ch.length) > 0){
$c_obj(make_doclist(doc.doctype, doc.name), 'get_item_defaults', '', function(r, rt) {refresh_field('indent_details'); }); $c_obj(make_doclist(doc.doctype, doc.name), 'get_item_defaults', '', function(r, rt) {refresh_field('indent_details'); });
} }
} }
//======================= Refresh ===================================== //======================= Refresh =====================================
cur_frm.cscript.refresh = function(doc, cdt, cdn) { cur_frm.cscript.refresh = function(doc, cdt, cdn) {
// Unhide Fields in Next Steps // Unhide Fields in Next Steps
// --------------------------------- // ---------------------------------
cur_frm.clear_custom_buttons(); cur_frm.clear_custom_buttons();
if(doc.docstatus == 1 && doc.status != 'Stopped'){ if(doc.docstatus == 1 && doc.status != 'Stopped'){
var ch = getchildren('Indent Detail',doc.name,'indent_details'); var ch = getchildren('Indent Detail',doc.name,'indent_details');
var is_closed = 1; var is_closed = 1;
for(var i in ch){ for(var i in ch){
if(flt(ch[i].qty) > flt(ch[i].ordered_qty)) is_closed = 0; if(flt(ch[i].qty) > flt(ch[i].ordered_qty)) is_closed = 0;
} }
if(!is_closed) { if(!is_closed) {
cur_frm.add_custom_button('Make Purchase Order', cur_frm.cscript['Make Purchase Order']) cur_frm.add_custom_button('Make Purchase Order', cur_frm.cscript['Make Purchase Order'])
cur_frm.add_custom_button('Stop ' + cur_frm.cscript.indent_doctype_label, cur_frm.cscript['Stop Purchase Requisition']) cur_frm.add_custom_button('Stop ' + cur_frm.cscript.indent_doctype_label, cur_frm.cscript['Stop Purchase Requisition'])
} }
cur_frm.add_custom_button('Send SMS', cur_frm.cscript['Send SMS']); cur_frm.add_custom_button('Send SMS', cur_frm.cscript['Send SMS']);
} }
if(doc.docstatus == 1 && doc.status == 'Stopped') if(doc.docstatus == 1 && doc.status == 'Stopped')
cur_frm.add_custom_button('Unstop ' + cur_frm.cscript.indent_doctype_label, cur_frm.cscript['Unstop Purchase Requisition']) cur_frm.add_custom_button('Unstop ' + cur_frm.cscript.indent_doctype_label, cur_frm.cscript['Unstop Purchase Requisition'])
if(doc.docstatus == 1) if(doc.docstatus == 1)
unhide_field(['Repair Purchase Requisition']); unhide_field(['Repair Purchase Requisition']);
else else
hide_field(['Repair Purchase Requisition']); hide_field(['Repair Purchase Requisition']);
} }
//======================= validation =================================== //======================= validation ===================================
cur_frm.cscript.validate = function(doc,cdt,cdn){ cur_frm.cscript.validate = function(doc,cdt,cdn){
is_item_table(doc,cdt,cdn); is_item_table(doc,cdt,cdn);
} }
//======================= transaction date ============================= //======================= transaction date =============================
cur_frm.cscript.transaction_date = function(doc,cdt,cdn){ cur_frm.cscript.transaction_date = function(doc,cdt,cdn){
if(doc.__islocal){ if(doc.__islocal){
cur_frm.cscript.get_default_schedule_date(doc); cur_frm.cscript.get_default_schedule_date(doc);
} }
} }
//=================== Quantity =================================================================== //=================== Quantity ===================================================================
cur_frm.cscript.qty = function(doc, cdt, cdn) { cur_frm.cscript.qty = function(doc, cdt, cdn) {
var d = locals[cdt][cdn]; var d = locals[cdt][cdn];
if (flt(d.qty) < flt(d.min_order_qty)) if (flt(d.qty) < flt(d.min_order_qty))
alert("Warning: " + cur_frm.cscript.indent_doctype_label + " Qty is less than Minimum Order Qty"); alert("Warning: " + cur_frm.cscript.indent_doctype_label + " Qty is less than Minimum Order Qty");
} }
// On Button Click Functions // On Button Click Functions
@ -80,43 +82,43 @@ cur_frm.cscript.qty = function(doc, cdt, cdn) {
// Make Purchase Order // Make Purchase Order
cur_frm.cscript['Make Purchase Order'] = function() { cur_frm.cscript['Make Purchase Order'] = function() {
var doc = cur_frm.doc; var doc = cur_frm.doc;
n = createLocal('Purchase Order'); n = createLocal('Purchase Order');
$c('dt_map', args={ $c('dt_map', args={
'docs':compress_doclist([locals['Purchase Order'][n]]), 'docs':compress_doclist([locals['Purchase Order'][n]]),
'from_doctype':doc.doctype, 'from_doctype':doc.doctype,
'to_doctype':'Purchase Order', 'to_doctype':'Purchase Order',
'from_docname':doc.name, 'from_docname':doc.name,
'from_to_list':"[['Indent','Purchase Order'],['Indent Detail','PO Detail']]" 'from_to_list':"[['Indent','Purchase Order'],['Indent Detail','PO Detail']]"
}, function(r,rt) { }, function(r,rt) {
loaddoc('Purchase Order', n); loaddoc('Purchase Order', n);
} }
); );
} }
// Stop INDENT // Stop INDENT
// ================================================================================================== // ==================================================================================================
cur_frm.cscript['Stop Purchase Requisition'] = function() { cur_frm.cscript['Stop Purchase Requisition'] = function() {
var doc = cur_frm.doc; var doc = cur_frm.doc;
var check = confirm("Do you really want to STOP this " + cur_frm.cscript.indent_doctype_label + "?"); var check = confirm("Do you really want to STOP this " + cur_frm.cscript.indent_doctype_label + "?");
if (check) { if (check) {
$c('runserverobj', args={'method':'update_status', 'arg': 'Stopped', 'docs': compress_doclist(make_doclist(doc.doctype, doc.name))}, function(r,rt) { $c('runserverobj', args={'method':'update_status', 'arg': 'Stopped', 'docs': compress_doclist(make_doclist(doc.doctype, doc.name))}, function(r,rt) {
cur_frm.refresh(); cur_frm.refresh();
}); });
} }
} }
// Un Stop INDENT // Un Stop INDENT
//==================================================================================================== //====================================================================================================
cur_frm.cscript['Unstop Purchase Requisition'] = function(){ cur_frm.cscript['Unstop Purchase Requisition'] = function(){
var doc = cur_frm.doc var doc = cur_frm.doc
var check = confirm("Do you really want to UNSTOP this " + cur_frm.cscript.indent_doctype_label + "?"); var check = confirm("Do you really want to UNSTOP this " + cur_frm.cscript.indent_doctype_label + "?");
if (check) { if (check) {
$c('runserverobj', args={'method':'update_status', 'arg': 'Submitted','docs': compress_doclist(make_doclist(doc.doctype, doc.name))}, function(r,rt) { $c('runserverobj', args={'method':'update_status', 'arg': 'Submitted','docs': compress_doclist(make_doclist(doc.doctype, doc.name))}, function(r,rt) {
cur_frm.refresh(); cur_frm.refresh();
}); });
} }
} }

View File

@ -90,7 +90,21 @@ class DocType:
# get item details # get item details
# --------------------------------- # ---------------------------------
def get_item_details(self, arg =''): def get_item_details(self, arg =''):
return get_obj(dt='Purchase Common').get_item_details(self,arg) if arg:
return get_obj(dt='Purchase Common').get_item_details(self,arg)
else:
obj = get_obj('Purchase Common')
for doc in self.doclist:
if doc.fields.get('item_code'):
temp = {
'item_code': doc.fields.get('item_code'),
'warehouse': doc.fields.get('warehouse')
}
ret = obj.get_item_details(self, json.dumps(temp))
for r in ret:
if not doc.fields.get(r):
doc.fields[r] = ret[r]
# Get UOM Details # Get UOM Details
# --------------------------------- # ---------------------------------

View File

@ -7,389 +7,433 @@ var fname = cur_frm.cscript.fname;
cur_frm.cscript.get_default_schedule_date = function(doc) { cur_frm.cscript.get_default_schedule_date = function(doc) {
var ch = getchildren( tname, doc.name, fname); var ch = getchildren( tname, doc.name, fname);
if (flt(ch.length) > 0){ if (flt(ch.length) > 0){
$c_obj(make_doclist(doc.doctype, doc.name), 'get_default_schedule_date', '', function(r, rt) { refresh_field(fname); }); $c_obj(make_doclist(doc.doctype, doc.name), 'get_default_schedule_date', '', function(r, rt) { refresh_field(fname); });
} }
}
// Gets called after existing item details are update to fill in
// remaining default values
cur_frm.cscript.load_defaults = function(doc, dt, dn) {
if(!cur_frm.doc.__islocal) { return; }
doc = locals[doc.doctype][doc.name];
var fields_to_refresh = LocalDB.set_default_values(doc);
if(fields_to_refresh) { refresh_many(fields_to_refresh); }
fields_to_refresh = null;
var children = getchildren(cur_frm.cscript.tname, doc.name, cur_frm.cscript.fname);
if(!children) { return; }
for(var i=0; i<children.length; i++) {
LocalDB.set_default_values(children[i]);
}
refresh_field(cur_frm.cscript.fname);
}
// Update existing item details
cur_frm.cscript.update_item_details = function(doc, dt, dn) {
if(!cur_frm.doc.__islocal) return;
var children = getchildren(cur_frm.cscript.tname, doc.name, cur_frm.cscript.fname);
if(children) {
$c_obj(make_doclist(doc.doctype, doc.name), 'get_item_details', '',
function(r, rt) {
if(!r.exc) {
refresh_field(cur_frm.cscript.fname);
doc = locals[doc.doctype][doc.name];
cur_frm.cscript.load_defaults(doc, dt, dn);
}
});
}
} }
// ======================== Conversion Rate ========================================== // ======================== Conversion Rate ==========================================
cur_frm.cscript.conversion_rate = function(doc,cdt,cdn) { cur_frm.cscript.conversion_rate = function(doc,cdt,cdn) {
cur_frm.cscript.calc_amount( doc, 1); cur_frm.cscript.calc_amount( doc, 1);
} }
//==================== Item Code Get Query ======================================================= //==================== Item Code Get Query =======================================================
// Only Is Purchase Item = 'Yes' and Items not moved to trash are allowed. // Only Is Purchase Item = 'Yes' and Items not moved to trash are allowed.
cur_frm.fields_dict[fname].grid.get_field("item_code").get_query = function(doc, cdt, cdn) { cur_frm.fields_dict[fname].grid.get_field("item_code").get_query = function(doc, cdt, cdn) {
return 'SELECT tabItem.name, tabItem.description FROM tabItem WHERE tabItem.is_purchase_item="Yes" AND (IFNULL(`tabItem`.`end_of_life`,"") = "" OR `tabItem`.`end_of_life` ="0000-00-00" OR `tabItem`.`end_of_life` > NOW()) AND tabItem.%(key)s LIKE "%s" LIMIT 50' return 'SELECT tabItem.name, tabItem.description FROM tabItem WHERE tabItem.is_purchase_item="Yes" AND (IFNULL(`tabItem`.`end_of_life`,"") = "" OR `tabItem`.`end_of_life` ="0000-00-00" OR `tabItem`.`end_of_life` > NOW()) AND tabItem.%(key)s LIKE "%s" LIMIT 50'
} }
//==================== Get Item Code Details ===================================================== //==================== Get Item Code Details =====================================================
cur_frm.cscript.item_code = function(doc,cdt,cdn) { cur_frm.cscript.item_code = function(doc,cdt,cdn) {
var d = locals[cdt][cdn]; var d = locals[cdt][cdn];
if (d.item_code) { if (d.item_code) {
temp = "{'item_code':'"+(d.item_code?d.item_code:'')+"', 'warehouse':'"+(d.warehouse?d.warehouse:'')+"'}" temp = {
get_server_fields('get_item_details', temp, fname, doc, cdt, cdn, 1); item_code: d.item_code || '',
} warehouse: d.warehouse || ''
}
get_server_fields('get_item_details', JSON.stringify(temp), fname, doc, cdt, cdn, 1);
}
} }
//==================== Update Stock Qty ========================================================== //==================== Update Stock Qty ==========================================================
cur_frm.cscript.update_stock_qty = function(doc,cdt,cdn){ cur_frm.cscript.update_stock_qty = function(doc,cdt,cdn){
d = locals[cdt][cdn] d = locals[cdt][cdn]
// Step 1:=> Check if qty , uom, conversion_factor // Step 1:=> Check if qty , uom, conversion_factor
if (d.qty && d.uom && d.conversion_factor){ if (d.qty && d.uom && d.conversion_factor){
// Step 2:=> Set stock_qty = qty * conversion_factor // Step 2:=> Set stock_qty = qty * conversion_factor
d.stock_qty = flt(flt(d.qty) * flt(d.conversion_factor)); d.stock_qty = flt(flt(d.qty) * flt(d.conversion_factor));
// Step 3:=> Refer stock_qty field a that particular row. // Step 3:=> Refer stock_qty field a that particular row.
refresh_field('stock_qty' , d.name,fname); refresh_field('stock_qty' , d.name,fname);
} }
} }
//==================== UOM ====================================================================== //==================== UOM ======================================================================
cur_frm.cscript.uom = function(doc, cdt, cdn) { cur_frm.cscript.uom = function(doc, cdt, cdn) {
var d = locals[cdt][cdn]; var d = locals[cdt][cdn];
if (d.item_code && d.uom) { if (d.item_code && d.uom) {
call_back = function(doc, cdt, cdn){ call_back = function(doc, cdt, cdn){
cur_frm.cscript.calc_amount(doc, 2); cur_frm.cscript.calc_amount(doc, 2);
} }
str_arg = {'item_code':d.item_code, 'uom':d.uom, 'stock_qty':flt(d.stock_qty), 'qty': flt(d.qty), 'conversion_rate':doc.conversion_rate} str_arg = {'item_code':d.item_code, 'uom':d.uom, 'stock_qty':flt(d.stock_qty), 'qty': flt(d.qty), 'conversion_rate':doc.conversion_rate}
// Updates Conversion Factor, Qty and Purchase Rate // Updates Conversion Factor, Qty and Purchase Rate
get_server_fields('get_uom_details',JSON.stringify(str_arg), fname, doc,cdt,cdn,1, call_back); get_server_fields('get_uom_details',JSON.stringify(str_arg), fname, doc,cdt,cdn,1, call_back);
// don't make mistake of calling update_stock_qty() the get_uom_details returns stock_qty as per conversion factor properly // don't make mistake of calling update_stock_qty() the get_uom_details returns stock_qty as per conversion factor properly
} }
} }
//==================== Conversion factor ========================================================= //==================== Conversion factor =========================================================
cur_frm.cscript.conversion_factor = function(doc, cdt, cdn) { cur_frm.cscript.conversion_factor = function(doc, cdt, cdn) {
cur_frm.cscript.uom(doc, cdt, cdn); cur_frm.cscript.uom(doc, cdt, cdn);
} }
//==================== stock qty ====================================================================== //==================== stock qty ======================================================================
cur_frm.cscript.stock_qty = function(doc, cdt, cdn) { cur_frm.cscript.stock_qty = function(doc, cdt, cdn) {
var d = locals[cdt][cdn]; var d = locals[cdt][cdn];
if(d.uom && d.qty){ if(d.uom && d.qty){
d.conversion_factor = flt(d.stock_qty)/flt(d.qty); d.conversion_factor = flt(d.stock_qty)/flt(d.qty);
refresh_field('conversion_factor', d.name, fname); refresh_field('conversion_factor', d.name, fname);
} }
} }
//==================== Warehouse ================================================================ //==================== Warehouse ================================================================
cur_frm.cscript.warehouse = function(doc, cdt, cdn) { cur_frm.cscript.warehouse = function(doc, cdt, cdn) {
var d = locals[cdt][cdn]; var d = locals[cdt][cdn];
if (d.item_code && d.warehouse) { if (d.item_code && d.warehouse) {
str_arg = "{'item_code':'" + (d.item_code?d.item_code:'') + "', 'warehouse':'" + (d.warehouse?d.warehouse:'') + "'}" str_arg = "{'item_code':'" + (d.item_code?d.item_code:'') + "', 'warehouse':'" + (d.warehouse?d.warehouse:'') + "'}"
get_server_fields('get_bin_details', str_arg, fname, doc, cdt, cdn, 1); get_server_fields('get_bin_details', str_arg, fname, doc, cdt, cdn, 1);
} }
} }
//=================== Quantity =================================================================== //=================== Quantity ===================================================================
cur_frm.cscript.qty = function(doc, cdt, cdn) { cur_frm.cscript.qty = function(doc, cdt, cdn) {
var d = locals[cdt][cdn]; var d = locals[cdt][cdn];
// Step 1: => Update Stock Qty // Step 1: => Update Stock Qty
cur_frm.cscript.update_stock_qty(doc,cdt,cdn); cur_frm.cscript.update_stock_qty(doc,cdt,cdn);
// Step 2: => Calculate Amount // Step 2: => Calculate Amount
cur_frm.cscript.calc_amount(doc, 2); cur_frm.cscript.calc_amount(doc, 2);
} }
//=================== Purchase Rate ============================================================== //=================== Purchase Rate ==============================================================
cur_frm.cscript.purchase_rate = function(doc, cdt, cdn) { cur_frm.cscript.purchase_rate = function(doc, cdt, cdn) {
cur_frm.cscript.calc_amount(doc, 2); cur_frm.cscript.calc_amount(doc, 2);
} }
//==================== Import Rate ================================================================ //==================== Import Rate ================================================================
cur_frm.cscript.import_rate = function(doc, cdt, cdn) { cur_frm.cscript.import_rate = function(doc, cdt, cdn) {
cur_frm.cscript.calc_amount(doc, 1); cur_frm.cscript.calc_amount(doc, 1);
} }
//==================== Discount Rate ================================================================ //==================== Discount Rate ================================================================
cur_frm.cscript.discount_rate = function(doc, cdt, cdn) { cur_frm.cscript.discount_rate = function(doc, cdt, cdn) {
cur_frm.cscript.calc_amount(doc, 4); cur_frm.cscript.calc_amount(doc, 4);
} }
//==================== Purchase Ref Rate ================================================================ //==================== Purchase Ref Rate ================================================================
cur_frm.cscript.purchase_ref_rate = function(doc, cdt, cdn) { cur_frm.cscript.purchase_ref_rate = function(doc, cdt, cdn) {
cur_frm.cscript.calc_amount(doc, 4); cur_frm.cscript.calc_amount(doc, 4);
} }
//==================== Import Ref Rate ================================================================ //==================== Import Ref Rate ================================================================
cur_frm.cscript.import_ref_rate = function(doc, cdt, cdn) { cur_frm.cscript.import_ref_rate = function(doc, cdt, cdn) {
cur_frm.cscript.calc_amount(doc, 5); cur_frm.cscript.calc_amount(doc, 5);
} }
//==================== check if item table is blank ============================================== //==================== check if item table is blank ==============================================
var is_item_table = function(doc,cdt,cdn) { var is_item_table = function(doc,cdt,cdn) {
// Step 1 :=>Get all childrens/ rows from Detail Table // Step 1 :=>Get all childrens/ rows from Detail Table
var cl = getchildren(tname, doc.name, fname); var cl = getchildren(tname, doc.name, fname);
// Step 2 :=> If there are no rows then set validated = false, I hope this will stop further execution of code. // Step 2 :=> If there are no rows then set validated = false, I hope this will stop further execution of code.
if (cl.length == 0) { if (cl.length == 0) {
alert("There is no item in table"); validated = false; alert("There is no item in table"); validated = false;
} }
} }
//==================== Validate ==================================================================== //==================== Validate ====================================================================
cur_frm.cscript.validate = function(doc, cdt, cdn) { cur_frm.cscript.validate = function(doc, cdt, cdn) {
// Step 1:=> check if item table is blank // Step 1:=> check if item table is blank
is_item_table(doc,cdt,cdn); is_item_table(doc,cdt,cdn);
// Step 2:=> Calculate Amount // Step 2:=> Calculate Amount
cur_frm.cscript.calc_amount(doc, 1); cur_frm.cscript.calc_amount(doc, 1);
// calculate advances if pv // calculate advances if pv
if(doc.doctype == 'Payable Voucher') calc_total_advance(doc, cdt, cdn); if(doc.doctype == 'Payable Voucher') calc_total_advance(doc, cdt, cdn);
} }
// **************** RE-CALCULATE VALUES *************************** // **************** RE-CALCULATE VALUES ***************************
cur_frm.cscript['Re-Calculate Values'] = function(doc, cdt, cdn) { cur_frm.cscript['Re-Calculate Values'] = function(doc, cdt, cdn) {
cur_frm.cscript['Calculate Tax'](doc,cdt,cdn); cur_frm.cscript['Calculate Tax'](doc,cdt,cdn);
} }
cur_frm.cscript['Calculate Tax'] = function(doc, cdt, cdn) { cur_frm.cscript['Calculate Tax'] = function(doc, cdt, cdn) {
var other_fname = cur_frm.cscript.other_fname; var other_fname = cur_frm.cscript.other_fname;
var cl = getchildren('Purchase Tax Detail', doc.name, other_fname, doc.doctype); var cl = getchildren('Purchase Tax Detail', doc.name, other_fname, doc.doctype);
for(var i = 0; i<cl.length; i++){ for(var i = 0; i<cl.length; i++){
cl[i].total_tax_amount = 0; cl[i].total_tax_amount = 0;
cl[i].total_amount = 0; cl[i].total_amount = 0;
cl[i].tax_amount = 0; // this is done to calculate other charges cl[i].tax_amount = 0; // this is done to calculate other charges
cl[i].total = 0; cl[i].total = 0;
if(in_list(['On Previous Row Amount','On Previous Row Total'],cl[i].charge_type) && !cl[i].row_id){ if(in_list(['On Previous Row Amount','On Previous Row Total'],cl[i].charge_type) && !cl[i].row_id){
alert("Please Enter Row on which amount needs to be calculated for row : "+cl[i].idx); alert("Please Enter Row on which amount needs to be calculated for row : "+cl[i].idx);
validated = false; validated = false;
} }
} }
cur_frm.cscript.calc_amount(doc, 1); cur_frm.cscript.calc_amount(doc, 1);
} }
cur_frm.cscript.get_item_wise_tax_detail = function( doc, rate, cl, i, tax, t) { cur_frm.cscript.get_item_wise_tax_detail = function( doc, rate, cl, i, tax, t) {
doc = locals[doc.doctype][doc.name]; doc = locals[doc.doctype][doc.name];
var detail = ''; var detail = '';
detail = cl[i].item_code + " : " + cstr(rate) + NEWLINE; detail = cl[i].item_code + " : " + cstr(rate) + NEWLINE;
return detail; return detail;
} }
cur_frm.cscript.amount = function(doc, cdt, cdn) { cur_frm.cscript.amount = function(doc, cdt, cdn) {
cur_frm.cscript.calc_amount(doc, 3); cur_frm.cscript.calc_amount(doc, 3);
} }
//====================== Calculate Amount for PO and PR not for PV ============================================================ //====================== Calculate Amount for PO and PR not for PV ============================================================
cur_frm.cscript.calc_amount = function(doc, n) { cur_frm.cscript.calc_amount = function(doc, n) {
// Set defaults // Set defaults
doc = locals[doc.doctype][doc.name] doc = locals[doc.doctype][doc.name]
var other_fname = cur_frm.cscript.other_fname; var other_fname = cur_frm.cscript.other_fname;
if(!flt(doc.conversion_rate)) { doc.conversion_rate = 1; refresh_field('conversion_rate'); } if(!flt(doc.conversion_rate)) { doc.conversion_rate = 1; refresh_field('conversion_rate'); }
if(!n) n=0; if(!n) n=0;
var net_total = 0; var net_total = 0;
var net_total_import = 0; var net_total_import = 0;
var cl = getchildren(tname, doc.name, fname); var cl = getchildren(tname, doc.name, fname);
for(var i=0;i<cl.length;i++) for(var i=0;i<cl.length;i++)
{ {
var rate_fld = (doc.doctype != 'Payable Voucher') ? 'purchase_rate': 'rate'; var rate_fld = (doc.doctype != 'Payable Voucher') ? 'purchase_rate': 'rate';
var tmp = {}; var tmp = {};
if(!cl[i].discount_rate) cl[i].discount_rate = 0; if(!cl[i].discount_rate) cl[i].discount_rate = 0;
if(n == 1){ if(n == 1){
set_multiple(tname, cl[i].name, {'purchase_ref_rate':flt(cl[i].import_ref_rate)*flt(doc.conversion_rate)}, fname); set_multiple(tname, cl[i].name, {'purchase_ref_rate':flt(cl[i].import_ref_rate)*flt(doc.conversion_rate)}, fname);
set_multiple(tname, cl[i].name, {'discount_rate': flt(flt( flt( flt(cl[i].import_ref_rate) - flt(cl[i].import_rate) ) * 100 )/flt(cl[i].import_ref_rate)) }, fname); set_multiple(tname, cl[i].name, {'discount_rate': flt(flt( flt( flt(cl[i].import_ref_rate) - flt(cl[i].import_rate) ) * 100 )/flt(cl[i].import_ref_rate)) }, fname);
tmp[rate_fld] = flt(doc.conversion_rate) * flt(cl[i].import_rate); tmp[rate_fld] = flt(doc.conversion_rate) * flt(cl[i].import_rate);
set_multiple(tname, cl[i].name, tmp, fname); set_multiple(tname, cl[i].name, tmp, fname);
set_multiple(tname, cl[i].name, {'amount': flt(flt(cl[i].qty) * flt(doc.conversion_rate) * flt(cl[i].import_rate))}, fname); set_multiple(tname, cl[i].name, {'amount': flt(flt(cl[i].qty) * flt(doc.conversion_rate) * flt(cl[i].import_rate))}, fname);
set_multiple(tname, cl[i].name, {'import_amount': flt(flt(cl[i].qty) * flt(cl[i].import_rate))}, fname); set_multiple(tname, cl[i].name, {'import_amount': flt(flt(cl[i].qty) * flt(cl[i].import_rate))}, fname);
}else if(n == 2){ }else if(n == 2){
set_multiple(tname, cl[i].name, {'purchase_ref_rate':flt(cl[i].import_ref_rate)*flt(doc.conversion_rate)}, fname); set_multiple(tname, cl[i].name, {'purchase_ref_rate':flt(cl[i].import_ref_rate)*flt(doc.conversion_rate)}, fname);
set_multiple(tname, cl[i].name, {'discount_rate': flt(flt( flt( flt(cl[i].purchase_ref_rate) - flt(cl[i][rate_fld]) ) * 100 )/flt(cl[i].purchase_ref_rate)) }, fname); set_multiple(tname, cl[i].name, {'discount_rate': flt(flt( flt( flt(cl[i].purchase_ref_rate) - flt(cl[i][rate_fld]) ) * 100 )/flt(cl[i].purchase_ref_rate)) }, fname);
set_multiple(tname, cl[i].name, {'amount': flt(flt(cl[i].qty) * flt(cl[i][rate_fld])),}, fname); set_multiple(tname, cl[i].name, {'amount': flt(flt(cl[i].qty) * flt(cl[i][rate_fld])),}, fname);
set_multiple(tname, cl[i].name, {'import_rate': flt(flt(cl[i][rate_fld]) / flt(doc.conversion_rate)) }, fname); set_multiple(tname, cl[i].name, {'import_rate': flt(flt(cl[i][rate_fld]) / flt(doc.conversion_rate)) }, fname);
set_multiple(tname, cl[i].name, {'import_amount': flt(flt(cl[i].qty) * flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname); set_multiple(tname, cl[i].name, {'import_amount': flt(flt(cl[i].qty) * flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname);
}else if(n == 3){ }else if(n == 3){
tmp[rate_fld] = flt(flt(cl[i].amount) / flt(cl[i].qty)); tmp[rate_fld] = flt(flt(cl[i].amount) / flt(cl[i].qty));
set_multiple(tname, cl[i].name, tmp, fname); set_multiple(tname, cl[i].name, tmp, fname);
set_multiple(tname, cl[i].name, {'import_rate': flt(flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname); set_multiple(tname, cl[i].name, {'import_rate': flt(flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname);
set_multiple(tname, cl[i].name, {'import_amount': flt(flt(cl[i].qty) * flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname); set_multiple(tname, cl[i].name, {'import_amount': flt(flt(cl[i].qty) * flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname);
}else if( n==4){ }else if( n==4){
set_multiple(tname, cl[i].name, {'import_ref_rate': flt(flt(cl[i].purchase_ref_rate) / flt(doc.conversion_rate))}, fname); set_multiple(tname, cl[i].name, {'import_ref_rate': flt(flt(cl[i].purchase_ref_rate) / flt(doc.conversion_rate))}, fname);
tmp[rate_fld] = flt( flt(cl[i].purchase_ref_rate) - flt(flt(cl[i].purchase_ref_rate)*flt(cl[i].discount_rate)/100) ) tmp[rate_fld] = flt( flt(cl[i].purchase_ref_rate) - flt(flt(cl[i].purchase_ref_rate)*flt(cl[i].discount_rate)/100) )
set_multiple(tname, cl[i].name, tmp, fname); set_multiple(tname, cl[i].name, tmp, fname);
set_multiple(tname, cl[i].name, {'import_rate': flt(flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname); set_multiple(tname, cl[i].name, {'import_rate': flt(flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname);
set_multiple(tname, cl[i].name, {'amount':flt(flt(cl[i].qty) * flt(cl[i][rate_fld]))}, fname); set_multiple(tname, cl[i].name, {'amount':flt(flt(cl[i].qty) * flt(cl[i][rate_fld]))}, fname);
set_multiple(tname, cl[i].name, {'import_amount': flt(flt(cl[i].qty) * flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname); set_multiple(tname, cl[i].name, {'import_amount': flt(flt(cl[i].qty) * flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname);
}else if( n==5){ }else if( n==5){
tmp[rate_fld] = flt( flt(cl[i].import_ref_rate) - flt(flt(cl[i].import_ref_rate)*flt(cl[i].discount_rate)/100) ) * flt(doc.conversion_rate); tmp[rate_fld] = flt( flt(cl[i].import_ref_rate) - flt(flt(cl[i].import_ref_rate)*flt(cl[i].discount_rate)/100) ) * flt(doc.conversion_rate);
set_multiple(tname, cl[i].name, {'purchase_ref_rate': flt(flt(cl[i].import_ref_rate) * flt(doc.conversion_rate))}, fname); set_multiple(tname, cl[i].name, {'purchase_ref_rate': flt(flt(cl[i].import_ref_rate) * flt(doc.conversion_rate))}, fname);
set_multiple(tname, cl[i].name, tmp, fname); set_multiple(tname, cl[i].name, tmp, fname);
set_multiple(tname, cl[i].name, {'import_rate': flt(flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname); set_multiple(tname, cl[i].name, {'import_rate': flt(flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname);
set_multiple(tname, cl[i].name, {'amount':flt(flt(cl[i].qty) * flt(cl[i][rate_fld]))}, fname); set_multiple(tname, cl[i].name, {'amount':flt(flt(cl[i].qty) * flt(cl[i][rate_fld]))}, fname);
set_multiple(tname, cl[i].name, {'import_amount': flt(flt(cl[i].qty) * flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname); set_multiple(tname, cl[i].name, {'import_amount': flt(flt(cl[i].qty) * flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname);
} }
if (n != 3){ if (n != 3){
net_total += flt(flt(cl[i].qty) * flt(cl[i][rate_fld])); net_total += flt(flt(cl[i].qty) * flt(cl[i][rate_fld]));
net_total_import += flt(flt(cl[i].qty) * flt(cl[i].import_rate)); net_total_import += flt(flt(cl[i].qty) * flt(cl[i].import_rate));
} else if(n == 3){ } else if(n == 3){
net_total += flt(cl[i].amount); net_total += flt(cl[i].amount);
net_total_import += flt(cl[i].amount) / flt(doc.conversion_rate); net_total_import += flt(cl[i].amount) / flt(doc.conversion_rate);
} }
//update stock uom //update stock uom
cur_frm.cscript.update_stock_qty(doc, tname, cl[i].name); cur_frm.cscript.update_stock_qty(doc, tname, cl[i].name);
} }
doc.net_total = flt(net_total) ; doc.net_total = flt(net_total) ;
doc.net_total_import = flt(net_total_import) ; doc.net_total_import = flt(net_total_import) ;
refresh_field('net_total'); refresh_field('net_total');
refresh_field('net_total_import'); refresh_field('net_total_import');
cur_frm.cscript.val_cal_charges(doc, cdt, cdn, tname, fname, other_fname); cur_frm.cscript.val_cal_charges(doc, cdt, cdn, tname, fname, other_fname);
} }
//======== Function was broken away from cur_frm.cscript.calc_amount as PV has fieldname 'rate' instead of 'purchase_rate'=========== //======== Function was broken away from cur_frm.cscript.calc_amount as PV has fieldname 'rate' instead of 'purchase_rate'===========
cur_frm.cscript.val_cal_charges = function(doc, cdt, cdn, tname, fname, other_fname){ cur_frm.cscript.val_cal_charges = function(doc, cdt, cdn, tname, fname, other_fname){
doc = locals[doc.doctype][doc.name] doc = locals[doc.doctype][doc.name]
if(flt(doc.net_total) > 0) { if(flt(doc.net_total) > 0) {
var cl = getchildren('Purchase Tax Detail', doc.name, other_fname,doc.doctype); var cl = getchildren('Purchase Tax Detail', doc.name, other_fname,doc.doctype);
for(var i = 0; i<cl.length; i++){ for(var i = 0; i<cl.length; i++){
cl[i].total_tax_amount = 0; cl[i].total_tax_amount = 0;
cl[i].total_amount = 0; cl[i].total_amount = 0;
cl[i].tax_amount = 0; // this is done to calculate other charges cl[i].tax_amount = 0; // this is done to calculate other charges
cl[i].total = 0; cl[i].total = 0;
cl[i].item_wise_tax_detail = ""; cl[i].item_wise_tax_detail = "";
if(in_list(['On Previous Row Amount','On Previous Row Total'],cl[i].charge_type) && !cl[i].row_id){ if(in_list(['On Previous Row Amount','On Previous Row Total'],cl[i].charge_type) && !cl[i].row_id){
alert("Please Enter Row on which amount needs to be calculated for row : "+cl[i].idx); alert("Please Enter Row on which amount needs to be calculated for row : "+cl[i].idx);
validated = false; validated = false;
} }
} }
cur_frm.cscript.calc_other_charges(doc , tname , fname , other_fname); // calculate other charges cur_frm.cscript.calc_other_charges(doc , tname , fname , other_fname); // calculate other charges
} }
cur_frm.cscript.calc_doc_values(doc, cdt, cdn, tname, fname, other_fname); // calculates total amounts cur_frm.cscript.calc_doc_values(doc, cdt, cdn, tname, fname, other_fname); // calculates total amounts
refresh_many(['net_total', 'grand_total', 'rounded_total', 'grand_total_import', 'rounded_total_import', 'in_words', 'in_words_import', 'purchase_tax_details', 'total_tax', 'other_charges_added', 'other_charges_deducted', 'net_total_import', 'other_charges_added_import', 'other_charges_deducted_import']); refresh_many(['net_total', 'grand_total', 'rounded_total', 'grand_total_import', 'rounded_total_import', 'in_words', 'in_words_import', 'purchase_tax_details', 'total_tax', 'other_charges_added', 'other_charges_deducted', 'net_total_import', 'other_charges_added_import', 'other_charges_deducted_import']);
} }
// ******************************* OTHER CHARGES ************************************* // ******************************* OTHER CHARGES *************************************
cur_frm.cscript.calc_other_charges = function(doc , tname , fname , other_fname) { cur_frm.cscript.calc_other_charges = function(doc , tname , fname , other_fname) {
doc = locals[doc.doctype][doc.name]; doc = locals[doc.doctype][doc.name];
// make display area // make display area
// ------------------ // ------------------
cur_frm.fields_dict['Tax Calculation'].disp_area.innerHTML = '<b style="padding: 8px 0px;">Calculation Details for Other Charges and Landed cost:</b>'; cur_frm.fields_dict['Tax Calculation'].disp_area.innerHTML = '<b style="padding: 8px 0px;">Calculation Details for Other Charges and Landed cost:</b>';
var cl = getchildren(tname, doc.name, fname); var cl = getchildren(tname, doc.name, fname);
var tax = getchildren('Purchase Tax Detail', doc.name, other_fname,doc.doctype); var tax = getchildren('Purchase Tax Detail', doc.name, other_fname,doc.doctype);
// make display table // make display table
// ------------------ // ------------------
var otc = make_table(cur_frm.fields_dict['Tax Calculation'].disp_area, cl.length + 1, tax.length + 1, '90%',[],{border:'1px solid #AAA',padding:'2px'}); var otc = make_table(cur_frm.fields_dict['Tax Calculation'].disp_area, cl.length + 1, tax.length + 1, '90%',[],{border:'1px solid #AAA',padding:'2px'});
$y(otc,{marginTop:'8px'}); $y(otc,{marginTop:'8px'});
var tax_desc = {}; var tax_desc_rates = []; var net_total = 0; var tax_desc = {}; var tax_desc_rates = []; var net_total = 0;
for(var i=0;i<cl.length;i++) { for(var i=0;i<cl.length;i++) {
var item_tax = 0; var item_tax = 0;
if(doc.doctype != 'Payable Voucher') net_total += flt(flt(cl[i].qty) * flt(cl[i].purchase_rate)); if(doc.doctype != 'Payable Voucher') net_total += flt(flt(cl[i].qty) * flt(cl[i].purchase_rate));
else if(doc.doctype == 'Payable Voucher') net_total += flt(flt(cl[i].qty) * flt(cl[i].rate)); else if(doc.doctype == 'Payable Voucher') net_total += flt(flt(cl[i].qty) * flt(cl[i].rate));
var prev_total = flt(cl[i].amount); var prev_total = flt(cl[i].amount);
if(cl[i].item_tax_rate) if(cl[i].item_tax_rate) {
var check_tax = eval('var a='+cl[i].item_tax_rate+';a'); //to get in dictionary try {
var check_tax = JSON.parse(cl[i].item_tax_rate); //to get in dictionary
// Add Item Code in new Row } catch(exception) {
//-------------------------- var check_tax = eval('var a='+cl[i].item_tax_rate+';a'); //to get in dictionary
$td(otc,i+1,0).innerHTML = cl[i].item_code; }
}
var tax = getchildren('Purchase Tax Detail', doc.name, other_fname,doc.doctype);
var total = net_total; // Add Item Code in new Row
for(var t=0;t<tax.length;t++){ //--------------------------
$td(otc,i+1,0).innerHTML = cl[i].item_code;
var tax = getchildren('Purchase Tax Detail', doc.name, other_fname,doc.doctype);
var total = net_total;
for(var t=0;t<tax.length;t++){
var account = tax[t].account_head; var account = tax[t].account_head;
$td(otc,0,t+1).innerHTML = account?account:''; $td(otc,0,t+1).innerHTML = account?account:'';
//Check For Rate //Check For Rate
if(cl[i].item_tax_rate && check_tax[account]!=null) {rate = flt(check_tax[account]);} if(cl[i].item_tax_rate && check_tax[account]!=null) {rate = flt(check_tax[account]);}
else // if particular item doesn't have particular rate it will take other charges rate else // if particular item doesn't have particular rate it will take other charges rate
rate = flt(tax[t].rate); rate = flt(tax[t].rate);
//Check For Rate and get tax amount
var tax_amount = cur_frm.cscript.check_charge_type_and_get_tax_amount(doc,tax,t, cl[i], rate);
//enter item_wise_tax_detail i.e. tax rate on each item
item_wise_tax_detail = cur_frm.cscript.get_item_wise_tax_detail( doc, rate, cl, i, tax, t);
if(tax[t].add_deduct_tax == 'Add'){
// this is calculation part for all types
if(tax[t].charge_type != "Actual") tax[t].item_wise_tax_detail += item_wise_tax_detail;
tax[t].total_amount = flt(tax_amount.toFixed(2)); //stores actual tax amount in virtual field
tax[t].total_tax_amount = flt(prev_total.toFixed(2)); //stores total amount in virtual field
tax[t].tax_amount += flt(tax_amount.toFixed(2));
var total_amount = flt(tax[t].tax_amount);
total_tax_amount = flt(tax[t].total_tax_amount) + flt(total_amount);
if(tax[t].category != "For Valuation"){
set_multiple('Purchase Tax Detail', tax[t].name, { 'item_wise_tax_detail':tax[t].item_wise_tax_detail, 'amount':total_amount, 'total':flt(total)+flt(tax[t].tax_amount)/*_tax_amount)*/}, other_fname);
prev_total += flt(tax[t].total_amount);
total += flt(tax[t].tax_amount); // for adding total to previous amount
}
else{
set_multiple('Purchase Tax Detail', tax[t].name, { 'item_wise_tax_detail':tax[t].item_wise_tax_detail, 'amount':total_amount, 'total':flt(total)/*_tax_amount)*/}, other_fname);
prev_total = prev_total;
}
//prev_total += flt(tax[t].total_amount); // for previous row total
if(tax[t].charge_type == 'Actual') //Check For Rate and get tax amount
$td(otc,i+1,t+1).innerHTML = fmt_money(tax[t].total_amount); var tax_amount = cur_frm.cscript.check_charge_type_and_get_tax_amount(doc,tax,t, cl[i], rate);
else
$td(otc,i+1,t+1).innerHTML = '('+fmt_money(rate) + '%) ' +fmt_money(tax[t].total_amount); //enter item_wise_tax_detail i.e. tax rate on each item
item_wise_tax_detail = cur_frm.cscript.get_item_wise_tax_detail( doc, rate, cl, i, tax, t);
if(tax[t].add_deduct_tax == 'Add'){
// this is calculation part for all types
if(tax[t].charge_type != "Actual") tax[t].item_wise_tax_detail += item_wise_tax_detail;
tax[t].total_amount = flt(tax_amount.toFixed(2)); //stores actual tax amount in virtual field
tax[t].total_tax_amount = flt(prev_total.toFixed(2)); //stores total amount in virtual field
tax[t].tax_amount += flt(tax_amount.toFixed(2));
var total_amount = flt(tax[t].tax_amount);
total_tax_amount = flt(tax[t].total_tax_amount) + flt(total_amount);
if(tax[t].category != "For Valuation"){
set_multiple('Purchase Tax Detail', tax[t].name, { 'item_wise_tax_detail':tax[t].item_wise_tax_detail, 'amount':total_amount, 'total':flt(total)+flt(tax[t].tax_amount)/*_tax_amount)*/}, other_fname);
prev_total += flt(tax[t].total_amount);
total += flt(tax[t].tax_amount); // for adding total to previous amount
}
else{
set_multiple('Purchase Tax Detail', tax[t].name, { 'item_wise_tax_detail':tax[t].item_wise_tax_detail, 'amount':total_amount, 'total':flt(total)/*_tax_amount)*/}, other_fname);
prev_total = prev_total;
}
//prev_total += flt(tax[t].total_amount); // for previous row total
if (tax[t].category != "For Total"){ if(tax[t].charge_type == 'Actual')
item_tax += tax[t].total_amount; $td(otc,i+1,t+1).innerHTML = fmt_money(tax[t].total_amount);
} else
} $td(otc,i+1,t+1).innerHTML = '('+fmt_money(rate) + '%) ' +fmt_money(tax[t].total_amount);
else if(tax[t].add_deduct_tax == 'Deduct'){
// this is calculation part for all types
if(tax[t].charge_type != "Actual") tax[t].item_wise_tax_detail += item_wise_tax_detail;
tax[t].total_amount = flt(tax_amount.toFixed(2)); //stores actual tax amount in virtual field
tax[t].total_tax_amount = flt(prev_total.toFixed(2)); //stores total amount in virtual field
tax[t].tax_amount += flt(tax_amount.toFixed(2));
var total_amount = flt(tax[t].tax_amount);
total_tax_amount = flt(tax[t].total_tax_amount) - flt(total_amount);
if(tax[t].category != "For Valuation"){
set_multiple('Purchase Tax Detail', tax[t].name, { 'item_wise_tax_detail':tax[t].item_wise_tax_detail, 'tax_amount':total_amount, 'total':flt(total)-flt(tax[t].tax_amount)/*_tax_amount)*/}, other_fname);
prev_total -= flt(tax[t].total_amount);
total -= flt(tax[t].tax_amount); // for adding total to previous amount
}
else{
set_multiple('Purchase Tax Detail', tax[t].name, { 'item_wise_tax_detail':tax[t].item_wise_tax_detail, 'tax_amount':total_amount, 'total':flt(total)/*_tax_amount)*/}, other_fname);
prev_total = prev_total;
}
//prev_total += flt(tax[t].total_amount); // for previous row total
if(tax[t].charge_type == 'Actual') if (tax[t].category != "For Total"){
$td(otc,i+1,t+1).innerHTML = fmt_money(tax[t].total_amount); item_tax += tax[t].total_amount;
else }
$td(otc,i+1,t+1).innerHTML = '('+fmt_money(rate) + '%) ' +fmt_money(tax[t].total_amount); }
else if(tax[t].add_deduct_tax == 'Deduct'){
// this is calculation part for all types
if(tax[t].charge_type != "Actual") tax[t].item_wise_tax_detail += item_wise_tax_detail;
tax[t].total_amount = flt(tax_amount.toFixed(2)); //stores actual tax amount in virtual field
tax[t].total_tax_amount = flt(prev_total.toFixed(2)); //stores total amount in virtual field
tax[t].tax_amount += flt(tax_amount.toFixed(2));
var total_amount = flt(tax[t].tax_amount);
total_tax_amount = flt(tax[t].total_tax_amount) - flt(total_amount);
if(tax[t].category != "For Valuation"){
set_multiple('Purchase Tax Detail', tax[t].name, { 'item_wise_tax_detail':tax[t].item_wise_tax_detail, 'tax_amount':total_amount, 'total':flt(total)-flt(tax[t].tax_amount)/*_tax_amount)*/}, other_fname);
prev_total -= flt(tax[t].total_amount);
total -= flt(tax[t].tax_amount); // for adding total to previous amount
}
else{
set_multiple('Purchase Tax Detail', tax[t].name, { 'item_wise_tax_detail':tax[t].item_wise_tax_detail, 'tax_amount':total_amount, 'total':flt(total)/*_tax_amount)*/}, other_fname);
prev_total = prev_total;
}
//prev_total += flt(tax[t].total_amount); // for previous row total
if (tax[t].category != "For Total"){ if(tax[t].charge_type == 'Actual')
item_tax -= tax[t].total_amount; $td(otc,i+1,t+1).innerHTML = fmt_money(tax[t].total_amount);
} else
} $td(otc,i+1,t+1).innerHTML = '('+fmt_money(rate) + '%) ' +fmt_money(tax[t].total_amount);
if (tax[t].category != "For Total"){
} item_tax -= tax[t].total_amount;
set_multiple(tname, cl[i].name, {'item_tax_amount': item_tax }, fname); }
} }
}
set_multiple(tname, cl[i].name, {'item_tax_amount': item_tax }, fname);
}
} }
@ -397,45 +441,45 @@ cur_frm.cscript.calc_other_charges = function(doc , tname , fname , other_fname)
// ******* Calculation of total amounts of document (item amount + other charges)**************** // ******* Calculation of total amounts of document (item amount + other charges)****************
cur_frm.cscript.calc_doc_values = function(doc, cdt, cdn, tname, fname, other_fname) { cur_frm.cscript.calc_doc_values = function(doc, cdt, cdn, tname, fname, other_fname) {
doc = locals[doc.doctype][doc.name]; doc = locals[doc.doctype][doc.name];
var net_total = 0; var total_tax = 0; var other_charges_added = 0; var other_charges_deducted = 0; var net_total = 0; var total_tax = 0; var other_charges_added = 0; var other_charges_deducted = 0;
var cl = getchildren(tname, doc.name, fname); var cl = getchildren(tname, doc.name, fname);
for(var i = 0; i<cl.length; i++){ for(var i = 0; i<cl.length; i++){
net_total += flt(cl[i].amount); net_total += flt(cl[i].amount);
} }
var d = getchildren('Purchase Tax Detail', doc.name, other_fname,doc.doctype); var d = getchildren('Purchase Tax Detail', doc.name, other_fname,doc.doctype);
for(var j = 0; j<d.length; j++){ for(var j = 0; j<d.length; j++){
if(d[j].category != 'For Valuation'){ if(d[j].category != 'For Valuation'){
if(d[j].add_deduct_tax == 'Add'){ if(d[j].add_deduct_tax == 'Add'){
other_charges_added += flt(d[j].tax_amount); other_charges_added += flt(d[j].tax_amount);
total_tax += flt(d[j].tax_amount); total_tax += flt(d[j].tax_amount);
} }
if(d[j].add_deduct_tax == 'Deduct'){ if(d[j].add_deduct_tax == 'Deduct'){
other_charges_deducted += flt(d[j].tax_amount); other_charges_deducted += flt(d[j].tax_amount);
total_tax -= flt(d[j].tax_amount); total_tax -= flt(d[j].tax_amount);
} }
} }
} }
doc.net_total = flt(net_total); doc.net_total = flt(net_total);
doc.total_tax = flt(total_tax); doc.total_tax = flt(total_tax);
doc.other_charges_added = flt(other_charges_added); doc.other_charges_added = flt(other_charges_added);
doc.other_charges_deducted = flt(other_charges_deducted); doc.other_charges_deducted = flt(other_charges_deducted);
doc.grand_total = flt(flt(net_total) + flt(other_charges_added) - flt(other_charges_deducted)); doc.grand_total = flt(flt(net_total) + flt(other_charges_added) - flt(other_charges_deducted));
doc.rounded_total = Math.round(doc.grand_total); doc.rounded_total = Math.round(doc.grand_total);
doc.net_total_import = flt(flt(net_total) / flt(doc.conversion_rate)); doc.net_total_import = flt(flt(net_total) / flt(doc.conversion_rate));
doc.other_charges_added_import = flt(flt(other_charges_added) / flt(doc.conversion_rate)); doc.other_charges_added_import = flt(flt(other_charges_added) / flt(doc.conversion_rate));
doc.other_charges_deducted_import = flt(flt(other_charges_deducted) / flt(doc.conversion_rate)); doc.other_charges_deducted_import = flt(flt(other_charges_deducted) / flt(doc.conversion_rate));
doc.grand_total_import = flt(flt(doc.grand_total) / flt(doc.conversion_rate)); doc.grand_total_import = flt(flt(doc.grand_total) / flt(doc.conversion_rate));
doc.rounded_total_import = Math.round(doc.grand_total_import); doc.rounded_total_import = Math.round(doc.grand_total_import);
refresh_many(['net_total','total_taxes','grand_total']); refresh_many(['net_total','total_taxes','grand_total']);
if(doc.doctype == 'Payable Voucher'){ if(doc.doctype == 'Payable Voucher'){
calculate_outstanding(doc); calculate_outstanding(doc);
} }
} }
var calculate_outstanding = function(doc) { var calculate_outstanding = function(doc) {
@ -453,41 +497,41 @@ var calculate_outstanding = function(doc) {
cur_frm.cscript.check_charge_type_and_get_tax_amount = function(doc, tax, t, cl, rate, print_amt) { cur_frm.cscript.check_charge_type_and_get_tax_amount = function(doc, tax, t, cl, rate, print_amt) {
doc = locals[doc.doctype][doc.name]; doc = locals[doc.doctype][doc.name];
var tax_amount = 0; var tax_amount = 0;
if(tax[t].charge_type == 'Actual') { if(tax[t].charge_type == 'Actual') {
var value = flt(tax[t].rate) / flt(doc.net_total); // this give the ratio in which all items are divided var value = flt(tax[t].rate) / flt(doc.net_total); // this give the ratio in which all items are divided
return tax_amount = flt(value) * flt(cl.amount); return tax_amount = flt(value) * flt(cl.amount);
} }
else if(tax[t].charge_type == 'On Net Total') { else if(tax[t].charge_type == 'On Net Total') {
return tax_amount = (flt(rate) * flt(cl.amount) / 100); return tax_amount = (flt(rate) * flt(cl.amount) / 100);
} }
else if(tax[t].charge_type == 'On Previous Row Amount'){ else if(tax[t].charge_type == 'On Previous Row Amount'){
var row_no = (tax[t].row_id).toString(); var row_no = (tax[t].row_id).toString();
var row = (row_no).split("+"); // splits the values and stores in an array var row = (row_no).split("+"); // splits the values and stores in an array
for(var r = 0;r<row.length;r++){ for(var r = 0;r<row.length;r++){
var id = cint(row[r].replace(/^\s+|\s+$/g,"")); var id = cint(row[r].replace(/^\s+|\s+$/g,""));
tax_amount += (flt(rate) * flt(tax[id-1].total_amount) / 100); tax_amount += (flt(rate) * flt(tax[id-1].total_amount) / 100);
} }
var row_id = row_no.indexOf("/"); var row_id = row_no.indexOf("/");
if(row_id != -1) { if(row_id != -1) {
rate = ''; rate = '';
var row = (row_no).split("/"); // splits the values and stores in an array var row = (row_no).split("/"); // splits the values and stores in an array
if(row.length>2) alert("You cannot enter more than 2 nos. for division"); if(row.length>2) alert("You cannot enter more than 2 nos. for division");
var id1 = cint(row[0].replace(/^\s+|\s+$/g,"")); var id1 = cint(row[0].replace(/^\s+|\s+$/g,""));
var id2 = cint(row[1].replace(/^\s+|\s+$/g,"")); var id2 = cint(row[1].replace(/^\s+|\s+$/g,""));
tax_amount = flt(tax[id1-1].total_amount) / flt(tax[id2-1].total_amount); tax_amount = flt(tax[id1-1].total_amount) / flt(tax[id2-1].total_amount);
} }
return tax_amount return tax_amount
} }
else if(tax[t].charge_type == 'On Previous Row Total') { else if(tax[t].charge_type == 'On Previous Row Total') {
var row = cint(tax[t].row_id); var row = cint(tax[t].row_id);
if(tax[row-1].add_deduct_tax == 'Add'){ if(tax[row-1].add_deduct_tax == 'Add'){
return tax_amount = flt(rate) * (flt(tax[row-1].total_tax_amount)+flt(tax[row-1].total_amount)) / 100; return tax_amount = flt(rate) * (flt(tax[row-1].total_tax_amount)+flt(tax[row-1].total_amount)) / 100;
} }
else if(tax[row-1].add_deduct_tax == 'Deduct'){ else if(tax[row-1].add_deduct_tax == 'Deduct'){
return tax_amount = flt(rate) * (flt(tax[row-1].total_tax_amount)-flt(tax[row-1].total_amount)) / 100; return tax_amount = flt(rate) * (flt(tax[row-1].total_tax_amount)-flt(tax[row-1].total_amount)) / 100;
} }
} }
} }

View File

@ -96,9 +96,9 @@ class DocType(TransactionBase):
if r: obj.doc.terms = r[0][0] if r: obj.doc.terms = r[0][0]
# Get Item Details # Get Item Details
def get_item_details( self, obj, arg =''): def get_item_details(self, obj, arg =''):
import json
arg = eval(arg) arg = json.loads(arg)
item = sql("select item_name,item_group, brand, description, min_order_qty, stock_uom, default_warehouse,lead_time_days, last_purchase_rate from `tabItem` where name = %s and (ifnull(end_of_life,'')='' or end_of_life = '0000-00-00' or end_of_life > now())", (arg['item_code']), as_dict = 1) item = sql("select item_name,item_group, brand, description, min_order_qty, stock_uom, default_warehouse,lead_time_days, last_purchase_rate from `tabItem` where name = %s and (ifnull(end_of_life,'')='' or end_of_life = '0000-00-00' or end_of_life > now())", (arg['item_code']), as_dict = 1)
tax = sql("select tax_type, tax_rate from `tabItem Tax` where parent = %s" , arg['item_code']) tax = sql("select tax_type, tax_rate from `tabItem Tax` where parent = %s" , arg['item_code'])
t = {} t = {}
@ -119,7 +119,7 @@ class DocType(TransactionBase):
'stock_uom' : item and item[0]['stock_uom'] or '', 'stock_uom' : item and item[0]['stock_uom'] or '',
'conversion_factor' : '1', 'conversion_factor' : '1',
'warehouse' : wh, 'warehouse' : wh,
'item_tax_rate' : str(t), 'item_tax_rate' : json.dumps(t),
'batch_no' : '', 'batch_no' : '',
'discount_rate' : 0 'discount_rate' : 0
} }

View File

@ -8,86 +8,89 @@ $import(SMS Control)
//========================== On Load ================================================= //========================== On Load =================================================
cur_frm.cscript.onload = function(doc, cdt, cdn) { cur_frm.cscript.onload = function(doc, cdt, cdn) {
if(!doc.fiscal_year && doc.__islocal){ //set_default_values(doc); if(!doc.fiscal_year && doc.__islocal){ //set_default_values(doc);
doc.fiscal_year = sys_defaults.fiscal_year; doc.fiscal_year = sys_defaults.fiscal_year;
} }
if(!doc.conversion_rate) doc.conversion_rate = 1; if(!doc.conversion_rate) doc.conversion_rate = 1;
if(!doc.currency) doc.currency = sys_defaults.currency; if(!doc.currency) doc.currency = sys_defaults.currency;
if(!doc.status) set_multiple(cdt,cdn,{status:'Draft'}); if(!doc.status) set_multiple(cdt,cdn,{status:'Draft'});
if(!doc.transaction_date) set_multiple(cdt,cdn,{transaction_date:get_today()}); if(!doc.transaction_date) set_multiple(cdt,cdn,{transaction_date:get_today()});
if(doc.__islocal){ if(doc.__islocal){
hide_field(['supplier_name','supplier_address','contact_person','address_display','contact_display','contact_mobile','contact_email']); hide_field(['supplier_name','supplier_address','contact_person','address_display','contact_display','contact_mobile','contact_email']);
} }
// defined in purchase_common.js
//cur_frm.cscript.update_item_details(doc, cdt, cdn);
} }
cur_frm.cscript.onload_post_render = function(doc, cdt, cdn) { cur_frm.cscript.onload_post_render = function(doc, cdt, cdn) {
if(doc.__islocal){ if(doc.__islocal){
cur_frm.cscript.get_default_schedule_date(doc); cur_frm.cscript.get_default_schedule_date(doc);
} }
} }
// ================================== Refresh ========================================== // ================================== Refresh ==========================================
cur_frm.cscript.refresh = function(doc, cdt, cdn) { cur_frm.cscript.refresh = function(doc, cdt, cdn) {
// Show buttons // Show buttons
// --------------------------------- // ---------------------------------
cur_frm.clear_custom_buttons(); cur_frm.clear_custom_buttons();
if(doc.docstatus == 1 && doc.status != 'Stopped'){ if(doc.docstatus == 1 && doc.status != 'Stopped'){
var ch = getchildren('PO Detail',doc.name,'po_details'); var ch = getchildren('PO Detail',doc.name,'po_details');
var allow_billing = 0; var allow_receipt = 0; var allow_billing = 0; var allow_receipt = 0;
cur_frm.add_custom_button('Send SMS', cur_frm.cscript['Send SMS']); cur_frm.add_custom_button('Send SMS', cur_frm.cscript['Send SMS']);
for(var i in ch){ for(var i in ch){
if(ch[i].qty > ch[i].received_qty) allow_receipt = 1; if(ch[i].qty > ch[i].received_qty) allow_receipt = 1;
if(ch[i].qty > ch[i].billed_qty) allow_billing = 1; if(ch[i].qty > ch[i].billed_qty) allow_billing = 1;
} }
if(allow_receipt) if(allow_receipt)
cur_frm.add_custom_button('Make Purchase Receipt', cur_frm.cscript['Make Purchase Receipt']); cur_frm.add_custom_button('Make Purchase Receipt', cur_frm.cscript['Make Purchase Receipt']);
if(allow_billing) if(allow_billing)
cur_frm.add_custom_button('Make Invoice', cur_frm.cscript['Make Purchase Invoice']); cur_frm.add_custom_button('Make Invoice', cur_frm.cscript['Make Purchase Invoice']);
if(allow_billing || allow_receipt) if(allow_billing || allow_receipt)
cur_frm.add_custom_button('Stop', cur_frm.cscript['Stop Purchase Order']); cur_frm.add_custom_button('Stop', cur_frm.cscript['Stop Purchase Order']);
} }
if(doc.docstatus == 1 && doc.status == 'Stopped') if(doc.docstatus == 1 && doc.status == 'Stopped')
cur_frm.add_custom_button('Unstop Purchase Order', cur_frm.cscript['Unstop Purchase Order']); cur_frm.add_custom_button('Unstop Purchase Order', cur_frm.cscript['Unstop Purchase Order']);
if(doc.docstatus == 1) unhide_field(['Repair Purchase Order']); if(doc.docstatus == 1) unhide_field(['Repair Purchase Order']);
else hide_field(['Repair Purchase Order']); else hide_field(['Repair Purchase Order']);
} }
//Supplier //Supplier
cur_frm.cscript.supplier = function(doc,dt,dn) { cur_frm.cscript.supplier = function(doc,dt,dn) {
if(doc.supplier) get_server_fields('get_default_supplier_address', JSON.stringify({supplier: doc.supplier}),'', doc, dt, dn, 1); if(doc.supplier) get_server_fields('get_default_supplier_address', JSON.stringify({supplier: doc.supplier}),'', doc, dt, dn, 1);
if(doc.supplier) unhide_field(['supplier_name','supplier_address','contact_person','address_display','contact_display','contact_mobile','contact_email']); if(doc.supplier) unhide_field(['supplier_name','supplier_address','contact_person','address_display','contact_display','contact_mobile','contact_email']);
} }
cur_frm.cscript.supplier_address = cur_frm.cscript.contact_person = function(doc,dt,dn) { cur_frm.cscript.supplier_address = cur_frm.cscript.contact_person = function(doc,dt,dn) {
if(doc.supplier) get_server_fields('get_supplier_address', JSON.stringify({supplier: doc.supplier, address: doc.supplier_address, contact: doc.contact_person}),'', doc, dt, dn, 1); if(doc.supplier) get_server_fields('get_supplier_address', JSON.stringify({supplier: doc.supplier, address: doc.supplier_address, contact: doc.contact_person}),'', doc, dt, dn, 1);
} }
cur_frm.fields_dict['supplier_address'].get_query = function(doc, cdt, cdn) { cur_frm.fields_dict['supplier_address'].get_query = function(doc, cdt, cdn) {
return 'SELECT name,address_line1,city FROM tabAddress WHERE supplier = "'+ doc.supplier +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50'; return 'SELECT name,address_line1,city FROM tabAddress WHERE supplier = "'+ doc.supplier +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
} }
cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) { cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE supplier = "'+ doc.supplier +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50'; return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE supplier = "'+ doc.supplier +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
} }
cur_frm.fields_dict.supplier_address.on_new = function(dn) { cur_frm.fields_dict.supplier_address.on_new = function(dn) {
locals['Address'][dn].supplier = locals[cur_frm.doctype][cur_frm.docname].supplier; locals['Address'][dn].supplier = locals[cur_frm.doctype][cur_frm.docname].supplier;
locals['Address'][dn].supplier_name = locals[cur_frm.doctype][cur_frm.docname].supplier_name; locals['Address'][dn].supplier_name = locals[cur_frm.doctype][cur_frm.docname].supplier_name;
} }
cur_frm.fields_dict.contact_person.on_new = function(dn) { cur_frm.fields_dict.contact_person.on_new = function(dn) {
locals['Contact'][dn].supplier = locals[cur_frm.doctype][cur_frm.docname].supplier; locals['Contact'][dn].supplier = locals[cur_frm.doctype][cur_frm.docname].supplier;
locals['Contact'][dn].supplier_name = locals[cur_frm.doctype][cur_frm.docname].supplier_name; locals['Contact'][dn].supplier_name = locals[cur_frm.doctype][cur_frm.docname].supplier_name;
} }
@ -96,154 +99,154 @@ cur_frm.fields_dict.contact_person.on_new = function(dn) {
//================ create new contact ============================================================================ //================ create new contact ============================================================================
cur_frm.cscript.new_contact = function(){ cur_frm.cscript.new_contact = function(){
tn = createLocal('Contact'); tn = createLocal('Contact');
locals['Contact'][tn].is_supplier = 1; locals['Contact'][tn].is_supplier = 1;
if(doc.supplier) locals['Contact'][tn].supplier = doc.supplier; if(doc.supplier) locals['Contact'][tn].supplier = doc.supplier;
loaddoc('Contact', tn); loaddoc('Contact', tn);
} }
//======================= transaction date ============================= //======================= transaction date =============================
cur_frm.cscript.transaction_date = function(doc,cdt,cdn){ cur_frm.cscript.transaction_date = function(doc,cdt,cdn){
if(doc.__islocal){ if(doc.__islocal){
cur_frm.cscript.get_default_schedule_date(doc); cur_frm.cscript.get_default_schedule_date(doc);
} }
} }
// ---------------------- Get project name -------------------------- // ---------------------- Get project name --------------------------
cur_frm.fields_dict['po_details'].grid.get_field('project_name').get_query = function(doc, cdt, cdn) { cur_frm.fields_dict['po_details'].grid.get_field('project_name').get_query = function(doc, cdt, cdn) {
return 'SELECT `tabProject`.name FROM `tabProject` WHERE `tabProject`.status = "Open" AND `tabProject`.name LIKE "%s" ORDER BY `tabProject`.name ASC LIMIT 50'; return 'SELECT `tabProject`.name FROM `tabProject` WHERE `tabProject`.status = "Open" AND `tabProject`.name LIKE "%s" ORDER BY `tabProject`.name ASC LIMIT 50';
} }
//==================== Indent No Get Query ======================================================= //==================== Indent No Get Query =======================================================
//===== Only those Indents status != 'Completed' and docstatus = 1 i.e. submitted================= //===== Only those Indents status != 'Completed' and docstatus = 1 i.e. submitted=================
cur_frm.fields_dict['indent_no'].get_query = function(doc) { cur_frm.fields_dict['indent_no'].get_query = function(doc) {
return 'SELECT DISTINCT `tabIndent`.`name` FROM `tabIndent` WHERE `tabIndent`.company = "' + doc.company + '" and `tabIndent`.`docstatus` = 1 and `tabIndent`.`status` != "Stopped" and ifnull(`tabIndent`.`per_ordered`,0) < 100 and `tabIndent`.%(key)s LIKE "%s" ORDER BY `tabIndent`.`name` DESC LIMIT 50'; return 'SELECT DISTINCT `tabIndent`.`name` FROM `tabIndent` WHERE `tabIndent`.company = "' + doc.company + '" and `tabIndent`.`docstatus` = 1 and `tabIndent`.`status` != "Stopped" and ifnull(`tabIndent`.`per_ordered`,0) < 100 and `tabIndent`.%(key)s LIKE "%s" ORDER BY `tabIndent`.`name` DESC LIMIT 50';
} }
/* /*
//*********** get approved supplier quotation ******************** //*********** get approved supplier quotation ********************
cur_frm.fields_dict['supplier_qtn'].get_query = function(doc) { cur_frm.fields_dict['supplier_qtn'].get_query = function(doc) {
var cond=''; var cond='';
if(doc.supplier) cond = 'ifnull(`tabSupplier Quotation`.supplier, "") = "'+doc.supplier+'" and'; if(doc.supplier) cond = 'ifnull(`tabSupplier Quotation`.supplier, "") = "'+doc.supplier+'" and';
return repl('SELECT DISTINCT `tabSupplier Quotation`.`name` FROM `tabSupplier Quotation` WHERE `tabSupplier Quotation`.company = "%(company)s" and`tabSupplier Quotation`.`docstatus` = 1 and `tabSupplier Quotation`.`approval_status` = "Approved" and %(cond)s `tabSupplier Quotation`.%(key)s LIKE "%s" ORDER BY `tabSupplier Quotation`.`name` DESC LIMIT 50', {company:doc.company,cond:cond}); return repl('SELECT DISTINCT `tabSupplier Quotation`.`name` FROM `tabSupplier Quotation` WHERE `tabSupplier Quotation`.company = "%(company)s" and`tabSupplier Quotation`.`docstatus` = 1 and `tabSupplier Quotation`.`approval_status` = "Approved" and %(cond)s `tabSupplier Quotation`.%(key)s LIKE "%s" ORDER BY `tabSupplier Quotation`.`name` DESC LIMIT 50', {company:doc.company,cond:cond});
} }
*/ */
//========================= Get Last Purhase Rate ===================================== //========================= Get Last Purhase Rate =====================================
cur_frm.cscript['Get Last Purchase Rate'] = function(doc, cdt, cdn){ cur_frm.cscript['Get Last Purchase Rate'] = function(doc, cdt, cdn){
$c_obj(make_doclist(doc.doctype, doc.name), 'get_last_purchase_rate', '', $c_obj(make_doclist(doc.doctype, doc.name), 'get_last_purchase_rate', '',
function(r, rt) { function(r, rt) {
refresh_field(cur_frm.cscript.fname); refresh_field(cur_frm.cscript.fname);
var doc = locals[cdt][cdn]; var doc = locals[cdt][cdn];
cur_frm.cscript.calc_amount( doc, 2); cur_frm.cscript.calc_amount( doc, 2);
} }
); );
} }
//========================= Make Purchase Receipt ======================================================= //========================= Make Purchase Receipt =======================================================
cur_frm.cscript['Make Purchase Receipt'] = function() { cur_frm.cscript['Make Purchase Receipt'] = function() {
n = createLocal('Purchase Receipt'); n = createLocal('Purchase Receipt');
$c('dt_map', args={ $c('dt_map', args={
'docs':compress_doclist([locals['Purchase Receipt'][n]]), 'docs':compress_doclist([locals['Purchase Receipt'][n]]),
'from_doctype': cur_frm.doc.doctype, 'from_doctype': cur_frm.doc.doctype,
'to_doctype':'Purchase Receipt', 'to_doctype':'Purchase Receipt',
'from_docname':cur_frm.doc.name, 'from_docname':cur_frm.doc.name,
'from_to_list':"[['Purchase Order','Purchase Receipt'],['PO Detail','Purchase Receipt Detail'],['Purchase Tax Detail','Purchase Tax Detail']]" 'from_to_list':"[['Purchase Order','Purchase Receipt'],['PO Detail','Purchase Receipt Detail'],['Purchase Tax Detail','Purchase Tax Detail']]"
}, function(r,rt) { }, function(r,rt) {
loaddoc('Purchase Receipt', n); loaddoc('Purchase Receipt', n);
} }
); );
} }
//========================== Make Purchase Invoice ===================================================== //========================== Make Purchase Invoice =====================================================
cur_frm.cscript['Make Purchase Invoice'] = function() { cur_frm.cscript['Make Purchase Invoice'] = function() {
n = createLocal('Payable Voucher'); n = createLocal('Payable Voucher');
$c('dt_map', args={ $c('dt_map', args={
'docs':compress_doclist([locals['Payable Voucher'][n]]), 'docs':compress_doclist([locals['Payable Voucher'][n]]),
'from_doctype':cur_frm.doc.doctype, 'from_doctype':cur_frm.doc.doctype,
'to_doctype':'Payable Voucher', 'to_doctype':'Payable Voucher',
'from_docname': cur_frm.doc.name, 'from_docname': cur_frm.doc.name,
'from_to_list':"[['Purchase Order','Payable Voucher'],['PO Detail','PV Detail'],['Purchase Tax Detail','Purchase Tax Detail']]" 'from_to_list':"[['Purchase Order','Payable Voucher'],['PO Detail','PV Detail'],['Purchase Tax Detail','Purchase Tax Detail']]"
}, function(r,rt) { }, function(r,rt) {
loaddoc('Payable Voucher', n); loaddoc('Payable Voucher', n);
} }
); );
} }
// Stop PURCHASE ORDER // Stop PURCHASE ORDER
// ================================================================================================== // ==================================================================================================
cur_frm.cscript['Stop Purchase Order'] = function() { cur_frm.cscript['Stop Purchase Order'] = function() {
var doc = cur_frm.doc; var doc = cur_frm.doc;
var check = confirm("Do you really want to STOP " + doc.name); var check = confirm("Do you really want to STOP " + doc.name);
if (check) { if (check) {
$c('runserverobj', args={'method':'update_status', 'arg': 'Stopped', 'docs': compress_doclist(make_doclist(doc.doctype, doc.name))}, function(r,rt) { $c('runserverobj', args={'method':'update_status', 'arg': 'Stopped', 'docs': compress_doclist(make_doclist(doc.doctype, doc.name))}, function(r,rt) {
cur_frm.refresh(); cur_frm.refresh();
}); });
} }
} }
// Unstop PURCHASE ORDER // Unstop PURCHASE ORDER
// ================================================================================================== // ==================================================================================================
cur_frm.cscript['Unstop Purchase Order'] = function() { cur_frm.cscript['Unstop Purchase Order'] = function() {
var doc = cur_frm.doc; var doc = cur_frm.doc;
var check = confirm("Do you really want to UNSTOP " + doc.name); var check = confirm("Do you really want to UNSTOP " + doc.name);
if (check) { if (check) {
$c('runserverobj', args={'method':'update_status', 'arg': 'Submitted', 'docs': compress_doclist(make_doclist(doc.doctype, doc.name))}, function(r,rt) { $c('runserverobj', args={'method':'update_status', 'arg': 'Submitted', 'docs': compress_doclist(make_doclist(doc.doctype, doc.name))}, function(r,rt) {
cur_frm.refresh(); cur_frm.refresh();
}); });
} }
} }
// ***************** Get Print Heading ***************** // ***************** Get Print Heading *****************
cur_frm.fields_dict['select_print_heading'].get_query = function(doc, cdt, cdn) { cur_frm.fields_dict['select_print_heading'].get_query = function(doc, cdt, cdn) {
return 'SELECT `tabPrint Heading`.name FROM `tabPrint Heading` WHERE `tabPrint Heading`.docstatus !=2 AND `tabPrint Heading`.name LIKE "%s" ORDER BY `tabPrint Heading`.name ASC LIMIT 50'; return 'SELECT `tabPrint Heading`.name FROM `tabPrint Heading` WHERE `tabPrint Heading`.docstatus !=2 AND `tabPrint Heading`.name LIKE "%s" ORDER BY `tabPrint Heading`.name ASC LIMIT 50';
} }
//****************** For print sales order no and date************************* //****************** For print sales order no and date*************************
cur_frm.pformat.indent_no = function(doc, cdt, cdn){ cur_frm.pformat.indent_no = function(doc, cdt, cdn){
//function to make row of table //function to make row of table
var make_row = function(title,val1, val2, bold){ var make_row = function(title,val1, val2, bold){
var bstart = '<b>'; var bend = '</b>'; var bstart = '<b>'; var bend = '</b>';
return '<tr><td style="width:39%;">'+(bold?bstart:'')+title+(bold?bend:'')+'</td>' return '<tr><td style="width:39%;">'+(bold?bstart:'')+title+(bold?bend:'')+'</td>'
+'<td style="width:61%;text-align:left;">'+val1+(val2?' ('+dateutil.str_to_user(val2)+')':'')+'</td>' +'<td style="width:61%;text-align:left;">'+val1+(val2?' ('+dateutil.str_to_user(val2)+')':'')+'</td>'
+'</tr>' +'</tr>'
} }
out =''; out ='';
var cl = getchildren('PO Detail',doc.name,'po_details'); var cl = getchildren('PO Detail',doc.name,'po_details');
// outer table // outer table
var out='<div><table class="noborder" style="width:100%"><tr><td style="width: 50%"></td><td>'; var out='<div><table class="noborder" style="width:100%"><tr><td style="width: 50%"></td><td>';
// main table // main table
out +='<table class="noborder" style="width:100%">'; out +='<table class="noborder" style="width:100%">';
// add rows // add rows
if(cl.length){ if(cl.length){
prevdoc_list = new Array(); prevdoc_list = new Array();
for(var i=0;i<cl.length;i++){ for(var i=0;i<cl.length;i++){
if(cl[i].prevdoc_doctype == 'Indent' && cl[i].prevdoc_docname && prevdoc_list.indexOf(cl[i].prevdoc_docname) == -1) { if(cl[i].prevdoc_doctype == 'Indent' && cl[i].prevdoc_docname && prevdoc_list.indexOf(cl[i].prevdoc_docname) == -1) {
prevdoc_list.push(cl[i].prevdoc_docname); prevdoc_list.push(cl[i].prevdoc_docname);
if(prevdoc_list.length ==1) if(prevdoc_list.length ==1)
out += make_row(cl[i].prevdoc_doctype, cl[i].prevdoc_docname, cl[i].prevdoc_date,0); out += make_row(cl[i].prevdoc_doctype, cl[i].prevdoc_docname, cl[i].prevdoc_date,0);
else else
out += make_row('', cl[i].prevdoc_docname, cl[i].prevdoc_date,0); out += make_row('', cl[i].prevdoc_docname, cl[i].prevdoc_date,0);
} }
} }
} }
out +='</table></td></tr></table></div>'; out +='</table></td></tr></table></div>';
return out; return out;
} }
$import(Notification Control) $import(Notification Control)

View File

@ -19,325 +19,340 @@ convert_to_lists = webnotes.conn.convert_to_lists
from utilities.transaction_base import TransactionBase from utilities.transaction_base import TransactionBase
class DocType(TransactionBase): class DocType(TransactionBase):
def __init__(self, doc, doclist=[]): def __init__(self, doc, doclist=[]):
self.doc = doc self.doc = doc
self.doclist = doclist self.doclist = doclist
self.defaults = get_defaults() self.defaults = get_defaults()
self.tname = 'PO Detail' self.tname = 'PO Detail'
self.fname = 'po_details' self.fname = 'po_details'
# Autoname # Autoname
# --------- # ---------
def autoname(self): def autoname(self):
self.doc.name = make_autoname(self.doc.naming_series+'.#####') self.doc.name = make_autoname(self.doc.naming_series+'.#####')
def get_default_schedule_date(self): def get_default_schedule_date(self):
get_obj(dt = 'Purchase Common').get_default_schedule_date(self) get_obj(dt = 'Purchase Common').get_default_schedule_date(self)
def validate_fiscal_year(self): def validate_fiscal_year(self):
get_obj(dt = 'Purchase Common').validate_fiscal_year(self.doc.fiscal_year,self.doc.transaction_date,'PO Date') get_obj(dt = 'Purchase Common').validate_fiscal_year(self.doc.fiscal_year,self.doc.transaction_date,'PO Date')
# Get Item Details # Get Item Details
def get_item_details(self, arg =''): def get_item_details(self, arg =''):
return get_obj(dt='Purchase Common').get_item_details(self,arg) if arg:
return get_obj(dt='Purchase Common').get_item_details(self,arg)
# Get UOM Details else:
def get_uom_details(self, arg = ''): obj = get_obj('Purchase Common')
return get_obj(dt='Purchase Common').get_uom_details(arg) for doc in self.doclist:
if doc.fields.get('item_code'):
# get available qty at warehouse temp = {
def get_bin_details(self, arg = ''): 'item_code': doc.fields.get('item_code'),
return get_obj(dt='Purchase Common').get_bin_details(arg) 'warehouse': doc.fields.get('warehouse')
}
# Pull Indent ret = obj.get_item_details(self, json.dumps(temp))
def get_indent_details(self): for r in ret:
#self.validate_prev_docname() if not doc.fields.get(r):
if self.doc.indent_no: doc.fields[r] = ret[r]
get_obj('DocType Mapper','Indent-Purchase Order').dt_map('Indent','Purchase Order',self.doc.indent_no, self.doc, self.doclist, "[['Indent','Purchase Order'],['Indent Detail', 'PO Detail']]")
for d in getlist(self.doclist, 'po_details'):
if d.item_code:
item = sql("select last_purchase_rate from tabItem where name = '%s'" %(d.item_code), as_dict=1)
d.purchase_rate = item and flt(item[0]['last_purchase_rate']) or 0
d.import_rate = flt(item and flt(item[0]['last_purchase_rate']) or 0) / flt(self.doc.fields.has_key('conversion_rate') and flt(self.doc.conversion_rate) or 1)
if self.doc.supplier_qtn:
get_obj('DocType Mapper','Supplier Quotation-Purchase Order').dt_map('Supplier Quotation','Purchase Order',self.doc.supplier_qtn, self.doc, self.doclist, "[['Supplier Quotation','Purchase Order'],['Supplier Quotation Detail', 'PO Detail']]")
# GET TERMS & CONDITIONS
# =====================================================================================
def get_tc_details(self):
return get_obj('Purchase Common').get_tc_details(self)
# validate if indent has been pulled twice
def validate_prev_docname(self):
for d in getlist(self.doclist, 'po_details'):
if d.prevdoc_docname and self.doc.indent_no == d.prevdoc_docname:
msgprint(cstr(self.doc.indent_no) + " indent details have already been pulled. ")
raise Exception
# get last purchase rate
def get_last_purchase_rate(self):
get_obj('Purchase Common').get_last_purchase_rate(self)
# validation
#-------------------------------------------------------------------------------------------------------------
def validate_doc(self,pc_obj):
# Please Check Supplier Quotation - Purchase ORder Transaction , it has to be discussed
if self.doc.supp_quo_no:
pc_obj.validate_doc(obj = self, prevdoc_doctype = 'Supplier Quotation', prevdoc_docname = cstr(self.doc.supp_quo_no))
else:
# Validate values with reference document
pc_obj.validate_reference_value(obj = self)
# Check for Stopped status
def check_for_stopped_status(self, pc_obj):
check_list =[]
for d in getlist(self.doclist, 'po_details'):
if d.fields.has_key('prevdoc_docname') and d.prevdoc_docname and d.prevdoc_docname not in check_list:
check_list.append(d.prevdoc_docname)
pc_obj.check_for_stopped_status( d.prevdoc_doctype, d.prevdoc_docname)
# Validate
def validate(self):
self.validate_fiscal_year()
# Step 1:=> set status as "Draft"
set(self.doc, 'status', 'Draft')
# Step 2:=> get Purchase Common Obj
pc_obj = get_obj(dt='Purchase Common')
# Step 3:=> validate mandatory
pc_obj.validate_mandatory(self)
# Step 4:=> validate for items
pc_obj.validate_for_items(self)
# Step 5:=> validate conversion rate
pc_obj.validate_conversion_rate(self)
# Get po date
pc_obj.get_prevdoc_date(self)
# validate_doc
self.validate_doc(pc_obj)
# Check for stopped status
self.check_for_stopped_status(pc_obj)
# get total in words
dcc = TransactionBase().get_company_currency(self.doc.company)
self.doc.in_words = pc_obj.get_total_in_words(dcc, self.doc.grand_total)
self.doc.in_words_import = pc_obj.get_total_in_words(self.doc.currency, self.doc.grand_total_import)
# update bin
# ----------
def update_bin(self, is_submit, is_stopped = 0):
pc_obj = get_obj('Purchase Common')
for d in getlist(self.doclist, 'po_details'):
#1. Check if is_stock_item == 'Yes'
if sql("select is_stock_item from tabItem where name=%s", d.item_code)[0][0]=='Yes':
ind_qty, po_qty = 0, flt(d.qty) * flt(d.conversion_factor)
if is_stopped:
po_qty = flt(d.qty) > flt(d.received_qty) and flt( flt(flt(d.qty) - flt(d.received_qty)) * flt(d.conversion_factor))or 0
# No updates in Indent on Stop / Unstop
if cstr(d.prevdoc_doctype) == 'Indent' and not is_stopped:
# get qty and pending_qty of prevdoc
curr_ref_qty = pc_obj.get_qty( d.doctype, 'prevdoc_detail_docname', d.prevdoc_detail_docname, 'Indent Detail', 'Indent - Purchase Order', self.doc.name)
max_qty, qty, curr_qty = flt(curr_ref_qty.split('~~~')[1]), flt(curr_ref_qty.split('~~~')[0]), 0
if flt(qty) + flt(po_qty) > flt(max_qty):
curr_qty = flt(max_qty) - flt(qty)
# special case as there is no restriction for Indent - Purchase Order
curr_qty = (curr_qty > 0) and curr_qty or 0
else:
curr_qty = flt(po_qty)
ind_qty = -flt(curr_qty)
#==> Update Bin's Indent Qty by +- ind_qty and Ordered Qty by +- qty
get_obj('Warehouse', d.warehouse).update_bin(0, 0, (is_submit and 1 or -1) * flt(po_qty), (is_submit and 1 or -1) * flt(ind_qty), 0, d.item_code, self.doc.transaction_date)
def check_modified_date(self):
mod_db = sql("select modified from `tabPurchase Order` where name = '%s'" % self.doc.name)
date_diff = sql("select TIMEDIFF('%s', '%s')" % ( mod_db[0][0],cstr(self.doc.modified)))
if date_diff and date_diff[0][0]:
msgprint(cstr(self.doc.doctype) +" => "+ cstr(self.doc.name) +" has been modified. Please Refresh. ")
raise Exception
# On Close
#-------------------------------------------------------------------------------------------------
def update_status(self, status):
self.check_modified_date()
# step 1:=> Set Status
set(self.doc,'status',cstr(status))
# step 2:=> Update Bin
self.update_bin(is_submit = (status == 'Submitted') and 1 or 0, is_stopped = 1)
# step 3:=> Acknowledge user
msgprint(self.doc.doctype + ": " + self.doc.name + " has been %s." % ((status == 'Submitted') and 'Unstopped' or cstr(status)))
# On Submit
def on_submit(self):
pc_obj = get_obj(dt ='Purchase Common')
# Step 1 :=> Update Previous Doc i.e. update pending_qty and Status accordingly
pc_obj.update_prevdoc_detail(self, is_submit = 1)
# Step 2 :=> Update Bin # Get UOM Details
self.update_bin(is_submit = 1, is_stopped = 0) def get_uom_details(self, arg = ''):
return get_obj(dt='Purchase Common').get_uom_details(arg)
# Step 3 :=> Check For Approval Authority
get_obj('Authorization Control').validate_approving_authority(self.doc.doctype, self.doc.company, self.doc.grand_total)
# Step 4 :=> Update Current PO No. in Supplier as last_purchase_order.
update_supplier = sql("update `tabSupplier` set last_purchase_order = '%s' where name = '%s'" % (self.doc.name, self.doc.supplier))
# Step 5 :=> Update last purchase rate # get available qty at warehouse
pc_obj.update_last_purchase_rate(self, is_submit = 1) def get_bin_details(self, arg = ''):
return get_obj(dt='Purchase Common').get_bin_details(arg)
# Step 6 :=> Set Status # Pull Indent
set(self.doc,'status','Submitted') def get_indent_details(self):
#self.validate_prev_docname()
self.doc.indent_no = ''; if self.doc.indent_no:
get_obj('DocType Mapper','Indent-Purchase Order').dt_map('Indent','Purchase Order',self.doc.indent_no, self.doc, self.doclist, "[['Indent','Purchase Order'],['Indent Detail', 'PO Detail']]")
for d in getlist(self.doclist, 'po_details'):
# On Cancel if d.item_code:
# ------------------------------------------------------------------------------------------------------- item = sql("select last_purchase_rate from tabItem where name = '%s'" %(d.item_code), as_dict=1)
def on_cancel(self): d.purchase_rate = item and flt(item[0]['last_purchase_rate']) or 0
pc_obj = get_obj(dt = 'Purchase Common') d.import_rate = flt(item and flt(item[0]['last_purchase_rate']) or 0) / flt(self.doc.fields.has_key('conversion_rate') and flt(self.doc.conversion_rate) or 1)
if self.doc.supplier_qtn:
# 1.Check if PO status is stopped get_obj('DocType Mapper','Supplier Quotation-Purchase Order').dt_map('Supplier Quotation','Purchase Order',self.doc.supplier_qtn, self.doc, self.doclist, "[['Supplier Quotation','Purchase Order'],['Supplier Quotation Detail', 'PO Detail']]")
pc_obj.check_for_stopped_status(cstr(self.doc.doctype), cstr(self.doc.name))
# GET TERMS & CONDITIONS
self.check_for_stopped_status(pc_obj) # =====================================================================================
def get_tc_details(self):
# 2.Check if Purchase Receipt has been submitted against current Purchase Order return get_obj('Purchase Common').get_tc_details(self)
pc_obj.check_docstatus(check = 'Next', doctype = 'Purchase Receipt', docname = self.doc.name, detail_doctype = 'Purchase Receipt Detail')
# 3.Check if Payable Voucher has been submitted against current Purchase Order # validate if indent has been pulled twice
#pc_obj.check_docstatus(check = 'Next', doctype = 'Payable Voucher', docname = self.doc.name, detail_doctype = 'PV Detail') def validate_prev_docname(self):
for d in getlist(self.doclist, 'po_details'):
submitted = sql("select t1.name from `tabPayable Voucher` t1,`tabPV Detail` t2 where t1.name = t2.parent and t2.purchase_order = '%s' and t1.docstatus = 1" % self.doc.name) if d.prevdoc_docname and self.doc.indent_no == d.prevdoc_docname:
if submitted: msgprint(cstr(self.doc.indent_no) + " indent details have already been pulled. ")
msgprint("Purchase Invoice : " + cstr(submitted[0][0]) + " has already been submitted !") raise Exception
raise Exception
# 4.Set Status as Cancelled # get last purchase rate
set(self.doc,'status','Cancelled') def get_last_purchase_rate(self):
get_obj('Purchase Common').get_last_purchase_rate(self)
# validation
#-------------------------------------------------------------------------------------------------------------
def validate_doc(self,pc_obj):
# Please Check Supplier Quotation - Purchase ORder Transaction , it has to be discussed
if self.doc.supp_quo_no:
pc_obj.validate_doc(obj = self, prevdoc_doctype = 'Supplier Quotation', prevdoc_docname = cstr(self.doc.supp_quo_no))
else:
# Validate values with reference document
pc_obj.validate_reference_value(obj = self)
# 5.Update Indents Pending Qty and accordingly it's Status # Check for Stopped status
pc_obj.update_prevdoc_detail(self,is_submit = 0) def check_for_stopped_status(self, pc_obj):
check_list =[]
# 6.Update Bin for d in getlist(self.doclist, 'po_details'):
self.update_bin( is_submit = 0, is_stopped = 0) if d.fields.has_key('prevdoc_docname') and d.prevdoc_docname and d.prevdoc_docname not in check_list:
check_list.append(d.prevdoc_docname)
# Step 7 :=> Update last purchase rate pc_obj.check_for_stopped_status( d.prevdoc_doctype, d.prevdoc_docname)
pc_obj.update_last_purchase_rate(self, is_submit = 0)
# Validate
def validate(self):
self.validate_fiscal_year()
# Step 1:=> set status as "Draft"
set(self.doc, 'status', 'Draft')
# Step 2:=> get Purchase Common Obj
pc_obj = get_obj(dt='Purchase Common')
# Step 3:=> validate mandatory
pc_obj.validate_mandatory(self)
# Step 4:=> validate for items
pc_obj.validate_for_items(self)
# Step 5:=> validate conversion rate
pc_obj.validate_conversion_rate(self)
# Get po date
pc_obj.get_prevdoc_date(self)
# validate_doc
self.validate_doc(pc_obj)
# Check for stopped status
self.check_for_stopped_status(pc_obj)
# get total in words
dcc = TransactionBase().get_company_currency(self.doc.company)
self.doc.in_words = pc_obj.get_total_in_words(dcc, self.doc.grand_total)
self.doc.in_words_import = pc_obj.get_total_in_words(self.doc.currency, self.doc.grand_total_import)
# update bin
# ----------
def update_bin(self, is_submit, is_stopped = 0):
pc_obj = get_obj('Purchase Common')
for d in getlist(self.doclist, 'po_details'):
#1. Check if is_stock_item == 'Yes'
if sql("select is_stock_item from tabItem where name=%s", d.item_code)[0][0]=='Yes':
ind_qty, po_qty = 0, flt(d.qty) * flt(d.conversion_factor)
if is_stopped:
po_qty = flt(d.qty) > flt(d.received_qty) and flt( flt(flt(d.qty) - flt(d.received_qty)) * flt(d.conversion_factor))or 0
# No updates in Indent on Stop / Unstop
if cstr(d.prevdoc_doctype) == 'Indent' and not is_stopped:
# get qty and pending_qty of prevdoc
curr_ref_qty = pc_obj.get_qty( d.doctype, 'prevdoc_detail_docname', d.prevdoc_detail_docname, 'Indent Detail', 'Indent - Purchase Order', self.doc.name)
max_qty, qty, curr_qty = flt(curr_ref_qty.split('~~~')[1]), flt(curr_ref_qty.split('~~~')[0]), 0
if flt(qty) + flt(po_qty) > flt(max_qty):
curr_qty = flt(max_qty) - flt(qty)
# special case as there is no restriction for Indent - Purchase Order
curr_qty = (curr_qty > 0) and curr_qty or 0
else:
curr_qty = flt(po_qty)
ind_qty = -flt(curr_qty)
#==> Update Bin's Indent Qty by +- ind_qty and Ordered Qty by +- qty
get_obj('Warehouse', d.warehouse).update_bin(0, 0, (is_submit and 1 or -1) * flt(po_qty), (is_submit and 1 or -1) * flt(ind_qty), 0, d.item_code, self.doc.transaction_date)
def check_modified_date(self):
mod_db = sql("select modified from `tabPurchase Order` where name = '%s'" % self.doc.name)
date_diff = sql("select TIMEDIFF('%s', '%s')" % ( mod_db[0][0],cstr(self.doc.modified)))
if date_diff and date_diff[0][0]:
msgprint(cstr(self.doc.doctype) +" => "+ cstr(self.doc.name) +" has been modified. Please Refresh. ")
raise Exception
# On Close
#-------------------------------------------------------------------------------------------------
def update_status(self, status):
self.check_modified_date()
# step 1:=> Set Status
set(self.doc,'status',cstr(status))
# step 2:=> Update Bin
self.update_bin(is_submit = (status == 'Submitted') and 1 or 0, is_stopped = 1)
# step 3:=> Acknowledge user
msgprint(self.doc.doctype + ": " + self.doc.name + " has been %s." % ((status == 'Submitted') and 'Unstopped' or cstr(status)))
# On Submit
def on_submit(self):
pc_obj = get_obj(dt ='Purchase Common')
# Step 1 :=> Update Previous Doc i.e. update pending_qty and Status accordingly
pc_obj.update_prevdoc_detail(self, is_submit = 1)
# Step 2 :=> Update Bin
self.update_bin(is_submit = 1, is_stopped = 0)
# Step 3 :=> Check For Approval Authority
get_obj('Authorization Control').validate_approving_authority(self.doc.doctype, self.doc.company, self.doc.grand_total)
# Step 4 :=> Update Current PO No. in Supplier as last_purchase_order.
update_supplier = sql("update `tabSupplier` set last_purchase_order = '%s' where name = '%s'" % (self.doc.name, self.doc.supplier))
# Step 5 :=> Update last purchase rate
pc_obj.update_last_purchase_rate(self, is_submit = 1)
# Step 6 :=> Set Status
set(self.doc,'status','Submitted')
self.doc.indent_no = '';
# On Cancel
# -------------------------------------------------------------------------------------------------------
def on_cancel(self):
pc_obj = get_obj(dt = 'Purchase Common')
# 1.Check if PO status is stopped
pc_obj.check_for_stopped_status(cstr(self.doc.doctype), cstr(self.doc.name))
self.check_for_stopped_status(pc_obj)
# 2.Check if Purchase Receipt has been submitted against current Purchase Order
pc_obj.check_docstatus(check = 'Next', doctype = 'Purchase Receipt', docname = self.doc.name, detail_doctype = 'Purchase Receipt Detail')
# 3.Check if Payable Voucher has been submitted against current Purchase Order
#pc_obj.check_docstatus(check = 'Next', doctype = 'Payable Voucher', docname = self.doc.name, detail_doctype = 'PV Detail')
submitted = sql("select t1.name from `tabPayable Voucher` t1,`tabPV Detail` t2 where t1.name = t2.parent and t2.purchase_order = '%s' and t1.docstatus = 1" % self.doc.name)
if submitted:
msgprint("Purchase Invoice : " + cstr(submitted[0][0]) + " has already been submitted !")
raise Exception
# 4.Set Status as Cancelled
set(self.doc,'status','Cancelled')
# 5.Update Indents Pending Qty and accordingly it's Status
pc_obj.update_prevdoc_detail(self,is_submit = 0)
# 6.Update Bin
self.update_bin( is_submit = 0, is_stopped = 0)
# Step 7 :=> Update last purchase rate
pc_obj.update_last_purchase_rate(self, is_submit = 0)
#----------- code for Sub-contracted Items ------------------- #----------- code for Sub-contracted Items -------------------
#--------check for sub-contracted items and accordingly update PO raw material detail table-------- #--------check for sub-contracted items and accordingly update PO raw material detail table--------
def update_rw_material_detail(self): def update_rw_material_detail(self):
for d in getlist(self.doclist,'po_details'): for d in getlist(self.doclist,'po_details'):
item_det = sql("select is_sub_contracted_item, is_purchase_item from `tabItem` where name = '%s'"%(d.item_code)) item_det = sql("select is_sub_contracted_item, is_purchase_item from `tabItem` where name = '%s'"%(d.item_code))
if item_det[0][0] == 'Yes': if item_det[0][0] == 'Yes':
if item_det[0][1] == 'Yes': if item_det[0][1] == 'Yes':
if not self.doc.is_subcontracted: if not self.doc.is_subcontracted:
msgprint("Please enter whether purchase order to be made for subcontracting or for purchasing in 'Is Subcontracted' field .") msgprint("Please enter whether purchase order to be made for subcontracting or for purchasing in 'Is Subcontracted' field .")
raise Exception raise Exception
if self.doc.is_subcontracted == 'Yes': if self.doc.is_subcontracted == 'Yes':
self.add_bom(d) self.add_bom(d)
else: else:
self.doc.clear_table(self.doclist,'po_raw_material_details',1) self.doc.clear_table(self.doclist,'po_raw_material_details',1)
self.doc.save() self.doc.save()
elif item_det[0][1] == 'No': elif item_det[0][1] == 'No':
self.add_bom(d) self.add_bom(d)
self.delete_irrelevant_raw_material() self.delete_irrelevant_raw_material()
#---------------calculate amt in PO Raw Material Detail------------- #---------------calculate amt in PO Raw Material Detail-------------
self.calculate_amount(d) self.calculate_amount(d)
def add_bom(self, d): def add_bom(self, d):
#----- fetching default bom from Bill of Materials instead of Item Master -- #----- fetching default bom from Bill of Materials instead of Item Master --
bom_det = sql("select t1.item, t2.item_code, t2.qty_consumed_per_unit, t2.moving_avg_rate, t2.value_as_per_mar, t2.stock_uom, t2.name, t2.parent from `tabBill Of Materials` t1, `tabBOM Material` t2 where t2.parent = t1.name and t1.item = '%s' and ifnull(t1.is_default,0) = 1 and t1.docstatus = 1" % d.item_code) bom_det = sql("select t1.item, t2.item_code, t2.qty_consumed_per_unit, t2.moving_avg_rate, t2.value_as_per_mar, t2.stock_uom, t2.name, t2.parent from `tabBill Of Materials` t1, `tabBOM Material` t2 where t2.parent = t1.name and t1.item = '%s' and ifnull(t1.is_default,0) = 1 and t1.docstatus = 1" % d.item_code)
if not bom_det: if not bom_det:
msgprint("No default BOM exists for item: %s" % d.item_code) msgprint("No default BOM exists for item: %s" % d.item_code)
raise Exception raise Exception
else: else:
#-------------- add child function-------------------- #-------------- add child function--------------------
chgd_rqd_qty = [] chgd_rqd_qty = []
for i in bom_det: for i in bom_det:
if i and not sql("select name from `tabPO Raw Material Detail` where reference_name = '%s' and bom_detail_no = '%s' and parent = '%s' " %(d.name, i[6], self.doc.name)): if i and not sql("select name from `tabPO Raw Material Detail` where reference_name = '%s' and bom_detail_no = '%s' and parent = '%s' " %(d.name, i[6], self.doc.name)):
rm_child = addchild(self.doc, 'po_raw_material_details', 'PO Raw Material Detail', 1, self.doclist) rm_child = addchild(self.doc, 'po_raw_material_details', 'PO Raw Material Detail', 1, self.doclist)
rm_child.reference_name = d.name rm_child.reference_name = d.name
rm_child.bom_detail_no = i and i[6] or '' rm_child.bom_detail_no = i and i[6] or ''
rm_child.main_item_code = i and i[0] or '' rm_child.main_item_code = i and i[0] or ''
rm_child.rm_item_code = i and i[1] or '' rm_child.rm_item_code = i and i[1] or ''
rm_child.stock_uom = i and i[5] or '' rm_child.stock_uom = i and i[5] or ''
rm_child.rate = i and flt(i[3]) or flt(i[4]) rm_child.rate = i and flt(i[3]) or flt(i[4])
rm_child.conversion_factor = d.conversion_factor rm_child.conversion_factor = d.conversion_factor
rm_child.required_qty = flt(i and flt(i[2]) or 0) * flt(d.qty) * flt(d.conversion_factor) rm_child.required_qty = flt(i and flt(i[2]) or 0) * flt(d.qty) * flt(d.conversion_factor)
rm_child.amount = flt(flt(rm_child.consumed_qty)*flt(rm_child.rate)) rm_child.amount = flt(flt(rm_child.consumed_qty)*flt(rm_child.rate))
rm_child.save() rm_child.save()
chgd_rqd_qty.append(cstr(i[1])) chgd_rqd_qty.append(cstr(i[1]))
else: else:
act_qty = flt(i and flt(i[2]) or 0) * flt(d.qty) * flt(d.conversion_factor) act_qty = flt(i and flt(i[2]) or 0) * flt(d.qty) * flt(d.conversion_factor)
for po_rmd in getlist(self.doclist, 'po_raw_material_details'): for po_rmd in getlist(self.doclist, 'po_raw_material_details'):
if i and i[6] == po_rmd.bom_detail_no and (flt(act_qty) != flt(po_rmd.required_qty) or i[1] != po_rmd.rm_item_code): if i and i[6] == po_rmd.bom_detail_no and (flt(act_qty) != flt(po_rmd.required_qty) or i[1] != po_rmd.rm_item_code):
chgd_rqd_qty.append(cstr(i[1])) chgd_rqd_qty.append(cstr(i[1]))
po_rmd.main_item_code = i[0] po_rmd.main_item_code = i[0]
po_rmd.rm_item_code = i[1] po_rmd.rm_item_code = i[1]
po_rmd.stock_uom = i[5] po_rmd.stock_uom = i[5]
po_rmd.required_qty = flt(act_qty) po_rmd.required_qty = flt(act_qty)
po_rmd.rate = i and flt(i[3]) or flt(i[4]) po_rmd.rate = i and flt(i[3]) or flt(i[4])
po_rmd.amount = flt(flt(po_rmd.consumed_qty)*flt(po_rmd.rate)) po_rmd.amount = flt(flt(po_rmd.consumed_qty)*flt(po_rmd.rate))
# Delete irrelevant raw material from PR Raw material details # Delete irrelevant raw material from PR Raw material details
#-------------------------------------------------------------- #--------------------------------------------------------------
def delete_irrelevant_raw_material(self): def delete_irrelevant_raw_material(self):
for d in getlist(self.doclist,'po_raw_material_details'): for d in getlist(self.doclist,'po_raw_material_details'):
if not sql("select name from `tabPO Detail` where name = '%s' and parent = '%s'and item_code = '%s'" % (d.reference_name, self.doc.name, d.main_item_code)): if not sql("select name from `tabPO Detail` where name = '%s' and parent = '%s'and item_code = '%s'" % (d.reference_name, self.doc.name, d.main_item_code)):
d.parent = 'old_par:'+self.doc.name d.parent = 'old_par:'+self.doc.name
d.save() d.save()
def calculate_amount(self, d): def calculate_amount(self, d):
amt = 0 amt = 0
for i in getlist(self.doclist,'po_raw_material_details'): for i in getlist(self.doclist,'po_raw_material_details'):
if(i.reference_name == d.name): if(i.reference_name == d.name):
i.amount = flt(i.required_qty)* flt(i.rate) i.amount = flt(i.required_qty)* flt(i.rate)
amt += i.amount amt += i.amount
d.rm_supp_cost = amt d.rm_supp_cost = amt
# On Update # On Update
# ---------------------------------------------------------------------------------------------------- # ----------------------------------------------------------------------------------------------------
def on_update(self): def on_update(self):
self.update_rw_material_detail() self.update_rw_material_detail()
# OTHER CHARGES TRIGGER FUNCTIONS # OTHER CHARGES TRIGGER FUNCTIONS
# ==================================================================================== # ====================================================================================
# *********** Get Tax rate if account type is TAX ******************** # *********** Get Tax rate if account type is TAX ********************
def get_rate(self,arg): def get_rate(self,arg):
return get_obj('Purchase Common').get_rate(arg,self) return get_obj('Purchase Common').get_rate(arg,self)
# **** Pull details from other charges master (Get Other Charges) **** # **** Pull details from other charges master (Get Other Charges) ****
def get_purchase_tax_details(self): def get_purchase_tax_details(self):
return get_obj('Purchase Common').get_purchase_tax_details(self) return get_obj('Purchase Common').get_purchase_tax_details(self)
# Repair Purchase Order # Repair Purchase Order
# =========================================== # ===========================================
def repair_purchase_order(self): def repair_purchase_order(self):
get_obj('Purchase Common', 'Purchase Common').repair_curr_doctype_details(self) get_obj('Purchase Common', 'Purchase Common').repair_curr_doctype_details(self)

View File

@ -94,8 +94,9 @@ class DocType:
from webnotes.utils import file_manager from webnotes.utils import file_manager
fn, content = file_manager.get_file(filename[1]) fn, content = file_manager.get_file(filename[1])
if not type(content) == str: # NOTE: Don't know why this condition exists
if not isinstance(content, basestring) and hasattr(content, 'tostring'):
content = content.tostring() content = content.tostring()
import webnotes.model.import_docs import webnotes.model.import_docs

View File

@ -2,49 +2,49 @@ $import(SMS Control)
cur_frm.cscript.refresh = function(doc, cdt, cdn){ cur_frm.cscript.refresh = function(doc, cdt, cdn){
// //
if(!doc.docstatus){ if(!doc.docstatus){
hide_field(['Update Follow up']); hide_field(['Update Follow up']);
hide_field(['email_id1','cc_to','subject','message','Attachment Html', 'Create New File', 'enquiry_attachment_detail','Send Email']); hide_field(['email_id1','cc_to','subject','message','Attachment Html', 'Create New File', 'enquiry_attachment_detail','Send Email']);
} }
else{ else{
unhide_field(['Update Follow up']); unhide_field(['Update Follow up']);
unhide_field(['email_id1','cc_to','subject','message','Attachment Html', 'Create New File', 'enquiry_attachment_detail','Send Email']); unhide_field(['email_id1','cc_to','subject','message','Attachment Html', 'Create New File', 'enquiry_attachment_detail','Send Email']);
} }
cur_frm.clear_custom_buttons(); cur_frm.clear_custom_buttons();
if(doc.docstatus == 1) { if(doc.docstatus == 1) {
cur_frm.add_custom_button('Create Quotation', cur_frm.cscript['Create Quotation']); cur_frm.add_custom_button('Create Quotation', cur_frm.cscript['Create Quotation']);
cur_frm.add_custom_button('Enquiry Lost', cur_frm.cscript['Declare Enquiry Lost']); cur_frm.add_custom_button('Enquiry Lost', cur_frm.cscript['Declare Enquiry Lost']);
cur_frm.add_custom_button('Send SMS', cur_frm.cscript['Send SMS']); cur_frm.add_custom_button('Send SMS', cur_frm.cscript['Send SMS']);
} }
//cur_frm.cscript.clear_values(doc,cdt,cdn); //cur_frm.cscript.clear_values(doc,cdt,cdn);
} }
// ONLOAD // ONLOAD
// =============================================================== // ===============================================================
cur_frm.cscript.onload = function(doc, cdt, cdn) { cur_frm.cscript.onload = function(doc, cdt, cdn) {
if(!doc.enquiry_from) hide_field(['customer', 'customer_address', 'contact_person', 'customer_name','lead', 'lead_name', 'address_display', 'contact_display', 'contact_mobile', 'contact_email', 'territory', 'customer_group']); if(!doc.enquiry_from) hide_field(['customer', 'customer_address', 'contact_person', 'customer_name','lead', 'lead_name', 'address_display', 'contact_display', 'contact_mobile', 'contact_email', 'territory', 'customer_group']);
if(!doc.status) set_multiple(cdt,cdn,{status:'Draft'}); if(!doc.status) set_multiple(cdt,cdn,{status:'Draft'});
if(!doc.date) doc.transaction_date = date.obj_to_str(new Date()); if(!doc.date) doc.transaction_date = date.obj_to_str(new Date());
if(!doc.company && sys_defaults.company) set_multiple(cdt,cdn,{company:sys_defaults.company}); if(!doc.company && sys_defaults.company) set_multiple(cdt,cdn,{company:sys_defaults.company});
if(!doc.fiscal_year && sys_defaults.fiscal_year) set_multiple(cdt,cdn,{fiscal_year:sys_defaults.fiscal_year}); if(!doc.fiscal_year && sys_defaults.fiscal_year) set_multiple(cdt,cdn,{fiscal_year:sys_defaults.fiscal_year});
if(doc.enquiry_from) { if(doc.enquiry_from) {
if(doc.enquiry_from == 'Customer') { if(doc.enquiry_from == 'Customer') {
hide_field(['lead', 'lead_name']); hide_field(['lead', 'lead_name']);
} }
else if (doc.enquiry_from == 'Lead') { else if (doc.enquiry_from == 'Lead') {
hide_field(['customer', 'customer_address', 'contact_person', 'customer_name', 'contact_display', 'customer_group']); hide_field(['customer', 'customer_address', 'contact_person', 'customer_name', 'contact_display', 'customer_group']);
} }
} }
// setup fetch // setup fetch
cur_frm.cscript.set_fetch(); cur_frm.cscript.set_fetch();
} }
cur_frm.cscript.onload_post_render = function(doc, cdt, cdn) { cur_frm.cscript.onload_post_render = function(doc, cdt, cdn) {
@ -57,119 +57,119 @@ cur_frm.cscript.onload_post_render = function(doc, cdt, cdn) {
// =============================================================== // ===============================================================
cur_frm.cscript.set_fetch = function() { cur_frm.cscript.set_fetch = function() {
// item // item
cur_frm.add_fetch('item_code', 'item_name', 'item_name'); cur_frm.add_fetch('item_code', 'item_name', 'item_name');
cur_frm.add_fetch('item_code', 'stock_uom', 'uom'); cur_frm.add_fetch('item_code', 'stock_uom', 'uom');
cur_frm.add_fetch('item_code', 'description', 'description'); cur_frm.add_fetch('item_code', 'description', 'description');
cur_frm.add_fetch('item_code', 'item_group', 'item_group'); cur_frm.add_fetch('item_code', 'item_group', 'item_group');
cur_frm.add_fetch('item_code', 'brand', 'brand'); cur_frm.add_fetch('item_code', 'brand', 'brand');
// customer // customer
} }
// hide - unhide fields on basis of enquiry_from lead or customer // hide - unhide fields on basis of enquiry_from lead or customer
cur_frm.cscript.enquiry_from = function(doc,cdt,cdn){ cur_frm.cscript.enquiry_from = function(doc,cdt,cdn){
cur_frm.cscript.lead_cust_show(doc,cdt,cdn); cur_frm.cscript.lead_cust_show(doc,cdt,cdn);
} }
// hide - unhide fields based on lead or customer // hide - unhide fields based on lead or customer
cur_frm.cscript.lead_cust_show = function(doc,cdt,cdn){ cur_frm.cscript.lead_cust_show = function(doc,cdt,cdn){
if(doc.enquiry_from == 'Lead'){ if(doc.enquiry_from == 'Lead'){
unhide_field(['lead']); unhide_field(['lead']);
hide_field(['lead_name','customer','customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']); hide_field(['lead_name','customer','customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']);
doc.lead = doc.lead_name = doc.customer = doc.customer_address = doc.contact_person = doc.address_display = doc.contact_display = doc.contact_mobile = doc.contact_email = doc.territory = doc.customer_group = ""; doc.lead = doc.lead_name = doc.customer = doc.customer_address = doc.contact_person = doc.address_display = doc.contact_display = doc.contact_mobile = doc.contact_email = doc.territory = doc.customer_group = "";
} }
else if(doc.enquiry_from == 'Customer'){ else if(doc.enquiry_from == 'Customer'){
unhide_field(['customer']); unhide_field(['customer']);
hide_field(['lead','lead_name','address_display','contact_display','contact_mobile','contact_email','territory']); hide_field(['lead','lead_name','address_display','contact_display','contact_mobile','contact_email','territory']);
doc.lead = doc.lead_name = doc.customer = doc.customer_address = doc.contact_person = doc.address_display = doc.contact_display = doc.contact_mobile = doc.contact_email = doc.territory = doc.customer_group = ""; doc.lead = doc.lead_name = doc.customer = doc.customer_address = doc.contact_person = doc.address_display = doc.contact_display = doc.contact_mobile = doc.contact_email = doc.territory = doc.customer_group = "";
} }
} }
// customer // customer
cur_frm.cscript.customer = function(doc,dt,dn) { cur_frm.cscript.customer = function(doc,dt,dn) {
if(doc.customer) get_server_fields('get_default_customer_address', JSON.stringify({customer: doc.customer}),'', doc, dt, dn, 1); if(doc.customer) get_server_fields('get_default_customer_address', JSON.stringify({customer: doc.customer}),'', doc, dt, dn, 1);
if(doc.customer) unhide_field(['customer_name','customer_address','contact_person','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']); if(doc.customer) unhide_field(['customer_name','customer_address','contact_person','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']);
} }
cur_frm.cscript.customer_address = cur_frm.cscript.contact_person = function(doc,dt,dn) { cur_frm.cscript.customer_address = cur_frm.cscript.contact_person = function(doc,dt,dn) {
if(doc.customer) get_server_fields('get_customer_address', JSON.stringify({customer: doc.customer, address: doc.customer_address, contact: doc.contact_person}),'', doc, dt, dn, 1); if(doc.customer) get_server_fields('get_customer_address', JSON.stringify({customer: doc.customer, address: doc.customer_address, contact: doc.contact_person}),'', doc, dt, dn, 1);
} }
cur_frm.fields_dict.customer_address.on_new = function(dn) { cur_frm.fields_dict.customer_address.on_new = function(dn) {
locals['Address'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer; locals['Address'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
locals['Address'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name; locals['Address'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
} }
cur_frm.fields_dict.contact_person.on_new = function(dn) { cur_frm.fields_dict.contact_person.on_new = function(dn) {
locals['Contact'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer; locals['Contact'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
locals['Contact'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name; locals['Contact'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
} }
cur_frm.fields_dict['customer_address'].get_query = function(doc, cdt, cdn) { cur_frm.fields_dict['customer_address'].get_query = function(doc, cdt, cdn) {
return 'SELECT name,address_line1,city FROM tabAddress WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50'; return 'SELECT name,address_line1,city FROM tabAddress WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
} }
cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) { cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50'; return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
} }
// lead // lead
cur_frm.fields_dict['lead'].get_query = function(doc,cdt,cdn){ cur_frm.fields_dict['lead'].get_query = function(doc,cdt,cdn){
return 'SELECT `tabLead`.name, `tabLead`.lead_name FROM `tabLead` WHERE `tabLead`.%(key)s LIKE "%s" ORDER BY `tabLead`.`name` ASC LIMIT 50'; return 'SELECT `tabLead`.name, `tabLead`.lead_name FROM `tabLead` WHERE `tabLead`.%(key)s LIKE "%s" ORDER BY `tabLead`.`name` ASC LIMIT 50';
} }
cur_frm.cscript.lead = function(doc, cdt, cdn) { cur_frm.cscript.lead = function(doc, cdt, cdn) {
if(doc.lead) get_server_fields('get_lead_details', doc.lead,'', doc, cdt, cdn, 1); if(doc.lead) get_server_fields('get_lead_details', doc.lead,'', doc, cdt, cdn, 1);
if(doc.lead) unhide_field(['lead_name','address_display','contact_mobile','contact_email','territory']); if(doc.lead) unhide_field(['lead_name','address_display','contact_mobile','contact_email','territory']);
} }
//item getquery //item getquery
//======================================= //=======================================
cur_frm.fields_dict['enquiry_details'].grid.get_field('item_code').get_query = function(doc, cdt, cdn) { cur_frm.fields_dict['enquiry_details'].grid.get_field('item_code').get_query = function(doc, cdt, cdn) {
if (doc.enquiry_type == 'Maintenance') if (doc.enquiry_type == 'Maintenance')
return 'SELECT tabItem.name,tabItem.item_name,tabItem.description FROM tabItem WHERE tabItem.is_service_item="Yes" AND (ifnull(`tabItem`.`end_of_life`,"") = "" OR `tabItem`.`end_of_life` > NOW() OR `tabItem`.`end_of_life`="0000-00-00") AND tabItem.%(key)s LIKE "%s" LIMIT 50'; return 'SELECT tabItem.name,tabItem.item_name,tabItem.description FROM tabItem WHERE tabItem.is_service_item="Yes" AND (ifnull(`tabItem`.`end_of_life`,"") = "" OR `tabItem`.`end_of_life` > NOW() OR `tabItem`.`end_of_life`="0000-00-00") AND tabItem.%(key)s LIKE "%s" LIMIT 50';
else else
return 'SELECT tabItem.name,tabItem.item_name,tabItem.description FROM tabItem WHERE tabItem.is_sales_item="Yes" AND (ifnull(`tabItem`.`end_of_life`,"") = "" OR `tabItem`.`end_of_life` > NOW() OR `tabItem`.`end_of_life`="0000-00-00") AND tabItem.%(key)s LIKE "%s" LIMIT 50'; return 'SELECT tabItem.name,tabItem.item_name,tabItem.description FROM tabItem WHERE tabItem.is_sales_item="Yes" AND (ifnull(`tabItem`.`end_of_life`,"") = "" OR `tabItem`.`end_of_life` > NOW() OR `tabItem`.`end_of_life`="0000-00-00") AND tabItem.%(key)s LIKE "%s" LIMIT 50';
} }
//Fetch Item Details //Fetch Item Details
//==================================================================================================================== //====================================================================================================================
cur_frm.cscript.item_code = function(doc, cdt, cdn) { cur_frm.cscript.item_code = function(doc, cdt, cdn) {
var d = locals[cdt][cdn]; var d = locals[cdt][cdn];
if (d.item_code) { if (d.item_code) {
get_server_fields('get_item_details',d.item_code,'enquiry_details',doc,cdt,cdn,1); get_server_fields('get_item_details',d.item_code,'enquiry_details',doc,cdt,cdn,1);
} }
} }
/* /*
//Fetch Customer Details //Fetch Customer Details
//====================================================================================================================== //======================================================================================================================
cur_frm.cscript.customer = function(doc, cdt, cdn){ cur_frm.cscript.customer = function(doc, cdt, cdn){
if (doc.customer) { if (doc.customer) {
get_server_fields('get_cust_address',doc.customer,'',doc,cdt,cdn,1); get_server_fields('get_cust_address',doc.customer,'',doc,cdt,cdn,1);
} }
} }
*/ */
/* /*
//======================================================================================================================= //=======================================================================================================================
cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) { cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
return 'SELECT `tabContact`.contact_name FROM `tabContact` WHERE `tabContact`.is_customer = 1 AND `tabContact`.customer = "'+ doc.customer+'" AND `tabContact`.docstatus != 2 AND `tabContact`.contact_name LIKE "%s" ORDER BY `tabContact`.contact_name ASC LIMIT 50'; return 'SELECT `tabContact`.contact_name FROM `tabContact` WHERE `tabContact`.is_customer = 1 AND `tabContact`.customer = "'+ doc.customer+'" AND `tabContact`.docstatus != 2 AND `tabContact`.contact_name LIKE "%s" ORDER BY `tabContact`.contact_name ASC LIMIT 50';
} }
*/ */
/* /*
//======================================================================================================================= //=======================================================================================================================
cur_frm.cscript.contact_person = function(doc, cdt, cdn){ cur_frm.cscript.contact_person = function(doc, cdt, cdn){
if (doc.contact_person) { if (doc.contact_person) {
arg = {}; arg = {};
arg.contact_person = doc.contact_person; arg.contact_person = doc.contact_person;
arg.customer = doc.customer; arg.customer = doc.customer;
get_server_fields('get_contact_details',docstring(arg),'',doc,cdt,cdn,1); get_server_fields('get_contact_details',docstring(arg),'',doc,cdt,cdn,1);
} }
} }
*/ */
@ -177,159 +177,159 @@ cur_frm.cscript.contact_person = function(doc, cdt, cdn){
// hide - unhide fields based on lead or customer.. // hide - unhide fields based on lead or customer..
//======================================================================================================================= //=======================================================================================================================
cur_frm.cscript.clear_values = function(doc,cdt,cdn) { cur_frm.cscript.clear_values = function(doc,cdt,cdn) {
if(doc.enquiry_from == 'Lead') { if(doc.enquiry_from == 'Lead') {
doc.customer = doc.customer_name = doc.contact_person = doc.customer_group = ""; doc.customer = doc.customer_name = doc.contact_person = doc.customer_group = "";
} }
else if(doc.enquiry_from == 'Customer') { else if(doc.enquiry_from == 'Customer') {
doc.lead = doc.lead_name = ""; doc.lead = doc.lead_name = "";
} }
refresh_many(['lead','lead_name','customer','customer_name','contact_person','customer_group']); refresh_many(['lead','lead_name','customer','customer_name','contact_person','customer_group']);
} }
*/ */
/* /*
//================ hide - unhide fields on basis of enquiry from either lead or customer =============================== //================ hide - unhide fields on basis of enquiry from either lead or customer ===============================
cur_frm.cscript.enquiry_from = function(doc,cdt,cdn){ cur_frm.cscript.enquiry_from = function(doc,cdt,cdn){
cur_frm.cscript.clear_values(doc,cdt,cdn); cur_frm.cscript.clear_values(doc,cdt,cdn);
doc.address = doc.territory = doc.contact_no = doc.email_id = ""; doc.address = doc.territory = doc.contact_no = doc.email_id = "";
refresh_many(['territory','address','contact_no','email_id']); refresh_many(['territory','address','contact_no','email_id']);
} }
*/ */
/* /*
//================ create new contact ============================================================================ //================ create new contact ============================================================================
cur_frm.cscript.new_contact = function(){ cur_frm.cscript.new_contact = function(){
tn = createLocal('Contact'); tn = createLocal('Contact');
locals['Contact'][tn].is_customer = 1; locals['Contact'][tn].is_customer = 1;
if(doc.customer) locals['Contact'][tn].customer = doc.customer; if(doc.customer) locals['Contact'][tn].customer = doc.customer;
loaddoc('Contact', tn); loaddoc('Contact', tn);
} }
*/ */
//======================================================================================================================= //=======================================================================================================================
cur_frm.cscript['Create New File'] = function(doc){ cur_frm.cscript['Create New File'] = function(doc){
var fl = LocalDB.create('File'); var fl = LocalDB.create('File');
fl = locals['File'][fl]; fl = locals['File'][fl];
loaddoc('File', fl.name); loaddoc('File', fl.name);
} }
//update follow up //update follow up
//================================================================================= //=================================================================================
cur_frm.cscript['Update Follow up'] = function(doc,cdt,cdn){ cur_frm.cscript['Update Follow up'] = function(doc,cdt,cdn){
$c_obj(make_doclist(doc.doctype, doc.name),'update_follow_up','',function(r, rt){ $c_obj(make_doclist(doc.doctype, doc.name),'update_follow_up','',function(r, rt){
refresh_field('follow_up'); refresh_field('follow_up');
doc.__unsaved = 0; doc.__unsaved = 0;
cur_frm.refresh_header(); cur_frm.refresh_header();
}); });
} }
// Create New Quotation // Create New Quotation
// ======================================================================================================================= // =======================================================================================================================
cur_frm.cscript['Create Quotation'] = function(){ cur_frm.cscript['Create Quotation'] = function(){
n = createLocal("Quotation"); n = createLocal("Quotation");
$c('dt_map', args={ $c('dt_map', args={
'docs':compress_doclist([locals["Quotation"][n]]), 'docs':compress_doclist([locals["Quotation"][n]]),
'from_doctype':'Enquiry', 'from_doctype':'Enquiry',
'to_doctype':'Quotation', 'to_doctype':'Quotation',
'from_docname':cur_frm.docname, 'from_docname':cur_frm.docname,
'from_to_list':"[['Enquiry', 'Quotation'],['Enquiry Detail','Quotation Detail']]" 'from_to_list':"[['Enquiry', 'Quotation'],['Enquiry Detail','Quotation Detail']]"
} }
, function(r,rt) { , function(r,rt) {
loaddoc("Quotation", n); loaddoc("Quotation", n);
} }
); );
} }
// declare enquiry lost // declare enquiry lost
//------------------------- //-------------------------
cur_frm.cscript['Declare Enquiry Lost'] = function(){ cur_frm.cscript['Declare Enquiry Lost'] = function(){
var e_lost_dialog; var e_lost_dialog;
set_e_lost_dialog = function(){ set_e_lost_dialog = function(){
e_lost_dialog = new Dialog(400,150,'Add Enquiry Lost Reason'); e_lost_dialog = new Dialog(400,150,'Add Enquiry Lost Reason');
e_lost_dialog.make_body([ e_lost_dialog.make_body([
['HTML', 'Message', '<div class="comment">Please add enquiry lost reason</div>'], ['HTML', 'Message', '<div class="comment">Please add enquiry lost reason</div>'],
['Text', 'Enquiry Lost Reason'], ['Text', 'Enquiry Lost Reason'],
['HTML', 'Response', '<div class = "comment" id="update_enquiry_dialog_response"></div>'], ['HTML', 'Response', '<div class = "comment" id="update_enquiry_dialog_response"></div>'],
['HTML', 'Add Reason', '<div></div>'] ['HTML', 'Add Reason', '<div></div>']
]); ]);
var add_reason_btn1 = $a($i(e_lost_dialog.widgets['Add Reason']), 'button', 'button'); var add_reason_btn1 = $a($i(e_lost_dialog.widgets['Add Reason']), 'button', 'button');
add_reason_btn1.innerHTML = 'Add'; add_reason_btn1.innerHTML = 'Add';
add_reason_btn1.onclick = function(){ e_lost_dialog.add(); } add_reason_btn1.onclick = function(){ e_lost_dialog.add(); }
var add_reason_btn2 = $a($i(e_lost_dialog.widgets['Add Reason']), 'button', 'button'); var add_reason_btn2 = $a($i(e_lost_dialog.widgets['Add Reason']), 'button', 'button');
add_reason_btn2.innerHTML = 'Cancel'; add_reason_btn2.innerHTML = 'Cancel';
$y(add_reason_btn2,{marginLeft:'4px'}); $y(add_reason_btn2,{marginLeft:'4px'});
add_reason_btn2.onclick = function(){ e_lost_dialog.hide();} add_reason_btn2.onclick = function(){ e_lost_dialog.hide();}
e_lost_dialog.onshow = function() { e_lost_dialog.onshow = function() {
e_lost_dialog.widgets['Enquiry Lost Reason'].value = ''; e_lost_dialog.widgets['Enquiry Lost Reason'].value = '';
$i('update_enquiry_dialog_response').innerHTML = ''; $i('update_enquiry_dialog_response').innerHTML = '';
} }
e_lost_dialog.add = function() { e_lost_dialog.add = function() {
// sending... // sending...
$i('update_enquiry_dialog_response').innerHTML = 'Processing...'; $i('update_enquiry_dialog_response').innerHTML = 'Processing...';
var arg = strip(e_lost_dialog.widgets['Enquiry Lost Reason'].value); var arg = strip(e_lost_dialog.widgets['Enquiry Lost Reason'].value);
var call_back = function(r,rt) { var call_back = function(r,rt) {
if(r.message == 'true'){ if(r.message == 'true'){
$i('update_enquiry_dialog_response').innerHTML = 'Done'; $i('update_enquiry_dialog_response').innerHTML = 'Done';
e_lost_dialog.hide(); e_lost_dialog.hide();
} }
} }
if(arg) { if(arg) {
$c_obj(make_doclist(cur_frm.doc.doctype, cur_frm.doc.name),'declare_enquiry_lost',arg,call_back); $c_obj(make_doclist(cur_frm.doc.doctype, cur_frm.doc.name),'declare_enquiry_lost',arg,call_back);
} }
else{ else{
msgprint("Please add enquiry lost reason"); msgprint("Please add enquiry lost reason");
} }
} }
} }
if(!e_lost_dialog){ if(!e_lost_dialog){
set_e_lost_dialog(); set_e_lost_dialog();
} }
e_lost_dialog.show(); e_lost_dialog.show();
} }
//get query select Territory //get query select Territory
//======================================================================================================================= //=======================================================================================================================
cur_frm.fields_dict['territory'].get_query = function(doc,cdt,cdn) { cur_frm.fields_dict['territory'].get_query = function(doc,cdt,cdn) {
return 'SELECT `tabTerritory`.`name`,`tabTerritory`.`parent_territory` FROM `tabTerritory` WHERE `tabTerritory`.`is_group` = "No" AND `tabTerritory`.`docstatus`!= 2 AND `tabTerritory`.%(key)s LIKE "%s" ORDER BY `tabTerritory`.`name` ASC LIMIT 50';} return 'SELECT `tabTerritory`.`name`,`tabTerritory`.`parent_territory` FROM `tabTerritory` WHERE `tabTerritory`.`is_group` = "No" AND `tabTerritory`.`docstatus`!= 2 AND `tabTerritory`.%(key)s LIKE "%s" ORDER BY `tabTerritory`.`name` ASC LIMIT 50';}
/* /*
//===================== Enquiry From validation - either customer or lead is mandatory ===================================== //===================== Enquiry From validation - either customer or lead is mandatory =====================================
cur_frm.cscript.enq_frm_validate = function(doc,cdt,cdn){ cur_frm.cscript.enq_frm_validate = function(doc,cdt,cdn){
if(doc.enquiry_from == 'Lead'){ if(doc.enquiry_from == 'Lead'){
if(!doc.lead){ if(!doc.lead){
alert("Lead is mandatory."); alert("Lead is mandatory.");
validated = false; validated = false;
} }
} }
else if(doc.enquiry_from == 'Customer'){ else if(doc.enquiry_from == 'Customer'){
if(!doc.customer){ if(!doc.customer){
alert("Customer is mandatory."); alert("Customer is mandatory.");
validated = false; validated = false;
} }
else if(!doc.contact_person){ else if(!doc.contact_person){
alert("Contact Person is mandatory."); alert("Contact Person is mandatory.");
validated = false; validated = false;
} }
else if(!doc.customer_group){ else if(!doc.customer_group){
alert("Customer Group is mandatory."); alert("Customer Group is mandatory.");
validated = false; validated = false;
} }
} }
} }
*/ */
//===================validation function ============================================================================== //===================validation function ==============================================================================
cur_frm.cscript.validate = function(doc,cdt,cdn){ cur_frm.cscript.validate = function(doc,cdt,cdn){
//cur_frm.cscript.enq_frm_validate(doc,cdt,cdn); //cur_frm.cscript.enq_frm_validate(doc,cdt,cdn);
} }

View File

@ -12,53 +12,57 @@ $import(SMS Control)
// ONLOAD // ONLOAD
// =================================================================================== // ===================================================================================
cur_frm.cscript.onload = function(doc, cdt, cdn) { cur_frm.cscript.onload = function(doc, cdt, cdn) {
if(!doc.quotation_to) hide_field(['customer','customer_address','contact_person','customer_name','lead', 'lead_name', 'address_display', 'contact_display', 'contact_mobile', 'contact_email', 'territory', 'customer_group']); if(!doc.quotation_to) hide_field(['customer','customer_address','contact_person','customer_name','lead', 'lead_name', 'address_display', 'contact_display', 'contact_mobile', 'contact_email', 'territory', 'customer_group']);
if(!doc.price_list_name) set_multiple(cdt,cdn,{price_list_name:sys_defaults.price_list_name}); if(!doc.price_list_name) set_multiple(cdt,cdn,{price_list_name:sys_defaults.price_list_name});
if(!doc.status) set_multiple(cdt,cdn,{status:'Draft'}); if(!doc.status) set_multiple(cdt,cdn,{status:'Draft'});
if(!doc.transaction_date) set_multiple(cdt,cdn,{transaction_date:get_today()}); if(!doc.transaction_date) set_multiple(cdt,cdn,{transaction_date:get_today()});
if(!doc.conversion_rate) set_multiple(cdt,cdn,{conversion_rate:'1.00'}); if(!doc.conversion_rate) set_multiple(cdt,cdn,{conversion_rate:'1.00'});
if(!doc.currency && sys_defaults.currency) set_multiple(cdt,cdn,{currency:sys_defaults.currency}); if(!doc.currency && sys_defaults.currency) set_multiple(cdt,cdn,{currency:sys_defaults.currency});
if(!doc.price_list_currency) set_multiple(cdt, cdn, {price_list_currency: doc.currency, plc_conversion_rate: 1}); if(!doc.price_list_currency) set_multiple(cdt, cdn, {price_list_currency: doc.currency, plc_conversion_rate: 1});
if(!doc.company && sys_defaults.company) set_multiple(cdt,cdn,{company:sys_defaults.company}); if(!doc.company && sys_defaults.company) set_multiple(cdt,cdn,{company:sys_defaults.company});
if(!doc.fiscal_year && sys_defaults.fiscal_year) set_multiple(cdt,cdn,{fiscal_year:sys_defaults.fiscal_year}); if(!doc.fiscal_year && sys_defaults.fiscal_year) set_multiple(cdt,cdn,{fiscal_year:sys_defaults.fiscal_year});
if(doc.quotation_to) {
if(doc.quotation_to == 'Customer') {
hide_field(['lead', 'lead_name']);
}
else if (doc.quotation_to == 'Lead') {
hide_field(['customer','customer_address','contact_person', 'customer_name','contact_display', 'customer_group']);
}
}
// defined in sales_common.js
cur_frm.cscript.update_item_details(doc, cdt, cdn);
if(doc.quotation_to) {
if(doc.quotation_to == 'Customer') {
hide_field(['lead', 'lead_name']);
}
else if (doc.quotation_to == 'Lead') {
hide_field(['customer','customer_address','contact_person', 'customer_name','contact_display', 'customer_group']);
}
}
} }
cur_frm.cscript.onload_post_render = function(doc, dt, dn) { cur_frm.cscript.onload_post_render = function(doc, dt, dn) {
// load default charges // load default charges
if(doc.__islocal && !getchildren('RV Tax Detail', doc.name, 'other_charges', doc.doctype).length) if(doc.__islocal && !getchildren('RV Tax Detail', doc.name, 'other_charges', doc.doctype).length)
cur_frm.cscript.load_taxes(doc, cdt, cdn); cur_frm.cscript.load_taxes(doc, cdt, cdn);
} }
// hide - unhide fields based on lead or customer.. // hide - unhide fields based on lead or customer..
// ======================================================================================================================= // =======================================================================================================================
cur_frm.cscript.lead_cust_show = function(doc,cdt,cdn){ cur_frm.cscript.lead_cust_show = function(doc,cdt,cdn){
if(doc.quotation_to == 'Lead'){ if(doc.quotation_to == 'Lead'){
unhide_field(['lead']); unhide_field(['lead']);
hide_field(['lead_name','customer','customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']); hide_field(['lead_name','customer','customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']);
doc.lead = doc.lead_name = doc.customer = doc.customer_address = doc.contact_person = doc.address_display = doc.contact_display = doc.contact_mobile = doc.contact_email = doc.territory = doc.customer_group = ""; doc.lead = doc.lead_name = doc.customer = doc.customer_address = doc.contact_person = doc.address_display = doc.contact_display = doc.contact_mobile = doc.contact_email = doc.territory = doc.customer_group = "";
} }
else if(doc.quotation_to == 'Customer'){ else if(doc.quotation_to == 'Customer'){
unhide_field(['customer']); unhide_field(['customer']);
hide_field(['lead','lead_name','address_display','contact_display','contact_mobile','contact_email','territory']); hide_field(['lead','lead_name','address_display','contact_display','contact_mobile','contact_email','territory']);
doc.lead = doc.lead_name = doc.customer = doc.customer_address = doc.contact_person = doc.address_display = doc.contact_display = doc.contact_mobile = doc.contact_email = doc.territory = doc.customer_group = ""; doc.lead = doc.lead_name = doc.customer = doc.customer_address = doc.contact_person = doc.address_display = doc.contact_display = doc.contact_mobile = doc.contact_email = doc.territory = doc.customer_group = "";
} }
} }
//================ hide - unhide fields on basis of quotation to either lead or customer =============================== //================ hide - unhide fields on basis of quotation to either lead or customer ===============================
cur_frm.cscript.quotation_to = function(doc,cdt,cdn){ cur_frm.cscript.quotation_to = function(doc,cdt,cdn){
cur_frm.cscript.lead_cust_show(doc,cdt,cdn); cur_frm.cscript.lead_cust_show(doc,cdt,cdn);
} }
@ -66,111 +70,111 @@ cur_frm.cscript.quotation_to = function(doc,cdt,cdn){
// =================================================================================== // ===================================================================================
cur_frm.cscript.refresh = function(doc, cdt, cdn) { cur_frm.cscript.refresh = function(doc, cdt, cdn) {
cur_frm.clear_custom_buttons(); cur_frm.clear_custom_buttons();
if(doc.docstatus == 1 && doc.status!='Order Lost') { if(doc.docstatus == 1 && doc.status!='Order Lost') {
cur_frm.add_custom_button('Make Sales Order', cur_frm.cscript['Make Sales Order']); cur_frm.add_custom_button('Make Sales Order', cur_frm.cscript['Make Sales Order']);
cur_frm.add_custom_button('Set as Lost', cur_frm.cscript['Declare Order Lost']); cur_frm.add_custom_button('Set as Lost', cur_frm.cscript['Declare Order Lost']);
cur_frm.add_custom_button('Send SMS', cur_frm.cscript['Send SMS']); cur_frm.add_custom_button('Send SMS', cur_frm.cscript['Send SMS']);
} }
if (!doc.docstatus) hide_field(['Update Follow up']); if (!doc.docstatus) hide_field(['Update Follow up']);
else unhide_field(['Update Follow up']); else unhide_field(['Update Follow up']);
} }
//customer //customer
cur_frm.cscript.customer = function(doc,dt,dn) { cur_frm.cscript.customer = function(doc,dt,dn) {
var callback = function(r,rt) { var callback = function(r,rt) {
var doc = locals[cur_frm.doctype][cur_frm.docname]; var doc = locals[cur_frm.doctype][cur_frm.docname];
cur_frm.refresh(); cur_frm.refresh();
} }
if(doc.customer) $c_obj(make_doclist(doc.doctype, doc.name), 'get_default_customer_address', '', callback); if(doc.customer) $c_obj(make_doclist(doc.doctype, doc.name), 'get_default_customer_address', '', callback);
if(doc.customer) unhide_field(['customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']); if(doc.customer) unhide_field(['customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']);
} }
cur_frm.cscript.customer_address = cur_frm.cscript.contact_person = function(doc,dt,dn) { cur_frm.cscript.customer_address = cur_frm.cscript.contact_person = function(doc,dt,dn) {
if(doc.customer) get_server_fields('get_customer_address', JSON.stringify({customer: doc.customer, address: doc.customer_address, contact: doc.contact_person}),'', doc, dt, dn, 1); if(doc.customer) get_server_fields('get_customer_address', JSON.stringify({customer: doc.customer, address: doc.customer_address, contact: doc.contact_person}),'', doc, dt, dn, 1);
} }
cur_frm.fields_dict.customer_address.on_new = function(dn) { cur_frm.fields_dict.customer_address.on_new = function(dn) {
locals['Address'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer; locals['Address'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
locals['Address'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name; locals['Address'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
} }
cur_frm.fields_dict.contact_person.on_new = function(dn) { cur_frm.fields_dict.contact_person.on_new = function(dn) {
locals['Contact'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer; locals['Contact'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
locals['Contact'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name; locals['Contact'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
} }
cur_frm.fields_dict['customer_address'].get_query = function(doc, cdt, cdn) { cur_frm.fields_dict['customer_address'].get_query = function(doc, cdt, cdn) {
return 'SELECT name,address_line1,city FROM tabAddress WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50'; return 'SELECT name,address_line1,city FROM tabAddress WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
} }
cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) { cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50'; return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
} }
//lead //lead
cur_frm.fields_dict['lead'].get_query = function(doc,cdt,cdn){ cur_frm.fields_dict['lead'].get_query = function(doc,cdt,cdn){
return 'SELECT `tabLead`.name, `tabLead`.lead_name FROM `tabLead` WHERE `tabLead`.%(key)s LIKE "%s" ORDER BY `tabLead`.`name` ASC LIMIT 50'; return 'SELECT `tabLead`.name, `tabLead`.lead_name FROM `tabLead` WHERE `tabLead`.%(key)s LIKE "%s" ORDER BY `tabLead`.`name` ASC LIMIT 50';
} }
cur_frm.cscript.lead = function(doc, cdt, cdn) { cur_frm.cscript.lead = function(doc, cdt, cdn) {
if(doc.lead) get_server_fields('get_lead_details', doc.lead,'', doc, cdt, cdn, 1); if(doc.lead) get_server_fields('get_lead_details', doc.lead,'', doc, cdt, cdn, 1);
if(doc.lead) unhide_field(['lead_name','address_display','contact_mobile','contact_email','territory']); if(doc.lead) unhide_field(['lead_name','address_display','contact_mobile','contact_email','territory']);
} }
// ===================================================================================== // =====================================================================================
cur_frm.fields_dict['enq_no'].get_query = function(doc,cdt,cdn){ cur_frm.fields_dict['enq_no'].get_query = function(doc,cdt,cdn){
var cond=''; var cond='';
var cond1=''; var cond1='';
if(doc.order_type) cond = 'ifnull(`tabEnquiry`.enquiry_type, "") = "'+doc.order_type+'" AND'; if(doc.order_type) cond = 'ifnull(`tabEnquiry`.enquiry_type, "") = "'+doc.order_type+'" AND';
if(doc.customer) cond1 = '`tabEnquiry`.customer = "'+doc.customer+'" AND'; if(doc.customer) cond1 = '`tabEnquiry`.customer = "'+doc.customer+'" AND';
else if(doc.lead) cond1 = '`tabEnquiry`.lead = "'+doc.lead+'" AND'; else if(doc.lead) cond1 = '`tabEnquiry`.lead = "'+doc.lead+'" AND';
return repl('SELECT `tabEnquiry`.`name` FROM `tabEnquiry` WHERE `tabEnquiry`.`docstatus` = 1 AND `tabEnquiry`.status = "Submitted" AND %(cond)s %(cond1)s `tabEnquiry`.`name` LIKE "%s" ORDER BY `tabEnquiry`.`name` ASC LIMIT 50', {cond:cond, cond1:cond1}); return repl('SELECT `tabEnquiry`.`name` FROM `tabEnquiry` WHERE `tabEnquiry`.`docstatus` = 1 AND `tabEnquiry`.status = "Submitted" AND %(cond)s %(cond1)s `tabEnquiry`.`name` LIKE "%s" ORDER BY `tabEnquiry`.`name` ASC LIMIT 50', {cond:cond, cond1:cond1});
} }
// Make Sales Order // Make Sales Order
// ===================================================================================== // =====================================================================================
cur_frm.cscript['Make Sales Order'] = function() { cur_frm.cscript['Make Sales Order'] = function() {
var doc = cur_frm.doc; var doc = cur_frm.doc;
if (doc.docstatus == 1) { if (doc.docstatus == 1) {
var n = createLocal("Sales Order"); var n = createLocal("Sales Order");
$c('dt_map', args={ $c('dt_map', args={
'docs':compress_doclist([locals["Sales Order"][n]]), 'docs':compress_doclist([locals["Sales Order"][n]]),
'from_doctype':'Quotation', 'from_doctype':'Quotation',
'to_doctype':'Sales Order', 'to_doctype':'Sales Order',
'from_docname':doc.name, 'from_docname':doc.name,
'from_to_list':"[['Quotation', 'Sales Order'], ['Quotation Detail', 'Sales Order Detail'],['RV Tax Detail','RV Tax Detail'], ['Sales Team', 'Sales Team'], ['TC Detail', 'TC Detail']]" 'from_to_list':"[['Quotation', 'Sales Order'], ['Quotation Detail', 'Sales Order Detail'],['RV Tax Detail','RV Tax Detail'], ['Sales Team', 'Sales Team'], ['TC Detail', 'TC Detail']]"
}, function(r,rt) { }, function(r,rt) {
loaddoc("Sales Order", n); loaddoc("Sales Order", n);
}); });
} }
} }
//pull enquiry details //pull enquiry details
cur_frm.cscript['Pull Enquiry Detail'] = function(doc,cdt,cdn){ cur_frm.cscript['Pull Enquiry Detail'] = function(doc,cdt,cdn){
var callback = function(r,rt){ var callback = function(r,rt){
if(r.message){ if(r.message){
doc.quotation_to = r.message; doc.quotation_to = r.message;
if(doc.quotation_to == 'Lead') { if(doc.quotation_to == 'Lead') {
unhide_field(['lead','lead_name','address_display','contact_mobile','contact_email','territory']); unhide_field(['lead','lead_name','address_display','contact_mobile','contact_email','territory']);
} }
else if(doc.quotation_to == 'Customer') { else if(doc.quotation_to == 'Customer') {
unhide_field(['customer','customer_address','contact_person','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']); unhide_field(['customer','customer_address','contact_person','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']);
} }
refresh_many(['quotation_details','quotation_to','customer','customer_address','contact_person','lead','lead_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group','order_type']); refresh_many(['quotation_details','quotation_to','customer','customer_address','contact_person','lead','lead_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group','order_type']);
} }
} }
$c_obj(make_doclist(doc.doctype, doc.name),'pull_enq_details','',callback); $c_obj(make_doclist(doc.doctype, doc.name),'pull_enq_details','',callback);
} }
@ -178,70 +182,70 @@ cur_frm.cscript['Pull Enquiry Detail'] = function(doc,cdt,cdn){
//================================================================================= //=================================================================================
cur_frm.cscript['Update Follow up'] = function(doc){ cur_frm.cscript['Update Follow up'] = function(doc){
$c_obj(make_doclist(doc.doctype, doc.name),'update_followup_details','',function(r, rt){ $c_obj(make_doclist(doc.doctype, doc.name),'update_followup_details','',function(r, rt){
refresh_field('follow_up'); refresh_field('follow_up');
doc.__unsaved = 0; doc.__unsaved = 0;
cur_frm.refresh_header(); cur_frm.refresh_header();
}); });
} }
// declare order lost // declare order lost
//------------------------- //-------------------------
cur_frm.cscript['Declare Order Lost'] = function(){ cur_frm.cscript['Declare Order Lost'] = function(){
var qtn_lost_dialog; var qtn_lost_dialog;
set_qtn_lost_dialog = function(doc,cdt,cdn){ set_qtn_lost_dialog = function(doc,cdt,cdn){
qtn_lost_dialog = new Dialog(400,400,'Add Quotation Lost Reason'); qtn_lost_dialog = new Dialog(400,400,'Add Quotation Lost Reason');
qtn_lost_dialog.make_body([ qtn_lost_dialog.make_body([
['HTML', 'Message', '<div class="comment">Please add quotation lost reason</div>'], ['HTML', 'Message', '<div class="comment">Please add quotation lost reason</div>'],
['Text', 'Quotation Lost Reason'], ['Text', 'Quotation Lost Reason'],
['HTML', 'Response', '<div class = "comment" id="update_quotation_dialog_response"></div>'], ['HTML', 'Response', '<div class = "comment" id="update_quotation_dialog_response"></div>'],
['HTML', 'Add Reason', '<div></div>'] ['HTML', 'Add Reason', '<div></div>']
]); ]);
var add_reason_btn1 = $a($i(qtn_lost_dialog.widgets['Add Reason']), 'button', 'button'); var add_reason_btn1 = $a($i(qtn_lost_dialog.widgets['Add Reason']), 'button', 'button');
add_reason_btn1.innerHTML = 'Add'; add_reason_btn1.innerHTML = 'Add';
add_reason_btn1.onclick = function(){ qtn_lost_dialog.add(); } add_reason_btn1.onclick = function(){ qtn_lost_dialog.add(); }
var add_reason_btn2 = $a($i(qtn_lost_dialog.widgets['Add Reason']), 'button', 'button'); var add_reason_btn2 = $a($i(qtn_lost_dialog.widgets['Add Reason']), 'button', 'button');
add_reason_btn2.innerHTML = 'Cancel'; add_reason_btn2.innerHTML = 'Cancel';
$y(add_reason_btn2,{marginLeft:'4px'}); $y(add_reason_btn2,{marginLeft:'4px'});
add_reason_btn2.onclick = function(){ qtn_lost_dialog.hide();} add_reason_btn2.onclick = function(){ qtn_lost_dialog.hide();}
qtn_lost_dialog.onshow = function() { qtn_lost_dialog.onshow = function() {
qtn_lost_dialog.widgets['Quotation Lost Reason'].value = ''; qtn_lost_dialog.widgets['Quotation Lost Reason'].value = '';
$i('update_quotation_dialog_response').innerHTML = ''; $i('update_quotation_dialog_response').innerHTML = '';
} }
qtn_lost_dialog.add = function() { qtn_lost_dialog.add = function() {
// sending... // sending...
$i('update_quotation_dialog_response').innerHTML = 'Processing...'; $i('update_quotation_dialog_response').innerHTML = 'Processing...';
var arg = strip(qtn_lost_dialog.widgets['Quotation Lost Reason'].value); var arg = strip(qtn_lost_dialog.widgets['Quotation Lost Reason'].value);
var call_back = function(r,rt) { var call_back = function(r,rt) {
if(r.message == 'true'){ if(r.message == 'true'){
$i('update_quotation_dialog_response').innerHTML = 'Done'; $i('update_quotation_dialog_response').innerHTML = 'Done';
qtn_lost_dialog.hide(); qtn_lost_dialog.hide();
} }
} }
if(arg) $c_obj(make_doclist(cur_frm.doc.doctype, cur_frm.doc.name),'declare_order_lost',arg,call_back); if(arg) $c_obj(make_doclist(cur_frm.doc.doctype, cur_frm.doc.name),'declare_order_lost',arg,call_back);
else msgprint("Please add Quotation lost reason"); else msgprint("Please add Quotation lost reason");
} }
} }
if(!qtn_lost_dialog){ if(!qtn_lost_dialog){
set_qtn_lost_dialog(doc,cdt,cdn); set_qtn_lost_dialog(doc,cdt,cdn);
} }
qtn_lost_dialog.show(); qtn_lost_dialog.show();
} }
// GET REPORT // GET REPORT
// ======================================================================================== // ========================================================================================
cur_frm.cscript['Get Report'] = function(doc,cdt,cdn) { cur_frm.cscript['Get Report'] = function(doc,cdt,cdn) {
var callback = function(report){ var callback = function(report){
report.set_filter('Sales Order Detail', 'Quotation No.',doc.name) report.set_filter('Sales Order Detail', 'Quotation No.',doc.name)
report.dt.run(); report.dt.run();
} }
loadreport('Sales Order Detail','Itemwise Sales Details', callback); loadreport('Sales Order Detail','Itemwise Sales Details', callback);
} }
@ -250,33 +254,34 @@ cur_frm.cscript['Get Report'] = function(doc,cdt,cdn) {
//===================== Quotation to validation - either customer or lead mandatory ==================== //===================== Quotation to validation - either customer or lead mandatory ====================
cur_frm.cscript.quot_to_validate = function(doc,cdt,cdn){ cur_frm.cscript.quot_to_validate = function(doc,cdt,cdn){
if(doc.quotation_to == 'Lead'){ if(doc.quotation_to == 'Lead'){
if(!doc.lead){ if(!doc.lead){
alert("Lead is mandatory."); alert("Lead is mandatory.");
validated = false; validated = false;
} }
} }
else if(doc.quotation_to == 'Customer'){ else if(doc.quotation_to == 'Customer'){
if(!doc.customer){ if(!doc.customer){
alert("Customer is mandatory."); alert("Customer is mandatory.");
validated = false; validated = false;
} }
} }
} }
//===================validation function ================================= //===================validation function =================================
cur_frm.cscript.validate = function(doc,cdt,cdn){ cur_frm.cscript.validate = function(doc,cdt,cdn){
cur_frm.cscript.quot_to_validate(doc,cdt,cdn); cur_frm.cscript['Re-Calculate Values'](doc, cdt, cdn);
cur_frm.cscript.quot_to_validate(doc,cdt,cdn);
} }
//================ Last Quoted Price and Last Sold Price suggestion ====================== //================ Last Quoted Price and Last Sold Price suggestion ======================
cur_frm.fields_dict['quotation_details'].grid.get_field('item_code').get_query= function(doc, cdt, cdn) { cur_frm.fields_dict['quotation_details'].grid.get_field('item_code').get_query= function(doc, cdt, cdn) {
var d = locals[cdt][cdn]; var d = locals[cdt][cdn];
var cond = (doc.order_type == 'Maintenance')? " and tabItem.is_service_item = 'Yes'" : " and tabItem.is_sales_item = 'Yes'" var cond = (doc.order_type == 'Maintenance')? " and tabItem.is_service_item = 'Yes'" : " and tabItem.is_sales_item = 'Yes'"
if(doc.customer) if(doc.customer)
return repl("SELECT i.name,i.item_code,concat('Last quoted at - ',cast(quote_rate as char)) as quote_rate,concat('Last sold at - ',cast(sales_rate as char)) as sales_rate, i.item_name, i.description FROM\ return repl("SELECT i.name,i.item_code,concat('Last quoted at - ',cast(quote_rate as char)) as quote_rate,concat('Last sold at - ',cast(sales_rate as char)) as sales_rate, i.item_name, i.description FROM\
(\ (\
select item_code,name, item_name, description from tabItem where tabItem.%(key)s like '%s' %(cond)s\ select item_code,name, item_name, description from tabItem where tabItem.%(key)s like '%s' %(cond)s\
)i\ )i\
@ -300,8 +305,8 @@ cur_frm.fields_dict['quotation_details'].grid.get_field('item_code').get_query=
select rd.item_code,max(voucher_date) as voucher_date from `tabRV Detail` rd, `tabReceivable Voucher` r where r.name=rd.parent and r.docstatus=1 and customer='%(cust)s' group by rd.item_code\ select rd.item_code,max(voucher_date) as voucher_date from `tabRV Detail` rd, `tabReceivable Voucher` r where r.name=rd.parent and r.docstatus=1 and customer='%(cust)s' group by rd.item_code\
)m where r.item_code=m.item_code and r.voucher_date=m.voucher_date\ )m where r.item_code=m.item_code and r.voucher_date=m.voucher_date\
)s on i.item_code=s.item_code ORDER BY item_code LIMIT 50",{cust:doc.customer, cond:cond}); )s on i.item_code=s.item_code ORDER BY item_code LIMIT 50",{cust:doc.customer, cond:cond});
else else
return repl("SELECT name, item_name, description FROM tabItem WHERE `tabItem`.%(key)s LIKE '%s' %(cond)s ORDER BY tabItem.item_code DESC LIMIT 50", {cond:cond}); return repl("SELECT name, item_name, description FROM tabItem WHERE `tabItem`.%(key)s LIKE '%s' %(cond)s ORDER BY tabItem.item_code DESC LIMIT 50", {cond:cond});
} }
$import(Notification Control) $import(Notification Control)

View File

@ -19,324 +19,334 @@ convert_to_lists = webnotes.conn.convert_to_lists
from utilities.transaction_base import TransactionBase from utilities.transaction_base import TransactionBase
class DocType(TransactionBase): class DocType(TransactionBase):
def __init__(self, doc, doclist=[]): def __init__(self, doc, doclist=[]):
self.doc = doc self.doc = doc
self.doclist = doclist self.doclist = doclist
self.tname = 'Quotation Detail' self.tname = 'Quotation Detail'
self.fname = 'quotation_details' self.fname = 'quotation_details'
# Autoname # Autoname
# --------- # ---------
def autoname(self): def autoname(self):
self.doc.name = make_autoname(self.doc.naming_series+'.#####') self.doc.name = make_autoname(self.doc.naming_series+'.#####')
# DOCTYPE TRIGGER FUNCTIONS # DOCTYPE TRIGGER FUNCTIONS
# ============================================================================== # ==============================================================================
# Pull Enquiry Details # Pull Enquiry Details
# -------------------- # --------------------
def pull_enq_details(self): def pull_enq_details(self):
self.doc.clear_table(self.doclist, 'quotation_details') self.doc.clear_table(self.doclist, 'quotation_details')
get_obj('DocType Mapper', 'Enquiry-Quotation').dt_map('Enquiry', 'Quotation', self.doc.enq_no, self.doc, self.doclist, "[['Enquiry', 'Quotation'],['Enquiry Detail', 'Quotation Detail']]") get_obj('DocType Mapper', 'Enquiry-Quotation').dt_map('Enquiry', 'Quotation', self.doc.enq_no, self.doc, self.doclist, "[['Enquiry', 'Quotation'],['Enquiry Detail', 'Quotation Detail']]")
self.get_adj_percent() self.get_adj_percent()
return self.doc.quotation_to return self.doc.quotation_to
# Get contact person details based on customer selected # Get contact person details based on customer selected
# ------------------------------------------------------ # ------------------------------------------------------
def get_contact_details(self): def get_contact_details(self):
return get_obj('Sales Common').get_contact_details(self,0) return get_obj('Sales Common').get_contact_details(self,0)
# Clear Quotation Details # Clear Quotation Details
# ----------------------- # -----------------------
def clear_quotation_details(self): def clear_quotation_details(self):
self.doc.clear_table(self.doclist, 'quotation_details') self.doc.clear_table(self.doclist, 'quotation_details')
# QUOTATION DETAILS TRIGGER FUNCTIONS # QUOTATION DETAILS TRIGGER FUNCTIONS
# ================================================================================ # ================================================================================
# Get Item Details # Get Item Details
# ----------------- # -----------------
def get_item_details(self, item_code): def get_item_details(self, item_code=None):
return get_obj('Sales Common').get_item_details(item_code, self) if item_code:
return get_obj('Sales Common').get_item_details(item_code, self)
# Re-calculates Basic Rate & amount based on Price List Selected else:
# -------------------------------------------------------------- obj = get_obj('Sales Common')
def get_adj_percent(self, arg=''): for doc in self.doclist:
get_obj('Sales Common').get_adj_percent(self) if doc.fields.get('item_code'):
ret = obj.get_item_details(doc.item_code, self)
for r in ret:
if not doc.fields.get(r):
doc.fields[r] = ret[r]
# Re-calculates Basic Rate & amount based on Price List Selected
# --------------------------------------------------------------
def get_adj_percent(self, arg=''):
get_obj('Sales Common').get_adj_percent(self)
# OTHER CHARGES TRIGGER FUNCTIONS # OTHER CHARGES TRIGGER FUNCTIONS
# ==================================================================================== # ====================================================================================
# Get Tax rate if account type is TAX # Get Tax rate if account type is TAX
# ----------------------------------- # -----------------------------------
def get_rate(self,arg): def get_rate(self,arg):
return get_obj('Sales Common').get_rate(arg) return get_obj('Sales Common').get_rate(arg)
# Load Default Charges # Load Default Charges
# ---------------------------------------------------------- # ----------------------------------------------------------
def load_default_taxes(self): def load_default_taxes(self):
return get_obj('Sales Common').load_default_taxes(self) return get_obj('Sales Common').load_default_taxes(self)
# Pull details from other charges master (Get Other Charges) # Pull details from other charges master (Get Other Charges)
# ---------------------------------------------------------- # ----------------------------------------------------------
def get_other_charges(self): def get_other_charges(self):
return get_obj('Sales Common').get_other_charges(self) return get_obj('Sales Common').get_other_charges(self)
# Get Lead Details along with its details # Get Lead Details along with its details
# ============================================================== # ==============================================================
def get_lead_details1(self, name): def get_lead_details1(self, name):
details = sql("select name, lead_name, address_line1, address_line2, city, country, state, pincode, territory, contact_no, mobile_no, email_id from `tabLead` where name = '%s'" %(name), as_dict = 1) details = sql("select name, lead_name, address_line1, address_line2, city, country, state, pincode, territory, contact_no, mobile_no, email_id from `tabLead` where name = '%s'" %(name), as_dict = 1)
ret = { ret = {
'lead_name' : details and details[0]['lead_name'] or '', 'lead_name' : details and details[0]['lead_name'] or '',
'address_display' : (details and details[0]['address_line1'] 'address_display' : (details and details[0]['address_line1']
+ (details[0]['address_line2'] and '\n' + details[0]['address_line2'] or '') + '\n' + (details[0]['address_line2'] and '\n' + details[0]['address_line2'] or '') + '\n'
+ details[0]['city'] + details[0]['city']
+ (details[0]['pincode'] and ', ' + details[0]['pincode'] or '') + '\n' + (details[0]['pincode'] and ', ' + details[0]['pincode'] or '') + '\n'
+ (details[0]['state'] and details[0]['state']+', ' or '') + (details[0]['state'] and details[0]['state']+', ' or '')
+ details[0]['country'] + '\nTel: ' + details[0]['contact_no'] + '\n' or '-'), + details[0]['country'] + '\nTel: ' + details[0]['contact_no'] + '\n' or '-'),
'territory' : details and details[0]['territory'] or '', 'territory' : details and details[0]['territory'] or '',
'contact_mobile' : details and details[0]['mobile_no'] or '-', 'contact_mobile' : details and details[0]['mobile_no'] or '-',
'contact_email' : details and details[0]['email_id'] or '-' 'contact_email' : details and details[0]['email_id'] or '-'
} }
return ret return ret
# GET TERMS AND CONDITIONS # GET TERMS AND CONDITIONS
# ==================================================================================== # ====================================================================================
def get_tc_details(self): def get_tc_details(self):
return get_obj('Sales Common').get_tc_details(self) return get_obj('Sales Common').get_tc_details(self)
# VALIDATE # VALIDATE
# ============================================================================================== # ==============================================================================================
# Amendment date is necessary if document is amended # Amendment date is necessary if document is amended
# -------------------------------------------------- # --------------------------------------------------
def validate_mandatory(self): def validate_mandatory(self):
if self.doc.amended_from and not self.doc.amendment_date: if self.doc.amended_from and not self.doc.amendment_date:
msgprint("Please Enter Amendment Date") msgprint("Please Enter Amendment Date")
raise Exception raise Exception
# Fiscal Year Validation # Fiscal Year Validation
# ---------------------- # ----------------------
def validate_fiscal_year(self): def validate_fiscal_year(self):
get_obj('Sales Common').validate_fiscal_year(self.doc.fiscal_year,self.doc.transaction_date,'Quotation Date') get_obj('Sales Common').validate_fiscal_year(self.doc.fiscal_year,self.doc.transaction_date,'Quotation Date')
# Does not allow same item code to be entered twice # Does not allow same item code to be entered twice
# ------------------------------------------------- # -------------------------------------------------
def validate_for_items(self): def validate_for_items(self):
chk_dupl_itm = [] chk_dupl_itm = []
for d in getlist(self.doclist,'quotation_details'): for d in getlist(self.doclist,'quotation_details'):
if [cstr(d.item_code),cstr(d.description)] in chk_dupl_itm: if [cstr(d.item_code),cstr(d.description)] in chk_dupl_itm:
msgprint("Item %s has been entered twice. Please change description atleast to continue" % d.item_code) msgprint("Item %s has been entered twice. Please change description atleast to continue" % d.item_code)
raise Exception raise Exception
else: else:
chk_dupl_itm.append([cstr(d.item_code),cstr(d.description)]) chk_dupl_itm.append([cstr(d.item_code),cstr(d.description)])
#do not allow sales item in maintenance quotation and service item in sales quotation #do not allow sales item in maintenance quotation and service item in sales quotation
#----------------------------------------------------------------------------------------------- #-----------------------------------------------------------------------------------------------
def validate_order_type(self): def validate_order_type(self):
if self.doc.order_type == 'Maintenance': if self.doc.order_type == 'Maintenance':
for d in getlist(self.doclist, 'quotation_details'): for d in getlist(self.doclist, 'quotation_details'):
is_service_item = sql("select is_service_item from `tabItem` where name=%s", d.item_code) is_service_item = sql("select is_service_item from `tabItem` where name=%s", d.item_code)
is_service_item = is_service_item and is_service_item[0][0] or 'No' is_service_item = is_service_item and is_service_item[0][0] or 'No'
if is_service_item == 'No': if is_service_item == 'No':
msgprint("You can not select non service item "+d.item_code+" in Maintenance Quotation") msgprint("You can not select non service item "+d.item_code+" in Maintenance Quotation")
raise Exception raise Exception
else: else:
for d in getlist(self.doclist, 'quotation_details'): for d in getlist(self.doclist, 'quotation_details'):
is_sales_item = sql("select is_sales_item from `tabItem` where name=%s", d.item_code) is_sales_item = sql("select is_sales_item from `tabItem` where name=%s", d.item_code)
is_sales_item = is_sales_item and is_sales_item[0][0] or 'No' is_sales_item = is_sales_item and is_sales_item[0][0] or 'No'
if is_sales_item == 'No': if is_sales_item == 'No':
msgprint("You can not select non sales item "+d.item_code+" in Sales Quotation") msgprint("You can not select non sales item "+d.item_code+" in Sales Quotation")
raise Exception raise Exception
#--------------Validation For Last Contact Date----------------- #--------------Validation For Last Contact Date-----------------
# ==================================================================================================================== # ====================================================================================================================
def set_last_contact_date(self): def set_last_contact_date(self):
#if not self.doc.contact_date_ref: #if not self.doc.contact_date_ref:
#self.doc.contact_date_ref=self.doc.contact_date #self.doc.contact_date_ref=self.doc.contact_date
#self.doc.last_contact_date=self.doc.contact_date_ref #self.doc.last_contact_date=self.doc.contact_date_ref
if self.doc.contact_date_ref and self.doc.contact_date_ref != self.doc.contact_date: if self.doc.contact_date_ref and self.doc.contact_date_ref != self.doc.contact_date:
if getdate(self.doc.contact_date_ref) < getdate(self.doc.contact_date): if getdate(self.doc.contact_date_ref) < getdate(self.doc.contact_date):
self.doc.last_contact_date=self.doc.contact_date_ref self.doc.last_contact_date=self.doc.contact_date_ref
else: else:
msgprint("Contact Date Cannot be before Last Contact Date") msgprint("Contact Date Cannot be before Last Contact Date")
raise Exception raise Exception
#set(self.doc, 'contact_date_ref',self.doc.contact_date) #set(self.doc, 'contact_date_ref',self.doc.contact_date)
# Validate # Validate
# -------- # --------
def validate(self): def validate(self):
self.validate_fiscal_year() self.validate_fiscal_year()
self.validate_mandatory() self.validate_mandatory()
self.set_last_contact_date() self.set_last_contact_date()
self.validate_order_type() self.validate_order_type()
self.validate_for_items() self.validate_for_items()
sales_com_obj = get_obj('Sales Common') sales_com_obj = get_obj('Sales Common')
sales_com_obj.check_active_sales_items(self) sales_com_obj.check_active_sales_items(self)
sales_com_obj.validate_max_discount(self,'quotation_details') #verify whether rate is not greater than max_discount sales_com_obj.validate_max_discount(self,'quotation_details') #verify whether rate is not greater than max_discount
sales_com_obj.check_conversion_rate(self) sales_com_obj.check_conversion_rate(self)
# Get total in words # Get total in words
dcc = TransactionBase().get_company_currency(self.doc.company) dcc = TransactionBase().get_company_currency(self.doc.company)
self.doc.in_words = sales_com_obj.get_total_in_words(dcc, self.doc.rounded_total) self.doc.in_words = sales_com_obj.get_total_in_words(dcc, self.doc.rounded_total)
self.doc.in_words_export = sales_com_obj.get_total_in_words(self.doc.currency, self.doc.rounded_total_export) self.doc.in_words_export = sales_com_obj.get_total_in_words(self.doc.currency, self.doc.rounded_total_export)
def on_update(self): def on_update(self):
# Add to calendar # Add to calendar
#if self.doc.contact_date and self.doc.last_contact_date != self.doc.contact_date: #if self.doc.contact_date and self.doc.last_contact_date != self.doc.contact_date:
if self.doc.contact_date and self.doc.contact_date_ref != self.doc.contact_date: if self.doc.contact_date and self.doc.contact_date_ref != self.doc.contact_date:
if self.doc.contact_by: if self.doc.contact_by:
self.add_calendar_event() self.add_calendar_event()
set(self.doc, 'contact_date_ref',self.doc.contact_date) set(self.doc, 'contact_date_ref',self.doc.contact_date)
# Set Quotation Status # Set Quotation Status
set(self.doc, 'status', 'Draft') set(self.doc, 'status', 'Draft')
# subject for follow # subject for follow
self.doc.subject = '[%(status)s] To %(customer)s worth %(currency)s %(grand_total)s' % self.doc.fields self.doc.subject = '[%(status)s] To %(customer)s worth %(currency)s %(grand_total)s' % self.doc.fields
# Add to Calendar # Add to Calendar
# ==================================================================================================================== # ====================================================================================================================
def add_calendar_event(self): def add_calendar_event(self):
desc='' desc=''
user_lst =[] user_lst =[]
if self.doc.customer: if self.doc.customer:
if self.doc.contact_person: if self.doc.contact_person:
desc = 'Contact '+cstr(self.doc.contact_person) desc = 'Contact '+cstr(self.doc.contact_person)
else: else:
desc = 'Contact customer '+cstr(self.doc.customer) desc = 'Contact customer '+cstr(self.doc.customer)
elif self.doc.lead: elif self.doc.lead:
if self.doc.lead_name: if self.doc.lead_name:
desc = 'Contact '+cstr(self.doc.lead_name) desc = 'Contact '+cstr(self.doc.lead_name)
else: else:
desc = 'Contact lead '+cstr(self.doc.lead) desc = 'Contact lead '+cstr(self.doc.lead)
desc = desc+ '.By : ' + cstr(self.doc.contact_by) desc = desc+ '.By : ' + cstr(self.doc.contact_by)
if self.doc.to_discuss: if self.doc.to_discuss:
desc = desc+' To Discuss : ' + cstr(self.doc.to_discuss) desc = desc+' To Discuss : ' + cstr(self.doc.to_discuss)
ev = Document('Event') ev = Document('Event')
ev.description = desc ev.description = desc
ev.event_date = self.doc.contact_date ev.event_date = self.doc.contact_date
ev.event_hour = '10:00' ev.event_hour = '10:00'
ev.event_type = 'Private' ev.event_type = 'Private'
ev.ref_type = 'Enquiry' ev.ref_type = 'Enquiry'
ev.ref_name = self.doc.name ev.ref_name = self.doc.name
ev.save(1) ev.save(1)
user_lst.append(self.doc.owner) user_lst.append(self.doc.owner)
chk = sql("select t1.name from `tabProfile` t1, `tabSales Person` t2 where t2.email_id = t1.name and t2.name=%s",self.doc.contact_by) chk = sql("select t1.name from `tabProfile` t1, `tabSales Person` t2 where t2.email_id = t1.name and t2.name=%s",self.doc.contact_by)
if chk: if chk:
user_lst.append(chk[0][0]) user_lst.append(chk[0][0])
for d in user_lst: for d in user_lst:
ch = addchild(ev, 'event_individuals', 'Event User', 0) ch = addchild(ev, 'event_individuals', 'Event User', 0)
ch.person = d ch.person = d
ch.save(1) ch.save(1)
#update enquiry #update enquiry
#------------------ #------------------
def update_enquiry(self, flag): def update_enquiry(self, flag):
prevdoc='' prevdoc=''
for d in getlist(self.doclist, 'quotation_details'): for d in getlist(self.doclist, 'quotation_details'):
if d.prevdoc_docname: if d.prevdoc_docname:
prevdoc = d.prevdoc_docname prevdoc = d.prevdoc_docname
if prevdoc: if prevdoc:
if flag == 'submit': #on submit if flag == 'submit': #on submit
sql("update `tabEnquiry` set status = 'Quotation Sent' where name = %s", prevdoc) sql("update `tabEnquiry` set status = 'Quotation Sent' where name = %s", prevdoc)
elif flag == 'cancel': #on cancel elif flag == 'cancel': #on cancel
sql("update `tabEnquiry` set status = 'Open' where name = %s", prevdoc) sql("update `tabEnquiry` set status = 'Open' where name = %s", prevdoc)
elif flag == 'order lost': #order lost elif flag == 'order lost': #order lost
sql("update `tabEnquiry` set status = 'Enquiry Lost' where name=%s", prevdoc) sql("update `tabEnquiry` set status = 'Enquiry Lost' where name=%s", prevdoc)
elif flag == 'order confirm': #order confirm elif flag == 'order confirm': #order confirm
sql("update `tabEnquiry` set status='Order Confirmed' where name=%s", prevdoc) sql("update `tabEnquiry` set status='Order Confirmed' where name=%s", prevdoc)
# declare as order lost # declare as order lost
#------------------------- #-------------------------
def declare_order_lost(self,arg): def declare_order_lost(self,arg):
chk = sql("select t1.name from `tabSales Order` t1, `tabSales Order Detail` t2 where t2.parent = t1.name and t1.docstatus=1 and t2.prevdoc_docname = %s",self.doc.name) chk = sql("select t1.name from `tabSales Order` t1, `tabSales Order Detail` t2 where t2.parent = t1.name and t1.docstatus=1 and t2.prevdoc_docname = %s",self.doc.name)
if chk: if chk:
msgprint("Sales Order No. "+cstr(chk[0][0])+" is submitted against this Quotation. Thus 'Order Lost' can not be declared against it.") msgprint("Sales Order No. "+cstr(chk[0][0])+" is submitted against this Quotation. Thus 'Order Lost' can not be declared against it.")
raise Exception raise Exception
else: else:
set(self.doc, 'status', 'Order Lost') set(self.doc, 'status', 'Order Lost')
set(self.doc, 'order_lost_reason', arg) set(self.doc, 'order_lost_reason', arg)
self.update_enquiry('order lost') self.update_enquiry('order lost')
return 'true' return 'true'
#check if value entered in item table #check if value entered in item table
#-------------------------------------- #--------------------------------------
def check_item_table(self): def check_item_table(self):
if not getlist(self.doclist, 'quotation_details'): if not getlist(self.doclist, 'quotation_details'):
msgprint("Please enter item details") msgprint("Please enter item details")
raise Exception raise Exception
# ON SUBMIT # ON SUBMIT
# ========================================================================= # =========================================================================
def on_submit(self): def on_submit(self):
self.check_item_table() self.check_item_table()
if not self.doc.amended_from: if not self.doc.amended_from:
set(self.doc, 'message', 'Quotation: '+self.doc.name+' has been sent') set(self.doc, 'message', 'Quotation: '+self.doc.name+' has been sent')
else: else:
set(self.doc, 'message', 'Quotation has been amended. New Quotation no:'+self.doc.name) set(self.doc, 'message', 'Quotation has been amended. New Quotation no:'+self.doc.name)
# Check for Approving Authority # Check for Approving Authority
get_obj('Authorization Control').validate_approving_authority(self.doc.doctype, self.doc.company, self.doc.grand_total, self) get_obj('Authorization Control').validate_approving_authority(self.doc.doctype, self.doc.company, self.doc.grand_total, self)
# Set Quotation Status # Set Quotation Status
set(self.doc, 'status', 'Submitted') set(self.doc, 'status', 'Submitted')
#update enquiry status #update enquiry status
self.update_enquiry('submit') self.update_enquiry('submit')
# ON CANCEL # ON CANCEL
# ========================================================================== # ==========================================================================
def on_cancel(self): def on_cancel(self):
set(self.doc, 'message', 'Quotation: '+self.doc.name+' has been cancelled') set(self.doc, 'message', 'Quotation: '+self.doc.name+' has been cancelled')
#update enquiry status #update enquiry status
self.update_enquiry('cancel') self.update_enquiry('cancel')
set(self.doc,'status','Cancelled') set(self.doc,'status','Cancelled')
# SEND SMS # SEND SMS
# ============================================================================= # =============================================================================
def send_sms(self): def send_sms(self):
if not self.doc.customer_mobile_no: if not self.doc.customer_mobile_no:
msgprint("Please enter customer mobile no") msgprint("Please enter customer mobile no")
elif not self.doc.message: elif not self.doc.message:
msgprint("Please enter the message you want to send") msgprint("Please enter the message you want to send")
else: else:
msgprint(get_obj("SMS Control", "SMS Control").send_sms([self.doc.contact_mobile,], self.doc.message)) msgprint(get_obj("SMS Control", "SMS Control").send_sms([self.doc.contact_mobile,], self.doc.message))
# Print other charges # Print other charges
# =========================================================================== # ===========================================================================
def print_other_charges(self,docname): def print_other_charges(self,docname):
print_lst = [] print_lst = []
for d in getlist(self.doclist,'other_charges'): for d in getlist(self.doclist,'other_charges'):
lst1 = [] lst1 = []
lst1.append(d.description) lst1.append(d.description)
lst1.append(d.total) lst1.append(d.total)
print_lst.append(lst1) print_lst.append(lst1)
return print_lst return print_lst
def update_followup_details(self): def update_followup_details(self):
sql("delete from `tabFollow up` where parent = '%s'"%self.doc.name) sql("delete from `tabFollow up` where parent = '%s'"%self.doc.name)
for d in getlist(self.doclist, 'follow_up'): for d in getlist(self.doclist, 'follow_up'):
d.save() d.save()

View File

@ -7,11 +7,47 @@
// ============== Load Default Taxes =================== // ============== Load Default Taxes ===================
cur_frm.cscript.load_taxes = function(doc, cdt, cdn) { cur_frm.cscript.load_taxes = function(doc, cdt, cdn) {
// run if this is not executed from dt_map... // run if this is not executed from dt_map...
if(doc.customer) return; if(doc.customer) return;
$c_obj([doc],'load_default_taxes','',function(r,rt){ $c_obj([doc],'load_default_taxes','',function(r,rt){
refresh_field('other_charges'); refresh_field('other_charges');
}); });
}
// Gets called after existing item details are update to fill in
// remaining default values
cur_frm.cscript.load_defaults = function(doc, dt, dn) {
if(!cur_frm.doc.__islocal) { return; }
doc = locals[doc.doctype][doc.name];
var fields_to_refresh = LocalDB.set_default_values(doc);
if(fields_to_refresh) { refresh_many(fields_to_refresh); }
fields_to_refresh = null;
var children = getchildren(cur_frm.cscript.tname, doc.name, cur_frm.cscript.fname);
if(!children) { return; }
for(var i=0; i<children.length; i++) {
LocalDB.set_default_values(children[i]);
}
refresh_field(cur_frm.cscript.fname);
}
// Update existing item details
cur_frm.cscript.update_item_details = function(doc, dt, dn) {
if(!cur_frm.doc.__islocal) return;
var children = getchildren(cur_frm.cscript.tname, doc.name, cur_frm.cscript.fname);
if(children) {
$c_obj(make_doclist(doc.doctype, doc.name), 'get_item_details', '',
function(r, rt) {
if(!r.exc) {
refresh_field(cur_frm.cscript.fname);
doc = locals[doc.doctype][doc.name];
cur_frm.cscript.load_defaults(doc, dt, dn);
}
});
}
} }
@ -26,28 +62,28 @@ cur_frm.add_fetch('company', 'default_currency', 'price_list_currency');
// ============== Customer and its primary contact Details ============================ // ============== Customer and its primary contact Details ============================
cur_frm.cscript.customer = function(doc, cdt, cdn) { cur_frm.cscript.customer = function(doc, cdt, cdn) {
if(doc.customer){ if(doc.customer){
if (!doc.company) { if (!doc.company) {
msgprint("Please select company to proceed"); msgprint("Please select company to proceed");
doc.customer = ''; doc.customer = '';
refresh_field('customer'); refresh_field('customer');
} else { } else {
var callback = function(r, rt){ var callback = function(r, rt){
cur_frm.refresh(); cur_frm.refresh();
} }
$c_obj(make_doclist(doc.doctype, doc.name), 'get_customer_details', '',callback); $c_obj(make_doclist(doc.doctype, doc.name), 'get_customer_details', '',callback);
} }
} }
} }
//====================opens territory tree page ================== //====================opens territory tree page ==================
cur_frm.cscript.TerritoryHelp = function(doc,dt,dn){ cur_frm.cscript.TerritoryHelp = function(doc,dt,dn){
var call_back = function(){ var call_back = function(){
var sb_obj = new SalesBrowser(); var sb_obj = new SalesBrowser();
sb_obj.set_val('Territory'); sb_obj.set_val('Territory');
} }
loadpage('Sales Browser',call_back); loadpage('Sales Browser',call_back);
} }
//====================opens customer group tree page ================== //====================opens customer group tree page ==================
@ -64,7 +100,7 @@ cur_frm.cscript.CGHelp = function(doc,dt,dn){
// ===================================================================================================== // =====================================================================================================
// ********************* CURRENCY ****************************** // ********************* CURRENCY ******************************
cur_frm.cscript.currency = function(doc, cdt, cdn) { cur_frm.cscript.currency = function(doc, cdt, cdn) {
cur_frm.cscript.price_list_name(doc, cdt, cdn); cur_frm.cscript.price_list_name(doc, cdt, cdn);
} }
@ -76,54 +112,54 @@ cur_frm.cscript.plc_conversion_rate = cur_frm.cscript.currency;
// ******************** PRICE LIST ****************************** // ******************** PRICE LIST ******************************
cur_frm.cscript.price_list_name = function(doc, cdt, cdn) { cur_frm.cscript.price_list_name = function(doc, cdt, cdn) {
var fname = cur_frm.cscript.fname; var fname = cur_frm.cscript.fname;
var cl = getchildren(cur_frm.cscript.tname, doc.name, cur_frm.cscript.fname); var cl = getchildren(cur_frm.cscript.tname, doc.name, cur_frm.cscript.fname);
if(doc.price_list_name && doc.currency && doc.price_list_currency && doc.conversion_rate && doc.plc_conversion_rate && cl.length) { if(doc.price_list_name && doc.currency && doc.price_list_currency && doc.conversion_rate && doc.plc_conversion_rate && cl.length) {
$c_obj(make_doclist(doc.doctype, doc.name), 'get_adj_percent', '', $c_obj(make_doclist(doc.doctype, doc.name), 'get_adj_percent', '',
function(r, rt) { function(r, rt) {
refresh_field(fname); refresh_field(fname);
var doc = locals[cdt][cdn]; var doc = locals[cdt][cdn];
cur_frm.cscript.recalc(doc,3); //this is to re-calculate BASIC RATE and AMOUNT on basis of changed REF RATE cur_frm.cscript.recalc(doc,3); //this is to re-calculate BASIC RATE and AMOUNT on basis of changed REF RATE
} }
); );
} }
} }
// ******************** ITEM CODE ******************************** // ******************** ITEM CODE ********************************
cur_frm.fields_dict[cur_frm.cscript.fname].grid.get_field("item_code").get_query = function(doc, cdt, cdn) { cur_frm.fields_dict[cur_frm.cscript.fname].grid.get_field("item_code").get_query = function(doc, cdt, cdn) {
if (doc.order_type == 'Maintenance') if (doc.order_type == 'Maintenance')
return 'SELECT tabItem.name,tabItem.item_name,tabItem.description FROM tabItem WHERE tabItem.is_service_item="Yes" AND tabItem.docstatus != 2 AND (ifnull(`tabItem`.`end_of_life`,"") = "" OR `tabItem`.`end_of_life` > NOW() OR `tabItem`.`end_of_life`="0000-00-00") AND tabItem.%(key)s LIKE "%s" LIMIT 50'; return 'SELECT tabItem.name,tabItem.item_name,tabItem.description FROM tabItem WHERE tabItem.is_service_item="Yes" AND tabItem.docstatus != 2 AND (ifnull(`tabItem`.`end_of_life`,"") = "" OR `tabItem`.`end_of_life` > NOW() OR `tabItem`.`end_of_life`="0000-00-00") AND tabItem.%(key)s LIKE "%s" LIMIT 50';
else else
return 'SELECT tabItem.name,tabItem.item_name,tabItem.description FROM tabItem WHERE tabItem.is_sales_item="Yes" AND tabItem.docstatus != 2 AND (ifnull(`tabItem`.`end_of_life`,"") = "" OR `tabItem`.`end_of_life` > NOW() OR `tabItem`.`end_of_life`="0000-00-00") AND tabItem.%(key)s LIKE "%s" LIMIT 50'; return 'SELECT tabItem.name,tabItem.item_name,tabItem.description FROM tabItem WHERE tabItem.is_sales_item="Yes" AND tabItem.docstatus != 2 AND (ifnull(`tabItem`.`end_of_life`,"") = "" OR `tabItem`.`end_of_life` > NOW() OR `tabItem`.`end_of_life`="0000-00-00") AND tabItem.%(key)s LIKE "%s" LIMIT 50';
} }
cur_frm.cscript.item_code = function(doc, cdt, cdn) { cur_frm.cscript.item_code = function(doc, cdt, cdn) {
var fname = cur_frm.cscript.fname; var fname = cur_frm.cscript.fname;
var d = locals[cdt][cdn]; var d = locals[cdt][cdn];
if (d.item_code) { if (d.item_code) {
if (!doc.company) { if (!doc.company) {
msgprint("Please select company to proceed"); msgprint("Please select company to proceed");
d.item_code = ''; d.item_code = '';
refresh_field('item_code', d.name, fname); refresh_field('item_code', d.name, fname);
} else { } else {
var callback = function(r, rt){ var callback = function(r, rt){
cur_frm.cscript.recalc(doc, 1); cur_frm.cscript.recalc(doc, 1);
} }
get_server_fields('get_item_details',d.item_code, fname,doc,cdt,cdn,1,callback); get_server_fields('get_item_details',d.item_code, fname,doc,cdt,cdn,1,callback);
} }
} }
if(cur_frm.cscript.custom_item_code){ if(cur_frm.cscript.custom_item_code){
cur_frm.cscript.custom_item_code(doc, cdt, cdn); cur_frm.cscript.custom_item_code(doc, cdt, cdn);
} }
} }
// *********************** QUANTITY *************************** // *********************** QUANTITY ***************************
cur_frm.cscript.qty = function(doc, cdt, cdn) { cur_frm.cscript.recalc(doc, 1); } cur_frm.cscript.qty = function(doc, cdt, cdn) { cur_frm.cscript.recalc(doc, 1); }
// ************************ DISCOUNT (%) *********************** // ************************ DISCOUNT (%) ***********************
cur_frm.cscript.adj_rate = function(doc, cdt, cdn) { cur_frm.cscript.recalc(doc, 1); } cur_frm.cscript.adj_rate = function(doc, cdt, cdn) { cur_frm.cscript.recalc(doc, 1); }
@ -171,7 +207,7 @@ cur_frm.cscript.export_rate = function(doc,cdt,cdn) {
var cur_rec = locals[cdt][cdn]; var cur_rec = locals[cdt][cdn];
var fname = cur_frm.cscript.fname; var fname = cur_frm.cscript.fname;
var tname = cur_frm.cscript.tname; var tname = cur_frm.cscript.tname;
if(flt(cur_rec.ref_rate)>0 && flt(cur_rec.export_rate)>0 && !flt(cur_rec.adj_rate)) { if(flt(cur_rec.ref_rate)>0 && flt(cur_rec.export_rate)>0) {
var adj_rate = 100 * (1 - (flt(cur_rec.export_rate) / flt(cur_rec.ref_rate))); var adj_rate = 100 * (1 - (flt(cur_rec.export_rate) / flt(cur_rec.ref_rate)));
set_multiple(tname, cur_rec.name, { 'adj_rate': adj_rate }, fname); set_multiple(tname, cur_rec.name, { 'adj_rate': adj_rate }, fname);
} }
@ -183,59 +219,59 @@ cur_frm.cscript.export_rate = function(doc,cdt,cdn) {
// ************* GET OTHER CHARGES BASED ON COMPANY ************* // ************* GET OTHER CHARGES BASED ON COMPANY *************
cur_frm.fields_dict.charge.get_query = function(doc) { cur_frm.fields_dict.charge.get_query = function(doc) {
return 'SELECT DISTINCT `tabOther Charges`.name FROM `tabOther Charges` WHERE `tabOther Charges`.company = "'+doc.company+'" AND `tabOther Charges`.company is not NULL AND `tabOther Charges`.docstatus != 2 AND `tabOther Charges`.%(key)s LIKE "%s" ORDER BY `tabOther Charges`.name LIMIT 50'; return 'SELECT DISTINCT `tabOther Charges`.name FROM `tabOther Charges` WHERE `tabOther Charges`.company = "'+doc.company+'" AND `tabOther Charges`.company is not NULL AND `tabOther Charges`.docstatus != 2 AND `tabOther Charges`.%(key)s LIKE "%s" ORDER BY `tabOther Charges`.name LIMIT 50';
} }
// ********************* Get Charges **************************** // ********************* Get Charges ****************************
cur_frm.cscript['Get Charges'] = function(doc, cdt, cdn) { cur_frm.cscript['Get Charges'] = function(doc, cdt, cdn) {
$c_obj(make_doclist(doc.doctype,doc.name),'get_other_charges','', function(r, rt) { cur_frm.cscript['Calculate Charges'](doc, cdt, cdn);}); $c_obj(make_doclist(doc.doctype,doc.name),'get_other_charges','', function(r, rt) { cur_frm.cscript['Calculate Charges'](doc, cdt, cdn);});
} }
// CALCULATION OF TOTAL AMOUNTS // CALCULATION OF TOTAL AMOUNTS
// ======================================================================================================== // ========================================================================================================
cur_frm.cscript.recalc = function(doc, n) { cur_frm.cscript.recalc = function(doc, n) {
if(!n)n=0; if(!n)n=0;
doc = locals[doc.doctype][doc.name]; doc = locals[doc.doctype][doc.name];
var tname = cur_frm.cscript.tname; var tname = cur_frm.cscript.tname;
var fname = cur_frm.cscript.fname; var fname = cur_frm.cscript.fname;
var sales_team = cur_frm.cscript.sales_team_fname; var sales_team = cur_frm.cscript.sales_team_fname;
var other_fname = cur_frm.cscript.other_fname; var other_fname = cur_frm.cscript.other_fname;
if(!flt(doc.conversion_rate)) { doc.conversion_rate = 1; refresh_field('conversion_rate'); } if(!flt(doc.conversion_rate)) { doc.conversion_rate = 1; refresh_field('conversion_rate'); }
if(!flt(doc.plc_conversion_rate)) { doc.plc_conversion_rate = 1; refresh_field('plc_conversion_rate'); } if(!flt(doc.plc_conversion_rate)) { doc.plc_conversion_rate = 1; refresh_field('plc_conversion_rate'); }
if(n > 0) cur_frm.cscript.update_fname_table(doc , tname , fname , n, other_fname); // updates all values in table (i.e. amount, export amount, net total etc.) if(n > 0) cur_frm.cscript.update_fname_table(doc , tname , fname , n, other_fname); // updates all values in table (i.e. amount, export amount, net total etc.)
if(flt(doc.net_total) > 0) { if(flt(doc.net_total) > 0) {
var cl = getchildren('RV Tax Detail', doc.name, other_fname,doc.doctype); var cl = getchildren('RV Tax Detail', doc.name, other_fname,doc.doctype);
for(var i = 0; i<cl.length; i++){ for(var i = 0; i<cl.length; i++){
cl[i].total_tax_amount = 0; cl[i].total_tax_amount = 0;
cl[i].total_amount = 0; cl[i].total_amount = 0;
cl[i].tax_amount = 0; // this is done to calculate other charges cl[i].tax_amount = 0; // this is done to calculate other charges
cl[i].total = 0; cl[i].total = 0;
cl[i].item_wise_tax_detail = ""; cl[i].item_wise_tax_detail = "";
if(in_list(['On Previous Row Amount','On Previous Row Total'],cl[i].charge_type) && !cl[i].row_id){ if(in_list(['On Previous Row Amount','On Previous Row Total'],cl[i].charge_type) && !cl[i].row_id){
alert("Please Enter Row on which amount needs to be calculated for row : "+cl[i].idx); alert("Please Enter Row on which amount needs to be calculated for row : "+cl[i].idx);
validated = false; validated = false;
} }
} }
cur_frm.cscript.calc_other_charges(doc , tname , fname , other_fname); // calculate other charges cur_frm.cscript.calc_other_charges(doc , tname , fname , other_fname); // calculate other charges
} }
cur_frm.cscript.calc_doc_values(doc, cdt, cdn, tname, fname, other_fname); // calculates total amounts cur_frm.cscript.calc_doc_values(doc, cdt, cdn, tname, fname, other_fname); // calculates total amounts
// ******************* calculate allocated amount of sales person ************************ // ******************* calculate allocated amount of sales person ************************
cl = getchildren('Sales Team', doc.name, sales_team); cl = getchildren('Sales Team', doc.name, sales_team);
for(var i=0;i<cl.length;i++) { for(var i=0;i<cl.length;i++) {
if (cl[i].allocated_percentage) { if (cl[i].allocated_percentage) {
cl[i].allocated_amount = flt(flt(doc.net_total)*flt(cl[i].allocated_percentage)/100); cl[i].allocated_amount = flt(flt(doc.net_total)*flt(cl[i].allocated_percentage)/100);
refresh_field('allocated_amount', cl[i].name, sales_team); refresh_field('allocated_amount', cl[i].name, sales_team);
} }
} }
doc.in_words = ''; doc.in_words = '';
doc.in_words_export = ''; doc.in_words_export = '';
refresh_many(['total_discount_rate','total_discount','net_total','total_commission','grand_total','rounded_total','grand_total_export','rounded_total_export','in_words','in_words_export','other_charges','other_charges_total']); refresh_many(['total_discount_rate','total_discount','net_total','total_commission','grand_total','rounded_total','grand_total_export','rounded_total_export','in_words','in_words_export','other_charges','other_charges_total']);
if(cur_frm.cscript.custom_recalc)cur_frm.cscript.custom_recalc(doc); if(cur_frm.cscript.custom_recalc)cur_frm.cscript.custom_recalc(doc);
} }
// ******* Calculation of total amounts of document (item amount + other charges)**************** // ******* Calculation of total amounts of document (item amount + other charges)****************
@ -282,27 +318,32 @@ cur_frm.cscript.calc_other_charges = function(doc , tname , fname , other_fname)
var cl = getchildren(tname, doc.name, fname); var cl = getchildren(tname, doc.name, fname);
var tax = getchildren('RV Tax Detail', doc.name, other_fname,doc.doctype); var tax = getchildren('RV Tax Detail', doc.name, other_fname,doc.doctype);
// Make display table // Make display table
var otc = make_table(cur_frm.fields_dict['Other Charges Calculation'].disp_area, var otc = make_table(cur_frm.fields_dict['Other Charges Calculation'].disp_area,
cl.length + 1, tax.length + 1, '90%', [], { border:'1px solid #AAA', padding:'2px' }); cl.length + 1, tax.length + 1, '90%', [], { border:'1px solid #AAA', padding:'2px' });
$y(otc,{marginTop:'8px'}); $y(otc,{marginTop:'8px'});
var tax_desc = {}; var tax_desc_rates = []; var net_total = 0; var tax_desc = {}; var tax_desc_rates = []; var net_total = 0;
for(var i=0;i<cl.length;i++) { for(var i=0;i<cl.length;i++) {
net_total += flt(flt(cl[i].qty) * flt(cl[i].basic_rate)); net_total += flt(flt(cl[i].qty) * flt(cl[i].basic_rate));
var prev_total = flt(cl[i].amount); var prev_total = flt(cl[i].amount);
if(cl[i].item_tax_rate) if(cl[i].item_tax_rate) {
var check_tax = eval('var a='+cl[i].item_tax_rate+';a'); //to get in dictionary try {
var check_tax = JSON.parse(cl[i].item_tax_rate); //to get in dictionary
} catch(exception) {
var check_tax = eval('var a='+cl[i].item_tax_rate+';a'); //to get in dictionary
}
}
// Add Item Code in new Row // Add Item Code in new Row
$td(otc,i+1,0).innerHTML = cl[i].item_code ? cl[i].item_code : cl[i].description; $td(otc,i+1,0).innerHTML = cl[i].item_code ? cl[i].item_code : cl[i].description;
//var tax = getchildren('RV Tax Detail', doc.name, other_fname,doc.doctype); //var tax = getchildren('RV Tax Detail', doc.name, other_fname,doc.doctype);
var total = net_total; var total = net_total;
for(var t=0;t<tax.length;t++){ for(var t=0;t<tax.length;t++){
var account = tax[t].account_head; var account = tax[t].account_head;
$td(otc,0,t+1).innerHTML = account?account:''; $td(otc,0,t+1).innerHTML = account?account:'';
@ -320,14 +361,14 @@ cur_frm.cscript.calc_other_charges = function(doc , tname , fname , other_fname)
//enter item_wise_tax_detail i.e. tax rate on each item //enter item_wise_tax_detail i.e. tax rate on each item
var item_wise_tax_detail = cur_frm.cscript.get_item_wise_tax_detail(doc, rate, cl, i, tax, t); var item_wise_tax_detail = cur_frm.cscript.get_item_wise_tax_detail(doc, rate, cl, i, tax, t);
if(tax[t].charge_type != "Actual") tax[t].item_wise_tax_detail += item_wise_tax_detail; if(tax[t].charge_type != "Actual") tax[t].item_wise_tax_detail += item_wise_tax_detail;
tax[t].total_amount = flt(tax_amount); //stores actual tax amount in virtual field tax[t].total_amount = flt(tax_amount); //stores actual tax amount in virtual field
tax[t].total_tax_amount = flt(prev_total); //stores total amount in virtual field tax[t].total_tax_amount = flt(prev_total); //stores total amount in virtual field
tax[t].tax_amount += flt(tax_amount); tax[t].tax_amount += flt(tax_amount);
var total_amount = flt(tax[t].tax_amount); var total_amount = flt(tax[t].tax_amount);
total_tax_amount = flt(tax[t].total_tax_amount) + flt(total_amount); total_tax_amount = flt(tax[t].total_tax_amount) + flt(total_amount);
set_multiple('RV Tax Detail', tax[t].name, { 'item_wise_tax_detail':tax[t].item_wise_tax_detail, 'amount':roundNumber(flt(total_amount), 2), 'total':roundNumber(flt(total)+flt(tax[t].tax_amount), 2)}, other_fname); set_multiple('RV Tax Detail', tax[t].name, { 'item_wise_tax_detail':tax[t].item_wise_tax_detail, 'amount':roundNumber(flt(total_amount), 2), 'total':roundNumber(flt(total)+flt(tax[t].tax_amount), 2)}, other_fname);
prev_total += flt(tax[t].total_amount); // for previous row total prev_total += flt(tax[t].total_amount); // for previous row total
total += flt(tax[t].tax_amount); // for adding total to previous amount total += flt(tax[t].tax_amount); // for adding total to previous amount
if(tax[t].charge_type == 'Actual') if(tax[t].charge_type == 'Actual')
$td(otc,i+1,t+1).innerHTML = fmt_money(tax[t].total_amount); $td(otc,i+1,t+1).innerHTML = fmt_money(tax[t].total_amount);
@ -342,55 +383,55 @@ cur_frm.cscript.calc_other_charges = function(doc , tname , fname , other_fname)
} }
} }
cur_frm.cscript.check_charge_type_and_get_tax_amount = function( doc, tax, t, cl, rate, print_amt) { cur_frm.cscript.check_charge_type_and_get_tax_amount = function( doc, tax, t, cl, rate, print_amt) {
doc = locals[doc.doctype][doc.name]; doc = locals[doc.doctype][doc.name];
if (! print_amt) print_amt = 0; if (! print_amt) print_amt = 0;
var tax_amount = 0; var tax_amount = 0;
if(tax[t].charge_type == 'Actual') { if(tax[t].charge_type == 'Actual') {
var value = flt(tax[t].rate) / flt(doc.net_total); // this give the ratio in which all items are divided var value = flt(tax[t].rate) / flt(doc.net_total); // this give the ratio in which all items are divided
return tax_amount = flt(value) * flt(cl.amount); return tax_amount = flt(value) * flt(cl.amount);
} }
else if(tax[t].charge_type == 'On Net Total') { else if(tax[t].charge_type == 'On Net Total') {
if (flt(print_amt) == 1) { if (flt(print_amt) == 1) {
doc.excise_rate = flt(rate); doc.excise_rate = flt(rate);
doc.total_excise_rate += flt(rate); doc.total_excise_rate += flt(rate);
refresh_field('excise_rate'); refresh_field('excise_rate');
refresh_field('total_excise_rate'); refresh_field('total_excise_rate');
return return
} }
return tax_amount = (flt(rate) * flt(cl.amount) / 100); return tax_amount = (flt(rate) * flt(cl.amount) / 100);
} }
else if(tax[t].charge_type == 'On Previous Row Amount'){ else if(tax[t].charge_type == 'On Previous Row Amount'){
if(flt(print_amt) == 1) { if(flt(print_amt) == 1) {
doc.total_excise_rate += flt(flt(doc.excise_rate) * 0.01 * flt(rate)); doc.total_excise_rate += flt(flt(doc.excise_rate) * 0.01 * flt(rate));
refresh_field('total_excise_rate'); refresh_field('total_excise_rate');
return return
} }
var row_no = (tax[t].row_id).toString(); var row_no = (tax[t].row_id).toString();
var row = (row_no).split("+"); // splits the values and stores in an array var row = (row_no).split("+"); // splits the values and stores in an array
for(var r = 0;r<row.length;r++){ for(var r = 0;r<row.length;r++){
var id = cint(row[r].replace(/^\s+|\s+$/g,"")); var id = cint(row[r].replace(/^\s+|\s+$/g,""));
tax_amount += (flt(rate) * flt(tax[id-1].total_amount) / 100); tax_amount += (flt(rate) * flt(tax[id-1].total_amount) / 100);
} }
var row_id = row_no.indexOf("/"); var row_id = row_no.indexOf("/");
if(row_id != -1) { if(row_id != -1) {
rate = ''; rate = '';
var row = (row_no).split("/"); // splits the values and stores in an array var row = (row_no).split("/"); // splits the values and stores in an array
if(row.length>2) alert("You cannot enter more than 2 nos. for division"); if(row.length>2) alert("You cannot enter more than 2 nos. for division");
var id1 = cint(row[0].replace(/^\s+|\s+$/g,"")); var id1 = cint(row[0].replace(/^\s+|\s+$/g,""));
var id2 = cint(row[1].replace(/^\s+|\s+$/g,"")); var id2 = cint(row[1].replace(/^\s+|\s+$/g,""));
tax_amount = flt(tax[id1-1].total_amount) / flt(tax[id2-1].total_amount); tax_amount = flt(tax[id1-1].total_amount) / flt(tax[id2-1].total_amount);
} }
return tax_amount return tax_amount
} }
else if(tax[t].charge_type == 'On Previous Row Total') { else if(tax[t].charge_type == 'On Previous Row Total') {
if(flt(print_amt) == 1) { if(flt(print_amt) == 1) {
doc.sales_tax_rate += flt(rate); doc.sales_tax_rate += flt(rate);
refresh_field('sales_tax_rate'); refresh_field('sales_tax_rate');
return return
} }
var row = cint(tax[t].row_id); var row = cint(tax[t].row_id);
return tax_amount = flt(rate) * (flt(tax[row-1].total_tax_amount)+flt(tax[row-1].total_amount)) / 100; return tax_amount = flt(rate) * (flt(tax[row-1].total_tax_amount)+flt(tax[row-1].total_amount)) / 100;
} }
} }
// ********************** Functions for inclusive value calc ****************************** // ********************** Functions for inclusive value calc ******************************
@ -409,8 +450,11 @@ cur_frm.cscript.consider_incl_rate = function(doc, other_fname) {
cur_frm.cscript.back_calc_basic_rate = function(doc, tname, fname, child, other_fname) { cur_frm.cscript.back_calc_basic_rate = function(doc, tname, fname, child, other_fname) {
var get_item_tax_rate = function(item, tax) { var get_item_tax_rate = function(item, tax) {
if(item.item_tax_rate) { if(item.item_tax_rate) {
// Should to replace eval with JSON.parse when item_tax_rate is converted to json string notation try {
var item_tax = eval('var a='+item.item_tax_rate+';a'); var item_tax = JSON.parse(item.item_tax_rate);
} catch(exception) {
var item_tax = eval('var a='+item.item_tax_rate+';a');
}
if(item_tax[tax.account_head]!=null) { if(item_tax[tax.account_head]!=null) {
return flt(item_tax[tax.account_head]); return flt(item_tax[tax.account_head]);
} }
@ -524,45 +568,45 @@ cur_frm.cscript.update_fname_table = function(doc , tname , fname , n, other_fna
'base_ref_rate': flt(base_ref_rate) 'base_ref_rate': flt(base_ref_rate)
}, fname); }, fname);
} }
} }
else if(n == 2){ else if(n == 2){
if(flt(cl[i].ref_rate) > 0) if(flt(cl[i].ref_rate) > 0)
set_multiple(tname, cl[i].name, {'adj_rate': 100 - flt(flt(cl[i].basic_rate) * 100 / (flt(cl[i].ref_rate) * flt(doc.conversion_rate)))}, fname); set_multiple(tname, cl[i].name, {'adj_rate': 100 - flt(flt(cl[i].basic_rate) * 100 / (flt(cl[i].ref_rate) * flt(doc.conversion_rate)))}, fname);
set_multiple(tname, cl[i].name, {'amount': flt(flt(cl[i].qty) * flt(cl[i].basic_rate)), 'export_rate': flt(flt(cl[i].basic_rate) / flt(doc.conversion_rate)), 'export_amount': flt((flt(cl[i].basic_rate) / flt(doc.conversion_rate)) * flt(cl[i].qty)) }, fname); set_multiple(tname, cl[i].name, {'amount': flt(flt(cl[i].qty) * flt(cl[i].basic_rate)), 'export_rate': flt(flt(cl[i].basic_rate) / flt(doc.conversion_rate)), 'export_amount': flt((flt(cl[i].basic_rate) / flt(doc.conversion_rate)) * flt(cl[i].qty)) }, fname);
} }
/*else if(n == 3){ /*else if(n == 3){
set_multiple(tname, cl[i].name, {'basic_rate': flt(flt(cl[i].export_rate) * flt(doc.conversion_rate))}, fname); set_multiple(tname, cl[i].name, {'basic_rate': flt(flt(cl[i].export_rate) * flt(doc.conversion_rate))}, fname);
set_multiple(tname, cl[i].name, {'amount' : flt(flt(cl[i].basic_rate) * flt(cl[i].qty)), 'export_amount': flt(flt(cl[i].export_rate) * flt(cl[i].qty))}, fname); set_multiple(tname, cl[i].name, {'amount' : flt(flt(cl[i].basic_rate) * flt(cl[i].qty)), 'export_amount': flt(flt(cl[i].export_rate) * flt(cl[i].qty))}, fname);
if(cl[i].ref_rate > 0) if(cl[i].ref_rate > 0)
set_multiple(tname, cl[i].name, {'adj_rate': 100 - flt(flt(cl[i].export_rate) * 100 / flt(cl[i].ref_rate)), 'base_ref_rate': flt(flt(cl[i].ref_rate) * flt(doc.conversion_rate)) }, fname); set_multiple(tname, cl[i].name, {'adj_rate': 100 - flt(flt(cl[i].export_rate) * 100 / flt(cl[i].ref_rate)), 'base_ref_rate': flt(flt(cl[i].ref_rate) * flt(doc.conversion_rate)) }, fname);
}*/ }*/
net_total += flt(flt(cl[i].qty) * flt(cl[i].basic_rate)); net_total += flt(flt(cl[i].qty) * flt(cl[i].basic_rate));
} }
doc.net_total = net_total; doc.net_total = net_total;
refresh_field('net_total'); refresh_field('net_total');
} }
cur_frm.cscript.get_item_wise_tax_detail = function( doc, rate, cl, i, tax, t) { cur_frm.cscript.get_item_wise_tax_detail = function( doc, rate, cl, i, tax, t) {
doc = locals[doc.doctype][doc.name]; doc = locals[doc.doctype][doc.name];
var detail = ''; var detail = '';
detail = cl[i].item_code + " : " + cstr(rate) + NEWLINE; detail = cl[i].item_code + " : " + cstr(rate) + NEWLINE;
return detail; return detail;
} }
// **************** RE-CALCULATE VALUES *************************** // **************** RE-CALCULATE VALUES ***************************
cur_frm.cscript['Re-Calculate Values'] = function(doc, cdt, cdn) { cur_frm.cscript['Re-Calculate Values'] = function(doc, cdt, cdn) {
cur_frm.cscript['Calculate Charges'](doc,cdt,cdn); cur_frm.cscript['Calculate Charges'](doc,cdt,cdn);
} }
cur_frm.cscript['Calculate Charges'] = function(doc, cdt, cdn) { cur_frm.cscript['Calculate Charges'] = function(doc, cdt, cdn) {
var other_fname = cur_frm.cscript.other_fname; var other_fname = cur_frm.cscript.other_fname;
var cl = getchildren('RV Tax Detail', doc.name, other_fname, doc.doctype); var cl = getchildren('RV Tax Detail', doc.name, other_fname, doc.doctype);
for(var i = 0; i<cl.length; i++){ for(var i = 0; i<cl.length; i++){
cl[i].total_tax_amount = 0; cl[i].total_tax_amount = 0;
cl[i].total_amount = 0; cl[i].total_amount = 0;
cl[i].tax_amount = 0; // this is done to calculate other charges cl[i].tax_amount = 0; // this is done to calculate other charges
cl[i].total = 0; cl[i].total = 0;
if(in_list(['On Previous Row Amount','On Previous Row Total'], cl[i].charge_type)) { if(in_list(['On Previous Row Amount','On Previous Row Total'], cl[i].charge_type)) {
if(!cl[i].row_id){ if(!cl[i].row_id){
@ -586,71 +630,71 @@ cur_frm.cscript['Calculate Charges'] = function(doc, cdt, cdn) {
// Get Sales Partner Commission // Get Sales Partner Commission
// ================================================================================= // =================================================================================
cur_frm.cscript.sales_partner = function(doc, cdt, cdn){ cur_frm.cscript.sales_partner = function(doc, cdt, cdn){
if(doc.sales_partner){ if(doc.sales_partner){
get_server_fields('get_comm_rate', doc.sales_partner, '', doc, cdt, cdn, 1); get_server_fields('get_comm_rate', doc.sales_partner, '', doc, cdt, cdn, 1);
} }
} }
// *******Commission Rate Trigger (calculates total commission amount)********* // *******Commission Rate Trigger (calculates total commission amount)*********
cur_frm.cscript.commission_rate = function(doc, cdt, cdn) { cur_frm.cscript.commission_rate = function(doc, cdt, cdn) {
if(doc.commission_rate > 100){ if(doc.commission_rate > 100){
alert("Commision rate cannot be greater than 100."); alert("Commision rate cannot be greater than 100.");
doc.total_commission = 0; doc.total_commission = 0;
doc.commission_rate = 0; doc.commission_rate = 0;
} }
else else
doc.total_commission = doc.net_total * doc.commission_rate / 100; doc.total_commission = doc.net_total * doc.commission_rate / 100;
refresh_many(['total_commission','commission_rate']); refresh_many(['total_commission','commission_rate']);
} }
// *******Total Commission Trigger (calculates commission rate)********* // *******Total Commission Trigger (calculates commission rate)*********
cur_frm.cscript.total_commission = function(doc, cdt, cdn) { cur_frm.cscript.total_commission = function(doc, cdt, cdn) {
if(doc.net_total){ if(doc.net_total){
if(doc.net_total < doc.total_commission){ if(doc.net_total < doc.total_commission){
alert("Total commission cannot be greater than net total."); alert("Total commission cannot be greater than net total.");
doc.total_commission = 0; doc.total_commission = 0;
doc.commission_rate = 0; doc.commission_rate = 0;
} }
else else
doc.commission_rate = doc.total_commission * 100 / doc.net_total; doc.commission_rate = doc.total_commission * 100 / doc.net_total;
refresh_many(['total_commission','commission_rate']); refresh_many(['total_commission','commission_rate']);
} }
} }
// Sales Person Allocated % trigger // Sales Person Allocated % trigger
// ============================================================================== // ==============================================================================
cur_frm.cscript.allocated_percentage = function(doc, cdt, cdn) { cur_frm.cscript.allocated_percentage = function(doc, cdt, cdn) {
var fname = cur_frm.cscript.sales_team_fname; var fname = cur_frm.cscript.sales_team_fname;
var d = locals[cdt][cdn]; var d = locals[cdt][cdn];
if (d.allocated_percentage) { if (d.allocated_percentage) {
d.allocated_amount = flt(flt(doc.net_total)*flt(d.allocated_percentage)/100); d.allocated_amount = flt(flt(doc.net_total)*flt(d.allocated_percentage)/100);
refresh_field('allocated_amount', d.name, fname); refresh_field('allocated_amount', d.name, fname);
} }
} }
// Client Side Validation // Client Side Validation
// ================================================================================= // =================================================================================
cur_frm.cscript.validate = function(doc, cdt, cdn) { cur_frm.cscript.validate = function(doc, cdt, cdn) {
cur_frm.cscript.validate_items(doc); cur_frm.cscript.validate_items(doc);
var cl = getchildren('Other Charges', doc.name, 'other_charges'); var cl = getchildren('Other Charges', doc.name, 'other_charges');
for(var i =0;i<cl.length;i++) { for(var i =0;i<cl.length;i++) {
if(!cl[i].amount) { if(!cl[i].amount) {
alert("Please Enter Amount in Row no. "+cl[i].idx+" in Other Charges table"); alert("Please Enter Amount in Row no. "+cl[i].idx+" in Other Charges table");
validated = false; validated = false;
} }
} }
cur_frm.cscript['Calculate Charges'] (doc, cdt, cdn); cur_frm.cscript['Calculate Charges'] (doc, cdt, cdn);
if (cur_frm.cscript.calc_adjustment_amount) cur_frm.cscript.calc_adjustment_amount(doc); if (cur_frm.cscript.calc_adjustment_amount) cur_frm.cscript.calc_adjustment_amount(doc);
} }
// ************** Atleast one item in document **************** // ************** Atleast one item in document ****************
cur_frm.cscript.validate_items = function(doc) { cur_frm.cscript.validate_items = function(doc) {
var cl = getchildren(cur_frm.cscript.tname, doc.name, cur_frm.cscript.fname); var cl = getchildren(cur_frm.cscript.tname, doc.name, cur_frm.cscript.fname);
if(!cl.length){ if(!cl.length){
alert("Please enter Items for " + doc.doctype); alert("Please enter Items for " + doc.doctype);
validated = false; validated = false;
} }
} }

View File

@ -109,10 +109,11 @@ class DocType(TransactionBase):
# Get Item Details # Get Item Details
# =============================================================== # ===============================================================
def get_item_details(self, item_code, obj): def get_item_details(self, item_code, obj):
import json
if not obj.doc.price_list_name: if not obj.doc.price_list_name:
msgprint("Please Select Price List before selecting Items") msgprint("Please Select Price List before selecting Items")
raise Exception raise Exception
item = webnotes.conn.sql("select description, item_name, brand, item_group, stock_uom, default_warehouse, default_income_account, default_sales_cost_center, description_html from `tabItem` where name = '%s' and (ifnull(end_of_life,'')='' or end_of_life > now() or end_of_life = '0000-00-00') and (is_sales_item = 'Yes' or is_service_item = 'Yes')" %(item_code), as_dict=1) item = webnotes.conn.sql("select description, item_name, brand, item_group, stock_uom, default_warehouse, default_income_account, default_sales_cost_center, description_html from `tabItem` where name = '%s' and (ifnull(end_of_life,'')='' or end_of_life > now() or end_of_life = '0000-00-00') and (is_sales_item = 'Yes' or is_service_item = 'Yes')" % (item_code), as_dict=1)
tax = webnotes.conn.sql("select tax_type, tax_rate from `tabItem Tax` where parent = %s" , item_code) tax = webnotes.conn.sql("select tax_type, tax_rate from `tabItem Tax` where parent = %s" , item_code)
t = {} t = {}
for x in tax: t[x[0]] = flt(x[1]) for x in tax: t[x[0]] = flt(x[1])
@ -130,7 +131,7 @@ class DocType(TransactionBase):
'adj_rate' : 0, 'adj_rate' : 0,
'amount' : 0, 'amount' : 0,
'export_amount' : 0, 'export_amount' : 0,
'item_tax_rate' : str(t), 'item_tax_rate' : json.dumps(t),
'batch_no' : '' 'batch_no' : ''
} }
if(obj.doc.price_list_name and item): #this is done to fetch the changed BASIC RATE and REF RATE based on PRICE LIST if(obj.doc.price_list_name and item): #this is done to fetch the changed BASIC RATE and REF RATE based on PRICE LIST

View File

@ -14,111 +14,114 @@ $import(SMS Control)
// ONLOAD // ONLOAD
// ================================================================================================ // ================================================================================================
cur_frm.cscript.onload = function(doc, cdt, cdn) { cur_frm.cscript.onload = function(doc, cdt, cdn) {
if(!doc.status) set_multiple(cdt,cdn,{status:'Draft'}); if(!doc.status) set_multiple(cdt,cdn,{status:'Draft'});
if(!doc.transaction_date) set_multiple(cdt,cdn,{transaction_date:get_today()}); if(!doc.transaction_date) set_multiple(cdt,cdn,{transaction_date:get_today()});
if(!doc.price_list_currency) set_multiple(cdt, cdn, {price_list_currency: doc.currency, plc_conversion_rate: 1}); if(!doc.price_list_currency) set_multiple(cdt, cdn, {price_list_currency: doc.currency, plc_conversion_rate: 1});
// load default charges // load default charges
if(doc.__islocal){ if(doc.__islocal){
hide_field(['customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group','shipping_address']); hide_field(['customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group','shipping_address']);
} }
// defined in sales_common.js
cur_frm.cscript.update_item_details(doc, cdt, cdn);
} }
cur_frm.cscript.onload_post_render = function(doc, cdt, cdn) { cur_frm.cscript.onload_post_render = function(doc, cdt, cdn) {
if(doc.__islocal) { if(doc.__islocal) {
if(doc.quotation) cur_frm.cscript['Pull Quotation Details'](doc,cdt,cdn); if(doc.quotation) cur_frm.cscript['Pull Quotation Details'](doc,cdt,cdn);
} else { } else {
cur_frm.cscript.load_taxes(doc, cdt, cdn); cur_frm.cscript.load_taxes(doc, cdt, cdn);
} }
} }
// Refresh // Refresh
//================== //==================
cur_frm.cscript.refresh = function(doc, cdt, cdn) { cur_frm.cscript.refresh = function(doc, cdt, cdn) {
cur_frm.clear_custom_buttons(); cur_frm.clear_custom_buttons();
if(doc.docstatus==1) { if(doc.docstatus==1) {
if(doc.status != 'Stopped') { if(doc.status != 'Stopped') {
cur_frm.add_custom_button('Send SMS', cur_frm.cscript['Send SMS']); cur_frm.add_custom_button('Send SMS', cur_frm.cscript['Send SMS']);
// delivery note // delivery note
if(doc.per_delivered < 100 && doc.order_type!='Maintenance') if(doc.per_delivered < 100 && doc.order_type!='Maintenance')
cur_frm.add_custom_button('Make Delivery', cur_frm.cscript['Make Delivery Note']); cur_frm.add_custom_button('Make Delivery', cur_frm.cscript['Make Delivery Note']);
// maintenance // maintenance
if(doc.per_delivered < 100 && doc.order_type=='Maintenance') { if(doc.per_delivered < 100 && doc.order_type=='Maintenance') {
cur_frm.add_custom_button('Make Maint. Visit', cur_frm.cscript['Make Maintenance Visit']); cur_frm.add_custom_button('Make Maint. Visit', cur_frm.cscript['Make Maintenance Visit']);
cur_frm.add_custom_button('Make Maint. Schedule', cur_frm.cscript['Make Maintenance Schedule']); cur_frm.add_custom_button('Make Maint. Schedule', cur_frm.cscript['Make Maintenance Schedule']);
} }
// indent // indent
if(doc.order_type != 'Maintenance') if(doc.order_type != 'Maintenance')
cur_frm.add_custom_button('Make ' + get_doctype_label('Indent'), cur_frm.cscript['Make Purchase Requisition']); cur_frm.add_custom_button('Make ' + get_doctype_label('Indent'), cur_frm.cscript['Make Purchase Requisition']);
// sales invoice // sales invoice
if(doc.per_billed < 100) if(doc.per_billed < 100)
cur_frm.add_custom_button('Make Invoice', cur_frm.cscript['Make Sales Invoice']); cur_frm.add_custom_button('Make Invoice', cur_frm.cscript['Make Sales Invoice']);
// stop // stop
if(doc.per_delivered < 100 || doc.per_billed < 100) if(doc.per_delivered < 100 || doc.per_billed < 100)
cur_frm.add_custom_button('Stop!', cur_frm.cscript['Stop Sales Order']); cur_frm.add_custom_button('Stop!', cur_frm.cscript['Stop Sales Order']);
} else { } else {
// un-stop // un-stop
cur_frm.add_custom_button('Unstop', cur_frm.cscript['Unstop Sales Order']); cur_frm.add_custom_button('Unstop', cur_frm.cscript['Unstop Sales Order']);
} }
unhide_field(['Repair Sales Order', 'Send SMS', 'message', 'customer_mobile_no']) unhide_field(['Repair Sales Order', 'Send SMS', 'message', 'customer_mobile_no'])
} else { } else {
hide_field(['Repair Sales Order', 'Send SMS', 'message', 'customer_mobile_no']) hide_field(['Repair Sales Order', 'Send SMS', 'message', 'customer_mobile_no'])
} }
} }
//customer //customer
cur_frm.cscript.customer = function(doc,dt,dn) { cur_frm.cscript.customer = function(doc,dt,dn) {
var callback = function(r,rt) { var callback = function(r,rt) {
var doc = locals[cur_frm.doctype][cur_frm.docname]; var doc = locals[cur_frm.doctype][cur_frm.docname];
get_server_fields('get_shipping_address',doc.customer,'',doc, dt, dn, 0); get_server_fields('get_shipping_address',doc.customer,'',doc, dt, dn, 0);
cur_frm.refresh(); cur_frm.refresh();
} }
if(doc.customer) $c_obj(make_doclist(doc.doctype, doc.name), 'get_default_customer_address', '', callback); if(doc.customer) $c_obj(make_doclist(doc.doctype, doc.name), 'get_default_customer_address', '', callback);
if(doc.customer) unhide_field(['customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group','shipping_address']); if(doc.customer) unhide_field(['customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group','shipping_address']);
} }
cur_frm.cscript.customer_address = cur_frm.cscript.contact_person = function(doc,dt,dn) { cur_frm.cscript.customer_address = cur_frm.cscript.contact_person = function(doc,dt,dn) {
if(doc.customer) get_server_fields('get_customer_address', JSON.stringify({customer: doc.customer, address: doc.customer_address, contact: doc.contact_person}),'', doc, dt, dn, 1); if(doc.customer) get_server_fields('get_customer_address', JSON.stringify({customer: doc.customer, address: doc.customer_address, contact: doc.contact_person}),'', doc, dt, dn, 1);
} }
cur_frm.fields_dict.customer_address.on_new = function(dn) { cur_frm.fields_dict.customer_address.on_new = function(dn) {
locals['Address'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer; locals['Address'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
locals['Address'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name; locals['Address'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
} }
cur_frm.fields_dict.contact_person.on_new = function(dn) { cur_frm.fields_dict.contact_person.on_new = function(dn) {
locals['Contact'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer; locals['Contact'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
locals['Contact'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name; locals['Contact'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
} }
cur_frm.fields_dict['customer_address'].get_query = function(doc, cdt, cdn) { cur_frm.fields_dict['customer_address'].get_query = function(doc, cdt, cdn) {
return 'SELECT name,address_line1,city FROM tabAddress WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50'; return 'SELECT name,address_line1,city FROM tabAddress WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
} }
cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) { cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50'; return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
} }
cur_frm.cscript['Pull Quotation Details'] = function(doc,dt,dn) { cur_frm.cscript['Pull Quotation Details'] = function(doc,dt,dn) {
var callback = function(r,rt){ var callback = function(r,rt){
var doc = locals[cur_frm.doctype][cur_frm.docname]; var doc = locals[cur_frm.doctype][cur_frm.docname];
if(r.message){ if(r.message){
doc.quotation_no = r.message; doc.quotation_no = r.message;
if(doc.quotation_no) { if(doc.quotation_no) {
unhide_field(['quotation_date','customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group','shipping_address']); unhide_field(['quotation_date','customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group','shipping_address']);
if(doc.customer) get_server_fields('get_shipping_address',doc.customer,'',doc, dt, dn, 0); if(doc.customer) get_server_fields('get_shipping_address',doc.customer,'',doc, dt, dn, 0);
} }
cur_frm.refresh(); cur_frm.refresh();
} }
} }
$c_obj(make_doclist(doc.doctype, doc.name),'pull_quotation_details','',callback); $c_obj(make_doclist(doc.doctype, doc.name),'pull_quotation_details','',callback);
} }
@ -126,10 +129,10 @@ cur_frm.cscript['Pull Quotation Details'] = function(doc,dt,dn) {
//================ create new contact ============================================================================ //================ create new contact ============================================================================
cur_frm.cscript.new_contact = function(){ cur_frm.cscript.new_contact = function(){
tn = createLocal('Contact'); tn = createLocal('Contact');
locals['Contact'][tn].is_customer = 1; locals['Contact'][tn].is_customer = 1;
if(doc.customer) locals['Contact'][tn].customer = doc.customer; if(doc.customer) locals['Contact'][tn].customer = doc.customer;
loaddoc('Contact', tn); loaddoc('Contact', tn);
} }
// DOCTYPE TRIGGERS // DOCTYPE TRIGGERS
@ -138,35 +141,35 @@ cur_frm.cscript.new_contact = function(){
/* /*
// ***************** get shipping address based on customer selected ***************** // ***************** get shipping address based on customer selected *****************
cur_frm.fields_dict['ship_det_no'].get_query = function(doc, cdt, cdn) { cur_frm.fields_dict['ship_det_no'].get_query = function(doc, cdt, cdn) {
return 'SELECT `tabShipping Address`.`name`, `tabShipping Address`.`ship_to`, `tabShipping Address`.`shipping_address` FROM `tabShipping Address` WHERE `tabShipping Address`.customer = "'+ doc.customer+'" AND `tabShipping Address`.`docstatus` != 2 AND `tabShipping Address`.`name` LIKE "%s" ORDER BY `tabShipping Address`.name ASC LIMIT 50'; return 'SELECT `tabShipping Address`.`name`, `tabShipping Address`.`ship_to`, `tabShipping Address`.`shipping_address` FROM `tabShipping Address` WHERE `tabShipping Address`.customer = "'+ doc.customer+'" AND `tabShipping Address`.`docstatus` != 2 AND `tabShipping Address`.`name` LIKE "%s" ORDER BY `tabShipping Address`.name ASC LIMIT 50';
} }
*/ */
// ***************** Get project name ***************** // ***************** Get project name *****************
cur_frm.fields_dict['project_name'].get_query = function(doc, cdt, cdn) { cur_frm.fields_dict['project_name'].get_query = function(doc, cdt, cdn) {
var cond = ''; var cond = '';
if(doc.customer) cond = '(`tabProject`.customer = "'+doc.customer+'" OR IFNULL(`tabProject`.customer,"")="") AND'; if(doc.customer) cond = '(`tabProject`.customer = "'+doc.customer+'" OR IFNULL(`tabProject`.customer,"")="") AND';
return repl('SELECT `tabProject`.name FROM `tabProject` WHERE `tabProject`.status = "Open" AND %(cond)s `tabProject`.name LIKE "%s" ORDER BY `tabProject`.name ASC LIMIT 50', {cond:cond}); return repl('SELECT `tabProject`.name FROM `tabProject` WHERE `tabProject`.status = "Open" AND %(cond)s `tabProject`.name LIKE "%s" ORDER BY `tabProject`.name ASC LIMIT 50', {cond:cond});
} }
//---- get customer details ---------------------------- //---- get customer details ----------------------------
cur_frm.cscript.project_name = function(doc,cdt,cdn){ cur_frm.cscript.project_name = function(doc,cdt,cdn){
$c_obj(make_doclist(doc.doctype, doc.name),'pull_project_customer','', function(r,rt){ $c_obj(make_doclist(doc.doctype, doc.name),'pull_project_customer','', function(r,rt){
refresh_many(['customer','customer_name', 'customer_address', 'contact_person', 'territory', 'contact_no', 'email_id', 'customer_group']); refresh_many(['customer','customer_name', 'customer_address', 'contact_person', 'territory', 'contact_no', 'email_id', 'customer_group']);
}); });
} }
// *************** Customized link query for QUOTATION ***************************** // *************** Customized link query for QUOTATION *****************************
cur_frm.fields_dict['quotation_no'].get_query = function(doc) { cur_frm.fields_dict['quotation_no'].get_query = function(doc) {
var cond=''; var cond='';
if(doc.order_type) cond = ' ifnull(`tabQuotation`.order_type, "") = "'+doc.order_type+'" and'; if(doc.order_type) cond = ' ifnull(`tabQuotation`.order_type, "") = "'+doc.order_type+'" and';
if(doc.customer) cond += ' ifnull(`tabQuotation`.customer, "") = "'+doc.customer+'" and'; if(doc.customer) cond += ' ifnull(`tabQuotation`.customer, "") = "'+doc.customer+'" and';
return repl('SELECT DISTINCT name, customer, transaction_date FROM `tabQuotation` WHERE `tabQuotation`.company = "' + doc.company + '" and `tabQuotation`.`docstatus` = 1 and `tabQuotation`.status != "Order Lost" and %(cond)s `tabQuotation`.%(key)s LIKE "%s" ORDER BY `tabQuotation`.`name` DESC LIMIT 50', {cond:cond}); return repl('SELECT DISTINCT name, customer, transaction_date FROM `tabQuotation` WHERE `tabQuotation`.company = "' + doc.company + '" and `tabQuotation`.`docstatus` = 1 and `tabQuotation`.status != "Order Lost" and %(cond)s `tabQuotation`.%(key)s LIKE "%s" ORDER BY `tabQuotation`.`name` DESC LIMIT 50', {cond:cond});
} }
@ -175,164 +178,164 @@ cur_frm.fields_dict['quotation_no'].get_query = function(doc) {
// ***************** Get available qty in warehouse of item selected **************** // ***************** Get available qty in warehouse of item selected ****************
cur_frm.cscript.reserved_warehouse = function(doc, cdt , cdn) { cur_frm.cscript.reserved_warehouse = function(doc, cdt , cdn) {
var d = locals[cdt][cdn]; var d = locals[cdt][cdn];
if (d.reserved_warehouse) { if (d.reserved_warehouse) {
arg = "{'item_code':'" + d.item_code + "','warehouse':'" + d.reserved_warehouse +"'}"; arg = "{'item_code':'" + d.item_code + "','warehouse':'" + d.reserved_warehouse +"'}";
get_server_fields('get_available_qty',arg,'sales_order_details',doc,cdt,cdn,1); get_server_fields('get_available_qty',arg,'sales_order_details',doc,cdt,cdn,1);
} }
} }
//----------- make maintenance schedule---------- //----------- make maintenance schedule----------
cur_frm.cscript['Make Maintenance Schedule'] = function() { cur_frm.cscript['Make Maintenance Schedule'] = function() {
var doc = cur_frm.doc; var doc = cur_frm.doc;
if (doc.docstatus == 1) { if (doc.docstatus == 1) {
$c_obj(make_doclist(doc.doctype, doc.name),'check_maintenance_schedule','', $c_obj(make_doclist(doc.doctype, doc.name),'check_maintenance_schedule','',
function(r,rt){ function(r,rt){
if(r.message == 'No'){ if(r.message == 'No'){
n = createLocal("Maintenance Schedule"); n = createLocal("Maintenance Schedule");
$c('dt_map', args={ $c('dt_map', args={
'docs':compress_doclist([locals["Maintenance Schedule"][n]]), 'docs':compress_doclist([locals["Maintenance Schedule"][n]]),
'from_doctype':'Sales Order', 'from_doctype':'Sales Order',
'to_doctype':'Maintenance Schedule', 'to_doctype':'Maintenance Schedule',
'from_docname':doc.name, 'from_docname':doc.name,
'from_to_list':"[['Sales Order', 'Maintenance Schedule'], ['Sales Order Detail', 'Item Maintenance Detail']]" 'from_to_list':"[['Sales Order', 'Maintenance Schedule'], ['Sales Order Detail', 'Item Maintenance Detail']]"
} }
, function(r,rt) { , function(r,rt) {
loaddoc("Maintenance Schedule", n); loaddoc("Maintenance Schedule", n);
} }
); );
} }
else{ else{
msgprint("You have already created Maintenance Schedule against this Sales Order"); msgprint("You have already created Maintenance Schedule against this Sales Order");
} }
} }
); );
} }
} }
//------------ make maintenance visit ------------ //------------ make maintenance visit ------------
cur_frm.cscript['Make Maintenance Visit'] = function() { cur_frm.cscript['Make Maintenance Visit'] = function() {
var doc = cur_frm.doc; var doc = cur_frm.doc;
if (doc.docstatus == 1) { if (doc.docstatus == 1) {
$c_obj(make_doclist(doc.doctype, doc.name),'check_maintenance_visit','', $c_obj(make_doclist(doc.doctype, doc.name),'check_maintenance_visit','',
function(r,rt){ function(r,rt){
if(r.message == 'No'){ if(r.message == 'No'){
n = createLocal("Maintenance Visit"); n = createLocal("Maintenance Visit");
$c('dt_map', args={ $c('dt_map', args={
'docs':compress_doclist([locals["Maintenance Visit"][n]]), 'docs':compress_doclist([locals["Maintenance Visit"][n]]),
'from_doctype':'Sales Order', 'from_doctype':'Sales Order',
'to_doctype':'Maintenance Visit', 'to_doctype':'Maintenance Visit',
'from_docname':doc.name, 'from_docname':doc.name,
'from_to_list':"[['Sales Order', 'Maintenance Visit'], ['Sales Order Detail', 'Maintenance Visit Detail']]" 'from_to_list':"[['Sales Order', 'Maintenance Visit'], ['Sales Order Detail', 'Maintenance Visit Detail']]"
} }
, function(r,rt) { , function(r,rt) {
loaddoc("Maintenance Visit", n); loaddoc("Maintenance Visit", n);
} }
); );
} }
else{ else{
msgprint("You have already completed maintenance against this Sales Order"); msgprint("You have already completed maintenance against this Sales Order");
} }
} }
); );
} }
} }
// make indent // make indent
// ================================================================================================ // ================================================================================================
cur_frm.cscript['Make Purchase Requisition'] = function() { cur_frm.cscript['Make Purchase Requisition'] = function() {
var doc = cur_frm.doc; var doc = cur_frm.doc;
if (doc.docstatus == 1) { if (doc.docstatus == 1) {
n = createLocal("Indent"); n = createLocal("Indent");
$c('dt_map', args={ $c('dt_map', args={
'docs':compress_doclist([locals["Indent"][n]]), 'docs':compress_doclist([locals["Indent"][n]]),
'from_doctype':'Sales Order', 'from_doctype':'Sales Order',
'to_doctype':'Indent', 'to_doctype':'Indent',
'from_docname':doc.name, 'from_docname':doc.name,
'from_to_list':"[['Sales Order', 'Indent'], ['Sales Order Detail', 'Indent Detail']]" 'from_to_list':"[['Sales Order', 'Indent'], ['Sales Order Detail', 'Indent Detail']]"
} }
, function(r,rt) { , function(r,rt) {
loaddoc("Indent", n); loaddoc("Indent", n);
} }
); );
} }
} }
// MAKE DELIVERY NOTE // MAKE DELIVERY NOTE
// ================================================================================================ // ================================================================================================
cur_frm.cscript['Make Delivery Note'] = function() { cur_frm.cscript['Make Delivery Note'] = function() {
var doc = cur_frm.doc; var doc = cur_frm.doc;
if (doc.docstatus == 1) { if (doc.docstatus == 1) {
n = createLocal("Delivery Note"); n = createLocal("Delivery Note");
$c('dt_map', args={ $c('dt_map', args={
'docs':compress_doclist([locals["Delivery Note"][n]]), 'docs':compress_doclist([locals["Delivery Note"][n]]),
'from_doctype':'Sales Order', 'from_doctype':'Sales Order',
'to_doctype':'Delivery Note', 'to_doctype':'Delivery Note',
'from_docname':doc.name, 'from_docname':doc.name,
'from_to_list':"[['Sales Order', 'Delivery Note'], ['Sales Order Detail', 'Delivery Note Detail'],['RV Tax Detail','RV Tax Detail'],['Sales Team','Sales Team']]" 'from_to_list':"[['Sales Order', 'Delivery Note'], ['Sales Order Detail', 'Delivery Note Detail'],['RV Tax Detail','RV Tax Detail'],['Sales Team','Sales Team']]"
} }
, function(r,rt) { , function(r,rt) {
loaddoc("Delivery Note", n); loaddoc("Delivery Note", n);
} }
); );
} }
} }
// MAKE SALES INVOICE // MAKE SALES INVOICE
// ================================================================================================ // ================================================================================================
cur_frm.cscript['Make Sales Invoice'] = function() { cur_frm.cscript['Make Sales Invoice'] = function() {
var doc = cur_frm.doc; var doc = cur_frm.doc;
n = createLocal('Receivable Voucher'); n = createLocal('Receivable Voucher');
$c('dt_map', args={ $c('dt_map', args={
'docs':compress_doclist([locals['Receivable Voucher'][n]]), 'docs':compress_doclist([locals['Receivable Voucher'][n]]),
'from_doctype':doc.doctype, 'from_doctype':doc.doctype,
'to_doctype':'Receivable Voucher', 'to_doctype':'Receivable Voucher',
'from_docname':doc.name, 'from_docname':doc.name,
'from_to_list':"[['Sales Order','Receivable Voucher'],['Sales Order Detail','RV Detail'],['RV Tax Detail','RV Tax Detail'],['Sales Team','Sales Team']]" 'from_to_list':"[['Sales Order','Receivable Voucher'],['Sales Order Detail','RV Detail'],['RV Tax Detail','RV Tax Detail'],['Sales Team','Sales Team']]"
}, function(r,rt) { }, function(r,rt) {
loaddoc('Receivable Voucher', n); loaddoc('Receivable Voucher', n);
} }
); );
} }
// STOP SALES ORDER // STOP SALES ORDER
// ================================================================================================== // ==================================================================================================
cur_frm.cscript['Stop Sales Order'] = function() { cur_frm.cscript['Stop Sales Order'] = function() {
var doc = cur_frm.doc; var doc = cur_frm.doc;
var check = confirm("Are you sure you want to STOP " + doc.name); var check = confirm("Are you sure you want to STOP " + doc.name);
if (check) { if (check) {
$c('runserverobj', args={'method':'stop_sales_order', 'docs': compress_doclist(make_doclist(doc.doctype, doc.name))}, function(r,rt) { $c('runserverobj', args={'method':'stop_sales_order', 'docs': compress_doclist(make_doclist(doc.doctype, doc.name))}, function(r,rt) {
cur_frm.refresh(); cur_frm.refresh();
}); });
} }
} }
// UNSTOP SALES ORDER // UNSTOP SALES ORDER
// ================================================================================================== // ==================================================================================================
cur_frm.cscript['Unstop Sales Order'] = function() { cur_frm.cscript['Unstop Sales Order'] = function() {
var doc = cur_frm.doc; var doc = cur_frm.doc;
var check = confirm("Are you sure you want to UNSTOP " + doc.name); var check = confirm("Are you sure you want to UNSTOP " + doc.name);
if (check) { if (check) {
$c('runserverobj', args={'method':'unstop_sales_order', 'docs': compress_doclist(make_doclist(doc.doctype, doc.name))}, function(r,rt) { $c('runserverobj', args={'method':'unstop_sales_order', 'docs': compress_doclist(make_doclist(doc.doctype, doc.name))}, function(r,rt) {
cur_frm.refresh(); cur_frm.refresh();
}); });
} }
} }
//get query select Territory //get query select Territory
//======================================================================================================================= //=======================================================================================================================
cur_frm.fields_dict['territory'].get_query = function(doc,cdt,cdn) { cur_frm.fields_dict['territory'].get_query = function(doc,cdt,cdn) {
return 'SELECT `tabTerritory`.`name`,`tabTerritory`.`parent_territory` FROM `tabTerritory` WHERE `tabTerritory`.`is_group` = "No" AND `tabTerritory`.`docstatus`!= 2 AND `tabTerritory`.%(key)s LIKE "%s" ORDER BY `tabTerritory`.`name` ASC LIMIT 50'; return 'SELECT `tabTerritory`.`name`,`tabTerritory`.`parent_territory` FROM `tabTerritory` WHERE `tabTerritory`.`is_group` = "No" AND `tabTerritory`.`docstatus`!= 2 AND `tabTerritory`.%(key)s LIKE "%s" ORDER BY `tabTerritory`.`name` ASC LIMIT 50';
} }
$import(Notification Control) $import(Notification Control)

View File

@ -85,8 +85,18 @@ class DocType(TransactionBase):
# ================================================================================ # ================================================================================
# Get Item Details # Get Item Details
# ---------------- # ----------------
def get_item_details(self, item_code): def get_item_details(self, item_code=None):
return get_obj('Sales Common').get_item_details(item_code, self) if item_code:
return get_obj('Sales Common').get_item_details(item_code, self)
else:
obj = get_obj('Sales Common')
for doc in self.doclist:
if doc.fields.get('item_code'):
ret = obj.get_item_details(doc.item_code, self)
for r in ret:
if not doc.fields.get(r):
doc.fields[r] = ret[r]
# Re-calculates Basic Rate & amount based on Price List Selected # Re-calculates Basic Rate & amount based on Price List Selected
# -------------------------------------------------------------- # --------------------------------------------------------------

View File

@ -763,7 +763,7 @@ def send():
""" """
edigest_list = webnotes.conn.sql(""" edigest_list = webnotes.conn.sql("""
SELECT name FROM `tabEmail Digest` SELECT name FROM `tabEmail Digest`
WHERE enabled=1 WHERE enabled=1 and docstatus<2
""", as_list=1) """, as_list=1)
from webnotes.model.code import get_obj from webnotes.model.code import get_obj

View File

@ -85,8 +85,9 @@ class DocType:
from webnotes.utils import file_manager from webnotes.utils import file_manager
fn, content = file_manager.get_file(fid) fn, content = file_manager.get_file(fid)
if not type(content) == str: # NOTE: Don't know why this condition exists
if not isinstance(content, basestring) and hasattr(content, 'tostring'):
content = content.tostring() content = content.tostring()
return content return content

View File

@ -96,8 +96,9 @@ class DocType:
from webnotes.utils import file_manager from webnotes.utils import file_manager
fn, content = file_manager.get_file(fid) fn, content = file_manager.get_file(fid)
if not type(content) == str: # NOTE: Don't know why this condition exists
if not isinstance(content, basestring) and hasattr(content, 'tostring'):
content = content.tostring() content = content.tostring()
return content return content

View File

@ -11,93 +11,97 @@ $import(SMS Control)
// ONLOAD // ONLOAD
// ================================================================================================ // ================================================================================================
cur_frm.cscript.onload = function(doc, dt, dn) { cur_frm.cscript.onload = function(doc, dt, dn) {
if(!doc.status) set_multiple(dt,dn,{status:'Draft'}); if(!doc.status) set_multiple(dt,dn,{status:'Draft'});
if(!doc.transaction_date) set_multiple(dt,dn,{transaction_date:get_today()}); if(!doc.transaction_date) set_multiple(dt,dn,{transaction_date:get_today()});
if(!doc.posting_date) set_multiple(dt,dn,{posting_date:get_today()}); if(!doc.posting_date) set_multiple(dt,dn,{posting_date:get_today()});
if(doc.__islocal && doc.customer) cur_frm.cscript.pull_item_details_onload(doc,dt,dn); if(doc.__islocal && doc.customer) cur_frm.cscript.pull_item_details_onload(doc,dt,dn);
if(!doc.price_list_currency) { if(!doc.price_list_currency) {
set_multiple(dt, dn, {price_list_currency: doc.currency, plc_conversion_rate:1}); set_multiple(dt, dn, {price_list_currency: doc.currency, plc_conversion_rate:1});
} }
if(!doc.posting_time) doc.posting_time = wn.datetime.get_cur_time() if(!doc.posting_time) doc.posting_time = wn.datetime.get_cur_time()
if(doc.__islocal){ if(doc.__islocal){
hide_field(['customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']); hide_field(['customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']);
} }
// defined in sales_common.js
//cur_frm.cscript.update_item_details(doc, cdt, cdn);
} }
cur_frm.cscript.onload_post_render = function(doc, dt, dn) { cur_frm.cscript.onload_post_render = function(doc, dt, dn) {
// load default charges // load default charges
if(doc.__islocal && !getchildren('RV Tax Detail', doc.name, 'other_charges', doc.doctype).length) if(doc.__islocal && !getchildren('RV Tax Detail', doc.name, 'other_charges', doc.doctype).length)
cur_frm.cscript.load_taxes(doc, cdt, cdn); cur_frm.cscript.load_taxes(doc, cdt, cdn);
} }
// REFRESH // REFRESH
// ================================================================================================ // ================================================================================================
cur_frm.cscript.refresh = function(doc, cdt, cdn) { cur_frm.cscript.refresh = function(doc, cdt, cdn) {
cur_frm.clear_custom_buttons(); cur_frm.clear_custom_buttons();
if(doc.per_billed < 100 && doc.docstatus==1) cur_frm.add_custom_button('Make Invoice', cur_frm.cscript['Make Sales Invoice']); if(doc.per_billed < 100 && doc.docstatus==1) cur_frm.add_custom_button('Make Invoice', cur_frm.cscript['Make Sales Invoice']);
if(doc.per_installed < 100 && doc.docstatus==1) cur_frm.add_custom_button('Make Installation Note', cur_frm.cscript['Make Installation Note']); if(doc.per_installed < 100 && doc.docstatus==1) cur_frm.add_custom_button('Make Installation Note', cur_frm.cscript['Make Installation Note']);
if (doc.docstatus!=1) { if (doc.docstatus!=1) {
hide_field(['SMS', 'Send SMS', 'message', 'customer_mobile_no', 'Repair Delivery Note']); hide_field(['SMS', 'Send SMS', 'message', 'customer_mobile_no', 'Repair Delivery Note']);
} else { } else {
cur_frm.add_custom_button('Send SMS', cur_frm.cscript['Send SMS']); cur_frm.add_custom_button('Send SMS', cur_frm.cscript['Send SMS']);
unhide_field(['SMS','Send SMS', 'message', 'customer_mobile_no', 'Repair Delivery Note']); unhide_field(['SMS','Send SMS', 'message', 'customer_mobile_no', 'Repair Delivery Note']);
} }
if(doc.docstatus==1) { if(doc.docstatus==1) {
cur_frm.add_custom_button('Make Packing Slip', cur_frm.cscript['Make Packing Slip']); cur_frm.add_custom_button('Make Packing Slip', cur_frm.cscript['Make Packing Slip']);
} }
set_print_hide(doc, cdt, cdn); set_print_hide(doc, cdt, cdn);
} }
//customer //customer
cur_frm.cscript.customer = function(doc,dt,dn) { cur_frm.cscript.customer = function(doc,dt,dn) {
var callback = function(r,rt) { var callback = function(r,rt) {
var doc = locals[cur_frm.doctype][cur_frm.docname]; var doc = locals[cur_frm.doctype][cur_frm.docname];
cur_frm.refresh(); cur_frm.refresh();
} }
if(doc.customer) $c_obj(make_doclist(doc.doctype, doc.name), 'get_default_customer_shipping_address', '', callback); if(doc.customer) $c_obj(make_doclist(doc.doctype, doc.name), 'get_default_customer_shipping_address', '', callback);
if(doc.customer) unhide_field(['customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group','shipping_address']); if(doc.customer) unhide_field(['customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group','shipping_address']);
} }
cur_frm.cscript.customer_address = cur_frm.cscript.contact_person = function(doc,dt,dn) { cur_frm.cscript.customer_address = cur_frm.cscript.contact_person = function(doc,dt,dn) {
if(doc.customer) get_server_fields('get_customer_address', JSON.stringify({customer: doc.customer, address: doc.customer_address, contact: doc.contact_person}),'', doc, dt, dn, 1); if(doc.customer) get_server_fields('get_customer_address', JSON.stringify({customer: doc.customer, address: doc.customer_address, contact: doc.contact_person}),'', doc, dt, dn, 1);
} }
cur_frm.fields_dict.customer_address.on_new = function(dn) { cur_frm.fields_dict.customer_address.on_new = function(dn) {
locals['Address'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer; locals['Address'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
locals['Address'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name; locals['Address'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
} }
cur_frm.fields_dict.contact_person.on_new = function(dn) { cur_frm.fields_dict.contact_person.on_new = function(dn) {
locals['Contact'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer; locals['Contact'][dn].customer = locals[cur_frm.doctype][cur_frm.docname].customer;
locals['Contact'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name; locals['Contact'][dn].customer_name = locals[cur_frm.doctype][cur_frm.docname].customer_name;
} }
cur_frm.fields_dict['customer_address'].get_query = function(doc, cdt, cdn) { cur_frm.fields_dict['customer_address'].get_query = function(doc, cdt, cdn) {
return 'SELECT name,address_line1,city FROM tabAddress WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50'; return 'SELECT name,address_line1,city FROM tabAddress WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
} }
cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) { cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50'; return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE customer = "'+ doc.customer +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
} }
cur_frm.cscript['Get Items'] = function(doc,dt,dn) { cur_frm.cscript['Get Items'] = function(doc,dt,dn) {
var callback = function(r,rt){ var callback = function(r,rt){
var doc = locals[cur_frm.doctype][cur_frm.docname]; var doc = locals[cur_frm.doctype][cur_frm.docname];
if(r.message){ if(r.message){
doc.sales_order_no = r.message; doc.sales_order_no = r.message;
if(doc.sales_order_no) { if(doc.sales_order_no) {
unhide_field(['customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']); unhide_field(['customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']);
} }
refresh_many(['delivery_note_details','customer','customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']); refresh_many(['delivery_note_details','customer','customer_address','contact_person','customer_name','address_display','contact_display','contact_mobile','contact_email','territory','customer_group']);
} }
} }
$c_obj(make_doclist(doc.doctype, doc.name),'pull_sales_order_details','',callback); $c_obj(make_doclist(doc.doctype, doc.name),'pull_sales_order_details','',callback);
} }
@ -105,45 +109,45 @@ cur_frm.cscript['Get Items'] = function(doc,dt,dn) {
//RV-DN : Pull Item details - UOM, Item Group as it was not in Sales Invoice //RV-DN : Pull Item details - UOM, Item Group as it was not in Sales Invoice
//--------------------------------------------------------------------- //---------------------------------------------------------------------
cur_frm.cscript.pull_item_details_onload = function(doc,dt,dn){ cur_frm.cscript.pull_item_details_onload = function(doc,dt,dn){
var callback = function(r,rt){ var callback = function(r,rt){
refresh_field('delivery_note_details'); refresh_field('delivery_note_details');
cur_frm.cscript.customer(doc,dt,dn); cur_frm.cscript.customer(doc,dt,dn);
} }
$c_obj(make_doclist(dt,dn),'set_item_details','',callback); $c_obj(make_doclist(dt,dn),'set_item_details','',callback);
} }
//================ create new contact ============================================================================ //================ create new contact ============================================================================
cur_frm.cscript.new_contact = function(){ cur_frm.cscript.new_contact = function(){
tn = createLocal('Contact'); tn = createLocal('Contact');
locals['Contact'][tn].is_customer = 1; locals['Contact'][tn].is_customer = 1;
if(doc.customer) locals['Contact'][tn].customer = doc.customer; if(doc.customer) locals['Contact'][tn].customer = doc.customer;
loaddoc('Contact', tn); loaddoc('Contact', tn);
} }
//========================= Overloaded query for link batch_no ============================================================= //========================= Overloaded query for link batch_no =============================================================
cur_frm.fields_dict['delivery_note_details'].grid.get_field('batch_no').get_query= function(doc, cdt, cdn) { cur_frm.fields_dict['delivery_note_details'].grid.get_field('batch_no').get_query= function(doc, cdt, cdn) {
var d = locals[cdt][cdn]; var d = locals[cdt][cdn];
if(d.item_code){ if(d.item_code){
return "SELECT tabBatch.name, tabBatch.description FROM tabBatch WHERE tabBatch.docstatus != 2 AND tabBatch.item = '"+ d.item_code +"' AND `tabBatch`.`name` like '%s' ORDER BY `tabBatch`.`name` DESC LIMIT 50" return "SELECT tabBatch.name, tabBatch.description FROM tabBatch WHERE tabBatch.docstatus != 2 AND tabBatch.item = '"+ d.item_code +"' AND `tabBatch`.`name` like '%s' ORDER BY `tabBatch`.`name` DESC LIMIT 50"
} }
else{ else{
alert("Please enter Item Code."); alert("Please enter Item Code.");
} }
} }
// ***************** Get project name ***************** // ***************** Get project name *****************
cur_frm.fields_dict['project_name'].get_query = function(doc, cdt, cdn) { cur_frm.fields_dict['project_name'].get_query = function(doc, cdt, cdn) {
var cond = ''; var cond = '';
if(doc.customer) cond = '(`tabProject`.customer = "'+doc.customer+'" OR IFNULL(`tabProject`.customer,"")="") AND'; if(doc.customer) cond = '(`tabProject`.customer = "'+doc.customer+'" OR IFNULL(`tabProject`.customer,"")="") AND';
return repl('SELECT `tabProject`.name FROM `tabProject` WHERE `tabProject`.status = "Open" AND %(cond)s `tabProject`.name LIKE "%s" ORDER BY `tabProject`.name ASC LIMIT 50', {cond:cond}); return repl('SELECT `tabProject`.name FROM `tabProject` WHERE `tabProject`.status = "Open" AND %(cond)s `tabProject`.name LIKE "%s" ORDER BY `tabProject`.name ASC LIMIT 50', {cond:cond});
} }
/* /*
//---- get customer details ---------------------------- //---- get customer details ----------------------------
cur_frm.cscript.project_name = function(doc,cdt,cdn){ cur_frm.cscript.project_name = function(doc,cdt,cdn){
$c_obj(make_doclist(doc.doctype, doc.name),'pull_project_customer','', function(r,rt){ $c_obj(make_doclist(doc.doctype, doc.name),'pull_project_customer','', function(r,rt){
refresh_many(['customer','customer_name', 'customer_address', 'contact_person', 'territory', 'contact_no', 'email_id', 'customer_group']); refresh_many(['customer','customer_name', 'customer_address', 'contact_person', 'territory', 'contact_no', 'email_id', 'customer_group']);
}); });
} }
*/ */
@ -154,23 +158,23 @@ cur_frm.cscript.project_name = function(doc,cdt,cdn){
/* /*
var cfn_set_fields = function(doc, cdt, cdn) { var cfn_set_fields = function(doc, cdt, cdn) {
var supplier_field_list = ['Supplier','supplier','supplier_address']; var supplier_field_list = ['Supplier','supplier','supplier_address'];
var customer_field_list = ['Customer','customer','customer_name','customer_address','territory','customer_group','Business Associate','sales_partner','commission_rate','total_commission','sales_order_no','Get Items']; var customer_field_list = ['Customer','customer','customer_name','customer_address','territory','customer_group','Business Associate','sales_partner','commission_rate','total_commission','sales_order_no','Get Items'];
if (doc.delivery_type == 'Rejected' && doc.purchase_receipt_no) { if (doc.delivery_type == 'Rejected' && doc.purchase_receipt_no) {
unhide_field('purchase_receipt_no'); unhide_field('purchase_receipt_no');
unhide_field(supplier_field_list); unhide_field(supplier_field_list);
hide_field(customer_field_list); hide_field(customer_field_list);
get_field(doc.doctype, 'delivery_type' , doc.name).permlevel = 1; get_field(doc.doctype, 'delivery_type' , doc.name).permlevel = 1;
} }
else if (doc.delivery_type == 'Subcontract' && doc.purchase_order_no) { else if (doc.delivery_type == 'Subcontract' && doc.purchase_order_no) {
unhide_field('purchase_order_no'); unhide_field('purchase_order_no');
unhide_field(supplier_field_list); unhide_field(supplier_field_list);
hide_field(cutomer_field_list); hide_field(cutomer_field_list);
get_field(doc.doctype, 'delivery_type' , doc.name).permlevel = 1; get_field(doc.doctype, 'delivery_type' , doc.name).permlevel = 1;
} }
else if (doc.delivery_type == 'Sample') unhide_field('to_warehouse'); else if (doc.delivery_type == 'Sample') unhide_field('to_warehouse');
else get_field(doc.doctype, 'delivery_type' , doc.name).permlevel = 0; else get_field(doc.doctype, 'delivery_type' , doc.name).permlevel = 0;
} }
*/ */
@ -181,14 +185,14 @@ var cfn_set_fields = function(doc, cdt, cdn) {
/* /*
// ***************** Get Contact Person based on customer selected ***************** // ***************** Get Contact Person based on customer selected *****************
cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) { cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
return 'SELECT `tabContact`.contact_name FROM `tabContact` WHERE ((`tabContact`.is_customer = 1 AND `tabContact`.customer = "'+ doc.customer+'") or (`tabContact`.is_sales_partner = 1 AND `tabContact`.sales_partner = "'+ doc.sales_partner+'")) AND `tabContact`.docstatus != 2 AND `tabContact`.contact_name LIKE "%s" ORDER BY `tabContact`.contact_name ASC LIMIT 50'; return 'SELECT `tabContact`.contact_name FROM `tabContact` WHERE ((`tabContact`.is_customer = 1 AND `tabContact`.customer = "'+ doc.customer+'") or (`tabContact`.is_sales_partner = 1 AND `tabContact`.sales_partner = "'+ doc.sales_partner+'")) AND `tabContact`.docstatus != 2 AND `tabContact`.contact_name LIKE "%s" ORDER BY `tabContact`.contact_name ASC LIMIT 50';
} }
*/ */
/* /*
// ***************** get shipping address based on customer selected ***************** // ***************** get shipping address based on customer selected *****************
cur_frm.fields_dict['ship_det_no'].get_query = function(doc, cdt, cdn) { cur_frm.fields_dict['ship_det_no'].get_query = function(doc, cdt, cdn) {
return 'SELECT `tabShipping Address`.`name`, `tabShipping Address`.`ship_to`, `tabShipping Address`.`shipping_address` FROM `tabShipping Address` WHERE `tabShipping Address`.customer = "'+ doc.customer+'" AND `tabShipping Address`.`docstatus` != 2 AND `tabShipping Address`.`name` LIKE "%s" ORDER BY `tabShipping Address`.name ASC LIMIT 50'; return 'SELECT `tabShipping Address`.`name`, `tabShipping Address`.`ship_to`, `tabShipping Address`.`shipping_address` FROM `tabShipping Address` WHERE `tabShipping Address`.customer = "'+ doc.customer+'" AND `tabShipping Address`.`docstatus` != 2 AND `tabShipping Address`.`name` LIKE "%s" ORDER BY `tabShipping Address`.name ASC LIMIT 50';
} }
*/ */
@ -196,179 +200,179 @@ cur_frm.fields_dict['ship_det_no'].get_query = function(doc, cdt, cdn) {
// *************** Customized link query for SALES ORDER based on customer and currency***************************** // *************** Customized link query for SALES ORDER based on customer and currency*****************************
cur_frm.fields_dict['sales_order_no'].get_query = function(doc) { cur_frm.fields_dict['sales_order_no'].get_query = function(doc) {
doc = locals[this.doctype][this.docname]; doc = locals[this.doctype][this.docname];
var cond = ''; var cond = '';
if(doc.customer) { if(doc.customer) {
if(doc.currency) cond = '`tabSales Order`.customer = "'+doc.customer+'" and `tabSales Order`.currency = "'+doc.currency+'" and'; if(doc.currency) cond = '`tabSales Order`.customer = "'+doc.customer+'" and `tabSales Order`.currency = "'+doc.currency+'" and';
else cond = '`tabSales Order`.customer = "'+doc.customer+'" and'; else cond = '`tabSales Order`.customer = "'+doc.customer+'" and';
} }
else { else {
if(doc.currency) cond = '`tabSales Order`.currency = "'+doc.currency+'" and'; if(doc.currency) cond = '`tabSales Order`.currency = "'+doc.currency+'" and';
else cond = ''; else cond = '';
} }
if(doc.project_name){ if(doc.project_name){
cond += '`tabSales Order`.project_name ="'+doc.project_name+'"'; cond += '`tabSales Order`.project_name ="'+doc.project_name+'"';
} }
return repl('SELECT DISTINCT `tabSales Order`.`name` FROM `tabSales Order` WHERE `tabSales Order`.company = "%(company)s" and `tabSales Order`.`docstatus` = 1 and `tabSales Order`.`status` != "Stopped" and ifnull(`tabSales Order`.per_delivered,0) < 100 and %(cond)s `tabSales Order`.%(key)s LIKE "%s" ORDER BY `tabSales Order`.`name` DESC LIMIT 50', {company:doc.company,cond:cond}) return repl('SELECT DISTINCT `tabSales Order`.`name` FROM `tabSales Order` WHERE `tabSales Order`.company = "%(company)s" and `tabSales Order`.`docstatus` = 1 and `tabSales Order`.`status` != "Stopped" and ifnull(`tabSales Order`.per_delivered,0) < 100 and %(cond)s `tabSales Order`.%(key)s LIKE "%s" ORDER BY `tabSales Order`.`name` DESC LIMIT 50', {company:doc.company,cond:cond})
} }
// ****************************** DELIVERY TYPE ************************************ // ****************************** DELIVERY TYPE ************************************
cur_frm.cscript.delivery_type = function(doc, cdt, cdn) { cur_frm.cscript.delivery_type = function(doc, cdt, cdn) {
if (doc.delivery_type = 'Sample') cfn_set_fields(doc, cdt, cdn); if (doc.delivery_type = 'Sample') cfn_set_fields(doc, cdt, cdn);
} }
cur_frm.cscript.serial_no = function(doc, cdt , cdn) { cur_frm.cscript.serial_no = function(doc, cdt , cdn) {
var d = locals[cdt][cdn]; var d = locals[cdt][cdn];
if (d.serial_no) { if (d.serial_no) {
get_server_fields('get_serial_details',d.serial_no,'delivery_note_details',doc,cdt,cdn,1); get_server_fields('get_serial_details',d.serial_no,'delivery_note_details',doc,cdt,cdn,1);
} }
} }
/* /*
// this won't work in case of Sales Bom item where item.is_stock_item = 'No' // this won't work in case of Sales Bom item where item.is_stock_item = 'No'
cur_frm.fields_dict['delivery_note_details'].grid.get_field('warehouse').get_query= function(doc, cdt, cdn) { cur_frm.fields_dict['delivery_note_details'].grid.get_field('warehouse').get_query= function(doc, cdt, cdn) {
var d = locals[cdt][cdn]; var d = locals[cdt][cdn];
return "SELECT `tabBin`.`warehouse`, `tabBin`.`actual_qty` FROM `tabBin` WHERE `tabBin`.`item_code` = '"+ d.item_code +"' AND ifnull(`tabBin`.`actual_qty`,0) > 0 AND `tabBin`.`warehouse` like '%s' ORDER BY `tabBin`.`warehouse` DESC LIMIT 50"; return "SELECT `tabBin`.`warehouse`, `tabBin`.`actual_qty` FROM `tabBin` WHERE `tabBin`.`item_code` = '"+ d.item_code +"' AND ifnull(`tabBin`.`actual_qty`,0) > 0 AND `tabBin`.`warehouse` like '%s' ORDER BY `tabBin`.`warehouse` DESC LIMIT 50";
} }
*/ */
cur_frm.cscript.warehouse = function(doc, cdt, cdn) { cur_frm.cscript.warehouse = function(doc, cdt, cdn) {
var d = locals[cdt][cdn]; var d = locals[cdt][cdn];
if (! d.item_code) {alert("please enter item code first"); return}; if (! d.item_code) {alert("please enter item code first"); return};
if (d.warehouse) { if (d.warehouse) {
arg = "{'item_code':'" + d.item_code + "','warehouse':'" + d.warehouse +"'}"; arg = "{'item_code':'" + d.item_code + "','warehouse':'" + d.warehouse +"'}";
get_server_fields('get_actual_qty',arg,'delivery_note_details',doc,cdt,cdn,1); get_server_fields('get_actual_qty',arg,'delivery_note_details',doc,cdt,cdn,1);
} }
} }
cur_frm.fields_dict['transporter_name'].get_query = function(doc) { cur_frm.fields_dict['transporter_name'].get_query = function(doc) {
return 'SELECT DISTINCT `tabSupplier`.`name` FROM `tabSupplier` WHERE `tabSupplier`.supplier_type = "transporter" AND `tabSupplier`.docstatus != 2 AND `tabSupplier`.%(key)s LIKE "%s" ORDER BY `tabSupplier`.`name` LIMIT 50'; return 'SELECT DISTINCT `tabSupplier`.`name` FROM `tabSupplier` WHERE `tabSupplier`.supplier_type = "transporter" AND `tabSupplier`.docstatus != 2 AND `tabSupplier`.%(key)s LIKE "%s" ORDER BY `tabSupplier`.`name` LIMIT 50';
} }
//-----------------------------------Make Sales Invoice---------------------------------------------- //-----------------------------------Make Sales Invoice----------------------------------------------
cur_frm.cscript['Make Sales Invoice'] = function() { cur_frm.cscript['Make Sales Invoice'] = function() {
var doc = cur_frm.doc var doc = cur_frm.doc
n = createLocal('Receivable Voucher'); n = createLocal('Receivable Voucher');
$c('dt_map', args={ $c('dt_map', args={
'docs':compress_doclist([locals['Receivable Voucher'][n]]), 'docs':compress_doclist([locals['Receivable Voucher'][n]]),
'from_doctype':doc.doctype, 'from_doctype':doc.doctype,
'to_doctype':'Receivable Voucher', 'to_doctype':'Receivable Voucher',
'from_docname':doc.name, 'from_docname':doc.name,
'from_to_list':"[['Delivery Note','Receivable Voucher'],['Delivery Note Detail','RV Detail'],['RV Tax Detail','RV Tax Detail'],['Sales Team','Sales Team']]" 'from_to_list':"[['Delivery Note','Receivable Voucher'],['Delivery Note Detail','RV Detail'],['RV Tax Detail','RV Tax Detail'],['Sales Team','Sales Team']]"
}, function(r,rt) { }, function(r,rt) {
loaddoc('Receivable Voucher', n); loaddoc('Receivable Voucher', n);
} }
); );
} }
//-----------------------------------Make Installation Note---------------------------------------------- //-----------------------------------Make Installation Note----------------------------------------------
cur_frm.cscript['Make Installation Note'] = function() { cur_frm.cscript['Make Installation Note'] = function() {
var doc = cur_frm.doc; var doc = cur_frm.doc;
if(doc.per_installed < 100){ if(doc.per_installed < 100){
n = createLocal('Installation Note'); n = createLocal('Installation Note');
$c('dt_map', args={ $c('dt_map', args={
'docs':compress_doclist([locals['Installation Note'][n]]), 'docs':compress_doclist([locals['Installation Note'][n]]),
'from_doctype':doc.doctype, 'from_doctype':doc.doctype,
'to_doctype':'Installation Note', 'to_doctype':'Installation Note',
'from_docname':doc.name, 'from_docname':doc.name,
'from_to_list':"[['Delivery Note','Installation Note'],['Delivery Note Detail','Installed Item Details']]" 'from_to_list':"[['Delivery Note','Installation Note'],['Delivery Note Detail','Installed Item Details']]"
}, function(r,rt) { }, function(r,rt) {
loaddoc('Installation Note', n); loaddoc('Installation Note', n);
} }
); );
} }
else if(doc.per_installed >= 100) else if(doc.per_installed >= 100)
msgprint("Item installation is already completed") msgprint("Item installation is already completed")
} }
//-----------------------------------Make Sales Invoice---------------------------------------------- //-----------------------------------Make Sales Invoice----------------------------------------------
cur_frm.cscript['Make Packing Slip'] = function() { cur_frm.cscript['Make Packing Slip'] = function() {
var doc = cur_frm.doc var doc = cur_frm.doc
n = createLocal('Packing Slip'); n = createLocal('Packing Slip');
$c('dt_map', args={ $c('dt_map', args={
'docs':compress_doclist([locals['Packing Slip'][n]]), 'docs':compress_doclist([locals['Packing Slip'][n]]),
'from_doctype':doc.doctype, 'from_doctype':doc.doctype,
'to_doctype':'Packing Slip', 'to_doctype':'Packing Slip',
'from_docname':doc.name, 'from_docname':doc.name,
'from_to_list':"[['Delivery Note','Packing Slip'],['Delivery Note Detail','Packing Slip Detail']]" 'from_to_list':"[['Delivery Note','Packing Slip'],['Delivery Note Detail','Packing Slip Detail']]"
}, function(r,rt) { }, function(r,rt) {
loaddoc('Packing Slip', n); loaddoc('Packing Slip', n);
} }
); );
} }
//get query select Territory //get query select Territory
//======================================================================================================================= //=======================================================================================================================
cur_frm.fields_dict['territory'].get_query = function(doc,cdt,cdn) { cur_frm.fields_dict['territory'].get_query = function(doc,cdt,cdn) {
return 'SELECT `tabTerritory`.`name`,`tabTerritory`.`parent_territory` FROM `tabTerritory` WHERE `tabTerritory`.`is_group` = "No" AND `tabTerritory`.`docstatus`!= 2 AND `tabTerritory`.%(key)s LIKE "%s" ORDER BY `tabTerritory`.`name` ASC LIMIT 50'; return 'SELECT `tabTerritory`.`name`,`tabTerritory`.`parent_territory` FROM `tabTerritory` WHERE `tabTerritory`.`is_group` = "No" AND `tabTerritory`.`docstatus`!= 2 AND `tabTerritory`.%(key)s LIKE "%s" ORDER BY `tabTerritory`.`name` ASC LIMIT 50';
} }
//------------------------for printing without amount---------- //------------------------for printing without amount----------
var set_print_hide= function(doc, cdt, cdn){ var set_print_hide= function(doc, cdt, cdn){
if (doc.print_without_amount) { if (doc.print_without_amount) {
fields['Delivery Note']['currency'].print_hide = 1; fields['Delivery Note']['currency'].print_hide = 1;
fields['Delivery Note Detail']['export_rate'].print_hide = 1; fields['Delivery Note Detail']['export_rate'].print_hide = 1;
fields['Delivery Note Detail']['adj_rate'].print_hide = 1; fields['Delivery Note Detail']['adj_rate'].print_hide = 1;
fields['Delivery Note Detail']['ref_rate'].print_hide = 1; fields['Delivery Note Detail']['ref_rate'].print_hide = 1;
fields['Delivery Note Detail']['export_amount'].print_hide = 1; fields['Delivery Note Detail']['export_amount'].print_hide = 1;
} else { } else {
fields['Delivery Note']['currency'].print_hide = 0; fields['Delivery Note']['currency'].print_hide = 0;
fields['Delivery Note Detail']['export_rate'].print_hide = 0; fields['Delivery Note Detail']['export_rate'].print_hide = 0;
fields['Delivery Note Detail']['adj_rate'].print_hide = 0; fields['Delivery Note Detail']['adj_rate'].print_hide = 0;
fields['Delivery Note Detail']['ref_rate'].print_hide = 0; fields['Delivery Note Detail']['ref_rate'].print_hide = 0;
fields['Delivery Note Detail']['export_amount'].print_hide = 0; fields['Delivery Note Detail']['export_amount'].print_hide = 0;
} }
} }
cur_frm.cscript.print_without_amount = function(doc, cdt, cdn) { cur_frm.cscript.print_without_amount = function(doc, cdt, cdn) {
set_print_hide(doc, cdt, cdn); set_print_hide(doc, cdt, cdn);
} }
//****************** For print sales order no and date************************* //****************** For print sales order no and date*************************
cur_frm.pformat.sales_order_no= function(doc, cdt, cdn){ cur_frm.pformat.sales_order_no= function(doc, cdt, cdn){
//function to make row of table //function to make row of table
var make_row = function(title,val1, val2, bold){ var make_row = function(title,val1, val2, bold){
var bstart = '<b>'; var bend = '</b>'; var bstart = '<b>'; var bend = '</b>';
return '<tr><td style="width:39%;">'+(bold?bstart:'')+title+(bold?bend:'')+'</td>' return '<tr><td style="width:39%;">'+(bold?bstart:'')+title+(bold?bend:'')+'</td>'
+'<td style="width:61%;text-align:left;">'+val1+(val2?' ('+dateutil.str_to_user(val2)+')':'')+'</td>' +'<td style="width:61%;text-align:left;">'+val1+(val2?' ('+dateutil.str_to_user(val2)+')':'')+'</td>'
+'</tr>' +'</tr>'
} }
out =''; out ='';
var cl = getchildren('Delivery Note Detail',doc.name,'delivery_note_details'); var cl = getchildren('Delivery Note Detail',doc.name,'delivery_note_details');
// outer table // outer table
var out='<div><table class="noborder" style="width:100%"><tr><td style="width: 50%"></td><td>'; var out='<div><table class="noborder" style="width:100%"><tr><td style="width: 50%"></td><td>';
// main table // main table
out +='<table class="noborder" style="width:100%">'; out +='<table class="noborder" style="width:100%">';
// add rows // add rows
if(cl.length){ if(cl.length){
prevdoc_list = new Array(); prevdoc_list = new Array();
for(var i=0;i<cl.length;i++){ for(var i=0;i<cl.length;i++){
if(cl[i].prevdoc_doctype == 'Sales Order' && cl[i].prevdoc_docname && prevdoc_list.indexOf(cl[i].prevdoc_docname) == -1) { if(cl[i].prevdoc_doctype == 'Sales Order' && cl[i].prevdoc_docname && prevdoc_list.indexOf(cl[i].prevdoc_docname) == -1) {
prevdoc_list.push(cl[i].prevdoc_docname); prevdoc_list.push(cl[i].prevdoc_docname);
if(prevdoc_list.length ==1) if(prevdoc_list.length ==1)
out += make_row(cl[i].prevdoc_doctype, cl[i].prevdoc_docname, cl[i].prevdoc_date,0); out += make_row(cl[i].prevdoc_doctype, cl[i].prevdoc_docname, cl[i].prevdoc_date,0);
else else
out += make_row('', cl[i].prevdoc_docname, cl[i].prevdoc_date,0); out += make_row('', cl[i].prevdoc_docname, cl[i].prevdoc_date,0);
} }
} }
} }
out +='</table></td></tr></table></div>'; out +='</table></td></tr></table></div>';
return out; return out;
} }
$import(Notification Control) $import(Notification Control)

View File

@ -100,8 +100,18 @@ class DocType(TransactionBase):
# ================================================================================ # ================================================================================
# ***************** Get Item Details ****************************** # ***************** Get Item Details ******************************
def get_item_details(self, item_code): def get_item_details(self, item_code=None):
return get_obj('Sales Common').get_item_details(item_code, self) if item_code:
return get_obj('Sales Common').get_item_details(item_code, self)
else:
obj = get_obj('Sales Common')
for doc in self.doclist:
if doc.fields.get('item_code'):
ret = obj.get_item_details(doc.item_code, self)
for r in ret:
if not doc.fields.get(r):
doc.fields[r] = ret[r]
# *** Re-calculates Basic Rate & amount based on Price List Selected *** # *** Re-calculates Basic Rate & amount based on Price List Selected ***
def get_adj_percent(self, arg=''): def get_adj_percent(self, arg=''):

View File

@ -9,17 +9,19 @@ $import(SMS Control)
//========================== On Load ================================================================ //========================== On Load ================================================================
cur_frm.cscript.onload = function(doc, cdt, cdn) { cur_frm.cscript.onload = function(doc, cdt, cdn) {
if(!doc.fiscal_year && doc.__islocal){ set_default_values(doc);} if(!doc.fiscal_year && doc.__islocal){ set_default_values(doc);}
if (!doc.posting_date) doc.posting_date = dateutil.obj_to_str(new Date()); if (!doc.posting_date) doc.posting_date = dateutil.obj_to_str(new Date());
if (!doc.transaction_date) doc.transaction_date = dateutil.obj_to_str(new Date()); if (!doc.transaction_date) doc.transaction_date = dateutil.obj_to_str(new Date());
if (!doc.status) doc.status = 'Draft'; if (!doc.status) doc.status = 'Draft';
if(doc.__islocal){ if(doc.__islocal){
hide_field(['supplier_name','supplier_address','contact_person','address_display','contact_display','contact_mobile','contact_email']); hide_field(['supplier_name','supplier_address','contact_person','address_display','contact_display','contact_mobile','contact_email']);
} }
if(doc.supplier) unhide_field(['supplier_name','supplier_address','contact_person','address_display','contact_display','contact_mobile','contact_email']); if(doc.supplier) unhide_field(['supplier_name','supplier_address','contact_person','address_display','contact_display','contact_mobile','contact_email']);
// defined in purchase_common.js
cur_frm.cscript.update_item_details(doc, cdt, cdn);
} }
cur_frm.cscript.onload_post_render = function(doc, dt, dn) { cur_frm.cscript.onload_post_render = function(doc, dt, dn) {
@ -31,198 +33,198 @@ cur_frm.cscript.onload_post_render = function(doc, dt, dn) {
//========================== Refresh =============================================================== //========================== Refresh ===============================================================
cur_frm.cscript.refresh = function(doc, cdt, cdn) { cur_frm.cscript.refresh = function(doc, cdt, cdn) {
// Unhide Fields in Next Steps // Unhide Fields in Next Steps
// --------------------------------- // ---------------------------------
cur_frm.clear_custom_buttons(); cur_frm.clear_custom_buttons();
if(doc.docstatus == 1){ if(doc.docstatus == 1){
var ch = getchildren('Purchase Receipt Detail',doc.name,'purchase_receipt_details'); var ch = getchildren('Purchase Receipt Detail',doc.name,'purchase_receipt_details');
allow_billing = 0; allow_billing = 0;
for(var i in ch){ for(var i in ch){
if(ch[i].qty > ch[i].billed_qty) allow_billing = 1; if(ch[i].qty > ch[i].billed_qty) allow_billing = 1;
} }
cur_frm.add_custom_button('Make Purchase Invoice', cur_frm.cscript['Make Purchase Invoice']); cur_frm.add_custom_button('Make Purchase Invoice', cur_frm.cscript['Make Purchase Invoice']);
cur_frm.add_custom_button('Send SMS', cur_frm.cscript['Send SMS']); cur_frm.add_custom_button('Send SMS', cur_frm.cscript['Send SMS']);
} }
else{ else{
hide_field(['Repair Purchase Receipt']); hide_field(['Repair Purchase Receipt']);
} }
} }
//Supplier //Supplier
cur_frm.cscript.supplier = function(doc,dt,dn) { cur_frm.cscript.supplier = function(doc,dt,dn) {
if(doc.supplier) get_server_fields('get_default_supplier_address', JSON.stringify({supplier: doc.supplier}),'', doc, dt, dn, 1); if(doc.supplier) get_server_fields('get_default_supplier_address', JSON.stringify({supplier: doc.supplier}),'', doc, dt, dn, 1);
if(doc.supplier) unhide_field(['supplier_name','supplier_address','contact_person','address_display','contact_display','contact_mobile','contact_email']); if(doc.supplier) unhide_field(['supplier_name','supplier_address','contact_person','address_display','contact_display','contact_mobile','contact_email']);
} }
cur_frm.cscript.supplier_address = cur_frm.cscript.contact_person = function(doc,dt,dn) { cur_frm.cscript.supplier_address = cur_frm.cscript.contact_person = function(doc,dt,dn) {
if(doc.supplier) get_server_fields('get_supplier_address', JSON.stringify({supplier: doc.supplier, address: doc.supplier_address, contact: doc.contact_person}),'', doc, dt, dn, 1); if(doc.supplier) get_server_fields('get_supplier_address', JSON.stringify({supplier: doc.supplier, address: doc.supplier_address, contact: doc.contact_person}),'', doc, dt, dn, 1);
} }
cur_frm.fields_dict['supplier_address'].get_query = function(doc, cdt, cdn) { cur_frm.fields_dict['supplier_address'].get_query = function(doc, cdt, cdn) {
return 'SELECT name,address_line1,city FROM tabAddress WHERE supplier = "'+ doc.supplier +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50'; return 'SELECT name,address_line1,city FROM tabAddress WHERE supplier = "'+ doc.supplier +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
} }
cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) { cur_frm.fields_dict['contact_person'].get_query = function(doc, cdt, cdn) {
return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE supplier = "'+ doc.supplier +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50'; return 'SELECT name,CONCAT(first_name," ",ifnull(last_name,"")) As FullName,department,designation FROM tabContact WHERE supplier = "'+ doc.supplier +'" AND docstatus != 2 AND name LIKE "%s" ORDER BY name ASC LIMIT 50';
} }
cur_frm.fields_dict.supplier_address.on_new = function(dn) { cur_frm.fields_dict.supplier_address.on_new = function(dn) {
locals['Address'][dn].supplier = locals[cur_frm.doctype][cur_frm.docname].supplier; locals['Address'][dn].supplier = locals[cur_frm.doctype][cur_frm.docname].supplier;
locals['Address'][dn].supplier_name = locals[cur_frm.doctype][cur_frm.docname].supplier_name; locals['Address'][dn].supplier_name = locals[cur_frm.doctype][cur_frm.docname].supplier_name;
} }
cur_frm.fields_dict.contact_person.on_new = function(dn) { cur_frm.fields_dict.contact_person.on_new = function(dn) {
locals['Contact'][dn].supplier = locals[cur_frm.doctype][cur_frm.docname].supplier; locals['Contact'][dn].supplier = locals[cur_frm.doctype][cur_frm.docname].supplier;
locals['Contact'][dn].supplier_name = locals[cur_frm.doctype][cur_frm.docname].supplier_name; locals['Contact'][dn].supplier_name = locals[cur_frm.doctype][cur_frm.docname].supplier_name;
} }
// Get Purchase Order Button // Get Purchase Order Button
// ----------------- // -----------------
cur_frm.cscript['Pull Purchase Order Details'] = function(doc, dt, dn) { cur_frm.cscript['Pull Purchase Order Details'] = function(doc, dt, dn) {
var callback = function(r,rt) { var callback = function(r,rt) {
unhide_field(['supplier_address','contact_person','supplier_name','address_display', 'contact_display', 'contact_mobile','contact_email']); unhide_field(['supplier_address','contact_person','supplier_name','address_display', 'contact_display', 'contact_mobile','contact_email']);
refresh_many(['supplier','supplier_address','contact_person', 'supplier_name', 'address_display', 'contact_display','contact_mobile', 'contact_email', 'purchase_receipt_details', 'purchase_tax_details']); refresh_many(['supplier','supplier_address','contact_person', 'supplier_name', 'address_display', 'contact_display','contact_mobile', 'contact_email', 'purchase_receipt_details', 'purchase_tax_details']);
} }
$c_obj(make_doclist(dt,dn),'get_po_details','',callback); $c_obj(make_doclist(dt,dn),'get_po_details','',callback);
} }
//================ create new contact ============================================================================ //================ create new contact ============================================================================
cur_frm.cscript.new_contact = function(){ cur_frm.cscript.new_contact = function(){
tn = createLocal('Contact'); tn = createLocal('Contact');
locals['Contact'][tn].is_supplier = 1; locals['Contact'][tn].is_supplier = 1;
if(doc.supplier) locals['Contact'][tn].supplier = doc.supplier; if(doc.supplier) locals['Contact'][tn].supplier = doc.supplier;
loaddoc('Contact', tn); loaddoc('Contact', tn);
} }
//======================= posting date ============================= //======================= posting date =============================
cur_frm.cscript.transaction_date = function(doc,cdt,cdn){ cur_frm.cscript.transaction_date = function(doc,cdt,cdn){
if(doc.__islocal){ if(doc.__islocal){
cur_frm.cscript.get_default_schedule_date(doc); cur_frm.cscript.get_default_schedule_date(doc);
} }
} }
// ***************** Get project name ***************** // ***************** Get project name *****************
cur_frm.fields_dict['purchase_receipt_details'].grid.get_field('project_name').get_query = function(doc, cdt, cdn) { cur_frm.fields_dict['purchase_receipt_details'].grid.get_field('project_name').get_query = function(doc, cdt, cdn) {
return 'SELECT `tabProject`.name FROM `tabProject` WHERE `tabProject`.status = "Open" AND `tabProject`.name LIKE "%s" ORDER BY `tabProject`.name ASC LIMIT 50'; return 'SELECT `tabProject`.name FROM `tabProject` WHERE `tabProject`.status = "Open" AND `tabProject`.name LIKE "%s" ORDER BY `tabProject`.name ASC LIMIT 50';
} }
//========================= Overloaded query for link batch_no ============================================================= //========================= Overloaded query for link batch_no =============================================================
cur_frm.fields_dict['purchase_receipt_details'].grid.get_field('batch_no').get_query= function(doc, cdt, cdn) { cur_frm.fields_dict['purchase_receipt_details'].grid.get_field('batch_no').get_query= function(doc, cdt, cdn) {
var d = locals[cdt][cdn]; var d = locals[cdt][cdn];
if(d.item_code){ if(d.item_code){
return "SELECT tabBatch.name, tabBatch.description FROM tabBatch WHERE tabBatch.docstatus != 2 AND tabBatch.item = '"+ d.item_code +"' AND `tabBatch`.`name` like '%s' ORDER BY `tabBatch`.`name` DESC LIMIT 50" return "SELECT tabBatch.name, tabBatch.description FROM tabBatch WHERE tabBatch.docstatus != 2 AND tabBatch.item = '"+ d.item_code +"' AND `tabBatch`.`name` like '%s' ORDER BY `tabBatch`.`name` DESC LIMIT 50"
} }
else{ else{
alert("Please enter Item Code."); alert("Please enter Item Code.");
} }
} }
cur_frm.cscript.select_print_heading = function(doc,cdt,cdn){ cur_frm.cscript.select_print_heading = function(doc,cdt,cdn){
if(doc.select_print_heading){ if(doc.select_print_heading){
// print heading // print heading
cur_frm.pformat.print_heading = doc.select_print_heading; cur_frm.pformat.print_heading = doc.select_print_heading;
} }
else else
cur_frm.pformat.print_heading = "Purchase Receipt"; cur_frm.pformat.print_heading = "Purchase Receipt";
} }
// ***************** Get Print Heading ***************** // ***************** Get Print Heading *****************
cur_frm.fields_dict['select_print_heading'].get_query = function(doc, cdt, cdn) { cur_frm.fields_dict['select_print_heading'].get_query = function(doc, cdt, cdn) {
return 'SELECT `tabPrint Heading`.name FROM `tabPrint Heading` WHERE `tabPrint Heading`.docstatus !=2 AND `tabPrint Heading`.name LIKE "%s" ORDER BY `tabPrint Heading`.name ASC LIMIT 50'; return 'SELECT `tabPrint Heading`.name FROM `tabPrint Heading` WHERE `tabPrint Heading`.docstatus !=2 AND `tabPrint Heading`.name LIKE "%s" ORDER BY `tabPrint Heading`.name ASC LIMIT 50';
} }
//========================= Received Qty ============================================================= //========================= Received Qty =============================================================
cur_frm.cscript.received_qty = function(doc, cdt, cdn) { cur_frm.cscript.received_qty = function(doc, cdt, cdn) {
var d = locals[cdt][cdn]; var d = locals[cdt][cdn];
ret = { ret = {
'qty' : 0, 'qty' : 0,
'stock_qty': 0, 'stock_qty': 0,
'rejected_qty' : 0 'rejected_qty' : 0
} }
set_multiple('Purchase Receipt Detail', cdn, ret, 'purchase_receipt_details'); set_multiple('Purchase Receipt Detail', cdn, ret, 'purchase_receipt_details');
cur_frm.cscript.calc_amount(doc, 2); cur_frm.cscript.calc_amount(doc, 2);
} }
//======================== Qty (Accepted Qty) ========================================================= //======================== Qty (Accepted Qty) =========================================================
cur_frm.cscript.qty = function(doc, cdt, cdn) { cur_frm.cscript.qty = function(doc, cdt, cdn) {
var d = locals[cdt][cdn]; var d = locals[cdt][cdn];
// Step 1 :=> Check If Qty > Received Qty // Step 1 :=> Check If Qty > Received Qty
if (flt(d.qty) > flt(d.received_qty)) { if (flt(d.qty) > flt(d.received_qty)) {
alert("Accepted Qty cannot be greater than Received Qty") alert("Accepted Qty cannot be greater than Received Qty")
ret = { ret = {
'qty' : 0, 'qty' : 0,
'stock_qty': 0, 'stock_qty': 0,
'rejected_qty' : 0 'rejected_qty' : 0
} }
// => Set Qty = 0 and rejected_qty = 0 // => Set Qty = 0 and rejected_qty = 0
set_multiple('Purchase Receipt Detail', cdn, ret, 'purchase_receipt_details'); set_multiple('Purchase Receipt Detail', cdn, ret, 'purchase_receipt_details');
cur_frm.cscript.calc_amount(doc, 2); cur_frm.cscript.calc_amount(doc, 2);
// => Return // => Return
return return
} }
// Step 2 :=> Check IF Qty <= REceived Qty // Step 2 :=> Check IF Qty <= REceived Qty
else { else {
ret = { ret = {
'rejected_qty':flt(d.received_qty) - flt(d.qty) 'rejected_qty':flt(d.received_qty) - flt(d.qty)
} }
// => Set Rejected Qty = Received Qty - Qty // => Set Rejected Qty = Received Qty - Qty
set_multiple('Purchase Receipt Detail', cdn, ret, 'purchase_receipt_details'); set_multiple('Purchase Receipt Detail', cdn, ret, 'purchase_receipt_details');
// => Calculate Amount // => Calculate Amount
cur_frm.cscript.calc_amount(doc, 2); cur_frm.cscript.calc_amount(doc, 2);
cur_frm.cscript.update_stock_qty(doc,cdt,cdn); cur_frm.cscript.update_stock_qty(doc,cdt,cdn);
} }
} }
//======================== Rejected Qty ========================================================= //======================== Rejected Qty =========================================================
cur_frm.cscript.rejected_qty = function(doc, cdt, cdn) { cur_frm.cscript.rejected_qty = function(doc, cdt, cdn) {
var d = locals[cdt][cdn]; var d = locals[cdt][cdn];
// Step 1 :=> Check If Rejected Qty > Received Qty // Step 1 :=> Check If Rejected Qty > Received Qty
if (flt(d.rejected_qty) > flt(d.received_qty)) { if (flt(d.rejected_qty) > flt(d.received_qty)) {
alert("Rejected Qty cannot be greater than Received Qty") alert("Rejected Qty cannot be greater than Received Qty")
ret = { ret = {
'qty' : 0, 'qty' : 0,
'stock_qty': 0, 'stock_qty': 0,
'rejected_qty' : 0 'rejected_qty' : 0
} }
// => Set Qty = 0 and rejected_qty = 0 // => Set Qty = 0 and rejected_qty = 0
set_multiple('Purchase Receipt Detail', cdn, ret, 'purchase_receipt_details'); set_multiple('Purchase Receipt Detail', cdn, ret, 'purchase_receipt_details');
cur_frm.cscript.calc_amount(doc, 2); cur_frm.cscript.calc_amount(doc, 2);
// => Return // => Return
return return
} }
// Step 2 :=> Check IF Rejected Qty <= REceived Qty // Step 2 :=> Check IF Rejected Qty <= REceived Qty
else { else {
ret = { ret = {
'qty':flt(d.received_qty) - flt(d.rejected_qty) 'qty':flt(d.received_qty) - flt(d.rejected_qty)
} }
// => Set Qty = Received Qty - Rejected Qty // => Set Qty = Received Qty - Rejected Qty
set_multiple('Purchase Receipt Detail', cdn, ret, 'purchase_receipt_details'); set_multiple('Purchase Receipt Detail', cdn, ret, 'purchase_receipt_details');
// Calculate Amount // Calculate Amount
cur_frm.cscript.calc_amount(doc, 2); cur_frm.cscript.calc_amount(doc, 2);
cur_frm.cscript.update_stock_qty(doc,cdt,cdn); cur_frm.cscript.update_stock_qty(doc,cdt,cdn);
} }
} }
//================================= Purchase Order No Get Query ==================================== //================================= Purchase Order No Get Query ====================================
cur_frm.fields_dict['purchase_order_no'].get_query = function(doc) { cur_frm.fields_dict['purchase_order_no'].get_query = function(doc) {
if (doc.supplier) if (doc.supplier)
return 'SELECT DISTINCT `tabPurchase Order`.`name` FROM `tabPurchase Order` WHERE `tabPurchase Order`.`supplier` = "' +doc.supplier + '" and`tabPurchase Order`.`docstatus` = 1 and `tabPurchase Order`.`status` != "Stopped" and ifnull(`tabPurchase Order`.`per_received`, 0) < 100 and `tabPurchase Order`.`currency` = ifnull("' +doc.currency+ '","") and `tabPurchase Order`.company = "'+ doc.company +'" and `tabPurchase Order`.%(key)s LIKE "%s" ORDER BY `tabPurchase Order`.`name` DESC LIMIT 50'; return 'SELECT DISTINCT `tabPurchase Order`.`name` FROM `tabPurchase Order` WHERE `tabPurchase Order`.`supplier` = "' +doc.supplier + '" and`tabPurchase Order`.`docstatus` = 1 and `tabPurchase Order`.`status` != "Stopped" and ifnull(`tabPurchase Order`.`per_received`, 0) < 100 and `tabPurchase Order`.`currency` = ifnull("' +doc.currency+ '","") and `tabPurchase Order`.company = "'+ doc.company +'" and `tabPurchase Order`.%(key)s LIKE "%s" ORDER BY `tabPurchase Order`.`name` DESC LIMIT 50';
else else
return 'SELECT DISTINCT `tabPurchase Order`.`name` FROM `tabPurchase Order` WHERE `tabPurchase Order`.`docstatus` = 1 and `tabPurchase Order`.`company` = "'+ doc.company +'" and `tabPurchase Order`.`status` != "Stopped" and ifnull(`tabPurchase Order`.`per_received`, 0) < 100 and `tabPurchase Order`.%(key)s LIKE "%s" ORDER BY `tabPurchase Order`.`name` DESC LIMIT 50'; return 'SELECT DISTINCT `tabPurchase Order`.`name` FROM `tabPurchase Order` WHERE `tabPurchase Order`.`docstatus` = 1 and `tabPurchase Order`.`company` = "'+ doc.company +'" and `tabPurchase Order`.`status` != "Stopped" and ifnull(`tabPurchase Order`.`per_received`, 0) < 100 and `tabPurchase Order`.%(key)s LIKE "%s" ORDER BY `tabPurchase Order`.`name` DESC LIMIT 50';
} }
// QA INspection report get_query // QA INspection report get_query
//--------------------------------- //---------------------------------
cur_frm.fields_dict.purchase_receipt_details.grid.get_field("qa_no").get_query = function(doc) { cur_frm.fields_dict.purchase_receipt_details.grid.get_field("qa_no").get_query = function(doc) {
return 'SELECT `tabQA Inspection Report`.name FROM `tabQA Inspection Report` WHERE `tabQA Inspection Report`.docstatus = 1 AND `tabQA Inspection Report`.%(key)s LIKE "%s"'; return 'SELECT `tabQA Inspection Report`.name FROM `tabQA Inspection Report` WHERE `tabQA Inspection Report`.docstatus = 1 AND `tabQA Inspection Report`.%(key)s LIKE "%s"';
} }
// On Button Click Functions // On Button Click Functions
@ -231,17 +233,17 @@ cur_frm.fields_dict.purchase_receipt_details.grid.get_field("qa_no").get_query =
// ================================ Make Purchase Invoice ========================================== // ================================ Make Purchase Invoice ==========================================
cur_frm.cscript['Make Purchase Invoice'] = function() { cur_frm.cscript['Make Purchase Invoice'] = function() {
n = createLocal('Payable Voucher'); n = createLocal('Payable Voucher');
$c('dt_map', args={ $c('dt_map', args={
'docs':compress_doclist([locals['Payable Voucher'][n]]), 'docs':compress_doclist([locals['Payable Voucher'][n]]),
'from_doctype': cur_frm.doc.doctype, 'from_doctype': cur_frm.doc.doctype,
'to_doctype':'Payable Voucher', 'to_doctype':'Payable Voucher',
'from_docname': cur_frm.doc.name, 'from_docname': cur_frm.doc.name,
'from_to_list':"[['Purchase Receipt','Payable Voucher'],['Purchase Receipt Detail','PV Detail']]" 'from_to_list':"[['Purchase Receipt','Payable Voucher'],['Purchase Receipt Detail','PV Detail'],['Purchase Tax Detail','Purchase Tax Detail']]"
}, function(r,rt) { }, function(r,rt) {
loaddoc('Payable Voucher', n); loaddoc('Payable Voucher', n);
} }
); );
} }
@ -249,43 +251,43 @@ cur_frm.cscript['Make Purchase Invoice'] = function() {
//****************** For print sales order no and date************************* //****************** For print sales order no and date*************************
cur_frm.pformat.purchase_order_no = function(doc, cdt, cdn){ cur_frm.pformat.purchase_order_no = function(doc, cdt, cdn){
//function to make row of table //function to make row of table
var make_row = function(title,val1, val2, bold){ var make_row = function(title,val1, val2, bold){
var bstart = '<b>'; var bend = '</b>'; var bstart = '<b>'; var bend = '</b>';
return '<tr><td style="width:39%;">'+(bold?bstart:'')+title+(bold?bend:'')+'</td>' return '<tr><td style="width:39%;">'+(bold?bstart:'')+title+(bold?bend:'')+'</td>'
+'<td style="width:61%;text-align:left;">'+val1+(val2?' ('+dateutil.str_to_user(val2)+')':'')+'</td>' +'<td style="width:61%;text-align:left;">'+val1+(val2?' ('+dateutil.str_to_user(val2)+')':'')+'</td>'
+'</tr>' +'</tr>'
} }
out =''; out ='';
var cl = getchildren('Purchase Receipt Detail',doc.name,'purchase_receipt_details'); var cl = getchildren('Purchase Receipt Detail',doc.name,'purchase_receipt_details');
// outer table // outer table
var out='<div><table class="noborder" style="width:100%"><tr><td style="width: 50%"></td><td>'; var out='<div><table class="noborder" style="width:100%"><tr><td style="width: 50%"></td><td>';
// main table // main table
out +='<table class="noborder" style="width:100%">'; out +='<table class="noborder" style="width:100%">';
// add rows // add rows
if(cl.length){ if(cl.length){
prevdoc_list = new Array(); prevdoc_list = new Array();
for(var i=0;i<cl.length;i++){ for(var i=0;i<cl.length;i++){
if(cl[i].prevdoc_doctype == 'Purchase Order' && cl[i].prevdoc_docname && prevdoc_list.indexOf(cl[i].prevdoc_docname) == -1) { if(cl[i].prevdoc_doctype == 'Purchase Order' && cl[i].prevdoc_docname && prevdoc_list.indexOf(cl[i].prevdoc_docname) == -1) {
prevdoc_list.push(cl[i].prevdoc_docname); prevdoc_list.push(cl[i].prevdoc_docname);
if(prevdoc_list.length ==1) if(prevdoc_list.length ==1)
out += make_row(cl[i].prevdoc_doctype, cl[i].prevdoc_docname, cl[i].prevdoc_date,0); out += make_row(cl[i].prevdoc_doctype, cl[i].prevdoc_docname, cl[i].prevdoc_date,0);
else else
out += make_row('', cl[i].prevdoc_docname, cl[i].prevdoc_date,0); out += make_row('', cl[i].prevdoc_docname, cl[i].prevdoc_date,0);
} }
} }
} }
out +='</table></td></tr></table></div>'; out +='</table></td></tr></table></div>';
return out; return out;
} }
$import(Notification Control) $import(Notification Control)

View File

@ -19,407 +19,422 @@ convert_to_lists = webnotes.conn.convert_to_lists
from utilities.transaction_base import TransactionBase from utilities.transaction_base import TransactionBase
class DocType(TransactionBase): class DocType(TransactionBase):
def __init__(self, doc, doclist=[]): def __init__(self, doc, doclist=[]):
self.doc = doc self.doc = doc
self.doclist = doclist self.doclist = doclist
self.defaults = get_defaults() self.defaults = get_defaults()
self.tname = 'Purchase Receipt Detail' self.tname = 'Purchase Receipt Detail'
self.fname = 'purchase_receipt_details' self.fname = 'purchase_receipt_details'
self.count = 0 self.count = 0
# Autoname # Autoname
# --------- # ---------
def autoname(self): def autoname(self):
self.doc.name = make_autoname(self.doc.naming_series+'.#####') self.doc.name = make_autoname(self.doc.naming_series+'.#####')
# Client Trigger Functions # Client Trigger Functions
#---------------------------------------------------------------------------------------------------- #----------------------------------------------------------------------------------------------------
def get_default_schedule_date(self): def get_default_schedule_date(self):
get_obj(dt = 'Purchase Common').get_default_schedule_date(self) get_obj(dt = 'Purchase Common').get_default_schedule_date(self)
#-----------------Validation For Fiscal Year------------------------ #-----------------Validation For Fiscal Year------------------------
def validate_fiscal_year(self): def validate_fiscal_year(self):
get_obj(dt = 'Purchase Common').validate_fiscal_year(self.doc.fiscal_year,self.doc.transaction_date,'Transaction Date') get_obj(dt = 'Purchase Common').validate_fiscal_year(self.doc.fiscal_year,self.doc.transaction_date,'Transaction Date')
# Get Item Details # Get Item Details
def get_item_details(self, arg = ''): def get_item_details(self, arg = ''):
return get_obj(dt='Purchase Common').get_item_details(self,arg) if arg:
return get_obj(dt='Purchase Common').get_item_details(self,arg)
# Get UOM Details else:
def get_uom_details(self, arg = ''): import json
return get_obj(dt='Purchase Common').get_uom_details(arg) obj = get_obj('Purchase Common')
for doc in self.doclist:
# GET TERMS & CONDITIONS if doc.fields.get('item_code'):
# ===================================================================================== temp = {
def get_tc_details(self): 'item_code': doc.fields.get('item_code'),
return get_obj('Purchase Common').get_tc_details(self) 'warehouse': doc.fields.get('warehouse')
}
# get available qty at warehouse ret = obj.get_item_details(self, json.dumps(temp))
def get_bin_details(self, arg = ''): for r in ret:
return get_obj(dt='Purchase Common').get_bin_details(arg) if not doc.fields.get(r):
doc.fields[r] = ret[r]
# Pull Purchase Order
def get_po_details(self):
self.validate_prev_docname()
get_obj('DocType Mapper', 'Purchase Order-Purchase Receipt').dt_map('Purchase Order', 'Purchase Receipt', self.doc.purchase_order_no, self.doc, self.doclist, "[['Purchase Order','Purchase Receipt'],['PO Detail', 'Purchase Receipt Detail'],['Purchase Tax Detail','Purchase Tax Detail']]")
# validate if PO has been pulled twice
def validate_prev_docname(self):
for d in getlist(self.doclist, 'purchase_receipt_details'):
if self.doc.purchase_order_no and d.prevdoc_docname and self.doc.purchase_order_no == d.prevdoc_docname:
msgprint(cstr(self.doc.purchase_order_no) + " Purchase Order details have already been pulled. ")
raise Exception
# validation # Get UOM Details
#------------------------------------------------------------------------------------------------------------- def get_uom_details(self, arg = ''):
# validate accepted and rejected qty return get_obj(dt='Purchase Common').get_uom_details(arg)
def validate_accepted_rejected_qty(self):
for d in getlist(self.doclist, "purchase_receipt_details"):
# If Reject Qty than Rejected warehouse is mandatory # GET TERMS & CONDITIONS
if flt(d.rejected_qty) and (not self.doc.rejected_warehouse): # =====================================================================================
msgprint("Rejected Warehouse is necessary if there are rejections. See 'Receipt Items'") def get_tc_details(self):
raise Exception return get_obj('Purchase Common').get_tc_details(self)
# Check Received Qty = Accepted Qty + Rejected Qty # get available qty at warehouse
if ((flt(d.qty) + flt(d.rejected_qty)) != flt(d.received_qty)): def get_bin_details(self, arg = ''):
return get_obj(dt='Purchase Common').get_bin_details(arg)
msgprint("Sum of Accepted Qty and Rejected Qty must be equal to Received quantity. Error for Item: " + cstr(d.item_code)) # Pull Purchase Order
raise Exception def get_po_details(self):
self.validate_prev_docname()
get_obj('DocType Mapper', 'Purchase Order-Purchase Receipt').dt_map('Purchase Order', 'Purchase Receipt', self.doc.purchase_order_no, self.doc, self.doclist, "[['Purchase Order','Purchase Receipt'],['PO Detail', 'Purchase Receipt Detail'],['Purchase Tax Detail','Purchase Tax Detail']]")
# validate if PO has been pulled twice
def validate_prev_docname(self):
for d in getlist(self.doclist, 'purchase_receipt_details'):
if self.doc.purchase_order_no and d.prevdoc_docname and self.doc.purchase_order_no == d.prevdoc_docname:
msgprint(cstr(self.doc.purchase_order_no) + " Purchase Order details have already been pulled. ")
raise Exception
def validate_challan_no(self): # validation
"Validate if same challan no exists for same supplier in a submitted purchase receipt" #-------------------------------------------------------------------------------------------------------------
if self.doc.challan_no: # validate accepted and rejected qty
exists = webnotes.conn.sql(""" def validate_accepted_rejected_qty(self):
SELECT name FROM `tabPurchase Receipt` for d in getlist(self.doclist, "purchase_receipt_details"):
WHERE name!=%s AND supplier=%s AND challan_no=%s
# If Reject Qty than Rejected warehouse is mandatory
if flt(d.rejected_qty) and (not self.doc.rejected_warehouse):
msgprint("Rejected Warehouse is necessary if there are rejections. See 'Receipt Items'")
raise Exception
# Check Received Qty = Accepted Qty + Rejected Qty
if ((flt(d.qty) + flt(d.rejected_qty)) != flt(d.received_qty)):
msgprint("Sum of Accepted Qty and Rejected Qty must be equal to Received quantity. Error for Item: " + cstr(d.item_code))
raise Exception
def validate_challan_no(self):
"Validate if same challan no exists for same supplier in a submitted purchase receipt"
if self.doc.challan_no:
exists = webnotes.conn.sql("""
SELECT name FROM `tabPurchase Receipt`
WHERE name!=%s AND supplier=%s AND challan_no=%s
AND docstatus=1""", (self.doc.name, self.doc.supplier, self.doc.challan_no)) AND docstatus=1""", (self.doc.name, self.doc.supplier, self.doc.challan_no))
if exists: if exists:
webnotes.msgprint("Another Purchase Receipt using the same Challan No. already exists.\ webnotes.msgprint("Another Purchase Receipt using the same Challan No. already exists.\
Please enter a valid Challan No.", raise_exception=1) Please enter a valid Challan No.", raise_exception=1)
# update valuation rate # update valuation rate
def update_valuation_rate(self): def update_valuation_rate(self):
total_b_cost = flt(self.doc.buying_cost_transport) + flt(self.doc.buying_cost_taxes) + flt(self.doc.buying_cost_other) total_b_cost = flt(self.doc.buying_cost_transport) + flt(self.doc.buying_cost_taxes) + flt(self.doc.buying_cost_other)
for d in getlist(self.doclist, 'purchase_receipt_details'): for d in getlist(self.doclist, 'purchase_receipt_details'):
if flt(self.doc.net_total) and flt(d.qty): if flt(self.doc.net_total) and flt(d.qty):
#d.valuation_rate = (flt(d.purchase_rate) + ((flt(d.amount) * (total_b_cost)) / (self.doc.net_total * flt(d.qty))) + (flt(d.rm_supp_cost) / flt(d.qty))) / flt(d.conversion_factor) #d.valuation_rate = (flt(d.purchase_rate) + ((flt(d.amount) * (total_b_cost)) / (self.doc.net_total * flt(d.qty))) + (flt(d.rm_supp_cost) / flt(d.qty))) / flt(d.conversion_factor)
d.valuation_rate = (flt(d.purchase_rate) + ((flt(d.amount) * (total_b_cost)) / (self.doc.net_total * flt(d.qty))) + (flt(d.rm_supp_cost) / flt(d.qty)) + (flt(d.item_tax_amount)/flt(d.qty))) / flt(d.conversion_factor) d.valuation_rate = (flt(d.purchase_rate) + ((flt(d.amount) * (total_b_cost)) / (self.doc.net_total * flt(d.qty))) + (flt(d.rm_supp_cost) / flt(d.qty)) + (flt(d.item_tax_amount)/flt(d.qty))) / flt(d.conversion_factor)
# Check for Stopped status # Check for Stopped status
def check_for_stopped_status(self, pc_obj): def check_for_stopped_status(self, pc_obj):
check_list =[] check_list =[]
for d in getlist(self.doclist, 'purchase_receipt_details'): for d in getlist(self.doclist, 'purchase_receipt_details'):
if d.fields.has_key('prevdoc_docname') and d.prevdoc_docname and d.prevdoc_docname not in check_list: if d.fields.has_key('prevdoc_docname') and d.prevdoc_docname and d.prevdoc_docname not in check_list:
check_list.append(d.prevdoc_docname) check_list.append(d.prevdoc_docname)
pc_obj.check_for_stopped_status( d.prevdoc_doctype, d.prevdoc_docname) pc_obj.check_for_stopped_status( d.prevdoc_doctype, d.prevdoc_docname)
#check in manage account if purchase order required or not. #check in manage account if purchase order required or not.
# ==================================================================================== # ====================================================================================
def po_required(self): def po_required(self):
res = sql("select value from `tabSingles` where doctype = 'Manage Account' and field = 'po_required'") res = sql("select value from `tabSingles` where doctype = 'Manage Account' and field = 'po_required'")
if res and res[0][0]== 'Yes': if res and res[0][0]== 'Yes':
for d in getlist(self.doclist,'purchase_receipt_details'): for d in getlist(self.doclist,'purchase_receipt_details'):
if not d.prevdoc_docname: if not d.prevdoc_docname:
msgprint("Purchse Order No. required against item %s"%d.item_code) msgprint("Purchse Order No. required against item %s"%d.item_code)
raise Exception raise Exception
# validate # validate
def validate(self): def validate(self):
self.po_required() self.po_required()
self.validate_fiscal_year() self.validate_fiscal_year()
set(self.doc, 'status', 'Draft') # set status as "Draft" set(self.doc, 'status', 'Draft') # set status as "Draft"
self.validate_accepted_rejected_qty() self.validate_accepted_rejected_qty()
self.validate_inspection() # Validate Inspection self.validate_inspection() # Validate Inspection
get_obj('Stock Ledger').validate_serial_no(self, 'purchase_receipt_details') get_obj('Stock Ledger').validate_serial_no(self, 'purchase_receipt_details')
self.validate_challan_no() self.validate_challan_no()
pc_obj = get_obj(dt='Purchase Common') pc_obj = get_obj(dt='Purchase Common')
pc_obj.validate_for_items(self) pc_obj.validate_for_items(self)
pc_obj.validate_mandatory(self) pc_obj.validate_mandatory(self)
pc_obj.validate_conversion_rate(self) pc_obj.validate_conversion_rate(self)
pc_obj.get_prevdoc_date(self) pc_obj.get_prevdoc_date(self)
pc_obj.validate_reference_value(self) pc_obj.validate_reference_value(self)
self.check_for_stopped_status(pc_obj) self.check_for_stopped_status(pc_obj)
# get total in words # get total in words
dcc = TransactionBase().get_company_currency(self.doc.company) dcc = TransactionBase().get_company_currency(self.doc.company)
self.doc.in_words = pc_obj.get_total_in_words(dcc, self.doc.grand_total) self.doc.in_words = pc_obj.get_total_in_words(dcc, self.doc.grand_total)
self.doc.in_words_import = pc_obj.get_total_in_words(self.doc.currency, self.doc.grand_total_import) self.doc.in_words_import = pc_obj.get_total_in_words(self.doc.currency, self.doc.grand_total_import)
# update valuation rate # update valuation rate
self.update_valuation_rate() self.update_valuation_rate()
# On Update # On Update
# ---------------------------------------------------------------------------------------------------- # ----------------------------------------------------------------------------------------------------
def on_update(self): def on_update(self):
if self.doc.rejected_warehouse: if self.doc.rejected_warehouse:
for d in getlist(self.doclist,'purchase_receipt_details'): for d in getlist(self.doclist,'purchase_receipt_details'):
d.rejected_warehouse = self.doc.rejected_warehouse d.rejected_warehouse = self.doc.rejected_warehouse
self.update_rw_material_detail() self.update_rw_material_detail()
get_obj('Stock Ledger').scrub_serial_nos(self) get_obj('Stock Ledger').scrub_serial_nos(self)
# On Submit # On Submit
# ----------------------------------------------------------------------------------------------------- # -----------------------------------------------------------------------------------------------------
# Update Stock # Update Stock
def update_stock(self, is_submit): def update_stock(self, is_submit):
pc_obj = get_obj('Purchase Common') pc_obj = get_obj('Purchase Common')
self.values = [] self.values = []
for d in getlist(self.doclist, 'purchase_receipt_details'): for d in getlist(self.doclist, 'purchase_receipt_details'):
# Check if is_stock_item == 'Yes' # Check if is_stock_item == 'Yes'
if sql("select is_stock_item from tabItem where name=%s", d.item_code)[0][0]=='Yes': if sql("select is_stock_item from tabItem where name=%s", d.item_code)[0][0]=='Yes':
ord_qty = 0 ord_qty = 0
pr_qty = flt(d.qty) * flt(d.conversion_factor) pr_qty = flt(d.qty) * flt(d.conversion_factor)
# Check If Prevdoc Doctype is Purchase Order # Check If Prevdoc Doctype is Purchase Order
if cstr(d.prevdoc_doctype) == 'Purchase Order': if cstr(d.prevdoc_doctype) == 'Purchase Order':
# get qty and pending_qty of prevdoc # get qty and pending_qty of prevdoc
curr_ref_qty = pc_obj.get_qty( d.doctype, 'prevdoc_detail_docname', d.prevdoc_detail_docname, 'PO Detail', 'Purchase Order - Purchase Receipt', self.doc.name) curr_ref_qty = pc_obj.get_qty( d.doctype, 'prevdoc_detail_docname', d.prevdoc_detail_docname, 'PO Detail', 'Purchase Order - Purchase Receipt', self.doc.name)
max_qty, qty, curr_qty = flt(curr_ref_qty.split('~~~')[1]), flt(curr_ref_qty.split('~~~')[0]), 0 max_qty, qty, curr_qty = flt(curr_ref_qty.split('~~~')[1]), flt(curr_ref_qty.split('~~~')[0]), 0
if flt(qty) + flt(pr_qty) > flt(max_qty): if flt(qty) + flt(pr_qty) > flt(max_qty):
curr_qty = (flt(max_qty) - flt(qty)) * flt(d.conversion_factor) curr_qty = (flt(max_qty) - flt(qty)) * flt(d.conversion_factor)
else: else:
curr_qty = flt(pr_qty) curr_qty = flt(pr_qty)
ord_qty = -flt(curr_qty) ord_qty = -flt(curr_qty)
# update order qty in bin # update order qty in bin
bin = get_obj('Warehouse', d.warehouse).update_bin(0, 0, (is_submit and 1 or -1) * flt(ord_qty), 0, 0, d.item_code, self.doc.transaction_date) bin = get_obj('Warehouse', d.warehouse).update_bin(0, 0, (is_submit and 1 or -1) * flt(ord_qty), 0, 0, d.item_code, self.doc.transaction_date)
# UPDATE actual qty to warehouse by pr_qty # UPDATE actual qty to warehouse by pr_qty
self.make_sl_entry(d, d.warehouse, flt(pr_qty), d.valuation_rate, is_submit) self.make_sl_entry(d, d.warehouse, flt(pr_qty), d.valuation_rate, is_submit)
# UPDATE actual to rejected warehouse by rejected qty # UPDATE actual to rejected warehouse by rejected qty
if flt(d.rejected_qty) > 0: if flt(d.rejected_qty) > 0:
self.make_sl_entry(d, self.doc.rejected_warehouse, flt(d.rejected_qty) * flt(d.conversion_factor), d.valuation_rate, is_submit) self.make_sl_entry(d, self.doc.rejected_warehouse, flt(d.rejected_qty) * flt(d.conversion_factor), d.valuation_rate, is_submit)
self.bk_flush_supp_wh(is_submit) self.bk_flush_supp_wh(is_submit)
if self.values: if self.values:
get_obj('Stock Ledger', 'Stock Ledger').update_stock(self.values) get_obj('Stock Ledger', 'Stock Ledger').update_stock(self.values)
# make Stock Entry # make Stock Entry
def make_sl_entry(self, d, wh, qty, in_value, is_submit): def make_sl_entry(self, d, wh, qty, in_value, is_submit):
self.values.append({ self.values.append({
'item_code' : d.fields.has_key('item_code') and d.item_code or d.rm_item_code, 'item_code' : d.fields.has_key('item_code') and d.item_code or d.rm_item_code,
'warehouse' : wh, 'warehouse' : wh,
'transaction_date' : self.doc.transaction_date, 'transaction_date' : self.doc.transaction_date,
'posting_date' : self.doc.posting_date, 'posting_date' : self.doc.posting_date,
'posting_time' : self.doc.posting_time, 'posting_time' : self.doc.posting_time,
'voucher_type' : 'Purchase Receipt', 'voucher_type' : 'Purchase Receipt',
'voucher_no' : self.doc.name, 'voucher_no' : self.doc.name,
'voucher_detail_no' : d.name, 'voucher_detail_no' : d.name,
'actual_qty' : qty, 'actual_qty' : qty,
'stock_uom' : d.stock_uom, 'stock_uom' : d.stock_uom,
'incoming_rate' : in_value, 'incoming_rate' : in_value,
'company' : self.doc.company, 'company' : self.doc.company,
'fiscal_year' : self.doc.fiscal_year, 'fiscal_year' : self.doc.fiscal_year,
'is_cancelled' : (is_submit==1) and 'No' or 'Yes', 'is_cancelled' : (is_submit==1) and 'No' or 'Yes',
'batch_no' : d.batch_no, 'batch_no' : d.batch_no,
'serial_no' : d.serial_no 'serial_no' : d.serial_no
}) })
def validate_inspection(self): def validate_inspection(self):
for d in getlist(self.doclist, 'purchase_receipt_details'): #Enter inspection date for all items that require inspection for d in getlist(self.doclist, 'purchase_receipt_details'): #Enter inspection date for all items that require inspection
ins_reqd = sql("select inspection_required from `tabItem` where name = %s", (d.item_code), as_dict = 1) ins_reqd = sql("select inspection_required from `tabItem` where name = %s", (d.item_code), as_dict = 1)
ins_reqd = ins_reqd and ins_reqd[0]['inspection_required'] or 'No' ins_reqd = ins_reqd and ins_reqd[0]['inspection_required'] or 'No'
if ins_reqd == 'Yes' and not d.qa_no: if ins_reqd == 'Yes' and not d.qa_no:
msgprint("Item: " + d.item_code + " requires QA Inspection. Please enter QA No or report to authorized person to create QA Inspection Report") msgprint("Item: " + d.item_code + " requires QA Inspection. Please enter QA No or report to authorized person to create QA Inspection Report")
# Check for Stopped status # Check for Stopped status
def check_for_stopped_status(self, pc_obj): def check_for_stopped_status(self, pc_obj):
check_list =[] check_list =[]
for d in getlist(self.doclist, 'purchase_receipt_details'): for d in getlist(self.doclist, 'purchase_receipt_details'):
if d.fields.has_key('prevdoc_docname') and d.prevdoc_docname and d.prevdoc_docname not in check_list: if d.fields.has_key('prevdoc_docname') and d.prevdoc_docname and d.prevdoc_docname not in check_list:
check_list.append(d.prevdoc_docname) check_list.append(d.prevdoc_docname)
pc_obj.check_for_stopped_status( d.prevdoc_doctype, d.prevdoc_docname) pc_obj.check_for_stopped_status( d.prevdoc_doctype, d.prevdoc_docname)
# on submit # on submit
def on_submit(self): def on_submit(self):
# Check for Approving Authority # Check for Approving Authority
get_obj('Authorization Control').validate_approving_authority(self.doc.doctype, self.doc.company, self.doc.grand_total) get_obj('Authorization Control').validate_approving_authority(self.doc.doctype, self.doc.company, self.doc.grand_total)
# Set status as Submitted # Set status as Submitted
set(self.doc,'status', 'Submitted') set(self.doc,'status', 'Submitted')
pc_obj = get_obj('Purchase Common') pc_obj = get_obj('Purchase Common')
# Update Previous Doc i.e. update pending_qty and Status accordingly # Update Previous Doc i.e. update pending_qty and Status accordingly
pc_obj.update_prevdoc_detail(self, is_submit = 1) pc_obj.update_prevdoc_detail(self, is_submit = 1)
# Update Serial Record # Update Serial Record
get_obj('Stock Ledger').update_serial_record(self, 'purchase_receipt_details', is_submit = 1, is_incoming = 1) get_obj('Stock Ledger').update_serial_record(self, 'purchase_receipt_details', is_submit = 1, is_incoming = 1)
# Update Stock # Update Stock
self.update_stock(is_submit = 1) self.update_stock(is_submit = 1)
# Update last purchase rate # Update last purchase rate
pc_obj.update_last_purchase_rate(self, 1) pc_obj.update_last_purchase_rate(self, 1)
#On Cancel #On Cancel
#---------------------------------------------------------------------------------------------------- #----------------------------------------------------------------------------------------------------
def check_next_docstatus(self): def check_next_docstatus(self):
submit_rv = sql("select t1.name from `tabPayable Voucher` t1,`tabPV Detail` t2 where t1.name = t2.parent and t2.purchase_receipt = '%s' and t1.docstatus = 1" % (self.doc.name)) submit_rv = sql("select t1.name from `tabPayable Voucher` t1,`tabPV Detail` t2 where t1.name = t2.parent and t2.purchase_receipt = '%s' and t1.docstatus = 1" % (self.doc.name))
if submit_rv: if submit_rv:
msgprint("Purchase Invoice : " + cstr(self.submit_rv[0][0]) + " has already been submitted !") msgprint("Purchase Invoice : " + cstr(self.submit_rv[0][0]) + " has already been submitted !")
raise Exception , "Validation Error." raise Exception , "Validation Error."
def on_cancel(self): def on_cancel(self):
pc_obj = get_obj('Purchase Common') pc_obj = get_obj('Purchase Common')
self.check_for_stopped_status(pc_obj) self.check_for_stopped_status(pc_obj)
# 1.Check if Payable Voucher has been submitted against current Purchase Order # 1.Check if Payable Voucher has been submitted against current Purchase Order
# pc_obj.check_docstatus(check = 'Next', doctype = 'Payable Voucher', docname = self.doc.name, detail_doctype = 'PV Detail') # pc_obj.check_docstatus(check = 'Next', doctype = 'Payable Voucher', docname = self.doc.name, detail_doctype = 'PV Detail')
submitted = sql("select t1.name from `tabPayable Voucher` t1,`tabPV Detail` t2 where t1.name = t2.parent and t2.purchase_receipt = '%s' and t1.docstatus = 1" % self.doc.name) submitted = sql("select t1.name from `tabPayable Voucher` t1,`tabPV Detail` t2 where t1.name = t2.parent and t2.purchase_receipt = '%s' and t1.docstatus = 1" % self.doc.name)
if submitted: if submitted:
msgprint("Purchase Invoice : " + cstr(submitted[0][0]) + " has already been submitted !") msgprint("Purchase Invoice : " + cstr(submitted[0][0]) + " has already been submitted !")
raise Exception raise Exception
# 2.Set Status as Cancelled # 2.Set Status as Cancelled
set(self.doc,'status','Cancelled') set(self.doc,'status','Cancelled')
# 3. Cancel Serial No # 3. Cancel Serial No
get_obj('Stock Ledger').update_serial_record(self, 'purchase_receipt_details', is_submit = 0, is_incoming = 1) get_obj('Stock Ledger').update_serial_record(self, 'purchase_receipt_details', is_submit = 0, is_incoming = 1)
# 4.Update Bin # 4.Update Bin
self.update_stock(is_submit = 0) self.update_stock(is_submit = 0)
# 5.Update Indents Pending Qty and accordingly it's Status # 5.Update Indents Pending Qty and accordingly it's Status
pc_obj.update_prevdoc_detail(self, is_submit = 0) pc_obj.update_prevdoc_detail(self, is_submit = 0)
# 6. Update last purchase rate # 6. Update last purchase rate
pc_obj.update_last_purchase_rate(self, 0) pc_obj.update_last_purchase_rate(self, 0)
#----------- code for Sub-contracted Items ------------------- #----------- code for Sub-contracted Items -------------------
#--------check for sub-contracted items and accordingly update PR raw material detail table-------- #--------check for sub-contracted items and accordingly update PR raw material detail table--------
def update_rw_material_detail(self): def update_rw_material_detail(self):
for d in getlist(self.doclist,'purchase_receipt_details'): for d in getlist(self.doclist,'purchase_receipt_details'):
item_det = sql("select is_sub_contracted_item, is_purchase_item from `tabItem` where name = '%s'"%(d.item_code)) item_det = sql("select is_sub_contracted_item, is_purchase_item from `tabItem` where name = '%s'"%(d.item_code))
if item_det[0][0] == 'Yes': if item_det[0][0] == 'Yes':
if item_det[0][1] == 'Yes': if item_det[0][1] == 'Yes':
if not self.doc.is_subcontracted: if not self.doc.is_subcontracted:
msgprint("Please enter whether purchase receipt to be made for subcontracting or for purchase in 'Is Subcontracted' field .") msgprint("Please enter whether purchase receipt to be made for subcontracting or for purchase in 'Is Subcontracted' field .")
raise Exception raise Exception
if self.doc.is_subcontracted == 'Yes': if self.doc.is_subcontracted == 'Yes':
if not self.doc.supplier_warehouse: if not self.doc.supplier_warehouse:
msgprint("Please Enter Supplier Warehouse for subcontracted Items") msgprint("Please Enter Supplier Warehouse for subcontracted Items")
raise Exception raise Exception
self.add_bom(d) self.add_bom(d)
else: else:
self.doc.clear_table(self.doclist,'pr_raw_material_details',1) self.doc.clear_table(self.doclist,'pr_raw_material_details',1)
self.doc.save() self.doc.save()
elif item_det[0][1] == 'No': elif item_det[0][1] == 'No':
if not self.doc.supplier_warehouse: if not self.doc.supplier_warehouse:
msgprint("Please Enter Supplier Warehouse for subcontracted Items") msgprint("Please Enter Supplier Warehouse for subcontracted Items")
raise Exception raise Exception
self.add_bom(d) self.add_bom(d)
self.delete_irrelevant_raw_material() self.delete_irrelevant_raw_material()
#---------------calculate amt in PR Raw Material Detail------------- #---------------calculate amt in PR Raw Material Detail-------------
self.calculate_amount(d) self.calculate_amount(d)
def add_bom(self, d): def add_bom(self, d):
#----- fetching default bom from Bill of Materials instead of Item Master -- #----- fetching default bom from Bill of Materials instead of Item Master --
bom_det = sql("select t1.item, t2.item_code, t2.qty_consumed_per_unit, t2.moving_avg_rate, t2.value_as_per_mar, t2.stock_uom, t2.name, t2.description from `tabBill Of Materials` t1, `tabBOM Material` t2 where t2.parent = t1.name and t1.item = '%s' and ifnull(t1.is_default,0) = 1 and t1.docstatus = 1 and t2.docstatus =1" % d.item_code) bom_det = sql("select t1.item, t2.item_code, t2.qty_consumed_per_unit, t2.moving_avg_rate, t2.value_as_per_mar, t2.stock_uom, t2.name, t2.description from `tabBill Of Materials` t1, `tabBOM Material` t2 where t2.parent = t1.name and t1.item = '%s' and ifnull(t1.is_default,0) = 1 and t1.docstatus = 1 and t2.docstatus =1" % d.item_code)
if not bom_det: if not bom_det:
msgprint("No default BOM exists for item: %s" % d.item_code) msgprint("No default BOM exists for item: %s" % d.item_code)
raise Exception raise Exception
else: else:
#-------------- add child function-------------------- #-------------- add child function--------------------
chgd_rqd_qty = [] chgd_rqd_qty = []
for i in bom_det: for i in bom_det:
if i and not sql("select name from `tabPR Raw Material Detail` where reference_name = '%s' and bom_detail_no = '%s' and parent = '%s' " %(d.name, i[6], self.doc.name)): if i and not sql("select name from `tabPR Raw Material Detail` where reference_name = '%s' and bom_detail_no = '%s' and parent = '%s' " %(d.name, i[6], self.doc.name)):
rm_child = addchild(self.doc, 'pr_raw_material_details', 'PR Raw Material Detail', 1, self.doclist) rm_child = addchild(self.doc, 'pr_raw_material_details', 'PR Raw Material Detail', 1, self.doclist)
rm_child.reference_name = d.name rm_child.reference_name = d.name
rm_child.bom_detail_no = i and i[6] or '' rm_child.bom_detail_no = i and i[6] or ''
rm_child.main_item_code = i and i[0] or '' rm_child.main_item_code = i and i[0] or ''
rm_child.rm_item_code = i and i[1] or '' rm_child.rm_item_code = i and i[1] or ''
rm_child.description = i and i[7] or '' rm_child.description = i and i[7] or ''
rm_child.stock_uom = i and i[5] or '' rm_child.stock_uom = i and i[5] or ''
rm_child.rate = i and flt(i[3]) or flt(i[4]) rm_child.rate = i and flt(i[3]) or flt(i[4])
rm_child.conversion_factor = d.conversion_factor rm_child.conversion_factor = d.conversion_factor
rm_child.required_qty = flt(i and flt(i[2]) or 0) * flt(d.qty) * flt(d.conversion_factor) rm_child.required_qty = flt(i and flt(i[2]) or 0) * flt(d.qty) * flt(d.conversion_factor)
rm_child.consumed_qty = flt(i and flt(i[2]) or 0) * flt(d.qty) * flt(d.conversion_factor) rm_child.consumed_qty = flt(i and flt(i[2]) or 0) * flt(d.qty) * flt(d.conversion_factor)
rm_child.amount = flt(flt(rm_child.consumed_qty)*flt(rm_child.rate)) rm_child.amount = flt(flt(rm_child.consumed_qty)*flt(rm_child.rate))
rm_child.save() rm_child.save()
chgd_rqd_qty.append(cstr(i[1])) chgd_rqd_qty.append(cstr(i[1]))
else: else:
act_qty = flt(i and flt(i[2]) or 0) * flt(d.qty) * flt(d.conversion_factor) act_qty = flt(i and flt(i[2]) or 0) * flt(d.qty) * flt(d.conversion_factor)
for pr_rmd in getlist(self.doclist, 'pr_raw_material_details'): for pr_rmd in getlist(self.doclist, 'pr_raw_material_details'):
if i and i[6] == pr_rmd.bom_detail_no and (flt(act_qty) != flt(pr_rmd.required_qty) or i[1] != pr_rmd.rm_item_code or i[7] != pr_rmd.description): if i and i[6] == pr_rmd.bom_detail_no and (flt(act_qty) != flt(pr_rmd.required_qty) or i[1] != pr_rmd.rm_item_code or i[7] != pr_rmd.description):
chgd_rqd_qty.append(cstr(i[1])) chgd_rqd_qty.append(cstr(i[1]))
pr_rmd.main_item_code = i[0] pr_rmd.main_item_code = i[0]
pr_rmd.rm_item_code = i[1] pr_rmd.rm_item_code = i[1]
pr_rmd.description = i[7] pr_rmd.description = i[7]
pr_rmd.stock_uom = i[5] pr_rmd.stock_uom = i[5]
pr_rmd.required_qty = flt(act_qty) pr_rmd.required_qty = flt(act_qty)
pr_rmd.consumed_qty = flt(act_qty) pr_rmd.consumed_qty = flt(act_qty)
pr_rmd.rate = i and flt(i[3]) or flt(i[4]) pr_rmd.rate = i and flt(i[3]) or flt(i[4])
pr_rmd.amount = flt(flt(pr_rmd.consumed_qty)*flt(pr_rmd.rate)) pr_rmd.amount = flt(flt(pr_rmd.consumed_qty)*flt(pr_rmd.rate))
pr_rmd.save() pr_rmd.save()
if chgd_rqd_qty: if chgd_rqd_qty:
msgprint("Please check consumed quantity for Raw Material Item Code: '%s'in Raw materials Detail Table" % ((len(chgd_rqd_qty) > 1 and ','.join(chgd_rqd_qty[:-1]) +' and ' + cstr(chgd_rqd_qty[-1:][0]) ) or cstr(chgd_rqd_qty[0]))) msgprint("Please check consumed quantity for Raw Material Item Code: '%s'in Raw materials Detail Table" % ((len(chgd_rqd_qty) > 1 and ','.join(chgd_rqd_qty[:-1]) +' and ' + cstr(chgd_rqd_qty[-1:][0]) ) or cstr(chgd_rqd_qty[0])))
# Delete irrelevant raw material from PR Raw material details # Delete irrelevant raw material from PR Raw material details
#-------------------------------------------------------------- #--------------------------------------------------------------
def delete_irrelevant_raw_material(self): def delete_irrelevant_raw_material(self):
for d in getlist(self.doclist,'pr_raw_material_details'): for d in getlist(self.doclist,'pr_raw_material_details'):
if not sql("select name from `tabPurchase Receipt Detail` where name = '%s' and parent = '%s' and item_code = '%s'" % (d.reference_name, self.doc.name, d.main_item_code)): if not sql("select name from `tabPurchase Receipt Detail` where name = '%s' and parent = '%s' and item_code = '%s'" % (d.reference_name, self.doc.name, d.main_item_code)):
d.parent = 'old_par:'+self.doc.name d.parent = 'old_par:'+self.doc.name
d.save() d.save()
def calculate_amount(self, d): def calculate_amount(self, d):
amt = 0 amt = 0
for i in getlist(self.doclist,'pr_raw_material_details'): for i in getlist(self.doclist,'pr_raw_material_details'):
if(i.reference_name == d.name): if(i.reference_name == d.name):
#if i.consumed_qty == 0: #if i.consumed_qty == 0:
# msgprint("consumed qty cannot be 0. Please Enter consumed qty ") # msgprint("consumed qty cannot be 0. Please Enter consumed qty ")
#raise Exception #raise Exception
i.amount = flt(i.consumed_qty)* flt(i.rate) i.amount = flt(i.consumed_qty)* flt(i.rate)
amt += i.amount amt += i.amount
d.rm_supp_cost = amt d.rm_supp_cost = amt
d.save() d.save()
# --------------- Back Flush function called on submit and on cancel from update stock # --------------- Back Flush function called on submit and on cancel from update stock
def bk_flush_supp_wh(self, is_submit): def bk_flush_supp_wh(self, is_submit):
for d in getlist(self.doclist, 'pr_raw_material_details'): for d in getlist(self.doclist, 'pr_raw_material_details'):
#--------- -ve quantity is passed as raw material qty has to be decreased when PR is submitted and it has to be increased when PR is cancelled #--------- -ve quantity is passed as raw material qty has to be decreased when PR is submitted and it has to be increased when PR is cancelled
consumed_qty = - flt(d.consumed_qty) consumed_qty = - flt(d.consumed_qty)
self.make_sl_entry(d, self.doc.supplier_warehouse, flt(consumed_qty), 0, is_submit) self.make_sl_entry(d, self.doc.supplier_warehouse, flt(consumed_qty), 0, is_submit)
# get current_stock # get current_stock
# ---------------- # ----------------
def get_current_stock(self): def get_current_stock(self):
for d in getlist(self.doclist, 'pr_raw_material_details'): for d in getlist(self.doclist, 'pr_raw_material_details'):
if self.doc.supplier_warehouse: if self.doc.supplier_warehouse:
bin = sql("select actual_qty from `tabBin` where item_code = %s and warehouse = %s", (d.rm_item_code, self.doc.supplier_warehouse), as_dict = 1) bin = sql("select actual_qty from `tabBin` where item_code = %s and warehouse = %s", (d.rm_item_code, self.doc.supplier_warehouse), as_dict = 1)
d.current_stock = bin and flt(bin[0]['actual_qty']) or 0 d.current_stock = bin and flt(bin[0]['actual_qty']) or 0
@ -427,15 +442,15 @@ class DocType(TransactionBase):
# OTHER CHARGES TRIGGER FUNCTIONS # OTHER CHARGES TRIGGER FUNCTIONS
# ==================================================================================== # ====================================================================================
# *********** Get Tax rate if account type is TAX ******************** # *********** Get Tax rate if account type is TAX ********************
def get_rate(self,arg): def get_rate(self,arg):
return get_obj('Purchase Common').get_rate(arg,self) return get_obj('Purchase Common').get_rate(arg,self)
# **** Pull details from other charges master (Get Other Charges) **** # **** Pull details from other charges master (Get Other Charges) ****
def get_purchase_tax_details(self): def get_purchase_tax_details(self):
return get_obj('Purchase Common').get_purchase_tax_details(self) return get_obj('Purchase Common').get_purchase_tax_details(self)
# Repair Purchase Order # Repair Purchase Order
# =========================================== # ===========================================
def repair_purchase_receipt(self): def repair_purchase_receipt(self):
get_obj('Purchase Common').repair_curr_doctype_details(self) get_obj('Purchase Common').repair_curr_doctype_details(self)

View File

@ -25,8 +25,9 @@ class DocType:
from webnotes.utils import file_manager from webnotes.utils import file_manager
fn, content = file_manager.get_file(filename[1]) fn, content = file_manager.get_file(filename[1])
if not type(content) == str: # NOTE: Don't know why this condition exists
content = content.tostring() if not isinstance(content, basestring) and hasattr(content, 'tostring'):
content = content.tostring()
return content return content

View File

@ -1,4 +1,5 @@
import webnotes import webnotes
from webnotes.utils import cstr
from webnotes.utils.email_lib.receive import POP3Mailbox from webnotes.utils.email_lib.receive import POP3Mailbox
@ -111,7 +112,7 @@ class SupportMailbox(POP3Mailbox):
status = add_file_list('Support Ticket', doc.name, attachment['filename'], fid) status = add_file_list('Support Ticket', doc.name, attachment['filename'], fid)
if not status: if not status:
doc.description = doc.description \ doc.description = doc.description \
+ "\nCould not attach: " + str(attachment['filename']) + "\nCould not attach: " + cstr(attachment['filename'])
doc.save() doc.save()
webnotes.conn.commit() webnotes.conn.commit()
@ -137,7 +138,7 @@ We will get back to you as soon as possible
sendmail(\ sendmail(\
recipients = [d.raised_by], \ recipients = [d.raised_by], \
sender = self.email_settings.support_email, \ sender = self.email_settings.support_email, \
subject = '['+d.name+'] ' + str(d.subject or ''), \ subject = '['+d.name+'] ' + cstr(d.subject), \
msg = response) msg = response)
def auto_close_tickets(self): def auto_close_tickets(self):

View File

@ -76,7 +76,8 @@ class DocType:
from webnotes.utils import file_manager from webnotes.utils import file_manager
fn, content = file_manager.get_file(fid) fn, content = file_manager.get_file(fid)
if not type(content) == str: # NOTE: Don't know why this condition exists
if not isinstance(content, basestring) and hasattr(content, 'tostring'):
content = content.tostring() content = content.tostring()
return content return content

View File

@ -3,7 +3,7 @@
<meta charset="utf-8"> <meta charset="utf-8">
<title>ERPNext</title> <title>ERPNext</title>
<meta name="author" content=""> <meta name="author" content="">
<script type="text/javascript">window._version_number="140" <script type="text/javascript">window._version_number="146"
wn={} wn={}
wn.provide=function(namespace){var nsl=namespace.split('.');var l=nsl.length;var parent=window;for(var i=0;i<l;i++){var n=nsl[i];if(!parent[n]){parent[n]={}} wn.provide=function(namespace){var nsl=namespace.split('.');var l=nsl.length;var parent=window;for(var i=0;i<l;i++){var n=nsl[i];if(!parent[n]){parent[n]={}}

View File

@ -1 +1 @@
141 146