<commit_before>Ext.define('test.PortletContainerController', {
    singleton: true,
    requires: ['faceid.controller.PortletContainer'],
    constructor: function () {
        describe('PortletContainerController test', function () {
            var oExtCreateFn;

            beforeEach(function () {
                oExtCreateFn = Ext.create;
            });

            afterEach(function () {
                Ext.create = oExtCreateFn;
            });

            it('should save the settings', function () {
                var saveExecuted = false;
                var data = {
                    xtype: 'my-xtype',
                    x: 1,
                    y: 2,
                    width: 3,
                    height: 4
                };
                Ext.create = function (name, args) {
                    var obj = oExtCreateFn(name, args);
                    if (name === 'faceid.model.PanelSettings') {
                        obj.save = function () {
                            saveExecuted = true;
                            expect(this.get('portletXtype')).toBe(data.xtype);
                            expect(this.get('x')).toBe(data.x);
                            expect(this.get('y')).toBe(data.y);
                            expect(this.get('width')).toBe(data.width);
                            expect(this.get('height')).toBe(data.height);
                        };
                    }
                    return obj;
                };

                var definition = classDefinitions['faceid.controller.PortletContainer'];
                var settings = definition.saveSettings(data);
                expect(settings).not.toBe(null);
            });
        });
    }
});

<commit_msg>-jasmine<commit_after>Ext.define('test.PortletContainerController', {
    singleton: true,
    requires: ['faceid.controller.PortletContainer'],
    constructor: function () {
        describe('PortletContainerController test', function () {
            var oExtCreateFn;

            beforeEach(function () {
                oExtCreateFn = Ext.create;
            });

            afterEach(function () {
                Ext.create = oExtCreateFn;
            });

            it('should save the settings', function () {
                var saveExecuted = false;
                var data = {
                    xtype: 'my-xtype',
                    x: 1,
                    y: 2,
                    width: 3,
                    height: 4
                };
                Ext.create = function (name, args) {
                    var obj = oExtCreateFn(name, args);
                    if (name === 'faceid.model.PanelSettings') {
                        obj.save = function () {
                            saveExecuted = true;
                            expect(this.get('portletXtype')).toBe(data.xtype);
                            expect(this.get('x')).toBe(data.x);
                            expect(this.get('y')).toBe(data.y);
                            expect(this.get('width')).toBe(data.width);
                            expect(this.get('height')).toBe(data.height);
                        };
                    }
                    return obj;
                };

                var definition = classDefinitions['faceid.controller.PortletContainer'];
                var settings = definition.saveSettings(data);
                expect(saveExecuted).toBe(true);
                expect(settings).not.toBe(null);

            });

            it('should show the portlet', function () {
                var saveExecuted = false;
                var data = {
                    xtype: 'my-xtype',
                    x: 1,
                    y: 2,
                    width: 3,
                    height: 4
                };
                Ext.create = function (name, args) {
                    var obj = oExtCreateFn(name, args);
                    if (name === 'faceid.model.PanelSettings') {
                        obj.save = function () {
                            saveExecuted = true;
                            expect(this.get('portletXtype')).toBe(data.xtype);
                            expect(this.get('x')).toBe(data.x);
                            expect(this.get('y')).toBe(data.y);
                            expect(this.get('width')).toBe(data.width);
                            expect(this.get('height')).toBe(data.height);
                        };
                    }
                    return obj;
                };

                var definition = classDefinitions['faceid.controller.PortletContainer'];
                var settings = definition.saveSettings(data);
                expect(saveExecuted).toBe(true);
                expect(settings).not.toBe(null);

            });

        });
    }
});

