<commit_before>class RoomController {
  constructor($state, params, toastr, socket, userService, $uibModal) {
    this.$state = $state;
    this.toastr = toastr;
    this.socket = socket;
    this.userService = userService;
    this.roomId = params.roomId;
    this.$modal = $uibModal;

    this.messages = [];
    this._setup(this.roomId);
  }

  sendMessage() {
    this.socket.emit('msg', {
      roomId: this.roomId,
      chatMsg: this.chatMsg
    }, data => {

    });
    this.chatMsg = '';
  }

  startGame() {
    this.socket.emit('startgame', { roomId: this.roomId }, (data, error) => {
      if (error) {
        this.toastr.warning(error);
      }
    });
  }

  pause(intent) {
    this.socket.emit('pause', { roomId: this.roomId, intent: intent }, (data, error) => {
      if (error) {
        this.toastr.error(error);
      } else {
        if (data.isSpy) {
          var theModal = this.$modal.open({
              animation: true,
              size: 'sm',
              templateUrl: '/views/select-pause-action-modal',
              controller: roomModalController,
              resolve: {
                roomId: () => {return this.roomId},
                users: () => {return this.users},
                locations: () => {return this.locations}
              }
          });
        }
      }
    });
  }

  toggleReady() {
    this.socket.emit('toggleready', {
      roomId: this.roomId
    });
  }

  vote(vote) {
    this.socket.emit('vote', {roomId: this.roomId, vote}, (data, error) => {
      if (error) {
        this.toastr.error(error);
      } else {
        this.isVoting = false;
      }
    });
  }

  _setup(roomId) {
    this.log = angular.element(document.querySelector('#chatLog'));

    this.socket.emit('join', { roomId }, (data, error) => {
      if (error) {
        this.toastr.error(error);
        this.$state.go('home');
      }
      else {
        this.users = data.users;
        this.isHost = data.isHost;
        this.host = data.host
      }
    });

    this.socket.on('user:join', data => {
      this.users[data.user] = false;
    });

    this.socket.on('user:disconnect', data => {
      delete this.users[data.user];
    });

    this.socket.on('user:msg', data => {
      this.messages.push(data.chatMsg);
    });

    this.socket.on('user:change-username', data => {
      this.users[data.newUsername] = this.users[data.oldUsername];
      delete this.users[data.oldUsername];
    });

    this.socket.on('user:toggleready', data => {
      this.users[data.user] = data.isReady;
    });

    this.socket.on('user:startgame', data => {
      this.startTime = data.startTime;
      this.endTime = data.endTime;
      this.isPaused = false;
      this.isStarted = true;
    });

    // Players are waiting for the spy to select a location
    this.socket.on('user:waitforlocation', data => {
      this.isPaused = true;
      this.pauseSliderClass = 'bg-warning';
      this.pauseReason = 'Waiting for ' + data.user + ' to select a location.';
    });

    // Spy is asked to select a location
    this.socket.on('spy:guesslocation', data => {
      this.isPaused = true;
      this.locations = data.locations;
      var theModal = this.$modal.open({
          animation: true,
          size: 'sm',
          templateUrl: '/views/guess-location-modal',
          controller: roomModalController,
          resolve: {
            roomId: () => {return this.roomId},
            users: () => {return this.users},
            locations: () => {return this.locations}
          },
          backdrop: 'static',
          keyboard: false
      });
    });

    // Players are waiting for the player who paused to select a player
    this.socket.on('user:waitforaccusation', data => {
      this.isPaused = true;
      this.pauseSliderClass = 'bg-info';
      this.pauseReason = 'Waiting for ' + data.user + ' to select a player';
    });

    // The player who paused is asked to select a player
    this.socket.on('user:accuse', data => {
      this.isPaused = true;
      var theModal = this.$modal.open({
          animation: true,
          size: 'sm',
          templateUrl: '/views/accuse-modal',
          controller: roomModalController,
          resolve: {
            roomId: () => {return this.roomId},
            users: () => {return this.users},
            locations: () => {return this.locations}
          },
        backdrop: 'static',
        keyboard: false
      });
    });

    this.socket.on('user:gameover', data => {
      this.gameOver = true;
      this.didWin = data.didWin;
      this.gameOverPanelClass = (this.didWin) ? 'panel-success' : 'panel-danger';
      this.gameOverPanelTitle = (this.didWin) ? 'You Won' : 'You Lost';
      if (data.condition === 'location') {
        if (data.spy === this.userService.username) {
          this.gameOverPanelBodyText = (this.didWin) ? data.guess + ' was correct! How did you know?' : 'Unfortunately ' + data.guess + ' was not it. Did you not get the hints? It was obviously ' + data.actualLocation;
        } else {
          this.gameOverPanelBodyText = (this.didWin) ? data.spy + ' thought it was ' + data.guess + ', what a dimwit!' : data.spy + ' correctly guessed the location. How could you just give it away like that?';
        }
      } else {
        // Accusation gameover messages
        if (data.spy === this.userService.username) {
          this.gameOverPanelBodyText = (this.didWin) ? data.suspect + ' has been arrested for spying! Good job on not blowing your cover, but you should proabably get out of here soon.' : 'You have been compromised! Your days of spying are over!';
        } else {
          if (data.suspect === this.userService.username && !this.didWin) {
            this.gameOverPanelBodyText = data.spy + ' laughs as you are being arrested for spying. How are they not seeing that he is the real spy?';
          } else {
            this.gameOverPanelBodyText = (this.didWin) ? data.spy + ' has been arrested for spying! Good job exposing him!' : data.suspect + ' has been arrested for spying! Minor thing though.. it was actually ' + data.spy + ' who was the real spy.';
          }
        }
      }
    });

    this.socket.on('user:waitforvote', data => {
      this.pauseSliderClass = 'bg-warning';
      this.pauseReason = data.accuser + ' accused you of being the spy! People are voting on it now..';
    });

    this.socket.on('user:vote', data => {
      this.isVoting = true;
    });
  }
}

RoomController.$inject = ['$state', '$stateParams', 'toastr', 'socketService', 'userService', '$uibModal'];

roomModalController.$inject = ['$scope', '$uibModalInstance', 'socketService', 'userService', 'roomId', 'users', 'locations'];
function roomModalController ($scope, theModal, socket, userService, roomId, users, locations) {
  $scope.userService = userService;
  $scope.selectAccuseAction = selectAccuseAction;
  $scope.selectGuessLocationAction = selectGuessLocationAction;
  $scope.accuse = accuse;
  $scope.guessLocation = guessLocation;
  $scope.users = users;
  $scope.locations = locations;

  function selectAccuseAction() {
    socket.emit('pause', { roomId: roomId, intent: 'accuse'}, (data, error) => {
      if (error) {
        theModal.dismiss(error);
      }
    });
    theModal.close();
  }

  function selectGuessLocationAction() {
    socket.emit('pause', { roomId: roomId, intent: 'guessLocation'}, (data, error) => {
      if (error) {
        theModal.dismiss(error);
      }
    });
    theModal.close();
  }

  function accuse(user) {
    socket.emit('accuse', {roomId, user}, (data, error) => {
      if (error) {
        theModal.dismiss(error);
      }
    });
    theModal.close();
  }

  function guessLocation(location) {
    socket.emit('guessLocation', {roomId, location}, (data, error) => {
      if (error) {
        theModal.dismiss(error);
      }
    });
    theModal.close();
  }
}

export { RoomController };
<commit_msg>Game now resumes if there is no majority vote for 'yes'.<commit_after>class RoomController {
  constructor($state, params, toastr, socket, userService, $uibModal) {
    this.$state = $state;
    this.toastr = toastr;
    this.socket = socket;
    this.userService = userService;
    this.roomId = params.roomId;
    this.$modal = $uibModal;

    this.messages = [];
    this._setup(this.roomId);
  }

  sendMessage() {
    this.socket.emit('msg', {
      roomId: this.roomId,
      chatMsg: this.chatMsg
    }, data => {

    });
    this.chatMsg = '';
  }

  startGame() {
    this.socket.emit('startgame', { roomId: this.roomId }, (data, error) => {
      if (error) {
        this.toastr.warning(error);
      }
    });
  }

  pause(intent) {
    this.socket.emit('pause', { roomId: this.roomId, intent: intent }, (data, error) => {
      if (error) {
        this.toastr.error(error);
      } else {
        if (data.isSpy) {
          var theModal = this.$modal.open({
              animation: true,
              size: 'sm',
              templateUrl: '/views/select-pause-action-modal',
              controller: roomModalController,
              resolve: {
                roomId: () => {return this.roomId},
                users: () => {return this.users},
                locations: () => {return this.locations}
              }
          });
        }
      }
    });
  }

  toggleReady() {
    this.socket.emit('toggleready', {
      roomId: this.roomId
    });
  }

  vote(vote) {
    this.socket.emit('vote', {roomId: this.roomId, vote}, (data, error) => {
      if (error) {
        this.toastr.error(error);
      } else {
        this.isVoting = false;
      }
    });
  }

  _setup(roomId) {
    this.log = angular.element(document.querySelector('#chatLog'));

    this.socket.emit('join', { roomId }, (data, error) => {
      if (error) {
        this.toastr.error(error);
        this.$state.go('home');
      }
      else {
        this.users = data.users;
        this.isHost = data.isHost;
        this.host = data.host
      }
    });

    this.socket.on('user:join', data => {
      this.users[data.user] = false;
    });

    this.socket.on('user:disconnect', data => {
      delete this.users[data.user];
    });

    this.socket.on('user:msg', data => {
      this.messages.push(data.chatMsg);
    });

    this.socket.on('user:change-username', data => {
      this.users[data.newUsername] = this.users[data.oldUsername];
      delete this.users[data.oldUsername];
    });

    this.socket.on('user:toggleready', data => {
      this.users[data.user] = data.isReady;
    });

    this.socket.on('user:startgame', data => {
      this.startTime = data.startTime;
      this.endTime = data.endTime;
      this.isPaused = false;
      this.isStarted = true;
    });

    // Players are waiting for the spy to select a location
    this.socket.on('user:waitforlocation', data => {
      this.isPaused = true;
      this.pauseSliderClass = 'bg-warning';
      this.pauseReason = 'Waiting for ' + data.user + ' to select a location.';
    });

    // Spy is asked to select a location
    this.socket.on('spy:guesslocation', data => {
      this.isPaused = true;
      this.locations = data.locations;
      var theModal = this.$modal.open({
          animation: true,
          size: 'sm',
          templateUrl: '/views/guess-location-modal',
          controller: roomModalController,
          resolve: {
            roomId: () => {return this.roomId},
            users: () => {return this.users},
            locations: () => {return this.locations}
          },
          backdrop: 'static',
          keyboard: false
      });
    });

    // Players are waiting for the player who paused to select a player
    this.socket.on('user:waitforaccusation', data => {
      this.isPaused = true;
      this.pauseSliderClass = 'bg-info';
      this.pauseReason = 'Waiting for ' + data.user + ' to select a player';
    });

    // The player who paused is asked to select a player
    this.socket.on('user:accuse', data => {
      this.isPaused = true;
      var theModal = this.$modal.open({
          animation: true,
          size: 'sm',
          templateUrl: '/views/accuse-modal',
          controller: roomModalController,
          resolve: {
            roomId: () => {return this.roomId},
            users: () => {return this.users},
            locations: () => {return this.locations}
          },
        backdrop: 'static',
        keyboard: false
      });
    });

    this.socket.on('user:gameover', data => {
      this.gameOver = true;
      this.didWin = data.didWin;
      this.gameOverPanelClass = (this.didWin) ? 'panel-success' : 'panel-danger';
      this.gameOverPanelTitle = (this.didWin) ? 'You Won' : 'You Lost';
      if (data.condition === 'location') {
        if (data.spy === this.userService.username) {
          this.gameOverPanelBodyText = (this.didWin) ? data.guess + ' was correct! How did you know?' : 'Unfortunately ' + data.guess + ' was not it. Did you not get the hints? It was obviously ' + data.actualLocation;
        } else {
          this.gameOverPanelBodyText = (this.didWin) ? data.spy + ' thought it was ' + data.guess + ', what a dimwit!' : data.spy + ' correctly guessed the location. How could you just give it away like that?';
        }
      } else {
        // Accusation gameover messages
        if (data.spy === this.userService.username) {
          this.gameOverPanelBodyText = (this.didWin) ? data.suspect + ' has been arrested for spying! Good job on not blowing your cover, but you should proabably get out of here soon.' : 'You have been compromised! Your days of spying are over!';
        } else {
          if (data.suspect === this.userService.username && !this.didWin) {
            this.gameOverPanelBodyText = data.spy + ' laughs as you are being arrested for spying. How are they not seeing that he is the real spy?';
          } else {
            this.gameOverPanelBodyText = (this.didWin) ? data.spy + ' has been arrested for spying! Good job exposing him!' : data.suspect + ' has been arrested for spying! Minor thing though.. it was actually ' + data.spy + ' who was the real spy.';
          }
        }
      }
    });

    this.socket.on('user:waitforvote', data => {
      this.pauseSliderClass = 'bg-warning';
      this.pauseReason = data.accuser + ' accused you of being the spy! People are voting on it now..';
    });

    this.socket.on('user:vote', data => {
      this.isVoting = true;
    });

    this.socket.on('user:resume', data => {
      this.isPaused = false;
    });
  }
}

