<commit_before>/*
    Instruction =>
    * Return true if the given string is a palindrome. Otherwise, return false.

    What's a palindrome?
    A palindrome is a word or sentence that's spelled the same way both forward and backward, ignoring
    punctuation, case, and spacing.

    Note
    You'll need to remove all non-alphanumeric characters (punctuation, spaces and symbols) and
    turn everything lower case in order to check for palindromes.

    We'll pass strings with varying formats, such as "racecar", "RaceCar", and "race CAR" among others.

    We'll also pass strings with special symbols, such as "2A3*3a2", "2A3 3a2", and "2_A3*3#A2".

    Remember to use Read-Search-Ask if you get stuck. Write your own code.

    Here are some helpful Methods:

    String.prototype.replace() = Searches a string for a specified value or RegEx and returns
    a string where the specified values are.
    String.prototype.toLowerCase() = converts a string value to lowercase

    MY TRAIN OF THOUGHTS
        -  OPTION 1 : Step 1 : Take out the special charaters in the string and convert to lowercase
                      Step 2 : Make a copy of the string; On the second copy, Convert the string into an
                               array with the split method, Reverse the array and Join.
                      Step 3 : Compare the original string with the newly reversed string and return the
                               appropriate booleen value.

        - OPTION 2 : (MY PREFERED OPTION)
                Step 1 : Same as Above.
                Step 2 : Find the middle number in the string using the .length/2 property;
                Step 3 : Using a while loop, (You'll need 2, one for the left and one for the right)
                         Checking for the condition while i < middle; assign this to the left value
                         while j > middle; assign this to the right value. Don't forget to increase the
                         Iteration for i by 1 and decrease the iteration for j by 1;
                Step 4 : Compare the values and return the appropriate booleen value.
*/

const palindrome = (str) => {
    //Remove any special characters from the string and convert the string to lowercase.
    str = str.replace(/[^A-Za-z0-9]/g, '').toLowerCase();
    // console.log(str);

    //Convert the string into an array so I can get easy access to each characters in the present string.
    // let arrPalindrome = str.split(''); // Not using this so I can use the charAt() method.
    // console.log(arrPalindrome);

    //gettingg the index of the middle value
    let middle = Math.floor(str.length/2);
    let i = 0;
    let j = str.length-1;
    // console.log(middle);
    // console.log(i);
    // console.log(j);
    while(i < middle){
        let left = str.charAt(i);
        i++;
        // console.log(left);
        while (j > middle){
            let right = str.charAt(j);
            j--;
            // console.log(right);

            if(left === right){
                return console.log('The left value is: '+ left + ' and right value is: '+ right + ': Palindrome: ' + true);

            }else{
                return console.log('The left value is: '+ left + ' and right value is: '+ right + ': Palindrome: ' + false);
            }
        }
    }

}

palindrome("_eye"); //true
palindrome("race car"); //true
palindrome("not a palindrome"); //false
palindrome("A man, a plan, a canal. Panama"); //true
palindrome("0_0 (: /-\ :) 0-0"); //true
palindrome("five|\_/|four");//false<commit_msg>03 Check For Palindromes<commit_after>/*
    Instruction =>
    * Return true if the given string is a palindrome. Otherwise, return false.

    What's a palindrome?
    A palindrome is a word or sentence that's spelled the same way both forward and backward, ignoring
    punctuation, case, and spacing.

    Note
    You'll need to remove all non-alphanumeric characters (punctuation, spaces and symbols) and
    turn everything lower case in order to check for palindromes.

    We'll pass strings with varying formats, such as "racecar", "RaceCar", and "race CAR" among others.

    We'll also pass strings with special symbols, such as "2A3*3a2", "2A3 3a2", and "2_A3*3#A2".

    Remember to use Read-Search-Ask if you get stuck. Write your own code.

    Here are some helpful Methods:

    String.prototype.replace() = Searches a string for a specified value or RegEx and returns
    a string where the specified values are.
    String.prototype.toLowerCase() = converts a string value to lowercase
    String.prototype.charAt() = It returns a charater at the specified position from a string.

    MY TRAIN OF THOUGHTS
        -  OPTION 1 : Step 1 : Take out the special charaters in the string and convert to lowercase
                      Step 2 : Make a copy of the string; On the second copy, Convert the string into an
                               array with the split method, Reverse the array and Join.
                      Step 3 : Compare the original string with the newly reversed string and return the
                               appropriate booleen value.

        - OPTION 2 : (MY PREFERED OPTION)
                Step 1 : Same as Above.
                Step 2 : Find the middle number in the string using the .length/2 property;
                Step 3 : Using a while loop, (You'll need 2, one for the left and one for the right)
                         Checking for the condition while i < middle; assign this to the left value
                         while j > middle; assign this to the right value. Don't forget to increase the
                         Iteration for i by 1 and decrease the iteration for j by 1;
                Step 4 : Compare the values and return the appropriate booleen value.
*/

const palindrome = (str) => {
    //Remove any special characters from the string and convert the string to lowercase.
    str = str.replace(/[^A-Za-z0-9]/g, '').toLowerCase();
    // console.log(str);

    //Convert the string into an array so I can get easy access to each characters in the present string.
    // let arrPalindrome = str.split(''); // Not using this so I can use the charAt() method.
    // console.log(arrPalindrome);

    //gettingg the index of the middle value
    let middle = Math.floor(str.length/2);
    let i = 0;
    let j = str.length-1;
    // console.log(middle);
    // console.log(i);
    // console.log(j);
    while(i < middle){
        let left = str.charAt(i);
        i++;
        // console.log(left);
        while (j > middle){
            let right = str.charAt(j);
            j--;
            // console.log(right);

            if(left === right){
                return console.log('The left value is: '+ left + ' and right value is: '+ right + ': Palindrome: ' + true);

            }else{
                return console.log('The left value is: '+ left + ' and right value is: '+ right + ': Palindrome: ' + false);
            }
        }
    }

}

palindrome("_eye"); //true
palindrome("race car"); //true
palindrome("not a palindrome"); //false
palindrome("A man, a plan, a canal. Panama"); //true
palindrome("0_0 (: /-\ :) 0-0"); //true
palindrome("five|\_/|four");//false<|endoftext|>


<commit_before>define(['app', 'angular', 'jquery', '/app/views/forms-input-list.partial.html.js'], function(app, angular, $){

return ['$scope', '$http', '$location', '$filter', '$timeout', 'user', function ($scope, authHttp, $location, $filter, $timeout, user) {

    $scope.returnUrl = $location.search().returnurl || $location.search().returnUrl || '/';

    //============================================================
    //
    //
    //============================================================
    function initialize() {

        authHttp.get('/api/v2013/users/' + $scope.user.userID).then(function onsuccess (response) {

            $scope.document = response.data;
            $scope.phones = ($scope.document.Phone||'').split(';');
            $scope.faxes  = ($scope.document.Fax  ||'').split(';');
            $scope.emailsCc  = ($scope.document.EmailsCc  ||'').split(';');

        }).catch(function onerror (response) {

            $scope.error = response.data;
        });

        authHttp.get('/api/v2013/thesaurus/domains/countries/terms', { cache: true }).then(function onerror (response) {

            $scope.countries = $filter('orderBy')(response.data, 'name');

        }).catch(function onerror (response) {

            $scope.error = response.data;
        });
    }

    //============================================================
    //
    //
    //============================================================
    $scope.actionSave = function() {

        $scope.waiting = true;

        authHttp.put('/api/v2013/users/' + $scope.user.userID, angular.toJson($scope.document)).success(function () {

            $location.path('/profile/done');

        }).error(function (data) {
            $scope.waiting = false;
            $scope.error = data;
        });
    };

    $scope.$watch('phones+faxes+emailsCc', function () {
        if($scope.document) {
            $scope.document.Phone = ($scope.phones||[]).join(';').replace(/^\s+|;$|\s+$/gm,'');
            $scope.document.Fax   = ($scope.faxes ||[]).join(';').replace(/^\s+|;$|\s+$/gm,'');
            $scope.document.EmailsCc   = ($scope.emailsCc ||[]).join(';').replace(/^\s+|;$|\s+$/gm,'');
        }
    });

    $timeout(initialize, 350);

}];
});
<commit_msg>Fix `form-input-list `directive reference<commit_after>define(['app', 'angular', 'directives/forms-input-list'], function(app, angular){

return ['$scope', '$http', '$location', '$filter', '$timeout', 'user', function ($scope, authHttp, $location, $filter, $timeout, user) {

    $scope.returnUrl = $location.search().returnurl || $location.search().returnUrl || '/';

    //============================================================
    //
    //
    //============================================================
    function initialize() {

        authHttp.get('/api/v2013/users/' + $scope.user.userID).then(function onsuccess (response) {

            $scope.document = response.data;
            $scope.phones = ($scope.document.Phone||'').split(';');
            $scope.faxes  = ($scope.document.Fax  ||'').split(';');
            $scope.emailsCc  = ($scope.document.EmailsCc  ||'').split(';');

        }).catch(function onerror (response) {

            $scope.error = response.data;
        });

        authHttp.get('/api/v2013/thesaurus/domains/countries/terms', { cache: true }).then(function onerror (response) {

            $scope.countries = $filter('orderBy')(response.data, 'name');

        }).catch(function onerror (response) {

            $scope.error = response.data;
        });
    }

    //============================================================
    //
    //
    //============================================================
    $scope.actionSave = function() {

        $scope.waiting = true;

        authHttp.put('/api/v2013/users/' + $scope.user.userID, angular.toJson($scope.document)).success(function () {

            $location.path('/profile/done');

        }).error(function (data) {
            $scope.waiting = false;
            $scope.error = data;
        });
    };

    $scope.$watch('phones+faxes+emailsCc', function () {
        if($scope.document) {
            $scope.document.Phone = ($scope.phones||[]).join(';').replace(/^\s+|;$|\s+$/gm,'');
            $scope.document.Fax   = ($scope.faxes ||[]).join(';').replace(/^\s+|;$|\s+$/gm,'');
            $scope.document.EmailsCc   = ($scope.emailsCc ||[]).join(';').replace(/^\s+|;$|\s+$/gm,'');
        }
    });

    $timeout(initialize, 350);

}];
});
<|endoftext|>


<commit_before>/*
 * This program is part of the OpenLMIS logistics management information system platform software.
 * Copyright © 2017 VillageReach
 *
 * This program is free software: you can redistribute it and/or modify it under the terms
 * of the GNU Affero General Public License as published by the Free Software Foundation, either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details. You should have received a copy of
 * the GNU Affero General Public License along with this program. If not, see
 * http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.
 */
(function() {

    'use strict';

    /**
     * @ngdoc directive
     * @restrict A
     * @name openlmis-table-form.directive:inputAutoResize
     *
     * @description
     * Adds auto-resize option to input elements.
     *
     * @example
     * ```
     * <input ng-model="model"></input>
     * ```
     */
    angular
        .module('openlmis-table-form')
        .directive('input', inputAutoResize);

    inputAutoResize.$inject = ['$window'];

    function inputAutoResize($window) {
        var directive = {
            link: link,
            restrict: 'E'
        };
        return directive;

        function link(scope, element) {
            if (shouldSkipElement(element)) {
                return;
            }

            var el = element[0];
            scope.$watch(function() {
                return el.value;
            }, function() {
                console.log('changing');
                console.log(el);
                $window.autosizeInput(el);
                console.log(el);
            });
        }

        function shouldSkipElement(element) {
            return element.parents().length < 2 ||
                isOutsideTd(element) ||
                isNotTextType(element);
        }

        function isOutsideTd(element) {
            var parents = element.parents();

            return parents[1].localName !== 'td' || parents[0].localName !== 'div' ||
                !parents[0].classList.contains('input-control');
        }

        function isNotTextType(element) {
            return element.attr('type') !== 'text' || element.attr('openlmis-datepicker');
        }
    }

})();
<commit_msg>OLMIS-5837: Removed console.logs<commit_after>/*
 * This program is part of the OpenLMIS logistics management information system platform software.
 * Copyright © 2017 VillageReach
 *
 * This program is free software: you can redistribute it and/or modify it under the terms
 * of the GNU Affero General Public License as published by the Free Software Foundation, either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details. You should have received a copy of
 * the GNU Affero General Public License along with this program. If not, see
 * http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.
 */
(function() {

    'use strict';

    /**
     * @ngdoc directive
     * @restrict A
     * @name openlmis-table-form.directive:inputAutoResize
     *
     * @description
     * Adds auto-resize option to input elements.
     *
     * @example
     * ```
     * <input ng-model="model"></input>
     * ```
     */
    angular
        .module('openlmis-table-form')
        .directive('input', inputAutoResize);

    inputAutoResize.$inject = ['$window'];

    function inputAutoResize($window) {
        var directive = {
            link: link,
            restrict: 'E'
        };
        return directive;

        function link(scope, element) {
            if (shouldSkipElement(element)) {
                return;
            }

            var el = element[0];
            scope.$watch(function() {
                return el.value;
            }, function() {
                $window.autosizeInput(el);
            });
        }

        function shouldSkipElement(element) {
            return element.parents().length < 2 ||
                isOutsideTd(element) ||
                isNotTextType(element);
        }

        function isOutsideTd(element) {
            var parents = element.parents();

            return parents[1].localName !== 'td' || parents[0].localName !== 'div' ||
                !parents[0].classList.contains('input-control');
        }

        function isNotTextType(element) {
            return element.attr('type') !== 'text' || element.attr('openlmis-datepicker');
        }
    }

})();
<|endoftext|>


<commit_before>//--------- ONLOAD -------------
cur_frm.cscript.onload = function(doc, cdt, cdn) {
  //
}

/*cur_frm.cscript.refresh = function(doc, cdt, cdn) {

}*/

// For customizing print
cur_frm.pformat.net_total = function(doc) {
	return '';
}

cur_frm.pformat.grand_total_export = function(doc) {
	return '';
}

cur_frm.pformat.round_total_export = function(doc) {
	return '';
}

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

	function convert_rate(val){
		var new_val = flt(val)/flt(doc.conversion_rate);
		return new_val;
	}
	out ='';
	if (!doc.print_without_amount) {
		print_hide_dict = {};
		for(var i in locals['DocField']) {
			var doc_field = locals['DocField'][i];
			if(doc_field.fieldname) {
				print_hide_dict[doc_field.fieldname] = doc_field.print_hide;
			}
		}

		var cl = getchildren('RV Tax Detail',doc.name,'other_charges');

		// outer table
		var out='

	';

		// main table

		out +='
';
		if(!print_hide_dict['net_total']) {
			out +=make_row('Net Total',fmt_money(convert_rate(doc.net_total)),1);
		}

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

		// grand total
		if(!print_hide_dict['grand_total_export']) {
			out += make_row('Grand Total',fmt_money(doc.grand_total_export),1);
		}

		if(!print_hide_dict['rounded_total_export']) {
			out += make_row('Rounded Total',fmt_money(doc.rounded_total_export),1);
		}

		if(doc.in_words_export){
			out +='

';
			out += '
';
			out += '

In Words	'
			out+= ''+doc.in_words_export+'
'
		}
		out +='

';
	}
	return out;
}

