<commit_before>var ws281x = require('rpi-ws281x-native'),
    _ = require('underscore'),
    socket = require('socket.io-client');

var sign = {

    totalLeds: 815,
    intervalRainbow: 10000, // Time in milliseconds for booked appointment to run
    rainbowSpeed: 1,
    rainbowDuration: 5000,
    pixelData: null,
    intervalCycle: null,
    intervalFade: null,
    currentColorIndex: 0,
    cycleDelay: 2500,
    colorFadeDuration: 1000,
    colors : [
        [255,0,0],
        [0,255,0],
        [0,0,255]
    ],

    init: function () {

        this.pixelData = new Uint32Array(this.totalLeds);

        ws281x.init(this.totalLeds);

        this.allGreen();

        socket = socket('https://appointments.spruce.me');

        socket.on('connect', function () {
            console.log('connected');
            this.cycleColors();
        }.bind(this));

        socket.on('did-book-appointments', function () {
            this.rainbow();
        }.bind(this));

    },
    rainbow: function () {

        var offset = 0;

        this.stop();

        var interval = setInterval(function () {

            _(this.totalLeds).times(function(i) {
                this.pixelData[i] = this.colorWheel((offset + i) % 256);
            }.bind(this));

            offset = (offset + 1) % 256;
            this.update();

        }.bind(this), this.rainbowSpeed);

        setTimeout(function() {
            this.stop();
            this.defaultColor();
        }.bind(this), this.rainbowDuration);

        this.intervalRainbow = interval;

    },
    colorWheel: function (pos) {
        pos = 255 - pos;
        if (pos < 85) {
            return this.rgb2Int(255 - pos * 3, 0, pos * 3);
        }
        else if (pos < 170) {
            pos -= 85;
            return this.rgb2Int(0, pos * 3, 255 - pos * 3);
        }
        else {
            pos -= 170;
            return this.rgb2Int(pos * 3, 255 - pos * 3, 0);
        }
    },
    cycleColors : function() {

        this.stop();
        this.rotateColor();

        this.intervalCycle = setInterval(function() {

            this.rotateColor();

        }.bind(this), this.cycleDelay);
    },

    rotateColor: function() {

        //var colors = this.colors[this.currentColorIndex].split(','),
        var start   = {},
            end     = {};

        start.r = this.colors[this.currentColorIndex][0];
        start.g = this.colors[this.currentColorIndex][1];
        start.b = this.colors[this.currentColorIndex][2];

        if(this.currentColorIndex >= (this.colors.length - 1)) {
            this.currentColorIndex = 0;
        } else {
            this.currentColorIndex++;
        }

        end.r = this.colors[this.currentColorIndex][0];
        end.g = this.colors[this.currentColorIndex][1];
        end.b = this.colors[this.currentColorIndex][2];

        this.fade(start, end, this.colorFadeDuration);

    },
    rgb2Int: function (r, g, b) {
        return ((r & 0xff) << 16) + ((g & 0xff) << 8) + (b & 0xff);
    },
    // fill(r, g, b)
    // r, g, b: value as 0 - 255
    fill: function (r, g, b) {

        _(this.totalLeds).times(function(i) {

            this.pixelData[i] = this.rgb2Int(r,g,b);

        }.bind(this));

        this.update();
    },

    stop: function () {

        clearInterval(this.intervalCycle);
        clearInterval(this.intervalFade);
        clearInterval(this.intervalRainbow);

    },
    // linear interpolation between two values a and b
    // u controls amount of a/b and is in range [0.0,1.0]
    getInterpolation :function(a,b,u) {
        return (1-u) * a + u * b;
    },
    fade :function(start, end, duration) {
        var interval = 10,
            steps = duration/interval,
            step_u = 1.0/steps,
            u = 0.0,
            theInterval = setInterval(function(){
                if (u >= 1.0){ clearInterval(theInterval) }
                var r = parseInt(this.getInterpolation(start.r, end.r, u)),
                    g = parseInt(this.getInterpolation(start.g, end.g, u)),
                    b = parseInt(this.getInterpolation(start.b, end.b, u));
                this.fill(r,g,b);
                u += step_u;
            }.bind(this), interval);

        this.intervalFade = theInterval;

    },
    allWhite: function () {
        this.fill(255, 255, 255);
    },
    allBlue: function () {
        this.fill(0, 0, 255);
    },
    allRed: function () {
        this.fill(255, 0, 0);
    },
    allGreen: function () {
        this.fill(0, 255, 0);
    },
    defaultColor: function () {
        this.cycleColors();
    },
    clear: function () {
        ws281x.reset();
    },

    update: function () {
        ws281x.render(this.pixelData);
    }
};

sign.init();

// Do we have any custom commands to run?
var args = process.argv.slice(2);

if (args.length > 0) {
    // We have passed a custom command, lets make sure we call that
    setTimeout(function () {
        sign[args[0]]()
    }, 2500);
}<commit_msg>real cycle<commit_after>var ws281x = require('rpi-ws281x-native'),
    _ = require('underscore'),
    socket = require('socket.io-client');

var sign = {

    totalLeds: 815,
    intervalRainbow: null,
    rainbowSpeed: 1,
    rainbowDuration: 30000, // Time in milliseconds for booked appointment to run
    pixelData: null,
    intervalCycle: null,
    intervalFade: null,
    currentColorIndex: 0,
    cycleDelay: 5000,
    colorFadeDuration: 1000,
    colors : [
        [255,255,255],
        [255,0,0],
        [255,255,255],
        [0,0,255]
    ],

    init: function () {

        this.pixelData = new Uint32Array(this.totalLeds);

        ws281x.init(this.totalLeds);

        this.allGreen();

        socket = socket('https://appointments.spruce.me');

        socket.on('connect', function () {
            console.log('connected');
            this.cycleColors();
        }.bind(this));

        socket.on('did-book-appointments', function () {
            this.stop();
            this.rainbow();
        }.bind(this));

    },
    rainbow: function () {

        var offset = 0;

        var interval = setInterval(function () {

            _(this.totalLeds).times(function(i) {
                this.pixelData[i] = this.colorWheel((offset + i) % 256);
            }.bind(this));

            offset = (offset + 1) % 256;
            this.update();

        }.bind(this), this.rainbowSpeed);

        setTimeout(function() {
            this.stop();
            this.defaultColor();
        }.bind(this), this.rainbowDuration);

        this.intervalRainbow = interval;

    },
    colorWheel: function (pos) {
        pos = 255 - pos;
        if (pos < 85) {
            return this.rgb2Int(255 - pos * 3, 0, pos * 3);
        }
        else if (pos < 170) {
            pos -= 85;
            return this.rgb2Int(0, pos * 3, 255 - pos * 3);
        }
        else {
            pos -= 170;
            return this.rgb2Int(pos * 3, 255 - pos * 3, 0);
        }
    },
    cycleColors : function() {

        //this.stop();
        this.rotateColor();

        this.intervalCycle = setInterval(function() {

            this.rotateColor();

        }.bind(this), this.cycleDelay);
    },

    rotateColor: function() {

        var start   = {},
            end     = {};

        start.r = this.colors[this.currentColorIndex][0];
        start.g = this.colors[this.currentColorIndex][1];
        start.b = this.colors[this.currentColorIndex][2];

        if(this.currentColorIndex >= (this.colors.length - 1)) {
            this.currentColorIndex = 0;
        } else {
            this.currentColorIndex++;
        }

        end.r = this.colors[this.currentColorIndex][0];
        end.g = this.colors[this.currentColorIndex][1];
        end.b = this.colors[this.currentColorIndex][2];

        this.fade(start, end, this.colorFadeDuration);

    },
    rgb2Int: function (r, g, b) {
        return ((r & 0xff) << 16) + ((g & 0xff) << 8) + (b & 0xff);
    },
    // fill(r, g, b)
    // r, g, b: value as 0 - 255
    fill: function (r, g, b) {

        r = Math.abs(r);
        g = Math.abs(g);
        b = Math.abs(b);

        _(this.totalLeds).times(function(i) {

            this.pixelData[i] = this.rgb2Int(r,g,b);

        }.bind(this));

        this.update();
    },

    stop: function () {

        clearInterval(this.intervalCycle);
        clearInterval(this.intervalFade);
        clearInterval(this.intervalRainbow);

    },
    // linear interpolation between two values a and b
    // u controls amount of a/b and is in range [0.0,1.0]
    getInterpolation :function(a,b,u) {
        return (1-u) * a + u * b;
    },
    fade :function(start, end, duration) {
        var interval = 10,
            steps = duration/interval,
            step_u = 1.0/steps,
            u = 0.0,
            theInterval = setInterval(function(){
                if (u >= 1.0){ clearInterval(theInterval) }
                var r = parseInt(this.getInterpolation(start.r, end.r, u)),
                    g = parseInt(this.getInterpolation(start.g, end.g, u)),
                    b = parseInt(this.getInterpolation(start.b, end.b, u));
                this.fill(r,g,b);
                u += step_u;
            }.bind(this), interval);

        this.intervalFade = theInterval;

    },
    allWhite: function () {
        this.fill(255, 255, 255);
    },
    allBlue: function () {
        this.fill(0, 0, 255);
    },
    allRed: function () {
        this.fill(255, 0, 0);
    },
    allGreen: function () {
        this.fill(0, 255, 0);
    },
    allOrange: function() {
        this.fill(170, 50, 0);
    },
    defaultColor: function () {
        this.cycleColors();
    },
    clear: function () {
        ws281x.reset();
    },
    update: function () {
        ws281x.render(this.pixelData);
    }
};

sign.init();

// Do we have any custom commands to run?
var args = process.argv.slice(2);

if (args.length > 0) {
    // We have passed a custom command, lets make sure we call that
    setTimeout(function () {
        sign.stop();
        sign[args[0]]()
    }.bind(this), 2500);
}<|endoftext|>


<commit_before>/**
 * Auto-update the 'latest activity' widget.
 *
 * @mixin
 * @namespace Bolt.activity
 *
 * @param {Object} bolt - The Bolt module.
 * @param {Object} $ - jQuery.
 */
(function (bolt, $) {
    'use strict';

    /**
     * Bolt.activity mixin container.
     *
     * @private
     * @type {Object}
     */
    var activity = {};

    /**
     * Initializes the mixin.
     *
     * @static
     * @function init
     * @memberof Bolt.activity
     */
    activity.init = function () {
        if ($('#latestactivity').is('*')) {
            console.log('activity.init');
            setTimeout(
                function () {
                    //console.log('bolt.activity.update()');
                    bolt.activity.update();
                },
                interval
            );
        }
        bolt.activity.update();
    };

    /**
     * Initializes the mixin.
     *
     * @static
     * @function update
     * @memberof Bolt.activity
     */
    activity.update = function () {
        $.get(
            bolt.conf('paths.async') + 'latestactivity',
            function (data) {
                var newActivity = $(data);

                newActivity.find('.buic-moment').moment();
                $('#latestactivity').empty().append(newActivity);
            }
        );

        setTimeout(
            function () {
                bolt.activity.update();
            },
            interval
        );
    };

    /**
     * Update interval.
     *
     * @private
     * @constant {number} interval
     * @memberof Bolt.activity
     */
    var interval = 30 * 1000; // 30 seconds

    // Apply mixin container
    bolt.activity = activity;

})(Bolt || {}, jQuery);
<commit_msg>Remove debug output<commit_after>/**
 * Auto-update the 'latest activity' widget.
 *
 * @mixin
 * @namespace Bolt.activity
 *
 * @param {Object} bolt - The Bolt module.
 * @param {Object} $ - jQuery.
 */