RoomController.$inject = ['$state', '$stateParams', 'toastr', 'socketService', 'userService', '$uibModal'];

roomModalController.$inject = ['$scope', '$uibModalInstance', 'socketService', 'userService', 'roomId', 'users', 'locations'];
function roomModalController ($scope, theModal, socket, userService, roomId, users, locations) {
  $scope.userService = userService;
  $scope.selectAccuseAction = selectAccuseAction;
  $scope.selectGuessLocationAction = selectGuessLocationAction;
  $scope.accuse = accuse;
  $scope.guessLocation = guessLocation;
  $scope.users = users;
  $scope.locations = locations;

  function selectAccuseAction() {
    socket.emit('pause', { roomId: roomId, intent: 'accuse'}, (data, error) => {
      if (error) {
        theModal.dismiss(error);
      }
    });
    theModal.close();
  }

  function selectGuessLocationAction() {
    socket.emit('pause', { roomId: roomId, intent: 'guessLocation'}, (data, error) => {
      if (error) {
        theModal.dismiss(error);
      }
    });
    theModal.close();
  }

  function accuse(user) {
    socket.emit('accuse', {roomId, user}, (data, error) => {
      if (error) {
        theModal.dismiss(error);
      }
    });
    theModal.close();
  }

  function guessLocation(location) {
    socket.emit('guessLocation', {roomId, location}, (data, error) => {
      if (error) {
        theModal.dismiss(error);
      }
    });
    theModal.close();
  }
}

export { RoomController };
<|endoftext|>


<commit_before>import Gulp from 'gulp';
import GUtil from 'gulp-util';
import {statSync} from 'fs';
import webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';

import {CLIENT_ENTRY, BUILD_TARGET, SERVER_PORT, DEV_SERVER_PORT, WATCHING} from 'linoleum';
import BABEL_DEFAULTS from 'linoleum/babel-defaults';

import loadWebpackConfig from '../src/webpack';

Gulp.task('webpack', function(done) {
  let configs = [],
      web = loadWebpackConfig({
        entry: {bootstrap: './src/bootstrap'}
      }),
      server = loadWebpackConfig({
        node: true,
        entry: {index: './src/index'},
        path: `${BUILD_TARGET}/`
      }),
      cover = loadWebpackConfig({
        node: true,
        cover: true,
        entry: {cover: require.resolve('../src/webpack-server-test')},
        path: `${BUILD_TARGET}/$cover$/`
      });

  if (entryExists('./src/bootstrap.js') || entryExists('./src/bootstrap.web.js')) {
    configs.push(web);
  }
  if (entryExists('./src/index.js') || entryExists('./src/index.server.js')) {
    configs.push(server);
  }
  configs.push(cover);

  webpack(configs, handleWebpack(done));
});

function entryExists(path) {
  try {
    statSync(path);
    return true;
  } catch (err) {
    return false;
  }
}

function handleWebpack(done) {
  return function(err, stats) {
    if (err) {
      throw new GUtil.PluginError('webpack', err);
    }
    GUtil.log('[webpack]', stats.toString({
      chunks: !WATCHING
    }));

    let hasErrors = (stats.stats || [stats]).reduce((prev, stat) => prev || stat.hasErrors, false);
    if (hasErrors) {
      done(new GUtil.PluginError('webpack', 'Build completed with errors'));
    } else {
      done();
    }
  };
}

Gulp.task('webpack:dev-server', function(done) {
  // Inject the hot reloader transform into the webpack config
  BABEL_DEFAULTS.plugins = BABEL_DEFAULTS.plugins || [];
  BABEL_DEFAULTS.plugins.push([require.resolve('babel-plugin-react-transform'), {
    transforms: [{
      transform: require.resolve('react-transform-hmr'),
      imports: ['react'],
      locals: ['module']
    }]
  }]);

  let devServer = `http://localhost:${DEV_SERVER_PORT}/`,
      config = loadWebpackConfig({
        entry: {
          bootstrap: [
            `${require.resolve('webpack-dev-server/client')}?${devServer}`,
            require.resolve(`webpack/hot/only-dev-server`),
            CLIENT_ENTRY
          ]
        }
      });
  config.plugins.unshift(
    new webpack.HotModuleReplacementPlugin()
  );

  config.output.path = '/static/';
  config.output.publicPath = `${devServer}static/`;

  let server = new WebpackDevServer(webpack(config), {
    // webpack-dev-server options
    contentBase: 'http://localhost:3000/',

    hot: true,
    proxy: {
      '*': `http://localhost:${SERVER_PORT}`
    },

    // webpack-dev-middleware options
    // NOTE: We can not use lazy here as this conflicts with the proxy
    lazy: false,
    quiet: false,
    noInfo: false,
    watchOptions: {
      aggregateTimeout: 300,
      poll: 1000
    },
    publicPath: '/static/',
    stats: {
      colors: true,
      chunks: false,
      version: false
    }
  });
  server.listen(DEV_SERVER_PORT, 'localhost', function() {
    console.log(`Dev server listening on ${devServer}`);    // eslint-disable-line no-console
    done();
  });
});
<commit_msg>Fix success checkin in webpack task<commit_after>import Gulp from 'gulp';
import GUtil from 'gulp-util';
import {statSync} from 'fs';
import webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';

import {CLIENT_ENTRY, BUILD_TARGET, SERVER_PORT, DEV_SERVER_PORT, WATCHING} from 'linoleum';
import BABEL_DEFAULTS from 'linoleum/babel-defaults';

import loadWebpackConfig from '../src/webpack';

Gulp.task('webpack', function(done) {
  let configs = [],
      web = loadWebpackConfig({
        entry: {bootstrap: './src/bootstrap'}
      }),
      server = loadWebpackConfig({
        node: true,
        entry: {index: './src/index'},
        path: `${BUILD_TARGET}/`
      }),
      cover = loadWebpackConfig({
        node: true,
        cover: true,
        entry: {cover: require.resolve('../src/webpack-server-test')},
        path: `${BUILD_TARGET}/$cover$/`
      });

  if (entryExists('./src/bootstrap.js') || entryExists('./src/bootstrap.web.js')) {
    configs.push(web);
  }
  if (entryExists('./src/index.js') || entryExists('./src/index.server.js')) {
    configs.push(server);
  }
  configs.push(cover);

  webpack(configs, handleWebpack(done));
});

function entryExists(path) {
  try {
    statSync(path);
    return true;
  } catch (err) {
    return false;
  }
}

function handleWebpack(done) {
  return function(err, stats) {
    if (err) {
      throw new GUtil.PluginError('webpack', err);
    }
    GUtil.log('[webpack]', stats.toString({
      chunks: !WATCHING
    }));

    let hasErrors = (stats.stats || [stats]).reduce((prev, stat) => prev || stat.hasErrors(), false);
    if (hasErrors) {
      done(new GUtil.PluginError('webpack', 'Build completed with errors'));
    } else {
      done();
    }
  };
}