cur_frm.cscript.charge_type = function(doc, cdt, cdn) {
  var d = locals[cdt][cdn];
  if(d.idx == 1 && (d.charge_type == 'On Previous Row Amount' || d.charge_type == 'On Previous Row Total')){
    alert("You cannot select Charge Type as 'On Previous Row Amount' or 'On Previous Row Total' for first row");
    d.charge_type = '';
  }
  validated = false;
  refresh_field('charge_type',d.name,'other_charges');
  cur_frm.cscript.row_id(doc, cdt, cdn);
  cur_frm.cscript.rate(doc, cdt, cdn);
  cur_frm.cscript.tax_amount(doc, cdt, cdn);
}

cur_frm.cscript.row_id = function(doc, cdt, cdn) {
  var d = locals[cdt][cdn];
  if(!d.charge_type && d.row_id){
    alert("Please select Charge Type first");
    d.row_id = '';
  }
  else if((d.charge_type == 'Actual' || d.charge_type == 'On Net Total') && d.row_id) {
    alert("You can Enter Row only if your Charge Type is 'On Previous Row Amount' or ' Previous Row Total'");
    d.row_id = '';
  }
  else if((d.charge_type == 'On Previous Row Amount' || d.charge_type == 'On Previous Row Total') && d.row_id){
    if(d.row_id >= d.idx){
      alert("You cannot Enter Row no. greater than or equal to current row no. for this Charge type");
      d.row_id = '';
    }
  }
  validated = false;
  refresh_field('row_id',d.name,'other_charges');
}

/*---------------------- Get rate if account_head has account_type as TAX or CHARGEABLE-------------------------------------*/

cur_frm.fields_dict['other_charges'].grid.get_field("account_head").get_query = function(doc,cdt,cdn) {
  return 'SELECT tabAccount.name FROM tabAccount WHERE tabAccount.group_or_ledger="Ledger" AND tabAccount.docstatus != 2 AND (tabAccount.account_type = "Tax" OR tabAccount.account_type = "Chargeable") AND tabAccount.company = "'+doc.company+'" AND  tabAccount.name LIKE "%s"'
}

cur_frm.fields_dict['other_charges'].grid.get_field("cost_center_other_charges").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';
}

cur_frm.cscript.account_head = function(doc, cdt, cdn) {
  var d = locals[cdt][cdn];
  if(!d.charge_type && d.account_head){
    alert("Please select Charge Type first");
    validated = false;
    d.account_head = '';
  }
  else if(d.account_head && d.charge_type) {
    arg = "{'charge_type' : '" + d.charge_type +"', 'account_head' : '" + d.account_head + "'}";
    get_server_fields('get_rate', arg, 'other_charges', doc, cdt, cdn, 1);
  }
  refresh_field('account_head',d.name,'other_charges');
}

cur_frm.cscript.rate = function(doc, cdt, cdn) {
  var d = locals[cdt][cdn];
  if(!d.charge_type && d.rate) {
    alert("Please select Charge Type first");
    d.rate = '';
  }
  validated = false;
  refresh_field('rate',d.name,'other_charges');
}

cur_frm.cscript.tax_amount = function(doc, cdt, cdn) {
  var d = locals[cdt][cdn];
  if(!d.charge_type && d.tax_amount){
    alert("Please select Charge Type first");
    d.tax_amount = '';
  }
  else if(d.charge_type && d.tax_amount) {
    alert("You cannot directly enter Amount and if your Charge Type is Actual enter your amount in Rate");
    d.tax_amount = '';
  }
  validated = false;
  refresh_field('tax_amount',d.name,'other_charges');
}
<commit_msg>Fix: Rounded Total appearing extra in Standard Print Format<commit_after>//--------- ONLOAD -------------
cur_frm.cscript.onload = function(doc, cdt, cdn) {
  //
}

/*cur_frm.cscript.refresh = function(doc, cdt, cdn) {

}*/

// For customizing print
cur_frm.pformat.net_total = function(doc) {
	return '';
}

cur_frm.pformat.grand_total_export = function(doc) {
	return '';
}

cur_frm.pformat.rounded_total_export = function(doc) {
	return '';
}

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

	function convert_rate(val){
		var new_val = flt(val)/flt(doc.conversion_rate);
		return new_val;
	}
	out ='';
	if (!doc.print_without_amount) {
		print_hide_dict = {};
		for(var i in locals['DocField']) {
			var doc_field = locals['DocField'][i];
			if(doc_field.fieldname) {
				print_hide_dict[doc_field.fieldname] = doc_field.print_hide;
			}
		}

		var cl = getchildren('RV Tax Detail',doc.name,'other_charges');

		// outer table
		var out='

	';

		// main table

		out +='
';
		if(!print_hide_dict['net_total']) {
			out +=make_row('Net Total',fmt_money(convert_rate(doc.net_total)),1);
		}

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

		// grand total
		if(!print_hide_dict['grand_total_export']) {
			out += make_row('Grand Total',fmt_money(doc.grand_total_export),1);
		}

		if(!print_hide_dict['rounded_total_export']) {
			out += make_row('Rounded Total',fmt_money(doc.rounded_total_export),1);
		}

		if(doc.in_words_export){
			out +='

';
			out += '
';
			out += '

In Words	'
			out+= ''+doc.in_words_export+'
'
		}
		out +='

';
	}
	return out;
}

cur_frm.cscript.charge_type = function(doc, cdt, cdn) {
  var d = locals[cdt][cdn];
  if(d.idx == 1 && (d.charge_type == 'On Previous Row Amount' || d.charge_type == 'On Previous Row Total')){
    alert("You cannot select Charge Type as 'On Previous Row Amount' or 'On Previous Row Total' for first row");
    d.charge_type = '';
  }
  validated = false;
  refresh_field('charge_type',d.name,'other_charges');
  cur_frm.cscript.row_id(doc, cdt, cdn);
  cur_frm.cscript.rate(doc, cdt, cdn);
  cur_frm.cscript.tax_amount(doc, cdt, cdn);
}

cur_frm.cscript.row_id = function(doc, cdt, cdn) {
  var d = locals[cdt][cdn];
  if(!d.charge_type && d.row_id){
    alert("Please select Charge Type first");
    d.row_id = '';
  }
  else if((d.charge_type == 'Actual' || d.charge_type == 'On Net Total') && d.row_id) {
    alert("You can Enter Row only if your Charge Type is 'On Previous Row Amount' or ' Previous Row Total'");
    d.row_id = '';
  }
  else if((d.charge_type == 'On Previous Row Amount' || d.charge_type == 'On Previous Row Total') && d.row_id){
    if(d.row_id >= d.idx){
      alert("You cannot Enter Row no. greater than or equal to current row no. for this Charge type");
      d.row_id = '';
    }
  }
  validated = false;
  refresh_field('row_id',d.name,'other_charges');
}

/*---------------------- Get rate if account_head has account_type as TAX or CHARGEABLE-------------------------------------*/