(function (bolt, $) {
    'use strict';

    /**
     * Bolt.activity mixin container.
     *
     * @private
     * @type {Object}
     */
    var activity = {};

    /**
     * Initializes the mixin.
     *
     * @static
     * @function init
     * @memberof Bolt.activity
     */
    activity.init = function () {
        if ($('#latestactivity').is('*')) {
            setTimeout(
                function () {
                    bolt.activity.update();
                },
                interval
            );
        }
        bolt.activity.update();
    };

    /**
     * Initializes the mixin.
     *
     * @static
     * @function update
     * @memberof Bolt.activity
     */
    activity.update = function () {
        $.get(
            bolt.conf('paths.async') + 'latestactivity',
            function (data) {
                var newActivity = $(data);

                newActivity.find('.buic-moment').moment();
                $('#latestactivity').empty().append(newActivity);
            }
        );

        setTimeout(
            function () {
                bolt.activity.update();
            },
            interval
        );
    };

    /**
     * Update interval.
     *
     * @private
     * @constant {number} interval
     * @memberof Bolt.activity
     */
    var interval = 30 * 1000; // 30 seconds

    // Apply mixin container
    bolt.activity = activity;

})(Bolt || {}, jQuery);
<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash');
const smoochBot = require('smooch-bot');

const scriptRules = require('./script.json');
const Script = require('smooch-bot').Script;

const Bot = smoochBot.Bot;

const MemoryStore = smoochBot.MemoryStore;
const MemoryLock = smoochBot.MemoryLock;

const StateMachine = smoochBot.StateMachine;

module.exports = new Script({

        processing: {
              prompt: (bot) => bot.say('![](http://www.bieg.nl/beeld/speechbubble.gif)'),
               receive: () => 'processing'
         },

        start: {
              receive: (bot,message) => {
                  return bot.say(`${groet}... Wat voor soort hypotheek zoek je? `)
                  .then(() => bot.say(`![](http://www.bieg.nl/beeld/woningen.jpg)`))
                  .then(() => bot.say(`%[Starters Hypotheek](postback:hypotheektype_starter)`))
                  .then(() => bot.say (`%[Nieuwe hypotheek](postback:hypotheektype_nieuw) `))
                  .then(() => bot.say (`%[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`))
                  .then(() => 'selecteerHypotheek');
            }
            }
});

const userId = 'testUserId';
const store = new MemoryStore();
const lock = new MemoryLock();
const bot = new ConsoleBot({
    store,
    lock,
    userId
});

const stateMachine = new StateMachine({
    script,
    bot,
    userId
});

process.stdin.on('data', function(data) {
    stateMachine.receiveMessage({
        text: data.toString().trim()
    })
        .catch((err) => {
            console.error(err);
            console.error(err.stack);
        });
});
<commit_msg>sc<commit_after>'use strict';

const _ = require('lodash')
const Script = require('smooch-bot').Script;
const scriptRules = require('./script.json');

var myDate = new Date();
var groet = '';

/* hour is before noon */
if ( myDate.getHours() < 8 )
{
  groet = "Goeiemorgen 🌝.  Bedankt voor je bezoek maar op dit moment is Independer echter gesloten. 🕘 Uiteraard kun je met onze IndyBot verder praten maar er is helaas niemand die jouw vraag specifiek kan beantwoorden. Je kan je vraag ook doormailen 📩 naar info@independer. Dan komt het altijd goed.";
}
else
if ( myDate.getHours() >= 8 && myDate.getHours() <=12 )
{
  groet = "Goeiemorgen 🌝 ";
}
else  /* Hour is from noon to 5pm (actually to 5:59 pm) */
if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 )
{
groet = "Goedendag 🌞";
}
else  /* the hour is after 5pm, so it is between 6pm and midnight */
if ( myDate.getHours() > 17&& myDate.getHours() <= 20 )
{
groet = "Goedenavond 🌙";
}
else
if (myDate.getHours() > 20  || myDate.getHours() <= 24 )
{
  groet = "Goedenavond 🌙  Bedankt voor je bezoek maar op dit moment is Independer echter gesloten. 🕘 Uiteraard kun je met onze IndyBot verder praten maar er is helaas niemand die jouw vraag specifiek kan beantwoorden. Je kan je vraag ook doormailen 📩 naar info@independer. Dan komt het altijd goed.";
}
else  /* the hour is not between 0 and 24, so something is wrong */
{
groet = "Welkom. ";
}
<|endoftext|>


<commit_before>/*
//1 get user profile
//2 get rit of beebop error
//3 click more buttons
//4 write json for hypo
*/

'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;
const scriptRules = require('./script.json');

var myDate = new Date();
var groet = '';

/* hour is before noon */
if ( myDate.getHours() < 8 )
{
  groet = "Goeiemorgen 🌝.  Bedankt voor je bezoek maar op dit moment is Independer echter gesloten. 🕘 Uiteraard kun je met onze IndyBot verder praten maar er is helaas niemand die jouw vraag specifiek kan beantwoorden. Je kan je vraag ook doormailen 📩 naar info@independer. Dan komt het altijd goed.";
}
else
if ( myDate.getHours() >= 8 && myDate.getHours() <=12 )
{
  groet = "Goeiemorgen 🌝 ";
}
else  /* Hour is from noon to 5pm (actually to 5:59 pm) */
if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 )
{
groet = "Goedendag 🌞";
}
else  /* the hour is after 5pm, so it is between 6pm and midnight */
if ( myDate.getHours() > 17&& myDate.getHours() <= 20 )
{
groet = "Goedenavond 🌙";
}
else
if (myDate.getHours() > 20  || myDate.getHours() <= 24 )
{
  groet = "Goedenavond 🌙  Bedankt voor je bezoek maar op dit moment is Independer echter gesloten. 🕘 Uiteraard kun je met onze IndyBot verder praten maar er is helaas niemand die jouw vraag specifiek kan beantwoorden. Je kan je vraag ook doormailen 📩 naar info@independer. Dan komt het altijd goed.";
}
else  /* the hour is not between 0 and 24, so something is wrong */
{
groet = "Welkom. ";
}

function wait(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}

module.exports = new Script({

 processing: {
prompt: (bot) => bot.say('![](http://www.bieg.nl/beeld/speechbubble.gif)'),
 receive: () => 'processing'
 },

start: {
    receive: (bot,message) => {
        const opening = message.text.trim().toUpperCase();

        return bot.say(`${groet}... Wat voor soort hypotheek zoek je? `)
        .then(() => bot.say(`![](http://www.bieg.nl/beeld/woningen.jpg)`))
        .then(() => bot.say(`%[Starters Hypotheek](postback:hypotheektype_starter)`))
        .then(() => bot.say (`%[Nieuwe hypotheek](postback:hypotheektype_nieuw) `))
        .then(() => bot.say (`%[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`))
        .then(() => 'selecteerHypotheek');
    }
},

.then(
                      => function updateUser() {
                        givenName: 'New',
                        surname: 'Name'
                      })

speak: {
          receive: (bot, message) => {

              const upperText = message.text.trim().toUpperCase();

              function updateSilent() {
                  switch (upperText) {
                      case "CONNECT ME":
                          return bot.setProp("silent", true);
                      case "DISCONNECT":
                          return bot.setProp("silent", false);
                      default:
                          return Promise.resolve();
                  }
              }

              function getSilent() {
                  return bot.getProp("silent");
              }

              function processMessage(isSilent) {
                  if (isSilent) {
                      return Promise.resolve("speak");
                  }

                  /*  CREATE EXTRA JSON FILE FOR HYPO AND INCLUDE IT */
                  if (!_.has(scriptRules, upperText)) {
                      return bot.say('![](http://www.bieg.nl/beeld/speechbubble.gif)').then(() => 'speak');
                  }

                  var response = scriptRules[upperText];
                  var lines = response.split('\n');

                  var p = Promise.resolve();
                  _.each(lines, function(line) {
                      line = line.trim();
                      p = p.then(function() {
                          console.log(line);
                          return wait(50).then(function() {
                              return bot.say(line);
                          });
                      });
                  });

                  return p.then(() => 'speak');
              }

              return updateSilent()
                  .then(getSilent)
                  .then(processMessage);
          }
},

selecteerHypotheek: {
    receive: (bot, message) => {
      switch(message.text) {
      case 'Hoi':
            return bot.say(`${groet} waar ben je naar op zoek? %[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`)
            .then(() => 'askName')
          break;
      case 'Starters Hypotheek':
          return bot.say(`Wat voor type woning zoek je? `)
          .then(() => bot.say(`%[🏬 Appartement](postback:hypotheekkeuze_appartement) %[🏠 Huis](postback:hypotheekkeuze_huis) %[📭 Vakantiewoning](postback:hypotheekkeuze_vakantiewoning)`))
          .then(() => 'woningType')
              break;
        case 'Nieuwe hypotheek':
          return bot.say(`😞 Helaas biedt Independer momenteel alleen Starters een hypotheek aan.`)
          .then(() => bot.say(`Via onderstaande link kun je de beste hypotheekadviseur voor jou vinden. %[💼 Zoek Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/jelocatie.aspx)`))
            .then(() => 'finish')
          break;
        case 'Hypotheek oversluiten':
          return bot.say(`😟 Het spijt me maar op dit moment biedt Independer alleen  Starters een hypotheek.`)
          .then(()=> bot.say(`Als het allemaal wel zo ver is, wil je dan een update ontvangen? %[Ja, dat wil ik wel](postback:update_ja) %[Nee, dat hoeft niet](postback:update_nee)`))
            .then(() => 'updateOntvangen')
          break;
        default:
          return bot.say(`![](http://www.bieg.nl/beeld/speechbubble.gif)`)
            .then(() => 'processing')
          break;
      }
    }
},

updateOntvangen: {
    receive: (bot, message) => {
      switch(message.text) {
        case 'Ja, dat wil ik wel':
            return bot.say(`👍 Leuk, dan houd ik  je op de hoogte zodra er weer nieuws is.`)
            .then(() => 'update_ja');
          break;
          case 'Nee, dat hoeft niet':
              receive: () => 'bye'
              break;
          default:
            receive => 'processing'
            break;
      }
    }
},

update_ja: {
  prompt: (bot) => bot.say('Wat is je email adres?'),
      receive: (bot, message) => {
          const email=message.text;
          return bot.setProp('email', email)
              .then(()  => bot.say(`Ok - ✉  dan hou ik je via ${email} op de hoogte.`))
              .then(()  =>'lastCheck')
    }
},
update_nee: {
  receive: () => 'bye'
},

hypotheekStarter: {
    receive: () => 'askName'
},

hypotheektype_nieuw: {
    prompt: (bot) => bot.say('Independer biedt momenteel alleen voor Starters een hypotheek. Onderstaande link bied je meer informatie %[Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/intro.aspx)'),
    receive: () => 'processing'
},

woningType: {
  receive: (bot, message) => {
    switch(message.text) {
        case '🏬 Appartement':
          return bot.say(`Nice!`)
          .then(() => 'vervolgVragen')
          break;
      case '🏠 Huis':
          return bot.say(`Leuk`)
          .then(() => 'vervolgVragen')
          break;
    case '📭 Vakantiewoning':
          return bot.say(`Gezellig`)
          .then(() => 'vervolgVragen')
          break;
      default:
        receive => 'processing'
        break;
        }
    }
},

vervolgVragen: {
  prompt: (bot) => bot.say(`Hoe heet je eigelijk? 😋`),
          receive: (bot, message) => {
              const Name = message.text;
              return bot.setProp('Name', Name)
                  .then(() => bot.say(`Hoi ${Name}. 📋 Ik heb nog wat vragen voor je om verder te kunnen.`))
                  .then(() => 'processing')            }
},

lastCheck: {
    prompt: (bot) => bot.say(' Is er nog iets waar ik  je bij kan helpen?  🔶  %[Ik zoek meer informatie](postback:meerInfo) %[Nee hoor](postback:bye)'),
          receive: (bot, message) => {
            switch(message.text) {
              case 'Nee hoor':
                  receive: ()  => 'bye'
                  break;
             case 'Ik zoek meer informatie':
                  receive: () => 'speak'
                  break;
            case 'Nee':
                  receive: () => 'bye'
                  break;
            default:
              return bot.say('![](http://www.bieg.nl/beeld/speechbubble.gif)')
                .then(() => 'processing')
              break;
            }
        }
},

meerInfo: {
  prompt: (bot) => bot.say('bestand'),
   receive: () => 'processing'
},

bye: {
    prompt: (bot) => bot.say('Fijn je gesproken te hebben. Bedankt voor je tijd ⏲'),
    receive: ()  => 'finish'
},

// error: {
// prompt: (bot) => bot.say('Sorry - kun je dat nog eens zeggen?  Er ging iets mis...'),
// receive: () => 'pri'
// },

finish: {
receive: () => 'finish'
}
});
<commit_msg>wg<commit_after>/*
//1 get user profile
//2 get rit of beebop error
//3 click more buttons
//4 write json for hypo
*/