<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import React from 'react';
import { injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import withSampleSize from '../../common/composers/SampleSize';
import withCsvDownloadNotifyContainer from '../../common/hocs/CsvDownloadNotifyContainer';
import { filteredLinkTo, filtersAsUrlParams } from '../../util/location';
import withAsyncFetch from '../../common/hocs/AsyncContainer';
import withSummary from '../../common/hocs/SummarizedVizualization';
import EditableWordCloudDataCard from '../../common/EditableWordCloudDataCard';
import { fetchTopicTopWords } from '../../../actions/topicActions';
import messages from '../../../resources/messages';
import { generateParamStr } from '../../../lib/apiUtil';
import { topicDownloadFilename } from '../../util/topicUtil';

const WORD_CLOUD_DOM_ID = 'topic-summary-media-word-cloud';

const localMessages = {
  descriptionIntro: { id: 'topic.summary.words.help.into',
    defaultMessage: '
Look at the top words to see how this topic was talked about. This can suggest what the dominant narrative was, and looking at different timespans can suggest how it evolved over time.
',
  },
};

class WordsSummaryContainer extends React.Component {
  componentWillReceiveProps(nextProps) {
    const { filters, fetchData } = this.props;
    if (nextProps.filters !== filters) {
      fetchData(nextProps);
    }
  }
  render() {
    const { topicInfo, initSampleSize, onViewSampleSizeClick, filters, handleWordCloudClick } = this.props;
    const urlDownload = `/api/topics/${topicInfo.topics_id}/words.csv?${filtersAsUrlParams(filters)}`;
    return (
      <EditableWordCloudDataCard
        words={this.props.words}
        initSampleSize={initSampleSize}
        downloadUrl={urlDownload}
        border={false}
        onViewModeClick={handleWordCloudClick}
        onViewSampleSizeClick={onViewSampleSizeClick}
        domId={WORD_CLOUD_DOM_ID}
        svgDownloadPrefix={`${topicDownloadFilename(topicInfo.name, filters)}-words`}
        hideGoogleWord2Vec
        actionsAsLinksUnderneath
      />
    );
  }
}

WordsSummaryContainer.propTypes = {
  // from compositional chain
  intl: PropTypes.object.isRequired,
  // from parent
  topicId: PropTypes.number.isRequired,
  topicName: PropTypes.string.isRequired,
  filters: PropTypes.object.isRequired,
  width: PropTypes.number,
  height: PropTypes.number,
  maxFontSize: PropTypes.number,
  minFontSize: PropTypes.number,
  // from dispatch
  asyncFetch: PropTypes.func.isRequired,
  fetchData: PropTypes.func.isRequired,
  initSampleSize: PropTypes.string,
  handleExplore: PropTypes.func.isRequired,
  // from state
  topicInfo: PropTypes.object,
  words: PropTypes.array,
  fetchStatus: PropTypes.string.isRequired,
  handleWordCloudClick: PropTypes.func,
  onViewSampleSizeClick: PropTypes.func.isRequired,
};

const mapStateToProps = state => ({
  fetchStatus: state.topics.selected.summary.topWords.fetchStatus,
  topicInfo: state.topics.selected.info,
  words: state.topics.selected.summary.topWords.list,
  filters: state.topics.selected.filters,
});

const mapDispatchToProps = (dispatch, ownProps) => ({
  fetchData: (sampleSize) => {
    dispatch(fetchTopicTopWords(ownProps.topicId, { ...ownProps.filters, sample_size: sampleSize.sample_size }));
  },
  asyncFetch: () => {
    dispatch(fetchTopicTopWords(ownProps.topicId, ownProps.filters));
  },
  pushToUrl: url => dispatch(push(url)),
  handleExplore: () => {
    const exploreUrl = filteredLinkTo(`/topics/${ownProps.topicId}/words`, ownProps.filters);
    dispatch(push(exploreUrl));
  },
});

function mergeProps(stateProps, dispatchProps, ownProps) {
  return Object.assign({}, stateProps, dispatchProps, ownProps, {
    handleWordCloudClick: (word) => {
      // imoprtant to pick term with the OR clause for other languages that we don't stem well
      const params = generateParamStr({ ...stateProps.filters, stem: word.stem, term: word.term || word.stem });
      const url = `/topics/${ownProps.topicId}/words/${word.stem}*?${params}`;
      dispatchProps.pushToUrl(url);
    },
  });
}

export default
  injectIntl(
    connect(mapStateToProps, mapDispatchToProps, mergeProps)(
      withSampleSize(
        withSummary(messages.topWords, localMessages.descriptionIntro, [messages.wordcloudHelpText, messages.wordCloudTopicWord2VecLayoutHelp])(
          withAsyncFetch(
            withCsvDownloadNotifyContainer(
              WordsSummaryContainer
            )
          )
        )
      )
    )
  );
<commit_msg>Topic word cloud width (#1144)<commit_after>import PropTypes from 'prop-types';
import React from 'react';
import { injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import withSampleSize from '../../common/composers/SampleSize';
import withCsvDownloadNotifyContainer from '../../common/hocs/CsvDownloadNotifyContainer';
import { filteredLinkTo, filtersAsUrlParams } from '../../util/location';
import withAsyncFetch from '../../common/hocs/AsyncContainer';
import withSummary from '../../common/hocs/SummarizedVizualization';
import EditableWordCloudDataCard from '../../common/EditableWordCloudDataCard';
import { fetchTopicTopWords } from '../../../actions/topicActions';
import messages from '../../../resources/messages';
import { generateParamStr } from '../../../lib/apiUtil';
import { topicDownloadFilename } from '../../util/topicUtil';

const WORD_CLOUD_DOM_ID = 'topic-summary-media-word-cloud';

const localMessages = {
  descriptionIntro: { id: 'topic.summary.words.help.into',
    defaultMessage: '
Look at the top words to see how this topic was talked about. This can suggest what the dominant narrative was, and looking at different timespans can suggest how it evolved over time.
',
  },
};

class WordsSummaryContainer extends React.Component {
  componentWillReceiveProps(nextProps) {
    const { filters, fetchData } = this.props;
    if (nextProps.filters !== filters) {
      fetchData(nextProps);
    }
  }
  render() {
    const { topicInfo, initSampleSize, onViewSampleSizeClick, filters, handleWordCloudClick } = this.props;
    const urlDownload = `/api/topics/${topicInfo.topics_id}/words.csv?${filtersAsUrlParams(filters)}`;
    return (
      <EditableWordCloudDataCard
        width={630}
        words={this.props.words}
        initSampleSize={initSampleSize}
        downloadUrl={urlDownload}
        border={false}
        onViewModeClick={handleWordCloudClick}
        onViewSampleSizeClick={onViewSampleSizeClick}
        domId={WORD_CLOUD_DOM_ID}
        svgDownloadPrefix={`${topicDownloadFilename(topicInfo.name, filters)}-words`}
        hideGoogleWord2Vec
        actionsAsLinksUnderneath
      />
    );
  }
}

WordsSummaryContainer.propTypes = {
  // from compositional chain
  intl: PropTypes.object.isRequired,
  // from parent
  topicId: PropTypes.number.isRequired,
  topicName: PropTypes.string.isRequired,
  filters: PropTypes.object.isRequired,
  width: PropTypes.number,
  height: PropTypes.number,
  maxFontSize: PropTypes.number,
  minFontSize: PropTypes.number,
  // from dispatch
  asyncFetch: PropTypes.func.isRequired,
  fetchData: PropTypes.func.isRequired,
  initSampleSize: PropTypes.string,
  handleExplore: PropTypes.func.isRequired,
  // from state
  topicInfo: PropTypes.object,
  words: PropTypes.array,
  fetchStatus: PropTypes.string.isRequired,
  handleWordCloudClick: PropTypes.func,
  onViewSampleSizeClick: PropTypes.func.isRequired,
};

const mapStateToProps = state => ({
  fetchStatus: state.topics.selected.summary.topWords.fetchStatus,
  topicInfo: state.topics.selected.info,
  words: state.topics.selected.summary.topWords.list,
  filters: state.topics.selected.filters,
});

const mapDispatchToProps = (dispatch, ownProps) => ({
  fetchData: (sampleSize) => {
    dispatch(fetchTopicTopWords(ownProps.topicId, { ...ownProps.filters, sample_size: sampleSize.sample_size }));
  },
  asyncFetch: () => {
    dispatch(fetchTopicTopWords(ownProps.topicId, ownProps.filters));
  },
  pushToUrl: url => dispatch(push(url)),
  handleExplore: () => {
    const exploreUrl = filteredLinkTo(`/topics/${ownProps.topicId}/words`, ownProps.filters);
    dispatch(push(exploreUrl));
  },
});

function mergeProps(stateProps, dispatchProps, ownProps) {
  return Object.assign({}, stateProps, dispatchProps, ownProps, {
    handleWordCloudClick: (word) => {
      // imoprtant to pick term with the OR clause for other languages that we don't stem well
      const params = generateParamStr({ ...stateProps.filters, stem: word.stem, term: word.term || word.stem });
      const url = `/topics/${ownProps.topicId}/words/${word.stem}*?${params}`;
      dispatchProps.pushToUrl(url);
    },
  });
}

export default
  injectIntl(
    connect(mapStateToProps, mapDispatchToProps, mergeProps)(
      withSampleSize(
        withSummary(messages.topWords, localMessages.descriptionIntro, [messages.wordcloudHelpText, messages.wordCloudTopicWord2VecLayoutHelp])(
          withAsyncFetch(
            withCsvDownloadNotifyContainer(
              WordsSummaryContainer
            )
          )
        )
      )
    )
  );
<|endoftext|>


<commit_before>// m16_003 #558, 568
//
// the fact that a page is returned is sufficient to validate this test
casper.test.begin('m16_003 #558, 568 diacritics in other author ', 1, function suite(test) {
casper.echo("Test environment: "+SERVER);
var USECASE='/item/13319347';
var ENTITY=SERVER+USECASE;
	casper.start(ENTITY, function() {
	test.assertTextExists('Cademos do Programa' , 'page title Cademo do Programa... found');
    }).run(function() {
        test.done();
    });
});
<commit_msg>revised test on title<commit_after>// m16_003 #558, 568
//
// the fact that a page is returned is sufficient to validate this test
casper.test.begin('m16_003 #558, 568 diacritics in other author ', 1, function suite(test) {
casper.echo("Test environment: "+SERVER);
var USECASE='/item/13319347';
var ENTITY=SERVER+USECASE;
	casper.start(ENTITY, function() {
	test.assertTextExists('Cadernos' , 'page title Caderno do Programa... found');
    }).run(function() {
        test.done();
    });
});
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var debug = require('debug')('workspace:server');
var http = require('http');

var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session')({
    secret: "secret",
    key: 'secret.sid',
    resave: true,
    saveUninitialized: true,
    cookie: {
        maxAge: 3600000
    }
});

var sharedSession = require('express-socket.io-session');
var openid = require('openid');

var app = express();

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

var server = http.Server(app);

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

function normalizePort(val) {
    var port = parseInt(val, 10);

    if (isNaN(port)) {
        // named pipe
        return val;
    }

    if (port >= 0) {
        // port number
        return port;
    }

    return false;
}

function onError(error) {
    if (error.syscall !== 'listen') {
        throw error;
    }

    var bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port;

    // handle specific listen errors with friendly messages
    switch (error.code) {
        case 'EACCES':
        console.error(bind + ' requires elevated privileges');
        process.exit(1);
        break;
        case 'EADDRINUSE':
        console.error(bind + ' is already in use');
        process.exit(1);
        break;
        default:
        throw error;
    }
}

function onListening() {
    var addr = server.address();
    var bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port;
    console.log('Listening on ' + bind);
}

var io = require('socket.io')(server);

var socketUsers = [];

io.use(sharedSession(session, {
    autoSave: true
}));

io.on('connection', function(socket) {
    socketUsers[socket.id] = socket;

    console.log('Player connected: ' + socket.id);

    socket.on('disconnect', function() {
        delete socketUsers[socket.id];
        console.log(socketUsers.length + ' players online.');
    });

    function broadcast(key, value) {
        io.emit(key, value);
    }
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));

app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(session);

function createRelyingParty(req) {
    var baseUrl = req.protocol + "://" + req.get("host");
    return new openid.RelyingParty(baseUrl + "/verify", baseUrl, true, false, []);
}

// for every request lets make the user session available to the templates
app.use(function(req, res, next) {
    res.locals.user = req.session.user;
    next();
});

app.get("/", function(req, res) {
    res.render('index', {
        title: 'Hello Title!',
        session: (typeof req.session.user !== 'undefined') ? req.session.user : ''
    });
});

app.get("/login", function(req, res) {
    createRelyingParty(req).authenticate("http://steamcommunity.com/openid", false, function(e, authUrl) {
        if (e) {
            return res.redirect("/");
        }
        res.redirect(authUrl);
    });
});

app.get("/verify", function(req, res) {
    createRelyingParty(req).verifyAssertion(req, function(e, result) {

        if (!result.authenticated) {
            return res.redirect("/");
        }

        var IDENTIFIER_REGEX = /^https?:\/\/steamcommunity\.com\/openid\/id\/([0-9]+)$/;
        var matches = IDENTIFIER_REGEX.exec(result.claimedIdentifier);

        if (matches === null) {
            return res.redirect("/");
        }

        req.session.user = matches[1]; // steam64
        return res.redirect("/");
    });

});

app.get("/logout", function(req, res) {
    req.session.destroy(function(err) {
        res.redirect("/");
    });
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});
<commit_msg>Fixed array of connected socket users<commit_after>var express = require('express');
var path = require('path');
var debug = require('debug')('workspace:server');
var http = require('http');

var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session')({
    secret: "secret",
    key: 'secret.sid',
    resave: true,
    saveUninitialized: true,
    cookie: {
        maxAge: 3600000
    }
});

