<commit_before>import $ from "jquery";

import * as color_class from "./color_class";
import {$t} from "./i18n";
import * as message_view_header from "./message_view_header";
import * as stream_settings_ui from "./stream_settings_ui";

function update_table_stream_color(table, stream_name, color) {
    // This is ugly, but temporary, as the new design will make it
    // so that we only have color in the headers.
    const style = color;

    const stream_labels = $("#floating_recipient_bar").add(table).find(".stream_label");

    for (const label of stream_labels) {
        const $label = $(label);
        if ($label.text().trim() === stream_name) {
            const messages = $label.closest(".recipient_row").children(".message_row");
            messages
                .children(".messagebox")
                .css(
                    "box-shadow",
                    "inset 2px 0px 0px 0px " + style + ", -1px 0px 0px 0px " + style,
                );
            messages
                .children(".date_row")
                .css(
                    "box-shadow",
                    "inset 2px 0px 0px 0px " + style + ", -1px 0px 0px 0px " + style,
                );
            $label.css({background: style, "border-left-color": style});
            $label.removeClass("dark_background");
            $label.addClass(color_class.get_css_class(color));
        }
    }
}

function update_stream_sidebar_swatch_color(id, color) {
    $(`#stream_sidebar_swatch_${CSS.escape(id)}`).css("background-color", color);
    $(`#stream_sidebar_privacy_swatch_${CSS.escape(id)}`).css("color", color);
}

function update_historical_message_color(stream_name, color) {
    update_table_stream_color($(".focused_table"), stream_name, color);
    if ($(".focused_table").attr("id") !== "#zhome") {
        update_table_stream_color($("#zhome"), stream_name, color);
    }
}

const stream_color_palette = [
    ["a47462", "c2726a", "e4523d", "e7664d", "ee7e4a", "f4ae55"],
    ["76ce90", "53a063", "94c849", "bfd56f", "fae589", "f5ce6e"],
    ["a6dcbf", "addfe5", "a6c7e5", "4f8de4", "95a5fd", "b0a5fd"],
    ["c2c2c2", "c8bebf", "c6a8ad", "e79ab5", "bd86e5", "9987e1"],
];

const subscriptions_table_colorpicker_options = {
    clickoutFiresChange: true,
    showPalette: true,
    showInput: true,
    palette: stream_color_palette,
};

export function set_colorpicker_color(colorpicker, color) {
    colorpicker.spectrum({
        ...subscriptions_table_colorpicker_options,
        color,
        container: "#subscription_overlay .subscription_settings.show",
    });
}

export function update_stream_color(sub, color, {update_historical = false} = {}) {
    sub.color = color;
    const stream_id = sub.stream_id;
    // The swatch in the subscription row header.
    $(`.stream-row[data-stream-id='${CSS.escape(stream_id)}'] .icon`).css(
        "background-color",
        color,
    );
    // The swatch in the color picker.
    set_colorpicker_color(
        $(
            `#subscription_overlay .subscription_settings[data-stream-id='${CSS.escape(
                stream_id,
            )}'] .colorpicker`,
        ),
        color,
    );
    $(
        `#subscription_overlay .subscription_settings[data-stream-id='${CSS.escape(
            stream_id,
        )}'] .large-icon`,
    ).css("color", color);

    if (update_historical) {
        update_historical_message_color(sub.name, color);
    }
    update_stream_sidebar_swatch_color(stream_id, color);
    message_view_header.colorize_message_view_header();
}

function picker_do_change_color(color) {
    const stream_id = Number.parseInt($(this).attr("stream_id"), 10);
    const hex_color = color.toHexString();
    stream_settings_ui.set_color(stream_id, hex_color);
}
subscriptions_table_colorpicker_options.change = picker_do_change_color;

export const sidebar_popover_colorpicker_options = {
    clickoutFiresChange: true,
    showPaletteOnly: true,
    showPalette: true,
    showInput: true,
    flat: true,
    palette: stream_color_palette,
    change: picker_do_change_color,
};

export const sidebar_popover_colorpicker_options_full = {
    clickoutFiresChange: false,
    showPalette: true,
    showInput: true,
    flat: true,
    cancelText: "",
    chooseText: $t({defaultMessage: "Confirm"}),
    palette: stream_color_palette,
    change: picker_do_change_color,
};
<commit_msg>stream_color: Fix stream color not updating to default.<commit_after>import $ from "jquery";

import * as color_class from "./color_class";
import {$t} from "./i18n";
import * as message_view_header from "./message_view_header";
import * as stream_settings_ui from "./stream_settings_ui";

function update_table_stream_color(table, stream_name, color) {
    // This is ugly, but temporary, as the new design will make it
    // so that we only have color in the headers.
    const style = color;

    const stream_labels = $("#floating_recipient_bar").add(table).find(".stream_label");

    for (const label of stream_labels) {
        const $label = $(label);
        if ($label.text().trim() === stream_name) {
            const messages = $label.closest(".recipient_row").children(".message_row");
            messages
                .children(".messagebox")
                .css(
                    "box-shadow",
                    "inset 2px 0px 0px 0px " + style + ", -1px 0px 0px 0px " + style,
                );
            messages
                .children(".date_row")
                .css(
                    "box-shadow",
                    "inset 2px 0px 0px 0px " + style + ", -1px 0px 0px 0px " + style,
                );
            $label.css({background: style, "border-left-color": style});
            $label.removeClass("dark_background");
            $label.addClass(color_class.get_css_class(color));
        }
    }
}

function update_stream_sidebar_swatch_color(id, color) {
    $(`#stream_sidebar_swatch_${CSS.escape(id)}`).css("background-color", color);
    $(`#stream_sidebar_privacy_swatch_${CSS.escape(id)}`).css("color", color);
}

function update_historical_message_color(stream_name, color) {
    update_table_stream_color($(".focused_table"), stream_name, color);
    if ($(".focused_table").attr("id") !== "#zhome") {
        update_table_stream_color($("#zhome"), stream_name, color);
    }
}

const stream_color_palette = [
    ["a47462", "c2726a", "e4523d", "e7664d", "ee7e4a", "f4ae55"],
    ["76ce90", "53a063", "94c849", "bfd56f", "fae589", "f5ce6e"],
    ["a6dcbf", "addfe5", "a6c7e5", "4f8de4", "95a5fd", "b0a5fd"],
    ["c2c2c2", "c8bebf", "c6a8ad", "e79ab5", "bd86e5", "9987e1"],
];

const subscriptions_table_colorpicker_options = {
    clickoutFiresChange: true,
    showPalette: true,
    showInput: true,
    palette: stream_color_palette,
};

export function set_colorpicker_color(colorpicker, color) {
    colorpicker.spectrum({
        ...subscriptions_table_colorpicker_options,
        color,
        container: "#subscription_overlay .subscription_settings.show",
    });
}

export function update_stream_color(sub, color, {update_historical = false} = {}) {
    sub.color = color;
    const stream_id = sub.stream_id;
    // The swatch in the subscription row header.
    $(`.stream-row[data-stream-id='${CSS.escape(stream_id)}'] .icon`).css(
        "background-color",
        color,
    );
    // The swatch in the color picker.
    set_colorpicker_color(
        $(
            `#subscription_overlay .subscription_settings[data-stream-id='${CSS.escape(
                stream_id,
            )}'] .colorpicker`,
        ),
        color,
    );
    $(
        `#subscription_overlay .subscription_settings[data-stream-id='${CSS.escape(
            stream_id,
        )}'] .large-icon`,
    ).css("color", color);

    if (update_historical) {
        update_historical_message_color(sub.name, color);
    }
    update_stream_sidebar_swatch_color(stream_id, color);
    message_view_header.colorize_message_view_header();
}

export const sidebar_popover_colorpicker_options_full = {
    clickoutFiresChange: false,
    showPalette: true,
    showInput: true,
    flat: true,
    cancelText: "",
    chooseText: $t({defaultMessage: "Confirm"}),
    palette: stream_color_palette,
    change: picker_do_change_color,
};

function picker_do_change_color(color) {
    $(".colorpicker").spectrum("destroy");
    $(".colorpicker").spectrum(sidebar_popover_colorpicker_options_full);
    const stream_id = Number.parseInt($(this).attr("stream_id"), 10);
    const hex_color = color.toHexString();
    stream_settings_ui.set_color(stream_id, hex_color);
}
subscriptions_table_colorpicker_options.change = picker_do_change_color;

export const sidebar_popover_colorpicker_options = {
    clickoutFiresChange: true,
    showPaletteOnly: true,
    showPalette: true,
    showInput: true,
    flat: true,
    palette: stream_color_palette,
    change: picker_do_change_color,
};
<|endoftext|>


<commit_before>/** @this {Place|Rail|Service} */
function offerBuying(player) {
	ask('buy ' + this.name + ' for ' + this.price + '?', player, buy.bind(this));
}

/** @this {Place|Rail|Service} */
function buy(player) {
	if (!player.tryPaying(this.price)) {
		return false;
	}
	changeOwner.call(this, player);
}

/** @this {Place|Rail|Service} */
function changeOwner(owner) {
	if (this.owner) {
		this.div.classList.remove('owner' + this.owner.index);
	}
	this.owner = owner;
	if (owner) {
		this.div.classList.add('owner' + owner.index);
		this.div.classList.add('owned');
		this.div.onclick = offerSelling.bind(this);
	} else {
		this.div.classList.remove('owned');
		this.div.onclick = undefined;
	}
	if (this.updateEarns) {
		this.updateEarns();
	}
}

function escape(s) {
	return s.replace(/&/g, '&').replace(/</g, '<');
}

function last(ar) {
	return ar[ar.length - 1];
}

/** @this {Place|Rail|Service} */
function offerSelling() {
	var input = '<input class=price type=number step=10 min=0 value=' + (this.price + (this.upgrades * this.upgradePrice || 0)) + '>';
	var options = [];
	// TODO: Sell to the bank for a fixed price.
	for (var i = 0; i < 4; i++) {
		var player = players[i];
		if (player && player != this.owner) {
			options.push('<option value=' + i + '>' + escape(player.name));
		}
	}
	if (!options.length) {
		say('nobody to sell to.', this.owner);
		return;
	}
	// TODO: Disable selling if there are upgrades with the same color.
	ask('sell ' + this.name + ' for ' + input + ' to <select class=buyer size=' + options.length + '>' + options.join('') + '</select>?', this.owner, sell.bind(this));
	last(document.getElementsByClassName('price')).focus();
}

/** @this {Place|Rail|Service} */
function sell() {
	var price = +last(document.getElementsByClassName('price')).value;
	var buyerIndex = last(document.getElementsByClassName('buyer')).value;
	if (!(price > 0)) { // price might be NaN.
		say('input a valid price.', this.owner);
		return false;
	}
	if (!buyerIndex) {
		say('select a buyer.', this.owner);
		return false;
	}
	var buyer = players[buyerIndex];
	if (!buyer.tryPaying(price, this.owner)) {
		return false;
	}
	changeOwner.call(this, buyer);
}

function goTo(position, player, diced) {
	player.position = position;
	player.moveFigure();
	say('you went to ' + fields[position].name + '.', player);
	if (fields[position].visit) {
		fields[position].visit(player, diced || 0);
	}
}

