<commit_before>var common = require('../casper_lib/common.js').common;

function submit_checked() {
    casper.then(function () {
        casper.waitUntilVisible('input:checked[type="checkbox"][id="id_realm_allow_message_editing"] + span', function () {
            casper.click('form.org-settings-form button.button');
        });
    });
}

function submit_unchecked() {
    casper.then(function () {
        casper.waitUntilVisible('input:not(:checked)[type="checkbox"][id="id_realm_allow_message_editing"] + span', function () {
            casper.click('form.org-settings-form button.button');
        });
    });
}

common.start_and_log_in();

// For clarity these should be different than what 08-edit uses, until
// we find a more robust way to manage DB state between tests.
var content1 = 'admin: edit test message 1';
var content2 = 'admin: edit test message 2';

// send two messages
common.then_send_message('stream', {
    stream:  'Verona',
    subject: 'edits',
    content: content1,
});
common.then_send_message('stream', {
    stream:  'Verona',
    subject: 'edits',
    content: content2,
});

casper.then(function () {
    casper.waitForSelectorText('#zhome .message_row', content1);
    casper.waitForSelectorText('#zhome .message_row', content2);
});

// wait for message to be sent
casper.then(function () {
    casper.waitFor(function () {
        return casper.evaluate(function () {
            return !current_msg_list.last().locally_echoed;
        });
    });
});

// edit the last message just sent
casper.then(function () {
    casper.evaluate(function () {
        var msg = $('#zhome .message_row:last');
        msg.find('.info').click();
        $('.popover_edit_message').click();
    });
});

var edited_value = 'admin tests: test edit';

casper.then(function () {
    casper.waitUntilVisible(".message_edit_content", function () {
        casper.evaluate(function (edited_value) {
            var msg = $('#zhome .message_row:last');
            msg.find('.message_edit_content').val(edited_value);
            msg.find('.message_edit_save').click();
        }, edited_value);
    });
});

casper.then(function () {
    // check that the message was indeed edited
    casper.waitWhileVisible("textarea.message_edit_content", function () {
        casper.test.assertSelectorHasText(".last_message .message_content", edited_value);
    });
});

// Commented out due to Issue #1243
// // edit the same message, but don't hit save this time
// casper.then(function () {
//     casper.evaluate(function () {
//         var msg = $('#zhome .message_row:last');
//         msg.find('.info').click();
//         $('.popover_edit_message').click();
//     });
// });
// casper.waitUntilVisible(".message_edit_content", function () {
//     casper.evaluate(function () {
//         var msg = $('#zhome .message_row:last');
//         msg.find('.message_edit_content').val("test RE-edited");
//     });
// });

// go to admin page
casper.then(function () {
    casper.click('#settings-dropdown');
    casper.click('a[href^="#organization"]');
});

