<commit_before>

function Enrichr_request(cgm){

  function enrichr_icon(){

    var low_opacity = 0.7;
    var high_opacity = 1.0;
    var icon_size = 42;

    d3.select('.viz_svg').append("svg:image")
     .attr('x', 50)
     .attr('y', 2)
     .attr('width', icon_size)
     .attr('height', icon_size)
     .attr("xlink:href","img/enrichr_logo.png")
     .style('opacity', low_opacity)
     .on('click', function(){
       make_enrichr_menu();
     })
     .on('mouseover', function(){
       d3.select(this).style('opacity', high_opacity);
     })
     .on('mouseout', function(){
       d3.select(this).style('opacity', low_opacity);
     });

    var enr_menu = d3.select(cgm.params.root+' .viz_svg')
      .append('g')
      .classed('showing', false)
      .classed('enrichr_menu', true)
      // .attr('x', 85)
      // .attr('y', 40)
      .attr('transform', 'translate(85,40)')
      .style('display', 'none');

    enr_menu
      .append('rect')
      .style('width', 500)
      .style('height', 400)
      .style('opacity', 0.9)
      .style('fill', 'white')
      .style('stroke', '#A3A3A3')
      .style('stroke-width', '3px');

    enr_menu
      .append('text')
      .attr('transform', 'translate(20,30)')
      .attr('font-family', '"Helvetica Neue", Helvetica, Arial, sans-serif')
      .style('font-size','18px')
      .style('font-weight', 800)
      .text('Choose Enrichr Library');

    var lib_section = enr_menu
      .append('g')
      .attr('transform', 'translate(20,60)')
      .style('width', 460)
      .style('height', 330)
      .classed('enr_lib_section','true');

    var possible_libraries = ['ChEA_2015','KEA_2015',
      'Disease_Perturbations_from_GEO_up'];
    var vertical_space = 30;

    var lib_groups = lib_section
      .selectAll('g')
      .data(possible_libraries)
      .enter()
      .append('g')
      .attr('transform', function(d,i){
        var vert =  i*vertical_space
        var transform_string = 'translate(0,'+ vert+')';
        return transform_string;
      })

    lib_groups
      .on('click', function(d){
        console.log(d);
        enr_obj.enrichr_rows(d, update_viz_callback)
      })

    lib_groups
      .append('text')
      .style('font-size','16px')
      .attr('font-family', '"Helvetica Neue", Helvetica, Arial, sans-serif')
      .text(function(d){
        return d.replace(/_/g, ' ');
      });

  }

  function make_enrichr_menu(){

    var enr_menu = d3.select(cgm.params.root+' .enrichr_menu');

    if (enr_menu.classed('showing') === false){
      enr_menu
        .classed('showing', true)
        .style('display', 'block');
    } else {
      enr_menu
        .classed('showing', false)
        .style('display', 'none');
    }

  }

  function get_enr_with_list(gene_list, library, callback_function){

    enr_obj.post_list(gene_list, function(){

      if (typeof callback_function != 'undefined'){
        enr_obj.get_enr(library, callback_function);
      } else {
        enr_obj.get_enr(library);
      }

    });
  }

  function post_list(gene_list, callback_function){

    var gene_list_string = gene_list.join('\n');

    var form = new FormData();
    var response;

    form.append("list", gene_list_string);

    form.append("description", "clustergrammer");

    var settings = {
     "async": true,
     "crossDomain": true,
     "url": "http://amp.pharm.mssm.edu/Enrichr/addList",
     "method": "POST",
     "processData": false,
     "contentType": false,
     "mimeType": "multipart/form-data",
     "data": form
    }

    if (typeof callback_function === 'undefined'){
      callback_function = confirm_save;
    }

    $.ajax(settings)
     .done(function(response){
      response = JSON.parse(response);
      enr_obj.user_list_id = response.userListId;
      callback_function(response);
     });
  }

  function confirm_save(response){
    console.log('saved user_list_id '+String(enr_obj.user_list_id));
  }

  function get_enr(library, callback_function){

    if (enr_obj.user_list_id !== null){
      var form = new FormData();

      var base_url = 'http://amp.pharm.mssm.edu/Enrichr/enrich?';
      var library_string = 'backgroundType=' + String(library);
      var list_id_string = 'userListId=' + String(enr_obj.user_list_id);

      var full_url = base_url + library_string + '&' + list_id_string;

      // get request
      var settings = {
       "async": true,
       "crossDomain": true,
       "url": full_url,
       "method": "GET",
       "processData": false,
       "contentType": false,
       "mimeType": "multipart/form-data",
       "data": form
      }

      $.ajax(settings)
        .done(function (response) {

          response = JSON.parse(response);
          enr_obj.enr_data = response;

          // parse enr_data to cat_data format
          /////////////////////////////////////
          // enr_obj.cat_data = enr_obj.enr_data
          enr_obj.enr_data_to_cats();

          if (typeof callback_function != 'undefined'){
            callback_function(enr_obj);
          }

        });

    } else {
      console.log('no user_list_id defined')
    }
  }

  function enrichr_rows(library, callback_function){

    var gene_list = cgm.params.network_data.row_nodes_names;

    enr_obj.get_enr_with_list(gene_list, library, callback_function)

  }

  function enr_data_to_cats(){

    // console.log('enr_data_to_cats');

    var library_name = _.keys(this.enr_data)[0];

    var enr_terms = this.enr_data[library_name];

    enr_terms = enr_terms.slice(0,10);

    cat_data = []

    _.each(enr_terms, function(inst_term){

      inst_data = {};
      inst_data['cat_title'] = inst_term[1];
      inst_data['cats'] = [];

      cat_details = {};
      cat_details.cat_name = 'true';
      cat_details.members = inst_term[5]

      // there are only two categories for Enrichr: true/false
      inst_data['cats'].push(cat_details)

      cat_data.push(inst_data);
    });

    // console.log(cat_data)

    this.cat_data = cat_data;

  }

  // example of how to check gene list
  // http://amp.pharm.mssm.edu/Enrichr/view?userListId=1284420

  var enr_obj = {};
  enr_obj.user_list_id = null;
  enr_obj.enr_data = null;
  enr_obj.cat_data = null;

  enr_obj.enrichr_icon = enrichr_icon;
  enr_obj.post_list = post_list;
  enr_obj.get_enr = get_enr;
  enr_obj.get_enr_with_list = get_enr_with_list;
  enr_obj.enrichr_rows = enrichr_rows;
  enr_obj.enr_data_to_cats = enr_data_to_cats;

  return enr_obj;

}

function update_viz_callback(enr_obj){
  // console.log('\nUpdating viz with enr\n------------------\n');
  // console.log(enr_obj.cat_data);
  cgm.update_cats(enr_obj.cat_data);
}

// tmp = cgm.params.network_data.row_nodes_names;
// enr_obj.get_enr_with_list(tmp, 'KEGG_2015', update_viz_callback);

// // example
// /////////////////
// enr_obj.enrichr_rows('ChEA_2015',update_viz_callback)

// // load toy category data
// enr_obj.cat_data;
// d3.json('json/category_mockup.json', function(cat_data){
//   console.log('cat_data')
//   console.log(cat_data)
//   // return cat_data;
//   enr_obj.cat_data = cat_data;
// })<commit_msg>unstable, working on enrichr menu behavior<commit_after>