function moveForward(number, player) {
	if (player.position == 10 || player.position == 30) {
		for (var i = 0, field; field = fields[i]; i++) {
			if (field instanceof Place && field.owner == player) {
				field.earns = field.amounts[field.upgrades];
				field.updateEarns();
			}
		}
	}

	if (player.position + number > fields.length) {
		say('you passed Start.', player);
		start.visit(player);
	}
	goTo((player.position + number + fields.length) % fields.length, player, number); // + fields.length - number might be negative.
}

function goToJail(player) {
	goTo(10, player);
	player.jailed = true;
}

function earn(amount, player) {
	player.pay(-amount);
}

function say(message, player) {
	var p = document.createElement('p');
	p.innerHTML = (player ? escape(player.name) + ', ' : '') + message;
	document.getElementById('message').appendChild(p);
	p.scrollIntoView();
}

function ask(message, player, callback) {
	var question = '' + message + '';
	if (!questions.length || last(questions).message != question) {
		say(question, player);
		var index = questions.length && questions[0].primary ? 1 : 0;
		questions[index] = {message: question, player: player, callback: callback};
		document.querySelector('.cancel').disabled = questions.length < 2;
	}
}
<commit_msg>Monopoly: Selling to bank<commit_after>/** @this {Place|Rail|Service} */
function offerBuying(player) {
	ask('buy ' + this.name + ' for ' + this.price + '?', player, buy.bind(this));
}

/** @this {Place|Rail|Service} */
function buy(player) {
	if (!player.tryPaying(this.price)) {
		return false;
	}
	changeOwner.call(this, player);
}

/** @this {Place|Rail|Service} */
function changeOwner(owner) {
	if (this.owner) {
		this.div.classList.remove('owner' + this.owner.index);
	}
	this.owner = owner;
	if (owner) {
		this.div.classList.add('owner' + owner.index);
		this.div.classList.add('owned');
		this.div.onclick = offerSelling.bind(this);
	} else {
		this.div.classList.remove('owned');
		this.div.onclick = undefined;
	}
	if (this.updateEarns) {
		this.updateEarns();
	}
}

function escape(s) {
	return s.replace(/&/g, '&').replace(/</g, '<');
}

function last(ar) {
	return ar[ar.length - 1];
}

/** @this {Place|Rail|Service} */
function offerSelling() {
	var input = '<input class=price type=number step=10 min=0 value=' + (this.price + (this.upgrades * this.upgradePrice || 0)) + '>';
	var options = [];
	if (this.owner.money < 0) {
		options.push('<option value=-1>bank');
	}
	for (var i = 0; i < 4; i++) {
		var player = players[i];
		if (player && player != this.owner) {
			options.push('<option value=' + i + '>' + escape(player.name));
		}
	}
	if (!options.length) {
		say('nobody to sell to.', this.owner);
		return;
	}
	// TODO: Disable selling if there are upgrades with the same color.
	ask('sell ' + this.name + ' for ' + input + ' to <select class=buyer size=' + options.length + '>' + options.join('') + '</select>?', this.owner, sell.bind(this));
	last(document.getElementsByClassName('price')).focus();
}

/** @this {Place|Rail|Service} */
function sell() {
	var price = +last(document.getElementsByClassName('price')).value;
	var buyerIndex = last(document.getElementsByClassName('buyer')).value;
	if (!(price > 0)) { // price might be NaN.
		say('input a valid price.', this.owner);
		return false;
	}
	if (!buyerIndex) {
		say('select a buyer.', this.owner);
		return false;
	}
	var buyer = players[buyerIndex];
	if (!buyer) {
		earn(price, this.owner);
	} else if (!buyer.tryPaying(price, this.owner)) {
		return false;
	}
	changeOwner.call(this, buyer);
}

function goTo(position, player, diced) {
	player.position = position;
	player.moveFigure();
	say('you went to ' + fields[position].name + '.', player);
	if (fields[position].visit) {
		fields[position].visit(player, diced || 0);
	}
}

function moveForward(number, player) {
	if (player.position == 10 || player.position == 30) {
		for (var i = 0, field; field = fields[i]; i++) {
			if (field instanceof Place && field.owner == player) {
				field.earns = field.amounts[field.upgrades];
				field.updateEarns();
			}
		}
	}

	if (player.position + number > fields.length) {
		say('you passed Start.', player);
		start.visit(player);
	}
	goTo((player.position + number + fields.length) % fields.length, player, number); // + fields.length - number might be negative.
}

function goToJail(player) {
	goTo(10, player);
	player.jailed = true;
}

function earn(amount, player) {
	player.pay(-amount);
}

function say(message, player) {
	var p = document.createElement('p');
	p.innerHTML = (player ? escape(player.name) + ', ' : '') + message;
	document.getElementById('message').appendChild(p);
	p.scrollIntoView();
}

function ask(message, player, callback) {
	var question = '' + message + '';
	if (!questions.length || last(questions).message != question) {
		say(question, player);
		var index = questions.length && questions[0].primary ? 1 : 0;
		questions[index] = {message: question, player: player, callback: callback};
		document.querySelector('.cancel').disabled = questions.length < 2;
	}
}
<|endoftext|>


<commit_before>/* global it,describe,before */
var ContentDiscovery = require('../lib/contentDiscovery')
var Message = require('../lib/message')
var should = require('should')

var q = require('q')

// Create a temporary to be used during tests
function getDattObject () {
  var datt = {}
  datt.getContent = function (hash) {
    var deferred = q.defer()
    if (hash === 'testhash') {
      deferred.resolve('testcontent')
    } else {
      deferred.reject()
    }
    return deferred.promise
  }
  datt.broadcastMessage = function (msg) {
    return q('broadcasted')
  }
  datt.sendMessage = function (msg, sender) {
    return q('sentMessage')
  }

  datt.peer = {}
  datt.peer.id = '0'
  return datt
}

describe('ContentDiscovery', function () {
  var contentDiscovery
  var datt = getDattObject()

  before(function () {
    contentDiscovery = new ContentDiscovery()
  })

  describe('ContentDiscovery', function () {
    it('should exist test contentDiscovery', function () {
      should.exist(contentDiscovery)
    })
  })

  describe('#handleContentDiscoveryRequest', function () {
    it('should not handle message coming from itself', function () {
      var message = Message.requestPeersForHash('testhash', datt)
      return contentDiscovery.handleContentDiscoveryRequest(message, datt).then(function (result) {
        result.should.equal('Own message')
      })
    })

    it('should handle message with another id and send an announcement because it has this content', function () {
      datt.peer.id = '1'
      var message = Message.requestPeersForHash('testhash', datt)
      datt.peer.id = '0'
      return contentDiscovery.handleContentDiscoveryRequest(message, datt).then(function (result) {
        result.should.eql(['broadcasted', 'sentMessage'])
      })
    })

    it('should not propagate the same message twice', function () {
      datt.peer.id = '1'
      var message = Message.requestPeersForHash('testhash', datt)
      datt.peer.id = '0'
      return contentDiscovery.handleContentDiscoveryRequest(message, datt).then(function (result) {
        result.should.equal('Already seen message. Stop propagating')
      })
    })

    it('should propagate message and not send announcement', function () {
      datt.peer.id = '1'
      var message = Message.requestPeersForHash('testhash2', datt)
      datt.peer.id = '0'
      return contentDiscovery.handleContentDiscoveryRequest(message, datt).then(function (result) {
        result.should.eql(['broadcasted', 'Did not have content'])
      })
    })
  })

  it('should throw an error if it cannot send announcement', function () {
    // Create datt object with failing send
    var datt2 = getDattObject()
    datt2.sendMessage = function (msg, sender) {
      var deferred = q.defer()
      deferred.reject('send error')
      return deferred.promise
    }
    datt2.peer.id = '2'
    var message = Message.requestPeersForHash('testhash', datt2)
    datt2.peer.id = '0'

    return contentDiscovery.handleContentDiscoveryRequest(message, datt).then(function (result) {
      should.fail('ContentDiscover#handleContentDiscoveryRequest should fail when unable to send message')
    }).fail(function (error) {
      error.should.equal('send error')
    })
  })
})
<commit_msg>fix failing test<commit_after>/* global it,describe,before */
var ContentDiscovery = require('../lib/contentDiscovery')
var Message = require('../lib/message')
var should = require('should')

var q = require('q')

// Create a temporary to be used during tests
function getDattObject () {
  var datt = {}
  datt.getContent = function (hash) {
    var deferred = q.defer()
    if (hash === 'testhash') {
      deferred.resolve('testcontent')
    } else {
      deferred.reject()
    }
    return deferred.promise
  }
  datt.broadcastMessage = function (msg) {
    return q('broadcasted')
  }
  datt.sendMessage = function (msg, sender) {
    return q('sentMessage')
  }

  datt.peer = {}
  datt.peer.id = '0'
  return datt
}

describe('ContentDiscovery', function () {
  var contentDiscovery
  var datt = getDattObject()

  before(function () {
    contentDiscovery = new ContentDiscovery()
  })

  describe('ContentDiscovery', function () {
    it('should exist test contentDiscovery', function () {
      should.exist(contentDiscovery)
    })
  })

  describe('#handleContentDiscoveryRequest', function () {
    it('should not handle message coming from itself', function () {
      var message = Message.requestPeersForHash('testhash', datt)
      return contentDiscovery.handleContentDiscoveryRequest(message, datt).then(function (result) {
        result.should.equal('Own message')
      })
    })

    it('should handle message with another id and send an announcement because it has this content', function () {
      datt.peer.id = '1'
      var message = Message.requestPeersForHash('testhash', datt)
      datt.peer.id = '0'
      return contentDiscovery.handleContentDiscoveryRequest(message, datt).then(function (result) {
        result.should.eql(['broadcasted', 'sentMessage'])
      })
    })

    it('should not propagate the same message twice', function () {
      datt.peer.id = '1'
      var message = Message.requestPeersForHash('testhash', datt)
      datt.peer.id = '0'
      return contentDiscovery.handleContentDiscoveryRequest(message, datt).then(function (result) {
        result.should.equal('Already seen message. Stop propagating')
      })
    })

    it('should propagate message and not send announcement', function () {
      datt.peer.id = '1'
      var message = Message.requestPeersForHash('testhash2', datt)
      datt.peer.id = '0'
      return contentDiscovery.handleContentDiscoveryRequest(message, datt).then(function (result) {
        result.should.eql(['broadcasted', 'Did not have content'])
      })
    })
  })

  it('should throw an error if it cannot send announcement', function () {
    // Create datt object with failing send
    var datt2 = getDattObject()
    datt2.sendMessage = function (msg, sender) {
      var deferred = q.defer()
      deferred.reject('send error')
      return deferred.promise
    }
    datt2.peer.id = '2'
    var message = Message.requestPeersForHash('testhash', datt2)
    datt2.peer.id = '0'

    return contentDiscovery.handleContentDiscoveryRequest(message, datt2).then(function (result) {
      should.fail('ContentDiscover#handleContentDiscoveryRequest should fail when unable to send message')
    }).fail(function (error) {
      error.should.equal('send error')
    })
  })
})
<|endoftext|>


