<commit_before>const path = require('path')
const pify = require('pify')
const fs = pify(require('fs-extra'))
const R = require('ramda')
const execa = require('execa')
const { TerminalUtils, AppUtils } = require('constellate-dev-utils')

module.exports = async function test({ watch, passThroughArgs }) {
  TerminalUtils.title('Running test...')

  const jestPath = path.resolve(process.cwd(), './node_modules/.bin/jest')
  const jestExists = await fs.pathExists(jestPath)
  if (!jestExists) {
    throw new Error('Could not find Jest. You may need to reinstall your dependencies.')
  }

  const appConfig = AppUtils.getConfig()
  const preTestHook = R.path(['commands', 'test', 'pre'], appConfig)
  const postTestHook = R.path(['commands', 'test', 'pre'], appConfig)

  if (preTestHook) {
    TerminalUtils.info('Running the pre test hook')
    await preTestHook()
  }

  const args = (watch ? ['--watch'] : passThroughArgs) || []
  const cmd = `${jestPath} ${args.join(' ')}`
  TerminalUtils.verbose(`Executing jest with args: [${args.join(', ')}]`)

  try {
    await execa.shell(cmd, {
      cwd: process.cwd(),
      stdio: 'inherit',
      env: process.env,
    })
  } catch (err) {
    TerminalUtils.verbose(err)
  }

  if (postTestHook) {
    TerminalUtils.info('Running the post test hook')
    await postTestHook()
  }
}
<commit_msg>Another round of jest test fix attempts.<commit_after>const path = require('path')
const pify = require('pify')
const fs = pify(require('fs-extra'))
const R = require('ramda')
const execa = require('execa')
const { TerminalUtils, AppUtils } = require('constellate-dev-utils')

module.exports = async function test({ watch, passThroughArgs }) {
  TerminalUtils.title('Running test...')

  const jestPath = path.resolve(process.cwd(), './node_modules/.bin/jest')
  const jestExists = await fs.pathExists(jestPath)
  if (!jestExists) {
    throw new Error('Could not find Jest. You may need to reinstall your dependencies.')
  }

  const appConfig = AppUtils.getConfig()
  const preTestHook = R.path(['commands', 'test', 'pre'], appConfig)
  const postTestHook = R.path(['commands', 'test', 'pre'], appConfig)

  if (preTestHook) {
    TerminalUtils.info('Running the pre test hook')
    await preTestHook()
  }

  const args = (watch ? ['--watch'] : passThroughArgs) || []
  const forceExitIfNotWatch = args.find(x => x === '--watch') != null ? '' : '--forceExit'
  const cmd = `${jestPath} ${args.join(' ')} ${forceExitIfNotWatch}`
  TerminalUtils.verbose(`Executing jest with args: [${args.join(', ')}]`)

  try {
    await execa.shell(cmd, {
      cwd: process.cwd(),
      stdio: 'inherit',
      env: process.env,
    })
  } catch (err) {
    TerminalUtils.verbose(err)
  }

  if (postTestHook) {
    TerminalUtils.info('Running the post test hook')
    await postTestHook()
  }
}
<|endoftext|>


<commit_before><commit_msg>rm copy file<commit_after><|endoftext|>


<commit_before>var restaurants = [];

function sort_restaurants(filtered_restaurants) {
    var open = $.grep(filtered_restaurants,
            function (r, idx) { return (r.open === true) });
    var closed = $.grep(filtered_restaurants,
            function (r, idx) { return (r.open === false) });
    return $.merge(open, closed);
}