'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;
const scriptRules = require('./script.json');

var myDate = new Date();
var groet = '';

/* hour is before noon */
if ( myDate.getHours() < 8 )
{
  groet = "Goeiemorgen 🌝.  Bedankt voor je bezoek maar op dit moment is Independer echter gesloten. 🕘 Uiteraard kun je met onze IndyBot verder praten maar er is helaas niemand die jouw vraag specifiek kan beantwoorden. Je kan je vraag ook doormailen 📩 naar info@independer. Dan komt het altijd goed.";
}
else
if ( myDate.getHours() >= 8 && myDate.getHours() <=12 )
{
  groet = "Goeiemorgen 🌝 ";
}
else  /* Hour is from noon to 5pm (actually to 5:59 pm) */
if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 )
{
groet = "Goedendag 🌞";
}
else  /* the hour is after 5pm, so it is between 6pm and midnight */
if ( myDate.getHours() > 17&& myDate.getHours() <= 20 )
{
groet = "Goedenavond 🌙";
}
else
if (myDate.getHours() > 20  || myDate.getHours() <= 24 )
{
  groet = "Goedenavond 🌙  Bedankt voor je bezoek maar op dit moment is Independer echter gesloten. 🕘 Uiteraard kun je met onze IndyBot verder praten maar er is helaas niemand die jouw vraag specifiek kan beantwoorden. Je kan je vraag ook doormailen 📩 naar info@independer. Dan komt het altijd goed.";
}
else  /* the hour is not between 0 and 24, so something is wrong */
{
groet = "Welkom. ";
}

function wait(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}

module.exports = new Script({

 processing: {
prompt: (bot) => bot.say('![](http://www.bieg.nl/beeld/speechbubble.gif)'),
 receive: () => 'processing'
 },

start: {
    receive: (bot,message) => {
        const opening = message.text.trim().toUpperCase();

        return bot.say(`${groet}... Wat voor soort hypotheek zoek je? `)
        .then(() => bot.say(`![](http://www.bieg.nl/beeld/woningen.jpg)`))
        .then(() => bot.say(`%[Starters Hypotheek](postback:hypotheektype_starter)`))
        .then(() => bot.say (`%[Nieuwe hypotheek](postback:hypotheektype_nieuw) `))
        .then(() => bot.say (`%[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`))
        .then(() => 'selecteerHypotheek');
    }
},

speak: {
          receive: (bot, message) => {

              const upperText = message.text.trim().toUpperCase();

              function updateSilent() {
                  switch (upperText) {
                      case "CONNECT ME":
                          return bot.setProp("silent", true);
                      case "DISCONNECT":
                          return bot.setProp("silent", false);
                      default:
                          return Promise.resolve();
                  }
              }

              function getSilent() {
                  return bot.getProp("silent");
              }

              function processMessage(isSilent) {
                  if (isSilent) {
                      return Promise.resolve("speak");
                  }

                  /*  CREATE EXTRA JSON FILE FOR HYPO AND INCLUDE IT */
                  if (!_.has(scriptRules, upperText)) {
                      return bot.say('![](http://www.bieg.nl/beeld/speechbubble.gif)').then(() => 'speak');
                  }

                  var response = scriptRules[upperText];
                  var lines = response.split('\n');

                  var p = Promise.resolve();
                  _.each(lines, function(line) {
                      line = line.trim();
                      p = p.then(function() {
                          console.log(line);
                          return wait(50).then(function() {
                              return bot.say(line);
                          });
                      });
                  });

                  return p.then(() => 'speak');
              }

              return updateSilent()
                  .then(getSilent)
                  .then(processMessage);
          }
},

selecteerHypotheek: {
    receive: (bot, message) => {
      switch(message.text) {
      case 'Hoi':
            return bot.say(`${groet} waar ben je naar op zoek? %[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`)
            .then(() => 'askName')
          break;
      case 'Starters Hypotheek':
          return bot.say(`Wat voor type woning zoek je? `)
          .then(() => bot.say(`%[🏬 Appartement](postback:hypotheekkeuze_appartement) %[🏠 Huis](postback:hypotheekkeuze_huis) %[📭 Vakantiewoning](postback:hypotheekkeuze_vakantiewoning)`))
          .then(() => 'woningType')
              break;
        case 'Nieuwe hypotheek':
          return bot.say(`😞 Helaas biedt Independer momenteel alleen Starters een hypotheek aan.`)
          .then(() => bot.say(`Via onderstaande link kun je de beste hypotheekadviseur voor jou vinden. %[💼 Zoek Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/jelocatie.aspx)`))
            .then(() => 'finish')
          break;
        case 'Hypotheek oversluiten':
          return bot.say(`😟 Het spijt me maar op dit moment biedt Independer alleen  Starters een hypotheek.`)
          .then(()=> bot.say(`Als het allemaal wel zo ver is, wil je dan een update ontvangen? %[Ja, dat wil ik wel](postback:update_ja) %[Nee, dat hoeft niet](postback:update_nee)`))
            .then(() => 'updateOntvangen')
          break;
        default:
          return bot.say(`![](http://www.bieg.nl/beeld/speechbubble.gif)`)
            .then(() => 'processing')
          break;
      }
    }
},

updateOntvangen: {
    receive: (bot, message) => {
      switch(message.text) {
        case 'Ja, dat wil ik wel':
            return bot.say(`👍 Leuk, dan houd ik  je op de hoogte zodra er weer nieuws is.`)
            .then(() => 'update_ja');
          break;
          case 'Nee, dat hoeft niet':
              receive: () => 'bye'
              break;
          default:
            receive => 'processing'
            break;
      }
    }
},

update_ja: {
  prompt: (bot) => bot.say('Wat is je email adres?'),
      receive: (bot, message) => {
          const email=message.text;
          return bot.setProp('email', email)
              .then(()  => bot.say(`Ok - ✉  dan hou ik je via ${email} op de hoogte.`))
              .then(()  =>'lastCheck')
    }
},
update_nee: {
  receive: () => 'bye'
},

hypotheekStarter: {
    receive: () => 'askName'
},

hypotheektype_nieuw: {
    prompt: (bot) => bot.say('Independer biedt momenteel alleen voor Starters een hypotheek. Onderstaande link bied je meer informatie %[Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/intro.aspx)'),
    receive: () => 'processing'
},

woningType: {
  receive: (bot, message) => {
    switch(message.text) {
        case '🏬 Appartement':
          return bot.say(`Nice!`)
          .then(() => 'vervolgVragen')
          break;
      case '🏠 Huis':
          return bot.say(`Leuk`)
          .then(() => 'vervolgVragen')
          break;
    case '📭 Vakantiewoning':
          return bot.say(`Gezellig`)
          .then(() => 'vervolgVragen')
          break;
      default:
        receive => 'processing'
        break;
        }
    }
},

vervolgVragen: {
  prompt: (bot) => bot.say(`Hoe heet je eigelijk? 😋`),
          receive: (bot, message) => {
              const Name = message.text;
              return bot.setProp('Name', Name)
                  .then(() => bot.say(`Hoi ${Name}. 📋 Ik heb nog wat vragen voor je om verder te kunnen.`))
                  .then(() => 'processing')            }
},

lastCheck: {
    prompt: (bot) => bot.say(' Is er nog iets waar ik  je bij kan helpen?  🔶  %[Ik zoek meer informatie](postback:meerInfo) %[Nee hoor](postback:bye)'),
          receive: (bot, message) => {
            switch(message.text) {
              case 'Nee hoor':
                  receive: ()  => 'bye'
                  break;
             case 'Ik zoek meer informatie':
                  receive: () => 'speak'
                  break;
            case 'Nee':
                  receive: () => 'bye'
                  break;
            default:
              return bot.say('![](http://www.bieg.nl/beeld/speechbubble.gif)')
                .then(() => 'processing')
              break;
            }
        }
},

meerInfo: {
  prompt: (bot) => bot.say('bestand'),
   receive: () => 'processing'
},

bye: {
    prompt: (bot) => bot.say('Fijn je gesproken te hebben. Bedankt voor je tijd ⏲'),
    receive: ()  => 'finish'
},

// error: {
// prompt: (bot) => bot.say('Sorry - kun je dat nog eens zeggen?  Er ging iets mis...'),
// receive: () => 'pri'
// },

finish: {
receive: () => 'finish'
}
});
<|endoftext|>