function Enrichr_request(cgm){

  function enrichr_icon(){

    var low_opacity = 0.7;
    var high_opacity = 1.0;
    var icon_size = 42;

    d3.select('.viz_svg').append("svg:image")
     .attr('x', 50)
     .attr('y', 2)
     .attr('width', icon_size)
     .attr('height', icon_size)
     .attr("xlink:href","img/enrichr_logo.png")
     .style('opacity', low_opacity)
     .on('click', function(){
       toggle_enrichr_menu();
     })
     .on('mouseover', function(){
       d3.select(this).style('opacity', high_opacity);
     })
     .on('mouseout', function(){
       d3.select(this).style('opacity', low_opacity);
     });

    var enr_menu = d3.select(cgm.params.root+' .viz_svg')
      .append('g')
      .classed('showing', false)
      .classed('enrichr_menu', true)
      .attr('transform', 'translate(85,40)')
      .style('display', 'none');

    enr_menu
      .append('rect')
      .classed('enr_menu_background', true)
      .style('width', 500)
      .style('height', 400)
      .style('opacity', 0.9)
      .style('fill', 'white')
      .style('stroke', '#A3A3A3')
      .style('stroke-width', '3px');

    enr_menu
      .append('text')
      .attr('transform', 'translate(20,30)')
      .attr('font-family', '"Helvetica Neue", Helvetica, Arial, sans-serif')
      .style('font-size','18px')
      .style('font-weight', 800)
      .text('Choose Enrichr Library');

    var lib_section = enr_menu
      .append('g')
      .attr('transform', 'translate(20,60)')
      .style('width', 460)
      .style('height', 330)
      .classed('enr_lib_section','true');

    var possible_libraries = ['ChEA_2015','KEA_2015',
      'Disease_Perturbations_from_GEO_up'];
    var vertical_space = 30;

    var lib_groups = lib_section
      .selectAll('g')
      .data(possible_libraries)
      .enter()
      .append('g')
      .attr('transform', function(d,i){
        var vert =  i*vertical_space
        var transform_string = 'translate(0,'+ vert+')';
        return transform_string;
      })

    lib_groups
      .on('click', function(d){
        console.log(d);
        enr_obj.enrichr_rows(d, update_viz_callback);
        toggle_enrichr_menu();
      })

    lib_groups
      .append('text')
      .style('font-size','16px')
      .attr('font-family', '"Helvetica Neue", Helvetica, Arial, sans-serif')
      .text(function(d){
        return d.replace(/_/g, ' ');
      });

  }

  function toggle_enrichr_menu(){

    var enr_menu = d3.select(cgm.params.root+' .enrichr_menu');

    if (enr_menu.classed('showing') === false){
      enr_menu
        .classed('showing', true)
        .style('display', 'block');

      d3.select(cgm.params.root+' .enrichr_menu')
        .style('opacity',0)
        .transition()
        .style('opacity',1)

    } else {

      setTimeout(function(){enr_menu.style('display', 'none');}, 1000)

      d3.select(cgm.params.root+' .enrichr_menu')
        .classed('showing', false)
        .style('opacity',1)
        .transition()
        .style('opacity',0)
    }

  }

  function get_enr_with_list(gene_list, library, callback_function){

    enr_obj.post_list(gene_list, function(){

      if (typeof callback_function != 'undefined'){
        enr_obj.get_enr(library, callback_function);
      } else {
        enr_obj.get_enr(library);
      }

    });
  }

  function post_list(gene_list, callback_function){

    var gene_list_string = gene_list.join('\n');

    var form = new FormData();
    var response;

    form.append("list", gene_list_string);

    form.append("description", "clustergrammer");

    var settings = {
     "async": true,
     "crossDomain": true,
     "url": "http://amp.pharm.mssm.edu/Enrichr/addList",
     "method": "POST",
     "processData": false,
     "contentType": false,
     "mimeType": "multipart/form-data",
     "data": form
    }

    if (typeof callback_function === 'undefined'){
      callback_function = confirm_save;
    }

    $.ajax(settings)
     .done(function(response){
      response = JSON.parse(response);
      enr_obj.user_list_id = response.userListId;
      callback_function(response);
     });
  }

  function confirm_save(response){
    console.log('saved user_list_id '+String(enr_obj.user_list_id));
  }

  function get_enr(library, callback_function){

    if (enr_obj.user_list_id !== null){
      var form = new FormData();

      var base_url = 'http://amp.pharm.mssm.edu/Enrichr/enrich?';
      var library_string = 'backgroundType=' + String(library);
      var list_id_string = 'userListId=' + String(enr_obj.user_list_id);

      var full_url = base_url + library_string + '&' + list_id_string;

      // get request
      var settings = {
       "async": true,
       "crossDomain": true,
       "url": full_url,
       "method": "GET",
       "processData": false,
       "contentType": false,
       "mimeType": "multipart/form-data",
       "data": form
      }

      $.ajax(settings)
        .done(function (response) {

          response = JSON.parse(response);
          enr_obj.enr_data = response;

          // parse enr_data to cat_data format
          /////////////////////////////////////
          // enr_obj.cat_data = enr_obj.enr_data
          enr_obj.enr_data_to_cats();

          if (typeof callback_function != 'undefined'){
            callback_function(enr_obj);
          }

        });

    } else {
      console.log('no user_list_id defined')
    }
  }

  function enrichr_rows(library, callback_function){

    var gene_list = cgm.params.network_data.row_nodes_names;

    enr_obj.get_enr_with_list(gene_list, library, callback_function)

  }

  function enr_data_to_cats(){

    // console.log('enr_data_to_cats');

    var library_name = _.keys(this.enr_data)[0];

    var enr_terms = this.enr_data[library_name];

    enr_terms = enr_terms.slice(0,10);

    cat_data = []

    _.each(enr_terms, function(inst_term){

      inst_data = {};
      inst_data['cat_title'] = inst_term[1];
      inst_data['cats'] = [];

      cat_details = {};
      cat_details.cat_name = 'true';
      cat_details.members = inst_term[5]

      // there are only two categories for Enrichr: true/false
      inst_data['cats'].push(cat_details)

      cat_data.push(inst_data);
    });

    // console.log(cat_data)

    this.cat_data = cat_data;

  }

  // example of how to check gene list
  // http://amp.pharm.mssm.edu/Enrichr/view?userListId=1284420

  var enr_obj = {};
  enr_obj.user_list_id = null;
  enr_obj.enr_data = null;
  enr_obj.cat_data = null;

  enr_obj.enrichr_icon = enrichr_icon;
  enr_obj.post_list = post_list;
  enr_obj.get_enr = get_enr;
  enr_obj.get_enr_with_list = get_enr_with_list;
  enr_obj.enrichr_rows = enrichr_rows;
  enr_obj.enr_data_to_cats = enr_data_to_cats;

  return enr_obj;

}

function update_viz_callback(enr_obj){
  // console.log('\nUpdating viz with enr\n------------------\n');
  // console.log(enr_obj.cat_data);
  cgm.update_cats(enr_obj.cat_data);
}

// tmp = cgm.params.network_data.row_nodes_names;
// enr_obj.get_enr_with_list(tmp, 'KEGG_2015', update_viz_callback);

// // example
// /////////////////
// enr_obj.enrichr_rows('ChEA_2015',update_viz_callback)

// // load toy category data
// enr_obj.cat_data;
// d3.json('json/category_mockup.json', function(cat_data){
//   console.log('cat_data')
//   console.log(cat_data)
//   // return cat_data;
//   enr_obj.cat_data = cat_data;
// })<|endoftext|>


<commit_before>const _ = require('lodash');
const {URL} = require('url');
const mailgun = require('mailgun-js');
const logging = require('../../../shared/logging');
const configService = require('../../../shared/config');
const settingsCache = require('../settings/cache');

const BATCH_SIZE = 1000;

function createMailgun(config) {
    const baseUrl = new URL(config.baseUrl);

    return mailgun({
        apiKey: config.apiKey,
        domain: config.domain,
        protocol: baseUrl.protocol,
        host: baseUrl.hostname,
        port: baseUrl.port,
        endpoint: baseUrl.pathname,
        retry: 5
    });
}

function getInstance() {
    const bulkEmailConfig = configService.get('bulkEmail');
    const bulkEmailSetting = {
        apiKey: settingsCache.get('mailgun_api_key'),
        domain: settingsCache.get('mailgun_domain'),
        baseUrl: settingsCache.get('mailgun_base_url')
    };
    const hasMailgunConfig = !!(bulkEmailConfig && bulkEmailConfig.mailgun);
    const hasMailgunSetting = !!(bulkEmailSetting && bulkEmailSetting.apiKey && bulkEmailSetting.baseUrl && bulkEmailSetting.domain);

    if (!hasMailgunConfig && !hasMailgunSetting) {
        logging.warn(`Bulk email service is not configured`);
    } else {
        let mailgunConfig = hasMailgunConfig ? bulkEmailConfig.mailgun : bulkEmailSetting;
        return createMailgun(mailgunConfig);
    }
    return null;
}

// recipients format:
// {
//     'test@example.com': {
//         name: 'Test User',
//         unique_id: '12345abcde',
//         unsubscribe_url: 'https://example.com/unsub/me'
//     }
// }
function send(message, recipientData, replacements) {
    if (recipientData.length > BATCH_SIZE) {
        // err - too many recipients
    }

    let messageData = {};

    try {
        const bulkEmailConfig = configService.get('bulkEmail');
        const mailgunInstance = getInstance();

        const messageContent = _.pick(message, 'html', 'plaintext');

        // update content to use Mailgun variable syntax for replacements
        replacements.forEach((replacement) => {
            messageContent[replacement.format] = messageContent[replacement.format].replace(
                replacement.match,
                `%recipient.${replacement.id}%`
            );
        });

        messageData = {
            to: Object.keys(recipientData),
            from: message.from,
            'h:Reply-To': message.replyTo,
            'recipient-variables': recipientData,
            html: messageContent.html,
            text: messageContent.plaintext
        };

        if (bulkEmailConfig && bulkEmailConfig.mailgun && bulkEmailConfig.mailgun.tag) {
            messageData['o:tag'] = [bulkEmailConfig.mailgun.tag, 'bulk-email'];
        }

        if (bulkEmailConfig && bulkEmailConfig.mailgun && bulkEmailConfig.mailgun.testmode) {
            messageData['o:testmode'] = true;
        }

        return new Promise((resolve, reject) => {
            mailgunInstance.messages().send(messageData, (error, body) => {
                if (error) {
                    return reject(error);
                }

                return resolve({
                    id: body.id
                });
            });
        });
    } catch (error) {
        return Promise.reject({error, messageData});
    }
}

module.exports = {
    BATCH_SIZE,
    getInstance,
    send
};
<commit_msg>🐛 Fixed newsletters emails having no subject<commit_after>const _ = require('lodash');
const {URL} = require('url');
const mailgun = require('mailgun-js');
const logging = require('../../../shared/logging');
const configService = require('../../../shared/config');
const settingsCache = require('../settings/cache');

const BATCH_SIZE = 1000;

function createMailgun(config) {
    const baseUrl = new URL(config.baseUrl);

    return mailgun({
        apiKey: config.apiKey,
        domain: config.domain,
        protocol: baseUrl.protocol,
        host: baseUrl.hostname,
        port: baseUrl.port,
        endpoint: baseUrl.pathname,
        retry: 5
    });
}

function getInstance() {
    const bulkEmailConfig = configService.get('bulkEmail');
    const bulkEmailSetting = {
        apiKey: settingsCache.get('mailgun_api_key'),
        domain: settingsCache.get('mailgun_domain'),
        baseUrl: settingsCache.get('mailgun_base_url')
    };
    const hasMailgunConfig = !!(bulkEmailConfig && bulkEmailConfig.mailgun);
    const hasMailgunSetting = !!(bulkEmailSetting && bulkEmailSetting.apiKey && bulkEmailSetting.baseUrl && bulkEmailSetting.domain);

    if (!hasMailgunConfig && !hasMailgunSetting) {
        logging.warn(`Bulk email service is not configured`);
    } else {
        let mailgunConfig = hasMailgunConfig ? bulkEmailConfig.mailgun : bulkEmailSetting;
        return createMailgun(mailgunConfig);
    }
    return null;
}