function construct_grid(filtered_restaurants) {
    $('#grid').empty();
    $('#grid').html('

');
    if (filtered_restaurants.length == 0) {
        $('#grid').append('No results found.');
        $('#footer').show();
        return;
    }
    sorted_restaurants = sort_restaurants(filtered_restaurants);
    $.each(sorted_restaurants, function (idx, restaurant) {
        var open_class = 'closed';
        if (restaurant.open) {
            open_class = 'opened';
        }
        // Append the data into the Bootstrap scaffolding
        // Note that identical restaurants can be numbered. If there is a number in square brackets
        // Next to a restuarant name, the number will be formatted as a subscript.
        $('#grid .row').append(
            '
\

' + restaurant.name.replace(/ ?\[(.+)\]/, ' ($1)') + '
\

'
        );
    });
}

function update_grid(restaurants) {
	$.each(restaurants, function (idx, restaurant) {
        var now = new Date();
        var date = new Date().setHours(0,0,0,0);
        // JavaScript sets 0 to Sunday instead of Monday
        var day = now.getDay() - 1;
        if (day === -1) {
            day = 6;
        }
        var schedule = undefined;
        // If there exists a valid special schedule choose it.
        $.each(restaurant.special_schedules, function (idx, special)  {
            if (day >= Date.parse(special.start)
                    && day <= Date.parse(special.end)) {
                schedule = special;
            }
        });
        // If there was no special schedule, then use main_schedule.
        if (schedule === undefined) {
            schedule = restaurant.main_schedule;
        }
        // Open the restaurants that are open, leave the rest closed.
        $.each(schedule.open_times, function (idx, time) {
            var start_day = time.start_day;
            var end_day = time.end_day;
            var start_time = Date.parse(time.start_time);
            var end_time = Date.parse(time.end_time);
            if (day === start_day) {
                if (now >= Date.parse(time.start_time)) {
                    if (day === end_day) {
                        if (now <= Date.parse(time.end_time)) {
                            restaurant.open = true;
                            restaurant.current = time;
                            return false;
                        }
                    } else {
                        restaurant.open = true;
                        restaurant.current = time;
                        return false;
                    }

                }
            } else if (day === end_day) {
                if (now <= Date.parse(time.end_time)) {
                    if (day === start_day) {
                        if (now >= Date.parse(time.start_time)) {
                            restaurant.open = true;
                            restaurant.current = time;
                            return false;
                        }
                    } else {
                        restaurant.open = true;
                        restaurant.current = time;
                        return false;
                    }
                }
            } else if (start_day < end_day) {
                if (day > start_day && day < end_day) {
                    restaurant.open = true;
                    restaurant.current = time;
                    return false;
                }
            } else if (start_day > end_day) {
                if (day < start_day || day > end_day) {
                    restaurant.open = true;
                    restaurant.current = time;
                    return false;
                }
            }
            restaurant.open = false;
        });
    });
}

$.ajax({
    url: '/ajax/schedule/',
}).done(function (data) {
    restaurants = data.data;
    update_grid(restaurants);
    construct_grid(restaurants);
    // Every second, check and see if it is necessary to update the grid.
    var last_updated = new Date();
    setInterval(function(){
    	now = new Date();
    	// If the hour has changed, it the half hour has changed
    	// or it has been over a half hour (180000 milliseconds) since the last update.
    	if (last_updated.getHours() != now.getHours() ||
    	   (last_updated.getMinutes() < 30 && now.getMinutes() >= 30) || now - last_updated > 1800000){
	    	update_grid(restaurants);
	    	construct_grid(restaurants);
	    	last_updated = new Date();
    	}
    }, 1000);
});
<commit_msg>Add overflow correction function<commit_after>var restaurants = [];

function correct_grid_overflow(){
    // This function ensures that all text inside the grid-boxes display nicely on one line.
    $('.restaurant').css('font-size', '');
    $('.restaurant').each(function() {
        // Overflow is detected if the height of the box is less than
        // the clipped scroll height of the box.
        while ($(this).height() > 0 && $(this).outerHeight() < $(this)[0].scrollHeight) {
            // Shrink the elements that overflow until their contents fit on one line.
            var newSize = parseInt($(this).css('font-size')) - 1;
            $(this).css('font-size', newSize + 'px');
            $(this).children('.building').css('font-size', newSize - 6 + 'px');
            // Calulated padding is added to ensure the text remains vertically centered.
            $(this).css('padding-top', 31 - newSize + 'px');
        }
    });
}

function sort_restaurants(filtered_restaurants) {
    var open = $.grep(filtered_restaurants,
            function (r, idx) { return (r.open === true) });
    var closed = $.grep(filtered_restaurants,
            function (r, idx) { return (r.open === false) });
    return $.merge(open, closed);
}

function construct_grid(filtered_restaurants) {
    $('#grid').empty();
    $('#grid').html('

');
    if (filtered_restaurants.length == 0) {
        $('#grid').append('No results found.');
        $('#footer').show();
        return;
    }
    sorted_restaurants = sort_restaurants(filtered_restaurants);
    $.each(sorted_restaurants, function (idx, restaurant) {
        var open_class = 'closed';
        if (restaurant.open) {
            open_class = 'opened';
        }
        // Append the data into the Bootstrap scaffolding
        // Note that identical restaurants can be numbered. If there is a number in square brackets
        // Next to a restuarant name, the number will be formatted as a subscript.
        $('#grid .row').append(
            '
\

' + restaurant.name.replace(/ ?\[(.+)\]/, ' ($1)') + '
\

'
        );
    });
    $('#grid').show();
    correct_overflow();
}

function update_grid(restaurants) {
	$.each(restaurants, function (idx, restaurant) {
        var now = new Date();
        var date = new Date().setHours(0,0,0,0);
        // JavaScript sets 0 to Sunday instead of Monday
        var day = now.getDay() - 1;
        if (day === -1) {
            day = 6;
        }
        var schedule = undefined;
        // If there exists a valid special schedule choose it.
        $.each(restaurant.special_schedules, function (idx, special)  {
            if (day >= Date.parse(special.start)
                    && day <= Date.parse(special.end)) {
                schedule = special;
            }
        });
        // If there was no special schedule, then use main_schedule.
        if (schedule === undefined) {
            schedule = restaurant.main_schedule;
        }
        // Open the restaurants that are open, leave the rest closed.
        $.each(schedule.open_times, function (idx, time) {
            var start_day = time.start_day;
            var end_day = time.end_day;
            var start_time = Date.parse(time.start_time);
            var end_time = Date.parse(time.end_time);
            if (day === start_day) {
                if (now >= Date.parse(time.start_time)) {
                    if (day === end_day) {
                        if (now <= Date.parse(time.end_time)) {
                            restaurant.open = true;
                            restaurant.current = time;
                            return false;
                        }
                    } else {
                        restaurant.open = true;
                        restaurant.current = time;
                        return false;
                    }

                }
            } else if (day === end_day) {
                if (now <= Date.parse(time.end_time)) {
                    if (day === start_day) {
                        if (now >= Date.parse(time.start_time)) {
                            restaurant.open = true;
                            restaurant.current = time;
                            return false;
                        }
                    } else {
                        restaurant.open = true;
                        restaurant.current = time;
                        return false;
                    }
                }
            } else if (start_day < end_day) {
                if (day > start_day && day < end_day) {
                    restaurant.open = true;
                    restaurant.current = time;
                    return false;
                }
            } else if (start_day > end_day) {
                if (day < start_day || day > end_day) {
                    restaurant.open = true;
                    restaurant.current = time;
                    return false;
                }
            }
            restaurant.open = false;
        });
    });
}

$.ajax({
    url: '/ajax/schedule/',
}).done(function (data) {
    restaurants = data.data;
    update_grid(restaurants);
    construct_grid(restaurants);
    // Every second, check and see if it is necessary to update the grid.
    var last_updated = new Date();
    setInterval(function(){
    	now = new Date();
    	// If the hour has changed, it the half hour has changed
    	// or it has been over a half hour (180000 milliseconds) since the last update.
    	if (last_updated.getHours() != now.getHours() ||
    	   (last_updated.getMinutes() < 30 && now.getMinutes() >= 30) || now - last_updated > 1800000){
	    	update_grid(restaurants);
	    	construct_grid(restaurants);
	    	last_updated = new Date();
    	}
    }, 1000);
    $(window).on('resize', function(){
        correct_grid_overflow();
    });
});
<|endoftext|>


<commit_before>'use strict';
function langListFactory() {
        var langList = {};
        var languages=[
                        {
                           id: '1',
                           name:'English',
                           description:'',
                           comment: ''
                        },
                        {
                           id: '2',
                           name:'Italian',
                           description:'',
                           comment: ''
                        },
                        {
                           id: '3',
                           name:'French',
                           description:'',
                           comment: ''
                        },
                        {
                           id: '4',
                           name:'Swedish',
                           description:'',
                           comment: ''
                        },
                        {
                           id: '5',
                           name:'Spanish',
                           description:'',
                           comment: ''
                        },
                        {
                           id: '6',
                           name:'Mongolian',
                           description:'',
                           comment: ''
                        }
                        ];
        langList.getLanguages = function() {
            return languages;
        }

        langList.getLanguage = function(index) {
            return languages[index];
        }
        return langList;

};

module.exports = {
  factory: langListFactory
};<commit_msg>Add all languages<commit_after>'use strict';
function langListFactory() {
    var langList = {};
    var languages = [
        {
            id: '1',
            name: 'Afrikaans',
            description: '',
            comment: ''
        },
        {
            id: '2',
            name: 'Albanian',
            description: '',
            comment: ''
        },
        {
            id: '3',
            name: 'Amharic',
            description: '',
            comment: ''
        },
        {
            id: '4',
            name: 'Arabic',
            description: '',
            comment: ''
        },
        {
            id: '5',
            name: 'Armenian',
            description: '',
            comment: ''
        },
        {
            id: '6',
            name: 'Azerbaijani',
            description: '',
            comment: ''
        },
        {
            id: '7',
            name: 'Basque',
            description: '',
            comment: ''
        },
        {
            id: '8',
            name: 'Belarusian',
            description: '',
            comment: ''
        },
        {
            id: '9',
            name: 'Bengali',
            description: '',
            comment: ''
        },
        {
            id: '10',
            name: 'Bosnian',
            description: '',
            comment: ''
        },
        {
            id: '11',
            name: 'Bulgarian',
            description: '',
            comment: ''
        },
        {
            id: '12',
            name: 'Catalan',
            description: '',
            comment: ''
        },
        {
            id: '13',
            name: 'Cebuano',
            description: '',
            comment: ''
        },
        {
            id: '14',
            name: 'Chichewa',
            description: '',
            comment: ''
        },
        {
            id: '15',
            name: 'Chinese',
            description: '',
            comment: ''
        },
        {
            id: '16',
            name: 'Corsican',
            description: '',
            comment: ''
        },
        {
            id: '17',
            name: 'Croatian',
            description: '',
            comment: ''
        },
        {
            id: '18',
            name: 'Czech',
            description: '',
            comment: ''
        },
        {
            id: '19',
            name: 'Danish',
            description: '',
            comment: ''
        },
        {
            id: '20',
            name: 'Dutch',
            description: '',
            comment: ''
        },
        {
            id: '21',
            name: 'English',
            description: '',
            comment: ''
        },
        {
            id: '22',
            name: 'Esperanto',
            description: '',
            comment: ''
        },
        {
            id: '23',
            name: 'Estonian',
            description: '',
            comment: ''
        },
        {
            id: '24',
            name: 'Filipino',
            description: '',
            comment: ''
        },
        {
            id: '25',
            name: 'Finnish',
            description: '',
            comment: ''
        },
        {
            id: '26',
            name: 'French',
            description: '',
            comment: ''
        },
        {
            id: '27',
            name: 'Frisian',
            description: '',
            comment: ''
        },
        {
            id: '28',
            name: 'Galician',
            description: '',
            comment: ''
        },
        {
            id: '29',
            name: 'Georgian',
            description: '',
            comment: ''
        },
        {
            id: '30',
            name: 'German',
            description: '',
            comment: ''
        },
        {
            id: '31',
            name: 'Greek',
            description: '',
            comment: ''
        },
        {
            id: '32',
            name: 'Gujarati',
            description: '',
            comment: ''
        },
        {
            id: '33',
            name: 'Haitian Creole',
            description: '',
            comment: ''
        },
        {
            id: '34',
            name: 'Hausa',
            description: '',
            comment: ''
        },
        {
            id: '35',
            name: 'Hawaiian',
            description: '',
            comment: ''
        },
        {
            id: '36',
            name: 'Hebrew',
            description: '',
            comment: ''
        },
        {
            id: '37',
            name: 'Hindi',
            description: '',
            comment: ''
        },
        {
            id: '38',
            name: 'Hmong',
            description: '',
            comment: ''
        },
        {
            id: '39',
            name: 'Hungarian',
            description: '',
            comment: ''
        },
        {
            id: '40',
            name: 'Icelandic',
            description: '',
            comment: ''
        },
        {
            id: '41',
            name: 'Igbo',
            description: '',
            comment: ''
        },
        {
            id: '42',
            name: 'Indonesian',
            description: '',
            comment: ''
        },
        {
            id: '43',
            name: 'Irish',
            description: '',
            comment: ''
        },
        {
            id: '44',
            name: 'Italian',
            description: '',
            comment: ''
        },
        {
            id: '45',
            name: 'Japanese',
            description: '',
            comment: ''
        },
        {
            id: '46',
            name: 'Javanese',
            description: '',
            comment: ''
        },
        {
            id: '47',
            name: 'Kannada',
            description: '',
            comment: ''
        },
        {
            id: '48',
            name: 'Kazakh',
            description: '',
            comment: ''
        },
        {
            id: '49',
            name: 'Khmer',
            description: '',
            comment: ''
        },
        {
            id: '50',
            name: 'Korean',
            description: '',
            comment: ''
        },
        {
            id: '51',
            name: 'Kurdish (Kurmanji)',
            description: '',
            comment: ''
        },
        {
            id: '52',
            name: 'Kyrgyz',
            description: '',
            comment: ''
        },
        {
            id: '53',
            name: 'Lao',
            description: '',
            comment: ''
        },
        {
            id: '54',
            name: 'Latin',
            description: '',
            comment: ''
        },
        {
            id: '55',
            name: 'Latvian',
            description: '',
            comment: ''
        },
        {
            id: '56',
            name: 'Lithuanian',
            description: '',
            comment: ''
        },
        {
            id: '57',
            name: 'Luxembourgish',
            description: '',
            comment: ''
        },
        {
            id: '58',
            name: 'Macedonian',
            description: '',
            comment: ''
        },
        {
            id: '59',
            name: 'Malagasy',
            description: '',
            comment: ''
        },
        {
            id: '60',
            name: 'Malay',
            description: '',
            comment: ''
        },
        {
            id: '61',
            name: 'Malayalam',
            description: '',
            comment: ''
        },
        {
            id: '62',
            name: 'Maltese',
            description: '',
            comment: ''
        },
        {
            id: '63',
            name: 'Maori',
            description: '',
            comment: ''
        },
        {
            id: '64',
            name: 'Marathi',
            description: '',
            comment: ''
        },
        {
            id: '65',
            name: 'Mongolian',
            description: '',
            comment: ''
        },
        {
            id: '66',
            name: 'Myanmar (Burmese)',
            description: '',
            comment: ''
        },
        {
            id: '67',
            name: 'Nepali',
            description: '',
            comment: ''
        },
        {
            id: '68',
            name: 'Norwegian',
            description: '',
            comment: ''
        },
        {
            id: '69',
            name: 'Pashto',
            description: '',
            comment: ''
        },
        {
            id: '70',
            name: 'Persian',
            description: '',
            comment: ''
        },
        {
            id: '71',
            name: 'Polish',
            description: '',
            comment: ''
        },
        {
            id: '72',
            name: 'Portuguese',
            description: '',
            comment: ''
        },
        {
            id: '73',
            name: 'Punjabi',
            description: '',
            comment: ''
        },
        {
            id: '74',
            name: 'Romanian',
            description: '',
            comment: ''
        },
        {
            id: '75',
            name: 'Russian',
            description: '',
            comment: ''
        },
        {
            id: '76',
            name: 'Samoan',
            description: '',
            comment: ''
        },
        {
            id: '77',
            name: 'Scots Gaelic',
            description: '',
            comment: ''
        },
        {
            id: '78',
            name: 'Serbian',
            description: '',
            comment: ''
        },
        {
            id: '79',
            name: 'Sesotho',
            description: '',
            comment: ''
        },
        {
            id: '80',
            name: 'Shona',
            description: '',
            comment: ''
        },
        {
            id: '81',
            name: 'Sindhi',
            description: '',
            comment: ''
        },
        {
            id: '82',
            name: 'Sinhala',
            description: '',
            comment: ''
        },
        {
            id: '83',
            name: 'Slovak',
            description: '',
            comment: ''
        },
        {
            id: '84',
            name: 'Slovenian',
            description: '',
            comment: ''
        },
        {
            id: '85',
            name: 'Somali',
            description: '',
            comment: ''
        },
        {
            id: '86',
            name: 'Spanish',
            description: '',
            comment: ''
        },
        {
            id: '87',
            name: 'Sundanese',
            description: '',
            comment: ''
        },
        {
            id: '88',
            name: 'Swahili',
            description: '',
            comment: ''
        },
        {
            id: '89',
            name: 'Swedish',
            description: '',
            comment: ''
        },
        {
            id: '90',
            name: 'Tajik',
            description: '',
            comment: ''
        },
        {
            id: '91',
            name: 'Tamil',
            description: '',
            comment: ''
        },
        {
            id: '92',
            name: 'Telugu',
            description: '',
            comment: ''
        },
        {
            id: '93',
            name: 'Thai',
            description: '',
            comment: ''
        },
        {
            id: '94',
            name: 'Turkish',
            description: '',
            comment: ''
        },
        {
            id: '95',
            name: 'Ukrainian',
            description: '',
            comment: ''
        },
        {
            id: '96',
            name: 'Urdu',
            description: '',
            comment: ''
        },
        {
            id: '97',
            name: 'Uzbek',
            description: '',
            comment: ''
        },
        {
            id: '98',
            name: 'Vietnamese',
            description: '',
            comment: ''
        },
        {
            id: '99',
            name: 'Welsh',
            description: '',
            comment: ''
        },
        {
            id: '100',
            name: 'Xhosa',
            description: '',
            comment: ''
        },
        {
            id: '101',
            name: 'Yiddish',
            description: '',
            comment: ''
        },
        {
            id: '102',
            name: 'Yoruba',
            description: '',
            comment: ''
        },
        {
            id: '103',
            name: 'Zulu',
            description: '',
            comment: ''
        }
    ];
    langList.getLanguages = function () {
        return languages;
    }

    langList.getLanguage = function (index) {
        return languages[index];
    }
    return langList;

};

module.exports = {
    factory: langListFactory
};<|endoftext|>


<commit_before>(function($) {
	'use strict';

	module('Difference.common');

	test('Does not modify first parameter', function () {
		var u = { foo: 'baz', bar: 'abc' };
		var a = { foo: 'baz' };
		var original = $.extend({}, u);

		$.difference(u, a);

		deepEqual(u, original);
	});

	test('Does not modify second parameter', function () {
		var u = { foo: 'baz', bar: 'abc' };
		var a = { foo: 'baz' };
		var original = $.extend({}, a);

		$.difference(u, a);

		deepEqual(a, original);
	});

	test('No parameters returns empty object', function () {
		var result = $.difference();

		deepEqual(result, {});
	});

	test('One parameter returns that parameter', function () {
		var u = { foo: 'baz', bar: 'abc' };
		var original = $.extend({}, u);
		var result = $.difference(u);

		deepEqual(result, original);
	});

	module('Difference');

	test('Property on left, no property on right, gives left value', function () {
		var u = { prop: 'value' };
		var a = {};
		var result = $.difference(u, a);

		deepEqual(result, u);
	});

	test('No property on left, property on right, gives empty object', function () {
		var u = {};
		var a = { prop: 'value' };
		var result = $.difference(u, a);

		deepEqual(result, {});
	});

	test('No values on objects, gives empty object', function () {
		var u = {};
		var a = {};
		var result = $.difference(u, a);

		deepEqual(result, {});
	});

	test('Property on left and other property on right, gives left property', function () {
		var u = { prop1: 'foo' };
		var a = { prop2: 'bar' };
		var result = $.difference(u, a);

		deepEqual(result.prop1, u.prop1);
		ok(!result.prop2);
	});

	test('One value on left and other value on right, gives empty object', function () {
		var u = { prop: 'foo' };
		var a = { prop: 'bar' };
		var result = $.difference(u, a);

		deepEqual(result, {});
	});

	test('Two objects returns difference of first against second', function () {
		var u = { one: 1, two: 2 };
		var a = { one: 1, three: 3 };
		var expected = { two: 2 };

		var result = $.difference(u, a);

		deepEqual(result, expected);
	});

	test('Multiple objects returns difference of first against the rest', function () {
		var u = { one: 1, two: 2, three: 3, four: 4  };
		var a = { two: 2, three: 3 };
		var b = { three: 3, four: 4 };
		var c = { four: 4, three: 3 };
		var expected = { one: 1 };
		var result = $.difference(u, a, b, c);

		deepEqual(result, expected);
	});
}(jQuery));<commit_msg>Added test for old bug with difference()<commit_after>(function($) {
	'use strict';

	module('Difference.common');

	test('Does not modify first parameter', function () {
		var u = { foo: 'baz', bar: 'abc' };
		var a = { foo: 'baz' };
		var original = $.extend({}, u);

		$.difference(u, a);

		deepEqual(u, original);
	});

	test('Does not modify second parameter', function () {
		var u = { foo: 'baz', bar: 'abc' };
		var a = { foo: 'baz' };
		var original = $.extend({}, a);

		$.difference(u, a);

		deepEqual(a, original);
	});

	test('No parameters returns empty object', function () {
		var result = $.difference();

		deepEqual(result, {});
	});

	test('One parameter returns that parameter', function () {
		var u = { foo: 'baz', bar: 'abc' };
		var original = $.extend({}, u);
		var result = $.difference(u);

		deepEqual(result, original);
	});

	module('Difference');

	test('Property on left, no property on right, gives left value', function () {
		var u = { prop: 'value' };
		var a = {};
		var result = $.difference(u, a);

		deepEqual(result, u);
	});

	test('No property on left, property on right, gives empty object', function () {
		var u = {};
		var a = { prop: 'value' };
		var result = $.difference(u, a);

		deepEqual(result, {});
	});

	test('No values on objects, gives empty object', function () {
		var u = {};
		var a = {};
		var result = $.difference(u, a);

		deepEqual(result, {});
	});

	test('Property on left and other property on right, gives left property', function () {
		var u = { prop1: 'foo' };
		var a = { prop2: 'bar' };
		var result = $.difference(u, a);

		deepEqual(result.prop1, u.prop1);
		ok(!result.prop2);
	});

	test('One value on left and other value on right, gives empty object', function () {
		var u = { prop: 'foo' };
		var a = { prop: 'bar' };
		var result = $.difference(u, a);

		deepEqual(result, {});
	});

    test('Boolean values do not affect comparison to give wrong objects', function () {
        var u = { foo: true, bar: false };
        var a = { foo: false, bar: true };
        var result = $.difference(u, a);

        deepEqual(result, {});
    });

	test('Two objects returns difference of first against second', function () {
		var u = { one: 1, two: 2 };
		var a = { one: 1, three: 3 };
		var expected = { two: 2 };

		var result = $.difference(u, a);

		deepEqual(result, expected);
	});

	test('Multiple objects returns difference of first against the rest', function () {
		var u = { one: 1, two: 2, three: 3, four: 4  };
		var a = { two: 2, three: 3 };
		var b = { three: 3, four: 4 };
		var c = { four: 4, three: 3 };
		var expected = { one: 1 };
		var result = $.difference(u, a, b, c);

		deepEqual(result, expected);
	});
}(jQuery));<|endoftext|>


<commit_before>var mumuki = mumuki || {};

(function (mumuki) {

  function AceEditorBuilder(textarea) {
    this.textarea = textarea;
  }

  AceEditorBuilder.prototype = {
    setupEditor: function () {
      this.form = this.textarea.form;
      this.editor = ace.edit(this.textarea);
      this.editor.container.id = "editor-container";
    },
    setupLanguage: function () {
      var language = $(this.textarea).data('editor-language');
      if (language === 'dynamic') {
        mumuki.page.dynamicEditors.push(this.editor);
      } else {
        mumuki.editor.setEditorLanguage(this.editor, language);
      }
    },
    setupOptions: function () {
      this.editor.setOptions({
        minLines: 17,
        maxLines: Infinity,
        wrap: true
      });
      this.editor.setFontSize(14);
    },
    setupSubmit: function () {
      var textarea = this.textarea;
      var form = this.form;
      var editor = this.editor;
      this.form.addEventListener("submit", function () {
        textarea.style.visibility = "hidden";
        textarea.value = editor.getValue();
        form.appendChild(textarea)
      });
    },
    build: function () {
      return this.editor;
    }
  };

  mumuki.editor = mumuki.editor || {};
  mumuki.editor.AceEditorBuilder = AceEditorBuilder;
})(mumuki);
<commit_msg>Removing annoying ACE editor margin<commit_after>var mumuki = mumuki || {};

(function (mumuki) {

  function AceEditorBuilder(textarea) {
    this.textarea = textarea;
  }

  AceEditorBuilder.prototype = {
    setupEditor: function () {
      this.form = this.textarea.form;
      this.editor = ace.edit(this.textarea);
      this.editor.container.id = "editor-container";
    },
    setupLanguage: function () {
      var language = $(this.textarea).data('editor-language');
      if (language === 'dynamic') {
        mumuki.page.dynamicEditors.push(this.editor);
      } else {
        mumuki.editor.setEditorLanguage(this.editor, language);
      }
    },
    setupOptions: function () {
      this.editor.setOptions({
        minLines: 17,
        maxLines: Infinity,
        showPrintMargin: false,
        wrap: true
      });
      this.editor.setFontSize(14);
    },
    setupSubmit: function () {
      var textarea = this.textarea;
      var form = this.form;
      var editor = this.editor;
      this.form.addEventListener("submit", function () {
        textarea.style.visibility = "hidden";
        textarea.value = editor.getValue();
        form.appendChild(textarea)
      });
    },
    build: function () {
      return this.editor;
    }
  };

  mumuki.editor = mumuki.editor || {};
  mumuki.editor.AceEditorBuilder = AceEditorBuilder;
})(mumuki);
<|endoftext|>


<commit_before>import {h} from 'react-markup'
import React, {PropTypes} from 'react'
import prefixer from 'bem-prefixer'

import QuestionTitle from './elements/question-title'

const bem = prefixer('questionnaire-text')

class Text extends React.Component {

    handleChange = (e) => {
        const {onChange} = this.props
        onChange(e.target.value)
    }

    render() {
        const {name, title, value} = this.props
        return h(bem('div'),
            h(bem('label#label'),
                h(QuestionTitle, title),
                h(bem('input#input'), {type: 'text', name, value, onChange: this.handleChange})
            )
        )
    }
}

Text.propTypes = {
    name: PropTypes.string.isRequired,
    title: PropTypes.string.isRequired,
    value: PropTypes.string.isRequired,
    onChange: PropTypes.func.isRequired,
    mandatory: PropTypes.bool,
}

Text.defaultType = {
    mandatory: false,
}

export default Text
<commit_msg>Questionnaire: implement placeholder for text<commit_after>import {h} from 'react-markup'
import React, {PropTypes} from 'react'
import prefixer from 'bem-prefixer'

import QuestionTitle from './elements/question-title'

const bem = prefixer('questionnaire-text')

class Text extends React.Component {

    handleChange = (e) => {
        const {onChange} = this.props
        onChange(e.target.value)
    }

    render() {
        const {name, title, value, placeholder} = this.props
        return h(bem('div'),
            h(bem('label#label'),
                h(QuestionTitle, title),
                h(bem('input#input'), {
                    type: 'text',
                    placeholder,
                    name,
                    value,
                    onChange: this.handleChange,
                })
            )
        )
    }
}

Text.propTypes = {
    name: PropTypes.string.isRequired,
    title: PropTypes.string.isRequired,
    value: PropTypes.string.isRequired,
    onChange: PropTypes.func.isRequired,
    placeholder: PropTypes.string,
    mandatory: PropTypes.bool,
}

Text.defaultType = {
    placeholder: null,
    mandatory: false,
}

export default Text
<|endoftext|>


<commit_before>define(
	[
		'lib/jquery',
		'lib/underscore',
		'lib/backbone',
		'view/generic',
		'lib/i18n',
		'lib/backbone-forms',
		'view/editors',
		'model/bill',
		'model/cashPoint'
	],
	function($, _, Backbone, openhmis, i18n) {
		openhmis.BillLineItemView = openhmis.GenericListItemView.extend({
			initialize: function(options) {
				this.events = _.extend({}, this.events, {
					'keypress': 'onKeyPress'
				});
				openhmis.GenericListItemView.prototype.initialize.call(this, options);
				_.bindAll(this);
				if (this.form) {
					this.form.on('price:change', this.update);
					this.form.on('quantity:change', this.update);
					this.form.on('item:change', this.updateItem);
				}
			},

			updateItem: function(form, itemEditor) {
				var item = itemEditor.getValue();
				this.updatePriceOptions(item, form);
				if (form.fields.quantity.getValue() === 0)
					form.fields.quantity.setValue(1);
				this.update();
				this.$('.field-quantity input').focus();
			},

			updatePriceOptions: function(item, form) {
				item = item ? item : this.model.get("item");
				form = form ? form : this.form;
				var price;
				var defaultPrice = item ? item.get("defaultPrice") : undefined;
				var price = this.model.get("price") || defaultPrice;
				if (price !== undefined)
					price = price.id;
				var options = new openhmis.GenericCollection([], { model: openhmis.ItemPrice });
				if (item)
					options.reset(item.get("prices"));
				else
					options.add(0);
				if (form) {
					form.fields.price.editor.options.options = options;
					form.fields.price.editor.render();
					if (price)
						form.fields.price.setValue(price);
				}
			},

			update: function() {
				if (this.updateTimeout !== undefined) clearTimeout(this.updateTimeout);
				var view = this;
				var update = function() {
					var price = view.form.getValue("price");
					var quantity = view.form.getValue("quantity");
					view.form.setValue({ total: price * quantity });
				}
				this.updateTimeout = setTimeout(update, 200);
			},

			onKeyPress: function(event) {
				if (event.keyCode === 13) {
					var errors = this.commitForm(event);
				}
			},

			onModelChange: function(model) {
				if (model.hasChanged() && model.isValid())
					this.trigger("change", this);
			},

			displayErrors: function(errorMap, event) {
				// If there is already another item in the collection and
				// this is not triggered by enter key, skip the error message
				if (event && event.type !== "keypress" && this.model.collection && this.model.collection.length > 0)
					return;

				for(var item in errorMap) {
					var $errorEl = this.$('.field-' + item + ' .editor');
					if ($errorEl.length > 0) {
						openhmis.validationMessage($errorEl, errorMap[item]);
					}
				}
			},

			focus: function(form) {
				openhmis.GenericListItemView.prototype.focus.call(this, form);
				if (!form)
					this.$('.item-name').focus();
			},

			removeModel: function() {
				if (this.model.collection)
					this.model.collection.remove(this.model, { silent: true });
			},

			render: function() {
				openhmis.GenericListItemView.prototype.render.call(this);
				this.updatePriceOptions();
				this.$(".field-price input, .field-total input").attr("readonly", "readonly");
				return this;
			},
		});

		/**
		 * BillView
		 *
		 */
		openhmis.BillView = openhmis.GenericListView.extend({
			initialize: function(options) {
				_.bindAll(this);
				var bill = (options && options.bill) ? options.bill : new openhmis.Bill();
				this.setBill(bill);

				var billOptions = { showRetiredOption: false, showPaging: false }
				options = _.extend(billOptions, options);

				openhmis.GenericListView.prototype.initialize.call(this, options);
				this.options.roundToNearest = options.roundToNearest || 0;
				this.options.roundingMode = options.roundingMode || "MID";
				this.itemView = openhmis.BillLineItemView;
				this.totalsTemplate = this.getTemplate("bill.html", '#bill-totals');
			},

			schema: {
				item: { type: "Item" },
				quantity: { type: "CustomNumber" },
				price: {
					type: "ItemPriceSelect",
					options: new openhmis.GenericCollection([0], {model: openhmis.ItemPrice}),
					format: openhmis.ItemPrice.prototype.format
				}
			},

			setBill: function(bill) {
				this.bill = bill;
				this.model = bill.get("lineItems");
				this.model.on("all", this.updateTotals);
				if (bill.get("status") === bill.BillStatus.PENDING)
					this.options.itemActions = ["remove", "inlineEdit"];
				else
					this.options.itemActions = [];
			},

			addOne: function(model, schema) {
				var view = openhmis.GenericListView.prototype.addOne.call(this, model, schema);
				view.$('td.field-quantity').add('td.field-price').add('td.field-total').addClass("numeric");
				if (this.newItem && view.model.cid === this.newItem.cid) {
					this.selectedItem = view;
					view.on("change", this.setupNewItem);
				}
				else
					view.on("change remove", this.bill.setUnsaved);
				return view;
			},

			itemSelected: function(itemView) {
				openhmis.GenericListView.prototype.itemSelected.call(this, itemView);
				this.updateTotals();
			},

			itemRemoved: function(item) {
				openhmis.GenericListView.prototype.itemRemoved.call(this, item);
				if (item === this.newItem) {
					this.setupNewItem();
				}
			},

			patientSelected: function(patient) {
				this.bill.set("patient", patient);
				this.focus();
			},

			setupNewItem: function(lineItemView) {
				var dept_uuid;
				// Handle adding an item from the input line
				if (lineItemView !== undefined) {
					// Prevent multiple change events causing duplicate views
					if (this.model.getByCid(lineItemView.model.cid)) return;
					lineItemView.off("change", this.setupNewItem);
					this.model.add(lineItemView.model, { silent: true });
					this.bill.setUnsaved();
					lineItemView.on("change remove", this.bill.setUnsaved);
					this.deselectAll();
					dept_uuid = lineItemView.model.get("item").get("department").id;
				}
				this.newItem = new openhmis.LineItem();
				// Don't add the item to the collection, but give it a reference
				this.newItem.collection = this.model;
				if (this.$('p.empty').length > 0)
					this.render();
				else {
					var view = this.addOne(this.newItem);
					view.focus();
				}
			},

			setupCashPointForm: function(el) {
				var cashPoint = this.bill.get("cashPoint");
				var cashPointId = cashPoint ? cashPoint.id : undefined;
				this.cashPointForm = new Backbone.Form({
					schema: {
						cashPoint: {
							type: 'Select',
							title: i18n("Cash Point") + ":",
							options: new openhmis.GenericCollection([], { model: openhmis.CashPoint })
						}
					},
					data: {
						cashPoint: cashPointId
					},
					template: "trForm",
					fieldsetTemplate: "blankFieldset"
				});
				this.cashPointForm.render();
				$(el).empty().append(this.cashPointForm.el);
				return this.cashPointForm;
			},

			updateTotals: function() {
				var total = openhmis.round(this.bill.getAdjustedTotal(), this.options.roundToNearest, this.options.roundingMode);
				var totalPaid = this.bill.getTotalPayments();
				this.$totals.html(this.totalsTemplate({
					bill: this.bill,
					total: total,
					totalPaid: totalPaid,
					formatPrice: openhmis.ItemPrice.prototype.format,
					__: i18n }))
			},

			/**
			 * @should post bill if it is pending
			 * @should add payment if the bill has already been posted
			 */
			processPayment: function(payment, options) {
				options = options ? options : {};
				var success = options.success;
				var self = this;
				options.success = function(model, resp) {
					if (self.bill.getTotalPayments() >= self.bill.getTotal())
						self.trigger("paid", self.bill);
					self.updateTotals();
					if (success) success(model, resp);
				}
				payment.set("amountTendered", payment.get("amount"));
				var paymentChange = (this.bill.getTotalPayments() + payment.get("amount")) - this.bill.getAdjustedTotal();
				if (paymentChange > 0)
					payment.set("amount", payment.get("amountTendered") - paymentChange);
				this.bill.addPayment(payment);
				if (this.bill.get("status") === this.bill.BillStatus.PENDING)
					this.postBill(options);
				else
					payment.save([], options);
			},

			validate: function(allowEmptyBill) {
				var errors = this.bill.validate(true);
				var elMap = {
					'lineItems': [ $('#bill'), this ],
					'patient': [ $('#patient-view'),  $('#inputNode') ]
				}
				if (allowEmptyBill === true
					&& errors
					&& errors.lineItems !== undefined)
						delete errors.lineItems;
				if (errors && _.size(errors) > 0) {
					for (var e in errors)
						openhmis.validationMessage(elMap[e][0], errors[e], elMap[e][1]);
					return false;
				}
				return true;
			},

			saveBill: function(options, post) {
				options = options ? options : {};
				if (!this.validate(post)) return;
				if (this.cashPointForm !== undefined)
					this.bill.set("cashPoint", this.cashPointForm.getValue("cashPoint"));
				// Filter out any invalid lineItems (especially the bottom)
				// entry cursor
				this.bill.get("lineItems").reset(
					this.model.filter(function(item) { return item.isClean(); }),
					{ silent: true }
				);

				if (post === true
					&& this.bill.get("billAdjusted")
					&& this.bill.get("status") === this.bill.BillStatus.PENDING)
						this._postAdjustingBill(this.bill);
				var print = options.print;
				var success = options.success;
				var error = options.error;
				var self = this;
				options.success = function(model, resp) {
					self.trigger(print ? "saveAndPrint" : "save", model);
					if (success) success(model, resp);
				}
				options.error = function(model, resp) {
					openhmis.error(resp);
					if (error) error(model, resp);
				}
				this.bill.save([], options);
			},

			postBill: function(options) {
				this.saveBill(options, true);
			},

			_postAdjustingBill: function(bill) {
				bill.get("billAdjusted").get("payments").each(function(payment) {
					payment.set("amountTendered", payment.get("amount"));
				});
				bill.get("payments").add(bill.get("billAdjusted").get("payments").models);
				var adjustingItems = bill.get("lineItems");
				bill.set("lineItems", bill.get("billAdjusted").get("lineItems"));
				bill.get("lineItems").add(adjustingItems.models);
				bill.set("status", bill.BillStatus.POSTED);
			},

			adjustBill: function() {
				var __ = i18n;
				if (confirm(__("Are you sure you want to adjust this bill?"))) {
					var adjustingBill = new openhmis.Bill({
						billAdjusted: this.bill.id,
						patient: this.bill.get("patient").id
					});
					// Unset status to avoid the adjusted bill from being
					// immediately set to PAID
					adjustingBill.unset("status");
					var view = this;
					adjustingBill.save([], { success: function(model, resp) {
						view.trigger("adjusted", model);
					}});
				}
			},

			printReceipt: function(event) {
				var url = openhmis.config.pageUrlRoot
					+ "receipt.form?receiptNumber=" + encodeURIComponent(this.bill.get("receiptNumber"));
				if (event) {
					if (this.bill.get("receiptNumber")) {
						window.open(url, "pdfDownload");
					}
				}
				else {
					$iframe = $('');
					$("body").append($iframe);
				}
			},

			render: function() {
				if (this.newItem) this.model.add(this.newItem, { silent: true });
				openhmis.GenericListView.prototype.render.call(this, {
					listTitle: ""
				});
				if (this.newItem) this.model.remove(this.newItem, { silent: true });
				this.$('table').addClass("bill");
				this.$totals = $('

');
				this.$('div.box').append(this.$totals);
				this.updateTotals();
				return this;
			}
		});

		openhmis.BillAndPaymentsView = Backbone.View.extend({
			className: "combineBoxes",
			initialize: function(options) {
				var __ = i18n;
				this.itemsView = new openhmis.GenericListView({
					model: this.model.get("lineItems"),
					listTitle: __("Previous Bill (%s)", this.model),
					showPaging: false,
					showRetiredOption: false
				});
				this.paymentsView = new openhmis.GenericListView({
					model: this.model.get("payments"),
					className: "paymentList",
					listTitle: "Previous Payments",
					listFields: ["dateCreatedFmt", "paymentMode", "amountFmt"],
					showPaging: false,
					showRetiredOption: false
				});
			},

			render: function() {
				this.$el.append(this.itemsView.render().el);
				this.itemsView.$("table").addClass("bill");
				this.$el.append(this.paymentsView.render().el);
				return this;
			}
		});

		return openhmis;
	}
);<commit_msg>Prevent payment from showing if bill validation fails; fixes #89.<commit_after>define(
	[
		'lib/jquery',
		'lib/underscore',
		'lib/backbone',
		'view/generic',
		'lib/i18n',
		'lib/backbone-forms',
		'view/editors',
		'model/bill',
		'model/cashPoint'
	],
	function($, _, Backbone, openhmis, i18n) {
		openhmis.BillLineItemView = openhmis.GenericListItemView.extend({
			initialize: function(options) {
				this.events = _.extend({}, this.events, {
					'keypress': 'onKeyPress'
				});
				openhmis.GenericListItemView.prototype.initialize.call(this, options);
				_.bindAll(this);
				if (this.form) {
					this.form.on('price:change', this.update);
					this.form.on('quantity:change', this.update);
					this.form.on('item:change', this.updateItem);
				}
			},

			updateItem: function(form, itemEditor) {
				var item = itemEditor.getValue();
				this.updatePriceOptions(item, form);
				if (form.fields.quantity.getValue() === 0)
					form.fields.quantity.setValue(1);
				this.update();
				this.$('.field-quantity input').focus();
			},

			updatePriceOptions: function(item, form) {
				item = item ? item : this.model.get("item");
				form = form ? form : this.form;
				var price;
				var defaultPrice = item ? item.get("defaultPrice") : undefined;
				var price = this.model.get("price") || defaultPrice;
				if (price !== undefined)
					price = price.id;
				var options = new openhmis.GenericCollection([], { model: openhmis.ItemPrice });
				if (item)
					options.reset(item.get("prices"));
				else
					options.add(0);
				if (form) {
					form.fields.price.editor.options.options = options;
					form.fields.price.editor.render();
					if (price)
						form.fields.price.setValue(price);
				}
			},

			update: function() {
				if (this.updateTimeout !== undefined) clearTimeout(this.updateTimeout);
				var view = this;
				var update = function() {
					var price = view.form.getValue("price");
					var quantity = view.form.getValue("quantity");
					view.form.setValue({ total: price * quantity });
				}
				this.updateTimeout = setTimeout(update, 200);
			},

			onKeyPress: function(event) {
				if (event.keyCode === 13) {
					var errors = this.commitForm(event);
				}
			},

			onModelChange: function(model) {
				if (model.hasChanged() && model.isValid())
					this.trigger("change", this);
			},

			displayErrors: function(errorMap, event) {
				// If there is already another item in the collection and
				// this is not triggered by enter key, skip the error message
				if (event && event.type !== "keypress" && this.model.collection && this.model.collection.length > 0)
					return;

				for(var item in errorMap) {
					var $errorEl = this.$('.field-' + item + ' .editor');
					if ($errorEl.length > 0) {
						openhmis.validationMessage($errorEl, errorMap[item]);
					}
				}
			},

			focus: function(form) {
				openhmis.GenericListItemView.prototype.focus.call(this, form);
				if (!form)
					this.$('.item-name').focus();
			},

			removeModel: function() {
				if (this.model.collection)
					this.model.collection.remove(this.model, { silent: true });
			},

			render: function() {
				openhmis.GenericListItemView.prototype.render.call(this);
				this.updatePriceOptions();
				this.$(".field-price input, .field-total input").attr("readonly", "readonly");
				return this;
			},
		});

		/**
		 * BillView
		 *
		 */
		openhmis.BillView = openhmis.GenericListView.extend({
			initialize: function(options) {
				_.bindAll(this);
				var bill = (options && options.bill) ? options.bill : new openhmis.Bill();
				this.setBill(bill);

				var billOptions = { showRetiredOption: false, showPaging: false }
				options = _.extend(billOptions, options);

				openhmis.GenericListView.prototype.initialize.call(this, options);
				this.options.roundToNearest = options.roundToNearest || 0;
				this.options.roundingMode = options.roundingMode || "MID";
				this.itemView = openhmis.BillLineItemView;
				this.totalsTemplate = this.getTemplate("bill.html", '#bill-totals');
			},

			schema: {
				item: { type: "Item" },
				quantity: { type: "CustomNumber" },
				price: {
					type: "ItemPriceSelect",
					options: new openhmis.GenericCollection([0], {model: openhmis.ItemPrice}),
					format: openhmis.ItemPrice.prototype.format
				}
			},

			setBill: function(bill) {
				this.bill = bill;
				this.model = bill.get("lineItems");
				this.model.on("all", this.updateTotals);
				if (bill.get("status") === bill.BillStatus.PENDING)
					this.options.itemActions = ["remove", "inlineEdit"];
				else
					this.options.itemActions = [];
			},

			addOne: function(model, schema) {
				var view = openhmis.GenericListView.prototype.addOne.call(this, model, schema);
				view.$('td.field-quantity').add('td.field-price').add('td.field-total').addClass("numeric");
				if (this.newItem && view.model.cid === this.newItem.cid) {
					this.selectedItem = view;
					view.on("change", this.setupNewItem);
				}
				else
					view.on("change remove", this.bill.setUnsaved);
				return view;
			},

			itemSelected: function(itemView) {
				openhmis.GenericListView.prototype.itemSelected.call(this, itemView);
				this.updateTotals();
			},

			itemRemoved: function(item) {
				openhmis.GenericListView.prototype.itemRemoved.call(this, item);
				if (item === this.newItem) {
					this.setupNewItem();
				}
			},

			patientSelected: function(patient) {
				this.bill.set("patient", patient);
				this.focus();
			},

			setupNewItem: function(lineItemView) {
				var dept_uuid;
				// Handle adding an item from the input line
				if (lineItemView !== undefined) {
					// Prevent multiple change events causing duplicate views
					if (this.model.getByCid(lineItemView.model.cid)) return;
					lineItemView.off("change", this.setupNewItem);
					this.model.add(lineItemView.model, { silent: true });
					this.bill.setUnsaved();
					lineItemView.on("change remove", this.bill.setUnsaved);
					this.deselectAll();
					dept_uuid = lineItemView.model.get("item").get("department").id;
				}
				this.newItem = new openhmis.LineItem();
				// Don't add the item to the collection, but give it a reference
				this.newItem.collection = this.model;
				if (this.$('p.empty').length > 0)
					this.render();
				else {
					var view = this.addOne(this.newItem);
					view.focus();
				}
			},

			setupCashPointForm: function(el) {
				var cashPoint = this.bill.get("cashPoint");
				var cashPointId = cashPoint ? cashPoint.id : undefined;
				this.cashPointForm = new Backbone.Form({
					schema: {
						cashPoint: {
							type: 'Select',
							title: i18n("Cash Point") + ":",
							options: new openhmis.GenericCollection([], { model: openhmis.CashPoint })
						}
					},
					data: {
						cashPoint: cashPointId
					},
					template: "trForm",
					fieldsetTemplate: "blankFieldset"
				});
				this.cashPointForm.render();
				$(el).empty().append(this.cashPointForm.el);
				return this.cashPointForm;
			},

			updateTotals: function() {
				var total = openhmis.round(this.bill.getAdjustedTotal(), this.options.roundToNearest, this.options.roundingMode);
				var totalPaid = this.bill.getTotalPayments();
				this.$totals.html(this.totalsTemplate({
					bill: this.bill,
					total: total,
					totalPaid: totalPaid,
					formatPrice: openhmis.ItemPrice.prototype.format,
					__: i18n }))
			},

			/**
			 * @should post bill if it is pending
			 * @should add payment if the bill has already been posted
			 */
			processPayment: function(payment, options) {
				options = options ? options : {};
				var success = options.success;
				var self = this;
				options.success = function(model, resp) {
					if (self.bill.getTotalPayments() >= self.bill.getTotal())
						self.trigger("paid", self.bill);
					self.updateTotals();
					if (success) success(model, resp);
				}
				payment.set("amountTendered", payment.get("amount"));
				var paymentChange = (this.bill.getTotalPayments() + payment.get("amount")) - this.bill.getAdjustedTotal();
				if (paymentChange > 0)
					payment.set("amount", payment.get("amountTendered") - paymentChange);
				this.bill.addPayment(payment);
				if (this.bill.get("status") === this.bill.BillStatus.PENDING) {
					if (!this.postBill(options));
						this.bill.get("payments").remove(payment);
				}
				else
					payment.save([], options);
			},

			validate: function(allowEmptyBill) {
				var errors = this.bill.validate(true);
				var elMap = {
					'lineItems': [ $('#bill'), this ],
					'patient': [ $('#patient-view'),  $('#inputNode') ]
				}
				if (allowEmptyBill === true
					&& errors
					&& errors.lineItems !== undefined)
						delete errors.lineItems;
				if (errors && _.size(errors) > 0) {
					for (var e in errors)
						openhmis.validationMessage(elMap[e][0], errors[e], elMap[e][1]);
					return false;
				}
				return true;
			},

			saveBill: function(options, post) {
				options = options ? options : {};
				if (!this.validate(post)) return false;
				if (this.cashPointForm !== undefined)
					this.bill.set("cashPoint", this.cashPointForm.getValue("cashPoint"));
				// Filter out any invalid lineItems (especially the bottom)
				// entry cursor
				this.bill.get("lineItems").reset(
					this.model.filter(function(item) { return item.isClean(); }),
					{ silent: true }
				);

				if (post === true
					&& this.bill.get("billAdjusted")
					&& this.bill.get("status") === this.bill.BillStatus.PENDING)
						this._postAdjustingBill(this.bill);
				var print = options.print;
				var success = options.success;
				var error = options.error;
				var self = this;
				options.success = function(model, resp) {
					self.trigger(print ? "saveAndPrint" : "save", model);
					if (success) success(model, resp);
				}
				options.error = function(model, resp) {
					openhmis.error(resp);
					if (error) error(model, resp);
				}
				this.bill.save([], options);
				return true;
			},

			postBill: function(options) {
				return this.saveBill(options, true);
			},

			_postAdjustingBill: function(bill) {
				bill.get("billAdjusted").get("payments").each(function(payment) {
					payment.set("amountTendered", payment.get("amount"));
				});
				bill.get("payments").add(bill.get("billAdjusted").get("payments").models);
				var adjustingItems = bill.get("lineItems");
				bill.set("lineItems", bill.get("billAdjusted").get("lineItems"));
				bill.get("lineItems").add(adjustingItems.models);
				bill.set("status", bill.BillStatus.POSTED);
			},

			adjustBill: function() {
				var __ = i18n;
				if (confirm(__("Are you sure you want to adjust this bill?"))) {
					var adjustingBill = new openhmis.Bill({
						billAdjusted: this.bill.id,
						patient: this.bill.get("patient").id
					});
					// Unset status to avoid the adjusted bill from being
					// immediately set to PAID
					adjustingBill.unset("status");
					var view = this;
					adjustingBill.save([], { success: function(model, resp) {
						view.trigger("adjusted", model);
					}});
				}
			},

			printReceipt: function(event) {
				var url = openhmis.config.pageUrlRoot
					+ "receipt.form?receiptNumber=" + encodeURIComponent(this.bill.get("receiptNumber"));
				if (event) {
					if (this.bill.get("receiptNumber")) {
						window.open(url, "pdfDownload");
					}
				}
				else {
					$iframe = $('');
					$("body").append($iframe);
				}
			},

			render: function() {
				if (this.newItem) this.model.add(this.newItem, { silent: true });
				openhmis.GenericListView.prototype.render.call(this, {
					listTitle: ""
				});
				if (this.newItem) this.model.remove(this.newItem, { silent: true });
				this.$('table').addClass("bill");
				this.$totals = $('

');
				this.$('div.box').append(this.$totals);
				this.updateTotals();
				return this;
			}
		});

		openhmis.BillAndPaymentsView = Backbone.View.extend({
			className: "combineBoxes",
			initialize: function(options) {
				var __ = i18n;
				this.itemsView = new openhmis.GenericListView({
					model: this.model.get("lineItems"),
					listTitle: __("Previous Bill (%s)", this.model),
					showPaging: false,
					showRetiredOption: false
				});
				this.paymentsView = new openhmis.GenericListView({
					model: this.model.get("payments"),
					className: "paymentList",
					listTitle: "Previous Payments",
					listFields: ["dateCreatedFmt", "paymentMode", "amountFmt"],
					showPaging: false,
					showRetiredOption: false
				});
			},

			render: function() {
				this.$el.append(this.itemsView.render().el);
				this.itemsView.$("table").addClass("bill");
				this.$el.append(this.paymentsView.render().el);
				return this;
			}
		});

		return openhmis;
	}
);<|endoftext|>


<commit_before>/*
Copyright (c) 2014 Intel Corporation.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

* Redistributions of works must retain the original copyright notice, this list
  of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the original copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors
  may be used to endorse or promote products derived from this work without
  specific prior written permission.

THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Authors:
        Wang, Hongjuan <hongjuanx.wang@intel.com>

*/

var deviceReady = false;
var platformId = cordova.require('cordova/platform').id;
var pictureUrl = null;
var fileObj = null;
var fileEntry = null;
var pageStartTime = +new Date();

//default camera options
var camQualityDefault = ['quality value', 50];
var camDestinationTypeDefault = ['FILE_URI', 1];
var camPictureSourceTypeDefault = ['CAMERA', 1];
var camAllowEditDefault = ['allowEdit', false];
var camEncodingTypeDefault = ['JPEG', 0];
var camMediaTypeDefault = ['mediaType', 0];

//-------------------------------------------------------------------------
// Camera
//-------------------------------------------------------------------------

function log(value) {
  console.log(value);
 // document.getElementById('camera_status').textContent += (new Date() - pageStartTime) / 1000 + ': ' + value + '\n';
}

function clearStatus() {
  //document.getElementById('pic').innerHTML = '';
  document.getElementById('camera_image').src = 'about:blank';
  //var canvas = document.getElementById('canvas');
  // canvas.width = canvas.height = 1;
  pictureUrl = null;
  fileObj = null;
  fileEntry = null;
}

function setPicture(url, callback) {
try {
	window.atob(url);
	// if we got here it is a base64 string (DATA_URL)
	url = "data:image/jpeg;base64," + url;
} catch (e) {
	// not DATA_URL
    log('URL: ' + url.slice(0, 100));
}

  pictureUrl = url;
  var img = document.getElementById('camera_image');
  var startTime = new Date();
  img.src = url;
  img.onloadend = function() {
    log('Image tag load time: ' + (new Date() - startTime));
    callback && callback();
  };
}

function onGetPictureError(e) {
    log('Error getting picture: ' + e.code);
}

function getPictureWin(data) {
  setPicture(data);
  // TODO: Fix resolveLocalFileSystemURI to work with native-uri.
  if (pictureUrl.indexOf('file:') == 0 || pictureUrl.indexOf('content:') == 0) {
    resolveLocalFileSystemURI(data, function(e) {
      fileEntry = e;
      logCallback('resolveLocalFileSystemURI()', true)(e.toURL());
    }, logCallback('resolveLocalFileSystemURI()', false));
  } else if (pictureUrl.indexOf('data:image/jpeg;base64' == 0)) {
  	// do nothing
  } else {
    var path = pictureUrl.replace(/^file:\/\/(localhost)?/, '').replace(/%20/g, ' ');
    fileEntry = new FileEntry('image_name.png', path);
  }
}

function getPicture() {
  clearStatus();
  var options = extractOptions();
  log('Getting picture with options: ' + JSON.stringify(options));
  var popoverHandle = navigator.camera.getPicture(getPictureWin, onGetPictureError, options);

  // Reposition the popover if the orientation changes.
  window.onorientationchange = function() {
    var newPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, 0);
    popoverHandle.setPosition(newPopoverOptions);
  }
}

function uploadImage() {
  var ft = new FileTransfer(),
    uploadcomplete=0,
    progress = 0,
    options = new FileUploadOptions();
  options.fileKey="photo";
  options.fileName='test.jpg';
  options.mimeType="image/jpeg";
  ft.onprogress = function(progressEvent) {
    log('progress: ' + progressEvent.loaded + ' of ' + progressEvent.total);
  };
  var server = "http://cordova-filetransfer.jitsu.com";

  ft.upload(pictureUrl, server + '/upload', win, fail, options);
  function win(information_back){
    log('upload complete');
  }
  function fail(message) {
    log('upload failed: ' + JSON.stringify(message));
  }
}

function logCallback(apiName, success) {
  return function() {
    log('Call to ' + apiName + (success ? ' success: ' : ' failed: ') + JSON.stringify([].slice.call(arguments)));
  };
}

function extractOptions() {
  var els = document.querySelectorAll('#image-options select');
  var ret = {};
  for (var i = 0, el; el = els[i]; ++i) {
    var value = el.value;
    if (value === '') continue;
    if (el.isBool) {
      ret[el.keyName] = !!+value;
    } else {
      ret[el.keyName] = +value;
    }
  }
  return ret;
}

function createOptionsEl(name, values, selectionDefault) {
  var table = document.createElement('table');
  var tr = document.createElement('tr');
  var container = document.createElement('td');
  table.appendChild(tr);
  tr.appendChild(container);
  table.style.cssText = "border: 1px;"
  container.appendChild(document.createTextNode(name + ': '));
  var select = document.createElement('select');
  select.keyName = name;
  container.appendChild(select);

  // if we didn't get a default value, insert the blank <default> entry
  if (selectionDefault == undefined) {
    var opt = document.createElement('option');
    opt.value = '';
    opt.text = '<default>';
    select.appendChild(opt);
  }

  select.isBool = typeof values == 'boolean';
  if (select.isBool) {
    values = {'true': 1, 'false': 0};
  }

  for (var k in values) {
    var opt = document.createElement('option');
    opt.value = values[k];
    opt.textContent = k;
    if (selectionDefault) {
      if (selectionDefault[0] == k) {
        opt.selected = true;
      }
    }
    select.appendChild(opt);
  }
  var optionsDiv = document.getElementById('image-options');
  optionsDiv.appendChild(table);
}

/**
 * Function called when page has finished loading.
 */
function init() {
    document.addEventListener("deviceready", function() {
      deviceReady = true;
      createOptionsEl('Encoding Type', Camera.EncodingType, camEncodingTypeDefault);
      createOptionsEl('Media Type', Camera.MediaType, camMediaTypeDefault);
      createOptionsEl('Destination Type', Camera.DestinationType, camDestinationTypeDefault);
      createOptionsEl('Source Type', Camera.PictureSourceType, camPictureSourceTypeDefault);
    }, false);
    window.setTimeout(function() {
      if (!deviceReady) {
        alert("Error: Apache Cordova did not initialize.  Demo will not run correctly.");
      }
    },1000);
};
<commit_msg>[Cordova] enable the camera uscase selection<commit_after>/*
Copyright (c) 2014 Intel Corporation.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

* Redistributions of works must retain the original copyright notice, this list
  of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the original copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors
  may be used to endorse or promote products derived from this work without
  specific prior written permission.

THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Authors:
        Wang, Hongjuan <hongjuanx.wang@intel.com>

*/

var deviceReady = false;
var platformId = cordova.require('cordova/platform').id;
var pictureUrl = null;
var fileObj = null;
var fileEntry = null;
var pageStartTime = +new Date();

//default camera options
var camQualityDefault = ['quality value', 50];
var camDestinationTypeDefault = ['FILE_URI', 1];
var camPictureSourceTypeDefault = ['CAMERA', 1];
var camAllowEditDefault = ['allowEdit', false];
var camEncodingTypeDefault = ['JPEG', 0];
var camMediaTypeDefault = ['mediaType', 0];

//-------------------------------------------------------------------------
// Camera
//-------------------------------------------------------------------------

function log(value) {
  console.log(value);
 // document.getElementById('camera_status').textContent += (new Date() - pageStartTime) / 1000 + ': ' + value + '\n';
}

function clearStatus() {
  //document.getElementById('pic').innerHTML = '';
  document.getElementById('camera_image').src = 'about:blank';
  //var canvas = document.getElementById('canvas');
  // canvas.width = canvas.height = 1;
  pictureUrl = null;
  fileObj = null;
  fileEntry = null;
}

function setPicture(url, callback) {
try {
	window.atob(url);
	// if we got here it is a base64 string (DATA_URL)
	url = "data:image/jpeg;base64," + url;
} catch (e) {
	// not DATA_URL
    log('URL: ' + url.slice(0, 100));
}

  pictureUrl = url;
  var img = document.getElementById('camera_image');
  var startTime = new Date();
  img.src = url;
  img.onloadend = function() {
    log('Image tag load time: ' + (new Date() - startTime));
    callback && callback();
  };
}

function onGetPictureError(e) {
    log('Error getting picture: ' + e.code);
}

function getPictureWin(data) {
  setPicture(data);
  // TODO: Fix resolveLocalFileSystemURI to work with native-uri.
  if (pictureUrl.indexOf('file:') == 0 || pictureUrl.indexOf('content:') == 0) {
    resolveLocalFileSystemURI(data, function(e) {
      fileEntry = e;
      logCallback('resolveLocalFileSystemURI()', true)(e.toURL());
    }, logCallback('resolveLocalFileSystemURI()', false));
  } else if (pictureUrl.indexOf('data:image/jpeg;base64' == 0)) {
  	// do nothing
  } else {
    var path = pictureUrl.replace(/^file:\/\/(localhost)?/, '').replace(/%20/g, ' ');
    fileEntry = new FileEntry('image_name.png', path);
  }
}

function getPicture() {
  clearStatus();
  var options = extractOptions();
  log('Getting picture with options: ' + JSON.stringify(options));
  var popoverHandle = navigator.camera.getPicture(getPictureWin, onGetPictureError, options);

  // Reposition the popover if the orientation changes.
  window.onorientationchange = function() {
    var newPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, 0);
    popoverHandle.setPosition(newPopoverOptions);
  }
}

function uploadImage() {
  var ft = new FileTransfer(),
    uploadcomplete=0,
    progress = 0,
    options = new FileUploadOptions();
  options.fileKey="photo";
  options.fileName='test.jpg';
  options.mimeType="image/jpeg";
  ft.onprogress = function(progressEvent) {
    log('progress: ' + progressEvent.loaded + ' of ' + progressEvent.total);
  };
  var server = "http://cordova-filetransfer.jitsu.com";

  ft.upload(pictureUrl, server + '/upload', win, fail, options);
  function win(information_back){
    log('upload complete');
  }
  function fail(message) {
    log('upload failed: ' + JSON.stringify(message));
  }
}

function logCallback(apiName, success) {
  return function() {
    log('Call to ' + apiName + (success ? ' success: ' : ' failed: ') + JSON.stringify([].slice.call(arguments)));
  };
}

function extractOptions() {
  var els = document.querySelectorAll('#image-options select');
  var ret = {};
  for (var i = 0, el; el = els[i]; ++i) {
    var value = el.value;
    if (value === '') continue;
    if (el.isBool) {
      ret[el.keyName] = !!+value;
    } else {
      ret[el.keyName] = +value;
    }
  }
  return ret;
}

function createOptionsEl(name, values, selectionDefault) {
  var table = document.createElement('table');
  var tr = document.createElement('tr');
  var container = document.createElement('td');
  table.appendChild(tr);
  tr.appendChild(container);
  table.style.cssText = "border: 1px;"
  container.appendChild(document.createTextNode(name + ': '));
  var select = document.createElement('select');
  select.keyName = name;
  container.appendChild(select);

  // if we didn't get a default value, insert the blank <default> entry
  if (selectionDefault == undefined) {
    var opt = document.createElement('option');
    opt.value = '';
    opt.text = '<default>';
    select.appendChild(opt);
  }

  select.isBool = typeof values == 'boolean';
  if (select.isBool) {
    values = {'true': 1, 'false': 0};
  }

  for (var k in values) {
    var opt = document.createElement('option');
    opt.value = values[k];
    opt.textContent = k;
    if (selectionDefault) {
      if (selectionDefault[0] == k) {
        opt.selected = true;
      }
    }
    select.appendChild(opt);
  }
  var optionsDiv = document.getElementById('image-options');
  optionsDiv.appendChild(table);
}

/**
 * Function called when page has finished loading.
 */
function init() {
    document.addEventListener("deviceready", function() {
      deviceReady = true;
      createOptionsEl('encodingType', Camera.EncodingType, camEncodingTypeDefault);
      createOptionsEl('mediaType', Camera.MediaType, camMediaTypeDefault);
      createOptionsEl('destinationType', Camera.DestinationType, camDestinationTypeDefault);
      createOptionsEl('sourceType', Camera.PictureSourceType, camPictureSourceTypeDefault);
    }, false);
    window.setTimeout(function() {
      if (!deviceReady) {
        alert("Error: Apache Cordova did not initialize.  Demo will not run correctly.");
      }
    },1000);
};
<|endoftext|>


<commit_before>(function () {
    "use strict";

    angular.module("blocktrail.wallet")
        .controller("WalletSummaryCtrl", WalletSummaryCtrl);

    function WalletSummaryCtrl($scope, $rootScope, $q, $timeout, activeWallet, CONFIG,
                               launchService, settingsService, buyBTCService, $modal, CurrencyConverter) {

        var settings = settingsService.getReadOnlySettings();
        var transactionsListLimitStep = 15;
        var lastDateHeader = 0; // used to keep track of the last date header added
        var timeoutPromise = null;
        var timeoutDelay = 2000;

        $rootScope.pageTitle = 'TRANSACTIONS';
        $scope.walletData = activeWallet.getReadOnlyWalletData();
        $scope.isLoading = true;
        $scope.isShowNoMoreTransactions = false;
        $scope.isTwoFactorWarning = false; // display 2FA warning once every day when it's not enabled
        $scope.showBCCSweepWarning = false;
        $scope.lastDateHeader = lastDateHeader;
        $scope.buybtcPendingOrders = []; // Glidera transactions
        $scope.transactionsListLimit = transactionsListLimitStep;

        // Methods
        $scope.isHeader = isHeader;
        $scope.getTransactionHeader = getTransactionHeader;
        $scope.onShowTransaction = onShowTransaction;
        $scope.onShowMoreTransactions = onShowMoreTransactions;
        $scope.dismissBCCSweepWarning = dismissBCCSweepWarning;

        $scope.$on("$destroy", onDestroy);

        var initializingData = initData();

        if (CONFIG.NETWORK === "BCC") {
            initializingData.then(function() {
                $scope.showBCCSweepWarning = !$scope.walletData.transactions.length && !$scope.settings.hideBCCSweepWarning;
            });
        }

        /**
         * Init data
         */
        function initData() {
            return $q.all([
                $q.when($rootScope.getPrice()),
                $q.when(twoFactorWarning()),
                $q.when(getGlideraTransactions())
            ]).then(function() {
                $scope.isLoading = false;
            }, function (err) {
                console.log('err', err);
            });
        }

        function dismissBCCSweepWarning() {
            $scope.showBCCSweepWarning = false;
            settingsService.updateSettingsUp({
                hideBCCSweepWarning: true
            });
        }

        /**
         * Two factor warning
         *
         * if 2FA is turn off we display a message
         */
        function twoFactorWarning() {
            return $q.when(launchService.getAccountInfo())
                .then(function(accountInfo) {
                    var SECONDS_AGO = 86400;

                    if (!accountInfo.requires2FA) {

                        return settingsService.getSettings()
                            .then(function(settings) {
                                var last = settings.twoFactorWarningLastDisplayed;

                                if (!last || last < (new Date()).getTime() - SECONDS_AGO * 1000) {
                                    var updateSettings = {
                                        twoFactorWarningLastDisplayed: (new Date()).getTime()
                                    };

                                    settingsService.updateSettingsUp(updateSettings);

                                    $scope.isTwoFactorWarning = true;
                                }
                            });
                    }
                });
        }

        /**
         * Get glidera transactions
         *
         * TODO move this logic to Wallet class
         */
        function getGlideraTransactions() {
            return settingsService.getSettings()
                .then(function(settings) {
                    $scope.buybtcPendingOrders = [];

                    settings.glideraTransactions.forEach(function(glideraTxInfo) {
                        // don't display completed TXs, they will be part of our normal transaction history
                        if (glideraTxInfo.transactionHash || glideraTxInfo.status === "COMPLETE") {
                            return;
                        }

                        // only display TXs that are related to this wallet
                        if (glideraTxInfo.walletIdentifier !== $scope.walletData.identifier) {
                            return;
                        }

                        var order = {
                            qty: CurrencyConverter.toSatoshi(glideraTxInfo.qty, 'BTC'),
                            qtyBTC: glideraTxInfo.qty,
                            currency: glideraTxInfo.currency,
                            price: glideraTxInfo.price,
                            total: (glideraTxInfo.price * glideraTxInfo.qty).toFixed(2),
                            time: glideraTxInfo.time,
                            avatarUrl: buyBTCService.BROKERS.glidera.avatarUrl,
                            displayName: buyBTCService.BROKERS.glidera.displayName
                        };

                        $scope.buybtcPendingOrders.push(order);
                });

                // latest first
                $scope.buybtcPendingOrders.reverse();
            });
        }

        /**
         * On show more transactions
         *
         * Handler for "infinite-scroll" directive
         */
        function onShowMoreTransactions() {
            if($scope.transactionsListLimit < $scope.walletData.transactions.length) {
                $scope.transactionsListLimit = $scope.transactionsListLimit + transactionsListLimitStep;
            } else if (!$scope.isLoading && $scope.walletData.transactions.length && $scope.transactionsListLimit >= $scope.walletData.transactions.length) {
                $scope.isShowNoMoreTransactions = true;

                if(timeoutPromise) {
                    $timeout.cancel(timeoutPromise);
                }

                timeoutPromise = $timeout(function () {
                    timeoutPromise = null;
                    $scope.isShowNoMoreTransactions = false;
                }, timeoutDelay);
            }
        }

        /**
         * Is header
         *
         * @param transaction
         * @return {boolean}
         */
        function isHeader(transaction) {
            var isHeader = false;
            var date = new Date(transaction.time * 1000);

            date.setHours(0);
            date.setMinutes(0);
            date.setSeconds(0);
            date.setMilliseconds(0);

            if (lastDateHeader !== date.valueOf()) {
                lastDateHeader = date.valueOf();
                isHeader = true;
            }

            return isHeader;
        }

        /**
         * Get transaction header
         *
         * @return {number}
         */
        function getTransactionHeader() {
            return lastDateHeader;
        }

        /**
         * On show transaction
         *
         * @param transaction
         */
        function onShowTransaction(transaction) {
            $modal.open({
                controller: "WalletTransactionInfoModalCtrl",
                templateUrl: "js/modules/wallet/controllers/wallet-transaction-info-modal/wallet-transaction-info-modal.tpl.html",
                resolve: {
                    data: function() {
                        return {
                            transaction: angular.copy(transaction),
                            localCurrency: settings.localCurrency
                        }
                    }
                }
            });
        }

        /**
         * On destroy
         */
        function onDestroy() {
            if(timeoutPromise) {
                $timeout.cancel(timeoutPromise);
            }
        }
    }

})();
<commit_msg>use the isReady promise<commit_after>(function () {
    "use strict";

    angular.module("blocktrail.wallet")
        .controller("WalletSummaryCtrl", WalletSummaryCtrl);

    function WalletSummaryCtrl($scope, $rootScope, $q, $timeout, activeWallet, CONFIG,
                               launchService, settingsService, buyBTCService, $modal, CurrencyConverter) {

        var settings = settingsService.getReadOnlySettings();
        var transactionsListLimitStep = 15;
        var lastDateHeader = 0; // used to keep track of the last date header added
        var timeoutPromise = null;
        var timeoutDelay = 2000;

        $rootScope.pageTitle = 'TRANSACTIONS';
        $scope.walletData = activeWallet.getReadOnlyWalletData();
        $scope.isLoading = true;
        $scope.isShowNoMoreTransactions = false;
        $scope.isTwoFactorWarning = false; // display 2FA warning once every day when it's not enabled
        $scope.showBCCSweepWarning = false;
        $scope.lastDateHeader = lastDateHeader;
        $scope.buybtcPendingOrders = []; // Glidera transactions
        $scope.transactionsListLimit = transactionsListLimitStep;

        // Methods
        $scope.isHeader = isHeader;
        $scope.getTransactionHeader = getTransactionHeader;
        $scope.onShowTransaction = onShowTransaction;
        $scope.onShowMoreTransactions = onShowMoreTransactions;
        $scope.dismissBCCSweepWarning = dismissBCCSweepWarning;

        $scope.$on("$destroy", onDestroy);

        initData();

        if (CONFIG.NETWORK === "BCC") {
            activeWallet.isReady.then(function() {
                $scope.showBCCSweepWarning = !$scope.walletData.transactions.length && !$scope.settings.hideBCCSweepWarning;
            });
        }

        /**
         * Init data
         */
        function initData() {
            return $q.all([
                $q.when($rootScope.getPrice()),
                $q.when(twoFactorWarning()),
                $q.when(getGlideraTransactions())
            ]).then(function() {
                $scope.isLoading = false;
            }, function (err) {
                console.log('err', err);
            });
        }

        function dismissBCCSweepWarning() {
            $scope.showBCCSweepWarning = false;
            settingsService.updateSettingsUp({
                hideBCCSweepWarning: true
            });
        }

        /**
         * Two factor warning
         *
         * if 2FA is turn off we display a message
         */
        function twoFactorWarning() {
            return $q.when(launchService.getAccountInfo())
                .then(function(accountInfo) {
                    var SECONDS_AGO = 86400;

                    if (!accountInfo.requires2FA) {

                        return settingsService.getSettings()
                            .then(function(settings) {
                                var last = settings.twoFactorWarningLastDisplayed;

                                if (!last || last < (new Date()).getTime() - SECONDS_AGO * 1000) {
                                    var updateSettings = {
                                        twoFactorWarningLastDisplayed: (new Date()).getTime()
                                    };

                                    settingsService.updateSettingsUp(updateSettings);

                                    $scope.isTwoFactorWarning = true;
                                }
                            });
                    }
                });
        }

        /**
         * Get glidera transactions
         *
         * TODO move this logic to Wallet class
         */
        function getGlideraTransactions() {
            return settingsService.getSettings()
                .then(function(settings) {
                    $scope.buybtcPendingOrders = [];

                    settings.glideraTransactions.forEach(function(glideraTxInfo) {
                        // don't display completed TXs, they will be part of our normal transaction history
                        if (glideraTxInfo.transactionHash || glideraTxInfo.status === "COMPLETE") {
                            return;
                        }

                        // only display TXs that are related to this wallet
                        if (glideraTxInfo.walletIdentifier !== $scope.walletData.identifier) {
                            return;
                        }

                        var order = {
                            qty: CurrencyConverter.toSatoshi(glideraTxInfo.qty, 'BTC'),
                            qtyBTC: glideraTxInfo.qty,
                            currency: glideraTxInfo.currency,
                            price: glideraTxInfo.price,
                            total: (glideraTxInfo.price * glideraTxInfo.qty).toFixed(2),
                            time: glideraTxInfo.time,
                            avatarUrl: buyBTCService.BROKERS.glidera.avatarUrl,
                            displayName: buyBTCService.BROKERS.glidera.displayName
                        };

                        $scope.buybtcPendingOrders.push(order);
                });

                // latest first
                $scope.buybtcPendingOrders.reverse();
            });
        }

        /**
         * On show more transactions
         *
         * Handler for "infinite-scroll" directive
         */
        function onShowMoreTransactions() {
            if($scope.transactionsListLimit < $scope.walletData.transactions.length) {
                $scope.transactionsListLimit = $scope.transactionsListLimit + transactionsListLimitStep;
            } else if (!$scope.isLoading && $scope.walletData.transactions.length && $scope.transactionsListLimit >= $scope.walletData.transactions.length) {
                $scope.isShowNoMoreTransactions = true;

                if(timeoutPromise) {
                    $timeout.cancel(timeoutPromise);
                }

                timeoutPromise = $timeout(function () {
                    timeoutPromise = null;
                    $scope.isShowNoMoreTransactions = false;
                }, timeoutDelay);
            }
        }

        /**
         * Is header
         *
         * @param transaction
         * @return {boolean}
         */
        function isHeader(transaction) {
            var isHeader = false;
            var date = new Date(transaction.time * 1000);

            date.setHours(0);
            date.setMinutes(0);
            date.setSeconds(0);
            date.setMilliseconds(0);

            if (lastDateHeader !== date.valueOf()) {
                lastDateHeader = date.valueOf();
                isHeader = true;
            }

            return isHeader;
        }

        /**
         * Get transaction header
         *
         * @return {number}
         */
        function getTransactionHeader() {
            return lastDateHeader;
        }

        /**
         * On show transaction
         *
         * @param transaction
         */
        function onShowTransaction(transaction) {
            $modal.open({
                controller: "WalletTransactionInfoModalCtrl",
                templateUrl: "js/modules/wallet/controllers/wallet-transaction-info-modal/wallet-transaction-info-modal.tpl.html",
                resolve: {
                    data: function() {
                        return {
                            transaction: angular.copy(transaction),
                            localCurrency: settings.localCurrency
                        }
                    }
                }
            });
        }

        /**
         * On destroy
         */
        function onDestroy() {
            if(timeoutPromise) {
                $timeout.cancel(timeoutPromise);
            }
        }
    }

})();
<|endoftext|>


<commit_before>exports.commands {
    //example trainer card. You don't need to copy the same thing, this trainer card is really plain and simple.
    siiilver: 'silver',
    silver: function (target, user, room) {
        var avatar = getavy('siiilver');
        return cardPrint('
Siiilver
'+
        ''+avy+'', '');
    }
    /*You can even use some of the profile functions, like this one below. Its useful if you're hosting a league server.
    silver: 'silvy',
    silv: 'silvy',
    silvy: function(target, user, room, cmd) {
        if (!this.canBroadcast()) return;
        var fav = profile.checkDetails('frntiersilvy', 'ace');

        var l = profile.checkDetails('frntiersilvy', 'quote');

        var avy = getavy('frntiersilvy');

        return cardPrint('frntiersilvy', 'Fr❄ntier Silvy
' +
            '"' + l + '"

' +
            'Ace: ' + fav + '
' +
            '''+avy+'
',
            '');
    },
    /*Now while creating cards, this is where a lotta people go wrong, and end up crashing their servers and ask others how to fix the problem.
    If you see '};' after the last trainer card command, don't add a comma after the '}' which ends the last command. Those are only for commands which have another command after them.*/
};

//here are a couple of functions you'll find really handy.

//this function is used for getting the html code for displaying a user's avatar, as long as the server recognizes them. Otherwise, it won't return anything.
    function getavy(name) {
        if (Users.get(name)) {
            return ''
            }
        } else {
            return '';
        }
    }

