<commit_before>/**
    @arg {string} name - form state will appear in this.state[name]
    @arg {object} instance - `this` for the component
    @arg {array} fields - ['username', 'save', ...]
    @arg {object} initialValues required for checkboxes {save: false, ...}
    @arg {function} validation - values => ({ username: ! values.username ? 'Required' : null, ... })
*/
export default function reactForm({
    name,
    instance,
    fields,
    initialValues,
    validation = () => {},
}) {
    if (typeof instance !== 'object')
        throw new TypeError('instance is a required object');
    if (!Array.isArray(fields))
        throw new TypeError('fields is a required array');
    if (typeof initialValues !== 'object')
        throw new TypeError('initialValues is a required object');

    // Give API users access to this.props, this.state, this.etc..
    validation = validation.bind(instance);

    const formState = (instance.state = instance.state || {});
    formState[name] = {
        // validate: () => setFormState(instance, fields, validation),
        handleSubmit: submitCallback => event => {
            event.preventDefault();
            const { valid } = setFormState(name, instance, fields, validation);
            if (!valid) return;
            const data = getData(fields, instance.state);
            let formValid = true;
            const fs = instance.state[name] || {};
            fs.submitting = true;

            // User can call this function upon successful submission
            const updateInitialValues = () => {
                setInitialValuesFromForm(name, instance, fields, initialValues);
                formState[name].resetForm();
            };

            instance.setState({ [name]: fs }, () => {
                // TODO, support promise ret
                const ret =
                    submitCallback({ data, event, updateInitialValues }) || {};
                // Look for field level errors
                for (const fieldName of Object.keys(ret)) {
                    const error = ret[fieldName];
                    if (!error) continue;
                    const value = instance.state[fieldName] || {};
                    value.error = error;
                    value.touched = true;
                    if (error) formValid = false;
                    instance.setState({ [fieldName]: value });
                }
                fs.submitting = false;
                fs.valid = formValid;
                instance.setState({ [name]: fs });
            });
        },
        resetForm: () => {
            for (const field of fields) {
                const fieldName = n(field);
                const f = instance.state[fieldName];
                const def = initialValues[fieldName];
                f.props.onChange(def);
            }
        },
        clearForm: () => {
            for (const field of fields) {
                const fieldName = n(field);
                const f = instance.state[fieldName];
                f.props.onChange();
            }
        },
    };

    for (const field of fields) {
        const fieldName = n(field);
        const fieldType = t(field);

        const fs = (formState[fieldName] = {
            value: null,
            error: null,
            touched: false,
        });

        // Caution: fs.props is expanded <input {...fieldName.props} />, so only add valid props for the component
        fs.props = { name: fieldName };

        {
            const initialValue = initialValues[fieldName];
            if (fieldType === 'checked') {
                fs.value = toString(initialValue);
                fs.props.checked = toBoolean(initialValue);
            } else if (fieldType === 'selected') {
                fs.props.selected = toString(initialValue);
                fs.value = fs.props.selected;
            } else {
                fs.props.value = toString(initialValue);
                fs.value = fs.props.value;
            }
        }

        fs.props.onChange = e => {
            const value = e && e.target ? e.target.value : e; // API may pass value directly
            const v = { ...(instance.state[fieldName] || {}) };
            const initialValue = initialValues[fieldName];

            if (fieldType === 'checked') {
                v.touched = toString(value) !== toString(initialValue);
                v.value = v.props.checked = toBoolean(value);
                v.value = value;
            } else if (fieldType === 'selected') {
                v.touched = toString(value) !== toString(initialValue);
                v.value = v.props.selected = toString(value);
            } else {
                v.touched = toString(value) !== toString(initialValue);
                v.value = v.props.value = toString(value);
            }

            instance.setState({ [fieldName]: v }, () => {
                setFormState(name, instance, fields, validation);
            });
        };

        fs.props.onBlur = () => {
            // Some errors are better shown only after blur === true
            const v = { ...(instance.state[fieldName] || {}) };
            v.blur = true;
            instance.setState({ [fieldName]: v });
        };
    }
}

function setFormState(name, instance, fields, validation) {
    let formValid = true;
    let formTouched = false;
    const v = validation(getData(fields, instance.state));
    for (const field of fields) {
        const fieldName = n(field);
        const validate = v[fieldName];
        const error = validate ? validate : null;
        const value = { ...(instance.state[fieldName] || {}) };
        value.error = error;
        formTouched = formTouched || value.touched;
        if (error) formValid = false;
        instance.setState({ [fieldName]: value });
    }
    const fs = { ...(instance.state[name] || {}) };
    fs.valid = formValid;
    fs.touched = formTouched;
    instance.setState({ [name]: fs });
    return fs;
}

function setInitialValuesFromForm(name, instance, fields, initialValues) {
    const data = getData(fields, instance.state);
    for (const field of fields) {
        const fieldName = n(field);
        initialValues[fieldName] = data[fieldName];
    }
}

function getData(fields, state) {
    const data = {};
    for (const field of fields) {
        const fieldName = n(field);
        data[fieldName] = state[fieldName].value;
    }
    return data;
}

/*
    @arg {string} field - field:type

        type = checked (for checkbox or radio)
        type = selected (for seelct option)
        type = string

    @return {string} type
*/
function t(field) {
    const [, type = 'string'] = field.split(':');
    return type;
}

/**
    @return {string} name
*/
function n(field) {
    const [name] = field.split(':');
    return name;
}

const hasValue = v =>
    v == null
        ? false
        : (typeof v === 'string' ? v.trim() : v) === '' ? false : true;
const toString = v => (hasValue(v) ? v : '');
const toBoolean = v => (hasValue(v) ? JSON.parse(v) : '');
<commit_msg>Add debounce for onChange validatio #2282n<commit_after>/**
    @arg {string} name - form state will appear in this.state[name]
    @arg {object} instance - `this` for the component
    @arg {array} fields - ['username', 'save', ...]
    @arg {object} initialValues required for checkboxes {save: false, ...}
    @arg {function} validation - values => ({ username: ! values.username ? 'Required' : null, ... })
*/
const USER_INPUT_DEBOUNCE_MS = 400;

export default function reactForm({
    name,
    instance,
    fields,
    initialValues,
    validation = () => {},
}) {
    let debounce = { timeout: null };
    if (typeof instance !== 'object')
        throw new TypeError('instance is a required object');
    if (!Array.isArray(fields))
        throw new TypeError('fields is a required array');
    if (typeof initialValues !== 'object')
        throw new TypeError('initialValues is a required object');

    // Give API users access to this.props, this.state, this.etc..
    validation = validation.bind(instance);

    const formState = (instance.state = instance.state || {});
    formState[name] = {
        // validate: () => setFormState(instance, fields, validation),
        handleSubmit: submitCallback => event => {
            event.preventDefault();
            const { valid } = setFormState(name, instance, fields, validation);
            if (!valid) return;
            const data = getData(fields, instance.state);
            let formValid = true;
            const fs = instance.state[name] || {};
            fs.submitting = true;

            // User can call this function upon successful submission
            const updateInitialValues = () => {
                setInitialValuesFromForm(name, instance, fields, initialValues);
                formState[name].resetForm();
            };

            instance.setState({ [name]: fs }, () => {
                // TODO, support promise ret
                const ret =
                    submitCallback({ data, event, updateInitialValues }) || {};
                // Look for field level errors
                for (const fieldName of Object.keys(ret)) {
                    const error = ret[fieldName];
                    if (!error) continue;
                    const value = instance.state[fieldName] || {};
                    value.error = error;
                    value.touched = true;
                    if (error) formValid = false;
                    instance.setState({ [fieldName]: value });
                }
                fs.submitting = false;
                fs.valid = formValid;
                instance.setState({ [name]: fs });
            });
        },
        resetForm: () => {
            for (const field of fields) {
                const fieldName = n(field);
                const f = instance.state[fieldName];
                const def = initialValues[fieldName];
                f.props.onChange(def);
            }
        },
        clearForm: () => {
            for (const field of fields) {
                const fieldName = n(field);
                const f = instance.state[fieldName];
                f.props.onChange();
            }
        },
    };

    for (const field of fields) {
        const fieldName = n(field);
        const fieldType = t(field);

        const fs = (formState[fieldName] = {
            value: null,
            error: null,
            touched: false,
        });

        // Caution: fs.props is expanded <input {...fieldName.props} />, so only add valid props for the component
        fs.props = { name: fieldName };

        {
            const initialValue = initialValues[fieldName];
            if (fieldType === 'checked') {
                fs.value = toString(initialValue);
                fs.props.checked = toBoolean(initialValue);
            } else if (fieldType === 'selected') {
                fs.props.selected = toString(initialValue);
                fs.value = fs.props.selected;
            } else {
                fs.props.value = toString(initialValue);
                fs.value = fs.props.value;
            }
        }

        fs.props.onChange = e => {
            const value = e && e.target ? e.target.value : e; // API may pass value directly
            const v = { ...(instance.state[fieldName] || {}) };
            const initialValue = initialValues[fieldName];

            if (fieldType === 'checked') {
                v.touched = toString(value) !== toString(initialValue);
                v.value = v.props.checked = toBoolean(value);
                v.value = value;
            } else if (fieldType === 'selected') {
                v.touched = toString(value) !== toString(initialValue);
                v.value = v.props.selected = toString(value);
            } else {
                v.touched = toString(value) !== toString(initialValue);
                v.value = v.props.value = toString(value);
            }

            instance.setState({ [fieldName]: v }, () => {
                setFormStateDebounce(
                    name,
                    instance,
                    fields,
                    validation,
                    debounce
                );
            });
        };

        fs.props.onBlur = () => {
            // Some errors are better shown only after blur === true
            const v = { ...(instance.state[fieldName] || {}) };
            v.blur = true;
            instance.setState({ [fieldName]: v });
        };
    }
}

