<commit_before>import '../../polyfills/array-find';

const callbacks = [];
let currentMode = null;
let initialized = false;
let managerItem = null;
let userItem = null;

function callCallbacks(data) {
    callbacks.map((callback) => {
        if (callback && window.chayns.utils.isFunction(callback)) {
            callback(data);
        }
    });
}

function getChangeListener() {
    return (data) => {
        callCallbacks(data);

        currentMode = data;
    };
}

function setDefaultGroup(mode = 0) {
    initialized = true;

    getChangeListener()({
        id: mode
    });

    window.chayns.ui.modeSwitch.changeMode(0);
}

function getUacIds(group) {
    let retval = [];

    if (group.uacId && window.chayns.utils.isNumber(group.uacId)) {
        retval.push(group.uacId);
    }

    if (group.uacIds && window.chayns.utils.isArray(group.uacIds)) {
        retval = retval.concat(group.uacIds);
    }

    return retval;
}

function getAllowedUacIdsFromArray(uacArray) {
    const userGroups = window.chayns.env.user.groups;

    const allowedUacIds = [];

    for (let i = 0, x = userGroups.length; i < x; i += 1) {
        if (uacArray.indexOf(userGroups[i].id) !== -1) {
            allowedUacIds.push(userGroups[i].id);
        }
    }

    return allowedUacIds;
}

function convertToGroupObject(element) {
    if (window.chayns.utils.isObject(element)) {
        return element;
    }

    return {
        id: element,
        uacIds: [element]
    };
}

function getGroupObject(id, name, uacs) {
    return {
        id,
        uacIds: uacs,
        name
    };
}

function getSavedMode() {
    return window.chayns.utils.ls.get('react__modeSwitch--currentMode');
}

function setSavedMode(mode) {
    return window.chayns.utils.ls.set('react__modeSwitch--currentMode', mode.id);
}

function getDefaultMode() {
    const name = (window.chayns.env.user.isAuthenticated) ? window.chayns.env.user.name : '';

    return getGroupObject(0, name, null);
}

export default class ModeSwitchHelper {
    static init(options) {
        userItem = null;
        managerItem = null;

        if (options.groups) {
            if (window.chayns.utils.isFunction(options.onChange)) {
                callbacks.push(options.onChange);
            }

            if (options.save) {
                callbacks.push(setSavedMode);
            }

            const allowedGroups = [];
            let isChaynsIdAdmin = false;

            const groups = [];
            if (options.groups) {
                options.groups.map((element) => {
                    const group = convertToGroupObject(element);

                    groups.push(group);
                });
            }

            if (window.chayns.env.user.isAuthenticated) {
                userItem = getGroupObject(0, window.chayns.env.user.name, [0]);

                const managerGroup = ModeSwitchHelper.findManagerGroup(groups);
                if (managerGroup) {
                    const { id, name, uacIds } = managerGroup;

                    managerItem = getGroupObject(id, name, uacIds);
                }
            }

            chayns.ready.then((data) => {
                if (window.chayns.env.user.isAuthenticated) {
                    // Condition if adminMode ChaynsId
                    let groupObject;

                    if (managerItem && data && data.AppUser.AdminMode && hasAdminSwitch()) {
                        groupObject = managerItem;
                        isChaynsIdAdmin = true;
                    } else {
                        groupObject = userItem;
                        groupObject.default = true;
                    }

                    allowedGroups.push(groupObject);

                    let savedModeId = null;
                    let changeGroupIndex = 0;
                    if (options.save) {
                        savedModeId = getSavedMode();
                    }

                    if (savedModeId === null && options.defaultMode) {
                        savedModeId = options.defaultMode;
                    }

                    let changeGroup = false;
                    let changeGroupValue = null;

                    for (let i = 0, x = groups.length; i < x; i += 1) {
                        if (!groups[i].uacId && !groups[i].uacIds) {
                            const addGroupObject = getGroupObject(groups[i].id, groups[i].name, [0]);
                            allowedGroups.push(addGroupObject);

                            if (addGroupObject.id === savedModeId) {
                                changeGroup = true;
                                changeGroupIndex = allowedGroups.length - 1;
                                changeGroupValue = addGroupObject;
                            }
                        } else {
                            const uacIds = getUacIds(groups[i]);
                            const allowedUacs = getAllowedUacIdsFromArray(uacIds);

                            if (allowedUacs.length > 0 && !(allowedUacs.find(uac => uac === 1) && !chayns.env.isApp)) {
                                const addGroupObject = getGroupObject(groups[i].id, groups[i].name, allowedUacs);
                                allowedGroups.push(addGroupObject);

                                if (addGroupObject.id === savedModeId) {
                                    changeGroup = true;
                                    changeGroupIndex = allowedGroups.length - 1;
                                    changeGroupValue = addGroupObject;
                                }
                            }
                        }
                    }

                    if (allowedGroups.length > 1) {
                        window.chayns.ui.modeSwitch.init({
                            items: allowedGroups,
                            callback: getChangeListener()
                        });

                        initialized = true;

                        if (changeGroup) {
                            getChangeListener()(changeGroupValue);

                            window.chayns.ui.modeSwitch.changeMode(changeGroupIndex);
                        } else {
                            setDefaultGroup(isChaynsIdAdmin && managerItem ? managerItem.id : 0);
                        }

                        //  if (changeGroup) { window.setTimeout(() => { window.chayns.ui.modeSwitch.changeMode(changeGroupIndex); }, 0); }
                    } else {
                        setDefaultGroup(isChaynsIdAdmin && managerItem ? managerItem.id : 0);

                        // ToDo: Implement adminSwitchCallback for allowedGroups.length > 1 too
                        const changeListener = getChangeListener();
                        chayns.setAdminSwitchCallback(({ mode }) => changeListener({
                            id: mode,
                        }));
                    }
                } else {
                    setDefaultGroup();
                }
            });
        } else {
            console.warn('No groups specified');
        }
    }

    static getCurrentMode() {
        if (currentMode) return currentMode;

        return getDefaultMode();
    }

    static onChange(callback) {
        if (window.chayns.utils.isFunction(callback)) {
            callbacks.push(callback);

            return true;
        }

        return false;
    }

    static unregisterOnChange(callback) {
        const index = callbacks.indexOf(callback);

        if (index > -1) {
            callbacks.splice(index, 1);
        }
    }

    static isInitialized() {
        return initialized;
    }

    static hide() {
        window.chayns.ui.modeSwitch.remove();
    }

    static show() {
        window.chayns.ui.modeSwitch.add();
    }

    static isUserInGroup(uacId) {
        if (!window.chayns.env.user.isAuthenticated) return false;

        return !!window.chayns.env.user.groups.find((element) => {
            return element.id === uacId;
        });
    }

    static findManagerGroup(groups) {
        if (!window.chayns.env.user.isAuthenticated) return false;

        return groups.find((uac) => {
            return uac.uacIds && uac.uacIds.length === 1 && uac.uacIds[0] === 1;
        }) || groups.find((uac) => {
            return uac.uacIds && uac.uacIds.find(id => id === 1);
        });
    }

    static isChaynsManager() {
        return this.isUserInGroup(1);
    }
}
<commit_msg>Fix item selection<commit_after>import '../../polyfills/array-find';

const callbacks = [];
let currentMode = null;
let initialized = false;
let managerItem = null;
let userItem = null;

function callCallbacks(data) {
    callbacks.map((callback) => {
        if (callback && window.chayns.utils.isFunction(callback)) {
            callback(data);
        }
    });
}

function getChangeListener() {
    return (data) => {
        callCallbacks(data);

        currentMode = data;
    };
}

function setDefaultGroup(mode = 0) {
    initialized = true;

    getChangeListener()({
        id: mode
    });

    window.chayns.ui.modeSwitch.changeMode(0);
}

function getUacIds(group) {
    let retval = [];

    if (group.uacId && window.chayns.utils.isNumber(group.uacId)) {
        retval.push(group.uacId);
    }

    if (group.uacIds && window.chayns.utils.isArray(group.uacIds)) {
        retval = retval.concat(group.uacIds);
    }

    return retval;
}

function getAllowedUacIdsFromArray(uacArray) {
    const userGroups = window.chayns.env.user.groups;

    const allowedUacIds = [];

    for (let i = 0, x = userGroups.length; i < x; i += 1) {
        if (uacArray.indexOf(userGroups[i].id) !== -1) {
            allowedUacIds.push(userGroups[i].id);
        }
    }

    return allowedUacIds;
}

function convertToGroupObject(element) {
    if (window.chayns.utils.isObject(element)) {
        return element;
    }

    return {
        id: element,
        uacIds: [element]
    };
}

function getGroupObject(id, name, uacs) {
    return {
        id,
        uacIds: uacs,
        name
    };
}

function getSavedMode() {
    return window.chayns.utils.ls.get('react__modeSwitch--currentMode');
}

function setSavedMode(mode) {
    return window.chayns.utils.ls.set('react__modeSwitch--currentMode', mode.id);
}

function getDefaultMode() {
    const name = (window.chayns.env.user.isAuthenticated) ? window.chayns.env.user.name : '';

    return getGroupObject(0, name, null);
}