// recipients format:
// {
//     'test@example.com': {
//         name: 'Test User',
//         unique_id: '12345abcde',
//         unsubscribe_url: 'https://example.com/unsub/me'
//     }
// }
function send(message, recipientData, replacements) {
    if (recipientData.length > BATCH_SIZE) {
        // err - too many recipients
    }

    let messageData = {};

    try {
        const bulkEmailConfig = configService.get('bulkEmail');
        const mailgunInstance = getInstance();

        const messageContent = _.pick(message, 'subject', 'html', 'plaintext');

        // update content to use Mailgun variable syntax for replacements
        replacements.forEach((replacement) => {
            messageContent[replacement.format] = messageContent[replacement.format].replace(
                replacement.match,
                `%recipient.${replacement.id}%`
            );
        });

        messageData = {
            to: Object.keys(recipientData),
            from: message.from,
            'h:Reply-To': message.replyTo,
            'recipient-variables': recipientData,
            subject: messageContent.subject,
            html: messageContent.html,
            text: messageContent.plaintext
        };

        if (bulkEmailConfig && bulkEmailConfig.mailgun && bulkEmailConfig.mailgun.tag) {
            messageData['o:tag'] = [bulkEmailConfig.mailgun.tag, 'bulk-email'];
        }

        if (bulkEmailConfig && bulkEmailConfig.mailgun && bulkEmailConfig.mailgun.testmode) {
            messageData['o:testmode'] = true;
        }

        return new Promise((resolve, reject) => {
            mailgunInstance.messages().send(messageData, (error, body) => {
                if (error) {
                    return reject(error);
                }

                return resolve({
                    id: body.id
                });
            });
        });
    } catch (error) {
        return Promise.reject({error, messageData});
    }
}

module.exports = {
    BATCH_SIZE,
    getInstance,
    send
};
<|endoftext|>


<commit_before>import { nodeResolve } from "@rollup/plugin-node-resolve";
import { terser } from "rollup-plugin-terser";

const license = require("rollup-plugin-license");
const globby = require("globby");
const fs  = require("fs-extra");

import postcss from "rollup-plugin-postcss";

export default class Bundler{

	constructor(version, env){
		this.bundles = [];

		this.env = env;
		this.version = "/* Tabulator v" + version + " (c) Oliver Folkerd <%= moment().format('YYYY') %> */";
	}

	bundle(){
		if(this.env){
			this.watch(this.env);
		}else{
			this.build();
		}

		return this.bundles;
	}

	watch(env){
		console.log("Building Dev Package Bundles: ", env);
		switch(env){
			case "css":
				this.bundleCSS(false);
				break;

			case "esm":
				this.bundleESM(false);
				break;

			case "umd":
				this.bundleUMD(false);
				break;

			default:
				this.bundleCSS(false);
				this.bundleESM(false);
				break;
		}
	}

	build(){
		console.log("Clearing Dist Files");

		this.clearDist();

		console.log("Copying Standalong Builds");

		this.copyStandaloneBuilds();

		console.log("Building Production Package Bundles");

		this.bundleCSS(false);
		this.bundleCSS(true);

		this.bundleESM(false);
		this.bundleESM(true);

		this.bundleUMD(false);
		this.bundleUMD(true);
	}

	clearDist(){
		fs.emptyDirSync("./dist");
	}

	copyStandaloneBuilds(){
		var builds = ["jquery_wrapper.js"];

		builds.forEach((build) => {
			fs.copySync("./src/js/builds/" + build, "./dist/js/" + build);
		});
	}

	bundleCSS(minify){
		this.bundles = this.bundles.concat(globby.sync("./src/scss/**/tabulator*.scss").map(inputFile => {

			var file = inputFile.split("/");
			file = file.pop().replace(".scss", (minify ? ".min" : "") + ".css");

			return {
				input: inputFile,
				output: {
					file: "./dist/css/" + file,
					format: "es",
				},
				plugins: [
					postcss({
						modules: false,
						extract: true,
						minimize: minify,
						sourceMap: true,
						plugins: [require('postcss-prettify')]
					}),
				]
			};
		}));
	}

	bundleESM(minify){
		this.bundles.push({
			input:"src/js/builds/esm.js",
			plugins: [
				nodeResolve(),
				minify ? terser() : null,
				license({
					banner: {
						commentStyle:"none",
						content:this.version,
					},
				}),
			],
			output: [
				{
					file: "dist/js/tabulator_esm" + (minify ? ".min" : "") + ".js",
					format: "esm",
					exports: "named",
					sourcemap: true,
				},
			],
		});
	}

	bundleUMD(minify){
		this.bundles.push({
			input:"src/js/builds/usd.js",
			plugins: [
				nodeResolve(),
				minify ? terser() : null,
				license({
					banner: {
						commentStyle:"none",
						content:this.version,
					},
				}),
			],
			output: {
				file: "dist/js/tabulator" + (minify ? ".min" : "") + ".js",
				format: "umd",
				name: "Tabulator",
				esModule: false,
				exports: "default",
				sourcemap: true,
			},
		});
	}
}<commit_msg>prevent uneeded circular reference warnings in rollup on files with intended circular references<commit_after>import { nodeResolve } from "@rollup/plugin-node-resolve";
import { terser } from "rollup-plugin-terser";

const license = require("rollup-plugin-license");
const globby = require("globby");
const fs  = require("fs-extra");

import postcss from "rollup-plugin-postcss";

export default class Bundler{

	constructor(version, env){
		this.bundles = [];

		this.env = env;
		this.version = "/* Tabulator v" + version + " (c) Oliver Folkerd <%= moment().format('YYYY') %> */";
	}

	_suppressCircularWarnings(warn, defaultHandler){
		var ignoredCircularFiles = [
			"Column.js",
			"Tabulator.js",
		];

		if(!(warn.code === "CIRCULAR_DEPENDENCY" && ignoredCircularFiles.some(file => warn.importer.includes(file)))){
			defaultHandler(warn);
		}
	}

	bundle(){
		if(this.env){
			this.watch(this.env);
		}else{
			this.build();
		}

		return this.bundles;
	}

	watch(env){
		console.log("Building Dev Package Bundles: ", env);
		switch(env){
			case "css":
				this.bundleCSS(false);
				break;

			case "esm":
				this.bundleESM(false);
				break;

			case "umd":
				this.bundleUMD(false);
				break;

			default:
				this.bundleCSS(false);
				this.bundleESM(false);
				break;
		}
	}

	build(){
		console.log("Clearing Dist Files");

		this.clearDist();

		console.log("Copying Standalong Builds");

		this.copyStandaloneBuilds();

		console.log("Building Production Package Bundles");

		this.bundleCSS(false);
		this.bundleCSS(true);

		this.bundleESM(false);
		this.bundleESM(true);

		this.bundleUMD(false);
		this.bundleUMD(true);
	}

	clearDist(){
		fs.emptyDirSync("./dist");
	}

	copyStandaloneBuilds(){
		var builds = ["jquery_wrapper.js"];

		builds.forEach((build) => {
			fs.copySync("./src/js/builds/" + build, "./dist/js/" + build);
		});
	}

	bundleCSS(minify){
		this.bundles = this.bundles.concat(globby.sync("./src/scss/**/tabulator*.scss").map(inputFile => {

			var file = inputFile.split("/");
			file = file.pop().replace(".scss", (minify ? ".min" : "") + ".css");

			return {
				input: inputFile,
				output: {
					file: "./dist/css/" + file,
					format: "es",
				},
				plugins: [
					postcss({
						modules: false,
						extract: true,
						minimize: minify,
						sourceMap: true,
						plugins: [require('postcss-prettify')]
					}),
				]
			};
		}));
	}

	bundleESM(minify){
		this.bundles.push({
			input:"src/js/builds/esm.js",
			plugins: [
				nodeResolve(),
				minify ? terser() : null,
				license({
					banner: {
						commentStyle:"none",
						content:this.version,
					},
				}),
			],
			output: [
				{
					file: "dist/js/tabulator_esm" + (minify ? ".min" : "") + ".js",
					format: "esm",
					exports: "named",
					sourcemap: true,
				},
			],
			onwarn:this._suppressCircularWarnings,
		});
	}

	bundleUMD(minify){
		this.bundles.push({
			input:"src/js/builds/usd.js",
			plugins: [
				nodeResolve(),
				minify ? terser() : null,
				license({
					banner: {
						commentStyle:"none",
						content:this.version,
					},
				}),
			],
			output: {
				file: "dist/js/tabulator" + (minify ? ".min" : "") + ".js",
				format: "umd",
				name: "Tabulator",
				esModule: false,
				exports: "default",
				sourcemap: true,
			},
			onwarn:this._suppressCircularWarnings,
		});
	}
}<|endoftext|>


<commit_before>
var enr_obj = Enrichr_request();