<commit_before>define([
	"dojo/_base/declare",
	"dojo/_base/event",
	"dojo/_base/lang",
	"dojo/_base/sniff",
	"dojo/_base/window",
	"dojo/dom-class",
	"dojo/dom-construct",
	"dojo/dom-geometry",
	"dojo/dom-style",
	"./_ItemBase",
	"./Badge",
	"./TransitionEvent",
	"./iconUtils",
	"./lazyLoadUtils",
	"./viewRegistry"
], function(declare, event, lang, has, win, domClass, domConstruct, domGeometry, domStyle, ItemBase, Badge, TransitionEvent, iconUtils, lazyLoadUtils, viewRegistry){

	// module:
	//		dojox/mobile/IconItem
	// summary:
	//		An icon item widget.

	return declare("dojox.mobile.IconItem", ItemBase, {
		// summary:
		//		An icon item widget.
		// description:
		//		IconItem represents an item that has an application component
		//		and its icon image. You can tap the icon to open the
		//		corresponding application component. You can also use the icon
		//		to move to a different view by specifying either of the moveTo,
		//		href or url parameters.

		// lazy: String
		//		If true, the content of the widget, which includes dojo markup,
		//		is instantiated lazily. That is, only when the widget is opened
		//		by the user, the required modules are loaded and the content
		//		widgets are instantiated.
		//		This option works both in the sync and async loader mode.
		lazy: false,

		// requires: String
		//		Comma-separated required module names to be lazily loaded. This
		//		property is effective only when lazy=true. All the modules
		//		specified with data-dojo-type and their depending modules are
		//		automatically loaded by the IconItem when it is opened.
		//		However, if you need other extra modules to be loaded, use this parameter.
		//		This option works both in the sync and async loader mode.
		requires: "",

		// timeout: String
		//		Duration of highlight in seconds.
		timeout: 10,

		// content: String
		//		An HTML fragment to embed as icon content.
		content: "",

		// badge: String
		//		A text to show in a badge (ex. "55").
		badge: "",

		// badgeClass: String
		//		A class name of a DOM button for a badge.
		badgeClass: "mblDomButtonRedBadge",

		// deletable: Boolean
		//		If true, you can delete this IconItem by clicking on the delete
		//		icon during edit mode.
		//		If false, the delete icon is not displayed during edit mode so
		//		that it cannot be deleted.
		deletable: true,

		// deleteIcon: String
		//		A delete icon to display at the top-left corner of the item
		//		during edit mode. The value can be either a path for an image
		//		file or a class name of a DOM button.
		deleteIcon: "",

		// tag: String
		//		A name of the HTML tag to create as domNode.
		tag: "li",

		/* internal properties */
		// Note these are overrides for similar properties defined in _ItemBase.
		paramsToInherit: "transition,icon,deleteIcon,badgeClass,deleteIconTitle,deleteIconRole",
		baseClass: "mblIconItem",
		_selStartMethod: "touch",
		_selEndMethod: "none",

		destroy: function(){
			if(this.badgeObj){
				delete this.badgeObj;
			}
			this.inherited(arguments);
		},

		buildRendering: function(){
			this.domNode = this.srcNodeRef || domConstruct.create(this.tag);

			if(this.srcNodeRef){
				// reparent
				this._tmpNode = domConstruct.create("div");
				for(var i = 0, len = this.srcNodeRef.childNodes.length; i < len; i++){
					this._tmpNode.appendChild(this.srcNodeRef.firstChild);
				}
			}

			this.iconDivNode = domConstruct.create("div", {className:"mblIconArea"}, this.domNode);
			this.iconParentNode = domConstruct.create("div", {className:"mblIconAreaInner"}, this.iconDivNode);
			this.labelNode = domConstruct.create("span", {className:"mblIconAreaTitle"}, this.iconDivNode);

			this.inherited(arguments);
		},

		startup: function(){
			if(this._started){ return; }

			var p = this.getParent();
			require([p.iconItemPaneClass], lang.hitch(this, function(module){
				var w = this.paneWidget = new module(p.iconItemPaneProps);
				this.containerNode = w.containerNode;
				if(this._tmpNode){
					// reparent
					for(var i = 0, len = this._tmpNode.childNodes.length; i < len; i++){
						w.containerNode.appendChild(this._tmpNode.firstChild);
					}
					this._tmpNode = null;
				}
				p.paneContainerWidget.addChild(w, this.getIndexInParent());
				w.set("label", this.label);
				this._clickCloseHandle = this.connect(w.closeIconNode, "onclick", "_closeIconClicked");
				this._keydownCloseHandle = this.connect(w.closeIconNode, "onkeydown", "_closeIconClicked"); // for desktop browsers
			}));

			this.inherited(arguments);
			if(!this._isOnLine){
				this._isOnLine = true;
				this.set("icon", this.icon); // retry applying the attribute
			}
			if(!this.icon && p.defaultIcon){
				this.set("icon", p.defaultIcon);
			}

			this._dragstartHandle = this.connect(this.domNode, "ondragstart", event.stop);
			this._keydownHandle = this.connect(this.domNode, "onkeydown", "_onClick"); // for desktop browsers
		},

		highlight: function(/*Number?*/timeout){
			// summary:
			//		Shakes the icon 10 seconds.
			domClass.add(this.iconDivNode, "mblVibrate");
			timeout = (timeout !== undefined) ? timeout : this.timeout;
			if(timeout > 0){
				var _this = this;
				setTimeout(function(){
					_this.unhighlight();
				}, timeout*1000);
			}
		},

		unhighlight: function(){
			// summary:
			//		Stops shaking the icon.
			domClass.remove(this.iconDivNode, "mblVibrate");
		},

		isOpen: function(e){
			// summary:
			//		Returns true if the icon is open.
			return this.paneWidget.isOpen();
		},

		_onClick: function(e){
			// summary:
			//		Internal handler for click events.
			// tags:
			//		private
			if(this.getParent().isEditing || e && e.type === "keydown" && e.keyCode !== 13){ return; }
			if(this.onClick(e) === false){ return; } // user's click action
			this.defaultClickAction(e);
		},

		onClick: function(/*Event*/ /*===== e =====*/){
			// summary:
			//		User-defined function to handle clicks.
			// tags:
			//		callback
		},

		_onNewWindowOpened: function(e){
			// Override from _ItemBase
			this.set("selected", false);
		},

		_prepareForTransition: function(e, transOpts){
			// Override from _ItemBase
			if(transOpts){
				setTimeout(lang.hitch(this, function(d){
					this.set("selected", false);
				}), 1500);
				return true;
			}else{
				if(this.getParent().transition === "below" && this.isOpen()){
					this.close();
				}else{
					this.open(e);
				}
				return false;
			}
		},

		_closeIconClicked: function(e){
			// summary:
			//		Internal handler for click events.
			// tags:
			//		private
			if(e){
				if(e.type === "keydown" && e.keyCode !== 13){ return; }
				if(this.closeIconClicked(e) === false){ return; } // user's click action
				setTimeout(lang.hitch(this, function(d){ this._closeIconClicked(); }), 0);
				return;
			}
			this.close();
		},

		closeIconClicked: function(/*Event*/ /*===== e =====*/){
			// summary:
			//		User-defined function to handle clicks for the close icon.
			// tags:
			//		callback
		},

		open: function(e){
			// summary:
			//		Opens the icon content, or makes a transition.
			var parent = this.getParent(); // IconContainer
			if(this.transition === "below"){
				if(parent.single){
					parent.closeAll();
				}
				this._open_1();
			}else{
				parent._opening = this;
				if(parent.single){
					this.paneWidget.closeHeaderNode.style.display = "none";
					if(!this.isOpen()){
						parent.closeAll();
					}
					parent.appView._heading.set("label", this.label);
				}
				this.moveTo = parent.id + "_mblApplView";
				new TransitionEvent(this.domNode, this.getTransOpts(), e).dispatch();
			}
		},

		_open_1: function(){
			// tags:
			//		private
			this.paneWidget.show();
			this.unhighlight();
			if(this.lazy){
				lazyLoadUtils.instantiateLazyWidgets(this.containerNode, this.requires);
				this.lazy = false;
			}
			this.scrollIntoView(this.paneWidget.domNode);
			this.onOpen();
		},

		scrollIntoView: function(/*DomNode*/node){
			// summary:
			var s = viewRegistry.getEnclosingScrollable(node);
			if(s){ // this node is placed inside scrollable
				s.scrollIntoView(node, true);
			}else{
				win.global.scrollBy(0, domGeometry.position(node, false).y);
			}
		},

		close: function(/*Boolean?*/noAnimation){
			// summary:
			//		Closes the icon content.
			if(!this.isOpen()){ return; }
			this.set("selected", false);
			if(has("webkit") && !noAnimation){
				var contentNode = this.paneWidget.domNode;
				if(this.getParent().transition == "below"){
					domClass.add(contentNode, "mblCloseContent mblShrink");
					var nodePos = domGeometry.position(contentNode, true);
					var targetPos = domGeometry.position(this.domNode, true);
					var origin = (targetPos.x + targetPos.w/2 - nodePos.x) + "px " + (targetPos.y + targetPos.h/2 - nodePos.y) + "px";
					domStyle.set(contentNode, { webkitTransformOrigin:origin });
				}else{
					domClass.add(contentNode, "mblCloseContent mblShrink0");
				}
			}else{
				this.paneWidget.hide();
			}
			this.onClose();
		},

		onOpen: function(){
			// summary:
			//		Stub method to allow the application to connect.
		},

		onClose: function(){
			// summary:
			//		Stub method to allow the application to connect.
		},

		_setLabelAttr: function(/*String*/text){
			// tags:
			//		private
			this.label = text;
			var s = this._cv ? this._cv(text) : text;
			this.labelNode.innerHTML = s;
			if(this.paneWidget){
				this.paneWidget.set("label", text);
			}
		},

		_getBadgeAttr: function(){
			// tags:
			//		private
			return this.badgeObj ? this.badgeObj.getValue() : null;
		},

		_setBadgeAttr: function(/*String*/value){
			// tags:
			//		private
			if(!this.badgeObj){
				this.badgeObj = new Badge({fontSize:14, className:this.badgeClass});
				domStyle.set(this.badgeObj.domNode, {
					position: "absolute",
					top: "-2px",
					right: "2px"
				});
			}
			this.badgeObj.setValue(value);
			if(value){
				this.iconDivNode.appendChild(this.badgeObj.domNode);
			}else{
				this.iconDivNode.removeChild(this.badgeObj.domNode);
			}
		},

		_setDeleteIconAttr: function(icon){
			// tags:
			//		private
			if(!this.getParent()){ return; } // icon may be invalid because inheritParams is not called yet

			this._set("deleteIcon", icon);
			icon = this.deletable ? icon : "";
			this.deleteIconNode = iconUtils.setIcon(icon, this.deleteIconPos, this.deleteIconNode,
					this.deleteIconTitle || this.alt, this.iconDivNode);
			if(this.deleteIconNode){
				domClass.add(this.deleteIconNode, "mblIconItemDeleteIcon");
				if(this.deleteIconRole){
					this.deleteIconNode.setAttribute("role", this.deleteIconRole);
				}
			}
		},

		_setContentAttr: function(/*String|DomNode*/data){
			// tags:
			//		private
			var root;
			if(!this.paneWidget){
				if(!this._tmpNode){
					this._tmpNode = domConstruct.create("div");
				}
				root = this._tmpNode;
			}else{
				root = this.paneWidget.containerNode;
			}

			if(typeof data === "object"){
				domConstruct.empty(root);
				root.appendChild(data);
			}else{
				root.innerHTML = data;
			}
		},

		_setSelectedAttr: function(/*Boolean*/selected){
			// summary:
			//		Makes this widget in the selected or unselected state.
			// tags:
			//		private
			this.inherited(arguments);
			domStyle.set(this.iconNode, "opacity",
						 selected ? this.getParent().pressedIconOpacity : 1);
		}
	});
});
<commit_msg>refs #13101.  Add forgotten summary.<commit_after>define([
	"dojo/_base/declare",
	"dojo/_base/event",
	"dojo/_base/lang",
	"dojo/_base/sniff",
	"dojo/_base/window",
	"dojo/dom-class",
	"dojo/dom-construct",
	"dojo/dom-geometry",
	"dojo/dom-style",
	"./_ItemBase",
	"./Badge",
	"./TransitionEvent",
	"./iconUtils",
	"./lazyLoadUtils",
	"./viewRegistry"
], function(declare, event, lang, has, win, domClass, domConstruct, domGeometry, domStyle, ItemBase, Badge, TransitionEvent, iconUtils, lazyLoadUtils, viewRegistry){

	// module:
	//		dojox/mobile/IconItem
	// summary:
	//		An icon item widget.

	return declare("dojox.mobile.IconItem", ItemBase, {
		// summary:
		//		An icon item widget.
		// description:
		//		IconItem represents an item that has an application component
		//		and its icon image. You can tap the icon to open the
		//		corresponding application component. You can also use the icon
		//		to move to a different view by specifying either of the moveTo,
		//		href or url parameters.

		// lazy: String
		//		If true, the content of the widget, which includes dojo markup,
		//		is instantiated lazily. That is, only when the widget is opened
		//		by the user, the required modules are loaded and the content
		//		widgets are instantiated.
		//		This option works both in the sync and async loader mode.
		lazy: false,

		// requires: String
		//		Comma-separated required module names to be lazily loaded. This
		//		property is effective only when lazy=true. All the modules
		//		specified with data-dojo-type and their depending modules are
		//		automatically loaded by the IconItem when it is opened.
		//		However, if you need other extra modules to be loaded, use this parameter.
		//		This option works both in the sync and async loader mode.
		requires: "",

		// timeout: String
		//		Duration of highlight in seconds.
		timeout: 10,

		// content: String
		//		An HTML fragment to embed as icon content.
		content: "",

		// badge: String
		//		A text to show in a badge (ex. "55").
		badge: "",

		// badgeClass: String
		//		A class name of a DOM button for a badge.
		badgeClass: "mblDomButtonRedBadge",

		// deletable: Boolean
		//		If true, you can delete this IconItem by clicking on the delete
		//		icon during edit mode.
		//		If false, the delete icon is not displayed during edit mode so
		//		that it cannot be deleted.
		deletable: true,

		// deleteIcon: String
		//		A delete icon to display at the top-left corner of the item
		//		during edit mode. The value can be either a path for an image
		//		file or a class name of a DOM button.
		deleteIcon: "",

		// tag: String
		//		A name of the HTML tag to create as domNode.
		tag: "li",

		/* internal properties */
		// Note these are overrides for similar properties defined in _ItemBase.
		paramsToInherit: "transition,icon,deleteIcon,badgeClass,deleteIconTitle,deleteIconRole",
		baseClass: "mblIconItem",
		_selStartMethod: "touch",
		_selEndMethod: "none",

		destroy: function(){
			if(this.badgeObj){
				delete this.badgeObj;
			}
			this.inherited(arguments);
		},

		buildRendering: function(){
			this.domNode = this.srcNodeRef || domConstruct.create(this.tag);

			if(this.srcNodeRef){
				// reparent
				this._tmpNode = domConstruct.create("div");
				for(var i = 0, len = this.srcNodeRef.childNodes.length; i < len; i++){
					this._tmpNode.appendChild(this.srcNodeRef.firstChild);
				}
			}

			this.iconDivNode = domConstruct.create("div", {className:"mblIconArea"}, this.domNode);
			this.iconParentNode = domConstruct.create("div", {className:"mblIconAreaInner"}, this.iconDivNode);
			this.labelNode = domConstruct.create("span", {className:"mblIconAreaTitle"}, this.iconDivNode);

			this.inherited(arguments);
		},

		startup: function(){
			if(this._started){ return; }

			var p = this.getParent();
			require([p.iconItemPaneClass], lang.hitch(this, function(module){
				var w = this.paneWidget = new module(p.iconItemPaneProps);
				this.containerNode = w.containerNode;
				if(this._tmpNode){
					// reparent
					for(var i = 0, len = this._tmpNode.childNodes.length; i < len; i++){
						w.containerNode.appendChild(this._tmpNode.firstChild);
					}
					this._tmpNode = null;
				}
				p.paneContainerWidget.addChild(w, this.getIndexInParent());
				w.set("label", this.label);
				this._clickCloseHandle = this.connect(w.closeIconNode, "onclick", "_closeIconClicked");
				this._keydownCloseHandle = this.connect(w.closeIconNode, "onkeydown", "_closeIconClicked"); // for desktop browsers
			}));

			this.inherited(arguments);
			if(!this._isOnLine){
				this._isOnLine = true;
				this.set("icon", this.icon); // retry applying the attribute
			}
			if(!this.icon && p.defaultIcon){
				this.set("icon", p.defaultIcon);
			}

			this._dragstartHandle = this.connect(this.domNode, "ondragstart", event.stop);
			this._keydownHandle = this.connect(this.domNode, "onkeydown", "_onClick"); // for desktop browsers
		},

		highlight: function(/*Number?*/timeout){
			// summary:
			//		Shakes the icon 10 seconds.
			domClass.add(this.iconDivNode, "mblVibrate");
			timeout = (timeout !== undefined) ? timeout : this.timeout;
			if(timeout > 0){
				var _this = this;
				setTimeout(function(){
					_this.unhighlight();
				}, timeout*1000);
			}
		},

		unhighlight: function(){
			// summary:
			//		Stops shaking the icon.
			domClass.remove(this.iconDivNode, "mblVibrate");
		},

		isOpen: function(e){
			// summary:
			//		Returns true if the icon is open.
			return this.paneWidget.isOpen();
		},

		_onClick: function(e){
			// summary:
			//		Internal handler for click events.
			// tags:
			//		private
			if(this.getParent().isEditing || e && e.type === "keydown" && e.keyCode !== 13){ return; }
			if(this.onClick(e) === false){ return; } // user's click action
			this.defaultClickAction(e);
		},

		onClick: function(/*Event*/ /*===== e =====*/){
			// summary:
			//		User-defined function to handle clicks.
			// tags:
			//		callback
		},

		_onNewWindowOpened: function(e){
			// Override from _ItemBase
			this.set("selected", false);
		},

		_prepareForTransition: function(e, transOpts){
			// Override from _ItemBase
			if(transOpts){
				setTimeout(lang.hitch(this, function(d){
					this.set("selected", false);
				}), 1500);
				return true;
			}else{
				if(this.getParent().transition === "below" && this.isOpen()){
					this.close();
				}else{
					this.open(e);
				}
				return false;
			}
		},

		_closeIconClicked: function(e){
			// summary:
			//		Internal handler for click events.
			// tags:
			//		private
			if(e){
				if(e.type === "keydown" && e.keyCode !== 13){ return; }
				if(this.closeIconClicked(e) === false){ return; } // user's click action
				setTimeout(lang.hitch(this, function(d){ this._closeIconClicked(); }), 0);
				return;
			}
			this.close();
		},

		closeIconClicked: function(/*Event*/ /*===== e =====*/){
			// summary:
			//		User-defined function to handle clicks for the close icon.
			// tags:
			//		callback
		},

		open: function(e){
			// summary:
			//		Opens the icon content, or makes a transition.
			var parent = this.getParent(); // IconContainer
			if(this.transition === "below"){
				if(parent.single){
					parent.closeAll();
				}
				this._open_1();
			}else{
				parent._opening = this;
				if(parent.single){
					this.paneWidget.closeHeaderNode.style.display = "none";
					if(!this.isOpen()){
						parent.closeAll();
					}
					parent.appView._heading.set("label", this.label);
				}
				this.moveTo = parent.id + "_mblApplView";
				new TransitionEvent(this.domNode, this.getTransOpts(), e).dispatch();
			}
		},

		_open_1: function(){
			// tags:
			//		private
			this.paneWidget.show();
			this.unhighlight();
			if(this.lazy){
				lazyLoadUtils.instantiateLazyWidgets(this.containerNode, this.requires);
				this.lazy = false;
			}
			this.scrollIntoView(this.paneWidget.domNode);
			this.onOpen();
		},

		scrollIntoView: function(/*DomNode*/node){
			// summary:
			//		Scrolls until the given node is in the view.
			var s = viewRegistry.getEnclosingScrollable(node);
			if(s){ // this node is placed inside scrollable
				s.scrollIntoView(node, true);
			}else{
				win.global.scrollBy(0, domGeometry.position(node, false).y);
			}
		},

		close: function(/*Boolean?*/noAnimation){
			// summary:
			//		Closes the icon content.
			if(!this.isOpen()){ return; }
			this.set("selected", false);
			if(has("webkit") && !noAnimation){
				var contentNode = this.paneWidget.domNode;
				if(this.getParent().transition == "below"){
					domClass.add(contentNode, "mblCloseContent mblShrink");
					var nodePos = domGeometry.position(contentNode, true);
					var targetPos = domGeometry.position(this.domNode, true);
					var origin = (targetPos.x + targetPos.w/2 - nodePos.x) + "px " + (targetPos.y + targetPos.h/2 - nodePos.y) + "px";
					domStyle.set(contentNode, { webkitTransformOrigin:origin });
				}else{
					domClass.add(contentNode, "mblCloseContent mblShrink0");
				}
			}else{
				this.paneWidget.hide();
			}
			this.onClose();
		},

		onOpen: function(){
			// summary:
			//		Stub method to allow the application to connect.
		},

		onClose: function(){
			// summary:
			//		Stub method to allow the application to connect.
		},

		_setLabelAttr: function(/*String*/text){
			// tags:
			//		private
			this.label = text;
			var s = this._cv ? this._cv(text) : text;
			this.labelNode.innerHTML = s;
			if(this.paneWidget){
				this.paneWidget.set("label", text);
			}
		},

		_getBadgeAttr: function(){
			// tags:
			//		private
			return this.badgeObj ? this.badgeObj.getValue() : null;
		},

		_setBadgeAttr: function(/*String*/value){
			// tags:
			//		private
			if(!this.badgeObj){
				this.badgeObj = new Badge({fontSize:14, className:this.badgeClass});
				domStyle.set(this.badgeObj.domNode, {
					position: "absolute",
					top: "-2px",
					right: "2px"
				});
			}
			this.badgeObj.setValue(value);
			if(value){
				this.iconDivNode.appendChild(this.badgeObj.domNode);
			}else{
				this.iconDivNode.removeChild(this.badgeObj.domNode);
			}
		},

		_setDeleteIconAttr: function(icon){
			// tags:
			//		private
			if(!this.getParent()){ return; } // icon may be invalid because inheritParams is not called yet

			this._set("deleteIcon", icon);
			icon = this.deletable ? icon : "";
			this.deleteIconNode = iconUtils.setIcon(icon, this.deleteIconPos, this.deleteIconNode,
					this.deleteIconTitle || this.alt, this.iconDivNode);
			if(this.deleteIconNode){
				domClass.add(this.deleteIconNode, "mblIconItemDeleteIcon");
				if(this.deleteIconRole){
					this.deleteIconNode.setAttribute("role", this.deleteIconRole);
				}
			}
		},

		_setContentAttr: function(/*String|DomNode*/data){
			// tags:
			//		private
			var root;
			if(!this.paneWidget){
				if(!this._tmpNode){
					this._tmpNode = domConstruct.create("div");
				}
				root = this._tmpNode;
			}else{
				root = this.paneWidget.containerNode;
			}

			if(typeof data === "object"){
				domConstruct.empty(root);
				root.appendChild(data);
			}else{
				root.innerHTML = data;
			}
		},

		_setSelectedAttr: function(/*Boolean*/selected){
			// summary:
			//		Makes this widget in the selected or unselected state.
			// tags:
			//		private
			this.inherited(arguments);
			domStyle.set(this.iconNode, "opacity",
						 selected ? this.getParent().pressedIconOpacity : 1);
		}
	});
});
<|endoftext|>