casper.then(function () {
    casper.waitForSelector('#settings_overlay_container.show', function () {
        casper.test.info('Organization page is active');
        casper.test.assertUrlMatch(/^http:\/\/[^/]+\/#organization/, 'URL suggests we are on organization page');
    });
});

casper.then(function () {
    casper.click("li[data-section='organization-settings']");
    // deactivate "allow message editing"
    casper.waitUntilVisible('input[type="checkbox"][id="id_realm_allow_message_editing"] + span', function () {
        casper.click('input[type="checkbox"][id="id_realm_allow_message_editing"] + span');
    });
});

submit_unchecked();

casper.then(function () {
    casper.waitUntilVisible('#admin-realm-message-editing-status', function () {
        casper.test.assertSelectorHasText('#admin-realm-message-editing-status', 'Users can no longer edit their past messages!');
        casper.test.assertEval(function () {
            return !(document.querySelector('input[type="checkbox"][id="id_realm_allow_message_editing"]').checked);
        }, 'Allow message editing Setting de-activated');
    });
});

// go back to home page
casper.then(function () {
    casper.click('.settings-header .exit');
});

// Commented out due to Issue #1243
// // try to save the half-finished edit
// casper.waitUntilVisible('.message_table', function () {
//     casper.then(function () {
//         casper.evaluate(function () {
//             var msg = $('#zhome .message_row:last');
//             msg.find('.message_edit_save').click();
//         });
//     });
// });

// // make sure we get the right error message, and that the message hasn't actually changed
// casper.waitUntilVisible("div.edit_error", function () {
//     casper.test.assertSelectorHasText(
//         'div.edit_error',
//         'Error saving edit: Your organization has turned off message editing.');
//     casper.test.assertSelectorHasText(".last_message .message_content", "test edited");
// });

// Check that edit link has changed to "View source" in the popover menu
// TODO: also check that the edit icon no longer appears next to the message
casper.then(function () {
    // This somehow makes the "View source" test deterministic. It seems that
    // we are waiting on a wrong condition somewhere.
    casper.wait(1000);
});

casper.then(function () {
    casper.waitUntilVisible('.message_row');
    // Note that this could have a false positive, e.g. if all the messages aren't
    // loaded yet. See Issue #1243
    casper.evaluate(function () {
        var msg = $('#zhome .message_row:last');
        msg.find('.info').click();
    });
    casper.waitUntilVisible('.popover_edit_message', function () {
        casper.test.assertSelectorHasText('.popover_edit_message', 'View source');
    });
    casper.evaluate(function () {
        var msg = $('#zhome .message_row:last');
        msg.find('.info').click();
    });
});

// go back to admin page, and reactivate "allow message editing"
casper.then(function () {
    casper.click('#settings-dropdown');
    casper.click('a[href^="#organization"]');
});

casper.then(function () {
    casper.waitUntilVisible("li[data-section='organization-settings']", function () {
        casper.click("li[data-section='organization-settings']");
    });
});

casper.then(function () {
    casper.waitUntilVisible('input[type="checkbox"][id="id_realm_allow_message_editing"] + span', function () {
        casper.click('input[type="checkbox"][id="id_realm_allow_message_editing"] + span');
    });
});

submit_checked();

casper.then(function () {
    casper.waitUntilVisible('#admin-realm-message-editing-status', function () {
        casper.test.assertSelectorHasText('#admin-realm-message-editing-status', 'Users can now edit topics for all their messages, and the content of messages which are less than 10 minutes old.');
        casper.test.assertEval(function () {
            return document.querySelector('input[type="checkbox"][id="id_realm_allow_message_editing"]').checked;
        }, 'Allow message editing Setting re-activated');
    });
});

// Commented out due to Issue #1243
// go back home
// casper.then(function () {
//     casper.click('.settings-header .exit');
// });

// // save our edit
// casper.waitUntilVisible('.message_table', function () {
//     casper.then(function () {
//         casper.evaluate(function () {
//             var msg = $('#zhome .message_row:last');
//             msg.find('.message_edit_save').click();
//         });
//     });
// });

// // check that edit went through
// casper.waitWhileVisible("textarea.message_edit_content", function () {
//     casper.test.assertSelectorHasText(".last_message .message_content", "test RE-edited");
// });

// check that the edit link reappears in popover menu
// TODO check for edit icon next to message on hover
// casper.then(function () {
//     casper.evaluate(function () {
//         var msg = $('#zhome .message_row:last');
//         msg.find('.info').click();
//     });
//     casper.test.assertExists('.popover_edit_message');
//     casper.evaluate(function () {
//         var msg = $('#zhome .message_row:last');
//         msg.find('.info').click();
//     });
// });

// go to admin page
casper.then(function () {
    casper.test.info('Organization page');
    casper.click('a[href^="#organization"]');
    casper.test.assertUrlMatch(/^http:\/\/[^\/]+\/#organization/, 'URL suggests we are on organization page');
    casper.test.assertExists('#settings_overlay_container.show', 'Organization page is active');
});

casper.then(function () {
    casper.waitUntilVisible('form.admin-realm-form button.button');
});

// deactivate message editing
casper.then(function () {
    casper.waitUntilVisible('input[type="checkbox"][id="id_realm_allow_message_editing"] + span', function () {
        casper.evaluate(function () {
            $('input[type="text"][id="id_realm_message_content_edit_limit_minutes"]').val('4');
        });
        casper.click('input[type="checkbox"][id="id_realm_allow_message_editing"] + span');
    });
});

submit_unchecked();

casper.then(function () {
    casper.waitUntilVisible('#admin-realm-message-editing-status', function () {
        casper.test.assertSelectorHasText('#admin-realm-message-editing-status', 'Users can no longer edit their past messages!');
        casper.test.assertEval(function () {
            return !(document.querySelector('input[type="checkbox"][id="id_realm_allow_message_editing"]').checked);
        }, 'Allow message editing Setting de-activated');
        casper.test.assertEval(function () {
            return $('input[type="text"][id="id_realm_message_content_edit_limit_minutes"]').val() === '4';
        }, 'Message content edit limit now 4');
    });
});

casper.then(function () {
    // allow message editing again, and check that the old edit limit is still there
    casper.waitUntilVisible('input[type="checkbox"][id="id_realm_allow_message_editing"] + span', function () {
        casper.click('input[type="checkbox"][id="id_realm_allow_message_editing"] + span');
        casper.click('form.org-settings-form button.button');
    });
});

casper.then(function () {
    casper.waitUntilVisible('#admin-realm-message-editing-status', function () {
        casper.test.assertSelectorHasText('#admin-realm-message-editing-status', 'Users can now edit topics for all their messages, and the content of messages which are less than 4 minutes old.');
        casper.test.assertEval(function () {
            return document.querySelector('input[type="checkbox"][id="id_realm_allow_message_editing"]').checked;
        }, 'Allow message editing Setting activated');
        casper.test.assertEval(function () {
            return $('input[type="text"][id="id_realm_message_content_edit_limit_minutes"]').val() === '4';
        }, 'Message content edit limit still 4');
    });
});

casper.then(function () {
    // allow arbitrary message editing
    casper.waitUntilVisible('input[type="checkbox"][id="id_realm_allow_message_editing"] + span', function () {
        casper.evaluate(function () {
            $('input[type="text"][id="id_realm_message_content_edit_limit_minutes"]').val('0');
        });
        casper.click('form.org-settings-form button.button');
    });
});

casper.then(function () {
    casper.waitUntilVisible('#admin-realm-message-editing-status', function () {
        casper.test.assertSelectorHasText('#admin-realm-message-editing-status', 'Users can now edit the content and topics of all their past messages!');
        casper.test.assertEval(function () {
            return document.querySelector('input[type="checkbox"][id="id_realm_allow_message_editing"]').checked;
        }, 'Allow message editing Setting still activated');
        casper.test.assertEval(function () {
            return $('input[type="text"][id="id_realm_message_content_edit_limit_minutes"]').val() === '0';
        }, 'Message content edit limit is 0');
    });
});

casper.then(function () {
    // disallow message editing, with illegal edit limit value. should be fixed by admin.js
    casper.waitUntilVisible('input[type="checkbox"][id="id_realm_allow_message_editing"] + span', function () {
        casper.evaluate(function () {
            $('input[type="text"][id="id_realm_message_content_edit_limit_minutes"]').val('moo');
        });
        casper.click('input[type="checkbox"][id="id_realm_allow_message_editing"] + span');
        casper.click('form.org-settings-form button.button');
    });
});

casper.then(function () {
    casper.waitUntilVisible('#admin-realm-message-editing-status', function () {
        casper.test.assertSelectorHasText('#admin-realm-message-editing-status', 'Users can no longer edit their past messages!');
        casper.test.assertEval(function () {
            return !(document.querySelector('input[type="checkbox"][id="id_realm_allow_message_editing"]').checked);
        }, 'Allow message editing Setting de-activated');
        casper.test.assertEval(function () {
            return $('input[type="text"][id="id_realm_message_content_edit_limit_minutes"]').val() === '10';
        }, 'Message content edit limit has been reset to its default');
    });
});

common.then_log_out();

casper.run(function () {
    casper.test.done();
});
<commit_msg>casper: Add more flake protection for message editing.<commit_after>var common = require('../casper_lib/common.js').common;

function submit_checked() {
    casper.then(function () {
        casper.waitUntilVisible('input:checked[type="checkbox"][id="id_realm_allow_message_editing"] + span', function () {
            casper.click('form.org-settings-form button.button');
        });
    });
}

function submit_unchecked() {
    casper.then(function () {
        casper.waitUntilVisible('input:not(:checked)[type="checkbox"][id="id_realm_allow_message_editing"] + span', function () {
            casper.click('form.org-settings-form button.button');
        });
    });
}

common.start_and_log_in();

// For clarity these should be different than what 08-edit uses, until
// we find a more robust way to manage DB state between tests.
var content1 = 'admin: edit test message 1';
var content2 = 'admin: edit test message 2';

// send two messages
common.then_send_message('stream', {
    stream:  'Verona',
    subject: 'edits',
    content: content1,
});
common.then_send_message('stream', {
    stream:  'Verona',
    subject: 'edits',
    content: content2,
});

casper.then(function () {
    casper.waitForSelectorText('#zhome .message_row', content1);
    casper.waitForSelectorText('#zhome .message_row', content2);
});

// wait for message to be sent
casper.then(function () {
    casper.waitFor(function () {
        return casper.evaluate(function () {
            return !current_msg_list.last().locally_echoed;
        });
    });
});

// edit the last message just sent
casper.then(function () {
    casper.evaluate(function () {
        var msg = $('#zhome .message_row:last');
        msg.find('.info').click();
        $('.popover_edit_message').click();
    });
});

var edited_value = 'admin tests: test edit';

casper.then(function () {
    casper.waitUntilVisible(".message_edit_content", function () {
        casper.evaluate(function (edited_value) {
            var msg = $('#zhome .message_row:last');
            msg.find('.message_edit_content').val(edited_value);
            msg.find('.message_edit_save').click();
        }, edited_value);
    });
});

casper.then(function () {
    // check that the message was indeed edited
    casper.waitWhileVisible("textarea.message_edit_content", function () {
        casper.test.assertSelectorHasText(".last_message .message_content", edited_value);
    });
});

// Commented out due to Issue #1243
// // edit the same message, but don't hit save this time
// casper.then(function () {
//     casper.evaluate(function () {
//         var msg = $('#zhome .message_row:last');
//         msg.find('.info').click();
//         $('.popover_edit_message').click();
//     });
// });
// casper.waitUntilVisible(".message_edit_content", function () {
//     casper.evaluate(function () {
//         var msg = $('#zhome .message_row:last');
//         msg.find('.message_edit_content').val("test RE-edited");
//     });
// });

// go to admin page
casper.then(function () {
    casper.click('#settings-dropdown');
    casper.click('a[href^="#organization"]');
});

casper.then(function () {
    casper.waitForSelector('#settings_overlay_container.show', function () {
        casper.test.info('Organization page is active');
        casper.test.assertUrlMatch(/^http:\/\/[^/]+\/#organization/, 'URL suggests we are on organization page');
    });
});

casper.then(function () {
    casper.click("li[data-section='organization-settings']");
    // deactivate "allow message editing"
    casper.waitUntilVisible('input[type="checkbox"][id="id_realm_allow_message_editing"] + span', function () {
        casper.click('input[type="checkbox"][id="id_realm_allow_message_editing"] + span');
    });
});

submit_unchecked();

casper.then(function () {
    casper.waitUntilVisible('#admin-realm-message-editing-status', function () {
        casper.test.assertSelectorHasText('#admin-realm-message-editing-status', 'Users can no longer edit their past messages!');
        casper.test.assertEval(function () {
            return !(document.querySelector('input[type="checkbox"][id="id_realm_allow_message_editing"]').checked);
        }, 'Allow message editing Setting de-activated');
    });
});

// go back to home page
casper.then(function () {
    casper.click('.settings-header .exit');
});

// Commented out due to Issue #1243
// // try to save the half-finished edit
// casper.waitUntilVisible('.message_table', function () {
//     casper.then(function () {
//         casper.evaluate(function () {
//             var msg = $('#zhome .message_row:last');
//             msg.find('.message_edit_save').click();
//         });
//     });
// });

// // make sure we get the right error message, and that the message hasn't actually changed
// casper.waitUntilVisible("div.edit_error", function () {
//     casper.test.assertSelectorHasText(
//         'div.edit_error',
//         'Error saving edit: Your organization has turned off message editing.');
//     casper.test.assertSelectorHasText(".last_message .message_content", "test edited");
// });

// Check that edit link has changed to "View source" in the popover menu
// TODO: also check that the edit icon no longer appears next to the message
casper.then(function () {
    // This somehow makes the "View source" test deterministic. It seems that
    // we are waiting on a wrong condition somewhere.
    casper.wait(1000);
});

casper.then(function () {
    casper.waitUntilVisible('.message_row');
    // Note that this could have a false positive, e.g. if all the messages aren't
    // loaded yet. See Issue #1243
    casper.evaluate(function () {
        var msg = $('#zhome .message_row:last');
        msg.find('.info').click();
    });
    casper.waitUntilVisible('.popover_edit_message', function () {
        casper.test.assertSelectorHasText('.popover_edit_message', 'View source');
    });
    casper.evaluate(function () {
        var msg = $('#zhome .message_row:last');
        msg.find('.info').click();
    });
});

// go back to admin page, and reactivate "allow message editing"
casper.then(function () {
    casper.click('#settings-dropdown');
    casper.click('a[href^="#organization"]');
});

casper.then(function () {
    casper.waitUntilVisible("li[data-section='organization-settings']", function () {
        casper.click("li[data-section='organization-settings']");
    });
});

casper.then(function () {
    casper.waitUntilVisible('input[type="checkbox"][id="id_realm_allow_message_editing"] + span', function () {
        casper.click('input[type="checkbox"][id="id_realm_allow_message_editing"] + span');
    });
});

submit_checked();

casper.then(function () {
    casper.waitUntilVisible('#admin-realm-message-editing-status', function () {
        casper.test.assertSelectorHasText('#admin-realm-message-editing-status', 'Users can now edit topics for all their messages, and the content of messages which are less than 10 minutes old.');
        casper.test.assertEval(function () {
            return document.querySelector('input[type="checkbox"][id="id_realm_allow_message_editing"]').checked;
        }, 'Allow message editing Setting re-activated');
    });
});

// Commented out due to Issue #1243
// go back home
// casper.then(function () {
//     casper.click('.settings-header .exit');
// });

// // save our edit
// casper.waitUntilVisible('.message_table', function () {
//     casper.then(function () {
//         casper.evaluate(function () {
//             var msg = $('#zhome .message_row:last');
//             msg.find('.message_edit_save').click();
//         });
//     });
// });

// // check that edit went through
// casper.waitWhileVisible("textarea.message_edit_content", function () {
//     casper.test.assertSelectorHasText(".last_message .message_content", "test RE-edited");
// });

// check that the edit link reappears in popover menu
// TODO check for edit icon next to message on hover
// casper.then(function () {
//     casper.evaluate(function () {
//         var msg = $('#zhome .message_row:last');
//         msg.find('.info').click();
//     });
//     casper.test.assertExists('.popover_edit_message');
//     casper.evaluate(function () {
//         var msg = $('#zhome .message_row:last');
//         msg.find('.info').click();
//     });
// });

// go to admin page
casper.then(function () {
    casper.test.info('Organization page');
    casper.click('a[href^="#organization"]');
    casper.test.assertUrlMatch(/^http:\/\/[^\/]+\/#organization/, 'URL suggests we are on organization page');
    casper.test.assertExists('#settings_overlay_container.show', 'Organization page is active');
});

casper.then(function () {
    casper.waitUntilVisible('form.admin-realm-form button.button');
});

// deactivate message editing
casper.then(function () {
    casper.waitUntilVisible('input[type="checkbox"][id="id_realm_allow_message_editing"] + span', function () {
        casper.evaluate(function () {
            $('input[type="text"][id="id_realm_message_content_edit_limit_minutes"]').val('4');
        });
        casper.click('input[type="checkbox"][id="id_realm_allow_message_editing"] + span');
    });
});

submit_unchecked();

casper.then(function () {
    casper.waitUntilVisible('#admin-realm-message-editing-status', function () {
        casper.test.assertSelectorHasText('#admin-realm-message-editing-status', 'Users can no longer edit their past messages!');
        casper.test.assertEval(function () {
            return !(document.querySelector('input[type="checkbox"][id="id_realm_allow_message_editing"]').checked);
        }, 'Allow message editing Setting de-activated');
        casper.test.assertEval(function () {
            return $('input[type="text"][id="id_realm_message_content_edit_limit_minutes"]').val() === '4';
        }, 'Message content edit limit now 4');
    });
});

casper.then(function () {
    // allow message editing again, and check that the old edit limit is still there
    casper.waitUntilVisible('input[type="checkbox"][id="id_realm_allow_message_editing"] + span', function () {
        casper.click('input[type="checkbox"][id="id_realm_allow_message_editing"] + span');
    });
});

submit_checked();

casper.then(function () {
    casper.waitUntilVisible('#admin-realm-message-editing-status', function () {
        casper.test.assertSelectorHasText('#admin-realm-message-editing-status', 'Users can now edit topics for all their messages, and the content of messages which are less than 4 minutes old.');
        casper.test.assertEval(function () {
            return document.querySelector('input[type="checkbox"][id="id_realm_allow_message_editing"]').checked;
        }, 'Allow message editing Setting activated');
        casper.test.assertEval(function () {
            return $('input[type="text"][id="id_realm_message_content_edit_limit_minutes"]').val() === '4';
        }, 'Message content edit limit still 4');
    });
});

casper.then(function () {
    // allow arbitrary message editing
    casper.waitUntilVisible('input[type="checkbox"][id="id_realm_allow_message_editing"] + span', function () {
        casper.evaluate(function () {
            $('input[type="text"][id="id_realm_message_content_edit_limit_minutes"]').val('0');
        });
        casper.click('form.org-settings-form button.button');
    });
});

casper.then(function () {
    casper.waitUntilVisible('#admin-realm-message-editing-status', function () {
        casper.test.assertSelectorHasText('#admin-realm-message-editing-status', 'Users can now edit the content and topics of all their past messages!');
        casper.test.assertEval(function () {
            return document.querySelector('input[type="checkbox"][id="id_realm_allow_message_editing"]').checked;
        }, 'Allow message editing Setting still activated');
        casper.test.assertEval(function () {
            return $('input[type="text"][id="id_realm_message_content_edit_limit_minutes"]').val() === '0';
        }, 'Message content edit limit is 0');
    });
});

casper.then(function () {
    // disallow message editing, with illegal edit limit value. should be fixed by admin.js
    casper.waitUntilVisible('input[type="checkbox"][id="id_realm_allow_message_editing"] + span', function () {
        casper.evaluate(function () {
            $('input[type="text"][id="id_realm_message_content_edit_limit_minutes"]').val('moo');
        });
        casper.click('input[type="checkbox"][id="id_realm_allow_message_editing"] + span');
        casper.click('form.org-settings-form button.button');
    });
});

casper.then(function () {
    casper.waitUntilVisible('#admin-realm-message-editing-status', function () {
        casper.test.assertSelectorHasText('#admin-realm-message-editing-status', 'Users can no longer edit their past messages!');
        casper.test.assertEval(function () {
            return !(document.querySelector('input[type="checkbox"][id="id_realm_allow_message_editing"]').checked);
        }, 'Allow message editing Setting de-activated');
        casper.test.assertEval(function () {
            return $('input[type="text"][id="id_realm_message_content_edit_limit_minutes"]').val() === '10';
        }, 'Message content edit limit has been reset to its default');
    });
});

common.then_log_out();

casper.run(function () {
    casper.test.done();
});
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import _ from 'underscore';

export default React.createClass({
  propTypes : {
    packages: PropTypes.object.isRequired
  },

  _checkPackageIsRemoved (packageName) {
    if(this.props.packages.includes(packageName)){
      return (

You should consider removing the {packageName} package.

);
    } else {
      return (

{packageName} package was removed.

);
    }
  },

  _checkPackageIsIncluded (packageName) {
    if(!this.props.packages.includes(packageName)){
      return (

Consider using the {packageName} package.

);
    } else {
      return (

{packageName} package is included.

      );
    }
  },

  render () {
    return (

Packages:

Some package recommendations based on: https://guide.meteor.com/security.html#method-rules.

            {this._checkPackageIsRemoved('insecure')}
            {this._checkPackageIsRemoved('autopublish')}
            {this._checkPackageIsIncluded('aldeed:simple-schema')}
            {this._checkPackageIsIncluded('audit-argument-checks')}
            {this._checkPackageIsIncluded('mdg:validated-methods')}

    )
  }
});<commit_msg>Typo in mdg:validated-method<commit_after>import React, { PropTypes } from 'react';
import _ from 'underscore';

export default React.createClass({
  propTypes : {
    packages: PropTypes.object.isRequired
  },

  _checkPackageIsRemoved (packageName) {
    if(this.props.packages.includes(packageName)){
      return (

You should consider removing the {packageName} package.

);
    } else {
      return (

{packageName} package was removed.

);
    }
  },

  _checkPackageIsIncluded (packageName) {
    if(!this.props.packages.includes(packageName)){
      return (

Consider using the {packageName} package.

);
    } else {
      return (

{packageName} package is included.

      );
    }
  },

  render () {
    return (

Packages:

Some package recommendations based on: https://guide.meteor.com/security.html#method-rules.

            {this._checkPackageIsRemoved('insecure')}
            {this._checkPackageIsRemoved('autopublish')}
            {this._checkPackageIsIncluded('aldeed:simple-schema')}
            {this._checkPackageIsIncluded('audit-argument-checks')}
            {this._checkPackageIsIncluded('mdg:validated-method')}

    )
  }
});
<|endoftext|>


<commit_before>/**
 * JS used for AJAX requests on the single license detail page.
 *
 * @author Iron Bound Designs
 * @since 1.0
 */

jQuery(document).ready(function ($) {

	var status_span = $(".status span");

	status_span.editable({
		type       : 'select',
		pk         : ITELIC.key,
		name       : 'status',
		source     : ITELIC.statuses,
		showbuttons: false,
		placement  : "top",
		title      : ' ',
		mode       : 'inline',
		url        : function (params) {
			return editable_ajax(params);
		},
		success    : function (response, newValue) {
			return editable_success_callback(response, newValue);
		}
	});

	var expiresArgs = {
		type       : 'date',
		pk         : ITELIC.key,
		name       : 'expires',
		placement  : "bottom",
		title      : ' ',
		showbuttons: false,
		clear      : false,
		mode       : 'inline',
		datepicker : {
			prevText   : '',
			nextText   : '',
			minDate    : 0,
			changeMonth: false,
			changeYear : false,
			showOn     : 'both',
			onSelect   : function () {
				$('.expires input.hasDatepicker').focus();
			}
		},
		viewformat : ITELIC.df,
		url        : function (params) {
			return editable_ajax(params);
		},
		success    : function (response, newValue) {

			if (newValue && Modernizr.touchevents) {
				newValue = $.datepicker.formatDate($(".expires h3").data('df'), new Date(newValue));
			}

			return editable_success_callback(response, newValue);
		}
	};

	if (Modernizr.touchevents && Modernizr.inputtypes.date) {
		expiresArgs.type = 'text';
		expiresArgs.tpl = '<input type="date">';

		$(document).on('blur', '.expires .editable-input input[type="date"]', function () {

			$(".expires .editableform").submit();
		});
	}

	$(".expires h3").editable(expiresArgs);

	$(".max-activations h3").editable({
		type       : 'number',
		pk         : ITELIC.key,
		name       : 'max',
		placement  : "bottom",
		title      : ' ',
		showbuttons: false,
		mode       : 'inline',
		clear      : false,
		url        : function (params) {
			return editable_ajax(params);
		},
		success    : function (response, newValue) {

			if (newValue == 0 || newValue == '') {
				newValue = 'Unlimited';
			}

			return editable_success_callback(response, newValue);
		}
	});

	/**
	 * Callback function that parses the WP Ajax response.
	 *
	 * @param response
	 * @param newValue
	 * @returns {*}
	 */
	function editable_success_callback(response, newValue) {
		if (!response.success) {
			alert(response.data.message);
			return false;
		} else {
			return {"newValue": newValue};
		}
	}

	/**
	 * Callback function that processes a change from editable
	 * and posts it to a WP Ajax handle.
	 *
	 * @param params
	 * @returns {$.promise|*}
	 */
	function editable_ajax(params) {
		var data = {
			action: 'itelic_admin_licenses_single_update',
			key   : ITELIC.key,
			prop  : params.name,
			val   : params.value,
			nonce : ITELIC.update_nonce
		};

		return $.post(ITELIC.ajax, data);
	}

	status_span.on('shown', function (e, editable) {
		$(this).closest('.status').addClass('status-hovered');
	});

	status_span.on('hidden', function (e, editable) {
		$(this).closest('.status').removeClass('status-hovered');
	});

	status_span.on('save', function (e, params) {
		var container = $(this).closest('.status');

		$.each($.parseJSON(ITELIC.statuses), function (key, value) {
			container.removeClass('status-' + key);
		});

		container.addClass('status-' + params.newValue);
	});

	$(document).on('keypress', '#remote-activate-location', function (e) {

		var keycode = (e.keyCode ? e.keyCode : e.which);

		if (keycode == '13') {
			$("#remote-activate-submit").click();
		}
	});

	$(document).on('click', '#remote-activate-submit', function (e) {

		e.preventDefault();

		var data = {
			action  : 'itelic_admin_licenses_single_activate',
			location: $("#remote-activate-location").val(),
			key     : $("#remote-activate-key").val(),
			nonce   : $("#_wpnonce").val()
		};

		var button = $(this);
		button.prop('disabled', true);

		$.post(ITELIC.ajax, data, function (response) {

			button.prop('disabled', false);

			if (!response.success) {
				alert(response.data.message);
			} else {
				var html = response.data.html;

				$("#activations-table tr:last").after(html);

				$("#remote-activate-location").val("");
			}
		});
	});

	$(document).on('click', '.deactivate', function (e) {

		e.preventDefault();

		var link = $(this);

		var i = 0;
		var originalText = link.text();
		link.text(ITELIC.disabling);

		/**
		 * Animate the working text to append 3 '.'
		 * then revert.
		 *
		 * @type {number}
		 */
		var loading = setInterval(function () {

			link.append(".");
			i++;

			if (i == 4) {
				link.text(ITELIC.disabling);
				i = 0;
			}

		}, 500);

		var data = {
			action: 'itelic_admin_licenses_single_deactivate',
			id    : link.data('id'),
			key   : $("#remote-activate-key").val(),
			nonce : link.data('nonce')
		};

		$.post(ITELIC.ajax, data, function (response) {

			if (!response.success) {
				alert(response.data.message);
			} else {
				var html = response.data.html;

				var row = link.closest('tr');
				row.replaceWith(html);
			}

			clearTimeout(loading);
			link.text(originalText);
		});
	});

	$(document).on('click', '.remove-item', function (e) {

		e.preventDefault();

		var button = $(this);

		var degree = 0, timer;

		rotate();
		function rotate() {

			button.css({WebkitTransform: 'rotate(' + degree + 'deg)'});
			button.css({'-moz-transform': 'rotate(' + degree + 'deg)'});
			timer = setTimeout(function () {
				++degree;
				rotate();
			}, 1);
		}

		var data = {
			action: 'itelic_admin_licenses_single_delete',
			id    : button.data('id'),
			key   : $("#remote-activate-key").val(),
			nonce : button.data('nonce')
		};

		$.post(ITELIC.ajax, data, function (response) {

			if (!response.success) {
				alert(response.data.message);
			} else {
				var row = button.closest('tr');
				row.remove();
			}

			clearTimeout(timer);
			button.css({WebkitTransform: 'rotate(' + 0 + 'deg)'});
			button.css({'-moz-transform': 'rotate(' + 0 + 'deg)'});
		});
	});
});
<commit_msg>Fix how we add rows to the activation table, so the new rows appear in the tbody not thead.<commit_after>/**
 * JS used for AJAX requests on the single license detail page.
 *
 * @author Iron Bound Designs
 * @since 1.0
 */

jQuery(document).ready(function ($) {

	var status_span = $(".status span");

	status_span.editable({
		type       : 'select',
		pk         : ITELIC.key,
		name       : 'status',
		source     : ITELIC.statuses,
		showbuttons: false,
		placement  : "top",
		title      : ' ',
		mode       : 'inline',
		url        : function (params) {
			return editable_ajax(params);
		},
		success    : function (response, newValue) {
			return editable_success_callback(response, newValue);
		}
	});

	var expiresArgs = {
		type       : 'date',
		pk         : ITELIC.key,
		name       : 'expires',
		placement  : "bottom",
		title      : ' ',
		showbuttons: false,
		clear      : false,
		mode       : 'inline',
		datepicker : {
			prevText   : '',
			nextText   : '',
			minDate    : 0,
			changeMonth: false,
			changeYear : false,
			showOn     : 'both',
			onSelect   : function () {
				$('.expires input.hasDatepicker').focus();
			}
		},
		viewformat : ITELIC.df,
		url        : function (params) {
			return editable_ajax(params);
		},
		success    : function (response, newValue) {

			if (newValue && Modernizr.touchevents) {
				newValue = $.datepicker.formatDate($(".expires h3").data('df'), new Date(newValue));
			}

			return editable_success_callback(response, newValue);
		}
	};

	if (Modernizr.touchevents && Modernizr.inputtypes.date) {
		expiresArgs.type = 'text';
		expiresArgs.tpl = '<input type="date">';

		$(document).on('blur', '.expires .editable-input input[type="date"]', function () {

			$(".expires .editableform").submit();
		});
	}

	$(".expires h3").editable(expiresArgs);

	$(".max-activations h3").editable({
		type       : 'number',
		pk         : ITELIC.key,
		name       : 'max',
		placement  : "bottom",
		title      : ' ',
		showbuttons: false,
		mode       : 'inline',
		clear      : false,
		url        : function (params) {
			return editable_ajax(params);
		},
		success    : function (response, newValue) {

			if (newValue == 0 || newValue == '') {
				newValue = 'Unlimited';
			}

			return editable_success_callback(response, newValue);
		}
	});

	/**
	 * Callback function that parses the WP Ajax response.
	 *
	 * @param response
	 * @param newValue
	 * @returns {*}
	 */
	function editable_success_callback(response, newValue) {
		if (!response.success) {
			alert(response.data.message);
			return false;
		} else {
			return {"newValue": newValue};
		}
	}

	/**
	 * Callback function that processes a change from editable
	 * and posts it to a WP Ajax handle.
	 *
	 * @param params
	 * @returns {$.promise|*}
	 */
	function editable_ajax(params) {
		var data = {
			action: 'itelic_admin_licenses_single_update',
			key   : ITELIC.key,
			prop  : params.name,
			val   : params.value,
			nonce : ITELIC.update_nonce
		};

		return $.post(ITELIC.ajax, data);
	}

	status_span.on('shown', function (e, editable) {
		$(this).closest('.status').addClass('status-hovered');
	});

	status_span.on('hidden', function (e, editable) {
		$(this).closest('.status').removeClass('status-hovered');
	});

	status_span.on('save', function (e, params) {
		var container = $(this).closest('.status');

		$.each($.parseJSON(ITELIC.statuses), function (key, value) {
			container.removeClass('status-' + key);
		});

		container.addClass('status-' + params.newValue);
	});

	$(document).on('keypress', '#remote-activate-location', function (e) {

		var keycode = (e.keyCode ? e.keyCode : e.which);

		if (keycode == '13') {
			$("#remote-activate-submit").click();
		}
	});

	$(document).on('click', '#remote-activate-submit', function (e) {

		e.preventDefault();

		var data = {
			action  : 'itelic_admin_licenses_single_activate',
			location: $("#remote-activate-location").val(),
			key     : $("#remote-activate-key").val(),
			nonce   : $("#_wpnonce").val()
		};

		var button = $(this);
		button.prop('disabled', true);

		$.post(ITELIC.ajax, data, function (response) {

			button.prop('disabled', false);

			if (!response.success) {
				alert(response.data.message);
			} else {
				var html = response.data.html;

				$("#activations-table tbody:last-child").append(html);

				$("#remote-activate-location").val("");
			}
		});
	});

	$(document).on('click', '.deactivate', function (e) {

		e.preventDefault();

		var link = $(this);

		var i = 0;
		var originalText = link.text();
		link.text(ITELIC.disabling);

		/**
		 * Animate the working text to append 3 '.'
		 * then revert.
		 *
		 * @type {number}
		 */
		var loading = setInterval(function () {

			link.append(".");
			i++;

			if (i == 4) {
				link.text(ITELIC.disabling);
				i = 0;
			}

		}, 500);

		var data = {
			action: 'itelic_admin_licenses_single_deactivate',
			id    : link.data('id'),
			key   : $("#remote-activate-key").val(),
			nonce : link.data('nonce')
		};

		$.post(ITELIC.ajax, data, function (response) {

			if (!response.success) {
				alert(response.data.message);
			} else {
				var html = response.data.html;

				var row = link.closest('tr');
				row.replaceWith(html);
			}

			clearTimeout(loading);
			link.text(originalText);
		});
	});

	$(document).on('click', '.remove-item', function (e) {

		e.preventDefault();

		var button = $(this);

		var degree = 0, timer;

		rotate();
		function rotate() {

			button.css({WebkitTransform: 'rotate(' + degree + 'deg)'});
			button.css({'-moz-transform': 'rotate(' + degree + 'deg)'});
			timer = setTimeout(function () {
				++degree;
				rotate();
			}, 1);
		}

		var data = {
			action: 'itelic_admin_licenses_single_delete',
			id    : button.data('id'),
			key   : $("#remote-activate-key").val(),
			nonce : button.data('nonce')
		};

		$.post(ITELIC.ajax, data, function (response) {

			if (!response.success) {
				alert(response.data.message);
			} else {
				var row = button.closest('tr');
				row.remove();
			}

			clearTimeout(timer);
			button.css({WebkitTransform: 'rotate(' + 0 + 'deg)'});
			button.css({'-moz-transform': 'rotate(' + 0 + 'deg)'});
		});
	});
});
<|endoftext|>


<commit_before>
function startTime(d, sun) {
	return sun.sunsetStart }
function endTime(d) {
	var end = new Date(d)
	switch(d.getDay()) {
		case 0: case 1: case 2: case 3: case 4:
			end.setHours(23, 15)
			break
		default:
			end.setDate(end.getDate() + 1)
			end.setHours(0, 0)
			break }
	return end }
function dateRepr(d) {
	return [d.getFullYear(), d.getMonth(), d.getDate()].join("-") }

// export a function that is run daily
// use sunTimes to calculate when the sun
// comes up/down on a lat/long.
// return: [lightname, state, desc, time]

// keep in mind that these descriptions should not clash with any
// other ones you're using, because every schedule item with the same
// ones will be removed.
function timesForDay(day, sunTimes) {
	var sun = sunTimes(52.22, 5.15)
	var repr = dateRepr(day)
	var start = startTime(day, sun)
	var end = endTime(day, sun)
	return [
		/*['your_light', true, "sunset " + repr, start],
		  ['your_light', false, "night " + repr, end] */]}

module.exports = timesForDay
<commit_msg>remove executable bit from sun_sched example<commit_after>
function startTime(d, sun) {
	return sun.sunsetStart }
function endTime(d) {
	var end = new Date(d)
	switch(d.getDay()) {
		case 0: case 1: case 2: case 3: case 4:
			end.setHours(23, 15)
			break
		default:
			end.setDate(end.getDate() + 1)
			end.setHours(0, 0)
			break }
	return end }
function dateRepr(d) {
	return [d.getFullYear(), d.getMonth(), d.getDate()].join("-") }

// export a function that is run daily
// use sunTimes to calculate when the sun
// comes up/down on a lat/long.
// return: [lightname, state, desc, time]

// keep in mind that these descriptions should not clash with any
// other ones you're using, because every schedule item with the same
// ones will be removed.
function timesForDay(day, sunTimes) {
	var sun = sunTimes(52.22, 5.15)
	var repr = dateRepr(day)
	var start = startTime(day, sun)
	var end = endTime(day, sun)
	return [
		/*['your_light', true, "sunset " + repr, start],
		  ['your_light', false, "night " + repr, end] */]}

module.exports = timesForDay
<|endoftext|>


<commit_before>var words = {
	plus : "",
	minus : "",
	multiplyBy: "",
	divideBy: ""
}

var selectedOption = 0;
var numberOfOptions = 0;

function getRelevantWords(word)
{
	var wordArray = Object.getOwnPropertyNames(words);
	var relevantWords = [];
	for(var i = 0; i < wordArray.length; i++)
	{
		if(wordArray[i].toLowerCase().substr(0, word.length) == word.toLowerCase())
		{
			relevantWords.push(wordArray[i]);
		}
	}
	return relevantWords;
}

function optionString(item, i, classText)
{
	var selectedString = "";

	if(classText != null && classText != undefined)
	{
		selectedString = classText;
	}

	return "
" + item + "
";
}

function fullOptionString(items)
{
	selectedOption = 0;
	numberOfOptions = items.length;

	var result = "";

	for(var i = 0; i < items.length; i++)
	{
		if(i == 0){ result += optionString(items[i], i, "selected") }
		else{	result += optionString(items[i], i); }
	}
	return result;
}

function autoComplete()
{
	$("#math-words").removeClass("hidden");

	var typedText = $("textarea").val();

	var relevantWord =  typedText.split(' ').pop();

	$("#math-words").html( fullOptionString( getRelevantWords(relevantWord) ));
}

function SetCursorEnd(tID) {
    tID += "";
    $(tID).focus();
    var t = $(tID).val();
    if (t.length == 0) { return; }
    $(tID).val("");
    $(tID).val(t);
    $(tID).scrollTop($(tID)[0].scrollHeight);
}

function replaceText(replacementText)
{
	var typedText = $("textarea").val();
	var index = typedText.lastIndexOf(" ");
	if(index == null || index == undefined)	{
		index = 1;
	}
	var resultText = typedText.substr(0, index) + " " + replacementText;
	$("textarea").val(resultText);
	SetCursorEnd("#code-text");
}

$('body').on('click', '.ac-option', function() {
	replaceText($(this).text());
});

$('textarea').on( 'keydown', function( e ) {
    if( e.which == 9 ) {
    	e.preventDefault();
        console.log( e.target.href );

        replaceText($(".ac-option.selected").text());
    }
} )
.keyup(function(e) {
    if( e.which == 40 ){
    	selectedOption = (selectedOption + 1) % numberOfOptions;
    	$(".ac-option").removeClass("selected");
    	$("#aco" + selectedOption).addClass("selected");
    }
    if( e.which == 38 ){
    	selectedOption = (selectedOption + numberOfOptions - 1) % numberOfOptions;
    	$(".ac-option").removeClass("selected");
    	$("#aco" + selectedOption).addClass("selected");
    }
    return false;
});
<commit_msg>Update autocomplete.js<commit_after>var words = {
	plus : "",
	minus : "",
	multiplyBy: "",
	divideBy: ""
}

var selectedOption = 0;
var numberOfOptions = 0;

function getRelevantWords(word)
{
	var wordArray = Object.getOwnPropertyNames(words);
	var relevantWords = [];
	for(var i = 0; i < wordArray.length; i++)
	{
		if(wordArray[i].toLowerCase().substr(0, word.length) == word.toLowerCase())
		{
			relevantWords.push(wordArray[i]);
		}
	}
	return relevantWords;
}

function optionString(item, i, classText)
{
	var selectedString = "";

	if(classText != null && classText != undefined)
	{
		selectedString = classText;
	}

	return "
" + item + "
";
}

function fullOptionString(items)
{
	selectedOption = 0;
	numberOfOptions = items.length;

	var result = "";

	for(var i = 0; i < items.length; i++)
	{
		if(i == 0){ result += optionString(items[i], i, "selected") }
		else{	result += optionString(items[i], i); }
	}
	return result;
}

function autoComplete(e)
{
	if( e.which != 40 && e.which != 38 )
	{
		$("#math-words").removeClass("hidden");

		var typedText = $("textarea").val();

		var relevantWord =  typedText.split(' ').pop();

		$("#math-words").html( fullOptionString( getRelevantWords(relevantWord) ));
	}
}

function SetCursorEnd(tID) {
    tID += "";
    $(tID).focus();
    var t = $(tID).val();
    if (t.length == 0) { return; }
    $(tID).val("");
    $(tID).val(t);
    $(tID).scrollTop($(tID)[0].scrollHeight);
}

function replaceText(replacementText)
{
	var typedText = $("textarea").val();
	var index = typedText.lastIndexOf(" ");
	if(index == null || index == undefined)	{
		index = 1;
	}
	var resultText = typedText.substr(0, index) + " " + replacementText;
	$("textarea").val(resultText);
	SetCursorEnd("#code-text");
}

$('body').on('click', '.ac-option', function() {
	replaceText($(this).text());
});

$('textarea').on( 'keydown', function( e ) {
    if( e.which == 9 ) {
    	e.preventDefault();
        console.log( e.target.href );

        replaceText($(".ac-option.selected").text());
    }
} )
.keyup(function(e) {
    if( e.which == 40 ){
    	selectedOption = (selectedOption + 1) % numberOfOptions;
    	$(".ac-option").removeClass("selected");
    	$("#aco" + selectedOption).addClass("selected");
    }
    if( e.which == 38 ){
    	selectedOption = (selectedOption + numberOfOptions - 1) % numberOfOptions;
    	$(".ac-option").removeClass("selected");
    	$("#aco" + selectedOption).addClass("selected");
    }
    return false;
});
<|endoftext|>


<commit_before>import EmberObject from '@ember/object';
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';

module('Integration | Component | course sessions', function(hooks) {
  setupRenderingTest(hooks);

  test('it renders', async function(assert) {
    const title = '.title';
    const course = EmberObject.create({
      hasMany() {
        return {
          ids(){
            return [];
          }
        };
      }
    });

    this.set('course', course);
    this.set('nothing', ()=>{});
    await render(hbs`<CourseSessions
      @course={{course}}
      @sortBy="title"
      @setSortBy={{action nothing}}
      @filterBy={{null}}
      @setFilterBy={{action nothing}}
    />`);

    assert.dom(title).hasText('Sessions (0)');
  });
});
<commit_msg>Use a real model in test<commit_after>import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
import { setupMirage } from 'ember-cli-mirage/test-support';

module('Integration | Component | course sessions', function(hooks) {
  setupRenderingTest(hooks);
  setupMirage(hooks);

  test('it renders', async function(assert) {
    const title = '.title';
    const school = this.server.create('school');
    const course = this.server.create('course', { school });
    const courseModel = await this.owner.lookup('service:store').find('course', course.id);

    this.set('course', courseModel);
    this.set('nothing', ()=>{});
    await render(hbs`<CourseSessions
      @course={{course}}
      @sortBy="title"
      @setSortBy={{action nothing}}
      @filterBy={{null}}
      @setFilterBy={{action nothing}}
    />`);

    assert.dom(title).hasText('Sessions (0)');
  });
});
<|endoftext|>


<commit_before>/**
 * @module app.Theme
 */
/**
 * @fileoverview This service keeps and share the state of the theme.
 */

import appModule from './module.js';

/**
 * @constructor
 * @param {angular.$window} $window Global Scope.
 * @param {ngeo.statemanager.Location} ngeoLocation ngeo Location service.
 * @param {app.Themes} appThemes The themes services.
 * @ngInject
 */
const exports = function($window, ngeoLocation, appThemes) {

  /**
   * @const
   * @private
   * @type {Object}
   */
  this.piwikSiteIdLookup_ = {
    'eau': 6,
    'tourisme': 7,
    'emwelt': 8,
    'agriculture': 9,
    'prof': 10,
    'go': 11,
    'm': 12,
    'at': 16,
    'map': 18,
    'main': 18,
    'pag': 19,
    'cadastre_hertzien': 25,
    'atlas_demographique': 29,
    'urban_farming': 30,
    'logement': 32,
    'energie': 40
  };

  /**
   * @type {angular.$window}
   * @private
   */
  this.window_ = $window;

  /**
   * @type {app.Themes}
   * @private
   */
  this.appThemes_ = appThemes;

  /**
   * @type {string}
   * @private
   */
  this.currentTheme_ = exports.DEFAULT_THEME_;

  /**
   * @type {ngeo.statemanager.Location}
   * @private
   */
  this.ngeoLocation_ = ngeoLocation;
};

/**
 * @param {string} themeId The id of the theme.
 */
exports.prototype.setCurrentTheme = function(themeId) {
  this.currentTheme_ = themeId;

  var piwikSiteId = this.piwikSiteIdLookup_[this.currentTheme_];
  var isApp =
    location.search.includes('localforage=android') ||
    location.search.includes('localforage=ios') ||
    location.search.includes('applogin=yes');
  if (isApp) {
    piwikSiteId = this.piwikSiteIdLookup_['m'];
  }
  if (piwikSiteId === undefined || piwikSiteId === null) {
    piwikSiteId = this.piwikSiteIdLookup_[exports.DEFAULT_THEME_];
  }
  var piwik = /** @type {Piwik} */ (this.window_['_paq']);
  piwik.push(['setSiteId', piwikSiteId]);
  piwik.push(['setDocumentTitle', themeId]);
  piwik.push(['trackPageView']);

  this.setLocationPath_(this.currentTheme_);
};

/**
 * @return {string} themeId The id of the theme.
 */
exports.prototype.getCurrentTheme = function() {
  return this.currentTheme_;
};

/**
 * Encode the theme name.
 * @param {string} theme The theme to encode.
 * @return {string} The theme.
 * @export
 */
exports.prototype.encodeThemeName = function(theme) {
  if (theme !== undefined) {
    return theme.replace(/\s+/g, '_');
  }
  return theme;
};

/**
 * @return {string} themeId The id of the theme.
 */
exports.prototype.getDefaultTheme = function() {
  return exports.DEFAULT_THEME_;
};

/**
 * @param {string} themeId The theme id to set in the path of the URL.
 * @private
 */
exports.prototype.setLocationPath_ = function(themeId) {
  var pathElements = this.ngeoLocation_.getPath().split('/');
  console.assert(pathElements.length > 1);
  if (pathElements[pathElements.length - 1] === '') {
    // case where the path is just "/"
    pathElements.splice(pathElements.length - 1);
  }
  if (this.themeInUrl(pathElements)) {
    pathElements[pathElements.length - 1] = themeId;
  } else {
    pathElements.push('theme', themeId);
  }
  this.ngeoLocation_.setPath(pathElements.join('/'));
};

/**
 * Return true if there is a theme specified in the URL path.
 * @param {Array.<string>} pathElements Array of path elements.
 * @return {boolean} theme in path.
 */
exports.prototype.themeInUrl = function(pathElements) {
  var indexOfTheme = pathElements.indexOf('theme');
  return indexOfTheme >= 0 &&
      pathElements.indexOf('theme') == pathElements.length - 2;
};

/**
 * @const
 * @private
 */
exports.DEFAULT_THEME_ = 'main';

appModule.service('appTheme', exports);

export default exports;
<commit_msg>Set piwik id dedicated to embedded mode<commit_after>/**
 * @module app.Theme
 */
/**
 * @fileoverview This service keeps and share the state of the theme.
 */

import appModule from './module.js';

/**
 * @constructor
 * @param {angular.$window} $window Global Scope.
 * @param {ngeo.statemanager.Location} ngeoLocation ngeo Location service.
 * @param {app.Themes} appThemes The themes services.
 * @ngInject
 */
const exports = function($window, ngeoLocation, appThemes) {

  /**
   * @const
   * @private
   * @type {Object}
   */
  this.piwikSiteIdLookup_ = {
    'eau': 6,
    'tourisme': 7,
    'emwelt': 8,
    'agriculture': 9,
    'prof': 10,
    'go': 11,
    'm': 12,
    'at': 16,
    'map': 18,
    'main': 18,
    'pag': 19,
    'cadastre_hertzien': 25,
    'atlas_demographique': 29,
    'urban_farming': 30,
    'logement': 32,
    'energie': 40,
    'embedded': 44
  };

  /**
   * @type {angular.$window}
   * @private
   */
  this.window_ = $window;

  /**
   * @type {app.Themes}
   * @private
   */
  this.appThemes_ = appThemes;

  /**
   * @type {string}
   * @private
   */
  this.currentTheme_ = exports.DEFAULT_THEME_;

  /**
   * @type {ngeo.statemanager.Location}
   * @private
   */
  this.ngeoLocation_ = ngeoLocation;
};

/**
 * @param {string} themeId The id of the theme.
 */
exports.prototype.setCurrentTheme = function(themeId) {
  this.currentTheme_ = themeId;

  var piwikSiteId = this.piwikSiteIdLookup_[this.currentTheme_];
  if (!!(new URL(window.location).searchParams.get('embedded'))) {
    piwikSiteId = this.piwikSiteIdLookup_['embedded'];
  }
  var isApp =
    location.search.includes('localforage=android') ||
    location.search.includes('localforage=ios') ||
    location.search.includes('applogin=yes');
  if (isApp) {
    piwikSiteId = this.piwikSiteIdLookup_['m'];
  }
  if (piwikSiteId === undefined || piwikSiteId === null) {
    piwikSiteId = this.piwikSiteIdLookup_[exports.DEFAULT_THEME_];
  }
  var piwik = /** @type {Piwik} */ (this.window_['_paq']);
  piwik.push(['setSiteId', piwikSiteId]);
  piwik.push(['setDocumentTitle', themeId]);
  piwik.push(['trackPageView']);

  this.setLocationPath_(this.currentTheme_);
};

/**
 * @return {string} themeId The id of the theme.
 */
exports.prototype.getCurrentTheme = function() {
  return this.currentTheme_;
};

/**
 * Encode the theme name.
 * @param {string} theme The theme to encode.
 * @return {string} The theme.
 * @export
 */
exports.prototype.encodeThemeName = function(theme) {
  if (theme !== undefined) {
    return theme.replace(/\s+/g, '_');
  }
  return theme;
};

/**
 * @return {string} themeId The id of the theme.
 */
exports.prototype.getDefaultTheme = function() {
  return exports.DEFAULT_THEME_;
};

/**
 * @param {string} themeId The theme id to set in the path of the URL.
 * @private
 */
exports.prototype.setLocationPath_ = function(themeId) {
  var pathElements = this.ngeoLocation_.getPath().split('/');
  console.assert(pathElements.length > 1);
  if (pathElements[pathElements.length - 1] === '') {
    // case where the path is just "/"
    pathElements.splice(pathElements.length - 1);
  }
  if (this.themeInUrl(pathElements)) {
    pathElements[pathElements.length - 1] = themeId;
  } else {
    pathElements.push('theme', themeId);
  }
  this.ngeoLocation_.setPath(pathElements.join('/'));
};

/**
 * Return true if there is a theme specified in the URL path.
 * @param {Array.<string>} pathElements Array of path elements.
 * @return {boolean} theme in path.
 */
exports.prototype.themeInUrl = function(pathElements) {
  var indexOfTheme = pathElements.indexOf('theme');
  return indexOfTheme >= 0 &&
      pathElements.indexOf('theme') == pathElements.length - 2;
};

/**
 * @const
 * @private
 */
exports.DEFAULT_THEME_ = 'main';

appModule.service('appTheme', exports);

export default exports;
<|endoftext|>


<commit_before>// Find urls within selected domain in posts
//

'use strict';

const _        = require('lodash');
const argparse = require('argparse');
const Promise  = require('bluebird');
const mongoose = require('mongoose');
const pump     = require('pump');
const stream   = require('stream');
const URL      = require('url');

let parser = new argparse.ArgumentParser();

parser.addArgument(
  [ '-d', '--db' ],
  {
    help: 'database name',
    defaultValue: 'nodeca'
  }
);

parser.addArgument(
  [ '-c', '--cutoff' ],
  {
    help: 'cutoff (days)',
    type: 'int'
  }
);

parser.addArgument(
  'domain',
  {
    help: 'domain name'
  }
);

let args = parser.parseArgs();

mongoose.Promise = Promise;

Promise.coroutine(function* () {
  yield mongoose.connect('mongodb://localhost/' + args.db);

  let Post = mongoose.model('forum.Post', new mongoose.Schema());

  let regexp_search = new RegExp('href="https?:\\/\\/[^\\/]*' + _.escapeRegExp(args.domain));

  let query = { html: regexp_search };

  if (args.cutoff) {
    let ts = Date.now() / 1000 - args.cutoff * 24 * 60 * 60;
    let min_objectid = new mongoose.Types.ObjectId(Math.floor(ts).toString(16) + '0000000000000000');

    query._id = { $gt: min_objectid };
  }

  yield Promise.fromCallback(callback => pump(
    Post.find(query).lean(true).cursor(),

    new stream.Writable({
      objectMode: true,
      write(post, encoding, callback) {
        let urls = post.html.match(/href="[^"]+"/g)
                     .map(href => _.unescape(href.replace(/^href="|"$/g, '')));

        urls.forEach(url => {
          let parsed = URL.parse(url);

          if (parsed.host && parsed.host.includes(args.domain)) {
            /* eslint-disable no-console */
            console.log(url);
          }
        });

        callback();
      }
    }),

    callback
  ));

  yield mongoose.disconnect();
})();
<commit_msg>find_urls: option to show long links only<commit_after>// Find urls within selected domain in posts
//

'use strict';

const _        = require('lodash');
const argparse = require('argparse');
const Promise  = require('bluebird');
const mongoose = require('mongoose');
const pump     = require('pump');
const stream   = require('stream');
const URL      = require('url');

let parser = new argparse.ArgumentParser();

parser.addArgument(
  [ '-d', '--db' ],
  {
    help: 'database name',
    defaultValue: 'nodeca'
  }
);

parser.addArgument(
  [ '-c', '--cutoff' ],
  {
    help: 'cutoff (days)',
    type: 'int'
  }
);

parser.addArgument(
  [ '-l', '--long' ],
  {
    help: 'hide short links (without query)',
    action: 'storeTrue'
  }
);

parser.addArgument(
  'domain',
  {
    help: 'domain name'
  }
);

let args = parser.parseArgs();

mongoose.Promise = Promise;

Promise.coroutine(function* () {
  yield mongoose.connect('mongodb://localhost/' + args.db);

  let Post = mongoose.model('forum.Post', new mongoose.Schema());

  let regexp_search = new RegExp('href="https?:\\/\\/[^\\/]*' + _.escapeRegExp(args.domain));

  let query = { html: regexp_search };

  if (args.cutoff) {
    let ts = Date.now() / 1000 - args.cutoff * 24 * 60 * 60;
    let min_objectid = new mongoose.Types.ObjectId(Math.floor(ts).toString(16) + '0000000000000000');

    query._id = { $gt: min_objectid };
  }

  yield Promise.fromCallback(callback => pump(
    Post.find(query).lean(true).cursor(),

    new stream.Writable({
      objectMode: true,
      write(post, encoding, callback) {
        let urls = post.html.match(/href="[^"]+"/g)
                     .map(href => _.unescape(href.replace(/^href="|"$/g, '')));

        urls.forEach(url => {
          let parsed = URL.parse(url, true, true);

          if (parsed.host && parsed.host.includes(args.domain)) {
            /* eslint-disable no-console */

            if (args.long) {
              if (Object.keys(parsed.query).length || parsed.hash) console.log(url, '\n');
            } else console.log(url, '\n');
          }
        });

        callback();
      }
    }),

    callback
  ));

  yield mongoose.disconnect();
})();
<|endoftext|>


<commit_before>'use strict';

function locationOrigin(location) {
  return location.protocol + '//' + location.hostname + (location.port !== '' ? ':' + location.port : '');
}

/**
  The main namespace for Ember.SimpleAuth

  @class SimpleAuth
  @namespace Ember
  @static
**/
Ember.SimpleAuth = Ember.Namespace.create();

/**
  Sets up Ember.SimpleAuth for your application; invoke this method in a custom
  initializer like this:

  ```javascript
  Ember.Application.initializer({
    name: 'authentication',
    initialize: function(application) {
      Ember.SimpleAuth.setup(application);
    }
  });
  ```

  @method setup
  @static
  @param {Ember.Application} application The Ember.js application instance
  @param {Object} [options]
    @param {String} [options.routeAfterLogin] route to redirect the user to after successfully logging in - defaults to `'index'`
    @param {String} [options.routeAfterLogout] route to redirect the user to after logging out - defaults to `'index'`
    @param {String} [options.loginRoute] route to redirect the user to when login is required - defaults to `'login'`
    @param {Array[String]} [options.crossOriginWhitelist] list of origins that (besides the origin of the Ember.js application) send the authentication token to - defaults to `[]` (beware that origins consist of protocol, host and port (you can leave port out when it is 80))
    @param {Object} [options.authorizer] The authorizer "class" to use; must extend `Ember.Object` and also implement `function(jqXHR, requestOptions)` - defaults to `Ember.SimpleAuth.Authorizers.OAuth2`
    @param {Object} [options.store] The store "class" to use; must extend `Ember.Object` and also implement `function(jqXHR, requestOptions)` - defaults to `Ember.SimpleAuth.Stores.Cookie`
**/
Ember.SimpleAuth.setup = function(application, options) {
  options = options || {};
  this.routeAfterLogin       = options.routeAfterLogin || 'index';
  this.routeAfterLogout      = options.routeAfterLogout || 'index';
  this.loginRoute            = options.loginRoute || 'login';

  var store      = (options.store || Ember.SimpleAuth.Stores.Cookie).create();
  var session    = Ember.SimpleAuth.Session.create({ store: store });
  var authorizer = (options.authorizer || Ember.SimpleAuth.Authorizers.OAuth2).create({ session: session });

  application.register('simple_auth:session', session, { instantiate: false, singleton: true });
  Ember.A(['model', 'controller', 'view', 'route']).forEach(function(component) {
    application.inject(component, 'session', 'simple_auth:session');
  });

  Ember.$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
    if (shouldAuthorizeRequest(options.url)) {
      authorizer.authorize(jqXHR, options);
    }
  });

  var crossOriginWhitelist = Ember.A(options.crossOriginWhitelist || []);
  var linkOrigins          = {};
  var documentOrigin       = locationOrigin(window.location);
  function shouldAuthorizeRequest(url) {
    var link = linkOrigins[url] || function() {
      var link = document.createElement('a');
      link.href = url;
      return (linkOrigins[url] = link);
    }();
    var linkOrigin = locationOrigin(link);
    return crossOriginWhitelist.indexOf(linkOrigin) > -1 || linkOrigin === documentOrigin;
  }
};
<commit_msg>foramtting<commit_after>'use strict';

function locationOrigin(location) {
  return location.protocol + '//' + location.hostname + (location.port !== '' ? ':' + location.port : '');
}

/**
  The main namespace for Ember.SimpleAuth

  @class SimpleAuth
  @namespace Ember
  @static
**/
Ember.SimpleAuth = Ember.Namespace.create();

/**
  Sets up Ember.SimpleAuth for your application; invoke this method in a custom
  initializer like this:

  ```javascript
  Ember.Application.initializer({
    name: 'authentication',
    initialize: function(application) {
      Ember.SimpleAuth.setup(application);
    }
  });
  ```

  @method setup
  @static
  @param {Ember.Application} application The Ember.js application instance
  @param {Object} [options]
    @param {String} [options.routeAfterLogin] route to redirect the user to after successfully logging in - defaults to `'index'`
    @param {String} [options.routeAfterLogout] route to redirect the user to after logging out - defaults to `'index'`
    @param {String} [options.loginRoute] route to redirect the user to when login is required - defaults to `'login'`
    @param {Array[String]} [options.crossOriginWhitelist] list of origins that (besides the origin of the Ember.js application) send the authentication token to - defaults to `[]` (beware that origins consist of protocol, host and port (you can leave port out when it is 80))
    @param {Object} [options.authorizer] The authorizer "class" to use; must extend `Ember.Object` and also implement `function(jqXHR, requestOptions)` - defaults to `Ember.SimpleAuth.Authorizers.OAuth2`
    @param {Object} [options.store] The store "class" to use; must extend `Ember.Object` and also implement `function(jqXHR, requestOptions)` - defaults to `Ember.SimpleAuth.Stores.Cookie`
**/
Ember.SimpleAuth.setup = function(application, options) {
  options = options || {};
  this.routeAfterLogin  = options.routeAfterLogin || 'index';
  this.routeAfterLogout = options.routeAfterLogout || 'index';
  this.loginRoute       = options.loginRoute || 'login';

  var store      = (options.store || Ember.SimpleAuth.Stores.Cookie).create();
  var session    = Ember.SimpleAuth.Session.create({ store: store });
  var authorizer = (options.authorizer || Ember.SimpleAuth.Authorizers.OAuth2).create({ session: session });

  application.register('simple_auth:session', session, { instantiate: false, singleton: true });
  Ember.A(['model', 'controller', 'view', 'route']).forEach(function(component) {
    application.inject(component, 'session', 'simple_auth:session');
  });

  Ember.$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
    if (shouldAuthorizeRequest(options.url)) {
      authorizer.authorize(jqXHR, options);
    }
  });

  var crossOriginWhitelist = Ember.A(options.crossOriginWhitelist || []);
  var linkOrigins          = {};
  var documentOrigin       = locationOrigin(window.location);
  function shouldAuthorizeRequest(url) {
    var link = linkOrigins[url] || function() {
      var link = document.createElement('a');
      link.href = url;
      return (linkOrigins[url] = link);
    }();
    var linkOrigin = locationOrigin(link);
    return crossOriginWhitelist.indexOf(linkOrigin) > -1 || linkOrigin === documentOrigin;
  }
};
<|endoftext|>