function Enrichr_request(){

  function get_enr_with_list(gene_list, library, callback_function){
    console.log('get_enr_with_list: post and get requests')
    enr_obj.post_list(gene_list, function(){

      if (typeof callback_function != 'undefined'){
        enr_obj.get_enr(library, callback_function);
      } else {
        enr_obj.get_enr(library);
      }

    });
  }

  function post_list(gene_list, callback_function){

    var gene_list_string = gene_list.join('\n');

    var form = new FormData();
    var response;

    form.append("list", gene_list_string);

    form.append("description", "clustergrammer");

    var settings = {
     "async": true,
     "crossDomain": true,
     "url": "http://amp.pharm.mssm.edu/Enrichr/addList",
     "method": "POST",
     "processData": false,
     "contentType": false,
     "mimeType": "multipart/form-data",
     "data": form
    }

    if (typeof callback_function === 'undefined'){
      callback_function = confirm_save;
    }

    $.ajax(settings)
     .done(function(response){
      response = JSON.parse(response);
      enr_obj.user_list_id = response.userListId;
      callback_function(response);
     });
  }

  function confirm_save(response){
    console.log('saved user_list_id '+String(enr_obj.user_list_id));
  }

  function get_enr(library, callback_function){

    if (enr_obj.user_list_id !== null){
      var form = new FormData();

      var base_url = 'http://amp.pharm.mssm.edu/Enrichr/enrich?';
      var library_string = 'backgroundType=' + String(library);
      var list_id_string = 'userListId=' + String(enr_obj.user_list_id);

      var full_url = base_url + library_string + '&' + list_id_string;

      // get request
      var settings = {
       "async": true,
       "crossDomain": true,
       "url": full_url,
       "method": "GET",
       "processData": false,
       "contentType": false,
       "mimeType": "multipart/form-data",
       "data": form
      }

      $.ajax(settings).done(function (response) {
        response = JSON.parse(response);
        enr_obj.enr_data = response;

      if (typeof callback_function != 'undefined'){
        callback_function(enr_obj);
      }

      });
    } else {
      console.log('no user_list_id defined')
    }
  }

  function enrichr_rows(library, callback_function){

    var gene_list = cgm.params.network_data.row_nodes_names;

    enr_obj.get_enr_with_list(gene_list, library, callback_function)

    // console.log('send these rows to enrichr')
    // console.log(inst_rows)

    // if (typeof callback_function != 'undefined'){
    //   callback_function();
    // }

  }

  // example of how to check gene list
  // http://amp.pharm.mssm.edu/Enrichr/view?userListId=1284420

  var enr_obj = {};
  enr_obj.user_list_id = null;
  enr_obj.enr_data = null;

  enr_obj.post_list = post_list;
  enr_obj.get_enr = get_enr;
  enr_obj.get_enr_with_list = get_enr_with_list;
  enr_obj.enrichr_rows = enrichr_rows;

  return enr_obj;

}

function update_viz_callback(enr_obj){
  console.log('\nUpdating viz with enr\n------------------\n')
  console.log(enr_obj.enr_data)
  // console.log(enr_obj.enr_data)
}

// tmp = cgm.params.network_data.row_nodes_names;
// enr_obj.get_enr_with_list(tmp, 'KEGG_2015', update_viz_callback);

// // load toy category data
// enr_obj.cat_data;
// d3.json('json/category_mockup.json', function(cat_data){
//   console.log('cat_data')
//   console.log(cat_data)
//   // return cat_data;
//   enr_obj.cat_data = cat_data;
// })<commit_msg>unstable, working on passing enr_data to cat_data<commit_after>
var enr_obj = Enrichr_request();

function Enrichr_request(){

  function get_enr_with_list(gene_list, library, callback_function){
    console.log('get_enr_with_list: post and get requests')
    enr_obj.post_list(gene_list, function(){

      if (typeof callback_function != 'undefined'){
        enr_obj.get_enr(library, callback_function);
      } else {
        enr_obj.get_enr(library);
      }

    });
  }

  function post_list(gene_list, callback_function){

    var gene_list_string = gene_list.join('\n');

    var form = new FormData();
    var response;

    form.append("list", gene_list_string);

    form.append("description", "clustergrammer");

    var settings = {
     "async": true,
     "crossDomain": true,
     "url": "http://amp.pharm.mssm.edu/Enrichr/addList",
     "method": "POST",
     "processData": false,
     "contentType": false,
     "mimeType": "multipart/form-data",
     "data": form
    }

    if (typeof callback_function === 'undefined'){
      callback_function = confirm_save;
    }

    $.ajax(settings)
     .done(function(response){
      response = JSON.parse(response);
      enr_obj.user_list_id = response.userListId;
      callback_function(response);
     });
  }

  function confirm_save(response){
    console.log('saved user_list_id '+String(enr_obj.user_list_id));
  }

  function get_enr(library, callback_function){

    if (enr_obj.user_list_id !== null){
      var form = new FormData();

      var base_url = 'http://amp.pharm.mssm.edu/Enrichr/enrich?';
      var library_string = 'backgroundType=' + String(library);
      var list_id_string = 'userListId=' + String(enr_obj.user_list_id);

      var full_url = base_url + library_string + '&' + list_id_string;

      // get request
      var settings = {
       "async": true,
       "crossDomain": true,
       "url": full_url,
       "method": "GET",
       "processData": false,
       "contentType": false,
       "mimeType": "multipart/form-data",
       "data": form
      }

      $.ajax(settings)
        .done(function (response) {

          response = JSON.parse(response);
          enr_obj.enr_data = response;

          // parse enr_data to cat_data format
          /////////////////////////////////////
          enr_obj.cat_data = enr_obj.enr_data

          if (typeof callback_function != 'undefined'){
            callback_function(enr_obj);
          }

        });

    } else {
      console.log('no user_list_id defined')
    }
  }

  function enrichr_rows(library, callback_function){

    var gene_list = cgm.params.network_data.row_nodes_names;

    enr_obj.get_enr_with_list(gene_list, library, callback_function)

    // console.log('send these rows to enrichr')
    // console.log(inst_rows)

    // if (typeof callback_function != 'undefined'){
    //   callback_function();
    // }

  }

  // example of how to check gene list
  // http://amp.pharm.mssm.edu/Enrichr/view?userListId=1284420

  var enr_obj = {};
  enr_obj.user_list_id = null;
  enr_obj.enr_data = null;
  enr_obj.cat_data = null;

  enr_obj.post_list = post_list;
  enr_obj.get_enr = get_enr;
  enr_obj.get_enr_with_list = get_enr_with_list;
  enr_obj.enrichr_rows = enrichr_rows;

  return enr_obj;

}

function update_viz_callback(enr_obj){
  console.log('\nUpdating viz with enr\n------------------\n')
  console.log(enr_obj.cat_data)
  // console.log(enr_obj.enr_data)
}

// tmp = cgm.params.network_data.row_nodes_names;
// enr_obj.get_enr_with_list(tmp, 'KEGG_2015', update_viz_callback);

// // load toy category data
// enr_obj.cat_data;
// d3.json('json/category_mockup.json', function(cat_data){
//   console.log('cat_data')
//   console.log(cat_data)
//   // return cat_data;
//   enr_obj.cat_data = cat_data;
// })<|endoftext|>