<commit_before>// test CSVObject2
var CSV = require('../index.js');
var assert = require('assert');

describe('CSVObject2', function () {
  var file_test1 = __dirname + "/test1.csv";
  var file_test_sjis = __dirname + "/test-sjis.csv";
  var file_tmp = __dirname + '/tmp.csv';

  it('sort', function () {
    //
    var csv = new CSV.CSVObject();
    csv.setArray([
      ["name", "age"],
      ["Nami",  30],
      ["Sanae", 19],
      ["Aki",   17]
    ]);
    csv.useHeader = true;
    csv.sort(0); // order by name
    assert.equal(csv.getCell(1,0), "Aki");
    assert.equal(csv.getCell(2,0), "Nami");
    assert.equal(csv.getCell(3,0), "Sanae");
    //
    csv.sort(1); // order by age ASC
    assert.equal(csv.getCell(1,0), "Aki");
    assert.equal(csv.getCell(2,0), "Sanae");
    assert.equal(csv.getCell(3,0), "Nami");
  });

  it('sortNumber', function () {
    //
    var csv = new CSV.CSVObject();
    csv.setArray([
      ["name", "age"],
      ["Nami",  "30"],
      ["Sanae", "19"],
      ["Aki",   "17"]
    ]);
    csv.useHeader = true;
    csv.sortNumber(1, false); // order by age DESC
    assert.equal(csv.getCell(1,0), "Nami");
    assert.equal(csv.getCell(2,0), "Sanae");
    assert.equal(csv.getCell(3,0), "Aki");
  });

  it('insertCol', function () {
    var csv = new CSV.CSVObject();
    csv.setArray([
      ["name", "age"],
      ["Nami", 30],
      ["Aki",  12],
      ["Huyu", 17]
    ]);
    // insert
    csv.insertCol(1, [
      "level", 3, 5, 2
    ]);
    // sort by level
    csv.useHeader = true;
    csv.sort(1);
    //
    assert.equal(csv.getCell(1,0), "Huyu");
    assert.equal(csv.getCell(2,0), "Nami");
    assert.equal(csv.getCell(3,0), "Aki");
  });
  it('insertCol', function () {
    var csv = new CSV.CSVObject();
    csv.setArray([
      ["name", "age", "rank"],
      ["Nami", 30, 1],
      ["Aki",  20, 2],
      ["Huyu", 10, 3]
    ]);
    // delete
    csv.deleteCol(1);
    // sort by rank
    csv.useHeader = true;
    csv.sort(1);
    //
    assert.equal(csv.getCell(1,0), "Nami");
    assert.equal(csv.getCell(2,0), "Aki");
    assert.equal(csv.getCell(3,0), "Huyu");
  });

});

<commit_msg>Add sort test<commit_after>// test CSVObject2
var CSV = require('../index.js');
var assert = require('assert');

describe('CSVObject2', function () {
  var file_test1 = __dirname + "/test1.csv";
  var file_test_sjis = __dirname + "/test-sjis.csv";
  var file_tmp = __dirname + '/tmp.csv';

  it('sort', function () {
    //
    var csv = new CSV.CSVObject();
    csv.setArray([
      ["name", "age"],
      ["Nami",  30],
      ["Sanae", 19],
      ["Aki",   17]
    ]);
    csv.useHeader = true;
    csv.sort(0); // order by name
    assert.equal(csv.getCell(1,0), "Aki");
    assert.equal(csv.getCell(2,0), "Nami");
    assert.equal(csv.getCell(3,0), "Sanae");
    //
    csv.sort(1); // order by age ASC
    assert.equal(csv.getCell(1,0), "Aki");
    assert.equal(csv.getCell(2,0), "Sanae");
    assert.equal(csv.getCell(3,0), "Nami");
  });

  it('sort2', function () {
    //
    var csv = new CSV.CSVObject();
    csv.parse("name,rank,age\nHaru,A,22\nNatu,B,23\nAki,C,19\n");
    csv.useHeader = true;
    csv.sort(1, false); // order by rank DESC
    assert.equal(csv.getCell(1,0), "Aki");
    assert.equal(csv.getCell(2,0), "Natu");
    assert.equal(csv.getCell(3,0), "Haru");
    //
    csv.sort(2); // order by age ASC
    assert.equal(csv.getCell(1,0), "Aki");
    assert.equal(csv.getCell(2,0), "Haru");
    assert.equal(csv.getCell(3,0), "Natu");
  });

  it('sortNumber', function () {
    //
    var csv = new CSV.CSVObject();
    csv.setArray([
      ["name", "age"],
      ["Nami",  "30"],
      ["Sanae", "19"],
      ["Aki",   "17"]
    ]);
    csv.useHeader = true;
    csv.sortNumber(1, false); // order by age DESC
    assert.equal(csv.getCell(1,0), "Nami");
    assert.equal(csv.getCell(2,0), "Sanae");
    assert.equal(csv.getCell(3,0), "Aki");
  });

  it('insertCol', function () {
    var csv = new CSV.CSVObject();
    csv.setArray([
      ["name", "age"],
      ["Nami", 30],
      ["Aki",  12],
      ["Huyu", 17]
    ]);
    // insert
    csv.insertCol(1, [
      "level", 3, 5, 2
    ]);
    // sort by level
    csv.useHeader = true;
    csv.sort(1);
    //
    assert.equal(csv.getCell(1,0), "Huyu");
    assert.equal(csv.getCell(2,0), "Nami");
    assert.equal(csv.getCell(3,0), "Aki");
  });
  it('insertCol', function () {
    var csv = new CSV.CSVObject();
    csv.setArray([
      ["name", "age", "rank"],
      ["Nami", 30, 1],
      ["Aki",  20, 2],
      ["Huyu", 10, 3]
    ]);
    // delete
    csv.deleteCol(1);
    // sort by rank
    csv.useHeader = true;
    csv.sort(1);
    //
    assert.equal(csv.getCell(1,0), "Nami");
    assert.equal(csv.getCell(2,0), "Aki");
    assert.equal(csv.getCell(3,0), "Huyu");
  });

});

<|endoftext|>


<commit_before>/* global loadDateFixture, appendChartID */
describe('dc.inputFilter', function () {
    var dateFixture;
    var id, chart, data;
    var dimension, group;
    var countryDimension;

    beforeEach(function () {
        dateFixture = loadDateFixture();
        data = crossfilter(dateFixture);
        dimension = data.dimension(function (d) {
            return d.countrycode.toLowerCase() + ' ' + d.state.toLowerCase();
        });
        group = dimension.group().reduceSum(function (d) {
            return 1;
        });
        countryDimension = data.dimension(function (d) {
            return d.countrycode;
        });

        id = 'input-filter';
        appendChartID(id);
        chart = dc.inputFilter('#' + id)
            .dimension(dimension)
            .group(group);
        chart.render();
    });

    describe('creation', function () {
        it('generates something', function () {
            expect(chart).not.toBeNull();
        });
        it('registers', function () {
            expect(dc.hasChart(chart)).toBeTruthy();
        });
        it('sets an input field', function () {
            expect(chart.selectAll('input').nodes().length).toEqual(1);
        });
        it('doesn\'t filter by default', function () {
            expect(chart.dimension().top(1000).length).toEqual(100);
        });
    });

    describe('default accessor functions', function () {
        it('exists for html()', function () {
            var html = chart.html();
            expect(typeof html).toBe('function');
        });
        it('exists for normalize()', function () {
            var normalize = chart.normalize();
            expect(typeof normalize).toBe('function');
        });
        it('exists for filterFunction()', function () {
            var filterFunction = chart.filterFunction();
            expect(typeof filterFunction).toBe('function');
        });
        it('exists for throttleDuration()', function () {
            var throttleDuration = chart.throttleDuration();
            expect(typeof throttleDuration).toBe('number');
            expect(throttleDuration).toBe(200);
        });
    });

    describe('change the html search field', function () {
        it('generates something', function () {
            expect(chart).not.toBeNull();
        });
        it('registers', function () {
            expect(dc.hasChart(chart)).toBeTruthy();
        });
        it('sets an input field', function () {
            expect(chart.selectAll('input').nodes().length).toEqual(1);
        });
        it('doesn\'t filter by default', function () {
            expect(chart.dimension().top(1000).length).toEqual(100);
        });
    });

    describe('filter when typing', function () {
        var mockTyping = function (q) {
            var i = d3.select('input');
            i.nodes()[0].value = q;
            i.on('input').call(i.node(), i.datum());
        };

        beforeEach(function () {
            chart.redraw();
        });

        it('has a mock function that sets the value', function () {
            mockTyping('42');
            expect(chart.selectAll('input').nodes()[0].value).toEqual('42');
        });

        it('a letter that exists', function () {
            mockTyping('C');
            expect(chart.selectAll('input').nodes().length).toEqual(1);
        });

    });

    afterEach(function () {
        dimension.filterAll();
    });
});
<commit_msg>Tests passing<commit_after>/* global loadDateFixture, appendChartID */
describe('dc.inputFilter', function () {
    var dateFixture;
    var id, chart, data;
    var dimension, group;
    var countryDimension;

    beforeEach(function () {
        dateFixture = loadDateFixture();
        data = crossfilter(dateFixture);
        dimension = data.dimension(function (d) {
            return d.countrycode.toLowerCase() + ' ' + d.state.toLowerCase();
        });
        group = dimension.group().reduceSum(function (d) {
            return 1;
        });
        countryDimension = data.dimension(function (d) {
            return d.countrycode;
        });

        id = 'input-filter';
        appendChartID(id);
        chart = dc.inputFilter('#' + id)
            .dimension(dimension)
            .group(group);
        chart.render();
    });

    describe('creation', function () {
        it('generates something', function () {
            expect(chart).not.toBeNull();
        });
        it('registers', function () {
            expect(dc.hasChart(chart)).toBeTruthy();
        });
        it('sets an input field', function () {
            expect(chart.selectAll('input').nodes().length).toEqual(1);
        });
        it('doesn\'t filter by default', function () {
            expect(chart.dimension().top(1000).length).toEqual(10);
        });
    });

    describe('default accessor functions', function () {
        it('exists for html()', function () {
            var html = chart.html();
            expect(typeof html).toBe('function');
        });
        it('exists for normalize()', function () {
            var normalize = chart.normalize();
            expect(typeof normalize).toBe('function');
        });
        it('exists for filterFunction()', function () {
            var filterFunction = chart.filterFunction();
            expect(typeof filterFunction).toBe('function');
        });
        it('exists for throttleDuration()', function () {
            var throttleDuration = chart.throttleDuration();
            expect(typeof throttleDuration).toBe('number');
            expect(throttleDuration).toBe(200);
        });
    });

    describe('change the html search field', function () {
        it('generates something', function () {
            expect(chart).not.toBeNull();
        });
        it('registers', function () {
            expect(dc.hasChart(chart)).toBeTruthy();
        });
        it('sets an input field', function () {
            expect(chart.selectAll('input').nodes().length).toEqual(1);
        });
        it('doesn\'t filter by default', function () {
            expect(chart.dimension().top(1000).length).toEqual(10);
        });
    });

    describe('filter when typing', function () {
        var mockTyping = function (q) {
            var i = d3.select('input');
            i.nodes()[0].value = q;
            i.on('input').call(i.node(), i.datum());
        };

        beforeEach(function () {
            chart.redraw();
        });

        it('has a mock function that sets the value', function () {
            mockTyping('42');
            expect(chart.selectAll('input').nodes()[0].value).toEqual('42');
        });

        it('a letter that exists', function () {
            mockTyping('C');
            expect(chart.selectAll('input').nodes().length).toEqual(1);
        });

    });

    afterEach(function () {
        dimension.filterAll();
    });
});
<|endoftext|>