export default class ModeSwitchHelper {
    static init(options) {
        userItem = null;
        managerItem = null;

        if (options.groups) {
            if (window.chayns.utils.isFunction(options.onChange)) {
                callbacks.push(options.onChange);
            }

            if (options.save) {
                callbacks.push(setSavedMode);
            }

            const allowedGroups = [];
            let isChaynsIdAdmin = false;

            const groups = [];
            if (options.groups) {
                options.groups.map((element) => {
                    const group = convertToGroupObject(element);

                    groups.push(group);
                });
            }

            if (window.chayns.env.user.isAuthenticated) {
                userItem = getGroupObject(0, window.chayns.env.user.name, [0]);

                const managerGroup = ModeSwitchHelper.findManagerGroup(groups);
                if (managerGroup) {
                    const { id, name, uacIds } = managerGroup;

                    managerItem = getGroupObject(id, name, uacIds);
                }
            }

            chayns.ready.then((data) => {
                if (window.chayns.env.user.isAuthenticated) {
                    // Condition if adminMode ChaynsId
                    let groupObject;

                    if (managerItem && data && data.AppUser.AdminMode && hasAdminSwitch()) {
                        groupObject = managerItem;
                        isChaynsIdAdmin = true;
                    } else {
                        groupObject = userItem;
                        groupObject.default = true;
                    }

                    allowedGroups.push(groupObject);

                    let savedModeId = null;
                    let changeGroupIndex = 0;
                    if (options.save) {
                        savedModeId = getSavedMode();
                    }

                    if (savedModeId === null && options.defaultMode) {
                        savedModeId = options.defaultMode;
                    }

                    let changeGroup = false;
                    let changeGroupValue = null;

                    for (let i = 0, x = groups.length; i < x; i += 1) {
                        if (!groups[i].uacId && !groups[i].uacIds) {
                            const addGroupObject = getGroupObject(groups[i].id, groups[i].name, [0]);
                            allowedGroups.push(addGroupObject);

                            if (addGroupObject.id === savedModeId) {
                                changeGroup = true;
                                changeGroupIndex = allowedGroups.length - 1;
                                changeGroupValue = addGroupObject;
                            }
                        } else {
                            const uacIds = getUacIds(groups[i]);
                            const allowedUacs = getAllowedUacIdsFromArray(uacIds);

                            if (allowedUacs.length > 0 && (!hasAdminSwitch() || !managerItem || groups[i].id !== managerItem.id)) {
                                const addGroupObject = getGroupObject(groups[i].id, groups[i].name, allowedUacs);
                                allowedGroups.push(addGroupObject);

                                if (addGroupObject.id === savedModeId) {
                                    changeGroup = true;
                                    changeGroupIndex = allowedGroups.length - 1;
                                    changeGroupValue = addGroupObject;
                                }
                            }
                        }
                    }

                    if (allowedGroups.length > 1) {
                        window.chayns.ui.modeSwitch.init({
                            items: allowedGroups,
                            callback: getChangeListener()
                        });

                        initialized = true;

                        if (changeGroup) {
                            getChangeListener()(changeGroupValue);

                            window.chayns.ui.modeSwitch.changeMode(changeGroupIndex);
                        } else {
                            setDefaultGroup(isChaynsIdAdmin && managerItem ? managerItem.id : 0);
                        }

                        //  if (changeGroup) { window.setTimeout(() => { window.chayns.ui.modeSwitch.changeMode(changeGroupIndex); }, 0); }
                    } else {
                        setDefaultGroup(isChaynsIdAdmin && managerItem ? managerItem.id : 0);

                        // ToDo: Implement adminSwitchCallback for allowedGroups.length > 1 too
                        const changeListener = getChangeListener();
                        chayns.setAdminSwitchCallback(({ mode }) => changeListener({
                            id: mode,
                        }));
                    }
                } else {
                    setDefaultGroup();
                }
            });
        } else {
            console.warn('No groups specified');
        }
    }

    static getCurrentMode() {
        if (currentMode) return currentMode;

        return getDefaultMode();
    }

    static onChange(callback) {
        if (window.chayns.utils.isFunction(callback)) {
            callbacks.push(callback);

            return true;
        }

        return false;
    }

    static unregisterOnChange(callback) {
        const index = callbacks.indexOf(callback);

        if (index > -1) {
            callbacks.splice(index, 1);
        }
    }

    static isInitialized() {
        return initialized;
    }

    static hide() {
        window.chayns.ui.modeSwitch.remove();
    }

    static show() {
        window.chayns.ui.modeSwitch.add();
    }

    static isUserInGroup(uacId) {
        if (!window.chayns.env.user.isAuthenticated) return false;

        return !!window.chayns.env.user.groups.find((element) => {
            return element.id === uacId;
        });
    }

    static findManagerGroup(groups) {
        if (!window.chayns.env.user.isAuthenticated) return false;

        return groups.find((uac) => {
            return uac.uacIds && uac.uacIds.length === 1 && uac.uacIds[0] === 1;
        }) || groups.find((uac) => {
            return uac.uacIds && uac.uacIds.find(id => id === 1);
        });
    }

    static isChaynsManager() {
        return this.isUserInGroup(1);
    }
}
<|endoftext|>


<commit_before>var config = require("../server/config.js");
var setup = require("../test/setup.js");
var assertPage = require("../test/assertPage.js");
var assert = require("assert");

var expectedFeedName = "expectedFeedName";
var expectedPostName = "expectedPostName";
var expectedPostUrl = "http://expectedPostUrl.com/readme";

var testBlock = setup.given3rdPartyRssServer(setup.whenRunningTheServer(setup.givenCleanDatabase(exports)), {
        feedName: expectedFeedName,
        postName: expectedPostName,
        postUrl: expectedPostUrl
    });