var sharedSession = require('express-socket.io-session');
var openid = require('openid');

var app = express();

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

var server = http.Server(app);

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

function normalizePort(val) {
    var port = parseInt(val, 10);

    if (isNaN(port)) {
        // named pipe
        return val;
    }

    if (port >= 0) {
        // port number
        return port;
    }

    return false;
}

function onError(error) {
    if (error.syscall !== 'listen') {
        throw error;
    }

    var bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port;

    // handle specific listen errors with friendly messages
    switch (error.code) {
        case 'EACCES':
        console.error(bind + ' requires elevated privileges');
        process.exit(1);
        break;
        case 'EADDRINUSE':
        console.error(bind + ' is already in use');
        process.exit(1);
        break;
        default:
        throw error;
    }
}

function onListening() {
    var addr = server.address();
    var bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port;
    console.log('Listening on ' + bind);
}

var io = require('socket.io')(server);

var socketUsers = [];

io.use(sharedSession(session, {
    autoSave: true
}));

io.on('connection', function(socket) {
    socketUsers.push(socket);

    console.log('Player connected: ' + socket.id);

    socket.on('disconnect', function() {
        for(var i=0; i < socketUsers.length; i++) {
            if(socketUsers[i].id == socket.id) {
                delete socketUsers[i];
                break;
            }
        }
        console.log(socketUsers.length + ' players online.');
    });

    function broadcast(key, value) {
        io.emit(key, value);
    }
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));

app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(session);

function createRelyingParty(req) {
    var baseUrl = req.protocol + "://" + req.get("host");
    return new openid.RelyingParty(baseUrl + "/verify", baseUrl, true, false, []);
}

// for every request lets make the user session available to the templates
app.use(function(req, res, next) {
    res.locals.user = req.session.user;
    next();
});

app.get("/", function(req, res) {
    res.render('index', {
        title: 'Hello Title!',
        session: (typeof req.session.user !== 'undefined') ? req.session.user : ''
    });
});

app.get("/login", function(req, res) {
    createRelyingParty(req).authenticate("http://steamcommunity.com/openid", false, function(e, authUrl) {
        if (e) {
            return res.redirect("/");
        }
        res.redirect(authUrl);
    });
});

app.get("/verify", function(req, res) {
    createRelyingParty(req).verifyAssertion(req, function(e, result) {

        if (!result.authenticated) {
            return res.redirect("/");
        }

        var IDENTIFIER_REGEX = /^https?:\/\/steamcommunity\.com\/openid\/id\/([0-9]+)$/;
        var matches = IDENTIFIER_REGEX.exec(result.claimedIdentifier);

        if (matches === null) {
            return res.redirect("/");
        }

        req.session.user = matches[1]; // steam64
        return res.redirect("/");
    });

});

app.get("/logout", function(req, res) {
    req.session.destroy(function(err) {
        res.redirect("/");
    });
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});
<|endoftext|>