<commit_before>import React, {Component, PropTypes} from 'react';
import {Field, reduxForm} from 'redux-form';
import MenuItem from 'material-ui/MenuItem';
import RaisedButton from 'material-ui/RaisedButton';

import DICTIONARY_LANGS from './../../main/constants/dictionaryLangs';
import asyncValidate from './editFolderFormAsyncValidate';
import validate from './editFolderFormValidate';
import injectF from './../../helpers/injectF';
import injectMuiReduxFormHelper from './../../helpers/injectMuiReduxFormHelper';
import MULTI_LANG_FIELDS from './../../constants/multiLangFields';
import REGULAR_FIELDS from './../../constants/regularFields';
import {SELECTED_MENU_STYLE} from './../../constants/constants';

@reduxForm({
  form: 'editFolderForm',
  asyncValidate,
  validate
})
@injectF
@injectMuiReduxFormHelper
export default class EditFolderForm extends Component {

  static propTypes = {
    renderTextField: PropTypes.func.isRequired,
    renderSelectField: PropTypes.func.isRequired,
    handleSubmit: PropTypes.func.isRequired,
    buttonFontSize: PropTypes.string.isRequired,
    initialValues: PropTypes.object.isRequired,
    targetLanguages: PropTypes.array.isRequired,
    onTargetLanguagesChange: PropTypes.func.isRequired,
    f: PropTypes.func.isRequired,
    values: PropTypes.object
  };

  renderLangMenuItems(key) {
    return DICTIONARY_LANGS.map(({value, text}) => {
      return <MenuItem key={`${key}-${value}`} value={value} primaryText={text} />;
    });
  }

  renderContentFields = () => {

    const {f, targetLanguages} = this.props;
    const fields = [];

    MULTI_LANG_FIELDS.forEach((textId) => {
      (targetLanguages || []).forEach((lang) => {
        fields.push({textId, params: {lang: f(lang)}, value: `${textId}-${lang}`});
      });
    });

    return fields.concat(REGULAR_FIELDS)
      .map(({value, textId, params}) => {
        return <MenuItem key={`content-field-${value}`} value={value} primaryText={f(textId, params)} />;
      });
  };

  render() {

    const {handleSubmit, f, renderTextField, renderSelectField, onTargetLanguagesChange, buttonFontSize} = this.props;

    return (
      <form onSubmit={handleSubmit}>

          <Field name="folderName" component={renderTextField} label={f('folder-name')} autoFocus />

          <Field name="sourceLanguage" component={renderSelectField}
            selectedMenuItemStyle={SELECTED_MENU_STYLE} label={f('source-language')}>
            {this.renderLangMenuItems('source-lang')}
          </Field>

          <Field name="targetLanguages" component={renderSelectField} selectedMenuItemStyle={SELECTED_MENU_STYLE}
            onChange={onTargetLanguagesChange} label={f('target-language')} multiple>
            {this.renderLangMenuItems('target-lang')}
          </Field>

          <Field name="contentFields" component={renderSelectField}
            selectedMenuItemStyle={SELECTED_MENU_STYLE} label={f('content-fields')} multiple fullWidth>
            {this.renderContentFields()}
          </Field>

          <Field name="source" component={renderTextField} label={f('source')} />

          <RaisedButton primary type="submit" label={f('update')} labelStyle={{fontSize: buttonFontSize}} />

      </form>
    );
  }
}
<commit_msg>remove buttonFontSize prop<commit_after>import React, {Component, PropTypes} from 'react';
import {Field, reduxForm} from 'redux-form';
import MenuItem from 'material-ui/MenuItem';
import RaisedButton from 'material-ui/RaisedButton';

import DICTIONARY_LANGS from './../../main/constants/dictionaryLangs';
import asyncValidate from './editFolderFormAsyncValidate';
import validate from './editFolderFormValidate';
import injectF from './../../helpers/injectF';
import injectMuiReduxFormHelper from './../../helpers/injectMuiReduxFormHelper';
import MULTI_LANG_FIELDS from './../../constants/multiLangFields';
import REGULAR_FIELDS from './../../constants/regularFields';
import {SELECTED_MENU_STYLE} from './../../constants/constants';

@reduxForm({
  form: 'editFolderForm',
  asyncValidate,
  validate
})
@injectF
@injectMuiReduxFormHelper
export default class EditFolderForm extends Component {

  static propTypes = {
    renderTextField: PropTypes.func.isRequired,
    renderSelectField: PropTypes.func.isRequired,
    handleSubmit: PropTypes.func.isRequired,
    initialValues: PropTypes.object.isRequired,
    targetLanguages: PropTypes.array.isRequired,
    onTargetLanguagesChange: PropTypes.func.isRequired,
    f: PropTypes.func.isRequired,
    values: PropTypes.object
  };

  renderLangMenuItems(key) {
    return DICTIONARY_LANGS.map(({value, text}) => {
      return <MenuItem key={`${key}-${value}`} value={value} primaryText={text} />;
    });
  }

  renderContentFields = () => {

    const {f, targetLanguages} = this.props;
    const fields = [];

    MULTI_LANG_FIELDS.forEach((textId) => {
      (targetLanguages || []).forEach((lang) => {
        fields.push({textId, params: {lang: f(lang)}, value: `${textId}-${lang}`});
      });
    });

    return fields.concat(REGULAR_FIELDS)
      .map(({value, textId, params}) => {
        return <MenuItem key={`content-field-${value}`} value={value} primaryText={f(textId, params)} />;
      });
  };

  render() {

    const {handleSubmit, f, renderTextField, renderSelectField, onTargetLanguagesChange} = this.props;

    return (
      <form onSubmit={handleSubmit}>

          <Field name="folderName" component={renderTextField} label={f('folder-name')} autoFocus />

          <Field name="sourceLanguage" component={renderSelectField}
            selectedMenuItemStyle={SELECTED_MENU_STYLE} label={f('source-language')}>
            {this.renderLangMenuItems('source-lang')}
          </Field>

          <Field name="targetLanguages" component={renderSelectField} selectedMenuItemStyle={SELECTED_MENU_STYLE}
            onChange={onTargetLanguagesChange} label={f('target-language')} multiple>
            {this.renderLangMenuItems('target-lang')}
          </Field>

          <Field name="contentFields" component={renderSelectField}
            selectedMenuItemStyle={SELECTED_MENU_STYLE} label={f('content-fields')} multiple fullWidth>
            {this.renderContentFields()}
          </Field>

          <Field name="source" component={renderTextField} label={f('source')} />

          <RaisedButton primary type="submit" label={f('update')} />

      </form>
    );
  }
}
<|endoftext|>


<commit_before>import test from 'ava';
import { createStore, combineReducers, compose, applyMiddleware } from 'redux';

import 'babel-core/register';

import routerReducer from 'redux-router-kit/src/reducer';
import createRouterMiddleware from 'redux-router-kit/src/middleware/createRouterMiddleware';
import { routeTo } from 'redux-router-kit/src/Actions';
import findRoutes from 'redux-router-kit/src/utils/findRoutes';

const reducer = combineReducers({
  router: routerReducer
});

const routes = ({
  '/': {
    name: 'home'
  },
  '/todos': {
    name: 'todos',
    assign() {
      return {
        isTodosRoute: true
      };
    },
    routes: {
      ':id': {
        name: 'todo'
      }
    }
  },
  '/one': {
    name: 'one'
  },
  '/two': {
    name: 'two'
  },
  '/three': {
    name: 'three'
  }
});

const createStoreWithMiddleware = compose(
  applyMiddleware(
    createRouterMiddleware({routes})
  )
)(createStore);

test('dispatch routeTo', t => {
  const store = createStoreWithMiddleware(reducer);
  const result = store.dispatch(routeTo('/todos'));
  let router = store.getState().router;
  t.is(router.next.url, '/todos');
  t.is(router.current, null);
  return result
    .then(() => {
      router = store.getState().router;
      t.is(router.current.url, '/todos');
      const routeList = findRoutes(routes, router.current.routeKey);
      t.is(routeList[0].name, 'todos');
      t.true(router.current.isTodosRoute);
    });
});

// test('dispatch routeTo for nested route', t => {
//   const store = createStoreWithMiddleware(reducer);
//   store.dispatch(routeTo('/todos/123'))
//     .then(() => {
//       const router = store.getState().router;
//       t.is(router.current.url, '/todos/123');
//       t.same(router.current.params, {id: '123'});
//       const routeList = findRoutes(routes, router.current.routeKey);
//       t.is(routeList[0].name, 'todos');
//       t.is(routeList[1].name, 'todo');
//     });
// });

test('dispatch routeTo with state', t => {
  const store = createStoreWithMiddleware(reducer);
  const result = store.dispatch(routeTo('/todos', {
    state: {count: 100}
  }));
  let router = store.getState().router;
  t.is(router.next.url, '/todos');
  t.same(router.next.state, {count: 100});
  t.is(router.current, null);
  return result
    .then(() => {
      router = store.getState().router;
      t.is(router.current.url, '/todos');
      t.same(router.current.state, {count: 100});
    });
});

test('dispatch to same as current url should be no-op', t => {
  const store = createStoreWithMiddleware(reducer);
  return store.dispatch(routeTo('/todos'))
    .then(() => {
      return store.dispatch(routeTo('/todos'));
    })
    .then(() => {
      const router = store.getState().router;
      t.is(router.previous, null);
    });
});

test('dispatch with right-click should be no-op', t => {
  const store = createStoreWithMiddleware(reducer);
  return Promise.resolve(
    store.dispatch(
      routeTo('/todos', {
        event: {
          button: 2
        }
      })
    )
  )
    .then(() => {
      const router = store.getState().router;
      t.is(router.current, null);
    });
});

test('dispatch with meta-click should be no-op', t => {
  const store = createStoreWithMiddleware(reducer);
  return Promise.resolve(
    store.dispatch(
      routeTo('/todos', {
        event: {
          metaKey: true
        }
      })
    )
  )
    .then(() => {
      const router = store.getState().router;
      t.is(router.current, null);
    });
});

test('dispatch to same as current url with new state should not be a no-op', t => {
  const store = createStoreWithMiddleware(reducer);
  return store.dispatch(routeTo('/todos', {
    state: {
      count: 100
    }
  }))
    .then(() => {
      return store.dispatch(routeTo('/todos', {
        state: {
          count: 200
        }
      }));
    })
    .then(() => {
      const router = store.getState().router;
      t.same(router.previous.state, {count: 100});
      t.same(router.current.state, {count: 200});
    });
});