<commit_before>import { Component, forEach, stopAndPrevent } from 'substance'

export default
class SheetIssuesComponent extends Component {

  didMount() {
    const linter = this.props.editor.getLinter()
    linter.on('issues:changed', this.rerender, this)
  }

  dispose() {
    const linter = this.props.editor.getLinter()
    linter.off(this)
  }

  render($$) {
    const issues = this.props.editor.getIssues()
    let el = $$('div').addClass('sc-sheet-issues-list')
    forEach(issues, (issue) => {
      el.append(this._renderIssue($$, issue))
    })
    return el
  }

  _renderIssue($$, issue) {
    return $$(CellIssueComponent, { issue })
  }

}

class CellIssueComponent extends Component {
  render($$) {
    const issue = this.props.issue
    let el = $$('div').addClass('sc-cell-issue')
    let severity = issue.isError() ? 'error' : 'warning'
    el.addClass(`sm-${severity}`)
    let title = $$('div').addClass('se-title')
      .text(this.getLabel(`title:${severity}`))
    let message = $$('div').addClass('se-message')
      .text(issue.getMessage())
    el.append(
      title,
      message
    )
    el.on('click', this._onClick)
    return el
  }

  _onClick(e) {
    stopAndPrevent(e)
    console.log('Clicked on issue', this.props.issue)
  }
}
<commit_msg>Get message from cell issue.<commit_after>import { Component, forEach, stopAndPrevent } from 'substance'

export default
class SheetIssuesComponent extends Component {

  didMount() {
    const linter = this.props.editor.getLinter()
    linter.on('issues:changed', this.rerender, this)
  }

  dispose() {
    const linter = this.props.editor.getLinter()
    linter.off(this)
  }

  render($$) {
    const issues = this.props.editor.getIssues()
    let el = $$('div').addClass('sc-sheet-issues-list')
    forEach(issues, (issue) => {
      el.append(this._renderIssue($$, issue))
    })
    return el
  }

  _renderIssue($$, issue) {
    return $$(CellIssueComponent, { issue })
  }

}