Gulp.task('webpack:dev-server', function(done) {
  // Inject the hot reloader transform into the webpack config
  BABEL_DEFAULTS.plugins = BABEL_DEFAULTS.plugins || [];
  BABEL_DEFAULTS.plugins.push([require.resolve('babel-plugin-react-transform'), {
    transforms: [{
      transform: require.resolve('react-transform-hmr'),
      imports: ['react'],
      locals: ['module']
    }]
  }]);

  let devServer = `http://localhost:${DEV_SERVER_PORT}/`,
      config = loadWebpackConfig({
        entry: {
          bootstrap: [
            `${require.resolve('webpack-dev-server/client')}?${devServer}`,
            require.resolve(`webpack/hot/only-dev-server`),
            CLIENT_ENTRY
          ]
        }
      });
  config.plugins.unshift(
    new webpack.HotModuleReplacementPlugin()
  );

  config.output.path = '/static/';
  config.output.publicPath = `${devServer}static/`;

  let server = new WebpackDevServer(webpack(config), {
    // webpack-dev-server options
    contentBase: 'http://localhost:3000/',

    hot: true,
    proxy: {
      '*': `http://localhost:${SERVER_PORT}`
    },

    // webpack-dev-middleware options
    // NOTE: We can not use lazy here as this conflicts with the proxy
    lazy: false,
    quiet: false,
    noInfo: false,
    watchOptions: {
      aggregateTimeout: 300,
      poll: 1000
    },
    publicPath: '/static/',
    stats: {
      colors: true,
      chunks: false,
      version: false
    }
  });
  server.listen(DEV_SERVER_PORT, 'localhost', function() {
    console.log(`Dev server listening on ${devServer}`);    // eslint-disable-line no-console
    done();
  });
});
<|endoftext|>


<commit_before>import icon from 'part:@sanity/base/sync-icon'

export default {
  name: 'referenceTest',
  type: 'document',
  title: 'Reference test',
  description: 'Test cases for references',
  icon,
  fields: [
    {name: 'title', type: 'string'},
    {
      title: 'Book with decade filter',
      description: 'Reference will only search for books within given decade',
      name: 'filtered',
      type: 'object',
      validation: (Rule) =>
        Rule.custom((val) => (!val || val.decade ? true : 'Must have decade defined')),
      fields: [
        {
          title: 'Decade',
          description: 'eg. 1980, 1990, 2000',
          name: 'decade',
          type: 'number',
          validation: (Rule) =>
            Rule.required()
              .min(0)
              .max(3000)
              .custom((year) => {
                return year % 10 ? 'Must be a decade, eg use 1990 instead of 1994' : true
              }),
        },
        {
          name: 'book',
          title: 'Book reference',
          type: 'reference',
          to: {type: 'book'},
          options: {
            filter: (options) => {
              const decade = options.parent && options.parent.decade
              if (!decade) {
                return {filter: 'false'} // && false always returns no results :)
              }

              const minYear = Math.floor(decade / 10) * 10
              const maxYear = minYear + 9

              return {
                filter: 'publicationYear >= $minYear && publicationYear <= $maxYear',
                params: {minYear, maxYear},
              }
            },
          },
        },
      ],
    },
    {name: 'selfRef', type: 'reference', to: {type: 'referenceTest'}},
    {
      name: 'refToTypeWithNoToplevelStrings',
      type: 'reference',
      to: {type: 'typeWithNoToplevelStrings'},
    },
    {
      name: 'someStrongRef',
      title: 'Strong reference (default)',
      type: 'reference',
      to: {type: 'author'},
    },
    {
      name: 'someWeakRef',
      title: 'Weak reference',
      type: 'reference',
      weak: true,
      to: {type: 'author'},
    },
    {
      name: 'anotherWeakRef',
      title: 'Another weak reference',
      type: 'reference',
      weak: true,
      to: {type: 'author'},
    },
    {
      title: 'Reference to book or author',
      name: 'multiTypeRef',
      type: 'reference',
      to: [{type: 'book'}, {type: 'author'}],
    },
    {
      name: 'array',
      type: 'array',
      of: [
        {
          type: 'reference',
          name: 'strongAuthorRef',
          title: 'A strong author ref',
          to: {type: 'author'},
        },
        {
          type: 'reference',
          name: 'weakAuthorRef',
          title: 'A weak author ref',
          weak: true,
          to: {type: 'author'},
        },
      ],
    },
  ],
  preview: {
    fields: {
      title: 'title',
      author0: 'array.0.name',
      author1: 'array.1.name',
    },
    prepare(val) {
      return {
        title: val.title,
        subtitle: [val.author0, val.author1].filter(Boolean).join(', '),
      }
    },
  },
}
<commit_msg>chore(test-studio): add example of reference fields with async and invalid filters<commit_after>import icon from 'part:@sanity/base/sync-icon'

export default {
  name: 'referenceTest',
  type: 'document',
  title: 'Reference test',
  description: 'Test cases for references',
  icon,
  fields: [
    {name: 'title', type: 'string'},
    {
      title: 'Book with decade filter',
      description: 'Reference will only search for books within given decade',
      name: 'filtered',
      type: 'object',
      validation: (Rule) =>
        Rule.custom((val) => (!val || val.decade ? true : 'Must have decade defined')),
      fields: [
        {
          title: 'Decade',
          description: 'eg. 1980, 1990, 2000',
          name: 'decade',
          type: 'number',
          validation: (Rule) =>
            Rule.required()
              .min(0)
              .max(3000)
              .custom((year) => {
                return year % 10 ? 'Must be a decade, eg use 1990 instead of 1994' : true
              }),
        },
        {
          name: 'book',
          title: 'Book reference',
          type: 'reference',
          to: {type: 'book'},
          options: {
            filter: (options) => {
              const decade = options.parent && options.parent.decade
              if (!decade) {
                return {filter: 'false'} // && false always returns no results :)
              }

              const minYear = Math.floor(decade / 10) * 10
              const maxYear = minYear + 9

              return {
                filter: 'publicationYear >= $minYear && publicationYear <= $maxYear',
                params: {minYear, maxYear},
              }
            },
          },
        },
      ],
    },
    {name: 'selfRef', type: 'reference', to: {type: 'referenceTest'}},
    {
      name: 'invalidFilter',
      title: 'Invalid filter',
      description: 'This will error when trying to search for anything',
      type: 'reference',
      to: {type: 'book'},
      options: {
        filter: '&',
      },
    },
    {
      name: 'asyncFilter',
      title: 'Async filter',
      type: 'reference',
      to: {type: 'book'},
      options: {
        filter: () =>
          Promise.resolve({filter: '$param == "something"', params: {param: 'something'}}),
      },
    },
    {
      name: 'refToTypeWithNoToplevelStrings',
      type: 'reference',
      to: {type: 'typeWithNoToplevelStrings'},
    },
    {
      name: 'someStrongRef',
      title: 'Strong reference (default)',
      type: 'reference',
      to: {type: 'author'},
    },
    {
      name: 'someWeakRef',
      title: 'Weak reference',
      type: 'reference',
      weak: true,
      to: {type: 'author'},
    },
    {
      name: 'anotherWeakRef',
      title: 'Another weak reference',
      type: 'reference',
      weak: true,
      to: {type: 'author'},
    },
    {
      title: 'Reference to book or author',
      name: 'multiTypeRef',
      type: 'reference',
      to: [{type: 'book'}, {type: 'author'}],
    },
    {
      name: 'array',
      type: 'array',
      of: [
        {
          type: 'reference',
          name: 'strongAuthorRef',
          title: 'A strong author ref',
          to: {type: 'author'},
        },
        {
          type: 'reference',
          name: 'weakAuthorRef',
          title: 'A weak author ref',
          weak: true,
          to: {type: 'author'},
        },
      ],
    },
  ],
  preview: {
    fields: {
      title: 'title',
      author0: 'array.0.name',
      author1: 'array.1.name',
    },
    prepare(val) {
      return {
        title: val.title,
        subtitle: [val.author0, val.author1].filter(Boolean).join(', '),
      }
    },
  },
}
<|endoftext|>


<commit_before>module("Discourse.Utilities");

var utils = Discourse.Utilities;

test("emailValid", function() {
  ok(utils.emailValid('Bob@example.com'), "allows upper case in the first part of emails");
  ok(utils.emailValid('bob@EXAMPLE.com'), "allows upper case in the email domain");
});

var validUpload = utils.validateUploadedFiles;

test("validateUploadedFiles", function() {
  not(validUpload(null), "no files are invalid");
  not(validUpload(undefined), "undefined files are invalid");
  not(validUpload([]), "empty array of files is invalid");
});

test("uploading one file", function() {
  sandbox.stub(bootbox, "alert");

  not(validUpload([1, 2]));
  ok(bootbox.alert.calledWith(I18n.t('post.errors.too_many_uploads')));
});

test("new user cannot upload images", function() {
  Discourse.SiteSettings.newuser_max_images = 0;
  Discourse.User.resetCurrent(Discourse.User.create());
  sandbox.stub(bootbox, "alert");

  not(validUpload([{name: "image.png"}]), 'the upload is not valid');
  ok(bootbox.alert.calledWith(I18n.t('post.errors.image_upload_not_allowed_for_new_user')), 'the alert is called');
});

test("new user cannot upload attachments", function() {
  Discourse.SiteSettings.newuser_max_attachments = 0;
  sandbox.stub(bootbox, "alert");
  Discourse.User.resetCurrent(Discourse.User.create());

  not(validUpload([{name: "roman.txt"}]));
  ok(bootbox.alert.calledWith(I18n.t('post.errors.attachment_upload_not_allowed_for_new_user')));
});

test("ensures an authorized upload", function() {
  var html = { name: "unauthorized.html" };
  var extensions = Discourse.SiteSettings.authorized_extensions.replace(/\|/g, ", ");
  sandbox.stub(bootbox, "alert");

  not(validUpload([html]));
  ok(bootbox.alert.calledWith(I18n.t('post.errors.upload_not_authorized', { authorized_extensions: extensions })));
});

test("prevents files that are too big from being uploaded", function() {
  Discourse.User.resetCurrent(Discourse.User.create());
  var image = { name: "image.png", size: 10 * 1024 };
  Discourse.SiteSettings.max_image_size_kb = 5;
  Discourse.User.currentProp("trust_level", 1);
  sandbox.stub(bootbox, "alert");

  not(validUpload([image]));
  ok(bootbox.alert.calledWith(I18n.t('post.errors.image_too_large', { max_size_kb: 5 })));
});

var dummyBlob = function() {
  var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
  if (BlobBuilder) {
    var bb = new BlobBuilder();
    bb.append([1]);
    return bb.getBlob("image/png");
  } else {
    return new Blob([1], { "type" : "image\/png" });
  }
};