test('dispatch to same as next url should be no-op', t => {
  const store = createStoreWithMiddleware(reducer);
  store.dispatch(routeTo('/todos'));
  let router = store.getState().router;
  const routeId = router.next._routeId;
  store.dispatch(routeTo('/todos'));
  router = store.getState().router;
  t.is(router.next._routeId, routeId);
});

test('allow overwriting route', t => {
  const store = createStoreWithMiddleware(reducer);
  return store.dispatch(routeTo('/one'))
    .then(() => {
      store.dispatch(routeTo('/two'));
      const newResult = store.dispatch(routeTo('/three'));
      return newResult;
    })
    .then(() => {
      const router = store.getState().router;
      t.is(router.next, null);
      t.is(router.current.url, '/three');
    });
});

test('allow overwriting route with previous', t => {
  const store = createStoreWithMiddleware(reducer);
  return store.dispatch(routeTo('/one'))
    .then(() => {
      store.dispatch(routeTo('/two'));
      const newResult = store.dispatch(routeTo('/one'));
      const router = store.getState().router;
      t.is(router.next, null);
      return newResult;
    })
    .then(() => {
      const router = store.getState().router;
      t.is(router.next, null);
      t.is(router.current.url, '/one');
    });
});

test('put exit in state and then exit', t => {
  const store = createStoreWithMiddleware(reducer);
  return Promise.resolve()
    .then(() => {
      const result = store.dispatch(routeTo('/one', { exit: true }));
      const { router } = store.getState();
      t.true(router.next.exit);
      return result;
    })
    .then(() => {
      const { router } = store.getState();
      t.is(router.next.url, '/one');
    });
});

test('modify next route with exit', t => {
  const store = createStoreWithMiddleware(reducer);
  (
    () => {
      store.dispatch(routeTo('/one'));
      const { router } = store.getState();
      t.false(!!router.next.exit);
    }
  )();
  (
    () => {
      store.dispatch(routeTo('/one', { exit: true }));
      const { router } = store.getState();
      t.true(router.next.exit);
    }
  )();
});

test('pick up in-flight promise', t => {
  const store = createStoreWithMiddleware(reducer);
  return Promise.resolve()
    .then(() => {
      store.dispatch(routeTo('/one'));
      return store.dispatch(routeTo('/one'));
    })
    .then(() => {
      const { router } = store.getState();
      t.is(router.current.url, '/one');
    });
});
<commit_msg>onEnter/onLeave test<commit_after>import test from 'ava';
import { createStore, combineReducers, compose, applyMiddleware } from 'redux';
import sinon from 'sinon';

import 'babel-core/register';

import routerReducer from 'redux-router-kit/src/reducer';
import createRouterMiddleware from 'redux-router-kit/src/middleware/createRouterMiddleware';
import { routeTo } from 'redux-router-kit/src/Actions';
import findRoutes from 'redux-router-kit/src/utils/findRoutes';

const reducer = combineReducers({
  router: routerReducer
});

const routes = ({
  '/': {
    name: 'home'
  },
  '/todos': {
    name: 'todos',
    assign() {
      return {
        isTodosRoute: true
      };
    },
    routes: {
      ':id': {
        name: 'todo'
      }
    }
  },
  '/one': {
    name: 'one'
  },
  '/two': {
    name: 'two'
  },
  '/three': {
    name: 'three'
  }
});

const createStoreWithMiddleware = compose(
  applyMiddleware(
    createRouterMiddleware({routes})
  )
)(createStore);

test('dispatch routeTo', t => {
  const store = createStoreWithMiddleware(reducer);
  const result = store.dispatch(routeTo('/todos'));
  let router = store.getState().router;
  t.is(router.next.url, '/todos');
  t.is(router.current, null);
  return result
    .then(() => {
      router = store.getState().router;
      t.is(router.current.url, '/todos');
      const routeList = findRoutes(routes, router.current.routeKey);
      t.is(routeList[0].name, 'todos');
      t.true(router.current.isTodosRoute);
    });
});

// test('dispatch routeTo for nested route', t => {
//   const store = createStoreWithMiddleware(reducer);
//   store.dispatch(routeTo('/todos/123'))
//     .then(() => {
//       const router = store.getState().router;
//       t.is(router.current.url, '/todos/123');
//       t.same(router.current.params, {id: '123'});
//       const routeList = findRoutes(routes, router.current.routeKey);
//       t.is(routeList[0].name, 'todos');
//       t.is(routeList[1].name, 'todo');
//     });
// });

test('dispatch routeTo with state', t => {
  const store = createStoreWithMiddleware(reducer);
  const result = store.dispatch(routeTo('/todos', {
    state: {count: 100}
  }));
  let router = store.getState().router;
  t.is(router.next.url, '/todos');
  t.same(router.next.state, {count: 100});
  t.is(router.current, null);
  return result
    .then(() => {
      router = store.getState().router;
      t.is(router.current.url, '/todos');
      t.same(router.current.state, {count: 100});
    });
});

test('dispatch to same as current url should be no-op', t => {
  const store = createStoreWithMiddleware(reducer);
  return store.dispatch(routeTo('/todos'))
    .then(() => {
      return store.dispatch(routeTo('/todos'));
    })
    .then(() => {
      const router = store.getState().router;
      t.is(router.previous, null);
    });
});

test('dispatch with right-click should be no-op', t => {
  const store = createStoreWithMiddleware(reducer);
  return Promise.resolve(
    store.dispatch(
      routeTo('/todos', {
        event: {
          button: 2
        }
      })
    )
  )
    .then(() => {
      const router = store.getState().router;
      t.is(router.current, null);
    });
});

test('dispatch with meta-click should be no-op', t => {
  const store = createStoreWithMiddleware(reducer);
  return Promise.resolve(
    store.dispatch(
      routeTo('/todos', {
        event: {
          metaKey: true
        }
      })
    )
  )
    .then(() => {
      const router = store.getState().router;
      t.is(router.current, null);
    });
});

test('dispatch to same as current url with new state should not be a no-op', t => {
  const store = createStoreWithMiddleware(reducer);
  return store.dispatch(routeTo('/todos', {
    state: {
      count: 100
    }
  }))
    .then(() => {
      return store.dispatch(routeTo('/todos', {
        state: {
          count: 200
        }
      }));
    })
    .then(() => {
      const router = store.getState().router;
      t.same(router.previous.state, {count: 100});
      t.same(router.current.state, {count: 200});
    });
});

test('dispatch to same as next url should be no-op', t => {
  const store = createStoreWithMiddleware(reducer);
  store.dispatch(routeTo('/todos'));
  let router = store.getState().router;
  const routeId = router.next._routeId;
  store.dispatch(routeTo('/todos'));
  router = store.getState().router;
  t.is(router.next._routeId, routeId);
});

test('allow overwriting route', t => {
  const store = createStoreWithMiddleware(reducer);
  return store.dispatch(routeTo('/one'))
    .then(() => {
      store.dispatch(routeTo('/two'));
      const newResult = store.dispatch(routeTo('/three'));
      return newResult;
    })
    .then(() => {
      const router = store.getState().router;
      t.is(router.next, null);
      t.is(router.current.url, '/three');
    });
});

test('allow overwriting route with previous', t => {
  const store = createStoreWithMiddleware(reducer);
  return store.dispatch(routeTo('/one'))
    .then(() => {
      store.dispatch(routeTo('/two'));
      const newResult = store.dispatch(routeTo('/one'));
      const router = store.getState().router;
      t.is(router.next, null);
      return newResult;
    })
    .then(() => {
      const router = store.getState().router;
      t.is(router.next, null);
      t.is(router.current.url, '/one');
    });
});

test('put exit in state and then exit', t => {
  const store = createStoreWithMiddleware(reducer);
  return Promise.resolve()
    .then(() => {
      const result = store.dispatch(routeTo('/one', { exit: true }));
      const { router } = store.getState();
      t.true(router.next.exit);
      return result;
    })
    .then(() => {
      const { router } = store.getState();
      t.is(router.next.url, '/one');
    });
});

test('modify next route with exit', t => {
  const store = createStoreWithMiddleware(reducer);
  (
    () => {
      store.dispatch(routeTo('/one'));
      const { router } = store.getState();
      t.false(!!router.next.exit);
    }
  )();
  (
    () => {
      store.dispatch(routeTo('/one', { exit: true }));
      const { router } = store.getState();
      t.true(router.next.exit);
    }
  )();
});

test('pick up in-flight promise', t => {
  const store = createStoreWithMiddleware(reducer);
  return Promise.resolve()
    .then(() => {
      store.dispatch(routeTo('/one'));
      return store.dispatch(routeTo('/one'));
    })
    .then(() => {
      const { router } = store.getState();
      t.is(router.current.url, '/one');
    });
});

test('call onEnter, onLeave', t => {
  const onEnterSpy = sinon.spy();
  const onLeaveSpy = sinon.spy();
  const store = createStore(reducer, applyMiddleware(
    createRouterMiddleware({
      routes: {
        '/one': {
          onEnter: onEnterSpy,
          onLeave: onLeaveSpy
        },
        '/two': {}
      }
    })
  ));
  return Promise.resolve()
    .then(() => {
      return store.dispatch(routeTo('/one'));
    })
    .then(() => {
      t.true(onEnterSpy.called);
      t.false(onLeaveSpy.called);
      return store.dispatch(routeTo('/two'));
    })
    .then(() => {
      t.true(onLeaveSpy.called);
    });
});
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import Link from '../Link';
import s from '../VehicleResults/VehicleResults.scss';
import CategorizedResult from '../VehicleResults/CategorizedResult';
import withStyles from '../../decorators/withStyles';
import LuverneStore from '../../stores/LuverneStore';
import CategoryStore from '../../stores/LvCategoryStore';
import connectToStores from 'alt-utils/lib/connectToStores';
// import VehicleStyle from './VehicleStyle';
import Envision from '../VehicleResults/Envision';
import Configurator from '../VehicleResults/Configurator';

@withStyles(s)
@connectToStores
class LuverneResults extends Component {

	static propTypes = {
		className: PropTypes.string,
		activeIndex: PropTypes.number,
		context: PropTypes.shape({
			params: PropTypes.shape({
				year: PropTypes.string,
				make: PropTypes.string,
				model: PropTypes.string,
			}),
			iconMediaVehicle: PropTypes.object,
			iconParts: PropTypes.oneOfType([
				React.PropTypes.object,
				React.PropTypes.array,
			]),
			vehicleParts: PropTypes.array,
		}),
		vehicle: PropTypes.shape({
			base_vehicle: PropTypes.shape({
				year: PropTypes.string,
				make: PropTypes.string,
				model: PropTypes.string,
			}),
			available_years: PropTypes.array,
			available_makes: PropTypes.array,
			available_models: PropTypes.array,
			lookup_category: PropTypes.array,
			products: PropTypes.array,
		}),
		categories: PropTypes.array,
		activeCategory: PropTypes.object,
		fitments: PropTypes.array,
		error: PropTypes.object,
		iconMediaVehicle: PropTypes.object,
		win: PropTypes.object,
	};

	static contextTypes = {
		onSetTitle: PropTypes.func.isRequired,
		onPageNotFound: PropTypes.func.isRequired,
		onSetMeta: PropTypes.func.isRequired,
		seo: PropTypes.func.isRequired,
	};