class CellIssueComponent extends Component {
  render($$) {
    const issue = this.props.issue
    let el = $$('div').addClass('sc-cell-issue')
    let severity = issue.isError() ? 'error' : 'warning'
    el.addClass(`sm-${severity}`)
    let title = $$('div').addClass('se-title')
      .text(this.getLabel(`title:${severity}`))
    let message = $$('div').addClass('se-message')
      .text(issue.message)
    el.append(
      title,
      message
    )
    el.on('click', this._onClick)
    return el
  }

  _onClick(e) {
    stopAndPrevent(e)
    console.log('Clicked on issue', this.props.issue)
  }
}
<|endoftext|>


<commit_before>'use strict';

var log = log4javascript.getLogger("templateController-logger");

angular.module('uluwatuControllers').controller('templateController', ['$scope', '$rootScope', 'UserTemplate', 'GlobalTemplate',
    function ($scope, $rootScope, UserTemplate, GlobalTemplate) {

        $rootScope.volumeTypes = {
            'Gp2': 'SSD',
            'Standard': 'Magnetic'
        }

        $rootScope.awsRegions = {
            'US_EAST_1': 'US East(N. Virginia)',
            'US_WEST_1': 'US West (N. California)',
            'US_WEST_2': 'US West (Oregon)',
            'EU_WEST_1': 'EU (Ireland)',
            'AP_SOUTHEAST_1': 'Asia Pacific (Singapore)',
            'AP_SOUTHEAST_2': 'Asia Pacific (Sydney)',
            'AP_NORTHEAST_1': 'Asia Pacific (Tokyo)',
            'SA_EAST_1': 'South America (São Paulo)'
        }

        $rootScope.amis = {
            'US_EAST_1': 'ami-5edf6136',
            'US_WEST_1': 'ami-4fc1cb0a',
            'US_WEST_2': 'ami-29367a19',
            'EU_WEST_1': 'ami-e66cc191',
            'AP_SOUTHEAST_1': 'ami-7cedcb2e',
            'AP_SOUTHEAST_2': 'ami-2f385515',
            'AP_NORTHEAST_1': 'ami-757e4974',
            'SA_EAST_1': 'ami-91f0448c'
        }

        $rootScope.azureRegions = {
            'BRAZIL_SOUTH': 'Brazil South',
            'EAST_ASIA': 'East Asia',
            'EAST_US': 'East US',
            'NORTH_EUROPE': 'North Europe',
            'WEST_US': 'West US'
        }

        $rootScope.azureVmTypes = {
            'SMALL': 'Small',
            'MEDIUM': 'Medium',
            'LARGE': 'Large',
            'EXTRA_LARGE': 'Extra Large'
        }

        $rootScope.gccRegions = {
            'US_CENTRAL1_A': 'us-central1-a',
            'US_CENTRAL1_B': 'us-central1-b',
            'US_CENTRAL1_F': 'us-central1-f',
            'EUROPE_WEST1_A': 'europe-west1-a',
            'EUROPE_WEST1_B': 'europe-west1-b',
            'ASIA_EAST1_A': 'asia-east1-a',
            'ASIA_EAST1_B': 'asia-east1-b'
        }

        $rootScope.gccDiskTypes = {
            'HDD': 'Magnetic',
            'SSD': 'SSD'
        }

        $rootScope.gccInstanceTypes = {
            'N1_STANDARD_1': 'n1-standard-1',
            'N1_STANDARD_2': 'n1-standard-2',
            'N1_STANDARD_4': 'n1-standard-4',
            'N1_STANDARD_8': 'n1-standard-8',
            'N1_STANDARD_16': 'n1-standard-16',
            'N1_HIGHMEM_2': 'n1-highmem-2',
            'N1_HIGHMEM_4': 'n1-highmem-4',
            'N1_HIGHMEM_8': 'n1-highmem-8',
            'N1_HIGHMEM_16': 'n1-highmem-16',
            'N1_HIGHCPU_2': 'n1-highcpu-2',
            'N1_HIGHCPU_4': 'n1-highcpu-4',
            'N1_HIGHCPU_8': 'n1-highcpu-8',
            'N1_HIGHCPU_16': 'n1-highcpu-16'
        }

        $rootScope.templates = UserTemplate.query();
        $scope.azureTemp = {};
        $scope.gccTemp = {};
        $scope.azureTemp = {};
        $scope.awsTemplateForm = {};
        $scope.gccTemplateForm = {};
        initializeAzureTemp();
        initializeAwsTemp();
        initializeGccTemp();

        $scope.createAwsTemplateRequest = function () {
            $scope.azureTemplate = false;
            $scope.awsTemplate = true;
            $scope.gccTemplate = false;
        }

        $scope.createAzureTemplateRequest = function () {
            $scope.azureTemplate = true;
            $scope.awsTemplate = false;
            $scope.gccTemplate = false;
        }

        $scope.createGccTemplateRequest = function () {
            $scope.azureTemplate = false;
            $scope.awsTemplate = false;
            $scope.gccTemplate = true;
        }

        $scope.createAwsTemplate = function () {
            $scope.awsTemp.cloudPlatform = 'AWS';
            $scope.awsTemp.parameters.amiId = $rootScope.amis[$scope.awsTemp.parameters.region];

            UserTemplate.save($scope.awsTemp, function (result) {
                $scope.awsTemp.id = result.id;
                $rootScope.templates.push($scope.awsTemp);
                initializeAwsTemp();
                $scope.modifyStatusMessage($rootScope.error_msg.aws_template_success1 + result.id + $rootScope.error_msg.aws_template_success2);
                $scope.modifyStatusClass("has-success");
                $scope.awsTemplateForm.$setPristine();
                collapseCreateTemplateFormPanel();
            }, function (error) {
                $scope.modifyStatusMessage($rootScope.error_msg.aws_template_failed + ": " + error.data.message);
                $scope.modifyStatusClass("has-error");
            });
        }

        $scope.createGccTemplate = function () {
            $scope.gccTemp.cloudPlatform = 'GCC';
            $scope.gccTemp.parameters.gccImageType = "DEBIAN_HACK";

            UserTemplate.save($scope.gccTemp, function (result) {
                $scope.gccTemp.id = result.id;
                $rootScope.templates.push($scope.gccTemp);
                initializeGccTemp();
                $scope.modifyStatusMessage($rootScope.error_msg.gcc_template_success1 + result.id + $rootScope.error_msg.gcc_template_success2);
                $scope.modifyStatusClass("has-success");
                $scope.gccTemplateForm.$setPristine();
                collapseCreateTemplateFormPanel();
            }, function (error) {
                $scope.modifyStatusMessage($rootScope.error_msg.gcc_template_failed + ": " + error.data.message);
                $scope.modifyStatusClass("has-error");
            });
        }

        $scope.createAzureTemplate = function () {
            $scope.azureTemp.cloudPlatform = "AZURE";
            $scope.azureTemp.parameters.imageName = "ambari-docker-v1";

            UserTemplate.save($scope.azureTemp, function (result) {
                $scope.azureTemp.id = result.id;
                $rootScope.templates.push($scope.azureTemp);
                initializeAzureTemp();
                $scope.modifyStatusMessage($rootScope.error_msg.azure_template_success1 + result.id + $rootScope.error_msg.azure_template_success2);
                $scope.modifyStatusClass("has-success");
                $scope.azureTemplateForm.$setPristine();
                collapseCreateTemplateFormPanel();
            }, function (error) {
                $scope.modifyStatusMessage($rootScope.error_msg.azure_template_failed + ": " + error.data.message);
                $scope.modifyStatusClass("has-error");
            });
        }

        $scope.deleteTemplate = function (template) {
            GlobalTemplate.delete({ id: template.id }, function (success) {
                $rootScope.templates.splice($rootScope.templates.indexOf(template), 1);
                $scope.modifyStatusMessage($rootScope.error_msg.template_delete_success1 + template.id + $rootScope.error_msg.template_delete_success2);
                $scope.modifyStatusClass("has-success");
            }, function (error) {
                $scope.modifyStatusMessage($rootScope.error_msg.template_delete_failed + ": " + error.data.message);
                $scope.modifyStatusClass("has-error");
            });
        }

        function collapseCreateTemplateFormPanel() {
          angular.element(document.querySelector('#panel-create-templates-collapse-btn')).click();
        }

        function initializeAwsTemp() {
            $scope.awsTemp = {
                parameters: {
                    sshLocation: "0.0.0.0/0",
                    region: "EU_WEST_1",
                    instanceType: "T2Medium",
                    volumeType: "Standard"
                }
            }
        }

        function initializeAzureTemp() {
            $scope.azureTemp = {
                parameters: {
                    location: "NORTH_EUROPE",
                    vmType: "MEDIUM"
                }
            }
        }

        function initializeGccTemp() {
            $scope.gccTemp = {
                parameters: {
                    gccInstanceType: "N1_STANDARD_2",
                    gccZone: "EUROPE_WEST1_A",
                    volumeType: "HDD"
                }
            }
        }
    }
]);
<commit_msg>CLOUD-262 new zone in default template<commit_after>'use strict';

var log = log4javascript.getLogger("templateController-logger");