<commit_before>(function(root, factory) {
  if (typeof define === 'function' && define.amd) {
    define([], factory) /* global define */
  } else if (typeof module === 'object' && module.exports) {
    module.exports = factory()
  } else {
    root.Moo = factory()
  }
}(this, function() {
  'use strict';

  var hasSticky = typeof new RegExp().sticky === 'boolean'

  function isRegExp(o) { return o && o.constructor === RegExp }

  function reEscape(s) {
    return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
  }
  function reGroups(s) {
    var re = new RegExp('|' + s)
    return re.exec('').length - 1
  }
  function reCapture(s) {
    return '(' + s + ')'
  }
  function reUnion(regexps) {
    var source =  regexps.map(function(s) {
      return "(?:" + s + ")"
    }).join('|')
    return "(?:" + source + ")"
  }

  function compareLength(a, b) {
    return b.length - a.length
  }

  function regexpOrLiteral(obj) {
    if (typeof obj === 'string') {
      return '(?:' + reEscape(obj) + ')'

    } else if (isRegExp(obj)) {
      // TODO: consider /u support
      if (obj.ignoreCase) { throw new Error('RegExp /i flag not allowed') }
      if (obj.global) { throw new Error('RegExp /g flag is implied') }
      if (obj.sticky) { throw new Error('RegExp /y flag is implied') }
      if (obj.multiline) { throw new Error('RegExp /m flag is implied') }
      return obj.source

    } else {
      throw new Error('not a pattern: ' + obj)
    }
  }

  function objectToRules(object) {
    var keys = Object.getOwnPropertyNames(object)
    var result = []
    for (var i=0; i<keys.length; i++) {
      var key = keys[i]
      result.push([key, object[key]])
    }
    return result
  }

  function ruleOptions(name, obj) {
    if (typeof obj !== 'object' || Array.isArray(obj) || isRegExp(obj)) {
      obj = { match: obj }
    }

    var options = Object.assign({
      name: name,
      lineBreaks: false,
      pop: false,
      next: null,
      push: null,
    }, obj)

    // convert to array
    if (!Array.isArray(options.match)) { options.match = [options.match] }
    return options
  }

  function sortRules(rules) {
    var result = []
    for (var i=0; i<rules.length; i++) {
      var rule = rules[i]

      // get options
      var options = ruleOptions(rule[0], rule[1])
      var match = options.match

      // sort literals by length to ensure longest match
      var capturingPatterns = []
      var patterns = []
      var literals = []
      for (var j=0; j<match.length; j++) {
        var obj = match[j]
        if (!isRegExp(obj)) literals.push(obj)
        else if (reGroups(obj.source) > 0) capturingPatterns.push(obj)
        else patterns.push(obj)
      }
      literals.sort(compareLength)

      // append regexps to the end
      options.match = literals.concat(patterns)
      if (options.match.length) {
        result.push(options)
      }

      // add each capturing regexp as a separate rule
      for (var j=0; j<capturingPatterns.length; j++) {
        result.push(Object.assign({}, options, {
          match: [capturingPatterns[j]],
        }))
      }
    }
    return result
  }

  function compileRules(rules, hasStates) {
    if (!Array.isArray(rules)) rules = objectToRules(rules)

    rules = sortRules(rules)

    var groups = []
    var parts = []
    for (var i=0; i<rules.length; i++) {
      var options = rules[i]
      groups.push(options)

      // convert to RegExp
      var pat = reUnion(options.match.map(regexpOrLiteral))

      // validate
      var regexp = new RegExp(pat)
      if (regexp.test("")) {
        throw new Error("RegExp matches empty string: " + regexp)
      }
      var groupCount = reGroups(pat)
      if (groupCount > 1) {
        throw new Error("RegExp has more than one capture group: " + regexp)
      }
      if (!hasStates && (options.pop || options.push || options.next)) {
        throw new Error("State-switching options are not allowed in stateless lexers (for token '" + options.name + "')")
      }

      // try and detect rules matching newlines
      if (!options.lineBreaks && regexp.test('\n')) {
        throw new Error('Rule should declare lineBreaks: ' + regexp)
      }

      // store regex
      var isCapture = !!groupCount
      if (!isCapture) pat = reCapture(pat)
      parts.push(pat)
    }

    var suffix = hasSticky ? '' : '|(?:)'
    var flags = hasSticky ? 'ym' : 'gm'
    var regexp = new RegExp(reUnion(parts) + suffix, flags)

    return {regexp: regexp, groups: groups}
  }

  function compile(rules) {
    var result = compileRules(rules)
    return new Lexer({start: result}, 'start')
  }

  function compileStates(states, start) {
    var keys = Object.getOwnPropertyNames(states)
    if (!start) start = keys[0]

    var map = Object.create(null)
    for (var i=0; i<keys.length; i++) {
      var key = keys[i]
      map[key] = compileRules(states[key], true)
    }

    for (var i=0; i<keys.length; i++) {
      var groups = map[keys[i]].groups
      for (var j=0; j<groups.length; j++) {
        var g = groups[i]
        var state = g && (g.push || g.next)
        if (state && !map[state]) {
          throw new Error("Missing state '" + state + "' (in token '" + g.name + "' of state '" + keys[i] + "')")
        }
      }
    }

    return new Lexer(map, start)
  }

  var Lexer = function(states, state) {
    this.states = states
    this.buffer = ''
    this.stack = []
    this.setState(state)
    this.reset()
  }

  Lexer.error = {
    name: 'ERRORTOKEN',
    lineBreaks: true,
  }

  Lexer.prototype.setState = function(state) {
    if (!state || this.state === state) return
    this.state = state
    var index = this.re ? this.re.lastIndex : 0
    var info = this.states[state]
    this.groups = info.groups
    this.re = info.regexp
    this.re.lastIndex = index
  }

  Lexer.prototype.popState = function() {
    this.setState(this.stack.pop())
  }

  Lexer.prototype.pushState = function(state) {
    this.stack.push(this.state)
    this.setState(state)
  }

  Lexer.prototype.eat = hasSticky ? function(re) {
    // assume re is /y
    return re.exec(this.buffer)
  } : function(re) {
    // assume re is /g
    var match = re.exec(this.buffer)
    // assert(match)
    // assert(match.index === 0)
    if (match[0].length === 0) {
      return null
    }
    return match
  }
  // TODO: try instead the |(?:) trick?

  function tokenToString() {
    return this.value || this.type
  }

  Lexer.prototype.lex = function() {
    var re = this.re
    var buffer = this.buffer

    if (re.lastIndex === buffer.length) {
      return // EOF
    }

    var start = re.lastIndex
    var match = this.eat(re)
    var group, value, text
    if (match === null) {
      group = Lexer.error

      // consume rest of buffer
      text = value = buffer.slice(start)
      re.lastIndex = buffer.length

    } else {
      text = match[0]
      var groups = this.groups
      for (var i = 0; i < groups.length; i++) {
        value = match[i + 1]
        if (value !== undefined) {
          group = groups[i]
          break
        }
      }
      // assert(i < groupCount)
      // TODO is `buffer` being leaked here?
    }

    // count line breaks
    var lineBreaks = 0
    if (group.lineBreaks) {
      var matchNL = /\n/g
      var nl = 1
      if (text === '\n') {
        lineBreaks = 1
      } else {
        while (matchNL.exec(text)) { lineBreaks++; nl = matchNL.lastIndex }
      }
    }

    var size = text.length
    var token = {
      type: group.name,
      value: value,
      toString: tokenToString,
      offset: start,
      size: size,
      lineBreaks: lineBreaks,
      line: this.line,
      col: this.col,
    }

    if (group.pop) this.popState()
    else if (group.push) this.pushState(group.push)
    else if (group.next) this.setState(group.next)

    this.line += lineBreaks
    if (lineBreaks !== 0) {
      this.col = size - nl + 1
    } else {
      this.col += size
    }
    return token
  }

  Lexer.prototype.lexAll = function() {
    var tokens = []
    var token
    while ((token = this.lex())) {
      tokens.push(token)
    }
    return tokens
  }

  if (typeof Symbol !== 'undefined' && Symbol.iterator) {
    var LexerIterator = function(lexer) {
      this.lexer = lexer
    }

    LexerIterator.prototype.next = function() {
      var token = this.lexer.lex()
      return {value: token, done: !token}
    }

    Lexer.prototype[Symbol.iterator] = function() {
      return new LexerIterator(this)
    }
  }

  Lexer.prototype.index = function() {
    return this.re.lastIndex
  }

  Lexer.prototype.reset = function(data, state) {
    this.buffer = data || ''
    this.re.lastIndex = 0
    this.line = state ? state.line : 1
    this.col = state ? state.col : 1
    return this
  }

  Lexer.prototype.save = function() {
    return {
      line: this.line,
      col: this.col,
    }
  }

  Lexer.prototype.feed = function(data) {
    this.buffer += data
    return this
  }

  Lexer.prototype.remaining = function() {
    return this.buffer.slice(this.re.lastIndex)
  }

  Lexer.prototype.clone = function(input) {
    var map = Object.create(null)
    var keys = Object.getOwnPropertyNames(this.states)
    for (var i = 0; i < keys.length; i++) {
      var key = keys[i]
      var s = this.states[key]
      map[key] = {
        groups: s.groups,
        regexp: new RegExp(s.regexp.source, s.regexp.flags),
      }
    }
    return new Lexer(map, this.state, input)
  }

  var moo = {} // TODO: what should moo() do?
  moo.compile = compile
  moo.states = compileStates
  return moo

}))
<commit_msg>Polyfill Object.assign<commit_after>(function(root, factory) {
  if (typeof define === 'function' && define.amd) {
    define([], factory) /* global define */
  } else if (typeof module === 'object' && module.exports) {
    module.exports = factory()
  } else {
    root.Moo = factory()
  }
}(this, function() {
  'use strict';

  if (typeof Object.assign === 'undefined') {
    var hasOwnProperty = Object.prototype.hasOwnProperty
    // https://tc39.github.io/ecma262/#sec-object.assign
    Object.assign = function(target, sources) {
      if (target == null) {
        throw new TypeError('Target cannot be null or undefined');
      }
      target = Object(target)

      for (var i = 1; i < arguments.length; i++) {
        var source = arguments[i]
        if (source == null) continue

        for (var key in source) {
          if (hasOwnProperty.call(source, key)) {
            target[key] = source[key]
          }
        }
      }
      return target
    }
  }

  var hasSticky = typeof new RegExp().sticky === 'boolean'

  function isRegExp(o) { return o && o.constructor === RegExp }

  function reEscape(s) {
    return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
  }
  function reGroups(s) {
    var re = new RegExp('|' + s)
    return re.exec('').length - 1
  }
  function reCapture(s) {
    return '(' + s + ')'
  }
  function reUnion(regexps) {
    var source =  regexps.map(function(s) {
      return "(?:" + s + ")"
    }).join('|')
    return "(?:" + source + ")"
  }

  function compareLength(a, b) {
    return b.length - a.length
  }

  function regexpOrLiteral(obj) {
    if (typeof obj === 'string') {
      return '(?:' + reEscape(obj) + ')'

    } else if (isRegExp(obj)) {
      // TODO: consider /u support
      if (obj.ignoreCase) { throw new Error('RegExp /i flag not allowed') }
      if (obj.global) { throw new Error('RegExp /g flag is implied') }
      if (obj.sticky) { throw new Error('RegExp /y flag is implied') }
      if (obj.multiline) { throw new Error('RegExp /m flag is implied') }
      return obj.source

    } else {
      throw new Error('not a pattern: ' + obj)
    }
  }

  function objectToRules(object) {
    var keys = Object.getOwnPropertyNames(object)
    var result = []
    for (var i=0; i<keys.length; i++) {
      var key = keys[i]
      result.push([key, object[key]])
    }
    return result
  }

  function ruleOptions(name, obj) {
    if (typeof obj !== 'object' || Array.isArray(obj) || isRegExp(obj)) {
      obj = { match: obj }
    }

    var options = Object.assign({
      name: name,
      lineBreaks: false,
      pop: false,
      next: null,
      push: null,
    }, obj)

    // convert to array
    if (!Array.isArray(options.match)) { options.match = [options.match] }
    return options
  }

  function sortRules(rules) {
    var result = []
    for (var i=0; i<rules.length; i++) {
      var rule = rules[i]

      // get options
      var options = ruleOptions(rule[0], rule[1])
      var match = options.match

      // sort literals by length to ensure longest match
      var capturingPatterns = []
      var patterns = []
      var literals = []
      for (var j=0; j<match.length; j++) {
        var obj = match[j]
        if (!isRegExp(obj)) literals.push(obj)
        else if (reGroups(obj.source) > 0) capturingPatterns.push(obj)
        else patterns.push(obj)
      }
      literals.sort(compareLength)

      // append regexps to the end
      options.match = literals.concat(patterns)
      if (options.match.length) {
        result.push(options)
      }

      // add each capturing regexp as a separate rule
      for (var j=0; j<capturingPatterns.length; j++) {
        result.push(Object.assign({}, options, {
          match: [capturingPatterns[j]],
        }))
      }
    }
    return result
  }

  function compileRules(rules, hasStates) {
    if (!Array.isArray(rules)) rules = objectToRules(rules)

    rules = sortRules(rules)

    var groups = []
    var parts = []
    for (var i=0; i<rules.length; i++) {
      var options = rules[i]
      groups.push(options)

      // convert to RegExp
      var pat = reUnion(options.match.map(regexpOrLiteral))

      // validate
      var regexp = new RegExp(pat)
      if (regexp.test("")) {
        throw new Error("RegExp matches empty string: " + regexp)
      }
      var groupCount = reGroups(pat)
      if (groupCount > 1) {
        throw new Error("RegExp has more than one capture group: " + regexp)
      }
      if (!hasStates && (options.pop || options.push || options.next)) {
        throw new Error("State-switching options are not allowed in stateless lexers (for token '" + options.name + "')")
      }

      // try and detect rules matching newlines
      if (!options.lineBreaks && regexp.test('\n')) {
        throw new Error('Rule should declare lineBreaks: ' + regexp)
      }

      // store regex
      var isCapture = !!groupCount
      if (!isCapture) pat = reCapture(pat)
      parts.push(pat)
    }

    var suffix = hasSticky ? '' : '|(?:)'
    var flags = hasSticky ? 'ym' : 'gm'
    var regexp = new RegExp(reUnion(parts) + suffix, flags)

    return {regexp: regexp, groups: groups}
  }

  function compile(rules) {
    var result = compileRules(rules)
    return new Lexer({start: result}, 'start')
  }

  function compileStates(states, start) {
    var keys = Object.getOwnPropertyNames(states)
    if (!start) start = keys[0]

    var map = Object.create(null)
    for (var i=0; i<keys.length; i++) {
      var key = keys[i]
      map[key] = compileRules(states[key], true)
    }

    for (var i=0; i<keys.length; i++) {
      var groups = map[keys[i]].groups
      for (var j=0; j<groups.length; j++) {
        var g = groups[i]
        var state = g && (g.push || g.next)
        if (state && !map[state]) {
          throw new Error("Missing state '" + state + "' (in token '" + g.name + "' of state '" + keys[i] + "')")
        }
      }
    }

    return new Lexer(map, start)
  }

  var Lexer = function(states, state) {
    this.states = states
    this.buffer = ''
    this.stack = []
    this.setState(state)
    this.reset()
  }

  Lexer.error = {
    name: 'ERRORTOKEN',
    lineBreaks: true,
  }

  Lexer.prototype.setState = function(state) {
    if (!state || this.state === state) return
    this.state = state
    var index = this.re ? this.re.lastIndex : 0
    var info = this.states[state]
    this.groups = info.groups
    this.re = info.regexp
    this.re.lastIndex = index
  }

  Lexer.prototype.popState = function() {
    this.setState(this.stack.pop())
  }

  Lexer.prototype.pushState = function(state) {
    this.stack.push(this.state)
    this.setState(state)
  }

  Lexer.prototype.eat = hasSticky ? function(re) {
    // assume re is /y
    return re.exec(this.buffer)
  } : function(re) {
    // assume re is /g
    var match = re.exec(this.buffer)
    // assert(match)
    // assert(match.index === 0)
    if (match[0].length === 0) {
      return null
    }
    return match
  }
  // TODO: try instead the |(?:) trick?

  function tokenToString() {
    return this.value || this.type
  }

  Lexer.prototype.lex = function() {
    var re = this.re
    var buffer = this.buffer

    if (re.lastIndex === buffer.length) {
      return // EOF
    }

    var start = re.lastIndex
    var match = this.eat(re)
    var group, value, text
    if (match === null) {
      group = Lexer.error

      // consume rest of buffer
      text = value = buffer.slice(start)
      re.lastIndex = buffer.length

    } else {
      text = match[0]
      var groups = this.groups
      for (var i = 0; i < groups.length; i++) {
        value = match[i + 1]
        if (value !== undefined) {
          group = groups[i]
          break
        }
      }
      // assert(i < groupCount)
      // TODO is `buffer` being leaked here?
    }

    // count line breaks
    var lineBreaks = 0
    if (group.lineBreaks) {
      var matchNL = /\n/g
      var nl = 1
      if (text === '\n') {
        lineBreaks = 1
      } else {
        while (matchNL.exec(text)) { lineBreaks++; nl = matchNL.lastIndex }
      }
    }

    var size = text.length
    var token = {
      type: group.name,
      value: value,
      toString: tokenToString,
      offset: start,
      size: size,
      lineBreaks: lineBreaks,
      line: this.line,
      col: this.col,
    }

    if (group.pop) this.popState()
    else if (group.push) this.pushState(group.push)
    else if (group.next) this.setState(group.next)

    this.line += lineBreaks
    if (lineBreaks !== 0) {
      this.col = size - nl + 1
    } else {
      this.col += size
    }
    return token
  }

  Lexer.prototype.lexAll = function() {
    var tokens = []
    var token
    while ((token = this.lex())) {
      tokens.push(token)
    }
    return tokens
  }

  if (typeof Symbol !== 'undefined' && Symbol.iterator) {
    var LexerIterator = function(lexer) {
      this.lexer = lexer
    }

    LexerIterator.prototype.next = function() {
      var token = this.lexer.lex()
      return {value: token, done: !token}
    }

    Lexer.prototype[Symbol.iterator] = function() {
      return new LexerIterator(this)
    }
  }

  Lexer.prototype.index = function() {
    return this.re.lastIndex
  }

  Lexer.prototype.reset = function(data, state) {
    this.buffer = data || ''
    this.re.lastIndex = 0
    this.line = state ? state.line : 1
    this.col = state ? state.col : 1
    return this
  }

  Lexer.prototype.save = function() {
    return {
      line: this.line,
      col: this.col,
    }
  }

  Lexer.prototype.feed = function(data) {
    this.buffer += data
    return this
  }

  Lexer.prototype.remaining = function() {
    return this.buffer.slice(this.re.lastIndex)
  }

  Lexer.prototype.clone = function(input) {
    var map = Object.create(null)
    var keys = Object.getOwnPropertyNames(this.states)
    for (var i = 0; i < keys.length; i++) {
      var key = keys[i]
      var s = this.states[key]
      map[key] = {
        groups: s.groups,
        regexp: new RegExp(s.regexp.source, s.regexp.flags),
      }
    }
    return new Lexer(map, this.state, input)
  }

  var moo = {} // TODO: what should moo() do?
  moo.compile = compile
  moo.states = compileStates
  return moo

}))
<|endoftext|>


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