function setFormStateDebounce(name, instance, fields, validation, debounce) {
    clearTimeout(debounce.timeout);
    debounce.timeout = setTimeout(function() {
        setFormState(name, instance, fields, validation);
    }, USER_INPUT_DEBOUNCE_MS);
}

function setFormState(name, instance, fields, validation) {
    let formValid = true;
    let formTouched = false;
    const v = validation(getData(fields, instance.state));
    for (const field of fields) {
        const fieldName = n(field);
        const validate = v[fieldName];
        const error = validate ? validate : null;
        const value = { ...(instance.state[fieldName] || {}) };
        value.error = error;
        formTouched = formTouched || value.touched;
        if (error) formValid = false;
        instance.setState({ [fieldName]: value });
    }
    const fs = { ...(instance.state[name] || {}) };
    fs.valid = formValid;
    fs.touched = formTouched;
    instance.setState({ [name]: fs });
    return fs;
}

function setInitialValuesFromForm(name, instance, fields, initialValues) {
    const data = getData(fields, instance.state);
    for (const field of fields) {
        const fieldName = n(field);
        initialValues[fieldName] = data[fieldName];
    }
}

function getData(fields, state) {
    const data = {};
    for (const field of fields) {
        const fieldName = n(field);
        data[fieldName] = state[fieldName].value;
    }
    return data;
}

/*
    @arg {string} field - field:type

        type = checked (for checkbox or radio)
        type = selected (for seelct option)
        type = string

    @return {string} type
*/
function t(field) {
    const [, type = 'string'] = field.split(':');
    return type;
}

/**
    @return {string} name
*/
function n(field) {
    const [name] = field.split(':');
    return name;
}

const hasValue = v =>
    v == null
        ? false
        : (typeof v === 'string' ? v.trim() : v) === '' ? false : true;
const toString = v => (hasValue(v) ? v : '');
const toBoolean = v => (hasValue(v) ? JSON.parse(v) : '');
<|endoftext|>


<commit_before>'use strict';

const Promisie = require('promisie');
const fs = Promisie.promisifyAll(require('fs-extra'));
const path = require('path');
const periodicjs = require('periodicjs');
const Transform = require('stream').Transform;

/**
 * exports data from a given core data database model
 *
 * @param {string} core_data_name
 * @returns {Promise} contents of the core data model seed
 */
function handleWriteStream (fd) {
  let isFirst = true;
  let transform = new Transform({
    objectMode: true,
    transform: function (data, enc, next) {
      try {
        if (isFirst) {
          isFirst = false;
          this.push('[');
        }
        this.push((data && typeof data === 'object') ? JSON.stringify(data) : data);
        next();
      } catch (e) {
        next(e);
      }
    }
  });
  transform.pipe(fd);
  return transform;
}

function handleReadStream (core_data_name, writeStream, fd) {
  let firstData = true;
  return function (readStream) {
    let count = 0;
    return new Promisie((resolve, reject) => {
      try {
        writeStream.write(`{"${ core_data_name }": [`);
        writeStream.once('error', reject);
        readStream.on('data', data => {
          count++;
          if (firstData) {
            firstData = false;
            writeStream.write(data);
          } else {
            writeStream.write(',');
            writeStream.write(data);
          }
        })
          .on('error', reject)
          .on('end', () => {
            writeStream.write(']');
            resolve([writeStream, fd, count]);
          });
      } catch (e) {
        reject(e);
      }
    });
  }
}

function handleWriteEnd (transform, fd) {
  transform.end('}]');
  return new Promisie((resolve, reject) => {
    fd.on('finish', () => resolve())
      .on('error', reject);
  });
}

function exportCoreData (filepath, split_count) {
  return function (core_data_name) {
    let data_count = 0;
    let file_index = 0;
    return Promisie.doWhilst(() => {
      let fd = fs.createWriteStream(path.join(path.dirname(filepath), `${ path.basename(filepath, '.json') }_${ core_data_name }(${ file_index }).json`));
      let writeStream = handleWriteStream(fd);
      return periodicjs.datas.get(core_data_name).stream({
        limit: (typeof split_count === 'number') ? split_count : Infinity,
        skip: data_count
      })
        .then(handleReadStream(core_data_name, writeStream, fd))
        .then(result => {
          let [transform, fd, count] = result;
          data_count += count;
          file_index++;
          return handleWriteEnd(transform, fd)
            .then(() => count)
            .catch(e => Promisie.reject(e));
        })
        .catch(e => Promisie.reject(e));
    }, result => (typeof split_count === 'number' && split_count > 0 && result === split_count));
  }
}

/**
 * exports all data from periodic into a seed file
 *
 * @param {string} filepath
 * @returns {Promise} resolved value from each export from exportCoreData
 */
function exportData (filepath) {
  try {
    const excluded_data = periodicjs.settings.extensions['periodicjs.ext.dbseed'].export.ignore_core_datas;
    const split_count = periodicjs.settings.extensions['periodicjs.ext.dbseed'].export.split_count;
    const core_datas = Array.from(periodicjs.datas.keys()).filter(datum => excluded_data.indexOf(datum) === -1);
    return Promisie.map(core_datas, 5, exportCoreData(filepath, split_count));
  } catch (e) {
    return Promisie.reject(e);
  }
}

module.exports = {
  exportCoreData,
  // exportCoreDatabase,
  exportData,
};<commit_msg>updated with some prettifying<commit_after>'use strict';

const Promisie = require('promisie');
const fs = Promisie.promisifyAll(require('fs-extra'));
const path = require('path');
const periodicjs = require('periodicjs');
const Transform = require('stream').Transform;
const os = require('os');

/**
 * exports data from a given core data database model
 *
 * @param {string} core_data_name
 * @returns {Promise} contents of the core data model seed
 */
function handleWriteStream (fd) {
  let isFirst = true;
  let transform = new Transform({
    objectMode: true,
    transform: function (data, enc, next) {
      try {
        if (isFirst) {
          isFirst = false;
          this.push(`[${ os.EOL }`);
        }
        this.push((data && typeof data === 'object') ? JSON.stringify(data, null, 2) : data);
        next();
      } catch (e) {
        next(e);
      }
    }
  });
  transform.pipe(fd);
  return transform;
}

function handleReadStream (core_data_name, writeStream, fd) {
  let firstData = true;
  return function (readStream) {
    let count = 0;
    return new Promisie((resolve, reject) => {
      try {
        writeStream.write(`\t{${ os.EOL }\t\t"${ core_data_name }": [${ os.EOL }`);
        writeStream.once('error', reject);
        readStream.on('data', data => {
          count++;
          if (firstData) {
            firstData = false;
            writeStream.write(data);
          } else {
            writeStream.write(`,${ os.EOL }`);
            writeStream.write(data);
          }
        })
          .on('error', reject)
          .on('end', () => {
            writeStream.write(`${ os.EOL }\t\t]`);
            resolve([writeStream, fd, count]);
          });
      } catch (e) {
        reject(e);
      }
    });
  }
}

function handleWriteEnd (transform, fd) {
  transform.end(`${ os.EOL }\t}${ os.EOL }]`);
  return new Promisie((resolve, reject) => {
    fd.on('finish', () => resolve())
      .on('error', reject);
  });
}

function exportCoreData (filepath, split_count) {
  return function (core_data_name) {
    let data_count = 0;
    let file_index = 0;
    return Promisie.doWhilst(() => {
      let fd = fs.createWriteStream(path.join(path.dirname(filepath), `${ path.basename(filepath, '.json') }_${ core_data_name }(${ file_index }).json`));
      let writeStream = handleWriteStream(fd);
      return periodicjs.datas.get(core_data_name).stream({
        limit: (typeof split_count === 'number') ? split_count : Infinity,
        skip: data_count
      })
        .then(handleReadStream(core_data_name, writeStream, fd))
        .then(result => {
          let [transform, fd, count] = result;
          data_count += count;
          file_index++;
          return handleWriteEnd(transform, fd)
            .then(() => count)
            .catch(e => Promisie.reject(e));
        })
        .catch(e => Promisie.reject(e));
    }, result => (typeof split_count === 'number' && split_count > 0 && result === split_count));
  }
}

/**
 * exports all data from periodic into a seed file
 *
 * @param {string} filepath
 * @returns {Promise} resolved value from each export from exportCoreData
 */
function exportData (filepath) {
  try {
    const excluded_data = periodicjs.settings.extensions['periodicjs.ext.dbseed'].export.ignore_core_datas;
    const split_count = periodicjs.settings.extensions['periodicjs.ext.dbseed'].export.split_count;
    const core_datas = Array.from(periodicjs.datas.keys()).filter(datum => excluded_data.indexOf(datum) === -1);
    return Promisie.map(core_datas, 5, exportCoreData(filepath, split_count));
  } catch (e) {
    return Promisie.reject(e);
  }
}

module.exports = {
  exportCoreData,
  // exportCoreDatabase,
  exportData,
};<|endoftext|>


<commit_before>/**
 * @class Ext.ux.grid.property.Grid
 * @extends Ext.grid.property.Grid
 *
 * @author Harald Hanek (c) 2011-2012
 * @license http://harrydeluxe.mit-license.org
 */