	constructor() {
		super();
		this.state = {
			context: {},
			activeKey: '0',
			activeCat: 0,
		};
		this.getMatched = this.getMatched.bind(this);
		this.createParentItem = this.createParentItem.bind(this);
	}

	componentWillMount() {
		const base = this.props.context ? this.props.context.params : {};
		let title = 'Vehicle Results';
		if (base.year && base.make && base.model) {
			title = `${base.year} ${base.make} ${base.model} Fitment Results`;
		}
		this.context.onSetTitle(title);
		this.context.onSetMeta('description', title);
		this.context.seo({
			title,
			description: 'ARIES Automotive parts for ' + title,
		});
	}

	static getStores() {
		return [LuverneStore, CategoryStore];
	}

	static getPropsFromStores() {
		return {
			...LuverneStore.getState(),
			...CategoryStore.getState(),
		};
	}

	getMatched() {
		if (
			!this.props.vehicle ||
			!this.props.vehicle.lookup_category ||
			this.props.vehicle.lookup_category.length === 0 ||
			!this.props.categories ||
			this.props.categories.length === 0
		) {
			return ;
		}

		const groups = [];
		const categoriesGroup = {
			children: [],
		};

		if (this.props.categories && this.props.categories.length > 0) {
			this.props.categories.sort((a, b) => a.sort > b.sort);
		}
		this.props.categories.map((cat) => {
			console.log(cat);
			const tmp = this.createParentItem(cat);
			categoriesGroup.children = categoriesGroup.children.concat(tmp);
		});

		categoriesGroup.children.map((c) => {
			if (!c.children || !c.children.length === 0) {
				return;
			}

			let subs = [];
			(c.children || []).map((cat) => {
				const tmp = this.props.vehicle.lookup_category.filter((t) => t.category.id === cat.cat.id);
				if (tmp.length > 0) {
					subs = subs.concat(tmp);
				}
			});
			if (subs.length > 0) {
				groups.push(
					<CategorizedResult
						activeIndex={this.props.activeIndex}
						parent={c}
						subs={subs}
						fitments={this.props.fitments}
						key={groups.length}
						iconParts={this.props.context.iconParts}
					/>
				);
			}
		});

		return groups;
	}

	createParentItem(cat) {
		if (cat.children && cat.children.length > 0) {
			cat.children.sort((a, b) => a.sort > b.sort);
		}
		const newCat = {
			cat,
			title: cat.title,
			children: cat.children.map(this.createParentItem),
		};

		return newCat;
	}

	render() {
		const matched = this.getMatched();
		return (

<Link to="/" title="Home">Home</Link>

Vehicle Look Up Results

VEHICLE LOOK UP RESULTS

Choose a category below to see the products that fit your vehicle.
						Some products may require the style of the vehicle to be specified.

					{this.props.context.vehicleParts ? <Configurator win={this.props.win} className={s.configurator} context={this.props.context} /> : null}
					{this.props.context.vehicleParts ? <Envision className={s.envision} /> : null}

					{matched}

		);
	}

}

export default LuverneResults;
<commit_msg>Adding stuff for envision/parts<commit_after>import React, { Component, PropTypes } from 'react';
import Link from '../Link';
import s from '../VehicleResults/VehicleResults.scss';
import CategorizedResult from '../VehicleResults/CategorizedResult';
import withStyles from '../../decorators/withStyles';
import LuverneStore from '../../stores/LuverneStore';
import CategoryStore from '../../stores/LvCategoryStore';
import connectToStores from 'alt-utils/lib/connectToStores';
// import VehicleStyle from './VehicleStyle';
import Envision from './Envision';
import Configurator from '../VehicleResults/Configurator';

@withStyles(s)
@connectToStores
class LuverneResults extends Component {

	static propTypes = {
		className: PropTypes.string,
		activeIndex: PropTypes.number,
		context: PropTypes.shape({
			params: PropTypes.shape({
				year: PropTypes.string,
				make: PropTypes.string,
				model: PropTypes.string,
			}),
			iconMediaVehicle: PropTypes.object,
			iconParts: PropTypes.oneOfType([
				React.PropTypes.object,
				React.PropTypes.array,
			]),
			vehicleParts: PropTypes.array,
		}),
		vehicle: PropTypes.shape({
			base_vehicle: PropTypes.shape({
				year: PropTypes.string,
				make: PropTypes.string,
				model: PropTypes.string,
			}),
			available_years: PropTypes.array,
			available_makes: PropTypes.array,
			available_models: PropTypes.array,
			lookup_category: PropTypes.array,
			products: PropTypes.array,
		}),
		categories: PropTypes.array,
		activeCategory: PropTypes.object,
		fitments: PropTypes.array,
		error: PropTypes.object,
		iconMediaVehicle: PropTypes.object,
		win: PropTypes.object,
	};

	static contextTypes = {
		onSetTitle: PropTypes.func.isRequired,
		onPageNotFound: PropTypes.func.isRequired,
		onSetMeta: PropTypes.func.isRequired,
		seo: PropTypes.func.isRequired,
	};

	constructor() {
		super();
		this.state = {
			context: {},
			activeKey: '0',
			activeCat: 0,
		};
		this.getMatched = this.getMatched.bind(this);
		this.createParentItem = this.createParentItem.bind(this);
	}

	componentWillMount() {
		const base = this.props.context ? this.props.context.params : {};
		let title = 'Vehicle Results';
		if (base.year && base.make && base.model) {
			title = `${base.year} ${base.make} ${base.model} Fitment Results`;
		}
		this.context.onSetTitle(title);
		this.context.onSetMeta('description', title);
		this.context.seo({
			title,
			description: 'ARIES Automotive parts for ' + title,
		});
	}

	static getStores() {
		return [LuverneStore, CategoryStore];
	}

	static getPropsFromStores() {
		return {
			...LuverneStore.getState(),
			...CategoryStore.getState(),
		};
	}

	getMatched() {
		if (
			!this.props.vehicle ||
			!this.props.vehicle.lookup_category ||
			this.props.vehicle.lookup_category.length === 0 ||
			!this.props.categories ||
			this.props.categories.length === 0
		) {
			return ;
		}

		const groups = [];
		const categoriesGroup = {
			children: [],
		};

		if (this.props.categories && this.props.categories.length > 0) {
			this.props.categories.sort((a, b) => a.sort > b.sort);
		}
		this.props.categories.map((cat) => {
			const tmp = this.createParentItem(cat);
			categoriesGroup.children = categoriesGroup.children.concat(tmp);
		});

		categoriesGroup.children.map((c) => {
			if (!c.children || !c.children.length === 0) {
				return;
			}

			let subs = [];
			(c.children || []).map((cat) => {
				const tmp = this.props.vehicle.lookup_category.filter((t) => t.category.id === cat.cat.id);
				if (tmp.length > 0) {
					subs = subs.concat(tmp);
				}
			});
			if (subs.length > 0) {
				groups.push(
					<CategorizedResult
						activeIndex={this.props.activeIndex}
						parent={c}
						subs={subs}
						fitments={this.props.fitments}
						key={groups.length}
						iconParts={this.props.context.iconParts}
					/>
				);
			}
		});

		return groups;
	}

	createParentItem(cat) {
		if (cat.children && cat.children.length > 0) {
			cat.children.sort((a, b) => a.sort > b.sort);
		}
		const newCat = {
			cat,
			title: cat.title,
			children: cat.children.map(this.createParentItem),
		};

		return newCat;
	}

	render() {
		const matched = this.getMatched();
		return (

<Link to="/" title="Home">Home</Link>

Vehicle Look Up Results

VEHICLE LOOK UP RESULTS

Choose a category below to see the products that fit your vehicle.
						Some products may require the style of the vehicle to be specified.

					{this.props.context.vehicleParts ? <Configurator win={this.props.win} className={s.configurator} context={this.props.context} /> : null}
					{this.props.context.vehicleParts ? <Envision className={s.envision} /> : null}

					{matched}

		);
	}

}

export default LuverneResults;
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Button, Modal, Media, Label, Badge } from 'react-bootstrap';
import moment from 'moment';
import RegOpzDataGridHeader from './RegOpzDataGridHeader';
import RegOpzDataGridSideMarker from './RegOpzGridSideMarker';
import RegOpzDataGridHorizontalLines from './RegOpzDataGridHorizontalLines';
import RegOpzDataGridVerticalLines from './RegOpzDataGridVerticalLines';
import RegOpzDataGridBody from './RegOpzDataGridBody';
import { connect } from 'react-redux';
import { bindActionCreators, dispatch } from 'redux';
import {
  actionFetchReportData,
  actionDrillDown
} from '../../actions/CaptureReportAction';
import {actionFetchAuditList} from '../../actions/DefChangeAction';
import { hashHistory, routerContext } from 'react-router';
import Breadcrumbs from 'react-breadcrumbs';
import {BASE_URL} from '../../Constant/constant';
import axios from 'axios';
require('./RegOpzDataGrid.css');