<commit_before>/**
 * Shopware 4.0
 * Copyright © 2012 shopware AG
 *
 * According to our dual licensing model, this program can be used either
 * under the terms of the GNU Affero General Public License, version 3,
 * or under a proprietary license.
 *
 * The texts of the GNU Affero General Public License with an additional
 * permission and of our proprietary license can be found at and
 * in the LICENSE file you have received along with this program.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * "Shopware" is a registered trademark of shopware AG.
 * The licensing of the program under the AGPLv3 does not imply a
 * trademark license. Therefore any rights, title and interest in
 * our trademarks remain entirely with us.
 *
 * @category   Shopware
 * @package    Shipping
 * @subpackage View
 * @copyright  Copyright (c) 2012, shopware AG (http://www.shopware.de)
 * @version    $Id$
 * @author shopware AG
 */

/*{namespace name=backend/shipping/view/main/list}*/

/**
 * Shopware UI - Shipping Costs
 *
 * todo@all: Documentation
 */
//{block name="backend/shipping/view/main/list"}
Ext.define('Shopware.apps.Shipping.view.main.List', {
    /**
     * Parent Class
     * @String
     */
    extend : 'Ext.grid.Panel',
    /**
     * Alias
     * @string
     */
    alias : 'widget.shipping-list',

    /**
     * Enables autoscrolling
     * @boolean
     */
    autoScroll : true,

    /**
     * Text to display on empty entries
     * @string
     */
    emptyText: '{s name=grid_empty_text}No records{/s}',
    /**
     * Text displayed if all shops are meant
     * @string
     */
    emptySubshopText: '{s name=grid_empty_shop}All{/s}',
    /**
     * Text displayed if all customergroups are meant
     * @string
     */
    emptyCustomerGroupText: '{s name=grid_empty_customer_group}All{/s}',

    /**
     * USe statfull
     * @boolean
     */
    stateful : true,
    /**
     * Id to store the state
     * @string
     */
    stateId : 'shopware-shipping-list',

    /**
     * Initialize the Shopware.apps.Supplier.view.main.List and defines the necessary
     * default configuration
     */
    initComponent : function() {
        var me = this;

        me.store = me.dispatchStore;
        me.selModel = Ext.create('Ext.selection.CheckboxModel');

        me.tbar = me.createToolbar();
        me.bbar = me.getPagingbar();

        // Define the columns and renders
        me.columns = [
            {
                header: '{s name=grid_name}Name{/s}',
                dataIndex : 'dispatch.name',
                renderer: me.nameColumn,
                width: 125
            },
            {
                header:'{s name=grid_internal_comment}Internal comment{/s}',
                dataIndex:'dispatch.description',
                renderer : me.descriptionColumn,
                flex:1
            },
            {
                header:'{s name=grid_active}Active{/s}',
                xtype: 'booleancolumn',
                dataIndex:'dispatch.active',
                width:50,
                renderer:me.activeColumn
            },
            {
                header:'{s name=grid_type}Type{/s}',
                dataIndex:'dispatch.type',
                renderer:me.typeColumn,
                width:120
            },
            {
                header:'{s name=grid_shop}Shop{/s}',
                dataIndex:'dispatch.multiShopId',
                renderer:me.multishopIdColumn,
                width:120
            },
            {
                header:'{s name=grid_customer_group}Customer group{/s}',
                dataIndex:'dispatch.customerGroupId',
                renderer:me.customerGroupColumn,
                width:120
            },
            {
                header: '',
                xtype : 'actioncolumn',
                width : 80,
                items : [
                     /* {if {acl_is_allowed privilege=delete}} */
                    {
                        iconCls : 'sprite-minus-circle-frame',
                        action  : 'delete',
                        cls     : 'dispatchDelete',
                        tooltip : '{s name=grid_delete_tooltip}Delete this dispatch costs.{/s}'
                    },
                    /* {/if} */
                    /* {if {acl_is_allowed privilege=update}} */
                    {
                        iconCls : 'sprite-pencil',
                        cls     : 'editButton',
                        tooltip : '{s name=grid_edit_tooltip}Edit these shipping costs{/s}'
                    },
                    /* {/if} */
                     /* {if {acl_is_allowed privilege=create}} */
                    {
                        iconCls :'sprite-blue-document-copy',
                        cls     :'cloneButton',
                        tooltip :'{s name=grid_clone_tooltip}Duplicate these shipping costs{/s}',
                        style   : 'width: 16px; height: 16px'
                    }
                    /* {/if} */
                ]
            }
        ];

        me.callParent(arguments);
    },

    /**
     * Creates the toolbar for the position grid.
     * @return Ext.toolbar.Toolbar
     */
    createToolbar: function() {
        var me = this;

        return Ext.create('Ext.toolbar.Toolbar', {
            dock:'top',
            ui: 'shopware-ui',
            /**
             * Contains two buttons one for add one for delete.
             * @array
             */
            items : [
                /*{if {acl_is_allowed privilege=delete}}*/
                {
                    iconCls : 'sprite-plus-circle',
                    text : '{s name=grid_add}Add{/s}',
                    action : 'addShipping'
                },
                /* {/if} */
                /*{if {acl_is_allowed privilege=delete}}*/
                {
                    iconCls : 'sprite-minus-circle',
                    text : '{s name=grid_delete}Delete{/s}',
                    disabled : true,
                    action : 'deleteShipping'
                }
                /* {/if} */
            ]
        });
    },

    /**
     * Creates the pagingbar for the position grid.
     * @return Ext.toolbar.Pagingbar
     */
    getPagingbar : function() {
        var me = this;
        return  {
            xtype: 'pagingtoolbar',
            displayInfo : true,
            store: me.store
        };
    },

    /**
     * Does a translation from the numeric value to a more readable string
     *
     * @param [string] value - Name of the dispatch type
     * @param [object] metaData - Meta data for this column
     * @param [object] record - current record
     */
    typeColumn: function(value, obj, record) {
        switch (record.get('type')) {
            case 3:
                return '{s name=grid_dispatch_type_discount}Discount rule{/s}';
            case 2:
                return '{s name=grid_dispatch_type_surcharge}Surcharge rule{/s}';
            case 1:
                return '{s name=grid_dispatch_type_alternative}Alternate shipping type{/s}';
            case 0:
            default:
                return '{s name=grid_dispatch_type_default}Default shipping type{/s}';
        }
    },
    /**
     * Translate the shop id to there right name
     *
     * @param [string] value - Name of the shop
     * @param [object] metaData - Meta data for this column
     * @param [object] record - current record
     */
    multishopIdColumn : function(value, obj, record) {
        var me = this,
            shop = me.shopStore.findRecord('id', record.get('multiShopId'));

        // if we have an empty or a zero value show default empty text
        if (null === record.get('multiShopId') || 0 === record.get('multiShopId')) {
            return me.emptySubshopText;
        }
        return shop.get('name');
    },

    /**
     * Converts the numeric id to a readable name
     * @param [string] value - ID of the customer group
     * @param [object] metaData - Meta data for this column
     * @param [object] record - current record
     */
    customerGroupColumn : function(value, metaData, record) {
        var me = this,
            customerGroupStore = me.customerGroupStore;

        var customerGroup = customerGroupStore.findRecord('id', record.get('customerGroupId'));
        if (null == record.get('customerGroupId') || null == customerGroup) {
            return me.emptyCustomerGroupText;
        }
        return customerGroup.get('name') + ' ('+customerGroup.get('key')+')';
    },

    /**
     * Formats the name column
     *
     * @param [string] value - Name of the disptach
     * @param [object] metaData - Meta data for this column
     * @param [object] record - current record
     */
    nameColumn : function (value, metaData, record) {
        return Ext.String.format('{literal}{0}{/literal}', record.get('name'));
    },

    /**
     * Formats the description column
     *
     * @param [string] value - Description for the dispatch
     * @param [object] metaData - Meta data for this column
     * @param [object] record - current record
     */
    descriptionColumn : function (value, metaData, record) {
        return record.get('description');
    },
    /**
     * Formats the action column
     *
     * @param [string] value - flag if this dispatch is active or not
     * @param [object] metaData - Meta data for this column
     * @param [object] record - current record
     */
    activeColumn : function (value, metaData, record) {
        if(record.get('active') == 0) {
            return '{s name=grid_active_false_label}Inactive{/s}';
        }
        return '{s name=grid_active_true_label}Active{/s}';
    }
});
//{/block}
<commit_msg>SW-5642 fix internal comment in shipping module<commit_after>/**
 * Shopware 4.0
 * Copyright © 2012 shopware AG
 *
 * According to our dual licensing model, this program can be used either
 * under the terms of the GNU Affero General Public License, version 3,
 * or under a proprietary license.
 *
 * The texts of the GNU Affero General Public License with an additional
 * permission and of our proprietary license can be found at and
 * in the LICENSE file you have received along with this program.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * "Shopware" is a registered trademark of shopware AG.
 * The licensing of the program under the AGPLv3 does not imply a
 * trademark license. Therefore any rights, title and interest in
 * our trademarks remain entirely with us.
 *
 * @category   Shopware
 * @package    Shipping
 * @subpackage View
 * @copyright  Copyright (c) 2012, shopware AG (http://www.shopware.de)
 * @version    $Id$
 * @author shopware AG
 */