test("allows valid uploads to go through", function() {
  Discourse.User.resetCurrent(Discourse.User.create());
  Discourse.User.currentProp("trust_level", 1);
  Discourse.SiteSettings.max_image_size_kb = 15;
  sandbox.stub(bootbox, "alert");

  // image
  var image = { name: "image.png", size: 10 * 1024 };
  ok(validUpload([image]));
  // pasted image
  var pastedImage = dummyBlob();
  ok(validUpload([pastedImage]));

  not(bootbox.alert.calledOnce);
});

var getUploadMarkdown = function(filename) {
  return utils.getUploadMarkdown({
    original_filename: filename,
    filesize: 42,
    width: 100,
    height: 200,
    url: "/uploads/123/abcdef.ext"
  });
};

test("getUploadMarkdown", function() {
  ok(getUploadMarkdown("lolcat.gif") === '');
  ok(getUploadMarkdown("important.txt") === 'important.txt (42 Bytes)');
});

test("isAnImage", function() {
  _.each(["png", "jpg", "jpeg", "bmp", "gif", "tif", "tiff"], function(extension) {
    var image = "image." + extension;
    ok(utils.isAnImage(image), image + " is recognized as an image");
    ok(utils.isAnImage("http://foo.bar/path/to/" + image), image + " is recognized as an image");
  });
  not(utils.isAnImage("file.txt"));
  not(utils.isAnImage("http://foo.bar/path/to/file.txt"));
  not(utils.isAnImage(""));
});

test("avatarUrl", function() {
  blank(utils.avatarUrl('', 'tiny'), "no template returns blank");
  equal(utils.avatarUrl('/fake/template/{size}.png', 'tiny'), "/fake/template/" + 20*window.devicePixelRatio + ".png", "simple avatar url");
  equal(utils.avatarUrl('/fake/template/{size}.png', 'large'), "/fake/template/" + 45*window.devicePixelRatio +  ".png", "different size");
});

test("avatarImg", function() {
  var oldRatio = window.devicePixelRatio;
  window.devicePixelRatio = 2;

  var avatarTemplate = "/path/to/avatar/{size}.png";
  equal(utils.avatarImg({avatarTemplate: avatarTemplate, size: 'tiny'}),
        "",
        "it returns the avatar html");

  equal(utils.avatarImg({avatarTemplate: avatarTemplate, size: 'tiny', title: 'evilest trout'}),
        "",
        "it adds a title if supplied");

  equal(utils.avatarImg({avatarTemplate: avatarTemplate, size: 'tiny', extraClasses: 'evil fish'}),
        "",
        "it adds extra classes if supplied");

  blank(utils.avatarImg({avatarTemplate: "", size: 'tiny'}),
        "it doesn't render avatars for invalid avatar template");

  window.devicePixelRatio = oldRatio;
});

test("allowsAttachments", function() {
  Discourse.SiteSettings.authorized_extensions = "jpg|jpeg|gif";
  not(utils.allowsAttachments(), "no attachments allowed by default");

  Discourse.SiteSettings.authorized_extensions = "jpg|jpeg|gif|*";
  ok(utils.allowsAttachments(), "attachments are allowed when all extensions are allowed");

  Discourse.SiteSettings.authorized_extensions = "jpg|jpeg|gif|pdf";
  ok(utils.allowsAttachments(), "attachments are allowed when at least one extension is not an image extension");
});

test("defaultHomepage", function() {
  Discourse.SiteSettings.top_menu = "latest|top|hot";
  equal(utils.defaultHomepage(), "latest", "default homepage is the first item in the top_menu site setting");
});

module("Discourse.Utilities.cropAvatar with animated avatars", {
  setup: function() { Discourse.SiteSettings.allow_animated_avatars = true; }
});

asyncTestDiscourse("cropAvatar", function() {
  expect(1);

  utils.cropAvatar("/path/to/avatar.gif", "image/gif").then(function(avatarTemplate) {
    equal(avatarTemplate, "/path/to/avatar.gif", "returns the url to the gif when animated gif are enabled");
    start();
  });
});
<commit_msg>FIX: On devices with a weird pixel ratio, tests were failing.<commit_after>module("Discourse.Utilities");

var utils = Discourse.Utilities;

test("emailValid", function() {
  ok(utils.emailValid('Bob@example.com'), "allows upper case in the first part of emails");
  ok(utils.emailValid('bob@EXAMPLE.com'), "allows upper case in the email domain");
});

var validUpload = utils.validateUploadedFiles;

test("validateUploadedFiles", function() {
  not(validUpload(null), "no files are invalid");
  not(validUpload(undefined), "undefined files are invalid");
  not(validUpload([]), "empty array of files is invalid");
});

test("uploading one file", function() {
  sandbox.stub(bootbox, "alert");

  not(validUpload([1, 2]));
  ok(bootbox.alert.calledWith(I18n.t('post.errors.too_many_uploads')));
});

test("new user cannot upload images", function() {
  Discourse.SiteSettings.newuser_max_images = 0;
  Discourse.User.resetCurrent(Discourse.User.create());
  sandbox.stub(bootbox, "alert");

  not(validUpload([{name: "image.png"}]), 'the upload is not valid');
  ok(bootbox.alert.calledWith(I18n.t('post.errors.image_upload_not_allowed_for_new_user')), 'the alert is called');
});

test("new user cannot upload attachments", function() {
  Discourse.SiteSettings.newuser_max_attachments = 0;
  sandbox.stub(bootbox, "alert");
  Discourse.User.resetCurrent(Discourse.User.create());

  not(validUpload([{name: "roman.txt"}]));
  ok(bootbox.alert.calledWith(I18n.t('post.errors.attachment_upload_not_allowed_for_new_user')));
});

test("ensures an authorized upload", function() {
  var html = { name: "unauthorized.html" };
  var extensions = Discourse.SiteSettings.authorized_extensions.replace(/\|/g, ", ");
  sandbox.stub(bootbox, "alert");

  not(validUpload([html]));
  ok(bootbox.alert.calledWith(I18n.t('post.errors.upload_not_authorized', { authorized_extensions: extensions })));
});

test("prevents files that are too big from being uploaded", function() {
  Discourse.User.resetCurrent(Discourse.User.create());
  var image = { name: "image.png", size: 10 * 1024 };
  Discourse.SiteSettings.max_image_size_kb = 5;
  Discourse.User.currentProp("trust_level", 1);
  sandbox.stub(bootbox, "alert");

  not(validUpload([image]));
  ok(bootbox.alert.calledWith(I18n.t('post.errors.image_too_large', { max_size_kb: 5 })));
});

var dummyBlob = function() {
  var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
  if (BlobBuilder) {
    var bb = new BlobBuilder();
    bb.append([1]);
    return bb.getBlob("image/png");
  } else {
    return new Blob([1], { "type" : "image\/png" });
  }
};

test("allows valid uploads to go through", function() {
  Discourse.User.resetCurrent(Discourse.User.create());
  Discourse.User.currentProp("trust_level", 1);
  Discourse.SiteSettings.max_image_size_kb = 15;
  sandbox.stub(bootbox, "alert");

  // image
  var image = { name: "image.png", size: 10 * 1024 };
  ok(validUpload([image]));
  // pasted image
  var pastedImage = dummyBlob();
  ok(validUpload([pastedImage]));

  not(bootbox.alert.calledOnce);
});

var getUploadMarkdown = function(filename) {
  return utils.getUploadMarkdown({
    original_filename: filename,
    filesize: 42,
    width: 100,
    height: 200,
    url: "/uploads/123/abcdef.ext"
  });
};

test("getUploadMarkdown", function() {
  ok(getUploadMarkdown("lolcat.gif") === '');
  ok(getUploadMarkdown("important.txt") === 'important.txt (42 Bytes)');
});

test("isAnImage", function() {
  _.each(["png", "jpg", "jpeg", "bmp", "gif", "tif", "tiff"], function(extension) {
    var image = "image." + extension;
    ok(utils.isAnImage(image), image + " is recognized as an image");
    ok(utils.isAnImage("http://foo.bar/path/to/" + image), image + " is recognized as an image");
  });
  not(utils.isAnImage("file.txt"));
  not(utils.isAnImage("http://foo.bar/path/to/file.txt"));
  not(utils.isAnImage(""));
});

test("avatarUrl", function() {
  var rawSize = Discourse.Utilities.getRawSize;
  blank(utils.avatarUrl('', 'tiny'), "no template returns blank");
  equal(utils.avatarUrl('/fake/template/{size}.png', 'tiny'), "/fake/template/" + rawSize(20) + ".png", "simple avatar url");
  equal(utils.avatarUrl('/fake/template/{size}.png', 'large'), "/fake/template/" + rawSize(45) +  ".png", "different size");
});

test("avatarImg", function() {
  var oldRatio = window.devicePixelRatio;
  window.devicePixelRatio = 2;

  var avatarTemplate = "/path/to/avatar/{size}.png";
  equal(utils.avatarImg({avatarTemplate: avatarTemplate, size: 'tiny'}),
        "",
        "it returns the avatar html");

  equal(utils.avatarImg({avatarTemplate: avatarTemplate, size: 'tiny', title: 'evilest trout'}),
        "",
        "it adds a title if supplied");

  equal(utils.avatarImg({avatarTemplate: avatarTemplate, size: 'tiny', extraClasses: 'evil fish'}),
        "",
        "it adds extra classes if supplied");

  blank(utils.avatarImg({avatarTemplate: "", size: 'tiny'}),
        "it doesn't render avatars for invalid avatar template");

  window.devicePixelRatio = oldRatio;
});

test("allowsAttachments", function() {
  Discourse.SiteSettings.authorized_extensions = "jpg|jpeg|gif";
  not(utils.allowsAttachments(), "no attachments allowed by default");

  Discourse.SiteSettings.authorized_extensions = "jpg|jpeg|gif|*";
  ok(utils.allowsAttachments(), "attachments are allowed when all extensions are allowed");

  Discourse.SiteSettings.authorized_extensions = "jpg|jpeg|gif|pdf";
  ok(utils.allowsAttachments(), "attachments are allowed when at least one extension is not an image extension");
});

test("defaultHomepage", function() {
  Discourse.SiteSettings.top_menu = "latest|top|hot";
  equal(utils.defaultHomepage(), "latest", "default homepage is the first item in the top_menu site setting");
});

module("Discourse.Utilities.cropAvatar with animated avatars", {
  setup: function() { Discourse.SiteSettings.allow_animated_avatars = true; }
});