class RegOpzDataGrid extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isModalOpen:false
    };
    this.numberofCols = 52;
    this.numberofRows = 1000;
    this.data = [];
    this.selectedSheet = 0;
    this.report_id = this.props.location.query['report_id'];
    this.reporting_date = this.props.location.query['reporting_date'];
    this.cell_format_yn = 'Y';
    this.selectedCell = null;
    this.selectedSheetName = null;
    this.gridHight = 0;
    this.gridWidth = 0;
    this.rulesIdAsSubQuery = "";
    this.linkageData = null;
  }

  componentWillMount() {
    this.props.fetchCapturedReport(this.report_id,this.reporting_date);
  }

  alphaSequence(i) {
      return i < 0
          ? ""
          : this.alphaSequence((i / 26) - 1) + String.fromCharCode((65 + i % 26) + "");
  }

  render(){
    if (this.props.captured_report.length > 0) {
      this.data = this.props.captured_report[this.selectedSheet].matrix;
      this.selectedSheetName = this.props.captured_report[this.selectedSheet]['sheet'];
      let row_attr = this.props.captured_report[this.selectedSheet].row_attr;
      let col_attr = this.props.captured_report[this.selectedSheet].col_attr;
      console.log('no of rows...', row_attr, row_attr.length);
      this.numberofRows = Object.keys(row_attr).length;
      this.numberofCols = Object.keys(col_attr).length;
      this.gridHight = 0;
      this.gridWidth = 0;
      [... Array(parseInt(this.numberofRows))].map(function(item,index){
          //var stylex = {};
          if(typeof(row_attr[(index+1)+""]) != 'undefined') {
            this.gridHight += parseInt(row_attr[(index+1)+""].height) * 2;
          }
      }.bind(this));
      [... Array(parseInt(this.numberofCols))].map(function(item,index){
          //var stylex = {};
          if(typeof(col_attr[this.alphaSequence(index)]) != 'undefined'){
            this.gridWidth += parseInt(col_attr[this.alphaSequence(index)]['width']) * 9 + 1;
          }
      }.bind(this));
      console.log('grid hight',this.gridHight);
      if( typeof this.props.audit_list != 'undefined' && this.props.audit_list.length ){
        this.linkageData = this.props.audit_list;
      }
      return(

            <Breadcrumbs
              routes={this.props.routes}
              params={this.props.params}
              wrapperClass="breadcrumb"
            />

                      <button
                        data-toggle="tooltip"
                        data-placement="top"
                        title="Drill Down"
                        onClick={
                          (event) => {
                            hashHistory.push(`/dashboard/drill-down?report_id=${this.report_id}&sheet=${encodeURI(this.props.captured_report[this.selectedSheet].sheet)}&cell=${this.selectedCell}&reporting_date=${this.reporting_date}`);
                          }
                        }
                        className="btn btn-circle btn-primary business_rules_ops_buttons btn-xs"
                      >

                      </button>

                      <button
                        data-toggle="tooltip"
                        data-placement="top"
                        title="Export xlsx"
                        className="btn btn-circle btn-success business_rules_ops_buttons btn-xs"
                        onClick={
                          (event) => {
                              const url = BASE_URL + `document/get-report-export-to-excel?`
                                        + `report_id=${this.report_id}`
                                        + `&reporting_date=${this.reporting_date}`
                                        + `&cell_format_yn=${this.cell_format_yn}`;
                              axios.get(url)
                              .then(function(response){
                                console.log("export xlsx",response);
                                window.location.href = BASE_URL + "../../static/" + response.data.file_name;

                              })
                              .catch(function (error) {
                                console.log(error);
                              });
                          }
                        }
                      >

                      </button>

                      <button
                        data-toggle="tooltip"
                        data-placement="top"
                        title="Export Report Rules"
                        className="btn btn-circle btn-info business_rules_ops_buttons btn-xs"
                        onClick={
                          (event) => {
                              const url = BASE_URL + `document/get-report-rule-export-to-excel?`
                                        + `report_id=${this.report_id}`;
                              axios.get(url)
                              .then(function(response){
                                console.log("export xlsx",response);
                                window.location.href = BASE_URL + "../../static/" + response.data.file_name;

                              })
                              .catch(function (error) {
                                console.log(error);
                              });
                          }
                        }
                      >

                      </button>

                      <button
                        data-toggle="tooltip"
                        data-placement="top"
                        title="Report Rules History"
                        className="btn btn-circle btn-primary business_rules_ops_buttons btn-xs"
                        onClick={ this.showHistory.bind(this)}
                      >

                      </button>

                    <button className="btn btn-success btn-sm">Showing  {this.selectedSheetName}</button>
                    {
                      this.props.captured_report.map((item,index) => {
                        return(
                          <button
                            key={index}
                            target={index}
                            type="button"
                            className="btn btn-warning btn-xs"
                            onClick={(event) => {
                              this.selectedSheet = event.target.getAttribute("target");
                              this.forceUpdate();
                            }}
                          >
                            {item['sheet']}
                          </button>
                        )
                      })
                    }

          <RegOpzDataGridHeader
            numberofCols={this.numberofCols}
            colAttr={this.props.captured_report[this.selectedSheet].col_attr}
          />

          <RegOpzDataGridSideMarker
            numberofRows={this.numberofRows}
            rowAttr={this.props.captured_report[this.selectedSheet].row_attr}
          />

              <RegOpzDataGridHorizontalLines
                numberofRows={this.numberofRows}
                height={this.gridHight}
                width={this.gridWidth}
                rowAttr={this.props.captured_report[this.selectedSheet].row_attr}
              />
              <RegOpzDataGridVerticalLines
                numberofCols={this.numberofCols}
                height={this.gridHight}
                width={this.gridWidth}
                colAttr={this.props.captured_report[this.selectedSheet].col_attr}
              />
              <RegOpzDataGridBody
                data={this.data}
                colAttr={this.props.captured_report[this.selectedSheet].col_attr}
                rowAttr={this.props.captured_report[this.selectedSheet].row_attr}
                onSelect = {
                  (item) => {
                    this.selectedCell = item;
                    console.log("On select",item);
                  }
                }
              />

        <Modal
          show={this.state.isModalOpen}
          container={this}
          onHide={(event) => {
              this.setState({isModalOpen:false});
            }}
        >
          <Modal.Header closeButton>
            <Modal.Title>Report Rule Change History for
{this.report_id}
</Modal.Title>
          </Modal.Header>

          <Modal.Body>
            { this.renderChangeHistory(this.linkageData) }
          </Modal.Body>

          <Modal.Footer>
            <Button onClick={(event) => {
                this.setState({isModalOpen:false})
              }}>Ok</Button>
          </Modal.Footer>
        </Modal>

      )
    } else {
      return(

Loading...

      )
    }
  }

  renderBreadCrumb() {
    console.log('reporting_date', this.reporting_date);
    if (this.reporting_date == undefined || this.reporting_date == 'undefined') {
      return(

Maintain Report Rules

{`${this.report_id} (Manage Report Rules)`}

      )
    } else {
      return(

View Report

{`${this.report_id} (${this.reporting_date})`}

      )
    }
  }

  renderChangeHistory(linkageData){
    if(!linkageData || typeof(linkageData) == 'undefined' || linkageData == null || linkageData.length == 0)
      return(

No audit change report found!

      )
    else {
      return(

          {
            linkageData.map(function(item,index){
              return(

                        <Media>
                          <Media.Left>

{moment(item.date_of_change?item.date_of_change:"20170624T203000").format('DD')}

{moment(item.date_of_change?item.date_of_change:"20170624").format('MMM')},
                            {moment(item.date_of_change?item.date_of_change:"20170624").format('YYYY')}

                          </Media.Left>
                          <Media.Body>
                            <Media.Heading>Buisness Rule Change for id: {item.id}

                                {item.change_reference}

                            </Media.Heading>

<Badge>{item.change_type}</Badge> by {item.maker} on {item.date_of_change}

{item.maker_comment}

Change Summary

                                  {((item)=>{
                                      if (item.change_type=="UPDATE"){
                                          console.log("Update Info........",item.update_info);
                                          const update_list=item.update_info.map((uitem,uindex)=>{
                                              console.log("Uitem.....",uitem);
                                              return (

                                                        {uindex + 1}

{uitem.field_name}

                                                        {uitem.new_val}
                                                        {uitem.old_val}

                                                   );
                                          });
                                          return(

                                                  #
                                                  Column
                                                  New Value
                                                  Old Value

                                                {update_list}

                                          );
                                      } else {
                                        return (

This is a {item.change_type} request

                                            )
                                      }
                                  })(item)}

                              <Media>
                                <Media.Left>
                                  {
                                    ((status)=>{
                                      if(status=="PENDING"){
                                        return({status})
                                      } else if (status=="REJECTED"){
                                        return({status})
                                      } else if(status=="APPROVED"){
                                        return({status})
                                      } else {
                                        return({status})
                                      }
                                    }
                                  )(item.status)}
                                </Media.Left>
                                <Media.Body>
                                  <Media.Heading>Verification details</Media.Heading>
                                    {
                                      ((status)=>{
                                        if(status!="PENDING"){
                                          return(
by {item.checker} on {item.date_of_change}
)
                                        }
                                      }
                                    )(item.status)}

{item.checker_comment}

                                </Media.Body>
                              </Media>
                          </Media.Body>
                        </Media>

              )
            })
          }

      )
    }
  }
  showHistory(event){
    this.rulesIdAsSubQuery = `select id from report_calc_def where report_id= '${this.report_id}'`;
    this.props.fetchAuditList(this.rulesIdAsSubQuery,"report_calc_def");
    this.setState({isModalOpen:true})
  }
}

function mapStateToProps(state) {
  return {
    captured_report:state.captured_report,
    audit_list:state.def_change_store.audit_list
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    fetchCapturedReport:(report_id, reporting_date) => {
      dispatch(actionFetchReportData(report_id, reporting_date));
    },
    drillDown:(report_id, sheet_id, cell_id) => {
      dispatch(actionDrillDown(report_id, sheet_id, cell_id));
    },
    fetchAuditList:(idList,tableName)=>{
      dispatch(actionFetchAuditList(idList,tableName));
    }
  }
}

const VisibleRegOpzDataGrid = connect(
  mapStateToProps,
  mapDispatchToProps
)(RegOpzDataGrid);

export default VisibleRegOpzDataGrid;
<commit_msg>Minor fix for table-content-wrap<commit_after>import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Button, Modal, Media, Label, Badge } from 'react-bootstrap';
import moment from 'moment';
import RegOpzDataGridHeader from './RegOpzDataGridHeader';
import RegOpzDataGridSideMarker from './RegOpzGridSideMarker';
import RegOpzDataGridHorizontalLines from './RegOpzDataGridHorizontalLines';
import RegOpzDataGridVerticalLines from './RegOpzDataGridVerticalLines';
import RegOpzDataGridBody from './RegOpzDataGridBody';
import { connect } from 'react-redux';
import { bindActionCreators, dispatch } from 'redux';
import {
  actionFetchReportData,
  actionDrillDown
} from '../../actions/CaptureReportAction';
import {actionFetchAuditList} from '../../actions/DefChangeAction';
import { hashHistory, routerContext } from 'react-router';
import Breadcrumbs from 'react-breadcrumbs';
import {BASE_URL} from '../../Constant/constant';
import axios from 'axios';
require('./RegOpzDataGrid.css');