// print heading
cur_frm.pformat.print_heading = 'Invoice';

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

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

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

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

		// if document is POS then change default print format to "POS Invoice" if no default is specified
		if(cur_frm.doc.is_pos && cur_frm.doc.docstatus===1 && cint(frappe.defaults.get_user_defaults("fs_pos_view"))===1
			&& !locals.DocType[cur_frm.doctype].default_print_format) {
			locals.DocType[cur_frm.doctype].default_print_format = "POS Invoice";
			cur_frm.setup_print_layout();
		}
	},

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

		cur_frm.dashboard.reset();

		if(doc.docstatus==1) {
			cur_frm.add_custom_button('View Ledger', function() {
				frappe.route_options = {
					"voucher_no": doc.name,
					"from_date": doc.posting_date,
					"to_date": doc.posting_date,
					"company": doc.company,
					group_by_voucher: 0
				};
				frappe.set_route("query-report", "General Ledger");
			}, "icon-table");

			// var percent_paid = cint(flt(doc.base_grand_total - doc.outstanding_amount) / flt(doc.base_grand_total) * 100);
			// cur_frm.dashboard.add_progress(percent_paid + "% Paid", percent_paid);

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

				if(!from_delivery_note) {
					cur_frm.page.add_menu_item(__('Make Delivery'), cur_frm.cscript['Make Delivery Note'], "icon-truck")
				}
			}

			if(doc.outstanding_amount!=0) {
				cur_frm.add_custom_button(__('Make Payment Entry'), cur_frm.cscript.make_bank_entry, "icon-money");
			}
		}

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

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

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

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

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

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

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

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

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

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

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

	write_off_amount: function() {
		this.write_off_outstanding_amount_automatically();
	},

	paid_amount: function() {
		this.write_off_outstanding_amount_automatically();
	},

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

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

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

});

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

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

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

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

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

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

	cur_frm.refresh_fields();
}

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

			 }
		});
	 }
}

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

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

cur_frm.cscript.make_bank_entry = function() {
	return frappe.call({
		method: "erpnext.accounts.doctype.journal_entry.journal_entry.get_payment_entry_from_sales_invoice",
		args: {
			"sales_invoice": cur_frm.doc.name
		},
		callback: function(r) {
			var doclist = frappe.model.sync(r.message);
			frappe.set_route("Form", doclist[0].doctype, doclist[0].name);
		}
	});
}