asyncTestDiscourse("cropAvatar", function() {
  expect(1);

  utils.cropAvatar("/path/to/avatar.gif", "image/gif").then(function(avatarTemplate) {
    equal(avatarTemplate, "/path/to/avatar.gif", "returns the url to the gif when animated gif are enabled");
    start();
  });
});
<|endoftext|>


<commit_before>"use strict";
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import { FormMixin, Input } from '../../libs/bootstrap/form';
import { external_url_map } from '../globals';

import { DiseaseModal } from './modal';

/**
 * Component for adding/copying/deleting disease when creating adding a proband individual
 * to a new family evidence that is currently being created.
 */
const FamilyProbandDisease = module.exports.FamilyProbandDisease = React.createClass({
    mixins: [FormMixin],

    propTypes: {
        gdm: PropTypes.object, // For editing disease (passed to Modal)
        group: PropTypes.object,
        family: PropTypes.object,
        probandDiseaseObj: PropTypes.object,
        updateFamilyProbandDiseaseObj: PropTypes.func,
        clearErrorInParent: PropTypes.func,
        error: PropTypes.string,
        session: PropTypes.object,
        required: PropTypes.bool
    },

    getInitialState() {
        return {
            gdm: this.props.gdm,
            group: this.props.group,
            family: this.props.family,
            probandDiseaseObj: this.props.probandDiseaseObj,
            error: this.props.error,
            required: this.props.required,
            diseaseId: '',
            diseaseTerm: null,
            diseaseOntology: null,
            diseaseDescription: null,
            synonyms: [],
            phenotypes: [],
            diseaseFreeTextConfirm: false,
            diseaseObj: {}
        };
    },

    componentWillReceiveProps(nextProps)  {
        if (nextProps.probandDiseaseObj) {
            this.setState({probandDiseaseObj: nextProps.probandDiseaseObj}, () => {
                let probandDiseaseObj = this.state.probandDiseaseObj;
                if (Object.keys(probandDiseaseObj).length) {
                    this.setDiseaseObjectStates(probandDiseaseObj);
                }
            });
        }
        if (nextProps.error) {
            this.setState({error: nextProps.error});
        }
        /**
         * Set the value either true or false
         */
        this.setState({required: nextProps.required});
    },

    /**
     * Shared method called by componentWillReceiveProps(nextProps)
     * @param {*} disease
     */
    setDiseaseObjectStates(disease) {
        if (disease.id) { this.setState({diseaseId: disease.id}); }
        if (disease.term) { this.setState({diseaseTerm: disease.term}); }
        if (disease.ontology) { this.setState({diseaseOntology: disease.ontology}); }
        if (disease.description) { this.setState({diseaseDescription: disease.description}); }
        if (disease.synonyms) { this.setState({synonyms: disease.synonyms}); }
        if (disease.phenotypes) { this.setState({phenotypes: disease.phenotypes}); }
        if (disease.freetext) { this.setState({diseaseFreeTextConfirm: disease.freetext}); }
    },

    passDataToParent(id, term, ontology, description, synonyms, phenotypes, freetext) {
        let diseaseObj = this.state.diseaseObj;
        this.setState({error: null}, () => {
            this.props.clearErrorInParent('familyProband');
        });
        if (id) {
            /**
             * Changing colon to underscore in id string for database
             */
            diseaseObj['id'] = id.replace(':', '_');
            this.setState({diseaseId: id});
        }
        if (term) {
            diseaseObj['term'] = term;
            this.setState({diseaseTerm: term});
        }
        if (ontology) {
            diseaseObj['ontology'] = ontology;
            this.setState({diseaseOntology: ontology});
        }
        if (description) {
            diseaseObj['description'] = description;
            this.setState({diseaseDescription: description});
        } else {
            if (diseaseObj['description']) { delete diseaseObj['description']; }
            this.setState({diseaseDescription: null});
        }
        if (synonyms && synonyms.length) {
            diseaseObj['synonyms'] = synonyms;
            this.setState({synonyms: synonyms});
        } else {
            if (diseaseObj['synonyms']) { delete diseaseObj['synonyms']; }
            this.setState({synonyms: []});
        }
        if (phenotypes && phenotypes.length) {
            diseaseObj['phenotypes'] = phenotypes;
            this.setState({phenotypes: phenotypes});
        } else {
            if (diseaseObj['phenotypes']) { delete diseaseObj['phenotypes']; }
            this.setState({phenotypes: []});
        }
        if (freetext) {
            diseaseObj['freetext'] = true;
            this.setState({diseaseFreeTextConfirm: true});
        } else {
            if (diseaseObj['freetext']) { delete diseaseObj['freetext']; }
            this.setState({diseaseFreeTextConfirm: false});
        }
        this.setState({diseaseObj: diseaseObj}, () => {
            // Pass data object back to parent
            this.props.updateFamilyProbandDiseaseObj('add', this.state.diseaseObj);
        });
    },

    /**
     * Method to render the display of disease info
     * @param {*} id
     * @param {*} term
     * @param {*} desc
     * @param {*} hpo
     * @param {*} freetext
     */
    renderDiseaseData(id, term, desc, hpo, freetext) {
        let source = !freetext ? id.replace('_', ':') : this.props.session.user_properties.title;
        if (term && term.length) {
            return (

                    {term + ' (' + source + ')'}
                    {desc && desc.length ? Definition: {desc} : null}
                    {hpo && hpo.length ? HPO terms: {hpo.join(', ')} : null}

            );
        }
    },

    /**
     * Method to render the copy button given the curated evidence
     */
    renderCopyDiseaseButton() {
        /**
         * Copy disease into the 'Family — Variant(s) Segregating with Proband' section
         * from what had been selected for Family, either by copying from Group or adding new one
         */
        return (
            <Input type="button" ref="copyFamilyProbandDisease" title="Copy disease term from Family"
                wrapperClassName="family-proband-disease-copy" inputClassName="btn-default"
                clickHandler={this.handleCopyFamilyProbandDisease} />
        );
    },

    /**
     * Handler for button press event to copy disease from family into proband
     */
    handleCopyFamilyProbandDisease(e) {
        e.preventDefault(); e.stopPropagation();
        this.setState({error: null}, () => {
            this.props.clearErrorInParent('familyProband');
            this.props.updateFamilyProbandDiseaseObj('copy');
        });
    },

    /**
     * Handler for button press event to delete disease from the evidence
     */
    handleDeleteDisease(e) {
        e.preventDefault(); e.stopPropagation();
        this.setState({
            diseaseId: '',
            diseaseTerm: null,
            diseaseOntology: null,
            diseaseDescription: null,
            synonyms: [],
            phenotypes: [],
            diseaseFreeTextConfirm: false,
            probandDiseaseObj: {},
            error: null
        }, () => {
            // Pass data object back to parent
            this.props.updateFamilyProbandDiseaseObj('delete');
            this.props.clearErrorInParent('familyProband');
        });
    },

    render() {
        let diseaseId = this.state.diseaseId;
        let diseaseTerm = this.state.diseaseTerm;
        let diseaseOntology = this.state.diseaseOntology;
        let diseaseDescription = this.state.diseaseDescription;
        let diseaseFreeTextConfirm = this.state.diseaseFreeTextConfirm;
        let phenotypes = this.state.phenotypes;
        let synonyms = this.state.synonyms;
        let addDiseaseModalBtn = diseaseTerm ? Disease : Disease;
        let error = this.state.error;

        return (

                    Disease(s) for Individual:
                        {this.state.required ?  * : null}
                        Search MonDO using OLS

                        {error ?
                            {error}
                            :

                                {this.renderDiseaseData(diseaseId, diseaseTerm, diseaseDescription, phenotypes, diseaseFreeTextConfirm)}

                        }

                    {!diseaseTerm ?

                                {this.renderCopyDiseaseButton()}

- or -

                                <DiseaseModal
                                    addDiseaseModalBtn={addDiseaseModalBtn}
                                    diseaseId={diseaseId}
                                    diseaseTerm={diseaseTerm}
                                    diseaseOntology={diseaseOntology}
                                    diseaseDescription={diseaseDescription}
                                    diseaseFreeTextConfirm={diseaseFreeTextConfirm}
                                    phenotypes={phenotypes}
                                    synonyms={synonyms}
                                    passDataToParent={this.passDataToParent}
                                    addDiseaseModalBtnLayoutClass=" evidence-disease"
                                />

                    :

                                Disease

                    }

        );
    }
});
<commit_msg>:bug: Added handling to suppress the 'Copy disease term from Famiy' button for the Proband if a disease has not been added to the Family<commit_after>"use strict";
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import { FormMixin, Input } from '../../libs/bootstrap/form';
import { external_url_map } from '../globals';

import { DiseaseModal } from './modal';

/**
 * Component for adding/copying/deleting disease when creating adding a proband individual
 * to a new family evidence that is currently being created.
 */