/*{namespace name=backend/shipping/view/main/list}*/

/**
 * Shopware UI - Shipping Costs
 *
 * todo@all: Documentation
 */
//{block name="backend/shipping/view/main/list"}
Ext.define('Shopware.apps.Shipping.view.main.List', {
    /**
     * Parent Class
     * @String
     */
    extend : 'Ext.grid.Panel',
    /**
     * Alias
     * @string
     */
    alias : 'widget.shipping-list',

    /**
     * Enables autoscrolling
     * @boolean
     */
    autoScroll : true,

    /**
     * Text to display on empty entries
     * @string
     */
    emptyText: '{s name=grid_empty_text}No records{/s}',
    /**
     * Text displayed if all shops are meant
     * @string
     */
    emptySubshopText: '{s name=grid_empty_shop}All{/s}',
    /**
     * Text displayed if all customergroups are meant
     * @string
     */
    emptyCustomerGroupText: '{s name=grid_empty_customer_group}All{/s}',

    /**
     * USe statfull
     * @boolean
     */
    stateful : true,
    /**
     * Id to store the state
     * @string
     */
    stateId : 'shopware-shipping-list',

    /**
     * Initialize the Shopware.apps.Supplier.view.main.List and defines the necessary
     * default configuration
     */
    initComponent : function() {
        var me = this;

        me.store = me.dispatchStore;
        me.selModel = Ext.create('Ext.selection.CheckboxModel');

        me.tbar = me.createToolbar();
        me.bbar = me.getPagingbar();

        // Define the columns and renders
        me.columns = [
            {
                header: '{s name=grid_name}Name{/s}',
                dataIndex : 'dispatch.name',
                renderer: me.nameColumn,
                width: 125
            },
            {
                header:'{s name=grid_internal_comment}Internal comment{/s}',
                dataIndex:'dispatch.comment',
                renderer : me.commentColumn,
                flex:1
            },
            {
                header:'{s name=grid_active}Active{/s}',
                xtype: 'booleancolumn',
                dataIndex:'dispatch.active',
                width:50,
                renderer:me.activeColumn
            },
            {
                header:'{s name=grid_type}Type{/s}',
                dataIndex:'dispatch.type',
                renderer:me.typeColumn,
                width:120
            },
            {
                header:'{s name=grid_shop}Shop{/s}',
                dataIndex:'dispatch.multiShopId',
                renderer:me.multishopIdColumn,
                width:120
            },
            {
                header:'{s name=grid_customer_group}Customer group{/s}',
                dataIndex:'dispatch.customerGroupId',
                renderer:me.customerGroupColumn,
                width:120
            },
            {
                header: '',
                xtype : 'actioncolumn',
                width : 80,
                items : [
                     /* {if {acl_is_allowed privilege=delete}} */
                    {
                        iconCls : 'sprite-minus-circle-frame',
                        action  : 'delete',
                        cls     : 'dispatchDelete',
                        tooltip : '{s name=grid_delete_tooltip}Delete this dispatch costs.{/s}'
                    },
                    /* {/if} */
                    /* {if {acl_is_allowed privilege=update}} */
                    {
                        iconCls : 'sprite-pencil',
                        cls     : 'editButton',
                        tooltip : '{s name=grid_edit_tooltip}Edit these shipping costs{/s}'
                    },
                    /* {/if} */
                     /* {if {acl_is_allowed privilege=create}} */
                    {
                        iconCls :'sprite-blue-document-copy',
                        cls     :'cloneButton',
                        tooltip :'{s name=grid_clone_tooltip}Duplicate these shipping costs{/s}',
                        style   : 'width: 16px; height: 16px'
                    }
                    /* {/if} */
                ]
            }
        ];

        me.callParent(arguments);
    },

    /**
     * Creates the toolbar for the position grid.
     * @return Ext.toolbar.Toolbar
     */
    createToolbar: function() {
        var me = this;

        return Ext.create('Ext.toolbar.Toolbar', {
            dock:'top',
            ui: 'shopware-ui',
            /**
             * Contains two buttons one for add one for delete.
             * @array
             */
            items : [
                /*{if {acl_is_allowed privilege=delete}}*/
                {
                    iconCls : 'sprite-plus-circle',
                    text : '{s name=grid_add}Add{/s}',
                    action : 'addShipping'
                },
                /* {/if} */
                /*{if {acl_is_allowed privilege=delete}}*/
                {
                    iconCls : 'sprite-minus-circle',
                    text : '{s name=grid_delete}Delete{/s}',
                    disabled : true,
                    action : 'deleteShipping'
                }
                /* {/if} */
            ]
        });
    },

    /**
     * Creates the pagingbar for the position grid.
     * @return Ext.toolbar.Pagingbar
     */
    getPagingbar : function() {
        var me = this;
        return  {
            xtype: 'pagingtoolbar',
            displayInfo : true,
            store: me.store
        };
    },

    /**
     * Does a translation from the numeric value to a more readable string
     *
     * @param [string] value - Name of the dispatch type
     * @param [object] metaData - Meta data for this column
     * @param [object] record - current record
     */
    typeColumn: function(value, obj, record) {
        switch (record.get('type')) {
            case 3:
                return '{s name=grid_dispatch_type_discount}Discount rule{/s}';
            case 2:
                return '{s name=grid_dispatch_type_surcharge}Surcharge rule{/s}';
            case 1:
                return '{s name=grid_dispatch_type_alternative}Alternate shipping type{/s}';
            case 0:
            default:
                return '{s name=grid_dispatch_type_default}Default shipping type{/s}';
        }
    },
    /**
     * Translate the shop id to there right name
     *
     * @param [string] value - Name of the shop
     * @param [object] metaData - Meta data for this column
     * @param [object] record - current record
     */
    multishopIdColumn : function(value, obj, record) {
        var me = this,
            shop = me.shopStore.findRecord('id', record.get('multiShopId'));

        // if we have an empty or a zero value show default empty text
        if (null === record.get('multiShopId') || 0 === record.get('multiShopId')) {
            return me.emptySubshopText;
        }
        return shop.get('name');
    },

    /**
     * Converts the numeric id to a readable name
     * @param [string] value - ID of the customer group
     * @param [object] metaData - Meta data for this column
     * @param [object] record - current record
     */
    customerGroupColumn : function(value, metaData, record) {
        var me = this,
            customerGroupStore = me.customerGroupStore;

        var customerGroup = customerGroupStore.findRecord('id', record.get('customerGroupId'));
        if (null == record.get('customerGroupId') || null == customerGroup) {
            return me.emptyCustomerGroupText;
        }
        return customerGroup.get('name') + ' ('+customerGroup.get('key')+')';
    },

    /**
     * Formats the name column
     *
     * @param [string] value - Name of the disptach
     * @param [object] metaData - Meta data for this column
     * @param [object] record - current record
     */
    nameColumn : function (value, metaData, record) {
        return Ext.String.format('{literal}{0}{/literal}', record.get('name'));
    },

    /**
     * Formats the comment column
     *
     * @param [string] value - Description for the dispatch
     * @param [object] metaData - Meta data for this column
     * @param [object] record - current record
     */
    commentColumn : function (value, metaData, record) {
        return record.get('comment');
    },
    /**
     * Formats the action column
     *
     * @param [string] value - flag if this dispatch is active or not
     * @param [object] metaData - Meta data for this column
     * @param [object] record - current record
     */
    activeColumn : function (value, metaData, record) {
        if(record.get('active') == 0) {
            return '{s name=grid_active_false_label}Inactive{/s}';
        }
        return '{s name=grid_active_true_label}Active{/s}';
    }
});
//{/block}
<|endoftext|>