cur_frm.fields_dict.debit_to.get_query = function(doc) {
	return{
		filters: {
			'report_type': 'Balance Sheet',
			'is_group': 0,
			'company': doc.company
		}
	}
}

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

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

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

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

// Income Account in Details Table
// --------------------------------
cur_frm.set_query("income_account", "items", function(doc) {
	return{
		query: "erpnext.accounts.doctype.sales_invoice.sales_invoice.get_income_account",
		filters: {'company': doc.company}
	}
});

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

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

cur_frm.cscript.income_account = function(doc, cdt, cdn) {
	cur_frm.cscript.copy_account_in_all_row(doc, cdt, cdn, "income_account");
}

cur_frm.cscript.expense_account = function(doc, cdt, cdn) {
	cur_frm.cscript.copy_account_in_all_row(doc, cdt, cdn, "expense_account");
}

cur_frm.cscript.cost_center = function(doc, cdt, cdn) {
	cur_frm.cscript.copy_account_in_all_row(doc, cdt, cdn, "cost_center");
}

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

	if(cint(frappe.boot.notification_settings.sales_invoice)) {
		cur_frm.email_doc(frappe.boot.notification_settings.sales_invoice_message);
	} else if(cur_frm.doc.is_pos) {
		new_doc("Sales Invoice");
	}
}

cur_frm.set_query("debit_to", function(doc) {
	return{
		filters: [
			['Account', 'root_type', '=', 'Asset'],
			['Account', 'account_type', '=', 'Receivable']
		]
	}
});
<commit_msg>[minor] move buttons from sales invoice to toolbar<commit_after>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt

// print heading
cur_frm.pformat.print_heading = 'Invoice';

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

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

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

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

		// if document is POS then change default print format to "POS Invoice" if no default is specified
		if(cur_frm.doc.is_pos && cur_frm.doc.docstatus===1 && cint(frappe.defaults.get_user_defaults("fs_pos_view"))===1
			&& !locals.DocType[cur_frm.doctype].default_print_format) {
			locals.DocType[cur_frm.doctype].default_print_format = "POS Invoice";
			cur_frm.setup_print_layout();
		}
	},

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

		cur_frm.dashboard.reset();

		if(doc.docstatus==1) {
			cur_frm.add_custom_button('View Ledger', function() {
				frappe.route_options = {
					"voucher_no": doc.name,
					"from_date": doc.posting_date,
					"to_date": doc.posting_date,
					"company": doc.company,
					group_by_voucher: 0
				};
				frappe.set_route("query-report", "General Ledger");
			}, "icon-table");

			// var percent_paid = cint(flt(doc.base_grand_total - doc.outstanding_amount) / flt(doc.base_grand_total) * 100);
			// cur_frm.dashboard.add_progress(percent_paid + "% Paid", percent_paid);

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

				if(!from_delivery_note) {
					cur_frm.add_custom_button(__('Make Delivery'), cur_frm.cscript['Make Delivery Note'], "icon-truck")
				}
			}

			if(doc.outstanding_amount!=0) {
				cur_frm.add_custom_button(__('Make Payment Entry'), cur_frm.cscript.make_bank_entry, "icon-money");
			}
		}

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

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

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

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

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

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

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

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

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

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

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

	write_off_amount: function() {
		this.write_off_outstanding_amount_automatically();
	},

	paid_amount: function() {
		this.write_off_outstanding_amount_automatically();
	},

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

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

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

});

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

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

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

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

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

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

	cur_frm.refresh_fields();
}

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

			 }
		});
	 }
}

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

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

cur_frm.cscript.make_bank_entry = function() {
	return frappe.call({
		method: "erpnext.accounts.doctype.journal_entry.journal_entry.get_payment_entry_from_sales_invoice",
		args: {
			"sales_invoice": cur_frm.doc.name
		},
		callback: function(r) {
			var doclist = frappe.model.sync(r.message);
			frappe.set_route("Form", doclist[0].doctype, doclist[0].name);
		}
	});
}

cur_frm.fields_dict.debit_to.get_query = function(doc) {
	return{
		filters: {
			'report_type': 'Balance Sheet',
			'is_group': 0,
			'company': doc.company
		}
	}
}

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

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

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

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

// Income Account in Details Table
// --------------------------------
cur_frm.set_query("income_account", "items", function(doc) {
	return{
		query: "erpnext.accounts.doctype.sales_invoice.sales_invoice.get_income_account",
		filters: {'company': doc.company}
	}
});

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

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

cur_frm.cscript.income_account = function(doc, cdt, cdn) {
	cur_frm.cscript.copy_account_in_all_row(doc, cdt, cdn, "income_account");
}

cur_frm.cscript.expense_account = function(doc, cdt, cdn) {
	cur_frm.cscript.copy_account_in_all_row(doc, cdt, cdn, "expense_account");
}

cur_frm.cscript.cost_center = function(doc, cdt, cdn) {
	cur_frm.cscript.copy_account_in_all_row(doc, cdt, cdn, "cost_center");
}

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

	if(cint(frappe.boot.notification_settings.sales_invoice)) {
		cur_frm.email_doc(frappe.boot.notification_settings.sales_invoice_message);
	} else if(cur_frm.doc.is_pos) {
		new_doc("Sales Invoice");
	}
}

cur_frm.set_query("debit_to", function(doc) {
	return{
		filters: [
			['Account', 'root_type', '=', 'Asset'],
			['Account', 'account_type', '=', 'Receivable']
		]
	}
});
<|endoftext|>


<commit_before>// leave at least 2 line with only a star on it below, or doc generation fails
/**
 *
 *
 * Placeholder for custom user javascript
 * mainly to be overridden in profile/static/custom/custom.js
 * This will always be an empty file in IPython
 *
 * User could add any javascript in the `profile/static/custom/custom.js` file
 * It will be executed by the ipython notebook at load time.
 *
 * Same thing with `profile/static/custom/custom.css` to inject custom css into the notebook.
 *
 *
 * The object available at load time depend on the version of IPython in use.
 * there is no guaranties of API stability.
 *
 * The example below explain the principle, and might not be valid.
 *
 * Instances are created after the loading of this file and might need to be accessed using events:
 *     define([
 *        'base/js/namespace',
 *        'base/js/events'
 *     ], function(IPython, events) {
 *         events.on("app_initialized.NotebookApp", function () {
 *             IPython.keyboard_manager....
 *         });
 *     });
 *
 * __Example 1:__
 *
 * Create a custom button in toolbar that execute `%qtconsole` in kernel
 * and hence open a qtconsole attached to the same kernel as the current notebook
 *
 *    define([
 *        'base/js/namespace',
 *        'base/js/events'
 *    ], function(IPython, events) {
 *        events.on('app_initialized.NotebookApp', function(){
 *            IPython.toolbar.add_buttons_group([
 *                {
 *                    'label'   : 'run qtconsole',
 *                    'icon'    : 'icon-terminal', // select your icon from http://fortawesome.github.io/Font-Awesome/icons
 *                    'callback': function () {
 *                        IPython.notebook.kernel.execute('%qtconsole')
 *                    }
 *                }
 *                // add more button here if needed.
 *                ]);
 *        });
 *    });
 *
 * __Example 2:__
 *
 * At the completion of the dashboard loading, load an unofficial javascript extension
 * that is installed in profile/static/custom/
 *
 *    define([
 *        'base/js/events'
 *    ], function(events) {
 *        events.on('app_initialized.DashboardApp', function(){
 *            require(['custom/unofficial_extension.js'])
 *        });
 *    });
 *
 * __Example 3:__
 *
 *  Use `jQuery.getScript(url [, success(script, textStatus, jqXHR)] );`
 *  to load custom script into the notebook.
 *
 *    // to load the metadata ui extension example.
 *    $.getScript('/static/notebook/js/celltoolbarpresets/example.js');
 *    // or
 *    // to load the metadata ui extension to control slideshow mode / reveal js for nbconvert
 *    $.getScript('/static/notebook/js/celltoolbarpresets/slideshow.js');
 *
 *
 * @module IPython
 * @namespace IPython
 * @class customjs
 * @static
 */
<commit_msg>add dot end of sentence.<commit_after>// leave at least 2 line with only a star on it below, or doc generation fails
/**
 *
 *
 * Placeholder for custom user javascript
 * mainly to be overridden in profile/static/custom/custom.js
 * This will always be an empty file in IPython
 *
 * User could add any javascript in the `profile/static/custom/custom.js` file.
 * It will be executed by the ipython notebook at load time.
 *
 * Same thing with `profile/static/custom/custom.css` to inject custom css into the notebook.
 *
 *
 * The object available at load time depend on the version of IPython in use.
 * there is no guaranties of API stability.
 *
 * The example below explain the principle, and might not be valid.
 *
 * Instances are created after the loading of this file and might need to be accessed using events:
 *     define([
 *        'base/js/namespace',
 *        'base/js/events'
 *     ], function(IPython, events) {
 *         events.on("app_initialized.NotebookApp", function () {
 *             IPython.keyboard_manager....
 *         });
 *     });
 *
 * __Example 1:__
 *
 * Create a custom button in toolbar that execute `%qtconsole` in kernel
 * and hence open a qtconsole attached to the same kernel as the current notebook
 *
 *    define([
 *        'base/js/namespace',
 *        'base/js/events'
 *    ], function(IPython, events) {
 *        events.on('app_initialized.NotebookApp', function(){
 *            IPython.toolbar.add_buttons_group([
 *                {
 *                    'label'   : 'run qtconsole',
 *                    'icon'    : 'icon-terminal', // select your icon from http://fortawesome.github.io/Font-Awesome/icons
 *                    'callback': function () {
 *                        IPython.notebook.kernel.execute('%qtconsole')
 *                    }
 *                }
 *                // add more button here if needed.
 *                ]);
 *        });
 *    });
 *
 * __Example 2:__
 *
 * At the completion of the dashboard loading, load an unofficial javascript extension
 * that is installed in profile/static/custom/
 *
 *    define([
 *        'base/js/events'
 *    ], function(events) {
 *        events.on('app_initialized.DashboardApp', function(){
 *            require(['custom/unofficial_extension.js'])
 *        });
 *    });
 *
 * __Example 3:__
 *
 *  Use `jQuery.getScript(url [, success(script, textStatus, jqXHR)] );`
 *  to load custom script into the notebook.
 *
 *    // to load the metadata ui extension example.
 *    $.getScript('/static/notebook/js/celltoolbarpresets/example.js');
 *    // or
 *    // to load the metadata ui extension to control slideshow mode / reveal js for nbconvert
 *    $.getScript('/static/notebook/js/celltoolbarpresets/slideshow.js');
 *
 *
 * @module IPython
 * @namespace IPython
 * @class customjs
 * @static
 */