const FamilyProbandDisease = module.exports.FamilyProbandDisease = React.createClass({
    mixins: [FormMixin],

    propTypes: {
        gdm: PropTypes.object, // For editing disease (passed to Modal)
        group: PropTypes.object,
        family: PropTypes.object,
        familyDiseaseObj: PropTypes.object,
        probandDiseaseObj: PropTypes.object,
        updateFamilyProbandDiseaseObj: PropTypes.func,
        clearErrorInParent: PropTypes.func,
        error: PropTypes.string,
        session: PropTypes.object,
        required: PropTypes.bool
    },

    getInitialState() {
        return {
            gdm: this.props.gdm,
            group: this.props.group,
            family: this.props.family,
            familyDiseaseObj: this.props.familyDiseaseObj,
            probandDiseaseObj: this.props.probandDiseaseObj,
            error: this.props.error,
            required: this.props.required,
            diseaseId: '',
            diseaseTerm: null,
            diseaseOntology: null,
            diseaseDescription: null,
            synonyms: [],
            phenotypes: [],
            diseaseFreeTextConfirm: false,
            diseaseObj: {}
        };
    },

    componentWillReceiveProps(nextProps)  {
        if (nextProps.familyDiseaseObj) {
            this.setState({familyDiseaseObj: nextProps.familyDiseaseObj});
        }
        if (nextProps.probandDiseaseObj) {
            this.setState({probandDiseaseObj: nextProps.probandDiseaseObj}, () => {
                let probandDiseaseObj = this.state.probandDiseaseObj;
                if (Object.keys(probandDiseaseObj).length) {
                    this.setDiseaseObjectStates(probandDiseaseObj);
                }
            });
        }
        if (nextProps.error) {
            this.setState({error: nextProps.error});
        }
        /**
         * Set the value either true or false
         */
        this.setState({required: nextProps.required});
    },

    /**
     * Shared method called by componentWillReceiveProps(nextProps)
     * @param {*} disease
     */
    setDiseaseObjectStates(disease) {
        if (disease.id) { this.setState({diseaseId: disease.id}); }
        if (disease.term) { this.setState({diseaseTerm: disease.term}); }
        if (disease.ontology) { this.setState({diseaseOntology: disease.ontology}); }
        if (disease.description) { this.setState({diseaseDescription: disease.description}); }
        if (disease.synonyms) { this.setState({synonyms: disease.synonyms}); }
        if (disease.phenotypes) { this.setState({phenotypes: disease.phenotypes}); }
        if (disease.freetext) { this.setState({diseaseFreeTextConfirm: disease.freetext}); }
    },

    passDataToParent(id, term, ontology, description, synonyms, phenotypes, freetext) {
        let diseaseObj = this.state.diseaseObj;
        this.setState({error: null}, () => {
            this.props.clearErrorInParent('familyProband');
        });
        if (id) {
            /**
             * Changing colon to underscore in id string for database
             */
            diseaseObj['id'] = id.replace(':', '_');
            this.setState({diseaseId: id});
        }
        if (term) {
            diseaseObj['term'] = term;
            this.setState({diseaseTerm: term});
        }
        if (ontology) {
            diseaseObj['ontology'] = ontology;
            this.setState({diseaseOntology: ontology});
        }
        if (description) {
            diseaseObj['description'] = description;
            this.setState({diseaseDescription: description});
        } else {
            if (diseaseObj['description']) { delete diseaseObj['description']; }
            this.setState({diseaseDescription: null});
        }
        if (synonyms && synonyms.length) {
            diseaseObj['synonyms'] = synonyms;
            this.setState({synonyms: synonyms});
        } else {
            if (diseaseObj['synonyms']) { delete diseaseObj['synonyms']; }
            this.setState({synonyms: []});
        }
        if (phenotypes && phenotypes.length) {
            diseaseObj['phenotypes'] = phenotypes;
            this.setState({phenotypes: phenotypes});
        } else {
            if (diseaseObj['phenotypes']) { delete diseaseObj['phenotypes']; }
            this.setState({phenotypes: []});
        }
        if (freetext) {
            diseaseObj['freetext'] = true;
            this.setState({diseaseFreeTextConfirm: true});
        } else {
            if (diseaseObj['freetext']) { delete diseaseObj['freetext']; }
            this.setState({diseaseFreeTextConfirm: false});
        }
        this.setState({diseaseObj: diseaseObj}, () => {
            // Pass data object back to parent
            this.props.updateFamilyProbandDiseaseObj('add', this.state.diseaseObj);
        });
    },

    /**
     * Method to render the display of disease info
     * @param {*} id
     * @param {*} term
     * @param {*} desc
     * @param {*} hpo
     * @param {*} freetext
     */
    renderDiseaseData(id, term, desc, hpo, freetext) {
        let source = !freetext ? id.replace('_', ':') : this.props.session.user_properties.title;
        if (term && term.length) {
            return (

                    {term + ' (' + source + ')'}
                    {desc && desc.length ? Definition: {desc} : null}
                    {hpo && hpo.length ? HPO terms: {hpo.join(', ')} : null}

            );
        }
    },

    /**
     * Method to render the copy button given the curated evidence
     */
    renderCopyDiseaseButton() {
        /**
         * Copy disease into the 'Family — Variant(s) Segregating with Proband' section
         * from what had been selected for Family, either by copying from Group or adding new one
         */
        return (
            <Input type="button" ref="copyFamilyProbandDisease" title="Copy disease term from Family"
                wrapperClassName="family-proband-disease-copy" inputClassName="btn-default"
                clickHandler={this.handleCopyFamilyProbandDisease} />
        );
    },

    /**
     * Handler for button press event to copy disease from family into proband
     */
    handleCopyFamilyProbandDisease(e) {
        e.preventDefault(); e.stopPropagation();
        this.setState({error: null}, () => {
            this.props.clearErrorInParent('familyProband');
            this.props.updateFamilyProbandDiseaseObj('copy');
        });
    },

    /**
     * Handler for button press event to delete disease from the evidence
     */
    handleDeleteDisease(e) {
        e.preventDefault(); e.stopPropagation();
        this.setState({
            diseaseId: '',
            diseaseTerm: null,
            diseaseOntology: null,
            diseaseDescription: null,
            synonyms: [],
            phenotypes: [],
            diseaseFreeTextConfirm: false,
            probandDiseaseObj: {},
            error: null
        }, () => {
            // Pass data object back to parent
            this.props.updateFamilyProbandDiseaseObj('delete');
            this.props.clearErrorInParent('familyProband');
        });
    },

    render() {
        let diseaseId = this.state.diseaseId;
        let diseaseTerm = this.state.diseaseTerm;
        let diseaseOntology = this.state.diseaseOntology;
        let diseaseDescription = this.state.diseaseDescription;
        let diseaseFreeTextConfirm = this.state.diseaseFreeTextConfirm;
        let phenotypes = this.state.phenotypes;
        let synonyms = this.state.synonyms;
        let addDiseaseModalBtn = diseaseTerm ? Disease : Disease;
        let error = this.state.error;
        let family = this.state.family, familyDiseaseObj = this.state.familyDiseaseObj;

        return (

                    Disease(s) for Individual:
                        {this.state.required ?  * : null}
                        Search MonDO using OLS

                        {error ?
                            {error}
                            :

                                {this.renderDiseaseData(diseaseId, diseaseTerm, diseaseDescription, phenotypes, diseaseFreeTextConfirm)}

                        }

                    {!diseaseTerm ?

                            {(family && family.disease && family.disease.term) || (familyDiseaseObj && familyDiseaseObj.term) ?

                                    {this.renderCopyDiseaseButton()}

                            : null}
                            {(family && family.disease && family.disease.term) || (familyDiseaseObj && familyDiseaseObj.term) ?

- or -

                            : null}

                                <DiseaseModal
                                    addDiseaseModalBtn={addDiseaseModalBtn}
                                    diseaseId={diseaseId}
                                    diseaseTerm={diseaseTerm}
                                    diseaseOntology={diseaseOntology}
                                    diseaseDescription={diseaseDescription}
                                    diseaseFreeTextConfirm={diseaseFreeTextConfirm}
                                    phenotypes={phenotypes}
                                    synonyms={synonyms}
                                    passDataToParent={this.passDataToParent}
                                    addDiseaseModalBtnLayoutClass=" evidence-disease"
                                />

                    :

                                Disease

                    }

        );
    }
});
<|endoftext|>


<commit_before>'use strict';

const execa = require('execa');
const log = require('intel').getLogger('browsertime.video');
const get = require('lodash.get');
const path = require('path');

const SCRIPT_PATH = require('../visualMetricsPath');

module.exports = {
  async checkDependencies() {
    return execa(SCRIPT_PATH, ['--check']);
  },
  async run(
    videoPath,
    imageDirPath,
    elementsFile,
    videoDir,
    index,
    pageNumber,
    visitedPageNumber,
    options
  ) {
    const filmstripQuality = get(options, 'videoParams.filmstripQuality', 75);
    const createFilmstrip = get(options, 'videoParams.createFilmstrip', true);
    const fullSizeFilmstrip = get(
      options,
      'videoParams.filmstripFullSize',
      false
    );

    const scriptArgs = [
      '--video',
      videoPath,
      '--orange',
      '--perceptual',
      '--force',
      '--renderignore',
      5,
      '--json',
      '--viewport'
    ];

    // There seems to be a bug with --startwhite that makes VM bail out
    // 11:20:14.950 - Calculating image histograms
    // 11:20:14.951 - No video frames found in /private/var/folders/27/xpnvcsbs0nlfbb4qq397z3rh0000gn/T/vis-cn_JMf
    // 11:20:14.951 - Done calculating histograms
    // Since we tuned the borders of the video, I hope it will just work fine
    // without. If not, let us create a upstream issue
    // If it is the first page and no preURL we can use
    // start white, that gives us less variance in metrics in Chrome
    /*
    if (!options.preURL && visitedPageNumber === 0) {
      scriptArgs.push('--startwhite');
    }
    */

    if (options.visualElements) {
      scriptArgs.push('--herodata');
      scriptArgs.push(elementsFile);
    }

    if (createFilmstrip) {
      scriptArgs.push('-q');
      scriptArgs.push(filmstripQuality);
      scriptArgs.unshift('--dir', imageDirPath);
      if (fullSizeFilmstrip) {
        scriptArgs.push('--full');
      }
    }

    if (options.verbose >= 1) {
      scriptArgs.push('--logfile');
      scriptArgs.push(path.join(videoDir, index + '.visualmetrics.log'));
      scriptArgs.push('-vvvv');
    }

    log.verbose('Running visualmetrics.py ' + scriptArgs.join(' '));

    const result = await execa(SCRIPT_PATH, scriptArgs);
    return JSON.parse(result.stdout);
  }
};
<commit_msg>debug log output from Visual Metrics<commit_after>'use strict';

const execa = require('execa');
const log = require('intel').getLogger('browsertime.video');
const get = require('lodash.get');
const path = require('path');

const SCRIPT_PATH = require('../visualMetricsPath');

module.exports = {
  async checkDependencies() {
    return execa(SCRIPT_PATH, ['--check']);
  },
  async run(
    videoPath,
    imageDirPath,
    elementsFile,
    videoDir,
    index,
    pageNumber,
    visitedPageNumber,
    options
  ) {
    const filmstripQuality = get(options, 'videoParams.filmstripQuality', 75);
    const createFilmstrip = get(options, 'videoParams.createFilmstrip', true);
    const fullSizeFilmstrip = get(
      options,
      'videoParams.filmstripFullSize',
      false
    );

    const scriptArgs = [
      '--video',
      videoPath,
      '--orange',
      '--perceptual',
      '--force',
      '--renderignore',
      5,
      '--json',
      '--viewport'
    ];

    // There seems to be a bug with --startwhite that makes VM bail out
    // 11:20:14.950 - Calculating image histograms
    // 11:20:14.951 - No video frames found in /private/var/folders/27/xpnvcsbs0nlfbb4qq397z3rh0000gn/T/vis-cn_JMf
    // 11:20:14.951 - Done calculating histograms
    // Since we tuned the borders of the video, I hope it will just work fine
    // without. If not, let us create a upstream issue
    // If it is the first page and no preURL we can use
    // start white, that gives us less variance in metrics in Chrome
    /*
    if (!options.preURL && visitedPageNumber === 0) {
      scriptArgs.push('--startwhite');
    }
    */

    if (options.visualElements) {
      scriptArgs.push('--herodata');
      scriptArgs.push(elementsFile);
    }

    if (createFilmstrip) {
      scriptArgs.push('-q');
      scriptArgs.push(filmstripQuality);
      scriptArgs.unshift('--dir', imageDirPath);
      if (fullSizeFilmstrip) {
        scriptArgs.push('--full');
      }
    }

    if (options.verbose >= 1) {
      scriptArgs.push('--logfile');
      scriptArgs.push(path.join(videoDir, index + '.visualmetrics.log'));
      scriptArgs.push('-vvvv');
    }

    log.debug('Running visualmetrics.py ' + scriptArgs.join(' '));

    const result = await execa(SCRIPT_PATH, scriptArgs);

    log.debug('visualmetrics.py output:' + result.stdout);
    return JSON.parse(result.stdout);
  }
};
<|endoftext|>