Ext.define('Ext.ux.grid.property.Grid', {
    extend: 'Ext.grid.property.Grid',
    uses: ['Ext.ux.grid.property.Store',
            'Ext.ux.grid.property.HeaderContainer'],

    viewConfig: {
        forceFit: true,
        getRowClass: function(record)
        {
            return (record.data['disabled'] == true) ? "x-item-disabled" : "";
        }
    },

    /**
     * @cfg {String} groupField
     * The name of the field from the property store to use as the grouping field.
     */
    groupField: 'group',

    /**
     * @cfg {String} groupingConfig
     *
     */
    groupingConfig: {},

    /**
     * @private
     */
    initComponent: function()
    {
        if(!Ext.get('Ext.ux.grid.property.Grid'))
            Ext.getBody().createChild({
                tag: 'style',
                type: 'text/css',
                id: 'Ext.ux.grid.property.Grid',
                html: '.x-item-disabled div.x-grid-cell-inner {color: gray !important;}'
            });

        var me = this;
        me.addCls(Ext.baseCSSPrefix + 'property-grid');
        me.plugins = me.plugins || [];

        // Enable cell editing. Inject a custom startEdit which always edits
        // column 1 regardless of which column was clicked.
        me.plugins.push(new Ext.grid.plugin.CellEditing({
            clicksToEdit: me.clicksToEdit,
            // Inject a startEdit which always edits the value column
            startEdit: function(record, column, e)
            {
                //console.log(record, column);
                if(record.data && record.data['disabled'] == true)
                    return false;

                // Maintainer: Do not change this 'this' to 'me'! It is the
                // CellEditing object's own scope.
                return this.self.prototype.startEdit.call(this, record, me.headerCt.child('#' + me.valueField));
            }
        }));

        me.features = me.features || [];

        me.groupingFeature = new Ext.grid.feature.Grouping(Ext.apply({
            groupHeaderTpl: '{name}',
            enableGroupingMenu: true,
            groupField: me.groupField
        }, me.groupingConfig));

        me.features.push(me.groupingFeature);

        me.selModel = {
            selType: 'cellmodel',
            onCellSelect: function(position)
            {
                var record = me.store.getAt(position.row);
                if(record && record.data['disabled'] == true)
                    return false;

                if(position.column != 1)
                    position.column = 1;

                return this.self.prototype.onCellSelect.call(this, position);
            }
        };

        me.customRenderers = me.customRenderers || {};
        me.customEditors = me.customEditors || {};

        if(me.store && me.source && me.store.data.items.length == 0)
        {
            me.store.loadRawData(me.source); // harry
        }

        // Create a property.Store from the source object unless configured with
        // a store
        if(!me.store)
        {
            me.propStore = me.store = new Ext.ux.grid.property.Store(me, me.source);
        }

        if(!me.propStore)
            me.propStore = me.store;

        //me.store.sort('name', 'ASC');

        me.columns = new Ext.ux.grid.property.HeaderContainer(me, me.store); // harry

        me.addEvents(
            /**
             * @event beforepropertychange Fires before a property value changes.
             *        Handlers can return false to cancel the property change (this
             *        will internally call {@link Ext.data.Record#reject} on the
             *        property's record).
             * @param {Object} source The source data object for the grid
             *            (corresponds to the same object passed in as the
             *            {@link #source} config property).
             * @param {String} recordId The record's id in the data store
             * @param {Mixed} value The current edited property value
             * @param {Mixed} oldValue The original property value prior to editing
             */

            'beforepropertychange',
            /**
             * @event propertychange Fires after a property value has changed.
             * @param {Object} source The source data object for the grid
             *            (corresponds to the same object passed in as the
             *            {@link #source} config property).
             * @param {String} recordId The record's id in the data store
             * @param {Mixed} value The current edited property value
             * @param {Mixed} oldValue The original property value prior to editing
             */
            'propertychange');

        this.superclass.superclass.initComponent.call(this, arguments); // harry
        // Inject a custom implementation of walkCells which only goes up or
        // down
        me.getView().walkCells = this.walkCells;
        // Set up our default editor set for the 4 atomic data types
        me.editors = {
            'date': new Ext.grid.CellEditor({
                field: new Ext.form.field.Date({
                    selectOnFocus: true
                })
            }),
            'string': new Ext.grid.CellEditor({
                field: new Ext.form.field.Text({
                    selectOnFocus: true
                })
            }),
            'number': new Ext.grid.CellEditor({
                field: new Ext.form.field.Number({
                    selectOnFocus: true
                })
            }),
            'boolean': new Ext.grid.CellEditor({
                field: new Ext.form.field.ComboBox({
                    editable: false,
                    store: [[true,
                            me.headerCt.trueText],
                            [false,
                                    me.headerCt.falseText]]
                })
            })
        };
        // Track changes to the data so we can fire our events.
        me.store.on('update', me.onUpdate, me);
    },

    /**
     * returns the correct editor type for the property type, or a custom one
     * keyed by the property name
     *
     * @private
     */
    getCellEditor: function(record, column)
    {
        var me = this,
            propName = record.get(me.nameField),
            val = record.get(me.valueField),
            editor = me.customEditors[propName];

        editor = me.customEditors[record.data.editor] || record.data.editor || me.customEditors[propName]; // harry

        // A custom editor was found. If not already wrapped with a CellEditor,
        // wrap it, and stash it back
        // If it's not even a Field, just a config object, instantiate it before
        // wrapping it.
        if(editor)
        {
            if(Ext.isString(editor) && me.editors[editor]) // harry
            {
                editor = me.editors[editor];
            }
            else if(!(editor instanceof Ext.grid.CellEditor))
            {
                if(!(editor instanceof Ext.form.field.Base))
                {
                    editor = Ext.ComponentManager.create(editor, 'textfield');
                }
                editor = me.customEditors[propName] = new Ext.grid.CellEditor({
                    field: editor
                });
            }
        }
        else if(Ext.isDate(val))
        {
            editor = me.editors.date;
        }
        else if(Ext.isNumber(val))
        {
            editor = me.editors.number;
        }
        else if(Ext.isBoolean(val))
        {
            editor = me.editors['boolean'];
        }
        else
        {
            editor = me.editors.string;
        }

        // Give the editor a unique ID because the CellEditing plugin caches them
        editor.editorId = propName;
        return editor;
    }
});<commit_msg>skip diabled records<commit_after>/**
 * @class Ext.ux.grid.property.Grid
 * @extends Ext.grid.property.Grid
 *
 * @author Harald Hanek (c) 2011-2012
 * @license http://harrydeluxe.mit-license.org
 */
Ext.define('Ext.ux.grid.property.Grid', {
    extend: 'Ext.grid.property.Grid',

    uses: [ 'Ext.ux.grid.property.Store',
            'Ext.ux.grid.property.HeaderContainer',
            'Ext.grid.feature.Grouping'],

    viewConfig: {
        forceFit: true,
        getRowClass: function(record)
        {
            return (record.data['disabled'] == true) ? "x-item-disabled" : "";
        }
    },

    /**
     * @cfg {String} groupField
     * The name of the field from the property store to use as the grouping field.
     */
    groupField: 'group',

    /**
     * @cfg {String} groupingConfig
     *
     */
    groupingConfig: {},

    /**
     * @private
     */
    initComponent: function()
    {
        if(!Ext.get('Ext.ux.grid.property.Grid'))
            Ext.getBody().createChild({
                tag: 'style',
                type: 'text/css',
                id: 'Ext.ux.grid.property.Grid',
                html: '.x-item-disabled div.x-grid-cell-inner {color: gray !important;}'
            });

        var me = this;
        me.addCls(Ext.baseCSSPrefix + 'property-grid');
        me.plugins = me.plugins || [];

        // Enable cell editing. Inject a custom startEdit which always edits
        // column 1 regardless of which column was clicked.
        me.plugins.push(new Ext.grid.plugin.CellEditing({
            clicksToEdit: me.clicksToEdit,
            // Inject a startEdit which always edits the value column
            startEdit: function(record, column, e)
            {
                //console.log(record, column);
                if(record.data && record.data['disabled'] == true)
                    return false;

                // Maintainer: Do not change this 'this' to 'me'! It is the
                // CellEditing object's own scope.
                return this.self.prototype.startEdit.call(this, record, me.headerCt.child('#' + me.valueField));
            }
        }));

        me.features = me.features || [];

        me.groupingFeature = new Ext.grid.feature.Grouping(Ext.apply({
            groupHeaderTpl: '{name}',
            enableGroupingMenu: true,
            groupField: me.groupField
        }, me.groupingConfig));

        me.features.push(me.groupingFeature);

        me.selModel = {
            selType: 'cellmodel',
            onCellSelect: function(position)
            {
                var record = me.store.getAt(position.row);
                if(record && record.data['disabled'] == true)
                    return false;

                if(position.column != 1)
                    position.column = 1;

                return this.self.prototype.onCellSelect.call(this, position);
            }
        };

        me.customRenderers = me.customRenderers || {};
        me.customEditors = me.customEditors || {};

        if(me.store && me.source && me.store.data.items.length == 0)
        {
            me.store.loadRawData(me.source); // harry
        }

        // Create a property.Store from the source object unless configured with
        // a store
        if(!me.store)
        {
            me.propStore = me.store = new Ext.ux.grid.property.Store(me, me.source);
        }

        if(!me.propStore)
            me.propStore = me.store;

        //me.store.sort('name', 'ASC');

        me.columns = new Ext.ux.grid.property.HeaderContainer(me, me.store); // harry

        me.addEvents(
            /**
             * @event beforepropertychange Fires before a property value changes.
             *        Handlers can return false to cancel the property change (this
             *        will internally call {@link Ext.data.Record#reject} on the
             *        property's record).
             * @param {Object} source The source data object for the grid
             *            (corresponds to the same object passed in as the
             *            {@link #source} config property).
             * @param {String} recordId The record's id in the data store
             * @param {Mixed} value The current edited property value
             * @param {Mixed} oldValue The original property value prior to editing
             */

            'beforepropertychange',
            /**
             * @event propertychange Fires after a property value has changed.
             * @param {Object} source The source data object for the grid
             *            (corresponds to the same object passed in as the
             *            {@link #source} config property).
             * @param {String} recordId The record's id in the data store
             * @param {Mixed} value The current edited property value
             * @param {Mixed} oldValue The original property value prior to editing
             */
            'propertychange');

        this.superclass.superclass.initComponent.call(this, arguments); // harry
        // Inject a custom implementation of walkCells which only goes up or
        // down
        me.getView().walkCells = this.walkCells;
        // Set up our default editor set for the 4 atomic data types
        me.editors = {
            'date': new Ext.grid.CellEditor({
                field: new Ext.form.field.Date({
                    selectOnFocus: true
                })
            }),
            'string': new Ext.grid.CellEditor({
                field: new Ext.form.field.Text({
                    selectOnFocus: true
                })
            }),
            'number': new Ext.grid.CellEditor({
                field: new Ext.form.field.Number({
                    selectOnFocus: true
                })
            }),
            'boolean': new Ext.grid.CellEditor({
                field: new Ext.form.field.ComboBox({
                    editable: false,
                    store: [[true,
                            me.headerCt.trueText],
                            [false,
                                    me.headerCt.falseText]]
                })
            })
        };
        // Track changes to the data so we can fire our events.
        me.store.on('update', me.onUpdate, me);
    },

    /**
     * returns the correct editor type for the property type, or a custom one
     * keyed by the property name
     *
     * @private
     */
    getCellEditor: function(record, column)
    {
        var me = this,
            propName = record.get(me.nameField),
            val = record.get(me.valueField),
            editor = me.customEditors[propName];

        editor = me.customEditors[record.data.editor] || record.data.editor || me.customEditors[propName]; // harry

        // A custom editor was found. If not already wrapped with a CellEditor,
        // wrap it, and stash it back
        // If it's not even a Field, just a config object, instantiate it before
        // wrapping it.
        if(editor)
        {
            if(Ext.isString(editor) && me.editors[editor]) // harry
            {
                editor = me.editors[editor];
            }
            else if(!(editor instanceof Ext.grid.CellEditor))
            {
                if(!(editor instanceof Ext.form.field.Base))
                {
                    editor = Ext.ComponentManager.create(editor, 'textfield');
                }
                editor = me.customEditors[propName] = new Ext.grid.CellEditor({
                    field: editor
                });
            }
        }
        else if(Ext.isDate(val))
        {
            editor = me.editors.date;
        }
        else if(Ext.isNumber(val))
        {
            editor = me.editors.number;
        }
        else if(Ext.isBoolean(val))
        {
            editor = me.editors['boolean'];
        }
        else
        {
            editor = me.editors.string;
        }

        // Give the editor a unique ID because the CellEditing plugin caches them
        editor.editorId = propName;
        return editor;
    },

 // Custom implementation of walkCells which only goes up and down.
    walkCells: function(pos, direction, e, preventWrap, verifierFn, scope) {
        if (direction == 'left') {
            direction = 'up';
        } else if (direction == 'right') {
            direction = 'down';
        }

        // skip diabled records
        if(direction == 'up' && pos.record.index != 0 || direction == 'down' && pos.record.index < pos.record.store.totalCount-1)
        {
            var ind = (direction == 'down') ? + 1 : - 1,
                f = pos.record.store.getAt(pos.record.index + ind);

            if(f.data && f.data.disabled)
            {
                pos.row = pos.row + ind;
            }
        }

        pos = Ext.view.Table.prototype.walkCells.call(this, pos, direction, e, preventWrap, verifierFn, scope);
        if (!pos.column) {
            pos.column = 1;
        }
        return pos;
    }
});<|endoftext|>