cur_frm.fields_dict['other_charges'].grid.get_field("account_head").get_query = function(doc,cdt,cdn) {
  return 'SELECT tabAccount.name FROM tabAccount WHERE tabAccount.group_or_ledger="Ledger" AND tabAccount.docstatus != 2 AND (tabAccount.account_type = "Tax" OR tabAccount.account_type = "Chargeable") AND tabAccount.company = "'+doc.company+'" AND  tabAccount.name LIKE "%s"'
}

cur_frm.fields_dict['other_charges'].grid.get_field("cost_center_other_charges").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';
}

cur_frm.cscript.account_head = function(doc, cdt, cdn) {
  var d = locals[cdt][cdn];
  if(!d.charge_type && d.account_head){
    alert("Please select Charge Type first");
    validated = false;
    d.account_head = '';
  }
  else if(d.account_head && d.charge_type) {
    arg = "{'charge_type' : '" + d.charge_type +"', 'account_head' : '" + d.account_head + "'}";
    get_server_fields('get_rate', arg, 'other_charges', doc, cdt, cdn, 1);
  }
  refresh_field('account_head',d.name,'other_charges');
}

cur_frm.cscript.rate = function(doc, cdt, cdn) {
  var d = locals[cdt][cdn];
  if(!d.charge_type && d.rate) {
    alert("Please select Charge Type first");
    d.rate = '';
  }
  validated = false;
  refresh_field('rate',d.name,'other_charges');
}