<commit_before>const https = require('https')
const util = require('util')

module.exports = (params) => {
  const debug = params.debug || false

  /**
   * Caso o flag debug for true, retorna o log no console
   */
  const log = function () {
    if (debug) {
      console.log('------------ DEBUG ------------\n', new Date(), '\n\n', arguments, '\n\n------------ END DEBUG ------------\n')
    }
  }

  const options = {
    port: 443,
    secureProtocol: 'TLSv1_method',
    encoding: 'utf-8',
    headers: {
      'Content-Type': 'application/json',
      'MerchantId': params.MerchantId,
      'MerchantKey': params.MerchantKey,
      'RequestId': params.RequestId || ''
    }
  }

  function getHostname (type) {
    switch (type) {
      case 'requisicao':
        if (params.sandbox) {
          return 'apisandbox.cieloecommerce.cielo.com.br'
        } else {
          return 'api.cieloecommerce.cielo.com.br'
        }
      case 'consulta':
        if (params.sandbox) {
          return 'apiquerysandbox.cieloecommerce.cielo.com.br'
        } else {
          return 'apiquery.cieloecommerce.cielo.com.br'
        }
      default:
        return 'ERROR - HOSTNAME OPTIONS INVÁLIDO'
    }
  }

  const r = function (requestOptions, data) {
    return new Promise((resolve, reject) => {
      var opt = Object.assign(options, requestOptions)
      const d = JSON.stringify(data)
      opt.headers['Content-Length'] = Buffer.byteLength(d)
      var req = https.request(opt, (res) => {
        log('request options data', opt, data)
        var chunks = []

        res.on('data', function (chunk) {
          chunks.push(chunk)
        })

        res.on('end', function () {
          var body = Buffer.concat(chunks)
          var r = ''
          try {
            r = JSON.parse(body)
            log('retorno cielo', r)
          } catch (err) {
            return reject(err)
          }
          log('res.on(end)', r)
          return resolve(r)
        })
      })
      req.write(d)
      req.on('error', (err) => {
        log('erro no request ', err)
        return reject(err)
      })
      req.end()
    })
  }

  const postSalesCielo = (data) => {
    const o = {
      hostname: getHostname('requisicao'),
      path: '/1/sales',
      method: 'POST'
    }
    return r(o, data)
  }

  const captureSale = (data) => {
    var o = {
      hostname: getHostname('requisicao'),
      path: util.format('/1/sales/%s/capture?amount=%s', data.paymentId, data.amount)
    }

    if (data.serviceTaxAmount) {
      o.path += util.format('/serviceTaxAmount=%s', data.serviceTaxAmount)
    }

    options.method = 'PUT'
    return r(o, data)
  }

  /**
   * Cancela a venda - Dá preferencia para cancelar pelo paymentId, se não existir, utiliza o OrderId
   * @param {object} data
   * @param {callback} callback
   */
  const cancelSale = (data) => {
    var o = {
      hostname: getHostname('requisicao'),
      method: 'PUT'
    }

    if (data.paymentId) {
      o.path = util.format('/1/sales/%s/void', data.paymentId)
    } else {
      o.path = util.format('/1/sales/OrderId/%s/void', data.merchantOrderId)
    }

    // Se o valor do cancelamento for informado, concatena na url
    if (data.amount > 0){
      o.path += util.format('?amount=%s', data.amount)
    }

    return r(o, data)
  }

  const modifyingRecurrence = (data) => {
    const o = {
      hostname: getHostname('requisicao'),
      path: util.format('/1/RecurrentPayment/%s/%s', data.recurrentPaymentId, data.type),
      method: 'PUT'
    }
    return r(o, data)
  }

  const createTokenizedCard = (data) => {
    const o = {
      hostname: getHostname('requisicao'),
      path: '/1/card',
      method: 'POST'
    }
    return r(o, data)
  }

  const consultaCielo = (data) => {
    const o = {
      hostname: getHostname('consulta'),
      path: (typeof data.paymentId !== 'undefined') ? util.format('/1/sales/%s', data.paymentId) : util.format('/1/sales?merchantOrderId=%s', data.merchantOrderId),
      method: 'GET'
    }
    return r(o, data)
  }

  const cardBin = (data) => {
    const o = {
      hostname: getHostname('consulta'),
      path: util.format('/1/cardBin/%s', data.cardBin),
      method: 'GET'
    }
    return r(o, data)
  }

  return {
    creditCard: {
      simpleTransaction: postSalesCielo,
      completeTransaction: postSalesCielo,
      authenticationTransaction: postSalesCielo,
      fraudAnalysisTransaction: postSalesCielo,
      cardTokenTransaction: postSalesCielo,
      captureSaleTransaction: captureSale,
      cancelSale: cancelSale
    },
    debitCard: {
      simpleTransaction: postSalesCielo
    },
    bankSlip: {
      simpleTransaction: postSalesCielo
    },
    boleto: {
      sale: postSalesCielo
    },
    recurrentPayments: {
      firstScheduledRecurrence: postSalesCielo,
      creditScheduledRecurrence: postSalesCielo,
      authorizing: postSalesCielo,
      modifyBuyerData: modifyingRecurrence
    },
    cards: {
      createTokenizedCard: createTokenizedCard
    },
    consulting: {
      sale: consultaCielo,
      storeIndetifier: consultaCielo,
      fraudAnalysis: consultaCielo,
      cardBin: cardBin
    }
  }
}
<commit_msg>Correção de parâmetros de conexão com a Cielo Retorno de erro com mais informações sobre o erro<commit_after>const https = require('https')
const util = require('util')

module.exports = (params) => {
  const debug = params.debug || false

  /**
   * Caso o flag debug for true, retorna o log no console
   */
  const log = function () {
    if (debug) {
      console.log('------------ DEBUG ------------\n', new Date(), '\n\n', arguments, '\n\n------------ END DEBUG ------------\n')
    }
  }

  const options = {
    port: 443,
    encoding: 'utf-8',
    headers: {
      'Content-Type': 'application/json',
      'MerchantId': params.MerchantId,
      'MerchantKey': params.MerchantKey,
      'RequestId': params.RequestId || ''
    }
  }

  function getHostname (type) {
    switch (type) {
      case 'requisicao':
        if (params.sandbox) {
          return 'apisandbox.cieloecommerce.cielo.com.br'
        } else {
          return 'api.cieloecommerce.cielo.com.br'
        }
      case 'consulta':
        if (params.sandbox) {
          return 'apiquerysandbox.cieloecommerce.cielo.com.br'
        } else {
          return 'apiquery.cieloecommerce.cielo.com.br'
        }
      default:
        return 'ERROR - HOSTNAME OPTIONS INVÁLIDO'
    }
  }

  const r = function (requestOptions, data) {
    return new Promise((resolve, reject) => {
      var opt = Object.assign(options, requestOptions)
      const d = JSON.stringify(data)
      opt.headers['Content-Length'] = Buffer.byteLength(d)
      var req = https.request(opt, (res) => {
        log('request options data', opt, data)
        var chunks = []

        res.on('data', function (chunk) {
          chunks.push(chunk)
        })

        res.on('end', function () {
          var body = Buffer.concat(chunks)
          var r = ''
          try {
            r = JSON.parse(body)
            log('retorno cielo', r)
          } catch (err) {
            return reject(err)
          }
          log('res.on(end)', r)
          return resolve(r)
        })
      })
      req.write(d)
      req.on('error', (err) => {
        const e = {
          msg: 'Erro na requisicao para a Cielo',
          request: opt,
          data: d,
          erro: err
        }
        log('erro no request ', e)
        return reject(e)
      })
      req.end()
    })
  }

  const postSalesCielo = (data) => {
    const o = {
      hostname: getHostname('requisicao'),
      path: '/1/sales',
      method: 'POST'
    }
    return r(o, data)
  }

  const captureSale = (data) => {
    var o = {
      hostname: getHostname('requisicao'),
      path: util.format('/1/sales/%s/capture?amount=%s', data.paymentId, data.amount)
    }

    if (data.serviceTaxAmount) {
      o.path += util.format('/serviceTaxAmount=%s', data.serviceTaxAmount)
    }

    options.method = 'PUT'
    return r(o, data)
  }

  /**
   * Cancela a venda - Dá preferencia para cancelar pelo paymentId, se não existir, utiliza o OrderId
   * @param {object} data
   * @param {callback} callback
   */
  const cancelSale = (data) => {
    var o = {
      hostname: getHostname('requisicao'),
      method: 'PUT'
    }

    if (data.paymentId) {
      o.path = util.format('/1/sales/%s/void', data.paymentId)
    } else {
      o.path = util.format('/1/sales/OrderId/%s/void', data.merchantOrderId)
    }

    // Se o valor do cancelamento for informado, concatena na url
    if (data.amount > 0){
      o.path += util.format('?amount=%s', data.amount)
    }

    return r(o, data)
  }

  const modifyingRecurrence = (data) => {
    const o = {
      hostname: getHostname('requisicao'),
      path: util.format('/1/RecurrentPayment/%s/%s', data.recurrentPaymentId, data.type),
      method: 'PUT'
    }
    return r(o, data)
  }

  const createTokenizedCard = (data) => {
    const o = {
      hostname: getHostname('requisicao'),
      path: '/1/card',
      method: 'POST'
    }
    return r(o, data)
  }

  const consultaCielo = (data) => {
    const o = {
      hostname: getHostname('consulta'),
      path: (typeof data.paymentId !== 'undefined') ? util.format('/1/sales/%s', data.paymentId) : util.format('/1/sales?merchantOrderId=%s', data.merchantOrderId),
      method: 'GET'
    }
    return r(o, data)
  }

  const cardBin = (data) => {
    const o = {
      hostname: getHostname('consulta'),
      path: util.format('/1/cardBin/%s', data.cardBin),
      method: 'GET'
    }
    return r(o, data)
  }

  return {
    creditCard: {
      simpleTransaction: postSalesCielo,
      completeTransaction: postSalesCielo,
      authenticationTransaction: postSalesCielo,
      fraudAnalysisTransaction: postSalesCielo,
      cardTokenTransaction: postSalesCielo,
      captureSaleTransaction: captureSale,
      cancelSale: cancelSale
    },
    debitCard: {
      simpleTransaction: postSalesCielo
    },
    bankSlip: {
      simpleTransaction: postSalesCielo
    },
    boleto: {
      sale: postSalesCielo
    },
    recurrentPayments: {
      firstScheduledRecurrence: postSalesCielo,
      creditScheduledRecurrence: postSalesCielo,
      authorizing: postSalesCielo,
      modifyBuyerData: modifyingRecurrence
    },
    cards: {
      createTokenizedCard: createTokenizedCard
    },
    consulting: {
      sale: consultaCielo,
      storeIndetifier: consultaCielo,
      fraudAnalysis: consultaCielo,
      cardBin: cardBin
    }
  }
}
<|endoftext|>