<commit_before><<<<<<< HEAD
//Validate birthdate

function isValidDate(dateString)
{
    // First check for the pattern
    if(!/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dateString))
        return false;

    // Parse the date parts to integers
    var parts = dateString.split("/");
    var day = parseInt(parts[0], 10);
    var month = parseInt(parts[1], 10);
    var year = parseInt(parts[2], 10);

    // Check the ranges of month and year
    if(year < 1000 || year > 3000 || month == 0 || month > 12)
        return false;
=======

//Validate date
function validateDate(day, month, year) {

    // Check the ranges of month and year
    if(year < 1000 || year > 3000 || month == 0 || month > 12){
        return false;
    }
>>>>>>> 81a0ba3cb94b75fae129196b203d39774bf76fab

    var monthLength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];

    // Adjust for leap years
<<<<<<< HEAD
    if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
        monthLength[1] = 29;

    // Check the range of the day
    return day > 0 && day <= monthLength[month - 1];
};

//Name validation

function validateName($name) {

    if($name ==""){
        alert("EspaÃ§o precisa ser preenchido");
        return false;
    } else if (!/^[a-zA-Z]*$/.test($name)) {
            alert("O nome contem caracteres invalidos");
        return false;
    } else {
        alert("Tudo certo");
            return true;
    }
}
function validateSurname() {

    if($surname ==""){
        alert("EspaÃ§o precisa ser preenchido");
        return false;
    } else if (!/^[a-zA-Z]*$/.test($surname)) {
            alert("O nome contem caracteres invalidos");
        return false;
    } else {
        alert("Tudo certo");
            return true;
    }
}

//Password Validation

function checkForm(form)
{
=======
    if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)){
        monthLength[1] = 29;
    }

    // Check the range of the day
    return day > 0 && day <= monthLength[month - 1];
}

//Name validation
function validateName(name) {

    //Check if name box is empty
    if(name ==""){
        return false;
    //Check if contains special characters
    return /^[a-zA-Z]*$/.test(name);
}

//Password Validation
function checkForm(password){

>>>>>>> 81a0ba3cb94b75fae129196b203d39774bf76fab
	if(form.pwd1.value != "" && form.pwd1.value == form.pwd2.value) {
	if(form.pwd1.value.length < 6) {
		alert("Erro: A senha deve conter pelo menos 6 caracteres!");
		form.pwd1.focus();
		return false;
	}
	if(form.pwd1.value == form.name.value) {
		alert("Erro: A senha deve ser diferente do nome de usuario!");
		form.pwd1.focus();
		return false;
      	}
      	var re = /[0-9]/;
      	if(!re.test(form.pwd1.value)) {
		alert("Erro: A senha deve conter pelo menos um numero (0-9)!");
		form.pwd1.focus();
		return false;
      	}
      	var re = /[a-z]/;
      	if(!re.test(form.pwd1.value)) {
		alert("Erro: A senha deve conter pelo menos uma letra minuscula (a-z)!");
		form.pwd1.focus();
		return false;
	}
      	var re = /[A-Z]/;
      	if(!re.test(form.pwd1.value)) {
		alert("Erro: A senha deve conter pelo menos uma letra maiuscula (A-Z)!");
		form.pwd1.focus();
		return false;
      	}
    	} else {
	      alert("Erro: Verifique se introduziu e/ou confirmou a sua palavra-passe!");
	      form.pwd1.focus();
	      return false;
	}

	alert("Cadastro realizado com sucesso!");
	return true;
}

//Phone validation
   function validateForm() {
   return checkPhone();
     }
   function checkPhone() {
        var phone = document.forms["myForm"]["phone"].value;
	var phoneNum = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
	if(phone.value.match(phoneNum)) {
	return true;
	}
  else {
	document.getElementById("phone").className = document.getElementById("phone").className + " error";
	return false;
	}
	}
// CPF validation
	function mascara_cpf(cpf)
{
    var mycpf = '';
    mycpf = mycpf + cpf;
    if (mycpf.length == 3) {
        mycpf = mycpf + '.';
        document.forms[0].cpf.value = mycpf;
    }
    if (mycpf.length == 7) {
        mycpf = mycpf + '.';
        document.forms[0].cpf.value = mycpf;
    }
    if (mycpf.length == 11) {
        mycpf = mycpf + '-';
        document.forms[0].cpf.value = mycpf;
    }
    if (mycpf.length == 14) {
    }
}

<<<<<<< HEAD

=======
>>>>>>> 81a0ba3cb94b75fae129196b203d39774bf76fab
<commit_msg>nova validacao do cpf<commit_after>
//Validate birthdate

function isValidDate(dateString)
{
    // First check for the pattern
    if(!/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dateString))
        return false;

    // Parse the date parts to integers
    var parts = dateString.split("/");
    var day = parseInt(parts[0], 10);
    var month = parseInt(parts[1], 10);
    var year = parseInt(parts[2], 10);

    // Check the ranges of month and year
    if(year < 1000 || year > 3000 || month == 0 || month > 12)
        return false;

//Validate date
function validateDate(day, month, year) {

    // Check the ranges of month and year
    if(year < 1000 || year > 3000 || month == 0 || month > 12){
        return false;
    }

    var monthLength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];

    // Adjust for leap years

    if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
        monthLength[1] = 29;

    // Check the range of the day
    return day > 0 && day <= monthLength[month - 1];
};

//Name validation

function validateName($name) {

    if($name ==""){
        alert("EspaÃ§o precisa ser preenchido");
        return false;
    } else if (!/^[a-zA-Z]*$/.test($name)) {
            alert("O nome contem caracteres invalidos");
        return false;
    } else {
        alert("Tudo certo");
            return true;
    }
}
function validateSurname() {

    if($surname ==""){
        alert("EspaÃ§o precisa ser preenchido");
        return false;
    } else if (!/^[a-zA-Z]*$/.test($surname)) {
            alert("O nome contem caracteres invalidos");
        return false;
    } else {
        alert("Tudo certo");
            return true;
    }
}

//Password Validation

function checkForm(form)
{

    if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)){
        monthLength[1] = 29;
    }

    // Check the range of the day
    return day > 0 && day <= monthLength[month - 1];
}