angular.module('uluwatuControllers').controller('templateController', ['$scope', '$rootScope', 'UserTemplate', 'GlobalTemplate',
    function ($scope, $rootScope, UserTemplate, GlobalTemplate) {

        $rootScope.volumeTypes = {
            'Gp2': 'SSD',
            'Standard': 'Magnetic'
        }

        $rootScope.awsRegions = {
            'US_EAST_1': 'US East(N. Virginia)',
            'US_WEST_1': 'US West (N. California)',
            'US_WEST_2': 'US West (Oregon)',
            'EU_WEST_1': 'EU (Ireland)',
            'AP_SOUTHEAST_1': 'Asia Pacific (Singapore)',
            'AP_SOUTHEAST_2': 'Asia Pacific (Sydney)',
            'AP_NORTHEAST_1': 'Asia Pacific (Tokyo)',
            'SA_EAST_1': 'South America (São Paulo)'
        }

        $rootScope.amis = {
            'US_EAST_1': 'ami-5edf6136',
            'US_WEST_1': 'ami-4fc1cb0a',
            'US_WEST_2': 'ami-29367a19',
            'EU_WEST_1': 'ami-e66cc191',
            'AP_SOUTHEAST_1': 'ami-7cedcb2e',
            'AP_SOUTHEAST_2': 'ami-2f385515',
            'AP_NORTHEAST_1': 'ami-757e4974',
            'SA_EAST_1': 'ami-91f0448c'
        }

        $rootScope.azureRegions = {
            'BRAZIL_SOUTH': 'Brazil South',
            'EAST_ASIA': 'East Asia',
            'EAST_US': 'East US',
            'NORTH_EUROPE': 'North Europe',
            'WEST_US': 'West US'
        }

        $rootScope.azureVmTypes = {
            'SMALL': 'Small',
            'MEDIUM': 'Medium',
            'LARGE': 'Large',
            'EXTRA_LARGE': 'Extra Large'
        }

        $rootScope.gccRegions = {
            'US_CENTRAL1_A': 'us-central1-a',
            'US_CENTRAL1_B': 'us-central1-b',
            'US_CENTRAL1_F': 'us-central1-f',
            'EUROPE_WEST1_A': 'europe-west1-a',
            'EUROPE_WEST1_B': 'europe-west1-b',
            'ASIA_EAST1_A': 'asia-east1-a',
            'ASIA_EAST1_B': 'asia-east1-b'
        }

        $rootScope.gccDiskTypes = {
            'HDD': 'Magnetic',
            'SSD': 'SSD'
        }

        $rootScope.gccInstanceTypes = {
            'N1_STANDARD_1': 'n1-standard-1',
            'N1_STANDARD_2': 'n1-standard-2',
            'N1_STANDARD_4': 'n1-standard-4',
            'N1_STANDARD_8': 'n1-standard-8',
            'N1_STANDARD_16': 'n1-standard-16',
            'N1_HIGHMEM_2': 'n1-highmem-2',
            'N1_HIGHMEM_4': 'n1-highmem-4',
            'N1_HIGHMEM_8': 'n1-highmem-8',
            'N1_HIGHMEM_16': 'n1-highmem-16',
            'N1_HIGHCPU_2': 'n1-highcpu-2',
            'N1_HIGHCPU_4': 'n1-highcpu-4',
            'N1_HIGHCPU_8': 'n1-highcpu-8',
            'N1_HIGHCPU_16': 'n1-highcpu-16'
        }

        $rootScope.templates = UserTemplate.query();
        $scope.azureTemp = {};
        $scope.gccTemp = {};
        $scope.azureTemp = {};
        $scope.awsTemplateForm = {};
        $scope.gccTemplateForm = {};
        initializeAzureTemp();
        initializeAwsTemp();
        initializeGccTemp();

        $scope.createAwsTemplateRequest = function () {
            $scope.azureTemplate = false;
            $scope.awsTemplate = true;
            $scope.gccTemplate = false;
        }

        $scope.createAzureTemplateRequest = function () {
            $scope.azureTemplate = true;
            $scope.awsTemplate = false;
            $scope.gccTemplate = false;
        }

        $scope.createGccTemplateRequest = function () {
            $scope.azureTemplate = false;
            $scope.awsTemplate = false;
            $scope.gccTemplate = true;
        }

        $scope.createAwsTemplate = function () {
            $scope.awsTemp.cloudPlatform = 'AWS';
            $scope.awsTemp.parameters.amiId = $rootScope.amis[$scope.awsTemp.parameters.region];

            UserTemplate.save($scope.awsTemp, function (result) {
                $scope.awsTemp.id = result.id;
                $rootScope.templates.push($scope.awsTemp);
                initializeAwsTemp();
                $scope.modifyStatusMessage($rootScope.error_msg.aws_template_success1 + result.id + $rootScope.error_msg.aws_template_success2);
                $scope.modifyStatusClass("has-success");
                $scope.awsTemplateForm.$setPristine();
                collapseCreateTemplateFormPanel();
            }, function (error) {
                $scope.modifyStatusMessage($rootScope.error_msg.aws_template_failed + ": " + error.data.message);
                $scope.modifyStatusClass("has-error");
            });
        }

        $scope.createGccTemplate = function () {
            $scope.gccTemp.cloudPlatform = 'GCC';
            $scope.gccTemp.parameters.gccImageType = "DEBIAN_HACK";

            UserTemplate.save($scope.gccTemp, function (result) {
                $scope.gccTemp.id = result.id;
                $rootScope.templates.push($scope.gccTemp);
                initializeGccTemp();
                $scope.modifyStatusMessage($rootScope.error_msg.gcc_template_success1 + result.id + $rootScope.error_msg.gcc_template_success2);
                $scope.modifyStatusClass("has-success");
                $scope.gccTemplateForm.$setPristine();
                collapseCreateTemplateFormPanel();
            }, function (error) {
                $scope.modifyStatusMessage($rootScope.error_msg.gcc_template_failed + ": " + error.data.message);
                $scope.modifyStatusClass("has-error");
            });
        }

        $scope.createAzureTemplate = function () {
            $scope.azureTemp.cloudPlatform = "AZURE";
            $scope.azureTemp.parameters.imageName = "ambari-docker-v1";

            UserTemplate.save($scope.azureTemp, function (result) {
                $scope.azureTemp.id = result.id;
                $rootScope.templates.push($scope.azureTemp);
                initializeAzureTemp();
                $scope.modifyStatusMessage($rootScope.error_msg.azure_template_success1 + result.id + $rootScope.error_msg.azure_template_success2);
                $scope.modifyStatusClass("has-success");
                $scope.azureTemplateForm.$setPristine();
                collapseCreateTemplateFormPanel();
            }, function (error) {
                $scope.modifyStatusMessage($rootScope.error_msg.azure_template_failed + ": " + error.data.message);
                $scope.modifyStatusClass("has-error");
            });
        }

        $scope.deleteTemplate = function (template) {
            GlobalTemplate.delete({ id: template.id }, function (success) {
                $rootScope.templates.splice($rootScope.templates.indexOf(template), 1);
                $scope.modifyStatusMessage($rootScope.error_msg.template_delete_success1 + template.id + $rootScope.error_msg.template_delete_success2);
                $scope.modifyStatusClass("has-success");
            }, function (error) {
                $scope.modifyStatusMessage($rootScope.error_msg.template_delete_failed + ": " + error.data.message);
                $scope.modifyStatusClass("has-error");
            });
        }

        function collapseCreateTemplateFormPanel() {
          angular.element(document.querySelector('#panel-create-templates-collapse-btn')).click();
        }

        function initializeAwsTemp() {
            $scope.awsTemp = {
                parameters: {
                    sshLocation: "0.0.0.0/0",
                    region: "EU_WEST_1",
                    instanceType: "T2Medium",
                    volumeType: "Standard"
                }
            }
        }

        function initializeAzureTemp() {
            $scope.azureTemp = {
                parameters: {
                    location: "NORTH_EUROPE",
                    vmType: "MEDIUM"
                }
            }
        }

        function initializeGccTemp() {
            $scope.gccTemp = {
                parameters: {
                    gccInstanceType: "N1_STANDARD_2",
                    gccZone: "EUROPE_WEST1_B",
                    volumeType: "HDD"
                }
            }
        }
    }
]);
<|endoftext|>


<commit_before>(function(env) {
    "use strict";
    env.ddg_spice_github = function(api_result) {

        if (!api_result || !api_result.meta.status === 200) {
          return Spice.failed('github');
        }

        var script = $('[src*="/js/spice/github/"]')[0],
                    source = $(script).attr("src"),
                    query = source.match(/github\/([^\/]+)/)[1];

        var results = api_result.data.items;

        if (!results) {
            return Spice.failed('github');
        }

        // TODO: temp size limit - relevancy block should handle this later
        if (results.length > 30)
            results = results.splice(0,30);

        Spice.add({
            id: "github",
            name: "Software",
            data: results,
            meta: {
                itemType: "Git Repositories",
                sourceUrl: 'http://www.github.com/search?q=' +  encodeURIComponent(query),
                sourceName: 'GitHub'
            },
            templates: {
            group: 'text',
                    detail: false,
                    item_detail: false,
                    options: {
                        footer: Spice.github.footer
                    }
                },
            normalize: function(item) {
                return {
                    title: item.name,
                    subtitle: item.owner + "/" + item.name,
		    url: item.html_url
                };
            },
            relevancy: {
                primary: [
                    { key: 'description', match: /.+/, strict: false } // Reject things without a description.
                ]
            },
            sort_fields: {
                watchers: function(a, b) {
                    var x = a.watchers;
                    var y = b.watchers;
                    return ((x < y) ? 1 : ((x > y) ? -1 : 0));
                }
            },
            sort_default: 'watchers'
        });
    }
}(this));

// Make sure we display only three items.
Handlebars.registerHelper("GitHub_last_pushed", function(pushed_at) {
    "use strict";

    var last_pushed = Math.floor((new Date() - new Date(pushed_at)) / (1000*60*60*24));

    var years_ago = Math.floor(last_pushed / 365);
    if (years_ago >= 1) {
        last_pushed = years_ago + " year" + (years_ago == 1 ? "" : "s") + " ago";
    } else if (last_pushed == 0) {
        last_pushed = "today";
    } else if (last_pushed == 1) {
        last_pushed = "yesterday";
    } else {
        last_pushed = last_pushed + " day" + (last_pushed == 1 ? "" : "s") + " ago";
    }

    return last_pushed;
});

<commit_msg>fixed the user name rendering as [object]<commit_after>(function(env) {
    "use strict";
    env.ddg_spice_github = function(api_result) {

        if (!api_result || !api_result.meta.status === 200) {
          return Spice.failed('github');
        }

        var script = $('[src*="/js/spice/github/"]')[0],
                    source = $(script).attr("src"),
                    query = source.match(/github\/([^\/]+)/)[1];

        var results = api_result.data.items;

        if (!results) {
            return Spice.failed('github');
        }

        // TODO: temp size limit - relevancy block should handle this later
        if (results.length > 30)
            results = results.splice(0,30);

        Spice.add({
            id: "github",
            name: "Software",
            data: results,
            meta: {
                itemType: "Git Repositories",
                sourceUrl: 'http://www.github.com/search?q=' +  encodeURIComponent(query),
                sourceName: 'GitHub'
            },
            templates: {
            group: 'text',
                    detail: false,
                    item_detail: false,
                    options: {
                        footer: Spice.github.footer
                    }
                },
            normalize: function(item) {
                return {
                    title: item.name,
                    subtitle: item.owner.login + "/" + item.name,
		    url: item.html_url
                };
            },
            relevancy: {
                primary: [
                    { key: 'description', match: /.+/, strict: false } // Reject things without a description.
                ]
            },
            sort_fields: {
                watchers: function(a, b) {
                    var x = a.watchers;
                    var y = b.watchers;
                    return ((x < y) ? 1 : ((x > y) ? -1 : 0));
                }
            },
            sort_default: 'watchers'
        });
    }
}(this));

// Make sure we display only three items.
Handlebars.registerHelper("GitHub_last_pushed", function(pushed_at) {
    "use strict";

    var last_pushed = Math.floor((new Date() - new Date(pushed_at)) / (1000*60*60*24));

    var years_ago = Math.floor(last_pushed / 365);
    if (years_ago >= 1) {
        last_pushed = years_ago + " year" + (years_ago == 1 ? "" : "s") + " ago";
    } else if (last_pushed == 0) {
        last_pushed = "today";
    } else if (last_pushed == 1) {
        last_pushed = "yesterday";
    } else {
        last_pushed = last_pushed + " day" + (last_pushed == 1 ? "" : "s") + " ago";
    }

    return last_pushed;
});

<|endoftext|>


<commit_before>import BaseCtrl from '../base/base.controller';

export default class FormCtrl extends BaseCtrl {
  constructor($scope, DebugService, $stateParams, CRUDService, AlertService, PayloadService) {
    super($scope, DebugService, $stateParams, CRUDService, AlertService, undefined, PayloadService);
  }

  loader(pageIndex, pageSize) {
    var vm = this;
    var params = {
      catalogName: vm.$stateParams.catalogName,
      controlType: 'formView',
      mode: vm.$stateParams.mode,
      filters: vm.$stateParams.filters || '',
      getData: '1',
      getStructure: '1',
      pageIndex: pageIndex || parseInt(vm.$stateParams.pageIndex) || 1,
      pageSize: pageSize || parseInt(vm.$stateParams.pageSize) || 1
    };
    if(vm.$stateParams.id) {
      // Fallback options
      var idKey = vm.$stateParams.identityKey ||
                  vm.$stateParams.primaryKey ||
                  '$identity' || // Supported in SQL Server only for tables
                  'id';       // Last resort
      params.filters += '[' + idKey + '=' + vm.$stateParams.id + ']';
    }
    vm.CRUDService.read(params).then(function (res) {
      // Main `options' object
      // to be consumed by directive(s)
      vm.options = {
        metadata: res.data.data.metadata,
        fields: res.data.data.fields,
        data: res.data.data.model || [],
        opts: vm.getOpts()
      };

      vm.$scope.$emit('setPanelTitle', (function () {
        if(vm.$stateParams.mode === 'insert') return 'New ';
        if(vm.$stateParams.mode === 'edit') return 'Edit ';
        if(vm.$stateParams.mode === 'readonly') return 'View ';
        if(vm.$stateParams.mode === 'filters') return 'Filters ';
      })() + vm.options.metadata.tableName);
      // Set `vm.loaderOnce` at first `vm.loader()` call
      if(vm.loadedOnce === undefined) {
        vm.loadedOnce = true;
      }
    });
  }