<commit_before>openerp.web.data_import = function(openerp) {
var QWeb = openerp.web.qweb;
/**
 * Safari does not deal well at all with raw JSON data being returned. As a
 * result, we're going to cheat by using a pseudo-jsonp: instead of getting
 * JSON data in the iframe, we're getting a ``script`` tag which consists of a
 * function call and the returned data (the json dump).
 *
 * The function is an auto-generated name bound to ``window``, which calls
 * back into the callback provided here.
 *
 * @param {Object} form the form element (DOM or jQuery) to use in the call
 * @param {Object} attributes jquery.form attributes object
 * @param {Function} callback function to call with the returned data
 */
function jsonp(form, attributes, callback) {
    var options = {jsonp: _.uniqueId('import_callback_')};
    window[options.jsonp] = function () {
        delete window[options.jsonp];
        callback.apply(null, arguments);
    };
    $(form).ajaxSubmit(_.extend({
        data: options
    }, attributes));
}
openerp.web.DataImport = openerp.web.Dialog.extend({
    template: 'ImportDataView',
    dialog_title: "Import Data",
    init: function(parent, dataset){
        this._super(parent, {});
    },
    start: function() {
        var self = this;
        this._super();
        this.open({
            modal: true,
            width: '70%',
            height: 'auto',
            position: 'top',
            buttons: {
                "Close": function() {
                    self.stop();
                },
                "Import File": function() {
                    self.do_import();
                }
            },
            close: function(event, ui) {
                self.stop();
            }
        });
        this.$element.find('#csvfile').change(this.on_autodetect_data);
        this.$element.find('fieldset').change(this.on_autodetect_data);
        this.$element.find('fieldset legend').click(function() {
            $(this).next().toggle();
        });
    },
    do_import: function() {
        if(!this.$element.find('#csvfile').val()) { return; }
        jsonp(this.$element.find('#import_data'), {
            url: '/web/import/import_data'
        }, this.on_import_results);
    },
    on_autodetect_data: function() {
        if(this.$element.find("#res td")){
            this.$element.find("#res td").remove();
            this.$element.find("#imported_success").css('display','none');
        }
        if(!this.$element.find('#csvfile').val()) { return; }
        jsonp(this.$element.find('#import_data'), {
            url: '/web/import/detect_data'
        }, this.on_import_results);
    },
    on_import_results: function(results) {
        this.$element.find('#result, #success').empty();
        var result_node = $("#result");
        var records = {};

        if (results['records']) {
            records = {'header': results['header'], 'sel': results['all_fields'], 'row': results['records']};
            result_node.append(QWeb.render('ImportView-result', {'records': records}));
        } else if (results['error']) {
            result_node.append(QWeb.render('ImportView-result', {'error': results['error']}));
        } else if (results['success']) {
            self.stop();
            if (this.widget_parent.widget_parent.active_view == "list") {
                this.widget_parent.reload_content();
            }
        }
        this.do_check_req_field(results['req_field']);
        this.on_change_check(results['req_field']);
        var self = this;
        this.$element.find("td #sel_field").change(function() {
            self.on_change_check(results['req_field']);
        });
    },
    on_change_check: function (req_field){
        var self = this;
        self.$element.find("#message, #msg").remove();
        var selected_flds = self.$element.find("td #sel_field option:selected");
        _.each(selected_flds, function(fld) {
            if (fld.index != 0) {
                var res = self.$element.find("td #sel_field option:selected[value='" + fld.value + "']");
                if (res.length == 1) {
                    res.parent().removeClass("duplicate_fld").addClass("select_fld");
                } else if (res.length > 1) {
                    res.parent().removeClass("select_fld").addClass("duplicate_fld");
                    res.parent().focus();
                }
            } else {
                var elem = self.$element.find("td #sel_field option:selected[value='" + fld.value + "']");
                elem.parent().removeClass("duplicate_fld").addClass("select_fld");
            }
        });
        if (self.$element.find(".duplicate_fld").length) {
            $("#result").before('
*Selected column should not be same.
');
            $(".ui-button-text:contains('Import File')").parent().attr("disabled", true);
        } else {
            self.$element.find("#msg").remove();
            $(".ui-button-text:contains('Import File')").parent().attr("disabled", false);
        }
        self.do_check_req_field(req_field);
    },
    do_check_req_field: function(req_fld) {
        if (!req_fld.length) { return; }

        this.$element.find("#message").remove();
        var sel_fields = _.map(this.$element.find("td #sel_field option:selected"), function(fld) {
            return fld['text']
        });
        var required_fields = _.filter(req_fld, function(fld) {
            return !_.contains(sel_fields, fld)
        });
        if (required_fields.length) {
            $("#result").before('
*Required Fields are not selected : ' + required_fields + '.
');
            $(".ui-button-text:contains('Import File')").parent().attr("disabled", true);
        } else {
            this.$element.find("#message").remove();
            $(".ui-button-text:contains('Import File')").parent().attr("disabled", false);
        }
    },
    stop: function() {
        $(this.$dialog).remove();
        this._super();
    }
});
};
<commit_msg>[IMP] build a sequence of buttons to initialize dialog for localization (future), simplify enabling and disabling of import button<commit_after>openerp.web.data_import = function(openerp) {
var QWeb = openerp.web.qweb;
/**
 * Safari does not deal well at all with raw JSON data being returned. As a
 * result, we're going to cheat by using a pseudo-jsonp: instead of getting
 * JSON data in the iframe, we're getting a ``script`` tag which consists of a
 * function call and the returned data (the json dump).
 *
 * The function is an auto-generated name bound to ``window``, which calls
 * back into the callback provided here.
 *
 * @param {Object} form the form element (DOM or jQuery) to use in the call
 * @param {Object} attributes jquery.form attributes object
 * @param {Function} callback function to call with the returned data
 */
function jsonp(form, attributes, callback) {
    var options = {jsonp: _.uniqueId('import_callback_')};
    window[options.jsonp] = function () {
        delete window[options.jsonp];
        callback.apply(null, arguments);
    };
    $(form).ajaxSubmit(_.extend({
        data: options
    }, attributes));
}
openerp.web.DataImport = openerp.web.Dialog.extend({
    template: 'ImportDataView',
    dialog_title: "Import Data",
    init: function(parent, dataset){
        this._super(parent, {});
    },
    start: function() {
        var self = this;
        this._super();
        this.open({
            modal: true,
            width: '70%',
            height: 'auto',
            position: 'top',
            buttons: [
                {text: "Close", click: function() { self.stop(); }},
                {text: "Import File", click: function() { self.do_import(); }, 'class': 'oe-dialog-import-button'}
            ],
            close: function(event, ui) {
                self.stop();
            }
        });
        this.toggle_import_button(false);
        this.$element.find('#csvfile').change(this.on_autodetect_data);
        this.$element.find('fieldset').change(this.on_autodetect_data);
        this.$element.find('fieldset legend').click(function() {
            $(this).next().toggle();
        });
    },
    toggle_import_button: function (newstate) {
        this.$dialog.dialog('widget')
                .find('.oe-dialog-import-button')
                .button('option', 'disabled', !newstate);
    },
    do_import: function() {
        if(!this.$element.find('#csvfile').val()) { return; }
        jsonp(this.$element.find('#import_data'), {
            url: '/web/import/import_data'
        }, this.on_import_results);
    },
    on_autodetect_data: function() {
        if(this.$element.find("#res td")){
            this.$element.find("#res td").remove();
            this.$element.find("#imported_success").css('display','none');
        }
        if(!this.$element.find('#csvfile').val()) { return; }
        jsonp(this.$element.find('#import_data'), {
            url: '/web/import/detect_data'
        }, this.on_import_results);
    },
    on_import_results: function(results) {
        this.$element.find('#result, #success').empty();
        var result_node = this.$element.find("#result");
        var records = {};

        if (results['records']) {
            records = {'header': results['header'], 'sel': results['all_fields'], 'row': results['records']};
            result_node.append(QWeb.render('ImportView-result', {'records': records}));
        } else if (results['error']) {
            result_node.append(QWeb.render('ImportView-result', {'error': results['error']}));
        } else if (results['success']) {
            self.stop();
            if (this.widget_parent.widget_parent.active_view == "list") {
                this.widget_parent.reload_content();
            }
        }
        this.do_check_req_field(results['req_field']);
        this.on_change_check(results['req_field']);
        var self = this;
        this.$element.find("td #sel_field").change(function() {
            self.on_change_check(results['req_field']);
        });
    },
    on_change_check: function (req_field){
        var self = this;
        self.$element.find("#message, #msg").remove();
        var selected_flds = self.$element.find("td #sel_field option:selected");
        _.each(selected_flds, function(fld) {
            if (fld.index != 0) {
                var res = self.$element.find("td #sel_field option:selected[value='" + fld.value + "']");
                if (res.length == 1) {
                    res.parent().removeClass("duplicate_fld").addClass("select_fld");
                } else if (res.length > 1) {
                    res.parent().removeClass("select_fld").addClass("duplicate_fld");
                    res.parent().focus();
                }
            } else {
                var elem = self.$element.find("td #sel_field option:selected[value='" + fld.value + "']");
                elem.parent().removeClass("duplicate_fld").addClass("select_fld");
            }
        });
        if (self.$element.find(".duplicate_fld").length) {
            this.$element.find("#result").before('
*Selected column should not be same.
');
            this.toggle_import_button(false);
        } else {
            self.$element.find("#msg").remove();
            this.toggle_import_button(true);
        }
        self.do_check_req_field(req_field);
    },
    do_check_req_field: function(req_fld) {
        if (!req_fld.length) { return; }

        this.$element.find("#message").remove();
        var sel_fields = _.map(this.$element.find("td #sel_field option:selected"), function(fld) {
            return fld['text']
        });
        var required_fields = _.filter(req_fld, function(fld) {
            return !_.contains(sel_fields, fld)
        });
        if (required_fields.length) {
            this.$element.find("#result").before('
*Required Fields are not selected : ' + required_fields + '.
');
            this.toggle_import_button(false);
        } else {
            this.$element.find("#message").remove();
            this.toggle_import_button(true);
        }
    },
    stop: function() {
        $(this.$dialog).remove();
        this._super();
    }
});
};
<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import React from 'react';
import { FormattedHTMLMessage, FormattedMessage, injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import withFilteredAsyncData from '../FilteredAsyncDataContainer';
import { fetchTopicFocalSetsList } from '../../../actions/topicActions';

const localMessages = {
  title: { id: 'topic.info.title', defaultMessage: 'Subtopic Details' },
  set: { id: 'topic.info.set', defaultMessage: 'Set' },
  type: { id: 'topic.info.type', defaultMessage: 'Type' },
  search: { id: 'topic.info.search', defaultMessage: 'Search Terms' },
};

const SubtopicQuerySummary = ({ focalSets, snapshot }) => (
  // the form has them grouped together, but the topic object has them separate

      {snapshot && <FormattedHTMLMessage {...localMessages.title} values={{ versionNumber: snapshot.note }} />}

          <FormattedMessage {...localMessages.set} />
          <FormattedMessage {...localMessages.type} />
          <FormattedMessage {...localMessages.search} />

        {focalSets.sort((a, b) => a.name.localeCompare(b.name)).map(fs => (

            {fs.foci && fs.foci.map(f => (

                {f.name}
                {fs.focal_sets_id}
                {f.query}

            ))}

        ))}

);

SubtopicQuerySummary.propTypes = {
  topicId: PropTypes.number.isRequired,
  snapshot: PropTypes.object,
  focalSets: PropTypes.array,
  // intl: PropTypes.object.isRequired,
};

const mapStateToProps = state => ({
  fetchStatus: state.topics.selected.focalSets.all.fetchStatus,
  focalSets: state.topics.selected.focalSets.all.list,
  timespanStoryCount: state.topics.selected.timespans.selected.story_count,
});

const fetchAsyncData = (dispatch, { topicId, filters }) => {
  dispatch(fetchTopicFocalSetsList(topicId, { ...filters, includeStoryCounts: 1 }));
};

export default
injectIntl(
  connect(mapStateToProps)(
    withFilteredAsyncData(fetchAsyncData)(
      SubtopicQuerySummary
    )
  )
);
<commit_msg>#1559<commit_after>import PropTypes from 'prop-types';
import React from 'react';
import { FormattedHTMLMessage, FormattedMessage, injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import withFilteredAsyncData from '../FilteredAsyncDataContainer';
import { fetchTopicFocalSetsList } from '../../../actions/topicActions';

const localMessages = {
  title: { id: 'topic.info.title', defaultMessage: 'Subtopic Details' },
  set: { id: 'topic.info.set', defaultMessage: 'Set' },
  type: { id: 'topic.info.type', defaultMessage: 'Type' },
  search: { id: 'topic.info.search', defaultMessage: 'Search Terms' },
};

const SubtopicQuerySummary = ({ focalSets, snapshot }) => (
  // the form has them grouped together, but the topic object has them separate

      {snapshot && <FormattedHTMLMessage {...localMessages.title} values={{ versionNumber: snapshot.note }} />}

          <FormattedMessage {...localMessages.set} />
          <FormattedMessage {...localMessages.type} />
          <FormattedMessage {...localMessages.search} />

        {focalSets.sort((a, b) => a.name.localeCompare(b.name)).map(fs => (

            {fs.foci && fs.foci.map(f => (

                {fs.name}
                {f.name}
                {f.query}

            ))}

        ))}

);

SubtopicQuerySummary.propTypes = {
  topicId: PropTypes.number.isRequired,
  snapshot: PropTypes.object,
  focalSets: PropTypes.array,
  // intl: PropTypes.object.isRequired,
};

const mapStateToProps = state => ({
  fetchStatus: state.topics.selected.focalSets.all.fetchStatus,
  focalSets: state.topics.selected.focalSets.all.list,
  timespanStoryCount: state.topics.selected.timespans.selected.story_count,
});

const fetchAsyncData = (dispatch, { topicId, filters }) => {
  dispatch(fetchTopicFocalSetsList(topicId, { ...filters, includeStoryCounts: 1 }));
};

export default
injectIntl(
  connect(mapStateToProps)(
    withFilteredAsyncData(fetchAsyncData)(
      SubtopicQuerySummary
    )
  )
);
<|endoftext|>


<commit_before>// Install JSPrintSetup
function installjsPrintSetup() {
    //if (confirm("You don't have printer plugin.\nDo you want to install the Printer Plugin now?")) {
    if (confirm("No tienes instalado el plugin de la impresora.\nQuieres instalarlo ahora?")) {
        var xpi = new Object();
        xpi['jsprintsetup'] = '/bundles/inodataflora/downloads/jsprintsetup-0.9.2.xpi';
        InstallTrigger.install(xpi);
    }
}

function setupGlobalOptions(){
  //check if jsPrintSetup is installed
  if (typeof(jsPrintSetup) == 'undefined') {
          installjsPrintSetup();
  } else {
    // set page orientation.
    jsPrintSetup.setOption('orientation', jsPrintSetup.kPortraitOrientation);
    //jsPrintSetup.setOption('orientation', jsPrintSetup.kLandscapeOrientation);

    // set margins (in millimeters, firefox defaults 12.7mm).
    jsPrintSetup.setOption('marginTop', 0);
    jsPrintSetup.setOption('marginBottom', 0);
    jsPrintSetup.setOption('marginLeft', 0);
    jsPrintSetup.setOption('marginRight', 0);

    // set page header
    jsPrintSetup.setOption('headerStrLeft', '');
    jsPrintSetup.setOption('headerStrCenter', '');
    jsPrintSetup.setOption('headerStrRight', '');
    // set empty page footer
    jsPrintSetup.setOption('footerStrLeft', '');
    jsPrintSetup.setOption('footerStrCenter', '');
    jsPrintSetup.setOption('footerStrRight', '');

    definePaperSizes();

    // clears user preferences always silent print value
    // to enable using 'printSilent' option
    jsPrintSetup.clearSilentPrint();
    // Suppress print dialog (for this context only)
    jsPrintSetup.setOption('printSilent', 1);

  }
}

//This function was useless handling medium letter size.
//Define paper size
//39 : {PD:39, PN: 'na_fanfold-us',PWG:'na_fanfold-us_11x14.875in',Name: 'US Std Fanfold', W: 11, H: 14.875, M: kPaperSizeInches}
function definePaperSizes(){
  //note
  jsPrintSetup.definePaperSize(50, 50, 'na_letter', 'na_letter_8.5x11in', 'US Letter', 8.5, 5.5, jsPrintSetup.kPaperSizeInches);
  //card
  jsPrintSetup.definePaperSize(51, 51, 'na_letter', 'na_letter_8.5x11in', 'US Letter', 4.7, 5.5, jsPrintSetup.kPaperSizeInches);
}

// Do Print
// When print is submitted it is executed asynchronous and
// script flow continues after print independently of completetion of print process!
//  jsPrintSetup.print();
var print_delay = 3000;

function printCard(){
  setupGlobalOptions();
  jsPrintSetup.setPaperSizeData(51);
  jsPrintSetup.setPrinter('PostScript/default');
  //alert(jsPrintSetup.getPaperMeasure());
  setTimeout('jsPrintSetup.print()', print_delay);
}

function printNote(){
  setupGlobalOptions();
  jsPrintSetup.setPaperSizeData(50);
  jsPrintSetup.setPrinter('PostScript/default');
  //alert(jsPrintSetup.getPaperMeasure());
  //add a delay to render correctly all elements fetched via AJAX
  setTimeout('jsPrintSetup.print()', print_delay);
}

function printInvoice(){
  setupGlobalOptions();
  jsPrintSetup.setPaperSizeData(1);
  jsPrintSetup.setPrinter('PostScript/default');
  //alert(jsPrintSetup.getPaperMeasure());
  //add a delay to render correctly all elements fetched via AJAX
  setTimeout('jsPrintSetup.print()', print_delay);
}

//FIXME: Revisar la impresion de esta lista y seleccionar impresora.
function printDistributionList(){
	setupGlobalOptions();
	setTimeout('jsPrintSetup.print()', 3000);
}<commit_msg>actualiza los cambios de la impresora<commit_after>// Install JSPrintSetup
function installjsPrintSetup() {
    //if (confirm("You don't have printer plugin.\nDo you want to install the Printer Plugin now?")) {
    if (confirm("No tienes instalado el plugin de la impresora.\nQuieres instalarlo ahora?")) {
        var xpi = new Object();
        xpi['jsprintsetup'] = '/bundles/inodataflora/downloads/jsprintsetup-0.9.2.xpi';
        InstallTrigger.install(xpi);
    }
}

//This function was useless handling medium letter size.
//Define paper size
//39 : {PD:39, PN: 'na_fanfold-us',PWG:'na_fanfold-us_11x14.875in',Name: 'US Std Fanfold', W: 11, H: 14.875, M: kPaperSizeInches}
function definePaperSizes(){
  //note
  jsPrintSetup.definePaperSize(50, 50, 'na_letter', 'na_letter_8.5x11in', 'US Letter', 8.5, 5.5, jsPrintSetup.kPaperSizeInches);
  //card
  jsPrintSetup.definePaperSize(51, 51, 'na_letter', 'na_letter_8.5x11in', 'US Letter', 4.7, 5.5, jsPrintSetup.kPaperSizeInches);
}

function setupGlobalOptions(){
  //check if jsPrintSetup is installed
  if (typeof(jsPrintSetup) == 'undefined') {
          installjsPrintSetup();
  } else {
    // set page orientation.
    jsPrintSetup.setOption('orientation', jsPrintSetup.kPortraitOrientation);
    //jsPrintSetup.setOption('orientation', jsPrintSetup.kLandscapeOrientation);

    // set margins (in millimeters, firefox defaults 12.7mm).
    jsPrintSetup.setOption('marginTop', 0);
    jsPrintSetup.setOption('marginBottom', 0);
    jsPrintSetup.setOption('marginLeft', 0);
    jsPrintSetup.setOption('marginRight', 0);

    // set page header
    jsPrintSetup.setOption('headerStrLeft', '');
    jsPrintSetup.setOption('headerStrCenter', '');
    jsPrintSetup.setOption('headerStrRight', '');
    // set empty page footer
    jsPrintSetup.setOption('footerStrLeft', '');
    jsPrintSetup.setOption('footerStrCenter', '');
    jsPrintSetup.setOption('footerStrRight', '');

    //definePaperSizes();

    // clears user preferences always silent print value
    // to enable using 'printSilent' option
    jsPrintSetup.clearSilentPrint();
    // Suppress print dialog (for this context only)
    jsPrintSetup.setOption('printSilent', 1);

  }
}

// Do Print
// When print is submitted it is executed asynchronous and
// script flow continues after print independently of completetion of print process!
//  jsPrintSetup.print();
var print_delay = 3000;

function printCard(){
  setupGlobalOptions();
  jsPrintSetup.definePaperSize(1, 1, 'na_letter', 'na_letter_8.5x11in', 'US Letter', 4.7, 5.5, jsPrintSetup.kPaperSizeInches);
  jsPrintSetup.setPaperSizeData(1);
  jsPrintSetup.setPrinter('\\\\flora\\Tarjetas');
  //alert(jsPrintSetup.getPaperMeasure());
  setTimeout('jsPrintSetup.print()', print_delay);
}

function printNote(){
  setupGlobalOptions();
  //jsPrintSetup.setPaperSizeData(1);
  //jsPrintSetup.setOption ("paperWidth", 216);
  //jsPrintSetup.setOption ("paperHeight", 140);
  jsPrintSetup.definePaperSize(100, 100, 'na_letter', 'na_letter_8.5x11in', 'Notas', 8.5, 5.5, jsPrintSetup.kPaperSizeInches);
  jsPrintSetup.setPaperSizeData(100);
  //alert(jsPrintSetup.getPaperSizeList());
  jsPrintSetup.setPrinter('\\\\flora\\Notas');
  //alert(jsPrintSetup.getPaperMeasure());
  //add a delay to render correctly all elements fetched via AJAX
  setTimeout('jsPrintSetup.print()', print_delay);
}

function printInvoice(){
  setupGlobalOptions();
  jsPrintSetup.definePaperSize(1, 1, 'na_letter', 'na_letter_8.5x11in', 'US Letter', 8.5, 11, jsPrintSetup.kPaperSizeInches);
  jsPrintSetup.setPaperSizeData(1);
  jsPrintSetup.setPrinter('Facturas');
  //alert(jsPrintSetup.getPaperMeasure());
  //add a delay to render correctly all elements fetched via AJAX
  setTimeout('jsPrintSetup.print()', print_delay);
}

//FIXME: Revisar la impresion de esta lista y seleccionar impresora.
function printDistributionList(){
  setupGlobalOptions();
  setTimeout('jsPrintSetup.print()', 3000);
}<|endoftext|>


<commit_before>$(document).ready(function () {
    var $fix = $('#qunit-fixture');

    var instance;
    var baseSetup = function () {
        instance = openerp.testing.instanceFor('list_editable');

        openerp.testing.loadTemplate(instance);

        openerp.testing.mockifyRPC(instance);
    };

    /**
     *
     * @param {String} name
     * @param {Object} [attrs]
     * @param {String} [attrs.type="char"]
     * @param {Boolean} [attrs.required]
     * @param {Boolean} [attrs.invisible]
     * @param {Boolean} [attrs.readonly]
     * @return {Object}
     */
    function field(name, attrs) {
        attrs = attrs || {};
        attrs.name = name;
        return _.defaults(attrs, {
            type: 'char'
        });
    }

    /**
     * @param {Array} fields
     * @return {Object}
     */
    function makeFormView(fields) {
        var fobj = {};
        _(fields).each(function (field) {
            fobj[field.name] = {
                type: field.type,
                string: field.string
            };
        });
        var children = _(fields).map(function (field) {
            return {
                tag: 'field',
                attrs: {
                    name: field.name,
                    modifiers: JSON.stringify({
                        required: field.required,
                        invisible: field.invisible,
                        readonly: field.readonly
                    })
                }
            }
        });
        return {
            arch: {
                tag: 'form',
                attrs: {
                    version: '7.0',
                    'class': 'oe_form_container'
                },
                children: children
            },
            fields: fobj
        };
    }

    module('editor', {
        setup: baseSetup
    });
    asyncTest('base-state', 2, function () {
        var e = new instance.web.list.Editor({
            dataset: {ids: []},
            edition_view: function () {
                return makeFormView();
            }
        });
        e.appendTo($fix)
            .always(start)
            .fail(function (error) { ok(false, error && error.message); })
            .done(function () {
                ok(!e.is_editing(), "should not be editing");
                ok(e.form instanceof instance.web.FormView,
                   "should use default form type");
            });
    });
    asyncTest('toggle-edition-save', 4, function () {
        instance.session.responses['/web/dataset/call_kw:create'] = function () {
            return { result: 42 };
        };
        instance.session.responses['/web/dataset/call_kw:read'] = function () {
            return { result: [{
                id: 42,
                a: false,
                b: false,
                c: false
            }]};
        };
        var e = new instance.web.list.Editor({
            dataset: new instance.web.DataSetSearch(),
            prepends_on_create: function () { return false; },
            edition_view: function () {
                return makeFormView([ field('a'), field('b'), field('c') ]);
            }
        });
        var counter = 0;
        e.appendTo($fix)
            .pipe(function () {
                return e.edit({}, function () {
                    ++counter;
                });
            })
            .pipe(function (form) {
                ok(e.is_editing(), "should be editing");
                equal(counter, 3, "should have configured all fields");
                return e.save();
            })
            .always(start)
            .fail(function (error) { ok(false, error && error.message); })
            .done(function (record) {
                ok(!e.is_editing(), "should have stopped editing");
                equal(record.id, 42, "should have newly created id");
            })
    });
    asyncTest('toggle-edition-cancel', 2, function () {
        instance.session.responses['/web/dataset/call_kw:create'] = function () {
            return { result: 42 };
        };
        var e = new instance.web.list.Editor({
            dataset: new instance.web.DataSetSearch(),
            prepends_on_create: function () { return false; },
            edition_view: function () {
                return makeFormView([ field('a'), field('b'), field('c') ]);
            }
        });
        var counter = 0;
        e.appendTo($fix)
            .pipe(function () {
                return e.edit({}, function () {
                    ++counter;
                });
            })
            .pipe(function (form) {
                return e.cancel();
            })
            .always(start)
            .fail(function (error) { ok(false, error && error.message); })
            .done(function (record) {
                ok(!e.is_editing(), "should have stopped editing");
                ok(!record.id, "should have no id");
            })
    });
    asyncTest('toggle-save-required', 2, function () {
        instance.session.responses['/web/dataset/call_kw:create'] = function () {
            return { result: 42 };
        };
        var e = new instance.web.list.Editor({
            do_warn: function () {
                warnings++;
            },
            dataset: new instance.web.DataSetSearch(),
            prepends_on_create: function () { return false; },
            edition_view: function () {
                return makeFormView([
                    field('a', {required: true}), field('b'), field('c') ]);
            }
        });
        var counter = 0;
        var warnings = 0;
        e.appendTo($fix)
            .pipe(function () {
                return e.edit({}, function () {
                    ++counter;
                });
            })
            .pipe(function (form) {
                return e.save();
            })
            .always(start)
            .done(function () { ok(false, "cancel should not succeed"); })
            .fail(function () {
                equal(warnings, 1, "should have been warned");
                ok(e.is_editing(), "should have kept editing");
            })
    });

    module('list-edition', {
        setup: function () {
            baseSetup();

            var records = {};
            _.extend(instance.session.responses, {
                '/web/view/load': function () {
                    return {result: {
                        type: 'tree',
                        fields: {
                            a: {type: 'char', string: "A"},
                            b: {type: 'char', string: "B"},
                            c: {type: 'char', string: "C"}
                        },
                        arch: {
                            tag: 'tree',
                            attrs: {},
                            children: [
                                {tag: 'field', attrs: {name: 'a'}},
                                {tag: 'field', attrs: {name: 'b'}},
                                {tag: 'field', attrs: {name: 'c'}}
                            ]
                        }
                    }};
                },
                '/web/dataset/call_kw:create': function (params) {
                    records[42] = _.extend({}, params.params.args[0]);
                    return {result: 42};
                },
                '/web/dataset/call_kw:read': function (params) {
                    var id = params.params.args[0][0];
                    if (id in records) {
                        return {result: [records[id]]};
                    }
                    return {result: []};
                }
            })
        }
    });
    asyncTest('newrecord', 6, function () {
        var got_defaults = false;
        instance.session.responses['/web/dataset/call_kw:default_get'] = function (params) {
            var fields = params.params.args[0];
            deepEqual(
                fields, ['a', 'b', 'c'],
                "should ask defaults for all fields");
            got_defaults = true;
            return {result: {
                a: "qux",
                b: "quux"
            }};
        };

        var ds = new instance.web.DataSetStatic(null, 'demo', null, [1]);
        var l = new instance.web.ListView({}, ds, false, {editable: 'top'});

        l.appendTo($fix)
            .pipe(l.proxy('reload_content'))
            .pipe(function () {
                return l.start_edition();
            })
            .always(start)
            .pipe(function () {
                ok(got_defaults, "should have fetched default values for form");
                return l.save_edition();
            })
            .pipe(function (result) {
                ok(result.created, "should yield newly created record");
                equal(result.record.get('a'), "qux",
                      "should have used default values");
                equal(result.record.get('b'), "quux",
                      "should have used default values");
                ok(!result.record.get('c'),
                    "should have no value if there was no default");
            })
            .fail(function (e) { ok(false, e && e.message || e); });
    });

    module('list-edition-events', {
        setup: function () {
            baseSetup();
            _.extend(instance.session.responses, {
                '/web/view/load': function () {
                    return {result: {
                        type: 'tree',
                        fields: {
                            a: {type: 'char', string: "A"},
                            b: {type: 'char', string: "B"},
                            c: {type: 'char', string: "C"}
                        },
                        arch: {
                            tag: 'tree',
                            attrs: {},
                            children: [
                                {tag: 'field', attrs: {name: 'a'}},
                                {tag: 'field', attrs: {name: 'b'}},
                                {tag: 'field', attrs: {name: 'c'}}
                            ]
                        }
                    }};
                },
                '/web/dataset/call_kw:read': function (params) {
                    return {result: [{
                        id: 1,
                        a: 'foo',
                        b: 'bar',
                        c: 'baz'
                    }]};
                }
            });
        }
    });
    asyncTest('edition events', 4, function () {
        var ds = new instance.web.DataSetStatic(null, 'demo', null, [1]);
        var o = {
            counter: 0,
            onEvent: function (e) { this.counter++; }
        };
        var l = new instance.web.ListView({}, ds, false, {editable: 'top'});
        l.on('edit:before edit:after', o, o.onEvent);
        l.appendTo($fix)
            .pipe(l.proxy('reload_content'))
            .always(start)
            .pipe(function () {
                ok(l.options.editable, "should be editable");
                equal(o.counter, 0, "should have seen no event yet");
                return l.start_edition(l.records.get(1));
            })
            .pipe(function () {
                ok(l.editor.is_editing(), "should be editing");
                equal(o.counter, 2, "should have seen two edition events");
            })
            .fail(function (e) { ok(false, e && e.message); });
    });

    asyncTest('edition events: cancelling', 3, function () {
        var edit_after = false;
        var ds = new instance.web.DataSetStatic(null, 'demo', null, [1]);
        var l = new instance.web.ListView({}, ds, false, {editable: 'top'});
        l.on('edit:before', {}, function (e) {
            e.cancel = true;
        });
        l.on('edit:after', {}, function () {
            edit_after = true;
        });
        l.appendTo($fix)
            .pipe(l.proxy('reload_content'))
            .always(start)
            .pipe(function () {
                ok(l.options.editable, "should be editable");
                return l.start_edition();
            })
            // cancelling an event rejects the deferred
            .pipe($.Deferred().reject(), function () {
                ok(!l.editor.is_editing(), "should not be editing");
                ok(!edit_after, "should not have fired the edit:after event");
                return $.when();
            })
            .fail(function (e) { ok(false, e && e.message || e); });
    });
});
<commit_msg>[IMP] port list-edition tests to new framework<commit_after>openerp.testing.section('editor', {
    dependencies: ['web.list_editable'],
    rpc: 'mock',
    templates: true,
    setup: function (instance, $s, mock) {
        mock('test.model:create', function () {
            return 42;
        });
    }
}, function (test) {
    /**
     *
     * @param {String} name
     * @param {Object} [attrs]
     * @param {String} [attrs.type="char"]
     * @param {Boolean} [attrs.required]
     * @param {Boolean} [attrs.invisible]
     * @param {Boolean} [attrs.readonly]
     * @return {Object}
     */
    function field(name, attrs) {
        attrs = attrs || {};
        attrs.name = name;
        return _.defaults(attrs, {
            type: 'char'
        });
    }

    /**
     * @param {Array} [fields]
     * @return {Object}
     */
    function makeFormView(fields) {
        var fobj = {};
        _(fields).each(function (field) {
            fobj[field.name] = {
                type: field.type,
                string: field.string
            };
        });
        var children = _(fields).map(function (field) {
            return {
                tag: 'field',
                attrs: {
                    name: field.name,
                    modifiers: JSON.stringify({
                        required: field.required,
                        invisible: field.invisible,
                        readonly: field.readonly
                    })
                }
            }
        });
        return {
            arch: {
                tag: 'form',
                attrs: {
                    version: '7.0',
                    'class': 'oe_form_container'
                },
                children: children
            },
            fields: fobj
        };
    }

    test('base-state', {asserts: 2}, function (instance, $fix) {
        var e = new instance.web.list.Editor({
            dataset: {ids: []},
            edition_view: function () {
                return makeFormView();
            }
        });
        return e.appendTo($fix)
            .done(function () {
                ok(!e.is_editing(), "should not be editing");
                ok(e.form instanceof instance.web.FormView,
                   "should use default form type");
            });
    });
    test('toggle-edition-save', {
        asserts: 4,
        setup: function (instance, $s, mock) {
            mock('test.model:read', function () {
                return [{id: 42, a: false, b: false, c: false}];
            });
        }
    }, function (instance, $fix) {
        var e = new instance.web.list.Editor({
            dataset: new instance.web.DataSetSearch(null, 'test.model'),
            prepends_on_create: function () { return false; },
            edition_view: function () {
                return makeFormView([ field('a'), field('b'), field('c') ]);
            }
        });
        var counter = 0;
        return e.appendTo($fix)
            .pipe(function () {
                return e.edit({}, function () {
                    ++counter;
                });
            })
            .pipe(function (form) {
                ok(e.is_editing(), "should be editing");
                equal(counter, 3, "should have configured all fields");
                return e.save();
            })
            .done(function (record) {
                ok(!e.is_editing(), "should have stopped editing");
                equal(record.id, 42, "should have newly created id");
            })
    });
    test('toggle-edition-cancel', { asserts: 2 }, function (instance, $fix) {
        var e = new instance.web.list.Editor({
            dataset: new instance.web.DataSetSearch(null, 'test.model'),
            prepends_on_create: function () { return false; },
            edition_view: function () {
                return makeFormView([ field('a'), field('b'), field('c') ]);
            }
        });
        var counter = 0;
        return e.appendTo($fix)
            .pipe(function () {
                return e.edit({}, function () {
                    ++counter;
                });
            })
            .pipe(function (form) {
                return e.cancel();
            })
            .done(function (record) {
                ok(!e.is_editing(), "should have stopped editing");
                ok(!record.id, "should have no id");
            })
    });
    test('toggle-save-required', {
        asserts: 2,
        fail_on_rejection: false
    }, function (instance, $fix) {
        var e = new instance.web.list.Editor({
            do_warn: function () {
                warnings++;
            },
            dataset: new instance.web.DataSetSearch(null, 'test.model'),
            prepends_on_create: function () { return false; },
            edition_view: function () {
                return makeFormView([
                    field('a', {required: true}), field('b'), field('c') ]);
            }
        });
        var counter = 0;
        var warnings = 0;
        return e.appendTo($fix)
            .pipe(function () {
                return e.edit({}, function () {
                    ++counter;
                });
            })
            .pipe(function (form) {
                return e.save();
            })
            .done(function () { ok(false, "cancel should not succeed"); })
            .fail(function () {
                equal(warnings, 1, "should have been warned");
                ok(e.is_editing(), "should have kept editing");
            });
    });
});
openerp.testing.section('list.edition', {
    dependencies: ['web.list_editable'],
    rpc: 'mock',
    templates: true,
    setup: function (instance, $s, mock) {
        var records = {};
        mock('demo:create', function (args) {
            records[42] = _.extend({}, args[0]);
            return 42;
        });
        mock('demo:read', function (args) {
            var id = args[0][0];
            if (id in records) {
                return [records[id]];
            }
            return [];
        });
        mock('/web/view/load', function () {
            return {
                type: 'tree',
                fields: {
                    a: {type: 'char', string: "A"},
                    b: {type: 'char', string: "B"},
                    c: {type: 'char', string: "C"}
                },
                arch: {
                    tag: 'tree',
                    attrs: {},
                    children: [
                        {tag: 'field', attrs: {name: 'a'}},
                        {tag: 'field', attrs: {name: 'b'}},
                        {tag: 'field', attrs: {name: 'c'}}
                    ]
                }
            };
        });
    }
}, function (test) {
    test('newrecord', {asserts: 6}, function (instance, $fix, mock) {
        var got_defaults = false;
        mock('demo:default_get', function (args) {
            var fields = args[0];
            deepEqual(
                fields, ['a', 'b', 'c'],
                "should ask defaults for all fields");
            got_defaults = true;
            return { a: "qux", b: "quux" };
        });

        var ds = new instance.web.DataSetStatic(null, 'demo', null, [1]);
        var l = new instance.web.ListView({}, ds, false, {editable: 'top'});

        return l.appendTo($fix)
            .pipe(l.proxy('reload_content'))
            .pipe(function () {
                return l.start_edition();
            })
            .pipe(function () {
                ok(got_defaults, "should have fetched default values for form");

                return l.save_edition();
            })
            .pipe(function (result) {
                ok(result.created, "should yield newly created record");
                equal(result.record.get('a'), "qux",
                      "should have used default values");
                equal(result.record.get('b'), "quux",
                      "should have used default values");
                ok(!result.record.get('c'),
                    "should have no value if there was no default");
            });
    });
});
openerp.testing.section('list.edition.events', {
    dependencies: ['web.list_editable'],
    rpc: 'mock',
    templates: true,
    setup: function (instance, $s, mock) {
        mock('demo:read', function () {
            return [{ id: 1, a: 'foo', b: 'bar', c: 'baz' }];
        });
        mock('/web/view/load', function () {
            return {
                type: 'tree',
                fields: {
                    a: {type: 'char', string: "A"},
                    b: {type: 'char', string: "B"},
                    c: {type: 'char', string: "C"}
                },
                arch: {
                    tag: 'tree',
                    attrs: {},
                    children: [
                        {tag: 'field', attrs: {name: 'a'}},
                        {tag: 'field', attrs: {name: 'b'}},
                        {tag: 'field', attrs: {name: 'c'}}
                    ]
                }
            };
        });
    }
}, function (test) {
    test('edition events', {asserts: 4}, function (instance, $fix) {
        var ds = new instance.web.DataSetStatic(null, 'demo', null, [1]);
        var o = {
            counter: 0,
            onEvent: function (e) { this.counter++; }
        };
        var l = new instance.web.ListView({}, ds, false, {editable: 'top'});
        l.on('edit:before edit:after', o, o.onEvent);
        return l.appendTo($fix)
            .pipe(l.proxy('reload_content'))
            .pipe(function () {
                ok(l.options.editable, "should be editable");
                equal(o.counter, 0, "should have seen no event yet");
                return l.start_edition(l.records.get(1));
            })
            .pipe(function () {
                ok(l.editor.is_editing(), "should be editing");
                equal(o.counter, 2, "should have seen two edition events");
            });
    });

    test('edition events: cancelling', {asserts: 3}, function (instance, $fix) {
        var edit_after = false;
        var ds = new instance.web.DataSetStatic(null, 'demo', null, [1]);
        var l = new instance.web.ListView({}, ds, false, {editable: 'top'});
        l.on('edit:before', {}, function (e) {
            e.cancel = true;
        });
        l.on('edit:after', {}, function () {
            edit_after = true;
        });
        return l.appendTo($fix)
            .pipe(l.proxy('reload_content'))
            .pipe(function () {
                ok(l.options.editable, "should be editable");
                return l.start_edition();
            })
            // cancelling an event rejects the deferred
            .pipe($.Deferred().reject(), function () {
                ok(!l.editor.is_editing(), "should not be editing");
                ok(!edit_after, "should not have fired the edit:after event");
                return $.when();
            });
    });
});
<|endoftext|>