setup.qtest(testBlock, "New user is guided to import feeds and read them.", setup.usingPhantom(function(page) {

            var callToAction = "Import your feeds.";

            return page.promise.open(config.urlFor("/"))
                .then(function(status) {
                    assert.equal(status, "success");
                    return assertPage.isAtPath(page, "/");
                })
                .then(function() {
                    return assertPage.containsContent(page, callToAction);
                })
                .then(function() {
                    return require("../test/login.js").doLogin(page);
                })
                .then(function() {
                    return assertPage.isAtPath(page, "/feeds");
                })
                .then(function() {
                    return require("../test/uploadRss.js")(page, {
                            feeds: [{
                                    name: "ignored",
                                    rssUrl: "http://127.0.0.76:" + config.get("server_port") + "/rss",
                                    htmlUrl: "http://ignored/"
                                }
                            ]
                        });
                })
                .then(function() {
                    return page.promise.clickElement(".info a");
                })
                .then(function() {
                    return assertPage.isAtPath(page, "/");
                })
                .then(function() {
                    return page.promise.get("content");
                })
                .then(function(content) {
                    assert.ok(content.indexOf(expectedFeedName) > -1);
                    assert.ok(content.indexOf(expectedPostName) > -1);
                    assert.ok(content.indexOf(expectedPostUrl) > -1);
                });
        }));<commit_msg>test needed a wait for client-side behavior (not sure why other machine didn't need this wait)<commit_after>var config = require("../server/config.js");
var setup = require("../test/setup.js");
var assertPage = require("../test/assertPage.js");
var assert = require("assert");

var waitUntil = require("../test/waitUntil");

var expectedFeedName = "expectedFeedName";
var expectedPostName = "expectedPostName";
var expectedPostUrl = "http://expectedPostUrl.com/readme";

var testBlock = setup.given3rdPartyRssServer(setup.whenRunningTheServer(setup.givenCleanDatabase(exports)), {
        feedName: expectedFeedName,
        postName: expectedPostName,
        postUrl: expectedPostUrl
    });

setup.qtest(testBlock, "New user is guided to import feeds and read them.", setup.usingPhantom(function(page) {

            var callToAction = "Import your feeds.";

            return page.promise.open(config.urlFor("/"))
                .then(function(status) {
                    assert.equal(status, "success");
                    return assertPage.isAtPath(page, "/");
                })
                .then(function() {
                    return assertPage.containsContent(page, callToAction);
                })
                .then(function() {
                    return require("../test/login.js").doLogin(page);
                })
                .then(function() {
                    return assertPage.isAtPath(page, "/feeds");
                })
                .then(function() {
                    return require("../test/uploadRss.js")(page, {
                            feeds: [{
                                    name: "ignored",
                                    rssUrl: "http://127.0.0.76:" + config.get("server_port") + "/rss",
                                    htmlUrl: "http://ignored/"
                                }
                            ]
                        });
                })
                .then(function() {
                    return page.promise.clickElement(".info a");
                })
                .then(function() {
                    return assertPage.isAtPath(page, "/");
                })
                .then(function() {
                  return waitUntil("feed loads", function() {
                      return page.promise.get("content")
                          .then(function(content) {
                              return content.indexOf(expectedFeedName) > -1;
                          });
                  });
                })
                .then(function() {
                    return page.promise.get("content");
                })
                .then(function(content) {
                    assert.ok(content.indexOf(expectedFeedName) > -1);
                    assert.ok(content.indexOf(expectedPostName) > -1);
                    assert.ok(content.indexOf(expectedPostUrl) > -1);
                });
        }));<|endoftext|>


<commit_before>import React from 'react'
import { FormattedMessage } from 'react-intl'

export class VanillaTorDetails extends React.Component {

  constructor (props) {
    super(props)
    this.state = { showLog: false }
  }

  toggleLog () {
    this.setState({ showLog: !this.state.showLog })
  }

  render () {
    const { measurement } = this.props

    return (

        {measurement.test_keys.success === true &&

            <FormattedMessage
              id='nettests.vanillaTor.working'
              defaultMessage='Tor is working'
          />

            <FormattedMessage
              id='nettests.vanillaTor.working.text'
              defaultMessage='It took {testRuntime}s to bootstrap Tor version {torVersion}'
              values={{
                testRuntime: measurement.test_runtime,
                torVersion: {measurement.test_keys.tor_version}
              }}
          />

        }

        {measurement.test_keys.success === false &&

            <FormattedMessage
              id='nettests.vanillaTor.censorship'
              defaultMessage='Evidence of possible censorship'
            />

            <FormattedMessage
              id='nettests.vanillaTor.torVersion.blocked'
              defaultMessage='Tor version {torVersion} appears to be blocked.'
              values={{
                torVersion: {measurement.test_keys.tor_version}
              }}
          />

        }

        {this.state.showLog &&

{measurement.test_keys.tor_log}

        }

        <button className='btn btn-secondary' onClick={() => this.toggleLog()}>
          {this.state.showLog
           ? <FormattedMessage
             id='nettests.vanillaTor.hide'
             defaultMessage='Hide'
             />
           : <FormattedMessage
             id='nettests.vanillaTor.show'
             defaultMessage='Show'
             />
           }
             tor log
        </button>

    )
  }
}

VanillaTorDetails.propTypes = {
  measurement: React.PropTypes.object
}

export default VanillaTorDetails
<commit_msg>VanillaTor.js i18n: fix show/hide message<commit_after>import React from 'react'
import { FormattedMessage } from 'react-intl'

export class VanillaTorDetails extends React.Component {

  constructor (props) {
    super(props)
    this.state = { showLog: false }
  }

  toggleLog () {
    this.setState({ showLog: !this.state.showLog })
  }

  render () {
    const { measurement } = this.props

    return (

        {measurement.test_keys.success === true &&

            <FormattedMessage
              id='nettests.vanillaTor.working'
              defaultMessage='Tor is working'
          />

            <FormattedMessage
              id='nettests.vanillaTor.working.text'
              defaultMessage='It took {testRuntime}s to bootstrap Tor version {torVersion}'
              values={{
                testRuntime: measurement.test_runtime,
                torVersion: {measurement.test_keys.tor_version}
              }}
          />

        }

        {measurement.test_keys.success === false &&

            <FormattedMessage
              id='nettests.vanillaTor.censorship'
              defaultMessage='Evidence of possible censorship'
            />

            <FormattedMessage
              id='nettests.vanillaTor.torVersion.blocked'
              defaultMessage='Tor version {torVersion} appears to be blocked.'
              values={{
                torVersion: {measurement.test_keys.tor_version}
              }}
          />

        }

        {this.state.showLog &&

{measurement.test_keys.tor_log}

        }

        <button className='btn btn-secondary' onClick={() => this.toggleLog()}>
          {this.state.showLog
           ? <FormattedMessage
             id='nettests.vanillaTor.hide'
             defaultMessage='Hide tor log'
             />
           : <FormattedMessage
             id='nettests.vanillaTor.show'
             defaultMessage='Show tor log'
             />
           }
        </button>

    )
  }
}

VanillaTorDetails.propTypes = {
  measurement: React.PropTypes.object
}

export default VanillaTorDetails
<|endoftext|>


<commit_before>/*!
 * ${copyright}
 */

sap.ui.define([
        "sap/ui/core/Core",
        "sap/ui/mdc/library",
        "sap/ui/mdc/ActionToolbar",
        "sap/m/OverflowToolbarRenderer",
        "sap/m/OverflowToolbarButton",
        "sap/m/OverflowToolbarToggleButton",
        "sap/m/Title",
        "sap/ui/mdc/library",
        "sap/ui/mdc/chartNew/ChartTypeButtonNew",
        "sap/ui/mdc/chart/ChartSettings",
        "./ChartSelectionDetailsNew"
    ],
    function (
        Core,
        Control,
        ActionToolbar,
        OverflowToolbarRenderer,
        OverflowButton,
        OverflowToggleButton,
        Title,
        MDCLib,
        ChartTypeButton,
        ChartSettings,
        ChartSelectionDetailsNew
    ) {
        "use strict";

        /**
         /**
         * Constructor for a new ChartToolbarNew.
         *
         * @param {string} [sId] id for the new control, generated automatically if no id is given
         * @param {object} [mSettings] initial settings for the new control
         * @class The ChartToolbarNew control creates a sap.m.OverflowToolbar based on metadata and the configuration specified.
         * @extends sap.m.OverflowToolbar
         * @author SAP SE
         * @version ${version}
         * @constructor
         * @experimental As of version ...
         * @private
         * @since 1.88
         * @alias sap.ui.mdc.chartNew.ChartToolbarNew
         * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
         */
        var ChartToolbar = ActionToolbar.extend("sap.ui.mdc.chartNew.ChartToolbarNew", /** @lends sap.ui.mdc.chartNew.ChartToolbarNew.prototype */ {
            metadata: {
                library: "sap.ui.mdc",
                interfaces: [],
                defaultAggregation: "",
                properties: {},
                aggregations: {},
                associations: {},
                events: {}
            },
            renderer: OverflowToolbarRenderer
        });

        var MDCRb = sap.ui.getCore().getLibraryResourceBundle("sap.ui.mdc");

        /**
         * Initialises the MDC Chart Selection Details
         *
         * @experimental
         * @private
         * @ui5-restricted sap.ui.mdc
         */
        ChartToolbar.prototype.init = function () {
            ActionToolbar.prototype.init.apply(this, arguments);
        };

        ChartToolbar.prototype.createToolbarContent = function (oMDCChart) {
            this.setEnabled(false);

            /**add beginning**/
            var title = new Title(oMDCChart.getId() + "-title", {
                text: oMDCChart.getHeader()
            });
            this.addBegin(title);

            /**add end **/
            this._oChartSelectionDetails = new ChartSelectionDetailsNew(oMDCChart.getId() + "-selectionDetails", {});
            this._oChartSelectionDetails.attachBeforeOpen(function (oEvent) {
                this._updateSelectionDetailsActions(oMDCChart);
            }.bind(this));

            this.addEnd(this._oChartSelectionDetails);

            if (!oMDCChart.getIgnoreToolbarActions().length || oMDCChart.getIgnoreToolbarActions().indexOf(MDCLib.ChartToolbarActionType.DrillDownUp) < 0) {
                this._oDrillDownBtn = new OverflowButton(oMDCChart.getId() + "-drillDown", {
                    icon: "sap-icon://drill-down",
                    press: function (oEvent) {
                        oMDCChart._showDrillDown(this._oDrillDownBtn);
                    }.bind(this)
                });
                this.addEnd(this._oDrillDownBtn);
            }

            if (!oMDCChart.getIgnoreToolbarActions().length || oMDCChart.getIgnoreToolbarActions().indexOf(MDCLib.ChartToolbarActionType.Legend) < 0) {
                this._oLegendBtn = new OverflowToggleButton(oMDCChart.getId() +  "btnLegend", {
                    type: "Transparent",
                    text: MDCRb.getText("chart.LEGENDBTN_TEXT"),
                    tooltip: MDCRb.getText("chart.LEGENDBTN_TOOLTIP"),
                    icon: "sap-icon://legend",
                    pressed: "{$mdcChart>/legendVisible}"

                });
                this.addEnd(this._oLegendBtn);
            }

            if (!oMDCChart.getIgnoreToolbarActions().length || oMDCChart.getIgnoreToolbarActions().indexOf(MDCLib.ChartToolbarActionType.ZoomInOut)) {
                this.oZoomInButton = new OverflowButton(oMDCChart.getId() + "btnZoomIn", {
                    icon: "sap-icon://zoom-in",
                    press: function onZoomOutButtonPressed(oControlEvent) {
                        oMDCChart.zoomIn();
                        this.toggleZoomButtons(oMDCChart);
                    }.bind(this)
                });

                this.oZoomOutButton = new OverflowButton(oMDCChart.getId() + "btnZoomOut", {
                    icon: "sap-icon://zoom-out",
                    press: function onZoomOutButtonPressed(oControlEvent) {
                        oMDCChart.zoomOut();
                        this.toggleZoomButtons(oMDCChart);
                    }.bind(this)
                });
                this.addEnd(this.oZoomInButton);
                this.addEnd(this.oZoomOutButton);
            }

			//Check p13n mode property on the chart and enable only desired buttons
			var aP13nMode = oMDCChart.getP13nMode() || [];

            if (aP13nMode.indexOf("Item") > -1) {
                this._oSettingsBtn = new OverflowButton(oMDCChart.getId() + "-chart_settings", {
                    icon: "sap-icon://action-settings",//TODO the right icon for P13n chart dialog
                    press: function (oEvent) {
                        var oSource = oEvent.getSource();
                        ChartSettings.showPanel(oMDCChart, "Chart", oSource);
                    }
                });
                this.addEnd(this._oSettingsBtn);
            }

            if (aP13nMode.indexOf("Sort") > -1) {
                this._oSortBtn = new OverflowButton(oMDCChart.getId() + "-sort_settings", {
                    icon: "sap-icon://sort",
                    press: function (oEvent) {
                        var oSource = oEvent.getSource();
                        ChartSettings.showPanel(oMDCChart, "Sort", oSource, oMDCChart._getPropertyData());
                    }
                });
                this.addEnd(this._oSortBtn);
            }

            if (aP13nMode.indexOf("Type") > -1) {
                this._oChartTypeBtn = new ChartTypeButton(oMDCChart);
                this.addEnd(this._oChartTypeBtn);
            }
        };

        ChartToolbar.prototype.toggleZoomButtons = function (oMDCChart) {
            var oZoomInfo = this._getZoomEnablement(oMDCChart);

            if (oZoomInfo.enabled) {
                this.oZoomInButton.setEnabled(oZoomInfo.enabledZoomIn);
                this.oZoomOutButton.setEnabled(oZoomInfo.enabledZoomOut);
            } else {
                this.oZoomInButton.setEnabled(false);
                this.oZoomOutButton.setEnabled(false);
            }

        };

        ChartToolbar.prototype.updateToolbar = function (oMDCChart) {
            this.toggleZoomButtons(oMDCChart);

            if (!this._toolbarInitialUpdated) {
                this.setEnabled(true);
                this._toolbarInitialUpdated = true;
            }

            var oSelectionHandler = oMDCChart.getSelectionHandler();
            this._oChartSelectionDetails.attachSelectionHandler(oSelectionHandler.eventId, oSelectionHandler.listener);
        };

        ChartToolbar.prototype._getZoomEnablement = function (oMDCChart) {
            var zoomInfo = oMDCChart.getZoomState();

            if (zoomInfo && zoomInfo.hasOwnProperty("currentZoomLevel") && zoomInfo.currentZoomLevel != null && zoomInfo.enabled) {
                var toolbarZoomInfo = {enabled: true};

                //TODO: Move this to the delegate since we don't know how other chart librariers handle this
                toolbarZoomInfo.enabledZoomOut = zoomInfo.currentZoomLevel > 0;
                toolbarZoomInfo.enabledZoomIn = zoomInfo.currentZoomLevel < 1;
                return toolbarZoomInfo;
            } else {
                return {enabled: false};
            }
        };

        ChartToolbar.prototype._updateSelectionDetailsActions = function (oMDCChart) {
            var oSelectionDetailsActions = oMDCChart.getSelectionDetailsActions(), oClone;

            if (oSelectionDetailsActions) {
                // Update item actions
                var aSelectionItems = this._oChartSelectionDetails.getItems();

                aSelectionItems.forEach(function (oItem) {
                    var aItemActions = oSelectionDetailsActions.getDetailsItemActions();
                    aItemActions.forEach(function (oAction) {
                        oClone = oAction.clone();
                        oItem.addAction(oClone);
                    });
                });

                // Update list actions
                var aDetailsActions = oSelectionDetailsActions.getDetailsActions();
                this._oChartSelectionDetails.removeAllActions();
                aDetailsActions.forEach(function (oAction) {
                    oClone = oAction.clone();
                    this._oChartSelectionDetails.addAction(oClone);
                }.bind(this));

                // Update group actions
                var aActionGroups = oSelectionDetailsActions.getActionGroups();
                this._oChartSelectionDetails.removeAllActionGroups();
                aActionGroups.forEach(function (oActionGroup) {
                    oClone = oActionGroup.clone();
                    this._oChartSelectionDetails.addActionGroup(oClone);
                }.bind(this));
            }

        };
        return ChartToolbar;
    }, true);
<commit_msg>[INTERNAL] MDC Chart: Fixed issue with Chart Toolbar when no selection handler is present<commit_after>/*!
 * ${copyright}
 */

sap.ui.define([
        "sap/ui/core/Core",
        "sap/ui/mdc/library",
        "sap/ui/mdc/ActionToolbar",
        "sap/m/OverflowToolbarRenderer",
        "sap/m/OverflowToolbarButton",
        "sap/m/OverflowToolbarToggleButton",
        "sap/m/Title",
        "sap/ui/mdc/library",
        "sap/ui/mdc/chartNew/ChartTypeButtonNew",
        "sap/ui/mdc/chart/ChartSettings",
        "./ChartSelectionDetailsNew"
    ],
    function (
        Core,
        Control,
        ActionToolbar,
        OverflowToolbarRenderer,
        OverflowButton,
        OverflowToggleButton,
        Title,
        MDCLib,
        ChartTypeButton,
        ChartSettings,
        ChartSelectionDetailsNew
    ) {
        "use strict";

        /**
         /**
         * Constructor for a new ChartToolbarNew.
         *
         * @param {string} [sId] id for the new control, generated automatically if no id is given
         * @param {object} [mSettings] initial settings for the new control
         * @class The ChartToolbarNew control creates a sap.m.OverflowToolbar based on metadata and the configuration specified.
         * @extends sap.m.OverflowToolbar
         * @author SAP SE
         * @version ${version}
         * @constructor
         * @experimental As of version ...
         * @private
         * @since 1.88
         * @alias sap.ui.mdc.chartNew.ChartToolbarNew
         * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
         */
        var ChartToolbar = ActionToolbar.extend("sap.ui.mdc.chartNew.ChartToolbarNew", /** @lends sap.ui.mdc.chartNew.ChartToolbarNew.prototype */ {
            metadata: {
                library: "sap.ui.mdc",
                interfaces: [],
                defaultAggregation: "",
                properties: {},
                aggregations: {},
                associations: {},
                events: {}
            },
            renderer: OverflowToolbarRenderer
        });

        var MDCRb = sap.ui.getCore().getLibraryResourceBundle("sap.ui.mdc");

        /**
         * Initialises the MDC Chart Selection Details
         *
         * @experimental
         * @private
         * @ui5-restricted sap.ui.mdc
         */
        ChartToolbar.prototype.init = function () {
            ActionToolbar.prototype.init.apply(this, arguments);
        };

        ChartToolbar.prototype.createToolbarContent = function (oMDCChart) {
            this.setEnabled(false);

            /**add beginning**/
            var title = new Title(oMDCChart.getId() + "-title", {
                text: oMDCChart.getHeader()
            });
            this.addBegin(title);

            /**add end **/
            this._oChartSelectionDetails = new ChartSelectionDetailsNew(oMDCChart.getId() + "-selectionDetails", {});
            this._oChartSelectionDetails.attachBeforeOpen(function (oEvent) {
                this._updateSelectionDetailsActions(oMDCChart);
            }.bind(this));

            this.addEnd(this._oChartSelectionDetails);

            if (!oMDCChart.getIgnoreToolbarActions().length || oMDCChart.getIgnoreToolbarActions().indexOf(MDCLib.ChartToolbarActionType.DrillDownUp) < 0) {
                this._oDrillDownBtn = new OverflowButton(oMDCChart.getId() + "-drillDown", {
                    icon: "sap-icon://drill-down",
                    press: function (oEvent) {
                        oMDCChart._showDrillDown(this._oDrillDownBtn);
                    }.bind(this)
                });
                this.addEnd(this._oDrillDownBtn);
            }

            if (!oMDCChart.getIgnoreToolbarActions().length || oMDCChart.getIgnoreToolbarActions().indexOf(MDCLib.ChartToolbarActionType.Legend) < 0) {
                this._oLegendBtn = new OverflowToggleButton(oMDCChart.getId() +  "btnLegend", {
                    type: "Transparent",
                    text: MDCRb.getText("chart.LEGENDBTN_TEXT"),
                    tooltip: MDCRb.getText("chart.LEGENDBTN_TOOLTIP"),
                    icon: "sap-icon://legend",
                    pressed: "{$mdcChart>/legendVisible}"

                });
                this.addEnd(this._oLegendBtn);
            }

            if (!oMDCChart.getIgnoreToolbarActions().length || oMDCChart.getIgnoreToolbarActions().indexOf(MDCLib.ChartToolbarActionType.ZoomInOut)) {
                this.oZoomInButton = new OverflowButton(oMDCChart.getId() + "btnZoomIn", {
                    icon: "sap-icon://zoom-in",
                    press: function onZoomOutButtonPressed(oControlEvent) {
                        oMDCChart.zoomIn();
                        this.toggleZoomButtons(oMDCChart);
                    }.bind(this)
                });

                this.oZoomOutButton = new OverflowButton(oMDCChart.getId() + "btnZoomOut", {
                    icon: "sap-icon://zoom-out",
                    press: function onZoomOutButtonPressed(oControlEvent) {
                        oMDCChart.zoomOut();
                        this.toggleZoomButtons(oMDCChart);
                    }.bind(this)
                });
                this.addEnd(this.oZoomInButton);
                this.addEnd(this.oZoomOutButton);
            }

			//Check p13n mode property on the chart and enable only desired buttons
			var aP13nMode = oMDCChart.getP13nMode() || [];

            if (aP13nMode.indexOf("Item") > -1) {
                this._oSettingsBtn = new OverflowButton(oMDCChart.getId() + "-chart_settings", {
                    icon: "sap-icon://action-settings",//TODO the right icon for P13n chart dialog
                    press: function (oEvent) {
                        var oSource = oEvent.getSource();
                        ChartSettings.showPanel(oMDCChart, "Chart", oSource);
                    }
                });
                this.addEnd(this._oSettingsBtn);
            }

            if (aP13nMode.indexOf("Sort") > -1) {
                this._oSortBtn = new OverflowButton(oMDCChart.getId() + "-sort_settings", {
                    icon: "sap-icon://sort",
                    press: function (oEvent) {
                        var oSource = oEvent.getSource();
                        ChartSettings.showPanel(oMDCChart, "Sort", oSource, oMDCChart._getPropertyData());
                    }
                });
                this.addEnd(this._oSortBtn);
            }

            if (aP13nMode.indexOf("Type") > -1) {
                this._oChartTypeBtn = new ChartTypeButton(oMDCChart);
                this.addEnd(this._oChartTypeBtn);
            }
        };

        ChartToolbar.prototype.toggleZoomButtons = function (oMDCChart) {
            var oZoomInfo = this._getZoomEnablement(oMDCChart);

            if (oZoomInfo.enabled) {
                this.oZoomInButton.setEnabled(oZoomInfo.enabledZoomIn);
                this.oZoomOutButton.setEnabled(oZoomInfo.enabledZoomOut);
            } else {
                this.oZoomInButton.setEnabled(false);
                this.oZoomOutButton.setEnabled(false);
            }

        };

        ChartToolbar.prototype.updateToolbar = function (oMDCChart) {
            this.toggleZoomButtons(oMDCChart);

            if (!this._toolbarInitialUpdated) {
                this.setEnabled(true);
                this._toolbarInitialUpdated = true;
            }

            var oSelectionHandler = oMDCChart.getSelectionHandler();
            if (oSelectionHandler) {
                this._oChartSelectionDetails.attachSelectionHandler(oSelectionHandler.eventId, oSelectionHandler.listener);
            }
        };

        ChartToolbar.prototype._getZoomEnablement = function (oMDCChart) {
            var zoomInfo = oMDCChart.getZoomState();

            if (zoomInfo && zoomInfo.hasOwnProperty("currentZoomLevel") && zoomInfo.currentZoomLevel != null && zoomInfo.enabled) {
                var toolbarZoomInfo = {enabled: true};

                //TODO: Move this to the delegate since we don't know how other chart librariers handle this
                toolbarZoomInfo.enabledZoomOut = zoomInfo.currentZoomLevel > 0;
                toolbarZoomInfo.enabledZoomIn = zoomInfo.currentZoomLevel < 1;
                return toolbarZoomInfo;
            } else {
                return {enabled: false};
            }
        };

        ChartToolbar.prototype._updateSelectionDetailsActions = function (oMDCChart) {
            var oSelectionDetailsActions = oMDCChart.getSelectionDetailsActions(), oClone;

            if (oSelectionDetailsActions) {
                // Update item actions
                var aSelectionItems = this._oChartSelectionDetails.getItems();

                aSelectionItems.forEach(function (oItem) {
                    var aItemActions = oSelectionDetailsActions.getDetailsItemActions();
                    aItemActions.forEach(function (oAction) {
                        oClone = oAction.clone();
                        oItem.addAction(oClone);
                    });
                });

                // Update list actions
                var aDetailsActions = oSelectionDetailsActions.getDetailsActions();
                this._oChartSelectionDetails.removeAllActions();
                aDetailsActions.forEach(function (oAction) {
                    oClone = oAction.clone();
                    this._oChartSelectionDetails.addAction(oClone);
                }.bind(this));

                // Update group actions
                var aActionGroups = oSelectionDetailsActions.getActionGroups();
                this._oChartSelectionDetails.removeAllActionGroups();
                aActionGroups.forEach(function (oActionGroup) {
                    oClone = oActionGroup.clone();
                    this._oChartSelectionDetails.addActionGroup(oClone);
                }.bind(this));
            }

        };
        return ChartToolbar;
    }, true);
<|endoftext|>


<commit_before>//-------------------------------------
//-- Paths
//-------------------------------------
'use strict';

const findUp  = require('find-up');
const path    = require('path');
const slash   = require('slash');
const toolbox = require('./toolbox');

//-- Static properties
const STATIC = global.___NwayoPaths___ ? global.___NwayoPaths___ : global.___NwayoPaths___ = {
	root: (() => {
		const prjConfigFilepath = findUp.sync('nwayo.yaml', { cwd:process.cwd() });
		const prjConfig         = toolbox.readYAML(prjConfigFilepath);

		return path.normalize(`${path.dirname(prjConfigFilepath)}/${prjConfig.root}`);
	})()
};

const BOWER  = 'bower_components';
const CACHE  = '.nwayo-cache';
const NOLINT = 'vendor';

const pattern = {};
pattern.anytree = '**';
pattern.babel   = `^/?##includes##(\\${CACHE}|${BOWER}|components/.*/scripts/${NOLINT}/)`;  // https://regex101.com/r/kIKuJW/1

const ext = {};
ext.bundles   = 'yaml';
ext.fonts     = '{eot,svg,ttf,woff,woff2}';
ext.images    = '{gif,jpg,png,svg}';
ext.scripts   = 'js';
ext.styles    = 'scss';
ext.templates = 'jshtml';

const build = {};
build.fonts   = 'fonts';
build.icons   = 'icons';
build.images  = 'images';
build.raw     = 'raw';
build.scripts = 'scripts';
build.styles  = 'styles';

const folder = {};
folder.cache        = CACHE;
folder.cacheInline  = `${folder.cache}/inline-images`;
folder.cacheSass    = `${folder.cache}/sass`;
folder.cacheScripts = `${folder.cache}/${build.scripts}`;
folder.cacheStyles  = `${folder.cache}/${build.styles}`;

const dir = {};
dir.root         = STATIC.root;
dir.cache        = `${dir.root}/${folder.cache}`;
dir.cacheInline  = `${dir.root}/${folder.cacheInline}`;
dir.cacheSass    = `${dir.root}/${folder.cacheSass}`;
dir.cacheScripts = `${dir.root}/${folder.cacheScripts}`;
dir.cacheStyles  = `${dir.root}/${folder.cacheStyles}`;
dir.bundles      = `${dir.root}/bundles`;
dir.components   = `${dir.root}/components`;
dir.assets       = `${dir.components}/${pattern.anytree}/assets`;
dir.fonts        = `${dir.assets}/fonts`;
dir.icons        = `${dir.assets}/icons`;
dir.images       = `${dir.assets}/images`;
dir.inline       = `${dir.assets}/inline-images`;
dir.raw          = `${dir.assets}/raw`;
dir.scripts      = `${dir.components}/${pattern.anytree}/scripts`;
dir.styles       = `${dir.components}/${pattern.anytree}/styles`;
dir.templates    = `${dir.components}/${pattern.anytree}/templates`;
dir.bower        = `${dir.root}/${BOWER}`;
dir.misc         = `${dir.root}/misc`;
dir.resources    = `${dir.misc}/resources`;
dir.stubs        = `${dir.misc}/stubs`;

const files = {};
files.bundles      = `${dir.bundles}/${pattern.anytree}/*.${ext.bundles}`;
files.fonts        = `${dir.fonts}/${pattern.anytree}/*.${ext.fonts}`;
files.iconsFavicon = `${dir.icons}/favicon.png`;
files.iconsTouch   = `${dir.icons}/touch.png`;
files.iconsIcon    = `${dir.icons}/icon.png`;
files.iconsLarge   = `${dir.icons}/large.png`;
files.iconsTile    = `${dir.icons}/tile.png`;
files.images       = `${dir.images}/${pattern.anytree}/*.${ext.images}`;
files.images2x     = `${dir.images}/${pattern.anytree}/*@2x.${ext.images}`;
files.inline       = `${dir.inline}/${pattern.anytree}/*.${ext.images}`;
files.raw          = `${dir.raw}/${pattern.anytree}/*`;
files.scripts      = `${dir.scripts}/${pattern.anytree}/*.${ext.scripts}`;
files.scriptsLint  = [files.scripts, `!${dir.scripts}/${NOLINT}/${pattern.anytree}/*`];
files.styles       = `${dir.styles}/${pattern.anytree}/*.${ext.styles}`;
files.stylesLint   = [files.styles, `!${dir.styles}/${NOLINT}/${pattern.anytree}/*`];
files.templates    = `${dir.templates}/${pattern.anytree}/*.${ext.templates}`;
files.bowerScripts = `${dir.bower}/${pattern.anytree}/*.${ext.scripts}`;

const filename = {};
filename.konstan        = 'konstan';
filename.konstanLocal   = `${filename.konstan}.json`;
filename.konstanScripts = `${filename.konstan}.${ext.scripts}`;
filename.konstanStyles  = `${filename.konstan}.json`;
filename.modernizr      = `modernizr`;
filename.lodash         = `lodash`;

const workflow = {};
workflow.root       = slash(path.normalize(`${__dirname}/..`));
workflow.cliTasks   = `${workflow.root}/cli`;
workflow.tasks      = `${workflow.root}/tasks`;
workflow.ressources = `${workflow.root}/ressources`;

const config = {};
config.bower           = `${dir.root}/bower.json`;
config.konstan         = `${dir.root}/konstan.yaml`;
config.projectPackage  = `${dir.root}/package.json`;
config.workflowPackage = `${workflow.root}/package.json`;
config.sass            = `${workflow.ressources}/sass.rb`;
config.stylelint       = `${dir.root}/.stylelintrc.yaml`;
config.modernizr       = `${dir.root}/modernizr.yaml`;
config.lodash          = `${dir.root}/lodash.yaml`;
config.lodashBin       = slash(require.resolve('lodash-cli'));
config.babelPresetEnv  = slash(require.resolve('babel-preset-env'));
config.bowerBin        = slash(`${path.dirname(require.resolve('bower'))}/../bin/bower`);

module.exports = class paths {

	static get pattern()  { return pattern; }
	static get ext()      { return ext; }
	static get build()    { return build; }
	static get folder()   { return folder; }
	static get dir()      { return dir; }
	static get files()    { return files; }
	static get filename() { return filename; }
	static get workflow() { return workflow; }
	static get config()   { return config; }

};
<commit_msg>Handle root path via slash to prevent errors for Windows<commit_after>//-------------------------------------
//-- Paths
//-------------------------------------
'use strict';

const findUp  = require('find-up');
const path    = require('path');
const slash   = require('slash');
const toolbox = require('./toolbox');

//-- Static properties
const STATIC = global.___NwayoPaths___ ? global.___NwayoPaths___ : global.___NwayoPaths___ = {
	root: (() => {
		const prjConfigFilepath = findUp.sync('nwayo.yaml', { cwd:process.cwd() });
		const prjConfig         = toolbox.readYAML(prjConfigFilepath);

		return path.normalize(`${path.dirname(prjConfigFilepath)}/${prjConfig.root}`);
	})()
};

const BOWER  = 'bower_components';
const CACHE  = '.nwayo-cache';
const NOLINT = 'vendor';

const pattern = {};
pattern.anytree = '**';
pattern.babel   = `^/?##includes##(\\${CACHE}|${BOWER}|components/.*/scripts/${NOLINT}/)`;  // https://regex101.com/r/kIKuJW/1

const ext = {};
ext.bundles   = 'yaml';
ext.fonts     = '{eot,svg,ttf,woff,woff2}';
ext.images    = '{gif,jpg,png,svg}';
ext.scripts   = 'js';
ext.styles    = 'scss';
ext.templates = 'jshtml';

const build = {};
build.fonts   = 'fonts';
build.icons   = 'icons';
build.images  = 'images';
build.raw     = 'raw';
build.scripts = 'scripts';
build.styles  = 'styles';

const folder = {};
folder.cache        = CACHE;
folder.cacheInline  = `${folder.cache}/inline-images`;
folder.cacheSass    = `${folder.cache}/sass`;
folder.cacheScripts = `${folder.cache}/${build.scripts}`;
folder.cacheStyles  = `${folder.cache}/${build.styles}`;

const dir = {};
dir.root         = slash(STATIC.root);
dir.cache        = `${dir.root}/${folder.cache}`;
dir.cacheInline  = `${dir.root}/${folder.cacheInline}`;
dir.cacheSass    = `${dir.root}/${folder.cacheSass}`;
dir.cacheScripts = `${dir.root}/${folder.cacheScripts}`;
dir.cacheStyles  = `${dir.root}/${folder.cacheStyles}`;
dir.bundles      = `${dir.root}/bundles`;
dir.components   = `${dir.root}/components`;
dir.assets       = `${dir.components}/${pattern.anytree}/assets`;
dir.fonts        = `${dir.assets}/fonts`;
dir.icons        = `${dir.assets}/icons`;
dir.images       = `${dir.assets}/images`;
dir.inline       = `${dir.assets}/inline-images`;
dir.raw          = `${dir.assets}/raw`;
dir.scripts      = `${dir.components}/${pattern.anytree}/scripts`;
dir.styles       = `${dir.components}/${pattern.anytree}/styles`;
dir.templates    = `${dir.components}/${pattern.anytree}/templates`;
dir.bower        = `${dir.root}/${BOWER}`;
dir.misc         = `${dir.root}/misc`;
dir.resources    = `${dir.misc}/resources`;
dir.stubs        = `${dir.misc}/stubs`;

const files = {};
files.bundles      = `${dir.bundles}/${pattern.anytree}/*.${ext.bundles}`;
files.fonts        = `${dir.fonts}/${pattern.anytree}/*.${ext.fonts}`;
files.iconsFavicon = `${dir.icons}/favicon.png`;
files.iconsTouch   = `${dir.icons}/touch.png`;
files.iconsIcon    = `${dir.icons}/icon.png`;
files.iconsLarge   = `${dir.icons}/large.png`;
files.iconsTile    = `${dir.icons}/tile.png`;
files.images       = `${dir.images}/${pattern.anytree}/*.${ext.images}`;
files.images2x     = `${dir.images}/${pattern.anytree}/*@2x.${ext.images}`;
files.inline       = `${dir.inline}/${pattern.anytree}/*.${ext.images}`;
files.raw          = `${dir.raw}/${pattern.anytree}/*`;
files.scripts      = `${dir.scripts}/${pattern.anytree}/*.${ext.scripts}`;
files.scriptsLint  = [files.scripts, `!${dir.scripts}/${NOLINT}/${pattern.anytree}/*`];
files.styles       = `${dir.styles}/${pattern.anytree}/*.${ext.styles}`;
files.stylesLint   = [files.styles, `!${dir.styles}/${NOLINT}/${pattern.anytree}/*`];
files.templates    = `${dir.templates}/${pattern.anytree}/*.${ext.templates}`;
files.bowerScripts = `${dir.bower}/${pattern.anytree}/*.${ext.scripts}`;

const filename = {};
filename.konstan        = 'konstan';
filename.konstanLocal   = `${filename.konstan}.json`;
filename.konstanScripts = `${filename.konstan}.${ext.scripts}`;
filename.konstanStyles  = `${filename.konstan}.json`;
filename.modernizr      = `modernizr`;
filename.lodash         = `lodash`;

const workflow = {};
workflow.root       = slash(path.normalize(`${__dirname}/..`));
workflow.cliTasks   = `${workflow.root}/cli`;
workflow.tasks      = `${workflow.root}/tasks`;
workflow.ressources = `${workflow.root}/ressources`;

const config = {};
config.bower           = `${dir.root}/bower.json`;
config.konstan         = `${dir.root}/konstan.yaml`;
config.projectPackage  = `${dir.root}/package.json`;
config.workflowPackage = `${workflow.root}/package.json`;
config.sass            = `${workflow.ressources}/sass.rb`;
config.stylelint       = `${dir.root}/.stylelintrc.yaml`;
config.modernizr       = `${dir.root}/modernizr.yaml`;
config.lodash          = `${dir.root}/lodash.yaml`;
config.lodashBin       = slash(require.resolve('lodash-cli'));
config.babelPresetEnv  = slash(require.resolve('babel-preset-env'));
config.bowerBin        = slash(`${path.dirname(require.resolve('bower'))}/../bin/bower`);

module.exports = class paths {

	static get pattern()  { return pattern; }
	static get ext()      { return ext; }
	static get build()    { return build; }
	static get folder()   { return folder; }
	static get dir()      { return dir; }
	static get files()    { return files; }
	static get filename() { return filename; }
	static get workflow() { return workflow; }
	static get config()   { return config; }

};
<|endoftext|>


<commit_before>/* eslint no-process-exit: 0 */
"use strict";
require("requirish")._(module);
Error.stackTraceLimit = Infinity;

var argv = require('yargs')
    .wrap(132)
    .string("port")
    .describe("port")
    .alias('p', 'port')
    .argv;

var opcua = require("../index");
var _ = require("underscore");
var path = require("path");
var assert = require("assert");

var OPCUAServer = opcua.OPCUAServer;
var Variant = opcua.Variant;
var DataType = opcua.DataType;
var DataValue = opcua.DataValue;

var standard_nodeset_file = opcua.standard_nodeset_file;

var rootFolder = path.join(__dirname,"../");

var port = parseInt(argv.port) || 26555;
var server_certificate_file            = path.join(rootFolder, "certificates/server_cert_1024.pem");
var server_certificate_privatekey_file = path.join(rootFolder, "certificates/server_key_1024.pem");

var server_options = {
    certificateFile: server_certificate_file,
    privateKeyFile: server_certificate_privatekey_file,
    port: port,
    nodeset_filename: [
        standard_nodeset_file,
        path.join(rootFolder,"modeling/my_data_type.xml")
    ]
};

process.title = "Node OPCUA Server on port : " + server_options.port;

var server = new OPCUAServer(server_options);

var endpointUrl = server.endpoints[0].endpointDescriptions()[0].endpointUrl;

var hostname = require("os").hostname();

server.on("post_initialize", function () {
    var addressSpace = server.engine.addressSpace;
    var rootFolder = addressSpace.findNode("RootFolder");
});

server.start(function (err) {
    if (err) {
        console.log(" Server failed to start ... exiting");
        process.exit(-3);
    }
    console.log("  server on port      :".yellow, server.endpoints[0].port.toString().cyan);
    console.log("  endpointUrl         :".yellow, endpointUrl.cyan);
    console.log("\n  server now waiting for connections. CTRL+C to stop".yellow);
});

process.on('SIGINT', function () {
    // only work on linux apparently
    server.shutdown(1000, function () {
        console.log(" shutting down completed ".red.bold);
        process.exit(-1);
    });
});

<commit_msg>fix server PID console output required by test<commit_after>/* eslint no-process-exit: 0 */
"use strict";
require("requirish")._(module);
Error.stackTraceLimit = Infinity;

var argv = require('yargs')
    .wrap(132)
    .string("port")
    .describe("port")
    .alias('p', 'port')
    .argv;

var opcua = require("../index");
var _ = require("underscore");
var path = require("path");
var assert = require("assert");

var OPCUAServer = opcua.OPCUAServer;
var Variant = opcua.Variant;
var DataType = opcua.DataType;
var DataValue = opcua.DataValue;

var standard_nodeset_file = opcua.standard_nodeset_file;

var rootFolder = path.join(__dirname,"../");

var port = parseInt(argv.port) || 26555;
var server_certificate_file            = path.join(rootFolder, "certificates/server_cert_1024.pem");
var server_certificate_privatekey_file = path.join(rootFolder, "certificates/server_key_1024.pem");

var server_options = {
    certificateFile: server_certificate_file,
    privateKeyFile: server_certificate_privatekey_file,
    port: port,
    nodeset_filename: [
        standard_nodeset_file,
        path.join(rootFolder,"modeling/my_data_type.xml")
    ]
};

process.title = "Node OPCUA Server on port : " + server_options.port;

var server = new OPCUAServer(server_options);

var endpointUrl = server.endpoints[0].endpointDescriptions()[0].endpointUrl;

var hostname = require("os").hostname();

console.log("  server PID          :".yellow, process.pid);

server.on("post_initialize", function () {
    var addressSpace = server.engine.addressSpace;
    var rootFolder = addressSpace.findNode("RootFolder");
});

server.start(function (err) {
    if (err) {
        console.log(" Server failed to start ... exiting");
        process.exit(-3);
    }
    console.log("  server on port      :".yellow, server.endpoints[0].port.toString().cyan);
    console.log("  endpointUrl         :".yellow, endpointUrl.cyan);
    console.log("\n  server now waiting for connections. CTRL+C to stop".yellow);
});

process.on('SIGINT', function () {
    // only work on linux apparently
    server.shutdown(1000, function () {
        console.log(" shutting down completed ".red.bold);
        process.exit(-1);
    });
});

<|endoftext|>


<commit_before>
/**
 * Test different channel shuffle implementation for CNN ShuffleNet.
 *
 * @see {@link https://jsperf.com/colorfulcakechen-cnn-channel-shuffle}
 */

// concat-reshape-transpose-reshape-split
function ConcatReshapeTransposeReshapeSplit( dataTensor3dArray ) {
  return tf.tidy( () => {
    let groupCount = dataTensor3dArray.length;
    let lastAxisId = dataTensor3dArray[ 0 ].rank - 1;

    let dataTensor3d = tf.concat( dataTensor3dArray, lastAxisId );

    let [ h, w, c ] = dataTensor3d.shape;
    let intermediateChannelCount = c / groupCount;

    let x = dataTensor3d.reshape( [ h, w, groupCount, intermediateChannelCount ] );
    x = x.transpose( [ 0, 1, 3, 2 ] );
    x = x.reshape( [ h, w, c] );

    return x = x.split( groupCount, lastAxisId );
  });
}

// concat-gather
function ConcatGather( dataTensor3dArray ) {
  return tf.tidy( () => {
    let groupCount = dataTensor3dArray.length;
    let lastAxisId = dataTensor3dArray[ 0 ].rank - 1;

    let dataTensor3d = tf.concat( dataTensor3dArray, lastAxisId );

    // shuffle and split by gather (one operation achieves two operations).
    let shuffledSplitedTensor3dArray = globalThis.shuffledChannelIndicesTensor1dArray.map(
      ( shuffledChannelIndicesTensor1d, i ) => {
        return dataTensor3d.gather( shuffledChannelIndicesTensor1d, lastAxisId );
    });

    return shuffledSplitedTensor3dArray;
  });
}

// split-concat
function SplitConcat( dataTensor3dArray ) {
  return tf.tidy( () => {
    let groupCount = dataTensor3dArray.length;
    let lastAxisId = dataTensor3dArray[ 0 ].rank - 1;

    let totalChannelCount = groupCount * dataTensor3dArray[ 0 ].shape[ lastAxisId ];
    let intermediateChannelCount = totalChannelCount / groupCount;

    // Split every group (a multiple channel tensor3d) into more (intermediate) channels.
    let tensor3dArrayArray = dataTensor3dArray.map( ( dataTensor3d, i ) => {
      return dataTensor3d.split( intermediateChannelCount, lastAxisId );
    });

    let oneChannelTensor3dArray = tensor3dArrayArray.flat(); // Every element will be a single channel tensor3d.
    let multipleChannelTensor3dArray = new Array( intermediateChannelCount );

    // shuffle and split by concat (one operation achieves two operations).
    let shuffledSplitedTensor3dArray = globalThis.shuffledChannelIndicesArray.map( ( shuffledChannelIndices, i ) => {
//!!!
//       let multipleChannelTensor3dArray = shuffledChannelIndices.map( ( channelIndex ) => {
//         return oneChannelTensor3dArray[ channelIndex ];
//       });

      shuffledChannelIndices.forEach( ( channelIndex, i ) => {
        multipleChannelTensor3dArray[ i ] = oneChannelTensor3dArray[ channelIndex ];
      });

      return tf.concat( multipleChannelTensor3dArray, lastAxisId );
    });

    return shuffledSplitedTensor3dArray;

// !!!
//     let resultTensor3dArray = new Array( groupCount );
//     let shuffledTensor3dArray = new Array( intermediateChannelCount );
//     for ( let x = 0; x < groupCount; ++x ) {
//
//       // Collect x-th intermediate channels of every group as new (x-th) group (i.e. shuffle them).
//       for ( let y = 0; y < intermediateChannelCount; ++y ) {
//         shuffledTensor3dArray[ y ] = tensor3dArrayArray[ x ][ y ];
//       }
//
//       // Concatenate x-th intermediate channels into one group (i.e. the x-th group).
//       resultTensor3dArray[ x ] = tf.concat( shuffledTensor3dArray, lastAxisId );
//     }
//
//     return resultTensor3dArray;
  });
}

// Test concat-reshape-transpose-reshape-split
function by_ConcatReshapeTransposeReshapeSplit( dataTensor3dArray ) {
  tf.tidy( () => {
    ConcatReshapeTransposeReshapeSplit( dataTensor3dArray );
  });
}

// Test concat-gather
function by_ConcatGather( dataTensor3dArray ) {
  tf.tidy( () => {
    ConcatGather( dataTensor3dArray );
  });
}

// Test split-concat
function by_SplitConcat( dataTensor3dArray ) {
  tf.tidy( () => {
    SplitConcat( dataTensor3dArray );
  });
}

let height = 1000; // image height
let width = 1500;  // image width
let depth = 1200;  // image channel count

let valueCount = height * width * depth;

let groupCount = 200; // Split the data into how many groups.

let dataTensor3dArray = tf.tidy( () => {
  let dataTensor1d = tf.linspace(0, valueCount - 1, valueCount );
  let dataTensor3d = dataTensor1d.reshape( [ height, width, depth ] );
  return dataTensor3d.split( groupCount, dataTensor3d.rank - 1 );  // Along the last axis.
});

// Shuffled channel indices tensor1d (One dimension) for ConcatGather()
globalThis.shuffledChannelIndicesTensor1dArray = tf.tidy( () => {
  let channelIndices = tf.linspace( 0, depth - 1, depth ).toInt(); // should be integer so that can be used as gather's index.
  let lastAxisId = channelIndices.rank - 1;

  let intermediateChannelCount = depth / groupCount;

  let x = channelIndices.reshape( [ groupCount, intermediateChannelCount ] );
  x = x.transpose( [ 1, 0 ] );
  x = x.reshape( [ depth ] );

  return x.split( groupCount, lastAxisId );
});

// Shuffled channel indices (One dimension) for SplitConcat()
globalThis.shuffledChannelIndicesArray = new Array( globalThis.shuffledChannelIndicesTensor1dArray.length );
globalThis.shuffledChannelIndicesTensor1dArray.map( ( shuffledChannelIndicesTensor1d, i ) => {
  globalThis.shuffledChannelIndicesArray[ i ] = shuffledChannelIndicesTensor1d.dataSync();
});

//!!!
// Promise.all(
//   globalThis.shuffledChannelIndicesTensor1dArray.map( ( shuffledChannelIndicesTensor1d, i ) => {
//     let p = shuffledChannelIndicesTensor1d.data().then( ( shuffledChannelIndices ) => {
//       globalThis.shuffledChannelIndicesArray[ i ] = shuffledChannelIndices;
//     });
//     return p;
//   })
// ).then( ( values ) => {
//   //globalThis.shuffledChannelIndicesArray = values;
// });

globalThis.dataTensor3dArray = dataTensor3dArray;

globalThis.cnnShuffle_by_ConcatReshapeTransposeReshapeSplit = by_ConcatReshapeTransposeReshapeSplit;
globalThis.cnnShuffle_by_ConcatGather = by_ConcatGather;
globalThis.cnnShuffle_by_SplitConcat = by_SplitConcat;
<commit_msg>Update jsPerf_CNNChannelShuffle.js<commit_after>
/**
 * Test different channel shuffle implementation for CNN ShuffleNet.
 *
 * @see {@link https://jsperf.com/colorfulcakechen-cnn-channel-shuffle}
 */

// concat-reshape-transpose-reshape-split
function ConcatReshapeTransposeReshapeSplit( dataTensor3dArray ) {
  return tf.tidy( () => {
    let groupCount = dataTensor3dArray.length;
    let lastAxisId = dataTensor3dArray[ 0 ].rank - 1;

    let dataTensor3d = tf.concat( dataTensor3dArray, lastAxisId );

    let [ h, w, c ] = dataTensor3d.shape;
    let intermediateChannelCount = c / groupCount;

    let x = dataTensor3d.reshape( [ h, w, groupCount, intermediateChannelCount ] );
    x = x.transpose( [ 0, 1, 3, 2 ] );
    x = x.reshape( [ h, w, c] );

    return x = x.split( groupCount, lastAxisId );
  });
}

// concat-gather
function ConcatGather( dataTensor3dArray ) {
  return tf.tidy( () => {
    let groupCount = dataTensor3dArray.length;
    let lastAxisId = dataTensor3dArray[ 0 ].rank - 1;

    let dataTensor3d = tf.concat( dataTensor3dArray, lastAxisId );

    // shuffle and split by gather (one operation achieves two operations).
    let shuffledSplitedTensor3dArray = globalThis.shuffledChannelIndicesTensor1dArray.map(
      ( shuffledChannelIndicesTensor1d, i ) => {
        return dataTensor3d.gather( shuffledChannelIndicesTensor1d, lastAxisId );
    });

    return shuffledSplitedTensor3dArray;
  });
}

// split-concat
function SplitConcat( dataTensor3dArray ) {
  return tf.tidy( () => {
    let groupCount = dataTensor3dArray.length;
    let lastAxisId = dataTensor3dArray[ 0 ].rank - 1;

    let totalChannelCount = groupCount * dataTensor3dArray[ 0 ].shape[ lastAxisId ];
    let intermediateChannelCount = totalChannelCount / groupCount;

    // Split every group (a multiple channel tensor3d) into more (intermediate) channels.
    let tensor3dArrayArray = dataTensor3dArray.map( ( dataTensor3d, i ) => {
      return dataTensor3d.split( intermediateChannelCount, lastAxisId );
    });

    let oneChannelTensor3dArray = tensor3dArrayArray.flat(); // Every element will be a single channel tensor3d.
    let multipleChannelTensor3dArray = new Array( intermediateChannelCount );

    // shuffle and split by concat (one operation achieves two operations).
    let shuffledSplitedTensor3dArray = globalThis.shuffledChannelIndicesArray.map( ( shuffledChannelIndices, i ) => {
//!!!
//       let multipleChannelTensor3dArray = shuffledChannelIndices.map( ( channelIndex ) => {
//         return oneChannelTensor3dArray[ channelIndex ];
//       });

      shuffledChannelIndices.forEach( ( channelIndex, i ) => {
        multipleChannelTensor3dArray[ i ] = oneChannelTensor3dArray[ channelIndex ];
      });

      return tf.concat( multipleChannelTensor3dArray, lastAxisId );
    });

    return shuffledSplitedTensor3dArray;

// !!!
//     let resultTensor3dArray = new Array( groupCount );
//     let shuffledTensor3dArray = new Array( intermediateChannelCount );
//     for ( let x = 0; x < groupCount; ++x ) {
//
//       // Collect x-th intermediate channels of every group as new (x-th) group (i.e. shuffle them).
//       for ( let y = 0; y < intermediateChannelCount; ++y ) {
//         shuffledTensor3dArray[ y ] = tensor3dArrayArray[ x ][ y ];
//       }
//
//       // Concatenate x-th intermediate channels into one group (i.e. the x-th group).
//       resultTensor3dArray[ x ] = tf.concat( shuffledTensor3dArray, lastAxisId );
//     }
//
//     return resultTensor3dArray;
  });
}

// Test concat-reshape-transpose-reshape-split
function by_ConcatReshapeTransposeReshapeSplit( dataTensor3dArray ) {
  tf.tidy( () => {
    ConcatReshapeTransposeReshapeSplit( dataTensor3dArray );
  });
}

// Test concat-gather
function by_ConcatGather( dataTensor3dArray ) {
  tf.tidy( () => {
    ConcatGather( dataTensor3dArray );
  });
}

// Test split-concat
function by_SplitConcat( dataTensor3dArray ) {
  tf.tidy( () => {
    SplitConcat( dataTensor3dArray );
  });
}

let height = 1000; // image height
let width = 1500;  // image width
let depth = 120;  // image channel count

let valueCount = height * width * depth;

let groupCount = 20; // Split the data into how many groups.

let dataTensor3dArray = tf.tidy( () => {
  let dataTensor1d = tf.linspace(0, valueCount - 1, valueCount );
  let dataTensor3d = dataTensor1d.reshape( [ height, width, depth ] );
  return dataTensor3d.split( groupCount, dataTensor3d.rank - 1 );  // Along the last axis.
});

// Shuffled channel indices tensor1d (One dimension) for ConcatGather()
globalThis.shuffledChannelIndicesTensor1dArray = tf.tidy( () => {
  let channelIndices = tf.linspace( 0, depth - 1, depth ).toInt(); // should be integer so that can be used as gather's index.
  let lastAxisId = channelIndices.rank - 1;

  let intermediateChannelCount = depth / groupCount;

  let x = channelIndices.reshape( [ groupCount, intermediateChannelCount ] );
  x = x.transpose( [ 1, 0 ] );
  x = x.reshape( [ depth ] );

  return x.split( groupCount, lastAxisId );
});

// Shuffled channel indices (One dimension) for SplitConcat()
globalThis.shuffledChannelIndicesArray = new Array( globalThis.shuffledChannelIndicesTensor1dArray.length );
globalThis.shuffledChannelIndicesTensor1dArray.map( ( shuffledChannelIndicesTensor1d, i ) => {
  globalThis.shuffledChannelIndicesArray[ i ] = shuffledChannelIndicesTensor1d.dataSync();
});

//!!!
// Promise.all(
//   globalThis.shuffledChannelIndicesTensor1dArray.map( ( shuffledChannelIndicesTensor1d, i ) => {
//     let p = shuffledChannelIndicesTensor1d.data().then( ( shuffledChannelIndices ) => {
//       globalThis.shuffledChannelIndicesArray[ i ] = shuffledChannelIndices;
//     });
//     return p;
//   })
// ).then( ( values ) => {
//   //globalThis.shuffledChannelIndicesArray = values;
// });

globalThis.dataTensor3dArray = dataTensor3dArray;

globalThis.cnnShuffle_by_ConcatReshapeTransposeReshapeSplit = by_ConcatReshapeTransposeReshapeSplit;
globalThis.cnnShuffle_by_ConcatGather = by_ConcatGather;
globalThis.cnnShuffle_by_SplitConcat = by_SplitConcat;
<|endoftext|>


<commit_before>angular.module("DepotVente").controller('VenteController',['$scope', 'Vente', 'Products',
		function($scope, Vente, Products){
			$scope.vente = new Vente();
			$scope.vente.$save();
			$scope.objet="";
			$scope.listObjet = {
				objet : []
			};
			$scope.prixtotale=0;
			var hauteur = 0;
			var prix = "";
			$scope.type = "";

			$scope.addObject = function(){
				$scope.produit = Products.get({reference: $scope.objet.reference},
					function() {
                		console.log("ajout objet");
                		console.log($scope.produit);
                		$scope.listObjet.objet.push($scope.produit);
						$scope.objet="";
						$scope.prixtotale+=parseFloat($scope.produit.prix);
						$scope.error="";
           			},
           			function(err){
           				console.log(err);
           				$scope.error = err;
           			});
			}

			$scope.deleteObject = function(obj){
				for(i in $scope.listObjet.objet){
			    	if($scope.listObjet.objet[i] === obj){
			        	$scope.listObjet.objet.splice(i, 1);
			        	$scope.prixtotale-=obj.prix;
			        	break;
			    	}
				}
			}

			$scope.validVente = function(){
				if($scope.listObjet.objet.length > 0){
					$scope.payment=true;
					//prix ac comission de 5%
					$scope.prixtotaleAC=$scope.prixtotale+(5*$scope.prixtotale/100);
					console.log('vente validé');
					console.log($scope.listObjet);
					console.log($scope.listObjet.objet);
				}
			}

			var calculDate = function(){
				var m = [
					"Janvier", "Fevrier", "Mars",
					"Avril", "Mai", "Juin", "Juillet",
					"Aout", "Septembre", "Octobre",
					"Novembre", "Decembre"];
				var d = new Date(Date.now());
				var jour = d.getDate();
				var mois = d.getMonth();
				var annee = d.getFullYear();
				var date = (jour + ' ' + m[mois] + ' ' + annee);
				return date;
			}

			$scope.generatePDF = function(){
				console.log('generer pdf');
				var date = calculDate();
				console.log($scope.listObjet.objet[0]);
				var facture = new jsPDF();
				facture.text(20, 20, "Numero de facture : " /*ajout id vente*/);
				facture.text(20, 30, "Date : " + date);
				if($scope.vente.nom && $scope.vente.prenom){
					facture.text(120, 40, $scope.vente.nom + " " + $scope.vente.prenom);
				}
				else if($scope.vente.prenom){
					facture.text(120, 40, $scope.vente.prenom);
				}
				else if($scope.vente.nom){
					facture.text(120, 40, $scope.vente.nom);
				}
				if($scope.vente.adresse){
					facture.text(120, 48, $scope.vente.adresse);
				}
				if($scope.vente.ville){
					facture.text(120, 56, $scope.vente.ville);
				}
				facture.setFontSize(22);
				facture.text(20, 75, "Recapitulatif : ");
				facture.setFontSize(16);
				facture.text(20, 85, "Reference");
				facture.text(60, 85, "Description");
				facture.text(170, 85, "Prix");

				for(var i = 0; i < $scope.listObjet.objet.length; i++){
					hauteur = 95+10*i;
					var p = parseFloat($scope.listObjet.objet[i].prix);
					prix = (p+(5*p/100)).toFixed(2).toString();
					facture.text(20, hauteur, $scope.listObjet.objet[i].reference);
					facture.text(60, hauteur, $scope.listObjet.objet[i].description);
					facture.text(170, hauteur, prix);
				}
				facture.text(100, 225, "Total a payer : " + $scope.prixtotaleAC + " euros");
				if($scope.vente.paiement === "1"){
					$scope.type = "Liquide";
				}
				if($scope.vente.paiement === "2"){
					$scope.type = "Carte Bancaire";
				}
				if($scope.vente.paiement === "3"){
					$scope.type = "Cheque";
				}
				facture.text(100, 235, "Regle par : " + $scope.type);
				facture.save('facture.pdf');
			}

			$scope.annuleVente = function(){
				console.log('annuler vente');
			}
}]);<commit_msg>Correctif facture<commit_after>angular.module("DepotVente").controller('VenteController',['$scope', 'Vente', 'Products',
		function($scope, Vente, Products){
			$scope.vente = new Vente();
			$scope.vente.$save();
			$scope.objet="";
			$scope.listObjet = {
				objet : []
			};
			$scope.prixtotale=0;
			var hauteur = 0;
			var prix = "";
			$scope.type = "";

			$scope.addObject = function(){
				$scope.produit = Products.get({reference: $scope.objet.reference},
					function() {
                		console.log("ajout objet");
                		console.log($scope.produit);
                		$scope.listObjet.objet.push($scope.produit);
						$scope.objet="";
						$scope.prixtotale+=parseFloat($scope.produit.prix);
						$scope.error="";
           			},
           			function(err){
           				console.log(err);
           				$scope.error = err;
           			});
			}

			$scope.deleteObject = function(obj){
				for(i in $scope.listObjet.objet){
			    	if($scope.listObjet.objet[i] === obj){
			        	$scope.listObjet.objet.splice(i, 1);
			        	$scope.prixtotale-=obj.prix;
			        	break;
			    	}
				}
			}

			$scope.validVente = function(){
				if($scope.listObjet.objet.length > 0){
					$scope.payment=true;
					//prix ac comission de 5%
					$scope.prixtotaleAC=$scope.prixtotale+(5*$scope.prixtotale/100);
					console.log('vente validé');
					console.log($scope.listObjet);
					console.log($scope.listObjet.objet);
				}
			}

			var calculDate = function(){
				var m = [
					"Janvier", "Fevrier", "Mars",
					"Avril", "Mai", "Juin", "Juillet",
					"Aout", "Septembre", "Octobre",
					"Novembre", "Decembre"];
				var d = new Date(Date.now());
				var jour = d.getDate();
				var mois = d.getMonth();
				var annee = d.getFullYear();
				var date = (jour + ' ' + m[mois] + ' ' + annee);
				return date;
			}

			$scope.generatePDF = function(){
				console.log('generer pdf');
				var date = calculDate();
				console.log($scope.listObjet.objet[0]);
				var facture = new jsPDF();
				if($scope.display){
					facture.text(20, 20, "Numero de facture : " /*ajout id vente*/);
				}
				facture.text(20, 30, "Date : " + date);
				if($scope.vente.nom && $scope.vente.prenom){
					facture.text(120, 40, $scope.vente.nom + " " + $scope.vente.prenom);
				}
				else if($scope.vente.prenom){
					facture.text(120, 40, $scope.vente.prenom);
				}
				else if($scope.vente.nom){
					facture.text(120, 40, $scope.vente.nom);
				}
				if($scope.vente.adresse){
					facture.text(120, 48, $scope.vente.adresse);
				}
				if($scope.vente.ville){
					facture.text(120, 56, $scope.vente.ville);
				}
				facture.setFontSize(22);
				facture.text(20, 75, "Recapitulatif : ");
				facture.setFontSize(16);
				facture.text(20, 85, "Reference");
				facture.text(60, 85, "Description");
				facture.text(170, 85, "Prix");

				for(var i = 0; i < $scope.listObjet.objet.length; i++){
					hauteur = 95+10*i;
					var p = parseFloat($scope.listObjet.objet[i].prix);
					prix = (p+(5*p/100)).toFixed(2).toString();
					facture.text(20, hauteur, $scope.listObjet.objet[i].reference);
					facture.text(60, hauteur, $scope.listObjet.objet[i].description);
					facture.text(170, hauteur, prix);
				}
				facture.text(100, 225, "Total a payer : " + $scope.prixtotaleAC + " euros");
				if($scope.vente.paiement === "1"){
					$scope.type = "Liquide";
				}
				if($scope.vente.paiement === "2"){
					$scope.type = "Carte Bancaire";
				}
				if($scope.vente.paiement === "3"){
					$scope.type = "Cheque";
				}
				facture.text(100, 235, "Regle par : " + $scope.type);
				facture.save('facture.pdf');
			}

			$scope.annuleVente = function(){
				console.log('annuler vente');
			}
}]);<|endoftext|>


<commit_before>(function() {

	"use strict";

	var utils = modules.Utils,
		once = utils.once,
		pageFactory = modules.PoeticRivals.factories.page;

	pageFactory.Index = function(indexId, jqTemplateClassName, apiUrl, excludedIds, newModelCallback) {

		var page = this;

		pageFactory.Error.call(page);

		var jqTemplate = once(function() {
			return $($("." + page.jqTemplateClassName)[0]).clone();
		});

		var getModelsJSON = function(errorCallback) {
			$.ajax(
				{
					url: page.apiUrl + "?excluded_ids=" + page.excludedIds,
					method: "GET",
					dataType: "json",
					success: page.onGetModelsJSON,
					error: errorCallback
				}
			);
		};

		var onGetModelsJSON = function(modelsJSON) {
			modelsJSON.forEach(function(modelJSON) {
				var model = newModelCallback(modelJSON, page.indexId, page.jqTemplate().clone());
				model.updateJqTemplate();
				model.render();
				page.excludedIds += "," + model.id;
			});
		};

		var onRecordNotProcessed = function(error, errorJqXHR, recordNotFoundCallback, self) {
			console.log("Status %s: %s", error.status, error.title);
			console.log("This should not be possible on this page.");
		}

		page.indexId = indexId;
		page.jqTemplateClassName = jqTemplateClassName;
		page.apiUrl = apiUrl;
		page.excludedIds = excludedIds;
		page.jqTemplate = jqTemplate;
		page.newModelCallback = newModelCallback;
		page.getModelsJSON = getModelsJSON;
		page.onGetModelsJSON = onGetModelsJSON;
		page.onRecordNotProcessed = onRecordNotProcessed;

	}

})();<commit_msg>added an optional call to #afterModelRender to page.Index#onGetModelJson<commit_after>(function() {

	"use strict";

	var utils = modules.Utils,
		once = utils.once,
		pageFactory = modules.PoeticRivals.factories.page;

	pageFactory.Index = function(indexId, jqTemplateClassName, apiUrl, excludedIds, newModelCallback) {

		var page = this;

		pageFactory.Error.call(page);

		var jqTemplate = once(function() {
			return $($("." + page.jqTemplateClassName)[0]).clone();
		});

		var getModelsJSON = function(errorCallback) {
			$.ajax(
				{
					url: page.apiUrl + "?excluded_ids=" + page.excludedIds,
					method: "GET",
					dataType: "json",
					success: page.onGetModelsJSON,
					error: errorCallback
				}
			);
		};

		var onGetModelsJSON = function(modelsJSON) {
			modelsJSON.forEach(function(modelJSON) {
				var model = newModelCallback(modelJSON, page.indexId, page.jqTemplate().clone());
				model.updateJqTemplate();
				model.render();
				if (page.afterModelRender) {
					page.afterModelRender(model);
				}
				page.excludedIds += "," + model.id;
			});
		};

		var onRecordNotProcessed = function(error, errorJqXHR, recordNotFoundCallback, self) {
			console.log("Status %s: %s", error.status, error.title);
			console.log("This should not be possible on this page.");
		}

		page.indexId = indexId;
		page.jqTemplateClassName = jqTemplateClassName;
		page.apiUrl = apiUrl;
		page.excludedIds = excludedIds;
		page.jqTemplate = jqTemplate;
		page.newModelCallback = newModelCallback;
		page.getModelsJSON = getModelsJSON;
		page.onGetModelsJSON = onGetModelsJSON;
		page.onRecordNotProcessed = onRecordNotProcessed;

	}

})();<|endoftext|>