  getOpts() {
    var vm = this;
    return {
      asyncPagination: true,
      showPaginationRow: true,
      showSaveRow: vm.$stateParams.mode === 'edit' || vm.$stateParams.mode === 'insert',
      showFilterRow: vm.$stateParams.mode === 'filters'
    };
  }

  /*
  Common Handlers
  (unique & overriden from BaseCtrl)
   */

  onReset() {
    // // ToDo: Confirm
    // // vm.loader();
    // Alt: http://angular-formly.com/#/example/form-options/reset-model
    // ToDo: Confirm
    if (vm.form) {
      // http://jsbin.com/zaqeke
      //vm.$scope.options.resetModel();
      vm.form.$setPristine();
      vm.form.$setUntouched();
    }
  }

  onCancel() {
    // ToDo: Confirm of unsaved dirty form otherwise/then Go Back
    console.log("CANCEL");
  }

  onSubmit(fields, data) {
    var vm = this;
    if (vm.form.$valid) {
      /**
       * Create payload to be sent
       */
      var payload = vm.PayloadService.build(fields || vm.options.fields, data || vm.options.data, vm.options.metadata);
      /**
       * Perform Insert/Update in backend
       */
      if(vm.options.metadata.mode === 'insert') {
        /**
         * mode = INSERT
         */
        // Backend create call
        vm.CRUDService.create(payload).then(function (res) {
          if(res.success === true) {
            if(res.data[0].status === 'error') {
              vm.AlertService.show('danger', 'Error', res.data[0].statusMessage + ' [statusId: ' + res.data[0].statusId + ']');
            } else if(res.data[0].status === 'success') {
              vm.AlertService.show('success', 'Saved', 'Record(s) successfully saved');
              // Go to 'edit' mode of newly created record
              vm.$scope.$emit('goToState', 'main.panel.form', {
                catalogName: res.data[0].tableName,
                mode: 'edit',
                id:  res.data[0].identity
              });
            }
          } else {
            // Do nothing. HTTP 500 responses handled by ErrorInterceptor
          }
        });
      } else if(vm.options.metadata.mode === 'edit' && vm.form.$dirty) {
        /**
         * mode = EDIT
         */
        // Backend update call
        vm.CRUDService.update(payload).then(function (res) {
          if(res.success === true) {
            if(res.data[0].status === 'error') {
              vm.AlertService.show('danger', 'Error', res.data[0].statusMessage + ' [statusId: ' + res.data[0].statusId + ']');
            } else if(res.data[0].status === 'success') {
              vm.AlertService.show('success', 'Saved', 'Record(s) successfully updated');
              // Reset form to untouched & pristine
              // vm.onReset
              vm.form.$setPristine();
              vm.form.$setUntouched();
              // ToDo: Reload form? (to retrieve saved data and spot glitches via: vm.loader(); ?
            }
          } else {
            // Do nothing. HTTP 500 responses handled by ErrorInterceptor
          }
        });
      } else if(vm.options.metadata.mode === 'filters' && vm.form.$dirty) {
        /**
         * mode = FILTERS
         */
        // Backend filters call
        vm.CRUDService.filters(payload).then(function (res) {
          if(res.success === true) {
              // Go to 'edit' mode of filtered records
              vm.$scope.$emit('goToState', 'main.panel.grid', {
                catalogName: vm.options.metadata.catalogName,
                mode: 'edit',
                filters:  '[' + res.data + ']'
              });
          } else {
            // Do nothing. HTTP 500 responses handled by ErrorInterceptor
          }
        });
      } else {
        vm.AlertService.show('info', 'Info', 'No changes');
      }
    } else {
      vm.AlertService.show('warning', 'Warning', 'Invalid form');
    }
  }
}
<commit_msg>feat(shell[form]): automatically set Referrer (foreignReference) value in model<commit_after>import BaseCtrl from '../base/base.controller';

export default class FormCtrl extends BaseCtrl {
  constructor($scope, DebugService, $stateParams, CRUDService, AlertService, PayloadService) {
    super($scope, DebugService, $stateParams, CRUDService, AlertService, undefined, PayloadService);
  }

  loader(pageIndex, pageSize) {
    var vm = this;
    var params = {
      catalogName: vm.$stateParams.catalogName,
      controlType: 'formView',
      mode: vm.$stateParams.mode,
      filters: vm.$stateParams.filters || '',
      getData: '1',
      getStructure: '1',
      pageIndex: pageIndex || parseInt(vm.$stateParams.pageIndex) || 1,
      pageSize: pageSize || parseInt(vm.$stateParams.pageSize) || 1
    };
    if(vm.$stateParams.id) {
      // Fallback options
      var idKey = vm.$stateParams.identityKey ||
                  vm.$stateParams.primaryKey ||
                  '$identity' || // Supported in SQL Server only for tables
                  'id';       // Last resort
      params.filters += '[' + idKey + '=' + vm.$stateParams.id + ']';
    }
    vm.CRUDService.read(params).then(function (res) {
      // Main `options' object
      // to be consumed by directive(s)
      vm.options = {
        metadata: res.data.data.metadata,
        fields: res.data.data.fields,
        data: vm.setReferrerValue(res.data.data.model) || [],
        opts: vm.getOpts()
      };

      vm.$scope.$emit('setPanelTitle', (function () {
        if(vm.$stateParams.mode === 'insert') return 'New ';
        if(vm.$stateParams.mode === 'edit') return 'Edit ';
        if(vm.$stateParams.mode === 'readonly') return 'View ';
        if(vm.$stateParams.mode === 'filters') return 'Filters ';
      })() + vm.options.metadata.tableName);
      // Set `vm.loaderOnce` at first `vm.loader()` call
      if(vm.loadedOnce === undefined) {
        vm.loadedOnce = true;
      }
    });
  }

  setReferrerValue(model) {
    var vm = this;
    // Set Referrer property in model
    var ref = vm.$stateParams.ref;
    var refId = vm.$stateParams.refId;
    if(ref && refId && model[0][ref] !== undefined) {
      model[0][ref] = refId;
    }
    return model;
  }

  getOpts() {
    var vm = this;
    return {
      asyncPagination: true,
      showPaginationRow: true,
      showSaveRow: vm.$stateParams.mode === 'edit' || vm.$stateParams.mode === 'insert',
      showFilterRow: vm.$stateParams.mode === 'filters'
    };
  }

  /*
  Common Handlers
  (unique & overriden from BaseCtrl)
   */

  onReset() {
    // // ToDo: Confirm
    // // vm.loader();
    // Alt: http://angular-formly.com/#/example/form-options/reset-model
    // ToDo: Confirm
    if (vm.form) {
      // http://jsbin.com/zaqeke
      //vm.$scope.options.resetModel();
      vm.form.$setPristine();
      vm.form.$setUntouched();
    }
  }

  onCancel() {
    // ToDo: Confirm of unsaved dirty form otherwise/then Go Back
    console.log("CANCEL");
  }

  onSubmit(fields, data) {
    var vm = this;
    if (vm.form.$valid) {
      /**
       * Create payload to be sent
       */
      var payload = vm.PayloadService.build(fields || vm.options.fields, data || vm.options.data, vm.options.metadata);
      /**
       * Perform Insert/Update in backend
       */
      if(vm.options.metadata.mode === 'insert') {
        /**
         * mode = INSERT
         */
        // Backend create call
        vm.CRUDService.create(payload).then(function (res) {
          if(res.success === true) {
            if(res.data[0].status === 'error') {
              vm.AlertService.show('danger', 'Error', res.data[0].statusMessage + ' [statusId: ' + res.data[0].statusId + ']');
            } else if(res.data[0].status === 'success') {
              vm.AlertService.show('success', 'Saved', 'Record(s) successfully saved');
              // Go to 'edit' mode of newly created record
              vm.$scope.$emit('goToState', 'main.panel.form', {
                catalogName: res.data[0].tableName,
                mode: 'edit',
                id:  res.data[0].identity
              });
            }
          } else {
            // Do nothing. HTTP 500 responses handled by ErrorInterceptor
          }
        });
      } else if(vm.options.metadata.mode === 'edit' && vm.form.$dirty) {
        /**
         * mode = EDIT
         */
        // Backend update call
        vm.CRUDService.update(payload).then(function (res) {
          if(res.success === true) {
            if(res.data[0].status === 'error') {
              vm.AlertService.show('danger', 'Error', res.data[0].statusMessage + ' [statusId: ' + res.data[0].statusId + ']');
            } else if(res.data[0].status === 'success') {
              vm.AlertService.show('success', 'Saved', 'Record(s) successfully updated');
              // Reset form to untouched & pristine
              // vm.onReset
              vm.form.$setPristine();
              vm.form.$setUntouched();
              // ToDo: Reload form? (to retrieve saved data and spot glitches via: vm.loader(); ?
            }
          } else {
            // Do nothing. HTTP 500 responses handled by ErrorInterceptor
          }
        });
      } else if(vm.options.metadata.mode === 'filters' && vm.form.$dirty) {
        /**
         * mode = FILTERS
         */
        // Backend filters call
        vm.CRUDService.filters(payload).then(function (res) {
          if(res.success === true) {
              // Go to 'edit' mode of filtered records
              vm.$scope.$emit('goToState', 'main.panel.grid', {
                catalogName: vm.options.metadata.catalogName,
                mode: 'edit',
                filters:  '[' + res.data + ']'
              });
          } else {
            // Do nothing. HTTP 500 responses handled by ErrorInterceptor
          }
        });
      } else {
        vm.AlertService.show('info', 'Info', 'No changes');
      }
    } else {
      vm.AlertService.show('warning', 'Warning', 'Invalid form');
    }
  }
}
<|endoftext|>


<commit_before>const path = require("path");
const merge = require("webpack-merge");
const exec = require("child_process").exec;
const WatchPlugin = require("webpack-watch-files-plugin").default;
const ShellPlugin = require("webpack-shell-plugin");
const common = require("./webpack.common.js");

module.exports = merge(common, {
  mode: "development",
  watch: true,
  devServer: {
    contentBase: path.join(__dirname, "docs/build/html"),
    watchContentBase: true,
    compress: false,
    port: 1919,
    hot: false,
    liveReload: true,
    publicPath: "/_static/"
  },
  plugins: [
    new WatchPlugin({
      files: ["./docs/**/*.rst", "./docs/**/*.py"]
    }),
    new ShellPlugin({
      onBuildEnd: ["make -C docs clean html"],
      // dev=false here to force every build to trigger make, the default is
      // first build only.
      dev: false
    })
  ]
});
<commit_msg>Make webpack dev server config to be more useful<commit_after>const path = require("path");
const merge = require("webpack-merge");
const exec = require("child_process").exec;
const WatchPlugin = require("webpack-watch-files-plugin").default;
const ShellPlugin = require("webpack-shell-plugin");
const common = require("./webpack.common.js");

module.exports = merge(common, {
  mode: "development",
  watch: true,
  // The dev server uses both contentBase and publicPath. The contentBase is
  // used to server the built docs, and publicPath is the bundle path for live
  // reloading. The publicPath intercepts requests to the static assets in
  // _static/. Opening http://localhost:1919 is everything you need for
  // development.
  devServer: {
    contentBase: "docs/build/html",
    port: 1919,
    open: false,
    hot: false,
    liveReload: true,
    publicPath: "/_static/",
    disableHostCheck: true,
    headers: {
      "Access-Control-Allow-Origin": "*"
    }
  },
  plugins: [
    new WatchPlugin({
      files: ["./docs/**/*.rst", "./docs/**/*.py"]
    }),
    new ShellPlugin({
      onBuildStart: ["make -C docs clean html"],
    })
  ]
});
<|endoftext|>