<|endoftext|>


<commit_before>'use strict';

module.exports = {
    "plugins": [
        "stylelint-scss"
    ],
    "rules"  : {
        // @-else
        "scss/at-else-closing-brace-newline-after": [
            "always-last-in-chain",
            {
                "severity": "error"
            }
        ],
        "scss/at-else-closing-brace-space-after"  : [
            "always-intermediate",
            {
                "severity": "error"
            }
        ],
        "scss/at-else-empty-line-before"          : [
            "never",
            {
                "severity": "error"
            }
        ],

        // @-extend
        "scss/at-extend-no-missing-placeholder": [
            true,
            {
                "severity": "error"
            }
        ],

        // @-function
        "scss/at-function-pattern": [
            ".+",
            {
                "severity": "error"
            }
        ],

        // @-if
        "scss/at-if-closing-brace-newline-after": [
            "always-last-in-chain",
            {
                "severity": "error"
            }
        ],
        "scss/at-if-closing-brace-space-after"  : [
            "always-intermediate",
            {
                "severity": "error"
            }
        ],

        // @-import
        "scss/at-import-no-partial-leading-underscore": [
            true,
            {
                "severity": "error"
            }
        ],
        "scss/at-import-partial-extension-blacklist"  : [
            ["scss"],
            {
                "severity": "error"
            }
        ],
        "scss/at-import-partial-extension-whitelist"  : [
            null,
            {
                "severity": "error"
            }
        ],

        // @-mixin
        "scss/at-mixin-argumentless-call-parentheses": [
            "always",
            {
                "severity": "error"
            }
        ],
        "scss/at-mixin-pattern"                      : [
            ".+",
            {
                "severity": "error"
            }
        ],

        // $-variable
        "scss/dollar-variable-colon-newline-after"     : [
            null,
            {
                "severity": "error"
            }
        ],
        "scss/dollar-variable-colon-space-after"       : [
            "always",
            {
                "severity": "error"
            }
        ],
        "scss/dollar-variable-colon-space-before"      : [
            "never",
            {
                "severity": "error"
            }
        ],
        "scss/dollar-variable-empty-line-before"       : [
            "always",
            {
                "except"  : [
                    "first-nested",
                    "after-comment",
                    "after-dollar-variable"
                ],
                "ignore"  : [
                    "inside-single-line-block"
                ],
                "severity": "error"
            }
        ],
        "scss/dollar-variable-no-missing-interpolation": [
            true,
            {
                "severity": "error"
            }
        ],
        "scss/dollar-variable-pattern"                 : [
            ".+",
            {
                "severity": "error"
            }
        ],

        // %-placeholder
        "scss/percent-placeholder-pattern": [
            ".+",
            {
                "severity": "error"
            }
        ],

        // //-comment
        "scss/double-slash-comment-empty-line-before": [
            "always",
            {
                "except"  : [
                    "first-nested"
                ],
                "ignore"  : [],
                "severity": "error"
            }
        ],
        "scss/double-slash-comment-inline"           : [
            "never",
            {
                "ignore"  : [
                    "stylelint-commands"
                ],
                "severity": "warn"
            }
        ],
        "scss/double-slash-comment-whitespace-inside": [
            "always",
            {
                "severity": "error"
            }
        ],

        // Declaration
        "scss/declaration-nested-properties"                  : [
            null,
            {
                "except"  : [
                    "only-of-namespace"
                ],
                "severity": "error"
            }
        ],
        "scss/declaration-nested-properties-no-divided-groups": [
            true,
            {
                "severity": "error"
            }
        ],

        // Media feature
        "scss/media-feature-value-dollar-variable": [
            null,
            {
                "severity": "error"
            }
        ],

        // Operator
        "scss/operator-no-newline-after" : [
            true,
            {
                "severity": "error"
            }
        ],
        "scss/operator-no-newline-before": [
            true,
            {
                "severity": "error"
            }
        ],
        "scss/operator-no-unspaced"      : [
            true,
            {
                "severity": "error"
            }
        ],

        // Partial
        "scss/partial-no-import": [
            null,
            {
                "severity": "error"
            }
        ],

        // Selector
        "scss/selector-no-redundant-nesting-selector": [
            true,
            {
                "severity": "error"
            }
        ]
    }
};
<commit_msg>do not ignore `inside-single-line-block` for `scss/dollar-variable-empty-line-before` rule<commit_after>'use strict';

module.exports = {
    "plugins": [
        "stylelint-scss"
    ],
    "rules"  : {
        // @-else
        "scss/at-else-closing-brace-newline-after": [
            "always-last-in-chain",
            {
                "severity": "error"
            }
        ],
        "scss/at-else-closing-brace-space-after"  : [
            "always-intermediate",
            {
                "severity": "error"
            }
        ],
        "scss/at-else-empty-line-before"          : [
            "never",
            {
                "severity": "error"
            }
        ],

        // @-extend
        "scss/at-extend-no-missing-placeholder": [
            true,
            {
                "severity": "error"
            }
        ],

        // @-function
        "scss/at-function-pattern": [
            ".+",
            {
                "severity": "error"
            }
        ],

        // @-if
        "scss/at-if-closing-brace-newline-after": [
            "always-last-in-chain",
            {
                "severity": "error"
            }
        ],
        "scss/at-if-closing-brace-space-after"  : [
            "always-intermediate",
            {
                "severity": "error"
            }
        ],

        // @-import
        "scss/at-import-no-partial-leading-underscore": [
            true,
            {
                "severity": "error"
            }
        ],
        "scss/at-import-partial-extension-blacklist"  : [
            ["scss"],
            {
                "severity": "error"
            }
        ],
        "scss/at-import-partial-extension-whitelist"  : [
            null,
            {
                "severity": "error"
            }
        ],

        // @-mixin
        "scss/at-mixin-argumentless-call-parentheses": [
            "always",
            {
                "severity": "error"
            }
        ],
        "scss/at-mixin-pattern"                      : [
            ".+",
            {
                "severity": "error"
            }
        ],

        // $-variable
        "scss/dollar-variable-colon-newline-after"     : [
            null,
            {
                "severity": "error"
            }
        ],
        "scss/dollar-variable-colon-space-after"       : [
            "always",
            {
                "severity": "error"
            }
        ],
        "scss/dollar-variable-colon-space-before"      : [
            "never",
            {
                "severity": "error"
            }
        ],
        "scss/dollar-variable-empty-line-before"       : [
            "always",
            {
                "except"  : [
                    "first-nested",
                    "after-comment",
                    "after-dollar-variable"
                ],
                "ignore"  : [],
                "severity": "error"
            }
        ],
        "scss/dollar-variable-no-missing-interpolation": [
            true,
            {
                "severity": "error"
            }
        ],
        "scss/dollar-variable-pattern"                 : [
            ".+",
            {
                "severity": "error"
            }
        ],

        // %-placeholder
        "scss/percent-placeholder-pattern": [
            ".+",
            {
                "severity": "error"
            }
        ],

        // //-comment
        "scss/double-slash-comment-empty-line-before": [
            "always",
            {
                "except"  : [
                    "first-nested"
                ],
                "ignore"  : [],
                "severity": "error"
            }
        ],
        "scss/double-slash-comment-inline"           : [
            "never",
            {
                "ignore"  : [
                    "stylelint-commands"
                ],
                "severity": "warn"
            }
        ],
        "scss/double-slash-comment-whitespace-inside": [
            "always",
            {
                "severity": "error"
            }
        ],

        // Declaration
        "scss/declaration-nested-properties"                  : [
            null,
            {
                "except"  : [
                    "only-of-namespace"
                ],
                "severity": "error"
            }
        ],
        "scss/declaration-nested-properties-no-divided-groups": [
            true,
            {
                "severity": "error"
            }
        ],

        // Media feature
        "scss/media-feature-value-dollar-variable": [
            null,
            {
                "severity": "error"
            }
        ],

        // Operator
        "scss/operator-no-newline-after" : [
            true,
            {
                "severity": "error"
            }
        ],
        "scss/operator-no-newline-before": [
            true,
            {
                "severity": "error"
            }
        ],
        "scss/operator-no-unspaced"      : [
            true,
            {
                "severity": "error"
            }
        ],

        // Partial
        "scss/partial-no-import": [
            null,
            {
                "severity": "error"
            }
        ],

        // Selector
        "scss/selector-no-redundant-nesting-selector": [
            true,
            {
                "severity": "error"
            }
        ]
    }
};
<|endoftext|>