<commit_before>$(document).ready(function() {
    $('.draftbutt').on('click', function() {
	var dnum = $(this).parent().parent().next('.secondaryitems').attr('id');
	var mark = $(this).parent().parent().find('td :first').next().text().trim();
	var langSelect = whatLanguage(mark);

	$('#lansel').append('
'+dnum+'
');

	for (var langKey in langSelect) {
	    if (langSelect.hasOwnProperty(langKey)) {
		var langValue = langSelect[langKey];
		$('#lansel').append('<option val='+langKey+'>'+langValue+'</option>')
	    };
	};

	$('#modalreview2').modal();

	$('#loaddraft').on('click', function() {
	    window.location.replace('/draft/'+dnum+'/'+$('#lansel option:selected').attr('val')+'/');
	});
    });

    $('.mainitems, .secondaryitems').each(function() {
	var cleanclass = $(this).children('td:first').text().replace('/','').trim();
	$(this).addClass(cleanclass);
    });

    $('tr.mainitems').on('click', function() {
	var num = $(this).children("td:first").text().replace('/', '').trim();
	$('.secondaryitems.' + num).toggle();
    });

    $(document).on('click', '.editbutton', function() {
	//need to build an ajax call which will populate the modal with the data from the item
	var objId = parseInt($(this).parent().parent().attr('id'));
	//setup the AJAX request
	$.ajaxSetup({
	    type: 'POST',
	    dataType: 'json'
	});

	//the real AJAX request
	$.ajax({
	    url: '/ajax/',
	    data: {
		form_type: 'edit',
		id: objId
	    },
	    success: function(json_data) {
		modalEdit(json_data);
		},
	    error: function (ajaxObj, textStatus, error) {
		alert(error);
	    }
	});
	return true;
    });
});

function modalEdit(dataEdit) {
    //populate the field with the values from DB
    changedItem = dataEdit;
    changedStuff = 0;
    var iid = dataEdit.itemid;

    $('h4').append(''+iid+'');
    $('#id_market').val(dataEdit.market);
    $('#id_ccode').show();
    $('#id_ccode').val(dataEdit.ccode);
    $('#dln').val(dataEdit.remindernumber);
    $('#invn').val(dataEdit.invoicenumber);
    $('#id_invoicestatus').val(dataEdit.invoicestatus);
    $('#id_rejectreason').val(dataEdit.rejectreason);
    $('#id_paidon').val(dataEdit.paidon);
    $('#vendm').val(dataEdit.mailvendor);
    $('#vendn').val(dataEdit.vendor);
    $('#id_level').val(dataEdit.level);
    $('#dld').val(dataEdit.reminderdate);
    $('#modalreview').modal();
    $('#dld').datepicker();

    $('#save').on('click', function() {
	var dateToSplit = $('#id_paidon').val()
	var obj = {
	    itemid: $('#itemid').text(),
	    mailvendor: $('#vendm').val(),
	    paidon: dateToSplit.split("/")[2]+"-"+dateToSplit.split("/")[0]+"-"+dateToSplit.split("/")[1],
	    vendor: $('#vendn').val(),
	    ccode: $('#id_ccode').val(),
	    market: $('#id_market').val(),
	    remindernumber: $('#dln').val(),
	    invoicenumber: $('#invn').val(),
	    invoicestatus: $('#id_invoicestatus').val(),
	    //actiontaken: $('#id_actiontaken').val(),
	    rejectreason: $('#id_rejectreason').val(),
	    level: $('#id_level').val(),
	    reminderdate: $('#dld').val(),
	    };

	$.each(obj, function(key, value) {
	    if (key !== "success" || key !== "error") {
		if (obj[key] !== changedItem[key]) {
		    changedStuff++;
		};
	    };
	});
	if (changedStuff != 0) {Update(obj)};
    });
};

function Update(item) {
    $.ajaxSetup({
	type: 'POST',
	dataType: 'json'
    });

    //the real AJAX request
    $.ajax({
	url: '/ajax/',
	data: {
	    form_type: 'update',
	    mass_data: JSON.stringify(item)
	},
	success: alert("success"), //todo
	error: function (ajaxObj, textStatus, error) {
	    alert(error);
	}
    });
    return true;
}

function whatLanguage(market) {

    switch(market)
    {
	case "IT":
	var lObj = {IT: "Italian", EN: "English"};
	break;
	case "DE":
	var lObj = {DE: "German", EN: "English"};
	break;
    };

    return lObj;
};
<commit_msg>Replaced alert with "redirection".<commit_after>$(document).ready(function() {
    $('.draftbutt').on('click', function() {
	var dnum = $(this).parent().parent().next('.secondaryitems').attr('id');
	var mark = $(this).parent().parent().find('td :first').next().text().trim();
	var langSelect = whatLanguage(mark);

	$('#lansel').append('
'+dnum+'
');

	for (var langKey in langSelect) {
	    if (langSelect.hasOwnProperty(langKey)) {
		var langValue = langSelect[langKey];
		$('#lansel').append('<option val='+langKey+'>'+langValue+'</option>')
	    };
	};

	$('#modalreview2').modal();

	$('#loaddraft').on('click', function() {
	    window.location.replace('/draft/'+dnum+'/'+$('#lansel option:selected').attr('val')+'/');
	});
    });

    $('.mainitems, .secondaryitems').each(function() {
	var cleanclass = $(this).children('td:first').text().replace('/','').trim();
	$(this).addClass(cleanclass);
    });

    $('tr.mainitems').on('click', function() {
	var num = $(this).children("td:first").text().replace('/', '').trim();
	$('.secondaryitems.' + num).toggle();
    });

    $(document).on('click', '.editbutton', function() {
	//need to build an ajax call which will populate the modal with the data from the item
	var objId = parseInt($(this).parent().parent().attr('id'));
	//setup the AJAX request
	$.ajaxSetup({
	    type: 'POST',
	    dataType: 'json'
	});

	//the real AJAX request
	$.ajax({
	    url: '/ajax/',
	    data: {
		form_type: 'edit',
		id: objId
	    },
	    success: function(json_data) {
		modalEdit(json_data);
		},
	    error: function (ajaxObj, textStatus, error) {
		alert(error);
	    }
	});
	return true;
    });
});

function modalEdit(dataEdit) {
    //populate the field with the values from DB
    changedItem = dataEdit;
    changedStuff = 0;
    var iid = dataEdit.itemid;

    $('h4').append(''+iid+'');
    $('#id_market').val(dataEdit.market);
    $('#id_ccode').show();
    $('#id_ccode').val(dataEdit.ccode);
    $('#dln').val(dataEdit.remindernumber);
    $('#invn').val(dataEdit.invoicenumber);
    $('#id_invoicestatus').val(dataEdit.invoicestatus);
    $('#id_rejectreason').val(dataEdit.rejectreason);
    $('#id_paidon').val(dataEdit.paidon);
    $('#vendm').val(dataEdit.mailvendor);
    $('#vendn').val(dataEdit.vendor);
    $('#id_level').val(dataEdit.level);
    $('#dld').val(dataEdit.reminderdate);
    $('#modalreview').modal();
    $('#dld').datepicker();

    $('#save').on('click', function() {
	var dateToSplit = $('#id_paidon').val()
	var obj = {
	    itemid: $('#itemid').text(),
	    mailvendor: $('#vendm').val(),
	    paidon: dateToSplit.split("/")[2]+"-"+dateToSplit.split("/")[0]+"-"+dateToSplit.split("/")[1],
	    vendor: $('#vendn').val(),
	    ccode: $('#id_ccode').val(),
	    market: $('#id_market').val(),
	    remindernumber: $('#dln').val(),
	    invoicenumber: $('#invn').val(),
	    invoicestatus: $('#id_invoicestatus').val(),
	    //actiontaken: $('#id_actiontaken').val(),
	    rejectreason: $('#id_rejectreason').val(),
	    level: $('#id_level').val(),
	    reminderdate: $('#dld').val(),
	    };

	$.each(obj, function(key, value) {
	    if (key !== "success" || key !== "error") {
		if (obj[key] !== changedItem[key]) {
		    changedStuff++;
		};
	    };
	});
	if (changedStuff != 0) {Update(obj)};
    });
};

function Update(item) {
    $.ajaxSetup({
	type: 'POST',
	dataType: 'json'
    });

    //the real AJAX request
    $.ajax({
	url: '/ajax/',
	data: {
	    form_type: 'update',
	    mass_data: JSON.stringify(item)
	},
	success: window.location.replace("/overview/"),
	error: function (ajaxObj, textStatus, error) {
	    alert(error);
	}
    });
    return true;
}

function whatLanguage(market) {

    switch(market)
    {
	case "IT":
	var lObj = {IT: "Italian", EN: "English"};
	break;
	case "DE":
	var lObj = {DE: "German", EN: "English"};
	break;
    };

    return lObj;
};
<|endoftext|>