class RegOpzDataGrid extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isModalOpen:false
    };
    this.numberofCols = 52;
    this.numberofRows = 1000;
    this.data = [];
    this.selectedSheet = 0;
    this.report_id = this.props.location.query['report_id'];
    this.reporting_date = this.props.location.query['reporting_date'];
    this.cell_format_yn = 'Y';
    this.selectedCell = null;
    this.selectedSheetName = null;
    this.gridHight = 0;
    this.gridWidth = 0;
    this.rulesIdAsSubQuery = "";
    this.linkageData = null;
  }

  componentWillMount() {
    this.props.fetchCapturedReport(this.report_id,this.reporting_date);
  }

  alphaSequence(i) {
      return i < 0
          ? ""
          : this.alphaSequence((i / 26) - 1) + String.fromCharCode((65 + i % 26) + "");
  }

  render(){
    if (this.props.captured_report.length > 0) {
      this.data = this.props.captured_report[this.selectedSheet].matrix;
      this.selectedSheetName = this.props.captured_report[this.selectedSheet]['sheet'];
      let row_attr = this.props.captured_report[this.selectedSheet].row_attr;
      let col_attr = this.props.captured_report[this.selectedSheet].col_attr;
      console.log('no of rows...', row_attr, row_attr.length);
      this.numberofRows = Object.keys(row_attr).length;
      this.numberofCols = Object.keys(col_attr).length;
      this.gridHight = 0;
      this.gridWidth = 0;
      [... Array(parseInt(this.numberofRows))].map(function(item,index){
          //var stylex = {};
          if(typeof(row_attr[(index+1)+""]) != 'undefined') {
            this.gridHight += parseInt(row_attr[(index+1)+""].height) * 2;
          }
      }.bind(this));
      [... Array(parseInt(this.numberofCols))].map(function(item,index){
          //var stylex = {};
          if(typeof(col_attr[this.alphaSequence(index)]) != 'undefined'){
            this.gridWidth += parseInt(col_attr[this.alphaSequence(index)]['width']) * 9 + 1;
          }
      }.bind(this));
      console.log('grid hight',this.gridHight);
      if( typeof this.props.audit_list != 'undefined' && this.props.audit_list.length ){
        this.linkageData = this.props.audit_list;
      }
      return(

            <Breadcrumbs
              routes={this.props.routes}
              params={this.props.params}
              wrapperClass="breadcrumb"
            />

                      <button
                        data-toggle="tooltip"
                        data-placement="top"
                        title="Drill Down"
                        onClick={
                          (event) => {
                            hashHistory.push(`/dashboard/drill-down?report_id=${this.report_id}&sheet=${encodeURI(this.props.captured_report[this.selectedSheet].sheet)}&cell=${this.selectedCell}&reporting_date=${this.reporting_date}`);
                          }
                        }
                        className="btn btn-circle btn-primary business_rules_ops_buttons btn-xs"
                      >

                      </button>

                      <button
                        data-toggle="tooltip"
                        data-placement="top"
                        title="Export xlsx"
                        className="btn btn-circle btn-success business_rules_ops_buttons btn-xs"
                        onClick={
                          (event) => {
                              const url = BASE_URL + `document/get-report-export-to-excel?`
                                        + `report_id=${this.report_id}`
                                        + `&reporting_date=${this.reporting_date}`
                                        + `&cell_format_yn=${this.cell_format_yn}`;
                              axios.get(url)
                              .then(function(response){
                                console.log("export xlsx",response);
                                window.location.href = BASE_URL + "../../static/" + response.data.file_name;

                              })
                              .catch(function (error) {
                                console.log(error);
                              });
                          }
                        }
                      >

                      </button>

                      <button
                        data-toggle="tooltip"
                        data-placement="top"
                        title="Export Report Rules"
                        className="btn btn-circle btn-info business_rules_ops_buttons btn-xs"
                        onClick={
                          (event) => {
                              const url = BASE_URL + `document/get-report-rule-export-to-excel?`
                                        + `report_id=${this.report_id}`;
                              axios.get(url)
                              .then(function(response){
                                console.log("export xlsx",response);
                                window.location.href = BASE_URL + "../../static/" + response.data.file_name;

                              })
                              .catch(function (error) {
                                console.log(error);
                              });
                          }
                        }
                      >

                      </button>

                      <button
                        data-toggle="tooltip"
                        data-placement="top"
                        title="Report Rules History"
                        className="btn btn-circle btn-primary business_rules_ops_buttons btn-xs"
                        onClick={ this.showHistory.bind(this)}
                      >

                      </button>

                    <button className="btn btn-success btn-sm">Showing  {this.selectedSheetName}</button>
                    {
                      this.props.captured_report.map((item,index) => {
                        return(
                          <button
                            key={index}
                            target={index}
                            type="button"
                            className="btn btn-warning btn-xs"
                            onClick={(event) => {
                              this.selectedSheet = event.target.getAttribute("target");
                              this.forceUpdate();
                            }}
                          >
                            {item['sheet']}
                          </button>
                        )
                      })
                    }

          <RegOpzDataGridHeader
            numberofCols={this.numberofCols}
            colAttr={this.props.captured_report[this.selectedSheet].col_attr}
          />

          <RegOpzDataGridSideMarker
            numberofRows={this.numberofRows}
            rowAttr={this.props.captured_report[this.selectedSheet].row_attr}
          />

              <RegOpzDataGridHorizontalLines
                numberofRows={this.numberofRows}
                height={this.gridHight}
                width={this.gridWidth}
                rowAttr={this.props.captured_report[this.selectedSheet].row_attr}
              />
              <RegOpzDataGridVerticalLines
                numberofCols={this.numberofCols}
                height={this.gridHight}
                width={this.gridWidth}
                colAttr={this.props.captured_report[this.selectedSheet].col_attr}
              />
              <RegOpzDataGridBody
                data={this.data}
                colAttr={this.props.captured_report[this.selectedSheet].col_attr}
                rowAttr={this.props.captured_report[this.selectedSheet].row_attr}
                onSelect = {
                  (item) => {
                    this.selectedCell = item;
                    console.log("On select",item);
                  }
                }
              />

        <Modal
          show={this.state.isModalOpen}
          container={this}
          onHide={(event) => {
              this.setState({isModalOpen:false});
            }}
        >
          <Modal.Header closeButton>
            <Modal.Title>Report Rule Change History for
{this.report_id}
</Modal.Title>
          </Modal.Header>

          <Modal.Body>
            { this.renderChangeHistory(this.linkageData) }
          </Modal.Body>

          <Modal.Footer>
            <Button onClick={(event) => {
                this.setState({isModalOpen:false})
              }}>Ok</Button>
          </Modal.Footer>
        </Modal>

      )
    } else {
      return(

Loading...

      )
    }
  }

  renderBreadCrumb() {
    console.log('reporting_date', this.reporting_date);
    if (this.reporting_date == undefined || this.reporting_date == 'undefined') {
      return(

Maintain Report Rules

{`${this.report_id} (Manage Report Rules)`}

      )
    } else {
      return(

View Report

{`${this.report_id} (${this.reporting_date})`}

      )
    }
  }

  renderChangeHistory(linkageData){
    if(!linkageData || typeof(linkageData) == 'undefined' || linkageData == null || linkageData.length == 0)
      return(

No audit change report found!

      )
    else {
      return(

          {
            linkageData.map(function(item,index){
              return(

                        <Media>
                          <Media.Left>

{moment(item.date_of_change?item.date_of_change:"20170624T203000").format('DD')}

{moment(item.date_of_change?item.date_of_change:"20170624").format('MMM')},
                            {moment(item.date_of_change?item.date_of_change:"20170624").format('YYYY')}

                          </Media.Left>
                          <Media.Body>
                            <Media.Heading>Buisness Rule Change for id: {item.id}

                                {item.change_reference}

                            </Media.Heading>

<Badge>{item.change_type}</Badge> by {item.maker} on {item.date_of_change}

{item.maker_comment}

Change Summary

                                  {((item)=>{
                                      if (item.change_type=="UPDATE"){
                                          console.log("Update Info........",item.update_info);
                                          const update_list=item.update_info.map((uitem,uindex)=>{
                                              console.log("Uitem.....",uitem);
                                              return (

                                                        {uindex + 1}

{uitem.field_name}

                                                        {uitem.new_val}
                                                        {uitem.old_val}

                                                   );
                                          });
                                          return(

                                                  #
                                                  Column
                                                  New Value
                                                  Old Value

                                                {update_list}

                                          );
                                      } else {
                                        return (

This is a {item.change_type} request

                                            )
                                      }
                                  })(item)}

                              <Media>
                                <Media.Left>
                                  {
                                    ((status)=>{
                                      if(status=="PENDING"){
                                        return({status})
                                      } else if (status=="REJECTED"){
                                        return({status})
                                      } else if(status=="APPROVED"){
                                        return({status})
                                      } else {
                                        return({status})
                                      }
                                    }
                                  )(item.status)}
                                </Media.Left>
                                <Media.Body>
                                  <Media.Heading>Verification details</Media.Heading>
                                    {
                                      ((status)=>{
                                        if(status!="PENDING"){
                                          return(
by {item.checker} on {item.date_of_change}
)
                                        }
                                      }
                                    )(item.status)}

{item.checker_comment}

                                </Media.Body>
                              </Media>
                          </Media.Body>
                        </Media>

              )
            })
          }

      )
    }
  }
  showHistory(event){
    this.rulesIdAsSubQuery = `select id from report_calc_def where report_id= '${this.report_id}'`;
    this.props.fetchAuditList(this.rulesIdAsSubQuery,"report_calc_def");
    this.setState({isModalOpen:true})
  }
}

function mapStateToProps(state) {
  return {
    captured_report:state.captured_report,
    audit_list:state.def_change_store.audit_list
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    fetchCapturedReport:(report_id, reporting_date) => {
      dispatch(actionFetchReportData(report_id, reporting_date));
    },
    drillDown:(report_id, sheet_id, cell_id) => {
      dispatch(actionDrillDown(report_id, sheet_id, cell_id));
    },
    fetchAuditList:(idList,tableName)=>{
      dispatch(actionFetchAuditList(idList,tableName));
    }
  }
}

const VisibleRegOpzDataGrid = connect(
  mapStateToProps,
  mapDispatchToProps
)(RegOpzDataGrid);

export default VisibleRegOpzDataGrid;
<|endoftext|>


<commit_before>var expect = require('expect.js');
var Xikitita = require('../../app/models/xikitita.js');

describe('Error', function() {

  it('#toJson', function () {
    var error = new Xikitita.Error();

    expect(error.toJson).to.be('{}');
  });

  it('#asJson', function () {
    var error = new Xikitita.Error();

    expect(error.asJson).to.be.a(Object);
  });

  it('#isAny', function () {
    var error = new Xikitita.Error();

    expect(error.isAny).to.be(false);
    error.x = [];
    expect(error.isAny).to.be(true);
  });

  it('#isEmpty', function () {
    var error = new Xikitita.Error();

    expect(error.isEmpty).to.be(true);
    error.x = [];
    expect(error.isEmpty).to.be(false);
  });

  it('#add', function(){
    var error = new Xikitita.Error();

    error.add('attrName1', 'message1');
    expect(error.attrName1).to.be.a(Array);
    expect(error['attrName1']).to.be.a(Array);

    error.add('attrName1', 'message2');
    error.add('attrName2', 'message1');
    expect(error.toJson).to.be('{"attrName1":["message1","message2"],"attrName2":["message1"]}');
  });

  it('#clear', function () {
    var error = new Xikitita.Error();

    error.x = [];
    error.clear;
    expect(error.isEmpty).to.be(true);
  });

});<commit_msg>Error<commit_after>var expect = require('expect.js');
var Xikitita = require('../../app/models/xikitita.js');

describe('Error', function() {

  it('#toJson', function () {
    var error = new Xikitita.Error();

    expect(error.toJson).to.be('{}');
  });

  it('#asJson', function () {
    var error = new Xikitita.Error();

    expect(error.asJson).to.be.a(Object);
  });

  it('#isAny', function () {
    var error = new Xikitita.Error();

    expect(error.isAny).to.be(false);
    error.x = [];
    expect(error.isAny).to.be(true);
  });

  it('#isEmpty', function () {
    var error = new Xikitita.Error();

    expect(error.isEmpty).to.be(true);
    error.x = [];
    expect(error.isEmpty).to.be(false);
  });

  it('#add', function(){
    var error = new Xikitita.Error();

    error.add('attrName1', 'message1');
    expect(error.attrName1).to.be.a(Array);
    expect(error['attrName1']).to.be.a(Array);

    error.add('attrName1', 'message2');
    error.add('attrName2', 'message1');
    expect(error.toJson).to.be('{"attrName1":["message1","message2"],"attrName2":["message1"]}');
  });

  it('#clear', function () {
    var error = new Xikitita.Error();

    error.x = [];
    error.clear;
    expect(error.isEmpty).to.be(true);
  });

  it('#messages', function () {
    expect(error.messages.toJson).to.be('[]');
  });

  it('#fullMessages', function () {
    expect(error.fullMessages.toJson).to.be('[]');
  });

});<|endoftext|>