//If the user is online at the moment, something extra will be added to the card (that is, target1). Otherwise, it'll display how long ago the user was last seen, (if he was seen at all.)
//If you don't want to use this function, just stick with the normal this.sendReplyBox instead.
    function cardPrint(name, target, target1) {
        var br = '
';
        if (target.lastIndexOf('
') === target.length - 5) br = ''
        if (!Users.get(name)) {
            return this.sendReplyBox(target + br + 'Last seen: ' + datestuff.lastSeen(name) + ' ago');
        } else {
            if (!Users.get(name).connected) {
                return this.sendReplyBox(target + br + 'Last seen: ' + datestuff.lastSeen(name) + ' ago');
            } else {
                return this.sendReplyBox(target + target1);
            }
        }
    }
<commit_msg>Update trainercards.js<commit_after>var trainercards = exports.trainercards = {
    //example trainer card. You don't need to copy the same thing, this trainer card is really plain and simple.
    siiilver: 'silver',
    silver: function (target, user, room) {
        var avatar = getavy('siiilver');
        return cardPrint('
Siiilver
'+
        ''+avy+'', '');
    }
    /*You can even use some of the profile functions, like this one below. Its useful if you're hosting a league server.
    silver: 'silvy',
    silv: 'silvy',
    silvy: function(target, user, room, cmd) {
        if (!this.canBroadcast()) return;
        var fav = profile.checkDetails('frntiersilvy', 'ace');

        var l = profile.checkDetails('frntiersilvy', 'quote');

        var avy = getavy('frntiersilvy');

        return cardPrint('frntiersilvy', 'Fr❄ntier Silvy
' +
            '"' + l + '"

' +
            'Ace: ' + fav + '
' +
            '''+avy+'
',
            '');
    },
    /*Now while creating cards, this is where a lotta people go wrong, and end up crashing their servers and ask others how to fix the problem.
    If you see '};' after the last trainer card command, don't add a comma after the '}' which ends the last command. Those are only for commands which have another command after them.*/
};

//here are a couple of functions you'll find really handy.

//this function is used for getting the html code for displaying a user's avatar, as long as the server recognizes them. Otherwise, it won't return anything.
    function getavy(name) {
        if (Users.get(name)) {
            return ''
            }
        } else {
            return '';
        }
    }

//If the user is online at the moment, something extra will be added to the card (that is, target1). Otherwise, it'll display how long ago the user was last seen, (if he was seen at all.)
//If you don't want to use this function, just stick with the normal this.sendReplyBox instead.
    function cardPrint(name, target, target1) {
        var br = '
';
        if (target.lastIndexOf('
') === target.length - 5) br = ''
        if (!Users.get(name)) {
            return this.sendReplyBox(target + br + 'Last seen: ' + datestuff.lastSeen(name) + ' ago');
        } else {
            if (!Users.get(name).connected) {
                return this.sendReplyBox(target + br + 'Last seen: ' + datestuff.lastSeen(name) + ' ago');
            } else {
                return this.sendReplyBox(target + target1);
            }
        }
    }
<|endoftext|>