cur_frm.cscript.tax_amount = function(doc, cdt, cdn) {
  var d = locals[cdt][cdn];
  if(!d.charge_type && d.tax_amount){
    alert("Please select Charge Type first");
    d.tax_amount = '';
  }
  else if(d.charge_type && d.tax_amount) {
    alert("You cannot directly enter Amount and if your Charge Type is Actual enter your amount in Rate");
    d.tax_amount = '';
  }
  validated = false;
  refresh_field('tax_amount',d.name,'other_charges');
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

"use strict";

var fs = require('fs');
var requirejs = require('requirejs');
var QUnit = require('qunitjs');

var tests = ['core/test/byeresult',
    'core/test/correctionmodel',
    'core/test/correctionreferencemodel',
    'core/test/emitter',
    'core/test/listener',
    'core/test/matchmodel',
    'core/test/matchreferencemodel',
    'core/test/matchresult',
    'core/test/model',
    'core/test/propertymodel',
    'core/test/propertyvaluemodel',
    'core/test/random',
    'core/test/resultreferencemodel',
    'core/test/rle',
    'core/test/selectionvaluemodel',
    'core/test/statevaluemodel',
    'core/test/type',
    'core/test/valuemodel',
    'list/test/binningreferencelistmodel',
    'list/test/combinedreferencelistmodel',
    'list/test/indexedlistmodel',
    'list/test/indexedmodel',
    'list/test/lengthmodel',
    'list/test/listmodel',
    'list/test/listupdatelistener',
    'list/test/maplistmodel',
    'list/test/orderlistmodel',
    'list/test/readonlylistmodel',
    'list/test/referencelistmodel',
    'list/test/sortedreferencelistmodel',
    'list/test/uniquelistmodel',
    'math/test/absolutematrix',
    'math/test/antisymmetricmatrixmodel',
    'math/test/delegatematrix',
    'math/test/matrixmodel',
    'math/test/positivematrix',
    'math/test/symmetricmatrixmodel',
    'math/test/transposedifferencematrix',
    'math/test/transposesummatrix',
    'math/test/trianglematrixmodel',
    'math/test/vectormodel',
    'ranking/test/rankingcomponentindex',
    'ranking/test/rankingdatalistenerindex',
    'ranking/test/rankingheadtohead',
    'ranking/test/rankingmapper',
    'ranking/test/rankingmodel',
    'ranking/test/rankingsonneborn',
    'ranking/test/rankingtac',
    'timemachine/test/keymodel',
    'timemachine/test/query',
    'tournament/test/kotournamentmodel',
    'tournament/test/roundtournamentmodel',
    'tournament/test/swisstournamentmodel',
    'tournament/test/tournamentindex',
    'tournament/test/tournamentlistmodel',
    'tournament/test/tournamentmodel',
    //'ui/test/binarytreemodel',
    //'ui/test/listcollectormodel',
    //'ui/test/playermodel',
    //'ui/test/teammodel',
    //'ui/test/teamsfileloadcontroller'
];

process.chdir(__dirname);

requirejs.config({
    baseUrl: '../scripts'
});

requirejs(['core/config'], function (config) {
    var myBase = '../test/scripts/';

    requirejs.config({
        paths: {
            'options': myBase + 'options',
            'presets': myBase + 'presets',
            'strings': myBase + 'strings'
        }
    });

    QUnit.testStart(function (test) {
    });

    QUnit.log(function (test) {
        if (!test.result) {
            console.log(test.message);
            delete test.message;
            console.log(test);
        }
    });

    QUnit.testDone(function (test) {
    });

    QUnit.done(function (data) {
        console.log(data);
    });

    tests.forEach(test => requirejs(test)(QUnit, requirejs));

    QUnit.load();
});
<commit_msg>test.js: using exit code 1 to indicate failure of a file<commit_after>#!/usr/bin/env node

"use strict";

var fs = require('fs');
var requirejs = require('requirejs');
var QUnit = require('qunitjs');

var tests = ['core/test/byeresult',
    'core/test/correctionmodel',
    'core/test/correctionreferencemodel',
    'core/test/emitter',
    'core/test/listener',
    'core/test/matchmodel',
    'core/test/matchreferencemodel',
    'core/test/matchresult',
    'core/test/model',
    'core/test/propertymodel',
    'core/test/propertyvaluemodel',
    'core/test/random',
    'core/test/resultreferencemodel',
    'core/test/rle',
    'core/test/selectionvaluemodel',
    'core/test/statevaluemodel',
    'core/test/type',
    'core/test/valuemodel',
    'list/test/binningreferencelistmodel',
    'list/test/combinedreferencelistmodel',
    'list/test/indexedlistmodel',
    'list/test/indexedmodel',
    'list/test/lengthmodel',
    'list/test/listmodel',
    'list/test/listupdatelistener',
    'list/test/maplistmodel',
    'list/test/orderlistmodel',
    'list/test/readonlylistmodel',
    'list/test/referencelistmodel',
    'list/test/sortedreferencelistmodel',
    'list/test/uniquelistmodel',
    'math/test/absolutematrix',
    'math/test/antisymmetricmatrixmodel',
    'math/test/delegatematrix',
    'math/test/matrixmodel',
    'math/test/positivematrix',
    'math/test/symmetricmatrixmodel',
    'math/test/transposedifferencematrix',
    'math/test/transposesummatrix',
    'math/test/trianglematrixmodel',
    'math/test/vectormodel',
    'ranking/test/rankingcomponentindex',
    'ranking/test/rankingdatalistenerindex',
    'ranking/test/rankingheadtohead',
    'ranking/test/rankingmapper',
    'ranking/test/rankingmodel',
    'ranking/test/rankingsonneborn',
    'ranking/test/rankingtac',
    'timemachine/test/keymodel',
    'timemachine/test/query',
    'tournament/test/kotournamentmodel',
    'tournament/test/roundtournamentmodel',
    'tournament/test/swisstournamentmodel',
    'tournament/test/tournamentindex',
    'tournament/test/tournamentlistmodel',
    'tournament/test/tournamentmodel',
    //'ui/test/binarytreemodel',
    //'ui/test/listcollectormodel',
    //'ui/test/playermodel',
    //'ui/test/teammodel',
    //'ui/test/teamsfileloadcontroller'
];

process.chdir(__dirname);

requirejs.config({
    baseUrl: '../scripts'
});

requirejs(['core/config'], function (config) {
    var myBase = '../test/scripts/';

    requirejs.config({
        paths: {
            'options': myBase + 'options',
            'presets': myBase + 'presets',
            'strings': myBase + 'strings'
        }
    });

    QUnit.testStart(function (test) {
    });

    QUnit.log(function (test) {
        if (!test.result) {
            console.log(test.message);
            delete test.message;
            console.log(test);
        }
    });

    QUnit.testDone(function (test) {
    });

    QUnit.done(function (data) {
        console.log(data);
        if (data.failed) {
            process.exit(1);
        }
    });

    tests.forEach(test => requirejs(test)(QUnit, requirejs));

    QUnit.load();
});
<|endoftext|>


<commit_before>import React from 'react';
import Components from 'stockflux-components';
import MESSAGES from './messages';
import SearchResults from './SearchResults';

export default ({ results, children, isSearching, debouncedQuery }) => {
  const messageJsx = isSearching ? (
    <Components.Spinner />
  ) : (

{debouncedQuery ? MESSAGES.NO_MATCHES : MESSAGES.INITIAL}

  );

  return (
    <>
      {children}
      {results && results.length > 0 ? (
        <SearchResults results={results} paddingNeeded={children} />
      ) : (
        messageJsx
      )}
    </>
  );
};
<commit_msg>Ensure imports are not all caps<commit_after>import React from 'react';
import Components from 'stockflux-components';
import messages from './messages';
import SearchResults from './SearchResults';

export default ({ results, children, isSearching, debouncedQuery }) => {
  const messageJsx = isSearching ? (
    <Components.Spinner />
  ) : (

{debouncedQuery ? messages.NO_MATCHES : messages.INITIAL}

  );

  return (
    <>
      {children}
      {results && results.length > 0 ? (
        <SearchResults results={results} paddingNeeded={children} />
      ) : (
        messageJsx
      )}
    </>
  );
};
<|endoftext|>


<commit_before>import { remove as removeDiacritics } from 'diacritics';
import { fixRTLTextForSvg, rtlRegex } from './svg_paths_rtl_fix';

import { t, textDirection } from './locale';
import { utilArrayUnion } from './array';
import { utilDetect } from './detect';

export function utilTagText(entity) {
    var obj = (entity && entity.tags) || {};
    return Object.keys(obj)
        .map(function(k) { return k + '=' + obj[k]; })
        .join(', ');
}

export function utilTagDiff(oldTags, newTags) {
    var tagDiff = [];
    var keys = utilArrayUnion(Object.keys(oldTags), Object.keys(newTags)).sort();
    keys.forEach(function(k) {
        var oldVal = oldTags[k];
        var newVal = newTags[k];

        if (oldVal && (!newVal || newVal !== oldVal)) {
            tagDiff.push({
                type: '-',
                key: k,
                oldVal: oldVal,
                newVal: newVal,
                display: '- ' + k + '=' + oldVal
            });
        }
        if (newVal && (!oldVal || newVal !== oldVal)) {
            tagDiff.push({
                type: '+',
                key: k,
                oldVal: oldVal,
                newVal: newVal,
                display: '+ ' + k + '=' + newVal
            });
        }
    });
    return tagDiff;
}

export function utilEntitySelector(ids) {
    return ids.length ? '.' + ids.join(',.') : 'nothing';
}

// returns an selector to select entity ids for:
//  - entityIDs passed in
//  - shallow descendant entityIDs for any of those entities that are relations
export function utilEntityOrMemberSelector(ids, graph) {
    var seen = new Set(ids);
    ids.forEach(collectShallowDescendants);
    return utilEntitySelector(Array.from(seen));

    function collectShallowDescendants(id) {
        var entity = graph.hasEntity(id);
        if (!entity || entity.type !== 'relation') return;

        entity.members
            .map(function(member) { return member.id; })
            .forEach(function(id) { seen.add(id); });
    }
}

// returns an selector to select entity ids for:
//  - entityIDs passed in
//  - deep descendant entityIDs for any of those entities that are relations
export function utilEntityOrDeepMemberSelector(ids, graph) {
    return utilEntitySelector(utilEntityAndDeepMemberIDs(ids, graph));
}

// returns an selector to select entity ids for:
//  - entityIDs passed in
//  - deep descendant entityIDs for any of those entities that are relations
export function utilEntityAndDeepMemberIDs(ids, graph) {
    var seen = new Set();
    ids.forEach(collectDeepDescendants);
    return Array.from(seen);

    function collectDeepDescendants(id) {
        if (seen.has(id)) return;
        seen.add(id);

        var entity = graph.hasEntity(id);
        if (!entity || entity.type !== 'relation') return;

        entity.members
            .map(function(member) { return member.id; })
            .forEach(collectDeepDescendants);   // recurse
    }
}

// returns an selector to select entity ids for:
//  - deep descendant entityIDs for any of those entities that are relations
export function utilDeepMemberSelector(ids, graph, skipMultipolgonMembers) {
    var idsSet = new Set(ids);
    var seen = new Set();
    var returners = new Set();
    ids.forEach(collectDeepDescendants);
    return utilEntitySelector(Array.from(returners));

    function collectDeepDescendants(id) {
        if (seen.has(id)) return;
        seen.add(id);

        if (!idsSet.has(id)) {
            returners.add(id);
        }

        var entity = graph.hasEntity(id);
        if (!entity || entity.type !== 'relation') return;
        if (skipMultipolgonMembers && entity.isMultipolygon()) return;
        entity.members
            .map(function(member) { return member.id; })
            .forEach(collectDeepDescendants);   // recurse
    }
}

// Adds or removes highlight styling for the specified entities
export function utilHighlightEntities(ids, highlighted, context) {
    context.surface()
        .selectAll(utilEntityOrDeepMemberSelector(ids, context.graph()))
        .classed('highlighted', highlighted);
}

// returns an Array that is the union of:
//  - nodes for any nodeIDs passed in
//  - child nodes of any wayIDs passed in
//  - descendant member and child nodes of relationIDs passed in
export function utilGetAllNodes(ids, graph) {
    var seen = new Set();
    var nodes = new Set();

    ids.forEach(collectNodes);
    return Array.from(nodes);

    function collectNodes(id) {
        if (seen.has(id)) return;
        seen.add(id);

        var entity = graph.hasEntity(id);
        if (!entity) return;

        if (entity.type === 'node') {
            nodes.add(entity);
        } else if (entity.type === 'way') {
            entity.nodes.forEach(collectNodes);
        } else {
            entity.members
                .map(function(member) { return member.id; })
                .forEach(collectNodes);   // recurse
        }
    }
}

export function utilDisplayName(entity) {
    var localizedNameKey = 'name:' + utilDetect().locale.toLowerCase().split('-')[0];
    var name = entity.tags[localizedNameKey] || entity.tags.name || '';
    var network = entity.tags.cycle_network || entity.tags.network;

    if (!name && entity.tags.ref) {
        name = entity.tags.ref;
        if (network) {
            name = network + ' ' + name;
        }
    }

    return name;
}

export function utilDisplayNameForPath(entity) {
    var name = utilDisplayName(entity);
    var isFirefox = utilDetect().browser.toLowerCase().indexOf('firefox') > -1;

    if (!isFirefox && name && rtlRegex.test(name)) {
        name = fixRTLTextForSvg(name);
    }

    return name;
}

export function utilDisplayType(id) {
    return {
        n: t('inspector.node'),
        w: t('inspector.way'),
        r: t('inspector.relation')
    }[id.charAt(0)];
}

export function utilDisplayLabel(entity, context) {
    var displayName = utilDisplayName(entity);
    if (displayName) {
        // use the display name if there is one
        return displayName;
    }
    var preset = utilPreset(entity, context);
    if (preset && preset.name()) {
        // use the preset name if there is a match
        return preset.name();
    }
    // fallback to the display type (node/way/relation)
    return utilDisplayType(entity.id);
}

export function utilPreset(entity, context) {
    return context.presets().match(entity, context.graph());
}

export function utilEntityRoot(entityType) {
    return {
        node: 'n',
        way: 'w',
        relation: 'r'
    }[entityType];
}

// Returns a single object containing the tags of all the given entities.
// Example:
// {
//   highway: 'service',
//   service: 'parking_aisle'
// }
//           +
// {
//   highway: 'service',
//   service: 'driveway',
//   width: '3'
// }
//           =
// {
//   highway: 'service',
//   service: [ 'driveway', 'parking_aisle' ],
//   width: [ '3', undefined ]
// }
export function utilCombinedTags(entityIDs, graph) {

    var tags = {};
    var tagCounts = {};
    var allKeys = new Set();

    var entities = entityIDs.map(function(entityID) {
        return graph.hasEntity(entityID);
    }).filter(Boolean);

    // gather the aggregate keys
    entities.forEach(function(entity) {
        var keys = Object.keys(entity.tags).filter(Boolean);
        keys.forEach(function(key) {
            allKeys.add(key);
        });
    });

    entities.forEach(function(entity) {

        allKeys.forEach(function(key) {

            var value = entity.tags[key]; // purposely allow `undefined`

            if (!tags.hasOwnProperty(key)) {
                // first value, set as raw
                tags[key] = value;
            } else {
                if (!Array.isArray(tags[key])) {
                    if (tags[key] !== value) {
                        // first alternate value, replace single value with array
                        tags[key] = [tags[key], value];
                    }
                } else { // type is array
                    if (tags[key].indexOf(value) === -1) {
                        // subsequent alternate value, add to array
                        tags[key].push(value);
                    }
                }
            }

            var tagHash = key + '=' + value;
            if (!tagCounts[tagHash]) tagCounts[tagHash] = 0;
            tagCounts[tagHash] += 1;
        });
    });

    for (var key in tags) {
        if (!Array.isArray(tags[key])) continue;

        // sort values by frequency then alphabetically
        tags[key] = tags[key].sort(function(val1, val2) {
            var key = key; // capture
            var count2 = tagCounts[key + '=' + val2];
            var count1 = tagCounts[key + '=' + val1];
            if (count2 !== count1) {
                return count2 - count1;
            }
            if (val2 && val1) {
                return val1.localeCompare(val2);
            }
            return val1 ? 1 : -1;
        });
    }

    return tags;
}

export function utilStringQs(str) {
    var i = 0;  // advance past any leading '?' or '#' characters
    while (i < str.length && (str[i] === '?' || str[i] === '#')) i++;
    str = str.slice(i);

    return str.split('&').reduce(function(obj, pair){
        var parts = pair.split('=');
        if (parts.length === 2) {
            obj[parts[0]] = (null === parts[1]) ? '' : decodeURIComponent(parts[1]);
        }
        return obj;
    }, {});
}

export function utilQsString(obj, noencode) {
    // encode everything except special characters used in certain hash parameters:
    // "/" in map states, ":", ",", {" and "}" in background
    function softEncode(s) {
        return encodeURIComponent(s).replace(/(%2F|%3A|%2C|%7B|%7D)/g, decodeURIComponent);
    }

    return Object.keys(obj).sort().map(function(key) {
        return encodeURIComponent(key) + '=' + (
            noencode ? softEncode(obj[key]) : encodeURIComponent(obj[key]));
    }).join('&');
}

export function utilPrefixDOMProperty(property) {
    var prefixes = ['webkit', 'ms', 'moz', 'o'];
    var i = -1;
    var n = prefixes.length;
    var s = document.body;

    if (property in s)
        return property;

    property = property.substr(0, 1).toUpperCase() + property.substr(1);

    while (++i < n) {
        if (prefixes[i] + property in s) {
            return prefixes[i] + property;
        }
    }

    return false;
}

export function utilPrefixCSSProperty(property) {
    var prefixes = ['webkit', 'ms', 'Moz', 'O'];
    var i = -1;
    var n = prefixes.length;
    var s = document.body.style;

    if (property.toLowerCase() in s) {
        return property.toLowerCase();
    }

    while (++i < n) {
        if (prefixes[i] + property in s) {
            return '-' + prefixes[i].toLowerCase() + property.replace(/([A-Z])/g, '-$1').toLowerCase();
        }
    }

    return false;
}

var transformProperty;
export function utilSetTransform(el, x, y, scale) {
    var prop = transformProperty = transformProperty || utilPrefixCSSProperty('Transform');
    var translate = utilDetect().opera ? 'translate('   + x + 'px,' + y + 'px)'
        : 'translate3d(' + x + 'px,' + y + 'px,0)';
    return el.style(prop, translate + (scale ? ' scale(' + scale + ')' : ''));
}

// Calculates Levenshtein distance between two strings
// see:  https://en.wikipedia.org/wiki/Levenshtein_distance
// first converts the strings to lowercase and replaces diacritic marks with ascii equivalents.
export function utilEditDistance(a, b) {
    a = removeDiacritics(a.toLowerCase());
    b = removeDiacritics(b.toLowerCase());
    if (a.length === 0) return b.length;
    if (b.length === 0) return a.length;
    var matrix = [];
    for (var i = 0; i <= b.length; i++) { matrix[i] = [i]; }
    for (var j = 0; j <= a.length; j++) { matrix[0][j] = j; }
    for (i = 1; i <= b.length; i++) {
        for (j = 1; j <= a.length; j++) {
            if (b.charAt(i-1) === a.charAt(j-1)) {
                matrix[i][j] = matrix[i-1][j-1];
            } else {
                matrix[i][j] = Math.min(matrix[i-1][j-1] + 1, // substitution
                    Math.min(matrix[i][j-1] + 1, // insertion
                    matrix[i-1][j] + 1)); // deletion
            }
        }
    }
    return matrix[b.length][a.length];
}

// a d3.mouse-alike which
// 1. Only works on HTML elements, not SVG
// 2. Does not cause style recalculation
export function utilFastMouse(container) {
    var rect = container.getBoundingClientRect();
    var rectLeft = rect.left;
    var rectTop = rect.top;
    var clientLeft = +container.clientLeft;
    var clientTop = +container.clientTop;

    if (textDirection === 'rtl') {
        rectLeft = 0;
    }
    return function(e) {
        return [
            e.clientX - rectLeft - clientLeft,
            e.clientY - rectTop - clientTop];
    };
}

export function utilAsyncMap(inputs, func, callback) {
    var remaining = inputs.length;
    var results = [];
    var errors = [];

    inputs.forEach(function(d, i) {
        func(d, function done(err, data) {
            errors[i] = err;
            results[i] = data;
            remaining--;
            if (!remaining) callback(errors, results);
        });
    });
}

// wraps an index to an interval [0..length-1]
export function utilWrap(index, length) {
    if (index < 0) {
        index += Math.ceil(-index/length)*length;
    }
    return index % length;
}

/**
 * a replacement for functor
 *
 * @param {*} value any value
 * @returns {Function} a function that returns that value or the value if it's a function
 */
export function utilFunctor(value) {
    if (typeof value === 'function') return value;
    return function() {
        return value;
    };
}

export function utilNoAuto(selection) {
    var isText = (selection.size() && selection.node().tagName.toLowerCase() === 'textarea');

    return selection
        // assign 'new-password' even for non-password fields to prevent browsers (Chrome) ignoring 'off'
        .attr('autocomplete', 'new-password')
        .attr('autocorrect', 'off')
        .attr('autocapitalize', 'off')
        .attr('spellcheck', isText ? 'true' : 'false');
}

// https://stackoverflow.com/questions/194846/is-there-any-kind-of-hash-code-function-in-javascript
// https://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/
export function utilHashcode(str) {
    var hash = 0;
    if (str.length === 0) {
        return hash;
    }
    for (var i = 0; i < str.length; i++) {
        var char = str.charCodeAt(i);
        hash = ((hash << 5) - hash) + char;
        hash = hash & hash; // Convert to 32bit integer
    }
    return hash;
}

// returns version of `str` with all runs of special characters replaced by `_`;
// suitable for HTML ids, classes, selectors, etc.
export function utilSafeClassName(str) {
    return str.toLowerCase().replace(/[^a-z0-9]+/g, '_');
}
<commit_msg>Account for empty string tag values in utilTagDiff (re: #7363)<commit_after>import { remove as removeDiacritics } from 'diacritics';
import { fixRTLTextForSvg, rtlRegex } from './svg_paths_rtl_fix';

import { t, textDirection } from './locale';
import { utilArrayUnion } from './array';
import { utilDetect } from './detect';

export function utilTagText(entity) {
    var obj = (entity && entity.tags) || {};
    return Object.keys(obj)
        .map(function(k) { return k + '=' + obj[k]; })
        .join(', ');
}

export function utilTagDiff(oldTags, newTags) {
    var tagDiff = [];
    var keys = utilArrayUnion(Object.keys(oldTags), Object.keys(newTags)).sort();
    keys.forEach(function(k) {
        var oldVal = oldTags[k];
        var newVal = newTags[k];

        if (oldVal && (newVal === undefined || newVal !== oldVal)) {
            tagDiff.push({
                type: '-',
                key: k,
                oldVal: oldVal,
                newVal: newVal,
                display: '- ' + k + '=' + oldVal
            });
        }
        if (newVal && (oldVal === undefined || newVal !== oldVal)) {
            tagDiff.push({
                type: '+',
                key: k,
                oldVal: oldVal,
                newVal: newVal,
                display: '+ ' + k + '=' + newVal
            });
        }
    });
    return tagDiff;
}

export function utilEntitySelector(ids) {
    return ids.length ? '.' + ids.join(',.') : 'nothing';
}

// returns an selector to select entity ids for:
//  - entityIDs passed in
//  - shallow descendant entityIDs for any of those entities that are relations
export function utilEntityOrMemberSelector(ids, graph) {
    var seen = new Set(ids);
    ids.forEach(collectShallowDescendants);
    return utilEntitySelector(Array.from(seen));

    function collectShallowDescendants(id) {
        var entity = graph.hasEntity(id);
        if (!entity || entity.type !== 'relation') return;

        entity.members
            .map(function(member) { return member.id; })
            .forEach(function(id) { seen.add(id); });
    }
}

// returns an selector to select entity ids for:
//  - entityIDs passed in
//  - deep descendant entityIDs for any of those entities that are relations
export function utilEntityOrDeepMemberSelector(ids, graph) {
    return utilEntitySelector(utilEntityAndDeepMemberIDs(ids, graph));
}

// returns an selector to select entity ids for:
//  - entityIDs passed in
//  - deep descendant entityIDs for any of those entities that are relations
export function utilEntityAndDeepMemberIDs(ids, graph) {
    var seen = new Set();
    ids.forEach(collectDeepDescendants);
    return Array.from(seen);

    function collectDeepDescendants(id) {
        if (seen.has(id)) return;
        seen.add(id);

        var entity = graph.hasEntity(id);
        if (!entity || entity.type !== 'relation') return;

        entity.members
            .map(function(member) { return member.id; })
            .forEach(collectDeepDescendants);   // recurse
    }
}

// returns an selector to select entity ids for:
//  - deep descendant entityIDs for any of those entities that are relations
export function utilDeepMemberSelector(ids, graph, skipMultipolgonMembers) {
    var idsSet = new Set(ids);
    var seen = new Set();
    var returners = new Set();
    ids.forEach(collectDeepDescendants);
    return utilEntitySelector(Array.from(returners));

    function collectDeepDescendants(id) {
        if (seen.has(id)) return;
        seen.add(id);

        if (!idsSet.has(id)) {
            returners.add(id);
        }

        var entity = graph.hasEntity(id);
        if (!entity || entity.type !== 'relation') return;
        if (skipMultipolgonMembers && entity.isMultipolygon()) return;
        entity.members
            .map(function(member) { return member.id; })
            .forEach(collectDeepDescendants);   // recurse
    }
}

// Adds or removes highlight styling for the specified entities
export function utilHighlightEntities(ids, highlighted, context) {
    context.surface()
        .selectAll(utilEntityOrDeepMemberSelector(ids, context.graph()))
        .classed('highlighted', highlighted);
}

// returns an Array that is the union of:
//  - nodes for any nodeIDs passed in
//  - child nodes of any wayIDs passed in
//  - descendant member and child nodes of relationIDs passed in
export function utilGetAllNodes(ids, graph) {
    var seen = new Set();
    var nodes = new Set();

    ids.forEach(collectNodes);
    return Array.from(nodes);

    function collectNodes(id) {
        if (seen.has(id)) return;
        seen.add(id);

        var entity = graph.hasEntity(id);
        if (!entity) return;

        if (entity.type === 'node') {
            nodes.add(entity);
        } else if (entity.type === 'way') {
            entity.nodes.forEach(collectNodes);
        } else {
            entity.members
                .map(function(member) { return member.id; })
                .forEach(collectNodes);   // recurse
        }
    }
}

export function utilDisplayName(entity) {
    var localizedNameKey = 'name:' + utilDetect().locale.toLowerCase().split('-')[0];
    var name = entity.tags[localizedNameKey] || entity.tags.name || '';
    var network = entity.tags.cycle_network || entity.tags.network;

    if (!name && entity.tags.ref) {
        name = entity.tags.ref;
        if (network) {
            name = network + ' ' + name;
        }
    }

    return name;
}

export function utilDisplayNameForPath(entity) {
    var name = utilDisplayName(entity);
    var isFirefox = utilDetect().browser.toLowerCase().indexOf('firefox') > -1;

    if (!isFirefox && name && rtlRegex.test(name)) {
        name = fixRTLTextForSvg(name);
    }

    return name;
}

export function utilDisplayType(id) {
    return {
        n: t('inspector.node'),
        w: t('inspector.way'),
        r: t('inspector.relation')
    }[id.charAt(0)];
}

export function utilDisplayLabel(entity, context) {
    var displayName = utilDisplayName(entity);
    if (displayName) {
        // use the display name if there is one
        return displayName;
    }
    var preset = utilPreset(entity, context);
    if (preset && preset.name()) {
        // use the preset name if there is a match
        return preset.name();
    }
    // fallback to the display type (node/way/relation)
    return utilDisplayType(entity.id);
}

export function utilPreset(entity, context) {
    return context.presets().match(entity, context.graph());
}

export function utilEntityRoot(entityType) {
    return {
        node: 'n',
        way: 'w',
        relation: 'r'
    }[entityType];
}

// Returns a single object containing the tags of all the given entities.
// Example:
// {
//   highway: 'service',
//   service: 'parking_aisle'
// }
//           +
// {
//   highway: 'service',
//   service: 'driveway',
//   width: '3'
// }
//           =
// {
//   highway: 'service',
//   service: [ 'driveway', 'parking_aisle' ],
//   width: [ '3', undefined ]
// }
export function utilCombinedTags(entityIDs, graph) {

    var tags = {};
    var tagCounts = {};
    var allKeys = new Set();

    var entities = entityIDs.map(function(entityID) {
        return graph.hasEntity(entityID);
    }).filter(Boolean);

    // gather the aggregate keys
    entities.forEach(function(entity) {
        var keys = Object.keys(entity.tags).filter(Boolean);
        keys.forEach(function(key) {
            allKeys.add(key);
        });
    });

    entities.forEach(function(entity) {

        allKeys.forEach(function(key) {

            var value = entity.tags[key]; // purposely allow `undefined`

            if (!tags.hasOwnProperty(key)) {
                // first value, set as raw
                tags[key] = value;
            } else {
                if (!Array.isArray(tags[key])) {
                    if (tags[key] !== value) {
                        // first alternate value, replace single value with array
                        tags[key] = [tags[key], value];
                    }
                } else { // type is array
                    if (tags[key].indexOf(value) === -1) {
                        // subsequent alternate value, add to array
                        tags[key].push(value);
                    }
                }
            }

            var tagHash = key + '=' + value;
            if (!tagCounts[tagHash]) tagCounts[tagHash] = 0;
            tagCounts[tagHash] += 1;
        });
    });

    for (var key in tags) {
        if (!Array.isArray(tags[key])) continue;

        // sort values by frequency then alphabetically
        tags[key] = tags[key].sort(function(val1, val2) {
            var key = key; // capture
            var count2 = tagCounts[key + '=' + val2];
            var count1 = tagCounts[key + '=' + val1];
            if (count2 !== count1) {
                return count2 - count1;
            }
            if (val2 && val1) {
                return val1.localeCompare(val2);
            }
            return val1 ? 1 : -1;
        });
    }

    return tags;
}

export function utilStringQs(str) {
    var i = 0;  // advance past any leading '?' or '#' characters
    while (i < str.length && (str[i] === '?' || str[i] === '#')) i++;
    str = str.slice(i);

    return str.split('&').reduce(function(obj, pair){
        var parts = pair.split('=');
        if (parts.length === 2) {
            obj[parts[0]] = (null === parts[1]) ? '' : decodeURIComponent(parts[1]);
        }
        return obj;
    }, {});
}

export function utilQsString(obj, noencode) {
    // encode everything except special characters used in certain hash parameters:
    // "/" in map states, ":", ",", {" and "}" in background
    function softEncode(s) {
        return encodeURIComponent(s).replace(/(%2F|%3A|%2C|%7B|%7D)/g, decodeURIComponent);
    }

    return Object.keys(obj).sort().map(function(key) {
        return encodeURIComponent(key) + '=' + (
            noencode ? softEncode(obj[key]) : encodeURIComponent(obj[key]));
    }).join('&');
}

export function utilPrefixDOMProperty(property) {
    var prefixes = ['webkit', 'ms', 'moz', 'o'];
    var i = -1;
    var n = prefixes.length;
    var s = document.body;

    if (property in s)
        return property;

    property = property.substr(0, 1).toUpperCase() + property.substr(1);

    while (++i < n) {
        if (prefixes[i] + property in s) {
            return prefixes[i] + property;
        }
    }

    return false;
}

export function utilPrefixCSSProperty(property) {
    var prefixes = ['webkit', 'ms', 'Moz', 'O'];
    var i = -1;
    var n = prefixes.length;
    var s = document.body.style;

    if (property.toLowerCase() in s) {
        return property.toLowerCase();
    }

    while (++i < n) {
        if (prefixes[i] + property in s) {
            return '-' + prefixes[i].toLowerCase() + property.replace(/([A-Z])/g, '-$1').toLowerCase();
        }
    }

    return false;
}

var transformProperty;
export function utilSetTransform(el, x, y, scale) {
    var prop = transformProperty = transformProperty || utilPrefixCSSProperty('Transform');
    var translate = utilDetect().opera ? 'translate('   + x + 'px,' + y + 'px)'
        : 'translate3d(' + x + 'px,' + y + 'px,0)';
    return el.style(prop, translate + (scale ? ' scale(' + scale + ')' : ''));
}

// Calculates Levenshtein distance between two strings
// see:  https://en.wikipedia.org/wiki/Levenshtein_distance
// first converts the strings to lowercase and replaces diacritic marks with ascii equivalents.
export function utilEditDistance(a, b) {
    a = removeDiacritics(a.toLowerCase());
    b = removeDiacritics(b.toLowerCase());
    if (a.length === 0) return b.length;
    if (b.length === 0) return a.length;
    var matrix = [];
    for (var i = 0; i <= b.length; i++) { matrix[i] = [i]; }
    for (var j = 0; j <= a.length; j++) { matrix[0][j] = j; }
    for (i = 1; i <= b.length; i++) {
        for (j = 1; j <= a.length; j++) {
            if (b.charAt(i-1) === a.charAt(j-1)) {
                matrix[i][j] = matrix[i-1][j-1];
            } else {
                matrix[i][j] = Math.min(matrix[i-1][j-1] + 1, // substitution
                    Math.min(matrix[i][j-1] + 1, // insertion
                    matrix[i-1][j] + 1)); // deletion
            }
        }
    }
    return matrix[b.length][a.length];
}

// a d3.mouse-alike which
// 1. Only works on HTML elements, not SVG
// 2. Does not cause style recalculation
export function utilFastMouse(container) {
    var rect = container.getBoundingClientRect();
    var rectLeft = rect.left;
    var rectTop = rect.top;
    var clientLeft = +container.clientLeft;
    var clientTop = +container.clientTop;

    if (textDirection === 'rtl') {
        rectLeft = 0;
    }
    return function(e) {
        return [
            e.clientX - rectLeft - clientLeft,
            e.clientY - rectTop - clientTop];
    };
}

export function utilAsyncMap(inputs, func, callback) {
    var remaining = inputs.length;
    var results = [];
    var errors = [];

    inputs.forEach(function(d, i) {
        func(d, function done(err, data) {
            errors[i] = err;
            results[i] = data;
            remaining--;
            if (!remaining) callback(errors, results);
        });
    });
}

// wraps an index to an interval [0..length-1]
export function utilWrap(index, length) {
    if (index < 0) {
        index += Math.ceil(-index/length)*length;
    }
    return index % length;
}

/**
 * a replacement for functor
 *
 * @param {*} value any value
 * @returns {Function} a function that returns that value or the value if it's a function
 */
export function utilFunctor(value) {
    if (typeof value === 'function') return value;
    return function() {
        return value;
    };
}

export function utilNoAuto(selection) {
    var isText = (selection.size() && selection.node().tagName.toLowerCase() === 'textarea');

    return selection
        // assign 'new-password' even for non-password fields to prevent browsers (Chrome) ignoring 'off'
        .attr('autocomplete', 'new-password')
        .attr('autocorrect', 'off')
        .attr('autocapitalize', 'off')
        .attr('spellcheck', isText ? 'true' : 'false');
}

// https://stackoverflow.com/questions/194846/is-there-any-kind-of-hash-code-function-in-javascript
// https://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/
export function utilHashcode(str) {
    var hash = 0;
    if (str.length === 0) {
        return hash;
    }
    for (var i = 0; i < str.length; i++) {
        var char = str.charCodeAt(i);
        hash = ((hash << 5) - hash) + char;
        hash = hash & hash; // Convert to 32bit integer
    }
    return hash;
}

// returns version of `str` with all runs of special characters replaced by `_`;
// suitable for HTML ids, classes, selectors, etc.
export function utilSafeClassName(str) {
    return str.toLowerCase().replace(/[^a-z0-9]+/g, '_');
}
<|endoftext|>


<commit_before>import React, {Component} from 'react'
import Table from 'grommet/components/Table'
import TableRow from 'grommet/components/TableRow'
import Heading from 'grommet/components/Heading'
import Box from 'grommet/components/Box'
import Select from 'grommet/components/Select'
import Columns from 'grommet/components/Columns'
import FormField from 'grommet/components/FormField'
import DateTime from 'grommet/components/DateTime'

import {Link} from 'react-router-dom'

import axios from 'axios'
import numeral from 'numeral'
import moment from 'moment'
moment.locale('es')

class Bills extends Component {

  getDate = () => {
    const now = new Date()
    return `${now.getMonth()+1}/${now.getFullYear()}`
  }

  state = {
    bills: [],
    error: false,
    providerOptions: [],
    vehicleOptions: [],
    selectedVehicle: 'Todos',
    selectedProvider: 'Todos',
    date: this.getDate()
  }
  componentDidMount() {
    this.fetchProviders()
    this.fetchVehicles()
    axios.get('/api/bill')
    .then(({data}) => {
      this.setState(() => ({bills: data}))
    })
    .catch(err => {
      this.setState({
        error: true
      })
    })
  }

  fetchProviders = () => {
    axios.get('/api/provider')
    .then(({data}) => {
      this.setState({
        providerOptions: data
      })
    })
  }

  fetchVehicles = () => {
    axios.get('/api/vehicles')
    .then(({data}) => {
      this.setState({
        vehicleOptions: data
      })
    })
  }

  handleProviderSelect = ({option}) => {
    this.setState({
      selectedProvider: option
    })
  }

  handleVehicleSelect = ({option}) => {
    this.setState({
      selectedVehicle: option
    })
  }

  filteredData = () => {
    const bills = this.state.bills.filter(bill => {
      const date = new Date(bill.date)
      return `${date.getMonth()+1}/${date.getFullYear()}` === this.state.date
    })
    if(this.state.selectedProvider === 'Todos' && this.state.selectedVehicle==='Todos'){
      return bills
    } else {
      return bills.filter(bill => {
        let ok = true
        if(this.state.selectedProvider !== 'Todos'){
          ok = bill.provider.nombre === this.state.selectedProvider
        }
        if(this.state.selectedVehicle !=='Todos'){
          if(ok){
            if(bill.vehicle){
              const vehicle = bill.vehicle
              ok = `${vehicle.modelo} ${vehicle.color} ${vehicle.placas}` === this.state.selectedVehicle
            } else {
              ok = false
            }
          }
        }
        return ok
      })
    }
  }

  filteredProviderOptions = () => {
    const options = this.state.providerOptions.map(opt => opt.nombre)
    options.unshift('Todos')
    return options
  }

  filteredVehicleOptions = () => {
    const options = this.state.vehicleOptions.map(opt => `${opt.modelo} ${opt.color} ${opt.placas}`)
    options.unshift('Todos')
    return options
  }

  handleDate = (date) => {
    this.setState(() => ({date}))
  }

  render(){
    return(
      <Box align='center'>
        <Heading>Facturas</Heading>
        <Columns justify='center' size='small'>
          <FormField label='Proveedor'>
            <Select options={this.filteredProviderOptions()} onChange={this.handleProviderSelect} value={this.state.selectedProvider} />
          </FormField>
          <FormField label='Vehículo'>
            <Select options={this.filteredVehicleOptions()} onChange={this.handleVehicleSelect} value={this.state.selectedVehicle}/>
          </FormField>
          <FormField label='Mes/Año'>
            <DateTime format='M/YYYY' value={this.state.date} onChange={this.handleDate}/>
          </FormField>
        </Columns>

                Proveedor

                Total

                Fecha

                Vehículo

                Detalles

            {this.filteredData().map((bill) => {
              return(
                <TableRow key={bill._id}>
                  {bill.provider ? {bill.provider.nombre}	: Ninguno	}
                  ${numeral(bill.total).format('0,0')}
                  {moment(bill.date).format('LL')}
                  {bill.vehicle ? `${bill.vehicle.modelo} ${bill.vehicle.color} ${bill.vehicle.placas}` : 'No aplica'}
                  <Link to={'/factura/' + bill._id} style={{textDecoration: 'none', color: 'white'}}><Box colorIndex='brand' align='center' style={{borderRadius: '10px'}}>Ver Detalles</Box></Link>
                </TableRow>
              )
            })}

      </Box>
    )
  }
}

export default Bills
<commit_msg>Fix Vehicles fields in bills component<commit_after>import React, {Component} from 'react'
import Table from 'grommet/components/Table'
import TableRow from 'grommet/components/TableRow'
import Heading from 'grommet/components/Heading'
import Box from 'grommet/components/Box'
import Select from 'grommet/components/Select'
import Columns from 'grommet/components/Columns'
import FormField from 'grommet/components/FormField'
import DateTime from 'grommet/components/DateTime'

import {Link} from 'react-router-dom'

import axios from 'axios'
import numeral from 'numeral'
import moment from 'moment'
moment.locale('es')

class Bills extends Component {

  getDate = () => {
    const now = new Date()
    return `${now.getMonth()+1}/${now.getFullYear()}`
  }

  state = {
    bills: [],
    error: false,
    providerOptions: [],
    vehicleOptions: [],
    selectedVehicle: 'Todos',
    selectedProvider: 'Todos',
    date: this.getDate()
  }
  componentDidMount() {
    this.fetchProviders()
    this.fetchVehicles()
    axios.get('/api/bill')
    .then(({data}) => {
      this.setState(() => ({bills: data}))
    })
    .catch(err => {
      this.setState({
        error: true
      })
    })
  }

  fetchProviders = () => {
    axios.get('/api/provider')
    .then(({data}) => {
      this.setState({
        providerOptions: data
      })
    })
  }

  fetchVehicles = () => {
    axios.get('/api/vehicle')
    .then(({data}) => {
      this.setState({
        vehicleOptions: data
      })
    })
  }

  handleProviderSelect = ({option}) => {
    this.setState({
      selectedProvider: option
    })
  }

  handleVehicleSelect = ({option}) => {
    this.setState({
      selectedVehicle: option
    })
  }

  filteredData = () => {
    const bills = this.state.bills.filter(bill => {
      const date = new Date(bill.date)
      return `${date.getMonth()+1}/${date.getFullYear()}` === this.state.date
    })
    if(this.state.selectedProvider === 'Todos' && this.state.selectedVehicle==='Todos'){
      return bills
    } else {
      return bills.filter(bill => {
        let ok = true
        if(this.state.selectedProvider !== 'Todos'){
          ok = bill.provider.nombre === this.state.selectedProvider
        }
        if(this.state.selectedVehicle !=='Todos'){
          if(ok){
            if(bill.vehicle){
              const vehicle = bill.vehicle
              ok = `${vehicle.modelo} ${vehicle.color} ${vehicle.placas}` === this.state.selectedVehicle
            } else {
              ok = false
            }
          }
        }
        return ok
      })
    }
  }

  filteredProviderOptions = () => {
    const options = this.state.providerOptions.map(opt => opt.nombre)
    options.unshift('Todos')
    return options
  }

  filteredVehicleOptions = () => {
    const options = this.state.vehicleOptions.map(opt => `${opt.Modelo} ${opt.Color} ${opt.Placas}`)
    options.unshift('Todos')
    return options
  }

  handleDate = (date) => {
    this.setState(() => ({date}))
  }

  render(){
    return(
      <Box align='center'>
        <Heading>Facturas</Heading>
        <Columns justify='center' size='small'>
          <FormField label='Proveedor'>
            <Select options={this.filteredProviderOptions()} onChange={this.handleProviderSelect} value={this.state.selectedProvider} />
          </FormField>
          <FormField label='Vehículo'>
            <Select options={this.filteredVehicleOptions()} onChange={this.handleVehicleSelect} value={this.state.selectedVehicle}/>
          </FormField>
          <FormField label='Mes/Año'>
            <DateTime format='M/YYYY' value={this.state.date} onChange={this.handleDate}/>
          </FormField>
        </Columns>

                Proveedor

                Total

                Fecha

                Vehículo

                Detalles

            {this.filteredData().map((bill) => {
              return(
                <TableRow key={bill._id}>
                  {bill.provider ? {bill.provider.nombre}	: Ninguno	}
                  ${numeral(bill.total).format('0,0')}
                  {moment(bill.date).format('LL')}
                  {bill.vehicle ? `${bill.vehicle.modelo} ${bill.vehicle.color} ${bill.vehicle.placas}` : 'No aplica'}
                  <Link to={'/factura/' + bill._id} style={{textDecoration: 'none', color: 'white'}}><Box colorIndex='brand' align='center' style={{borderRadius: '10px'}}>Ver Detalles</Box></Link>
                </TableRow>
              )
            })}

      </Box>
    )
  }
}

export default Bills
<|endoftext|>


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

{% include 'erpnext/selling/sales_common.js' %};

cur_frm.add_fetch('customer', 'tax_id', 'tax_id');

frappe.provide("erpnext.stock");
frappe.provide("erpnext.stock.delivery_note");

frappe.ui.form.on("Delivery Note", {
	setup: function(frm) {
		frm.custom_make_buttons = {
			'Packing Slip': 'Packing Slip',
			'Installation Note': 'Installation Note',
			'Sales Invoice': 'Invoice',
			'Stock Entry': 'Return',
		},
		frm.set_indicator_formatter('item_code',
			function(doc) {
				return (doc.docstatus==1 || doc.qty<=doc.actual_qty) ? "green" : "orange"
			})

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

		frm.set_query('project', function(doc) {
			return {
				query: "erpnext.controllers.queries.get_project_name",
				filters: {
					'customer': doc.customer
				}
			}
		})

		frm.set_query('transporter', function() {
			return {
				filters: {
					'is_transporter': 1
				}
			}
		});

		frm.set_query('driver', function(doc) {
			return {
				filters: {
					'transporter': doc.transporter
				}
			}
		});

		frm.set_query('expense_account', 'items', function(doc, cdt, cdn) {
			if (erpnext.is_perpetual_inventory_enabled(doc.company)) {
				return {
					filters: {
						"report_type": "Profit and Loss",
						"company": doc.company,
						"is_group": 0
					}
				}
			}
		});

		frm.set_query('cost_center', 'items', function(doc, cdt, cdn) {
			if (erpnext.is_perpetual_inventory_enabled(doc.company)) {
				return {
					filters: {
						'company': doc.company,
						"is_group": 0
					}
				}
			}
		});

	},

	print_without_amount: function(frm) {
		erpnext.stock.delivery_note.set_print_hide(frm.doc);
	},

	refresh: function(frm) {
		if (frm.doc.docstatus === 1 && frm.doc.is_return === 1 && frm.doc.per_billed !== 100) {
			frm.add_custom_button(__('Credit Note'), function() {
				frappe.confirm(__("Are you sure you want to make credit note?"),
					function() {
						frm.trigger("make_credit_note");
					}
				);
			}, __('Create'));

			frm.page.set_inner_btn_group_as_primary(__('Create'));
		}
	},

	make_credit_note: function(frm) {
		frm.call({
			method: "make_return_invoice",
			doc: frm.doc,
			freeze: true,
			callback: function() {
				frm.reload_doc();
			}
		});
	}
});

frappe.ui.form.on("Delivery Note Item", {
	expense_account: function(frm, dt, dn) {
		var d = locals[dt][dn];
		frm.update_in_all_rows('items', 'expense_account', d.expense_account);
	},
	cost_center: function(frm, dt, dn) {
		var d = locals[dt][dn];
		frm.update_in_all_rows('items', 'cost_center', d.cost_center);
	}
});

erpnext.stock.DeliveryNoteController = erpnext.selling.SellingController.extend({
	setup: function(doc) {
		this.setup_posting_date_time_check();
		this._super(doc);
	},
	refresh: function(doc, dt, dn) {
		var me = this;
		this._super();
		if ((!doc.is_return) && (doc.status!="Closed" || this.frm.is_new())) {
			if (this.frm.doc.docstatus===0) {
				this.frm.add_custom_button(__('Sales Order'),
					function() {
						erpnext.utils.map_current_doc({
							method: "erpnext.selling.doctype.sales_order.sales_order.make_delivery_note",
							source_doctype: "Sales Order",
							target: me.frm,
							setters: {
								customer: me.frm.doc.customer || undefined,
							},
							get_query_filters: {
								docstatus: 1,
								status: ["not in", ["Closed", "On Hold"]],
								per_delivered: ["<", 99.99],
								company: me.frm.doc.company,
								project: me.frm.doc.project || undefined,
							}
						})
					}, __("Get items from"));
			}
		}

		if (!doc.is_return && doc.status!="Closed") {
			if(flt(doc.per_installed, 2) < 100 && doc.docstatus==1)
				this.frm.add_custom_button(__('Installation Note'), function() {
					me.make_installation_note() }, __('Create'));

			if (doc.docstatus==1) {
				this.frm.add_custom_button(__('Sales Return'), function() {
					me.make_sales_return() }, __('Create'));
			}

			if (doc.docstatus==1) {
				this.frm.add_custom_button(__('Delivery Trip'), function() {
					me.make_delivery_trip() }, __('Create'));
			}

			if(doc.docstatus==0 && !doc.__islocal) {
				this.frm.add_custom_button(__('Packing Slip'), function() {
					frappe.model.open_mapped_doc({
						method: "erpnext.stock.doctype.delivery_note.delivery_note.make_packing_slip",
						frm: me.frm
					}) }, __('Create'));
			}

			if (!doc.__islocal && doc.docstatus==1) {
				this.frm.page.set_inner_btn_group_as_primary(__('Create'));
			}
		}

		if (doc.docstatus==1) {
			this.show_stock_ledger();
			if (erpnext.is_perpetual_inventory_enabled(doc.company)) {
				this.show_general_ledger();
			}
			if (this.frm.has_perm("submit") && doc.status !== "Closed") {
				me.frm.add_custom_button(__("Close"), function() { me.close_delivery_note() },
					__("Status"))
			}
		}

		if(doc.docstatus==1 && !doc.is_return && doc.status!="Closed" && flt(doc.per_billed) < 100) {
			// show Make Invoice button only if Delivery Note is not created from Sales Invoice
			var from_sales_invoice = false;
			from_sales_invoice = me.frm.doc.items.some(function(item) {
				return item.against_sales_invoice ? true : false;
			});

			if(!from_sales_invoice) {
				this.frm.add_custom_button(__('Invoice'), function() { me.make_sales_invoice() },
					__('Create'));
			}
		}

		if(doc.docstatus==1 && doc.status === "Closed" && this.frm.has_perm("submit")) {
			this.frm.add_custom_button(__('Reopen'), function() { me.reopen_delivery_note() },
				__("Status"))
		}
		erpnext.stock.delivery_note.set_print_hide(doc, dt, dn);

		if(doc.docstatus==1 && !doc.is_return && !doc.auto_repeat) {
			cur_frm.add_custom_button(__('Subscription'), function() {
				erpnext.utils.make_subscription(doc.doctype, doc.name)
			}, __('Create'))
		}
	},

	make_sales_invoice: function() {
		frappe.model.open_mapped_doc({
			method: "erpnext.stock.doctype.delivery_note.delivery_note.make_sales_invoice",
			frm: this.frm
		})
	},

	make_installation_note: function() {
		frappe.model.open_mapped_doc({
			method: "erpnext.stock.doctype.delivery_note.delivery_note.make_installation_note",
			frm: this.frm
		});
	},

	make_sales_return: function() {
		frappe.model.open_mapped_doc({
			method: "erpnext.stock.doctype.delivery_note.delivery_note.make_sales_return",
			frm: this.frm
		})
	},

	make_delivery_trip: function() {
		frappe.model.open_mapped_doc({
			method: "erpnext.stock.doctype.delivery_note.delivery_note.make_delivery_trip",
			frm: this.frm
		})
	},

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

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

	packed_items_on_form_rendered: function(doc, grid_row) {
		erpnext.setup_serial_no();
	},

	close_delivery_note: function(doc){
		this.update_status("Closed")
	},

	reopen_delivery_note : function() {
		this.update_status("Submitted")
	},

	update_status: function(status) {
		var me = this;
		frappe.ui.form.is_saving = true;
		frappe.call({
			method:"erpnext.stock.doctype.delivery_note.delivery_note.update_delivery_note_status",
			args: {docname: me.frm.doc.name, status: status},
			callback: function(r){
				if(!r.exc)
					me.frm.reload_doc();
			},
			always: function(){
				frappe.ui.form.is_saving = false;
			}
		})
	}

});

$.extend(cur_frm.cscript, new erpnext.stock.DeliveryNoteController({frm: cur_frm}));

frappe.ui.form.on('Delivery Note', {
	setup: function(frm) {
		if(frm.doc.company) {
			frm.trigger("unhide_account_head");
		}
	},

	company: function(frm) {
		frm.trigger("unhide_account_head");
	},

	unhide_account_head: function(frm) {
		// unhide expense_account and cost_center if perpetual inventory is enabled in the company
		var aii_enabled = erpnext.is_perpetual_inventory_enabled(frm.doc.company)
		frm.fields_dict["items"].grid.set_column_disp(["expense_account", "cost_center"], aii_enabled);
	}
})

erpnext.stock.delivery_note.set_print_hide = function(doc, cdt, cdn){
	var dn_fields = frappe.meta.docfield_map['Delivery Note'];
	var dn_item_fields = frappe.meta.docfield_map['Delivery Note Item'];
	var dn_fields_copy = dn_fields;
	var dn_item_fields_copy = dn_item_fields;
	if (doc.print_without_amount) {
		dn_fields['currency'].print_hide = 1;
		dn_item_fields['rate'].print_hide = 1;
		dn_item_fields['discount_percentage'].print_hide = 1;
		dn_item_fields['price_list_rate'].print_hide = 1;
		dn_item_fields['amount'].print_hide = 1;
		dn_item_fields['discount_amount'].print_hide = 1;
		dn_fields['taxes'].print_hide = 1;
	} else {
		if (dn_fields_copy['currency'].print_hide != 1)
			dn_fields['currency'].print_hide = 0;
		if (dn_item_fields_copy['rate'].print_hide != 1)
			dn_item_fields['rate'].print_hide = 0;
		if (dn_item_fields_copy['amount'].print_hide != 1)
			dn_item_fields['amount'].print_hide = 0;
		if (dn_item_fields_copy['discount_amount'].print_hide != 1)
			dn_item_fields['discount_amount'].print_hide = 0;
		if (dn_fields_copy['taxes'].print_hide != 1)
			dn_fields['taxes'].print_hide = 0;
	}
}
<commit_msg>fix(delivery note): change the text invoice to sales invoice on make button (#18666)<commit_after>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt

{% include 'erpnext/selling/sales_common.js' %};

cur_frm.add_fetch('customer', 'tax_id', 'tax_id');

frappe.provide("erpnext.stock");
frappe.provide("erpnext.stock.delivery_note");

frappe.ui.form.on("Delivery Note", {
	setup: function(frm) {
		frm.custom_make_buttons = {
			'Packing Slip': 'Packing Slip',
			'Installation Note': 'Installation Note',
			'Sales Invoice': 'Invoice',
			'Stock Entry': 'Return',
		},
		frm.set_indicator_formatter('item_code',
			function(doc) {
				return (doc.docstatus==1 || doc.qty<=doc.actual_qty) ? "green" : "orange"
			})

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

		frm.set_query('project', function(doc) {
			return {
				query: "erpnext.controllers.queries.get_project_name",
				filters: {
					'customer': doc.customer
				}
			}
		})

		frm.set_query('transporter', function() {
			return {
				filters: {
					'is_transporter': 1
				}
			}
		});

		frm.set_query('driver', function(doc) {
			return {
				filters: {
					'transporter': doc.transporter
				}
			}
		});

		frm.set_query('expense_account', 'items', function(doc, cdt, cdn) {
			if (erpnext.is_perpetual_inventory_enabled(doc.company)) {
				return {
					filters: {
						"report_type": "Profit and Loss",
						"company": doc.company,
						"is_group": 0
					}
				}
			}
		});

		frm.set_query('cost_center', 'items', function(doc, cdt, cdn) {
			if (erpnext.is_perpetual_inventory_enabled(doc.company)) {
				return {
					filters: {
						'company': doc.company,
						"is_group": 0
					}
				}
			}
		});

	},

	print_without_amount: function(frm) {
		erpnext.stock.delivery_note.set_print_hide(frm.doc);
	},

	refresh: function(frm) {
		if (frm.doc.docstatus === 1 && frm.doc.is_return === 1 && frm.doc.per_billed !== 100) {
			frm.add_custom_button(__('Credit Note'), function() {
				frappe.confirm(__("Are you sure you want to make credit note?"),
					function() {
						frm.trigger("make_credit_note");
					}
				);
			}, __('Create'));

			frm.page.set_inner_btn_group_as_primary(__('Create'));
		}
	},

	make_credit_note: function(frm) {
		frm.call({
			method: "make_return_invoice",
			doc: frm.doc,
			freeze: true,
			callback: function() {
				frm.reload_doc();
			}
		});
	}
});

frappe.ui.form.on("Delivery Note Item", {
	expense_account: function(frm, dt, dn) {
		var d = locals[dt][dn];
		frm.update_in_all_rows('items', 'expense_account', d.expense_account);
	},
	cost_center: function(frm, dt, dn) {
		var d = locals[dt][dn];
		frm.update_in_all_rows('items', 'cost_center', d.cost_center);
	}
});

erpnext.stock.DeliveryNoteController = erpnext.selling.SellingController.extend({
	setup: function(doc) {
		this.setup_posting_date_time_check();
		this._super(doc);
	},
	refresh: function(doc, dt, dn) {
		var me = this;
		this._super();
		if ((!doc.is_return) && (doc.status!="Closed" || this.frm.is_new())) {
			if (this.frm.doc.docstatus===0) {
				this.frm.add_custom_button(__('Sales Order'),
					function() {
						erpnext.utils.map_current_doc({
							method: "erpnext.selling.doctype.sales_order.sales_order.make_delivery_note",
							source_doctype: "Sales Order",
							target: me.frm,
							setters: {
								customer: me.frm.doc.customer || undefined,
							},
							get_query_filters: {
								docstatus: 1,
								status: ["not in", ["Closed", "On Hold"]],
								per_delivered: ["<", 99.99],
								company: me.frm.doc.company,
								project: me.frm.doc.project || undefined,
							}
						})
					}, __("Get items from"));
			}
		}

		if (!doc.is_return && doc.status!="Closed") {
			if(flt(doc.per_installed, 2) < 100 && doc.docstatus==1)
				this.frm.add_custom_button(__('Installation Note'), function() {
					me.make_installation_note() }, __('Create'));

			if (doc.docstatus==1) {
				this.frm.add_custom_button(__('Sales Return'), function() {
					me.make_sales_return() }, __('Create'));
			}

			if (doc.docstatus==1) {
				this.frm.add_custom_button(__('Delivery Trip'), function() {
					me.make_delivery_trip() }, __('Create'));
			}

			if(doc.docstatus==0 && !doc.__islocal) {
				this.frm.add_custom_button(__('Packing Slip'), function() {
					frappe.model.open_mapped_doc({
						method: "erpnext.stock.doctype.delivery_note.delivery_note.make_packing_slip",
						frm: me.frm
					}) }, __('Create'));
			}

			if (!doc.__islocal && doc.docstatus==1) {
				this.frm.page.set_inner_btn_group_as_primary(__('Create'));
			}
		}

		if (doc.docstatus==1) {
			this.show_stock_ledger();
			if (erpnext.is_perpetual_inventory_enabled(doc.company)) {
				this.show_general_ledger();
			}
			if (this.frm.has_perm("submit") && doc.status !== "Closed") {
				me.frm.add_custom_button(__("Close"), function() { me.close_delivery_note() },
					__("Status"))
			}
		}

		if(doc.docstatus==1 && !doc.is_return && doc.status!="Closed" && flt(doc.per_billed) < 100) {
			// show Make Invoice button only if Delivery Note is not created from Sales Invoice
			var from_sales_invoice = false;
			from_sales_invoice = me.frm.doc.items.some(function(item) {
				return item.against_sales_invoice ? true : false;
			});

			if(!from_sales_invoice) {
				this.frm.add_custom_button(__('Sales Invoice'), function() { me.make_sales_invoice() },
					__('Create'));
			}
		}

		if(doc.docstatus==1 && doc.status === "Closed" && this.frm.has_perm("submit")) {
			this.frm.add_custom_button(__('Reopen'), function() { me.reopen_delivery_note() },
				__("Status"))
		}
		erpnext.stock.delivery_note.set_print_hide(doc, dt, dn);

		if(doc.docstatus==1 && !doc.is_return && !doc.auto_repeat) {
			cur_frm.add_custom_button(__('Subscription'), function() {
				erpnext.utils.make_subscription(doc.doctype, doc.name)
			}, __('Create'))
		}
	},

	make_sales_invoice: function() {
		frappe.model.open_mapped_doc({
			method: "erpnext.stock.doctype.delivery_note.delivery_note.make_sales_invoice",
			frm: this.frm
		})
	},

	make_installation_note: function() {
		frappe.model.open_mapped_doc({
			method: "erpnext.stock.doctype.delivery_note.delivery_note.make_installation_note",
			frm: this.frm
		});
	},

	make_sales_return: function() {
		frappe.model.open_mapped_doc({
			method: "erpnext.stock.doctype.delivery_note.delivery_note.make_sales_return",
			frm: this.frm
		})
	},

	make_delivery_trip: function() {
		frappe.model.open_mapped_doc({
			method: "erpnext.stock.doctype.delivery_note.delivery_note.make_delivery_trip",
			frm: this.frm
		})
	},

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

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

	packed_items_on_form_rendered: function(doc, grid_row) {
		erpnext.setup_serial_no();
	},

	close_delivery_note: function(doc){
		this.update_status("Closed")
	},

	reopen_delivery_note : function() {
		this.update_status("Submitted")
	},

	update_status: function(status) {
		var me = this;
		frappe.ui.form.is_saving = true;
		frappe.call({
			method:"erpnext.stock.doctype.delivery_note.delivery_note.update_delivery_note_status",
			args: {docname: me.frm.doc.name, status: status},
			callback: function(r){
				if(!r.exc)
					me.frm.reload_doc();
			},
			always: function(){
				frappe.ui.form.is_saving = false;
			}
		})
	}

});

$.extend(cur_frm.cscript, new erpnext.stock.DeliveryNoteController({frm: cur_frm}));

frappe.ui.form.on('Delivery Note', {
	setup: function(frm) {
		if(frm.doc.company) {
			frm.trigger("unhide_account_head");
		}
	},

	company: function(frm) {
		frm.trigger("unhide_account_head");
	},

	unhide_account_head: function(frm) {
		// unhide expense_account and cost_center if perpetual inventory is enabled in the company
		var aii_enabled = erpnext.is_perpetual_inventory_enabled(frm.doc.company)
		frm.fields_dict["items"].grid.set_column_disp(["expense_account", "cost_center"], aii_enabled);
	}
})

erpnext.stock.delivery_note.set_print_hide = function(doc, cdt, cdn){
	var dn_fields = frappe.meta.docfield_map['Delivery Note'];
	var dn_item_fields = frappe.meta.docfield_map['Delivery Note Item'];
	var dn_fields_copy = dn_fields;
	var dn_item_fields_copy = dn_item_fields;
	if (doc.print_without_amount) {
		dn_fields['currency'].print_hide = 1;
		dn_item_fields['rate'].print_hide = 1;
		dn_item_fields['discount_percentage'].print_hide = 1;
		dn_item_fields['price_list_rate'].print_hide = 1;
		dn_item_fields['amount'].print_hide = 1;
		dn_item_fields['discount_amount'].print_hide = 1;
		dn_fields['taxes'].print_hide = 1;
	} else {
		if (dn_fields_copy['currency'].print_hide != 1)
			dn_fields['currency'].print_hide = 0;
		if (dn_item_fields_copy['rate'].print_hide != 1)
			dn_item_fields['rate'].print_hide = 0;
		if (dn_item_fields_copy['amount'].print_hide != 1)
			dn_item_fields['amount'].print_hide = 0;
		if (dn_item_fields_copy['discount_amount'].print_hide != 1)
			dn_item_fields['discount_amount'].print_hide = 0;
		if (dn_fields_copy['taxes'].print_hide != 1)
			dn_fields['taxes'].print_hide = 0;
	}
}
<|endoftext|>