//Name validation
function validateName(name) {

    //Check if name box is empty
    if(name ==""){
        return false;
    //Check if contains special characters
    return /^[a-zA-Z]*$/.test(name);
}

//Password Validation
function checkForm(password){

	if(form.pwd1.value != "" && form.pwd1.value == form.pwd2.value) {
	if(form.pwd1.value.length < 6) {
		alert("Erro: A senha deve conter pelo menos 6 caracteres!");
		form.pwd1.focus();
		return false;
	}
	if(form.pwd1.value == form.name.value) {
		alert("Erro: A senha deve ser diferente do nome de usuario!");
		form.pwd1.focus();
		return false;
      	}
      	var re = /[0-9]/;
      	if(!re.test(form.pwd1.value)) {
		alert("Erro: A senha deve conter pelo menos um numero (0-9)!");
		form.pwd1.focus();
		return false;
      	}
      	var re = /[a-z]/;
      	if(!re.test(form.pwd1.value)) {
		alert("Erro: A senha deve conter pelo menos uma letra minuscula (a-z)!");
		form.pwd1.focus();
		return false;
	}
      	var re = /[A-Z]/;
      	if(!re.test(form.pwd1.value)) {
		alert("Erro: A senha deve conter pelo menos uma letra maiuscula (A-Z)!");
		form.pwd1.focus();
		return false;
      	}
    	} else {
	      alert("Erro: Verifique se introduziu e/ou confirmou a sua palavra-passe!");
	      form.pwd1.focus();
	      return false;
	}

	alert("Cadastro realizado com sucesso!");
	return true;
}

//Phone validation
   function validateForm() {
   return checkPhone();
     }
   function checkPhone() {
        var phone = document.forms["myForm"]["phone"].value;
	var phoneNum = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
	if(phone.value.match(phoneNum)) {
	return true;
	}
  else {
	document.getElementById("phone").className = document.getElementById("phone").className + " error";
	return false;
	}
	}
// CPF validation
/*	function mascara_cpf(cpf)
{
    var mycpf = '';
    mycpf = mycpf + cpf;
    if (mycpf.length == 3) {
        mycpf = mycpf + '.';
        document.forms[0].cpf.value = mycpf;
    }
    if (mycpf.length == 7) {
        mycpf = mycpf + '.';
        document.forms[0].cpf.value = mycpf;
    }
    if (mycpf.length == 11) {
        mycpf = mycpf + '-';
        document.forms[0].cpf.value = mycpf;
    }
    if (mycpf.length == 14) {
    }
}*/

function TestaCPF(strCPF) {
    var Soma;
    var Resto;
    Soma = 0;
	if (strCPF == "00000000000") return false;

	for (i=1; i<=9; i++) Soma = Soma + parseInt(strCPF.substring(i-1, i)) * (11 - i);
	Resto = (Soma * 10) % 11;

    if ((Resto == 10) || (Resto == 11))  Resto = 0;
    if (Resto != parseInt(strCPF.substring(9, 10)) ) return false;

	Soma = 0;
    for (i = 1; i <= 10; i++) Soma = Soma + parseInt(strCPF.substring(i-1, i)) * (12 - i);
    Resto = (Soma * 10) % 11;

    if ((Resto == 10) || (Resto == 11))  Resto = 0;
    if (Resto != parseInt(strCPF.substring(10, 11) ) ) return false;
    return true;
}
var strCPF = "12345678909";
alert(TestaCPF(strCPF));

<|endoftext|>


<commit_before>import React, {PropTypes, Component} from "react";
import {render} from "react-dom";
import {connect} from "react-redux";
import {Tabs, Tab} from "react-bootstrap";
import { Scrollbars } from 'react-custom-scrollbars';
import {browserHistory} from "react-router";
import { Panel } from 'react-bootstrap';
import {bindActionCreators} from "redux";
import Dropzone from "react-dropzone";
import ActionsUtils from "../../actions/ActionsUtils";
import HttpService from "../../http/HttpService";
import DialogMessages from "../../common/DialogMessages";
import ProcessUtils from "../../common/ProcessUtils";
import SideNodeDetails from "./SideNodeDetails";
import NodeUtils from '../graph/NodeUtils'
import InlinedSvgs from "../../assets/icons/InlinedSvgs"
import Dialogs from "../modals/Dialogs"

class UserRightPanel extends Component {

  static propTypes = {
    isOpened: React.PropTypes.bool.isRequired,
    graphLayoutFunction: React.PropTypes.func.isRequired,
    layout: React.PropTypes.array.isRequired,
    exportGraph: React.PropTypes.func.isRequired,
    zoomIn: React.PropTypes.func.isRequired,
    zoomOut: React.PropTypes.func.isRequired,
    featuresSettings: React.PropTypes.object.isRequired

  }

  constructor(props) {
    super(props);
  }

  renderClassName = () => {
    return this.props.isOpened ? 'rightSidenav is-opened' : 'rightSidenav'
  }

  render() {
    const saveDisabled = this.props.nothingToSave && this.props.processIsLatestVersion
    const deployPossible = this.props.processIsLatestVersion && ProcessUtils.hasNoErrors(this.props.processToDisplay) && this.props.nothingToSave
    const migratePossible = this.props.processIsLatestVersion && ProcessUtils.hasNoErrors(this.props.processToDisplay) && this.props.nothingToSave

    const config =
      [
        {
          panelName: "Deployment",
          buttons:[
            {name: "deploy", visible: this.props.loggedUser.canDeploy, disabled: !deployPossible, onClick: this.deploy, icon: InlinedSvgs.buttonDeploy},
            {name: "stop", visible: this.props.loggedUser.canDeploy, disabled: !this.isRunning(), onClick: this.stop, icon: InlinedSvgs.buttonStop},
            {name: "metrics", onClick: this.showMetrics, icon: InlinedSvgs.buttonMetrics}
          ]
        },
        {
        panelName: "Process",
        buttons: [
          {name: "save" + (!saveDisabled ? "*" : ""), visible: this.props.loggedUser.canWrite, disabled: saveDisabled, onClick: this.save, icon: InlinedSvgs.buttonSave},
          {name: "migrate", visible: this.props.loggedUser.canDeploy && !_.isEmpty(this.props.featuresSettings.migrationSettings), disabled: !migratePossible, onClick: this.migrate, icon: InlinedSvgs.buttonMigrate},

          {name: "import", visible: this.props.loggedUser.canWrite, disabled: false, onClick: this.importProcess, icon: InlinedSvgs.buttonImport, dropzone: true},
          {name: "export", onClick: this.exportProcess, icon: InlinedSvgs.buttonExport},
          {name: "exportPDF", disabled: !this.props.nothingToSave, onClick: this.exportProcessToPdf, icon: InlinedSvgs.buttonExport},
          {name: "zoomIn", onClick: this.props.zoomIn, icon: InlinedSvgs.buttonZoomIn},
          {name: "zoomOut", onClick: this.props.zoomOut, icon: InlinedSvgs.buttonZoomOut}

        ]
      },
        {
          panelName: "Edit",
          buttons: [
            {name: "undo", onClick: this.undo, icon: InlinedSvgs.buttonUndo},
            {name: "redo", onClick: this.redo, icon: InlinedSvgs.buttonRedo},
            {name: "align", onClick: this.props.graphLayoutFunction, icon: InlinedSvgs.buttonAlign},
            {name: "properties", onClick: this.showProperties, icon: InlinedSvgs.buttonSettings},
            {name: "duplicate", onClick: this.duplicateNode, icon: InlinedSvgs.duplicateButton,
              //cloning groups can be tricky...
              disabled: this.noChosenNode(this.props.nodeToDisplay) || NodeUtils.nodeIsGroup(this.props.nodeToDisplay)},
            {name: "delete", onClick: this.deleteNode, icon: InlinedSvgs.buttonDelete, disabled: this.noChosenNode(this.props.nodeToDisplay) }
          ]
        },
        {
          panelName: "Test",
          buttons: [
            {name: "from file", onClick: this.testProcess, icon: InlinedSvgs.buttonFromFile, dropzone: true,
              disabled: !this.props.testCapabilities.canBeTested},
            {name: "hide", onClick: this.hideRunProcessDetails, icon: InlinedSvgs.buttonHide, disabled: !this.props.showRunProcessDetails},
            {name: "generate", onClick: this.generateData, icon: InlinedSvgs.buttonGenerate,
              disabled: !this.props.processIsLatestVersion || !this.props.testCapabilities.canGenerateTestData},
            {name: "counts", onClick: this.fetchProcessCounts, icon: InlinedSvgs.buttonCounts, visible: this.props.featuresSettings.counts},
          ]
        },
        {
          panelName: "Group",
          buttons: [
            {name: "start", onClick: this.props.actions.startGrouping, icon: InlinedSvgs.buttonGroup, disabled: this.props.groupingState != null},
            {name: "finish", onClick: this.props.actions.finishGrouping, icon: InlinedSvgs.buttonGroup, disabled: (this.props.groupingState || []).length <= 1},
            {name: "cancel", onClick: this.props.actions.cancelGrouping, icon: InlinedSvgs.buttonUngroup, disabled: !this.props.groupingState },
            {name: "ungroup", onClick: this.ungroup, icon: InlinedSvgs.buttonUngroup, disabled: !NodeUtils.nodeIsGroup(this.props.nodeToDisplay) }
          ]
        }
      ]
    return (

        <Scrollbars renderThumbVertical={props =>
} hideTracksWhenNotNeeded={true}>
          {config.map ((panel, panelIdx) => {
            return (
              <Panel key={panelIdx} collapsible defaultExpanded header={panel.panelName}>
                {panel.properties ? panel.properties : null }
                {panel.buttons.map((panelButton, idx) => this.renderPanelButton(panelButton, idx))}
              </Panel>
            )}
          )}
          <Panel collapsible defaultExpanded header="Details">
            <SideNodeDetails/>
          </Panel>
        </Scrollbars>

    )
  }

  renderPanelButton = (panelButton, idx) => {
    const buttonClass = "espButton right-panel"
    return panelButton.visible == false ? null :
      panelButton.dropzone ?
        <Dropzone key={idx} disableClick={panelButton.disabled == true} onDrop={panelButton.onClick}
                   className={"dropZone " + buttonClass + (panelButton.disabled == true ? " disabled" : "")}>

{panelButton.name}

          </Dropzone>
        :
        <button key={idx} type="button" className={buttonClass} disabled={panelButton.disabled == true}
                onClick={panelButton.onClick}>

 {panelButton.name}
        </button>
  }

  noChosenNode = (node) => {
    return NodeUtils.nodeIsProperties(node) || _.isEmpty(node)
  }

  isRunning = () => this.props.fetchedProcessDetails && (this.props.fetchedProcessDetails.currentlyDeployedAt || []).length > 0

  showProperties = () => {
    this.props.actions.displayModalNodeDetails(this.props.processToDisplay.properties)
  }

  save = () => {
    this.props.actions.toggleModalDialog(Dialogs.types.saveProcess)
  }

  migrate = () => {
    this.props.actions.toggleConfirmDialog(true, DialogMessages.migrate(this.processId(), this.props.featuresSettings.migrationSettings.targetEnvironmentId), () => {
      HttpService.migrateProcess(this.processId())
    })
  }

  deploy = () => {
    this.props.actions.toggleConfirmDialog(true, DialogMessages.deploy(this.processId()), () => {
      return HttpService.deploy(this.processId()).then((resp) => {
        //ten kod wykonuje sie nawet kiedy deploy sie nie uda, bo wyzej robimy catch i w przypadku bledu tutaj dostajemy undefined, pomyslec jak ladnie to rozwiazac
        this.fetchProcessDetails()
      })
    })
  }

  stop = () => {
    this.props.actions.toggleConfirmDialog(true, DialogMessages.stop(this.processId()), () => {
      return HttpService.stop(this.processId()).then((resp) => {
        //ten kod wykonuje sie nawet kiedy deploy sie nie uda, bo wyzej robimy catch i w przypadku bledu tutaj dostajemy undefined, pomyslec jak ladnie to rozwiazac
        this.fetchProcessDetails()
      })
    })
  }

  clearHistory = () => {
    return this.props.undoRedoActions.clear()
  }

  fetchProcessDetails = () => {
    this.props.actions.displayCurrentProcessVersion(this.processId())
  }

  processId = () => {
    return (this.props.processToDisplay || {}).id
  }

  versionId = () => this.props.fetchedProcessDetails.processVersionId

  showMetrics = () => {
    browserHistory.push('/metrics/' + this.processId())
  }

  exportProcess = () => {
    HttpService.exportProcess(this.processId(), this.versionId())
  }

  exportProcessToPdf = () => {
    const data = this.props.exportGraph()
    HttpService.exportProcessToPdf(this.processId(), this.versionId(), data)
  }

  generateData = () => {
    this.props.actions.toggleModalDialog(Dialogs.types.generateTestData)
  }

  fetchProcessCounts = () => {
    this.props.actions.toggleModalDialog(Dialogs.types.calculateCounts)
  }

  importProcess = (files) => {
    files.forEach((file)=>
      this.props.actions.importProcess(this.processId(), file)
    );
  }

  testProcess = (files) => {
    files.forEach((file)=>
      this.props.actions.testProcessFromFile(this.processId(), file, this.props.processToDisplay)
    );
  }

  hideRunProcessDetails = () => {
    this.props.actions.hideRunProcessDetails()
  }

  undo = () => {
    //ten if moze powinien byc blisko reducera, tylko jak to ladnie zrobic?
    if (this.props.keyActionsAvailable) {
      this.props.undoRedoActions.undo()
    }
  }

  redo = () => {
    if (this.props.keyActionsAvailable) {
      this.props.undoRedoActions.redo()
    }
  }

  duplicateNode = () => {
    const duplicatedNodePosition = this.props.layout.find(node => node.id === this.props.nodeToDisplay.id) || {position: {x: 0, y: 0}}
    const visiblePosition = {x: duplicatedNodePosition.position.x -200, y: duplicatedNodePosition.position.y}
    this.props.actions.nodeAdded(this.props.nodeToDisplay, visiblePosition)
  }

  deleteNode = () => {
    this.props.actions.deleteNode(this.props.nodeToDisplay.id)
  }

  ungroup = () => {
    this.props.actions.ungroup(this.props.nodeToDisplay)
  }

}

function mapState(state) {
  const fetchedProcessDetails = state.graphReducer.fetchedProcessDetails
  return {
    fetchedProcessDetails: fetchedProcessDetails,
    processToDisplay: state.graphReducer.processToDisplay,
    //TODO: now only needed for duplicate, maybe we can do it somehow differently?
    layout: state.graphReducer.layout || [],

    testCapabilities: state.graphReducer.testCapabilities || {},

    loggedUser: state.settings.loggedUser,
    nothingToSave: ProcessUtils.nothingToSave(state),
    showRunProcessDetails: !_.isEmpty(state.graphReducer.testResults) || !_.isEmpty(state.graphReducer.processCounts),
    keyActionsAvailable: state.ui.allModalsClosed,
    processIsLatestVersion: _.get(fetchedProcessDetails, 'isLatestVersion', false),
    nodeToDisplay: state.graphReducer.nodeToDisplay,
    groupingState: state.graphReducer.groupingState,
    featuresSettings: state.settings.featuresSettings
  };
}

export default connect(mapState, ActionsUtils.mapDispatchWithEspActions)(UserRightPanel);<commit_msg>settings typo fix<commit_after>import React, {PropTypes, Component} from "react";
import {render} from "react-dom";
import {connect} from "react-redux";
import {Tabs, Tab} from "react-bootstrap";
import { Scrollbars } from 'react-custom-scrollbars';
import {browserHistory} from "react-router";
import { Panel } from 'react-bootstrap';
import {bindActionCreators} from "redux";
import Dropzone from "react-dropzone";
import ActionsUtils from "../../actions/ActionsUtils";
import HttpService from "../../http/HttpService";
import DialogMessages from "../../common/DialogMessages";
import ProcessUtils from "../../common/ProcessUtils";
import SideNodeDetails from "./SideNodeDetails";
import NodeUtils from '../graph/NodeUtils'
import InlinedSvgs from "../../assets/icons/InlinedSvgs"
import Dialogs from "../modals/Dialogs"

class UserRightPanel extends Component {

  static propTypes = {
    isOpened: React.PropTypes.bool.isRequired,
    graphLayoutFunction: React.PropTypes.func.isRequired,
    layout: React.PropTypes.array.isRequired,
    exportGraph: React.PropTypes.func.isRequired,
    zoomIn: React.PropTypes.func.isRequired,
    zoomOut: React.PropTypes.func.isRequired,
    featuresSettings: React.PropTypes.object.isRequired

  }

  constructor(props) {
    super(props);
  }

  renderClassName = () => {
    return this.props.isOpened ? 'rightSidenav is-opened' : 'rightSidenav'
  }

  render() {
    const saveDisabled = this.props.nothingToSave && this.props.processIsLatestVersion
    const deployPossible = this.props.processIsLatestVersion && ProcessUtils.hasNoErrors(this.props.processToDisplay) && this.props.nothingToSave
    const migratePossible = this.props.processIsLatestVersion && ProcessUtils.hasNoErrors(this.props.processToDisplay) && this.props.nothingToSave

    const config =
      [
        {
          panelName: "Deployment",
          buttons:[
            {name: "deploy", visible: this.props.loggedUser.canDeploy, disabled: !deployPossible, onClick: this.deploy, icon: InlinedSvgs.buttonDeploy},
            {name: "stop", visible: this.props.loggedUser.canDeploy, disabled: !this.isRunning(), onClick: this.stop, icon: InlinedSvgs.buttonStop},
            {name: "metrics", onClick: this.showMetrics, icon: InlinedSvgs.buttonMetrics}
          ]
        },
        {
        panelName: "Process",
        buttons: [
          {name: "save" + (!saveDisabled ? "*" : ""), visible: this.props.loggedUser.canWrite, disabled: saveDisabled, onClick: this.save, icon: InlinedSvgs.buttonSave},
          {name: "migrate", visible: this.props.loggedUser.canDeploy && !_.isEmpty(this.props.featuresSettings.migration), disabled: !migratePossible, onClick: this.migrate, icon: InlinedSvgs.buttonMigrate},

          {name: "import", visible: this.props.loggedUser.canWrite, disabled: false, onClick: this.importProcess, icon: InlinedSvgs.buttonImport, dropzone: true},
          {name: "export", onClick: this.exportProcess, icon: InlinedSvgs.buttonExport},
          {name: "exportPDF", disabled: !this.props.nothingToSave, onClick: this.exportProcessToPdf, icon: InlinedSvgs.buttonExport},
          {name: "zoomIn", onClick: this.props.zoomIn, icon: InlinedSvgs.buttonZoomIn},
          {name: "zoomOut", onClick: this.props.zoomOut, icon: InlinedSvgs.buttonZoomOut}

        ]
      },
        {
          panelName: "Edit",
          buttons: [
            {name: "undo", onClick: this.undo, icon: InlinedSvgs.buttonUndo},
            {name: "redo", onClick: this.redo, icon: InlinedSvgs.buttonRedo},
            {name: "align", onClick: this.props.graphLayoutFunction, icon: InlinedSvgs.buttonAlign},
            {name: "properties", onClick: this.showProperties, icon: InlinedSvgs.buttonSettings},
            {name: "duplicate", onClick: this.duplicateNode, icon: InlinedSvgs.duplicateButton,
              //cloning groups can be tricky...
              disabled: this.noChosenNode(this.props.nodeToDisplay) || NodeUtils.nodeIsGroup(this.props.nodeToDisplay)},
            {name: "delete", onClick: this.deleteNode, icon: InlinedSvgs.buttonDelete, disabled: this.noChosenNode(this.props.nodeToDisplay) }
          ]
        },
        {
          panelName: "Test",
          buttons: [
            {name: "from file", onClick: this.testProcess, icon: InlinedSvgs.buttonFromFile, dropzone: true,
              disabled: !this.props.testCapabilities.canBeTested},
            {name: "hide", onClick: this.hideRunProcessDetails, icon: InlinedSvgs.buttonHide, disabled: !this.props.showRunProcessDetails},
            {name: "generate", onClick: this.generateData, icon: InlinedSvgs.buttonGenerate,
              disabled: !this.props.processIsLatestVersion || !this.props.testCapabilities.canGenerateTestData},
            {name: "counts", onClick: this.fetchProcessCounts, icon: InlinedSvgs.buttonCounts, visible: this.props.featuresSettings.counts},
          ]
        },
        {
          panelName: "Group",
          buttons: [
            {name: "start", onClick: this.props.actions.startGrouping, icon: InlinedSvgs.buttonGroup, disabled: this.props.groupingState != null},
            {name: "finish", onClick: this.props.actions.finishGrouping, icon: InlinedSvgs.buttonGroup, disabled: (this.props.groupingState || []).length <= 1},
            {name: "cancel", onClick: this.props.actions.cancelGrouping, icon: InlinedSvgs.buttonUngroup, disabled: !this.props.groupingState },
            {name: "ungroup", onClick: this.ungroup, icon: InlinedSvgs.buttonUngroup, disabled: !NodeUtils.nodeIsGroup(this.props.nodeToDisplay) }
          ]
        }
      ]
    return (

        <Scrollbars renderThumbVertical={props =>
} hideTracksWhenNotNeeded={true}>
          {config.map ((panel, panelIdx) => {
            return (
              <Panel key={panelIdx} collapsible defaultExpanded header={panel.panelName}>
                {panel.properties ? panel.properties : null }
                {panel.buttons.map((panelButton, idx) => this.renderPanelButton(panelButton, idx))}
              </Panel>
            )}
          )}
          <Panel collapsible defaultExpanded header="Details">
            <SideNodeDetails/>
          </Panel>
        </Scrollbars>

    )
  }

  renderPanelButton = (panelButton, idx) => {
    const buttonClass = "espButton right-panel"
    return panelButton.visible == false ? null :
      panelButton.dropzone ?
        <Dropzone key={idx} disableClick={panelButton.disabled == true} onDrop={panelButton.onClick}
                   className={"dropZone " + buttonClass + (panelButton.disabled == true ? " disabled" : "")}>

{panelButton.name}

          </Dropzone>
        :
        <button key={idx} type="button" className={buttonClass} disabled={panelButton.disabled == true}
                onClick={panelButton.onClick}>

 {panelButton.name}
        </button>
  }

  noChosenNode = (node) => {
    return NodeUtils.nodeIsProperties(node) || _.isEmpty(node)
  }

  isRunning = () => this.props.fetchedProcessDetails && (this.props.fetchedProcessDetails.currentlyDeployedAt || []).length > 0

  showProperties = () => {
    this.props.actions.displayModalNodeDetails(this.props.processToDisplay.properties)
  }

  save = () => {
    this.props.actions.toggleModalDialog(Dialogs.types.saveProcess)
  }

  migrate = () => {
    this.props.actions.toggleConfirmDialog(true, DialogMessages.migrate(this.processId(), this.props.featuresSettings.migration.targetEnvironmentId), () => {
      HttpService.migrateProcess(this.processId())
    })
  }

  deploy = () => {
    this.props.actions.toggleConfirmDialog(true, DialogMessages.deploy(this.processId()), () => {
      return HttpService.deploy(this.processId()).then((resp) => {
        //ten kod wykonuje sie nawet kiedy deploy sie nie uda, bo wyzej robimy catch i w przypadku bledu tutaj dostajemy undefined, pomyslec jak ladnie to rozwiazac
        this.fetchProcessDetails()
      })
    })
  }

  stop = () => {
    this.props.actions.toggleConfirmDialog(true, DialogMessages.stop(this.processId()), () => {
      return HttpService.stop(this.processId()).then((resp) => {
        //ten kod wykonuje sie nawet kiedy deploy sie nie uda, bo wyzej robimy catch i w przypadku bledu tutaj dostajemy undefined, pomyslec jak ladnie to rozwiazac
        this.fetchProcessDetails()
      })
    })
  }

  clearHistory = () => {
    return this.props.undoRedoActions.clear()
  }

  fetchProcessDetails = () => {
    this.props.actions.displayCurrentProcessVersion(this.processId())
  }

  processId = () => {
    return (this.props.processToDisplay || {}).id
  }

  versionId = () => this.props.fetchedProcessDetails.processVersionId

  showMetrics = () => {
    browserHistory.push('/metrics/' + this.processId())
  }

  exportProcess = () => {
    HttpService.exportProcess(this.processId(), this.versionId())
  }

  exportProcessToPdf = () => {
    const data = this.props.exportGraph()
    HttpService.exportProcessToPdf(this.processId(), this.versionId(), data)
  }

  generateData = () => {
    this.props.actions.toggleModalDialog(Dialogs.types.generateTestData)
  }

  fetchProcessCounts = () => {
    this.props.actions.toggleModalDialog(Dialogs.types.calculateCounts)
  }

  importProcess = (files) => {
    files.forEach((file)=>
      this.props.actions.importProcess(this.processId(), file)
    );
  }

  testProcess = (files) => {
    files.forEach((file)=>
      this.props.actions.testProcessFromFile(this.processId(), file, this.props.processToDisplay)
    );
  }

  hideRunProcessDetails = () => {
    this.props.actions.hideRunProcessDetails()
  }

  undo = () => {
    //ten if moze powinien byc blisko reducera, tylko jak to ladnie zrobic?
    if (this.props.keyActionsAvailable) {
      this.props.undoRedoActions.undo()
    }
  }

  redo = () => {
    if (this.props.keyActionsAvailable) {
      this.props.undoRedoActions.redo()
    }
  }

  duplicateNode = () => {
    const duplicatedNodePosition = this.props.layout.find(node => node.id === this.props.nodeToDisplay.id) || {position: {x: 0, y: 0}}
    const visiblePosition = {x: duplicatedNodePosition.position.x -200, y: duplicatedNodePosition.position.y}
    this.props.actions.nodeAdded(this.props.nodeToDisplay, visiblePosition)
  }

  deleteNode = () => {
    this.props.actions.deleteNode(this.props.nodeToDisplay.id)
  }

  ungroup = () => {
    this.props.actions.ungroup(this.props.nodeToDisplay)
  }

}

function mapState(state) {
  const fetchedProcessDetails = state.graphReducer.fetchedProcessDetails
  return {
    fetchedProcessDetails: fetchedProcessDetails,
    processToDisplay: state.graphReducer.processToDisplay,
    //TODO: now only needed for duplicate, maybe we can do it somehow differently?
    layout: state.graphReducer.layout || [],

    testCapabilities: state.graphReducer.testCapabilities || {},

    loggedUser: state.settings.loggedUser,
    nothingToSave: ProcessUtils.nothingToSave(state),
    showRunProcessDetails: !_.isEmpty(state.graphReducer.testResults) || !_.isEmpty(state.graphReducer.processCounts),
    keyActionsAvailable: state.ui.allModalsClosed,
    processIsLatestVersion: _.get(fetchedProcessDetails, 'isLatestVersion', false),
    nodeToDisplay: state.graphReducer.nodeToDisplay,
    groupingState: state.graphReducer.groupingState,
    featuresSettings: state.settings.featuresSettings
  };
}

export default connect(mapState, ActionsUtils.mapDispatchWithEspActions)(UserRightPanel);<|endoftext|>


<commit_before>import rootTemplate from './root.html';

export default function(routeHelperProvider, $stateProvider, $urlRouterProvider) {
  'ngInject';

  $urlRouterProvider.otherwise(goToRoot);

  function yAPIResolve(yAPI) {
    'ngInject';
    return yAPI.resolve();
  }

  function makeLayoutFlexElement(elementName) {
    return `<${elementName} flex layout="column"></${elementName}>`;
  }

  routeHelperProvider.setDefaultOptions({
    resolve: { yAPIResolve }
  });

  routeHelperProvider.state('root', {
    url: '',
    templateUrl: rootTemplate
  }, (root) => {

    /* login/signup stuff -------------------------------------------------- */

    root('login', {
      url: '/login',
      template: makeLayoutFlexElement('login-page')
    });

    root('signup', {
      url: '/signup',
      template: makeLayoutFlexElement('signup-page')
    });

    root('logout', {
      url: '/logout',
      template: makeLayoutFlexElement('logout-page')
    });

    /* profile -------------------------------------------------------------- */

    root('profile', {
      url: '/profile',
      template: makeLayoutFlexElement('ui-view')
    }, (profile) => {

      profile('show', {
        url: '/{id:int}',
        template: makeLayoutFlexElement('profile-page')
      });

    });

    /* chat ----------------------------------------------------------------- */

    root('chat', {
      url: '/chat',
      template: makeLayoutFlexElement('y-chat-list'),
      access: {
        requiresLogin: true
      }
    }, (chat) => {

      chat('show', {
        url: '/{id:int}',
        access: {
          requiresLogin: true
        }
      });

      chat('new', {
        url: '/new/:userids',
        template: makeLayoutFlexElement('chat-page'),
        access: {
          requiresLogin: true
        }
      });

    });

    /* users ---------------------------------------------------------------- */

    root('users', {
      url: '/users',
      template: makeLayoutFlexElement('list-users-page'),
      access: {
        requiresLogin: true
      }
    });

    /* items ---------------------------------------------------------------- */

    root('items', {
      url: '/items',
      template: makeLayoutFlexElement('list-items-page')
    }, (items) => {

      items('new', {
        url: '/new',
        template: makeLayoutFlexElement('create-item-page'),
        access: {
          requiresLogin: true
        }
      });

      items('show', {
        url: '/{id:int}',
        template: makeLayoutFlexElement('item-detail-page')
      });

    });

    /* groups --------------------------------------------------------------- */

    root('groups', {
      url: '/groups',
      template: makeLayoutFlexElement('groups')
    }, (groups) => {

      groups('add', {
        url: '/add',
        template: makeLayoutFlexElement('groups-add')
      });

      groups('show', {
        url: '/{id:int}',
        template: makeLayoutFlexElement('group-page')
      });

    });

  });

  function goToRoot($injector) {
    'ngInject';

    /* this is needed because '' and '/' are slightly different... */
    $injector.get('$state').go('root');
  }

}
<commit_msg>Allow adding attributes to route elements<commit_after>import rootTemplate from './root.html';

export default function(routeHelperProvider, $stateProvider, $urlRouterProvider) {
  'ngInject';

  $urlRouterProvider.otherwise(goToRoot);

  function yAPIResolve(yAPI) {
    'ngInject';
    return yAPI.resolve();
  }

  function makeLayoutFlexElement(elementName, attributes) {
    let attrStr = "";
    if (attributes)
      for (const attr in attributes) {
        const value = attributes[attr];
        if (value === false) continue;
        attrStr += ` ${attr}`;
        if (value !== true) attrStr += `="${value}"`;
  }

    return `<${elementName} flex layout="column"${attrStr}></${elementName}>`;
  }

  routeHelperProvider.setDefaultOptions({
    resolve: { yAPIResolve }
  });

  routeHelperProvider.state('root', {
    url: '',
    templateUrl: rootTemplate
  }, (root) => {

    /* login/signup stuff -------------------------------------------------- */

    root('login', {
      url: '/login',
      template: makeLayoutFlexElement('login-page')
    });

    root('signup', {
      url: '/signup',
      template: makeLayoutFlexElement('signup-page')
    });

    root('logout', {
      url: '/logout',
      template: makeLayoutFlexElement('logout-page')
    });

    /* profile -------------------------------------------------------------- */

    root('profile', {
      url: '/profile',
      template: makeLayoutFlexElement('ui-view')
    }, (profile) => {

      profile('show', {
        url: '/{id:int}',
        template: makeLayoutFlexElement('profile-page')
      });

    });

    /* chat ----------------------------------------------------------------- */

    root('chat', {
      url: '/chat',
      template: makeLayoutFlexElement('y-chat-list'),
      access: {
        requiresLogin: true
      }
    }, (chat) => {

      chat('show', {
        url: '/{id:int}',
        access: {
          requiresLogin: true
        }
      });

      chat('new', {
        url: '/new/:userids',
        template: makeLayoutFlexElement('chat-page'),
        access: {
          requiresLogin: true
        }
      });

    });

    /* users ---------------------------------------------------------------- */

    root('users', {
      url: '/users',
      template: makeLayoutFlexElement('list-users-page'),
      access: {
        requiresLogin: true
      }
    });

    /* items ---------------------------------------------------------------- */

    root('items', {
      url: '/items',
      template: makeLayoutFlexElement('list-items-page')
    }, (items) => {

      items('new', {
        url: '/new',
        template: makeLayoutFlexElement('create-item-page'),
        access: {
          requiresLogin: true
        }
      });

      items('show', {
        url: '/{id:int}',
        template: makeLayoutFlexElement('item-detail-page')
      });

    });

    /* groups --------------------------------------------------------------- */

    root('groups', {
      url: '/groups',
      template: makeLayoutFlexElement('groups')
    }, (groups) => {

      groups('add', {
        url: '/add',
        template: makeLayoutFlexElement('groups-add')
      });

      groups('show', {
        url: '/{id:int}',
        template: makeLayoutFlexElement('group-page')
      });

    });

  });

  function goToRoot($injector) {
    'ngInject';

    /* this is needed because '' and '/' are slightly different... */
    $injector.get('$state').go('root');
  }

}
<|endoftext|>


<commit_before>'use strict';

const { throwCommonError } = require('../../../error');
const { evalFilter, mapNodes } = require('../../../filter');

const { handleSchemaFuncs } = require('./functions');

// Evaluate `coll.authorize` filter to a boolean
// Do a partial evaluation, because we do not know the value of `model.*` yet
// Returns partial filter if any.
const evalAuthorize = function ({
  collname,
  clientCollname,
  authorize,
  top,
  userVars,
  schema,
  mInput,
}) {
  const { authorize: authorizeA, vars } = handleSchemaFuncs({
    collname,
    authorize,
    userVars,
    schema,
    mInput,
  });

  const authorizeB = evalFilter({
    filter: authorizeA,
    attrs: vars,
    partialNames: PARTIAL_NAMES_REGEXP,
  });

  checkAuthorize({ clientCollname, authorize: authorizeB, top });

  if (authorizeB === true) { return authorizeB; }

  const authorizeC = mapNodes(authorizeB, removePrefix);
  return authorizeC;
};

// Throw error if authorization filter evaluated to false.
const checkAuthorize = function ({ clientCollname, authorize, top }) {
  if (authorize !== false) { return; }

  throwCommonError({ reason: 'AUTHORIZATION', clientCollname, top });
};

// Remove `model.` prefix in AST's `attrName`
const removePrefix = function ({ attrName, ...node }) {
  if (attrName === undefined) { return node; }

  const attrNameA = attrName.replace(PARTIAL_NAMES_REGEXP, '');
  return { ...node, attrName: attrNameA };
};

// `model.*` is transformed to `authorize`, which is added to
// `args.filter` and checked against `args.data`
const PARTIAL_NAMES_REGEXP = /^model\./;

module.exports = {
  evalAuthorize,
};
<commit_msg>Code simplification<commit_after>'use strict';

const { throwCommonError } = require('../../../error');
const { evalFilter, mapNodes } = require('../../../filter');

const { handleSchemaFuncs } = require('./functions');

// Evaluate `coll.authorize` filter to a boolean
// Do a partial evaluation, because we do not know the value of `model.*` yet
// Returns partial filter if any.
const evalAuthorize = function ({
  collname,
  clientCollname,
  authorize,
  top,
  userVars,
  schema,
  mInput,
}) {
  const { authorize: authorizeA, vars } = handleSchemaFuncs({
    collname,
    authorize,
    userVars,
    schema,
    mInput,
  });

  const authorizeB = evalFilter({
    filter: authorizeA,
    attrs: vars,
    partialNames: PARTIAL_NAMES_REGEXP,
  });

  checkAuthorize({ clientCollname, authorize: authorizeB, top });

  if (authorizeB === true) { return authorizeB; }

  const authorizeC = mapNodes(authorizeB, removePrefix);
  return authorizeC;
};

// Throw error if authorization filter evaluated to false.
const checkAuthorize = function ({ clientCollname, authorize, top }) {
  if (authorize) { return; }

  throwCommonError({ reason: 'AUTHORIZATION', clientCollname, top });
};

// Remove `model.` prefix in AST's `attrName`
const removePrefix = function ({ attrName, ...node }) {
  if (attrName === undefined) { return node; }

  const attrNameA = attrName.replace(PARTIAL_NAMES_REGEXP, '');
  return { ...node, attrName: attrNameA };
};

// `model.*` is transformed to `authorize`, which is added to
// `args.filter` and checked against `args.data`
const PARTIAL_NAMES_REGEXP = /^model\./;

module.exports = {
  evalAuthorize,
};
<|endoftext|>


<commit_before>'use strict'

module.exports = registry => {
  return function () {
    this.seq().obj(
      this.key('point').octstr()
    )
  }
}
<commit_msg>refactor(ECDSAPublicKey): remove<commit_after><|endoftext|>


<commit_before>const fs = require('fs')
const path = require('path')
const exec = require('child_process').exec
const tree = require('strong-npm-ls')
const test = require('tap').test
const bin = path.join(__dirname, '..', 'bin', 'dep.js')
const pkg = path.join(__dirname, 'deps/registry')
const pkgJSON = require(path.join(pkg, 'package.json'))

test((t) => {
  exec(`node ${bin} install --save=prod text-table`, {cwd: pkg}, (err, stdout, stderr) => {
    t.ifError(err, `${pkgJSON.name}: install ran without error`)
    tree.read(pkg, (err, out) => {
      t.ifError(err, `${pkgJSON.name}: tree could be read`)
      const deps = out.dependencies
      t.ok(deps['text-table'], `${pkgJSON.name}: deps are installed`)
      t.end()
    })
  })
})

test((t) => {
  exec(`node ${bin} install --save=dev quack-array`, {cwd: pkg}, (err, stdout, stderr) => {
    t.ifError(err, `${pkgJSON.name}: install ran without error`)
    tree.read(pkg, (err, out) => {
      t.ifError(err, `${pkgJSON.name}: tree could be read`)
      const deps = out.devDependencies
      t.ok(deps['quack-array'], `${pkgJSON.name}: deps are installed`)
      t.end()
    })
  })
})

test((t) => {
  var data = pkgJSON
  delete data.dependencies['text-table']
  delete data.devDependencies
  fs.writeFileSync(path.join(pkg, 'package.json'), JSON.stringify(data, 2, 2) + '\n')
  t.end()
})
<commit_msg>fix(test): fix lint errors<commit_after>const fs = require('fs')
const path = require('path')
const exec = require('child_process').exec
const tree = require('strong-npm-ls')
const test = require('tap').test
const bin = path.join(__dirname, '..', 'bin', 'dep.js')
const pkg = path.join(__dirname, 'deps/registry')
const pkgJSON = require(path.join(pkg, 'package.json'))

test((t) => {
  exec(`node ${bin} install --save=prod text-table`, {cwd: pkg}, (err, stdout, stderr) => {
    t.ifError(err, `${pkgJSON.name}: install ran without error`)
    tree.read(pkg, (err, out) => {
      t.ifError(err, `${pkgJSON.name}: tree could be read`)
      const deps = out.dependencies
      t.ok(deps['text-table'], `${pkgJSON.name}: deps are installed`)
      t.end()
    })
  })
})

test((t) => {
  exec(`node ${bin} install --save=dev quack-array`, {cwd: pkg}, (err, stdout, stderr) => {
    t.ifError(err, `${pkgJSON.name}: install ran without error`)
    tree.read(pkg, (err, out) => {
      t.ifError(err, `${pkgJSON.name}: tree could be read`)
      const deps = out.devDependencies
      t.ok(deps['quack-array'], `${pkgJSON.name}: deps are installed`)
      t.end()
    })
  })
})

test((t) => {
  var data = pkgJSON
  delete data.dependencies['text-table']
  delete data.devDependencies
  fs.writeFileSync(path.join(pkg, 'package.json'), JSON.stringify(data, 2, 2) + '\n')
  t.end()
})
<|endoftext|>