<commit_before>var env = process.env.NODE_ENV || 'development',
    config = require('../../config/config')[env],
    geolocator = require('../util/geolocator'),
    request = require('request'),
    moment = require('moment'),
    User = require('../models/User'),
    Request = require('../models/Request'),
    Trip = require('../models/Trip'),
    ObjectId = require('mongoose').Types.ObjectId;

function listAll(req, res) {
    var id, requests,
        uuid = req.params.uuid,
        userRequests = [];

    // return requests for a particular user
    User.findOne({ _id: uuid })
    .where('active')
    .equals(true)
    .exec(function (err, user) {
        if (err) {
            return res.status(400).json({ message: 'An error occurred with this request. Please try again later.', error: err });
        }

        if (!user) {
            return res.status(404).json({ message: 'User not found.' });
        }

        Request.find({ user: new ObjectId(uuid) })
        .where('active')
        .equals(true)
        .exec(function (err, requests) {
            if (err) {
                return res.status(400).json({ message: 'An error occurred with this request. Please try again later.', error: err });
            }

            if (!requests.length) {
                return res.status(404).json({ message: 'This user has no requests available.' });
            }

            return res.status(200).json({ message: 'Successfully retrieved requests for this user.', response: requests });
        });
    });
}

function createRequest(req, res) {
    var i, user, params, product, products,
        uuid = req.params.uuid,
        data = req.body;

    if (!data || !data.start || !data.start.time  || !data.start.location || !data.productType || !data.end || !data.end.location) {
        res.status(400).json({ error: 'Invalid request!' });
    }

    geolocator(data.start.location, function (err, coords) {
        if (err) {
            return res.status(400).json({ error: err });
        }

        data.start.location = {
            address     : coords.results[0].formatted_address,
            latitude    : coords.results[0].geometry.location.lat,
            longitude   : coords.results[0].geometry.location.lng
        };

        User.findOne({ _id: uuid })
        .where('active')
        .equals(true)
        .exec(function (err, user) {
            if (err) {
                return res.status(400).json({ message: 'An error occurred with this request. Please, try again later.', error: err });
            }

            if (!user) {
                return res.status(400).json({ message: 'This user cannot be found. Please, try again later.'});
            }

            data.uid = uuid;
            params = {
                url: config.uber.base_uber_url + 'products',
                qs: {
                    server_token    : config.uber.server_token,
                    latitude        : data.start.location.latitude,
                    longitude       : data.start.location.longitude
                }
            };

            request.get(params, function (err, status, body) {
                if (err) {
                    return res.status(400).json({ message: 'An error occurred with this request. Please, try again later.'});
                }

                body = JSON.parse(body);
                products = body.products;

                for (i in products) {
                    if (products[i].display_name === data.productType) {
                        product = products[i];
                    }
                }

                data.uber = {
                    id: product.product_id,
                    product: data.productType
                };

                delete data.productType;

                geolocator(data.end.location, function (err, coords) {
                    if (err) {
                        return res.status(400).json({ message: 'An error occurred with this request. Please, try again later.', error: err });
                    }

                    data.end.location = {
                        address     : coords.results[0].formatted_address,
                        latitude    : coords.results[0].geometry.location.lat,
                        longitude   : coords.results[0].geometry.location.lng
                    };

                    // Set the params object for making a call to Uber's Estimate endpoint
                    params.url = config.uber.base_uber_url + 'requests/estimate';
                    params.headers = {
                        'Authorization': 'Bearer ' + user.accessToken,
                        'Content-Type': 'application/json'
                    };

                    params.body = JSON.stringify({
                        product_id          : data.uber.id,
                        start_latitude      : data.start.location.latitude,
                        start_longitude     : data.start.location.longitude,
                        end_latitude        : data.end.destination.latitude,
                        end_longitude       : data.end.destination.longitude
                    });

                    params.qs = {};

                    // Get the estimated duration for the requested trip
                    request.post(params, function (err, status, body)  {
                        var pickup_estimate, time;

                        if (err) {
                            return res.status(400).json({ message: 'An error occurred with estimates calculation. Please, try again later.', error: err });
                        }

                        if (!body) {
                            return res.status(400).json({ message: 'Unable to calculate estimates! Please, try again later!' });
                        }

                        body = JSON.parse(body);

                        if (!body.trip || !body.pickup_estimate) {
                            return res.status(400).json({ message: 'Unable to get estimates! Please, try again later!' });
                        }

                        pickup_estimate = body.pickup_estimate;
                        time = moment(data.start.time).subtract(15, 'minutes').format();

                        data.uber.duration = body.trip.duration_estimate;
                        data.uber.reminder = moment(time).subtract(data.uber.duration, 'seconds').format();

                        new Request(data).save(function (err, request_body) {
                            if (err) {
                                return res.status(400).json({ message: 'An error occurred with this request. Please, try again later.', error: err });
                            }

                            return res.status(200).json({ message: 'Request was successfully created.', response: request_body });
                        });
                    });
                });
            });
        });
    });
}

function listOne(req, res) {
    var user, userTrips, trip, requestData,
        uuid = req.params.uuid,
        id = req.params.req_id,
        params = {};

    // Find the user from the database with the user's id
    User.findOne({ _id: uuid })
    .where('active')
    .equals(true)
    .exec(function (err, user) {
        if (err) {
            return res.status(400).json({ message: 'An error occurred with this request. Please, try again later.', error: err });
        }

        if (!user) {
            return res.status(404).json({ message: 'This user is not available.' });
        }

        Request.findOne({ _id: id })
        .exec(function (err, request_data) {
            if (err) {
                return res.status(400).json({ message: 'An error occurred with this request. Please, try again later.', error: err });
            }

            if (!request_data) {
                return res.status(404).json({ message: 'Request not found.' });
            }

            Trip.findOne({ request: new ObjectId(id) })
            .exec(function (err, trip) {
                if (err) {
                    return res.status(400).json({ message: 'An error occurred with this request. Please, try again later.', error: err });
                }

                if (!trip) {
                    return res.status(200).json({ message: 'Successfully returned request data.', response: request_data });
                }

                // Set the params object for making a call to Uber's Estimate endpoint
                params.url = config.uber.sandbox_base_url + 'requests/' + trip.request_id;
                params.headers = {
                    'Authorization': 'Bearer ' + user.accessToken,
                    'Content-Type': 'application/json'
                };

                request.get(params, function (err, status, body) {
                    if (err) {
                        return res.status(400).json({ error: 'An error occurred with this request. Please, try again later.' });
                    }

                    request_data.trip = JSON.parse(body) || null;

                    return res.json({ message: 'Successfully returned request data.', response: request_data });
                });
            });
        });
    });
}

function deleteOne(req, res) {
    var user, trip, trips,
        params = {},
        uuid = req.params.uuid,
        id  = req.params.id;

    // delete an existing request
    User.findOne({ _id: uuid })
    .where('active')
    .equals(true)
    .exec(function (err, user) {
        if (err) {
            return res.status(400).json({ message: 'An error occurred with this request. Please, try again later.', error: err });
        }

        if (!user) {
            return res.status(404).json({ message: 'This user is not available.' });
        }

        Request.findOne({ _id: new ObjectId(id) })
        .where('active')
        .equals(true)
        .exec(function (err, request_data) {
            if (err) {
                return res.status(400).json({ message: 'An error occurred with this request. Please, try again later.', error: err });
            }

            if (!request_data) {
                return res.status(404).json({ message: 'Reuqest was not found.' });
            }

            Trip.findOne({ request: new ObjectId(id) })
            .exec(function (err, trip) {
                if (err) {
                    return res.status(400).json({ message: 'An error occurred with this request. Please, try again later.', error: err });
                }

                if (!trip) {
                    return res.status(400).json({ message: 'Unable to complete this request. Please, try again later.' });
                }

                params.url = config.uber.sandbox_base_url + 'requests/' + trip.request_id;
                params.headers = {
                    'Authorization': 'Bearer ' + user.accessToken,
                    'Content-Type': 'application/json'
                };

                // Make a delete request to uber's api to delete the request
                request.del(params, function (err, response, body) {
                    if (err) {
                        return res.status(400).json({ message: 'Unable to cancel the trip!', error: err });
                    }

                    if (response.statusCode !== 204) {
                        return res.status(400).json({ message: 'Unable to cancel this request!' });
                    }

                    request_data.active = false;
                    request_data.save(function (err, requestData) {
                        if (err) {
                            return res.status(400).json({ message: 'Unable to cancel this request. Please, try again later.', error: err });
                        }

                        return res.status(200).json({ message: 'Successfully cancelled this request.', response: requestData });
                    });
                });

            });
        });
    });
}

module.exports = {
    create      : createRequest,
    listOne     : listOne,
    listAll     : listAll,
    deleteOne   : deleteOne
};
<commit_msg>Updated requests route to reflect changes in env variables<commit_after>var dotenv = require('node-env-file'),
    request = require('request'),
    moment = require('moment'),
    ObjectId = require('mongoose').Types.ObjectId,
    env = process.env.NODE_ENV || 'development',
    config = require('../../config/config')[env],
    geolocator = require('../util/geolocator'),
    User = require('../models/User'),
    Request = require('../models/Request'),
    Trip = require('../models/Trip');

if (env === 'development') {
    dotenv(__dirname + '/.env');
}

function listAll(req, res) {
    var id, requests,
        uuid = req.params.uuid,
        userRequests = [];

    // return requests for a particular user
    User.findOne({ _id: uuid })
    .where('active')
    .equals(true)
    .exec(function (err, user) {
        if (err) {
            return res.status(400).json({ message: 'An error occurred with this request. Please try again later.', error: err });
        }

        if (!user) {
            return res.status(404).json({ message: 'User not found.' });
        }

        Request.find({ user: new ObjectId(uuid) })
        .where('active')
        .equals(true)
        .exec(function (err, requests) {
            if (err) {
                return res.status(400).json({ message: 'An error occurred with this request. Please try again later.', error: err });
            }

            if (!requests.length) {
                return res.status(404).json({ message: 'This user has no requests available.' });
            }

            return res.status(200).json({ message: 'Successfully retrieved requests for this user.', response: requests });
        });
    });
}

function createRequest(req, res) {
    var i, user, params, product, products,
        uuid = req.params.uuid,
        data = req.body;

    if (!data || !data.start || !data.start.time  || !data.start.location || !data.productType || !data.end || !data.end.location) {
        res.status(400).json({ error: 'Invalid request!' });
    }

    geolocator(data.start.location, function (err, coords) {
        if (err) {
            return res.status(400).json({ error: err });
        }

        data.start.location = {
            address     : coords.results[0].formatted_address,
            latitude    : coords.results[0].geometry.location.lat,
            longitude   : coords.results[0].geometry.location.lng
        };

        User.findOne({ _id: uuid })
        .where('active')
        .equals(true)
        .exec(function (err, user) {
            if (err) {
                return res.status(400).json({ message: 'An error occurred with this request. Please, try again later.', error: err });
            }

            if (!user) {
                return res.status(400).json({ message: 'This user cannot be found. Please, try again later.'});
            }

            data.uid = uuid;
            params = {
                url: config.uber.base_uber_url + 'products',
                qs: {
                    server_token    : process.env.UBER_SERVER_TOKEN,
                    latitude        : data.start.location.latitude,
                    longitude       : data.start.location.longitude
                }
            };

            request.get(params, function (err, status, body) {
                if (err) {
                    return res.status(400).json({ message: 'An error occurred with this request. Please, try again later.'});
                }

                body = JSON.parse(body);
                products = body.products;

                for (i in products) {
                    if (products[i].display_name === data.productType) {
                        product = products[i];
                    }
                }

                data.uber = {
                    id: product.product_id,
                    product: data.productType
                };

                delete data.productType;

                geolocator(data.end.location, function (err, coords) {
                    if (err) {
                        return res.status(400).json({ message: 'An error occurred with this request. Please, try again later.', error: err });
                    }

                    data.end.location = {
                        address     : coords.results[0].formatted_address,
                        latitude    : coords.results[0].geometry.location.lat,
                        longitude   : coords.results[0].geometry.location.lng
                    };

                    // Set the params object for making a call to Uber's Estimate endpoint
                    params.url = config.uber.base_uber_url + 'requests/estimate';
                    params.headers = {
                        'Authorization': 'Bearer ' + user.accessToken,
                        'Content-Type': 'application/json'
                    };

                    params.body = JSON.stringify({
                        product_id          : data.uber.id,
                        start_latitude      : data.start.location.latitude,
                        start_longitude     : data.start.location.longitude,
                        end_latitude        : data.end.destination.latitude,
                        end_longitude       : data.end.destination.longitude
                    });

                    params.qs = {};

                    // Get the estimated duration for the requested trip
                    request.post(params, function (err, status, body)  {
                        var pickup_estimate, time;

                        if (err) {
                            return res.status(400).json({ message: 'An error occurred with estimates calculation. Please, try again later.', error: err });
                        }

                        if (!body) {
                            return res.status(400).json({ message: 'Unable to calculate estimates! Please, try again later!' });
                        }

                        body = JSON.parse(body);

                        if (!body.trip || !body.pickup_estimate) {
                            return res.status(400).json({ message: 'Unable to get estimates! Please, try again later!' });
                        }

                        pickup_estimate = body.pickup_estimate;
                        time = moment(data.start.time).subtract(15, 'minutes').format();

                        data.uber.duration = body.trip.duration_estimate;
                        data.uber.reminder = moment(time).subtract(data.uber.duration, 'seconds').format();

                        new Request(data).save(function (err, request_body) {
                            if (err) {
                                return res.status(400).json({ message: 'An error occurred with this request. Please, try again later.', error: err });
                            }

                            return res.status(200).json({ message: 'Request was successfully created.', response: request_body });
                        });
                    });
                });
            });
        });
    });
}

function listOne(req, res) {
    var user, userTrips, trip, requestData,
        uuid = req.params.uuid,
        id = req.params.req_id,
        params = {};

    // Find the user from the database with the user's id
    User.findOne({ _id: uuid })
    .where('active')
    .equals(true)
    .exec(function (err, user) {
        if (err) {
            return res.status(400).json({ message: 'An error occurred with this request. Please, try again later.', error: err });
        }

        if (!user) {
            return res.status(404).json({ message: 'This user is not available.' });
        }

        Request.findOne({ _id: id })
        .exec(function (err, request_data) {
            if (err) {
                return res.status(400).json({ message: 'An error occurred with this request. Please, try again later.', error: err });
            }

            if (!request_data) {
                return res.status(404).json({ message: 'Request not found.' });
            }

            Trip.findOne({ request: new ObjectId(id) })
            .exec(function (err, trip) {
                if (err) {
                    return res.status(400).json({ message: 'An error occurred with this request. Please, try again later.', error: err });
                }

                if (!trip) {
                    return res.status(200).json({ message: 'Successfully returned request data.', response: request_data });
                }

                // Set the params object for making a call to Uber's Estimate endpoint
                params.url = config.uber.sandbox_base_url + 'requests/' + trip.request_id;
                params.headers = {
                    'Authorization': 'Bearer ' + user.accessToken,
                    'Content-Type': 'application/json'
                };

                request.get(params, function (err, status, body) {
                    if (err) {
                        return res.status(400).json({ error: 'An error occurred with this request. Please, try again later.' });
                    }

                    request_data.trip = JSON.parse(body) || null;

                    return res.json({ message: 'Successfully returned request data.', response: request_data });
                });
            });
        });
    });
}

function deleteOne(req, res) {
    var user, trip, trips,
        params = {},
        uuid = req.params.uuid,
        id  = req.params.id;

    // delete an existing request
    User.findOne({ _id: uuid })
    .where('active')
    .equals(true)
    .exec(function (err, user) {
        if (err) {
            return res.status(400).json({ message: 'An error occurred with this request. Please, try again later.', error: err });
        }

        if (!user) {
            return res.status(404).json({ message: 'This user is not available.' });
        }

        Request.findOne({ _id: new ObjectId(id) })
        .where('active')
        .equals(true)
        .exec(function (err, request_data) {
            if (err) {
                return res.status(400).json({ message: 'An error occurred with this request. Please, try again later.', error: err });
            }

            if (!request_data) {
                return res.status(404).json({ message: 'Reuqest was not found.' });
            }

            Trip.findOne({ request: new ObjectId(id) })
            .exec(function (err, trip) {
                if (err) {
                    return res.status(400).json({ message: 'An error occurred with this request. Please, try again later.', error: err });
                }

                if (!trip) {
                    return res.status(400).json({ message: 'Unable to complete this request. Please, try again later.' });
                }

                params.url = config.uber.sandbox_base_url + 'requests/' + trip.request_id;
                params.headers = {
                    'Authorization': 'Bearer ' + user.accessToken,
                    'Content-Type': 'application/json'
                };

                // Make a delete request to uber's api to delete the request
                request.del(params, function (err, response, body) {
                    if (err) {
                        return res.status(400).json({ message: 'Unable to cancel the trip!', error: err });
                    }

                    if (response.statusCode !== 204) {
                        return res.status(400).json({ message: 'Unable to cancel this request!' });
                    }

                    request_data.active = false;
                    request_data.save(function (err, requestData) {
                        if (err) {
                            return res.status(400).json({ message: 'Unable to cancel this request. Please, try again later.', error: err });
                        }

                        return res.status(200).json({ message: 'Successfully cancelled this request.', response: requestData });
                    });
                });

            });
        });
    });
}

module.exports = {
    create      : createRequest,
    listOne     : listOne,
    listAll     : listAll,
    deleteOne   : deleteOne
};
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';

const customContentStyle = {
  width: '50%',
  maxWidth: 'none',
};

export default class RegisterModal extends Component {
  constructor(){
    super();
    this.state = {
      open: false,
      passVerification: "",
      user: {
        email: "",
        firstName: "",
        lastName: "",
        phone: "+569",
        password: "",
        payment_method: "debit"
      }
    };
    this.handleSubmit = this.handleSubmit.bind(this)
  };

  handleOpen = () => {
    this.setState({open: true});
  };

  handleClose = () => {
    this.setState({open: false});
  };

  handleChangePassVerification = (e) => {
    this.setState({passVerification: e.target.value})
  };

  handleChangeValue = (e) => {
    var u = this.state.user
    if(u.hasOwnProperty(e.target.name)) {
      u[e.target.name] = e.target.value
      this.setState({user: u})
    }
  };

  phoneVerification = () => {
    if(this.state.user.phone.length !== 12) {
      return false
    }
    return true
  };

  arePasswordsEquals = () => {
    if(this.state.user.password !== this.state.passVerification){
      return false
    }
    return true
  };

  isDisabled = () => {
    if (this.state.user.firstName.length === "" || this.state.user.lastName === "" ||
          this.state.user.email === ""     || this.state.user.phone === "" ||
            this.state.user.password === "")
    {
      console.log("missed variable")
      return true
    }

    if (!this.phoneVerification()){
      console.log("invalid phone")
      return true
    }

    if (!this.arePasswordsEquals()){
      console.log("Passwords are not equals")
      return true
    }

    return false
  };

  handleSubmit() {
    console.log(this.state.user, this.state.passVerification)
    return
    fetch('https://automotive-api.herokuapp.com/sign-in', {
          method: 'POST',
          headers: {
            "content-type": "application/json",
            "Accept": "application/json",
          },
          body: JSON.stringify({
            "client": this.state.user }),
    })
  };

  render() {
    const actions = [
      <RaisedButton
        label="Cancelar"
        buttonStyle={{
          borderRadius: 0,
        }}
        style={{
          boxShadow: 0,
          marginRight: 10
        }}
        onTouchTap={this.handleClose}
      />,
      <RaisedButton
        backgroundColor="#FF5252"
        labelColor="#FFF"
        label="Confirmar"
        disabled={false}
        buttonStyle={{
          borderRadius: 0
        }}
        style={{
          boxShadow: 0
        }}
        disabled={this.isDisabled()}
        onClick={this.handleSubmit}
      />,
    ];

    return (

        <FlatButton
          label="Crear Cuenta"
          style={{
            marginLeft: 10
          }}
          onTouchTap={this.handleOpen}
        />
        <Dialog title="NUEVA CUENTA" actions={actions} open={this.state.open} contentStyle={customContentStyle} className="text-center">

              <TextField
                hintText="Escriba su nombre"
                floatingLabelText="Nombre"
                fullWidth={true}
                floatingLabelStyle={{color: '#4c5661'}}
                underlineFocusStyle={{borderColor: '#000'}}
                name = "firstName"
                value={this.state.user.firstName}
                onChange={this.handleChangeValue}
              />
              <TextField
                hintText="Escriba su correo electrónico"
                floatingLabelText="Correo Electrónico"
                fullWidth={true}
                floatingLabelStyle={{color: '#4c5661'}}
                underlineFocusStyle={{borderColor: '#000'}}
                name = "email"
                value={this.state.user.email}
                onChange={this.handleChangeValue}
              />
              <TextField
                hintText="Escriba su contraseña"
                floatingLabelText="Contraseña"
                type="password"
                fullWidth={true}
                floatingLabelStyle={{color: '#4c5661'}}
                underlineFocusStyle={{borderColor: '#000'}}
                name = "password"
                value={this.state.user.password}
                onChange={this.handleChangeValue}
              />

              <TextField
                hintText="Escriba sus apellidos"
                floatingLabelText="Apellidos"
                fullWidth={true}
                floatingLabelStyle={{color: '#4c5661'}}
                underlineFocusStyle={{borderColor: '#000'}}
                name = "lastName"
                value={this.state.user.lastName}
                onChange={this.handleChangeValue}
              />
              <TextField
                hintText="Escriba su número de contacto"
                floatingLabelText="Número Teléfonico"
                fullWidth={true}
                floatingLabelStyle={{color: '#4c5661'}}
                underlineFocusStyle={{borderColor: '#000'}}
                name = "phone"
                value={this.state.user.phone}
                onChange={this.handleChangeValue}
              />
              <TextField
                hintText="Repita su contraseña"
                floatingLabelText="Repita Contraseña"
                type="password"
                fullWidth={true}
                floatingLabelStyle={{color: '#4c5661'}}
                underlineFocusStyle={{borderColor: '#000'}}
                name = "passVerification"
                value={this.state.passVerification}
                onChange={this.handleChangePassVerification}
              />

        </Dialog>

    );
  }
}
<commit_msg>Added email verification<commit_after>import React, {Component} from 'react';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';

const customContentStyle = {
  width: '50%',
  maxWidth: 'none',
};

export default class RegisterModal extends Component {
  constructor(){
    super();
    this.state = {
      open: false,
      passVerification: "",
      user: {
        email: "",
        firstName: "",
        lastName: "",
        phone: "+569",
        password: "",
        payment_method: "debit"
      }
    };
    this.handleSubmit = this.handleSubmit.bind(this)
  };

  handleOpen = () => {
    this.setState({open: true});
  };

  handleClose = () => {
    this.setState({open: false});
  };

  handleChangePassVerification = (e) => {
    this.setState({passVerification: e.target.value})
  };

  handleChangeValue = (e) => {
    var u = this.state.user
    if(u.hasOwnProperty(e.target.name)) {
      u[e.target.name] = e.target.value
      this.setState({user: u})
    }
  };

  emailVerification = () => {
    const reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

    if (reg.test(this.state.user.email) == false) {
        return false;
    }

    return true;
  }

  phoneVerification = () => {
    if(this.state.user.phone.length !== 12) {
      return false
    }
    return true
  };

  arePasswordsEquals = () => {
    if(this.state.user.password !== this.state.passVerification){
      return false
    }
    return true
  };

  isDisabled = () => {
    if (this.state.user.firstName.length === "" || this.state.user.lastName === "" ||
          this.state.user.email === ""     || this.state.user.phone === "" ||
            this.state.user.password === "")
    {
      console.log("missed variable")
      return true
    }

    if (!this.emailVerification()){
      console.log("invalid email")
      return true
    }

    if (!this.phoneVerification()){
      console.log("invalid phone")
      return true
    }

    if (!this.arePasswordsEquals()){
      console.log("Passwords are not equals")
      return true
    }

    return false
  };

  handleSubmit() {
    console.log(this.state.user, this.state.passVerification)
    return
    fetch('https://automotive-api.herokuapp.com/sign-in', {
          method: 'POST',
          headers: {
            "content-type": "application/json",
            "Accept": "application/json",
          },
          body: JSON.stringify({
            "client": this.state.user }),
    })
  };

  render() {
    const actions = [
      <RaisedButton
        label="Cancelar"
        buttonStyle={{
          borderRadius: 0,
        }}
        style={{
          boxShadow: 0,
          marginRight: 10
        }}
        onTouchTap={this.handleClose}
      />,
      <RaisedButton
        backgroundColor="#FF5252"
        labelColor="#FFF"
        label="Confirmar"
        buttonStyle={{
          borderRadius: 0
        }}
        style={{
          boxShadow: 0
        }}
        disabled={this.isDisabled()}
        onClick={this.handleSubmit}
      />,
    ];

    return (

        <FlatButton
          label="Crear Cuenta"
          style={{
            marginLeft: 10
          }}
          onTouchTap={this.handleOpen}
        />
        <Dialog title="NUEVA CUENTA" actions={actions} open={this.state.open} contentStyle={customContentStyle} className="text-center">

              <TextField
                hintText="Escriba su nombre"
                floatingLabelText="Nombre"
                fullWidth={true}
                floatingLabelStyle={{color: '#4c5661'}}
                underlineFocusStyle={{borderColor: '#000'}}
                name = "firstName"
                value={this.state.user.firstName}
                onChange={this.handleChangeValue}
              />
              <TextField
                hintText="Escriba su correo electrónico"
                floatingLabelText="Correo Electrónico"
                fullWidth={true}
                floatingLabelStyle={{color: '#4c5661'}}
                underlineFocusStyle={{borderColor: '#000'}}
                name = "email"
                value={this.state.user.email}
                onChange={this.handleChangeValue}
              />
              <TextField
                hintText="Escriba su contraseña"
                floatingLabelText="Contraseña"
                type="password"
                fullWidth={true}
                floatingLabelStyle={{color: '#4c5661'}}
                underlineFocusStyle={{borderColor: '#000'}}
                name = "password"
                value={this.state.user.password}
                onChange={this.handleChangeValue}
              />

              <TextField
                hintText="Escriba sus apellidos"
                floatingLabelText="Apellidos"
                fullWidth={true}
                floatingLabelStyle={{color: '#4c5661'}}
                underlineFocusStyle={{borderColor: '#000'}}
                name = "lastName"
                value={this.state.user.lastName}
                onChange={this.handleChangeValue}
              />
              <TextField
                hintText="Escriba su número de contacto"
                floatingLabelText="Número Teléfonico"
                fullWidth={true}
                floatingLabelStyle={{color: '#4c5661'}}
                underlineFocusStyle={{borderColor: '#000'}}
                name = "phone"
                value={this.state.user.phone}
                onChange={this.handleChangeValue}
              />
              <TextField
                hintText="Repita su contraseña"
                floatingLabelText="Repita Contraseña"
                type="password"
                fullWidth={true}
                floatingLabelStyle={{color: '#4c5661'}}
                underlineFocusStyle={{borderColor: '#000'}}
                name = "passVerification"
                value={this.state.passVerification}
                onChange={this.handleChangePassVerification}
              />

        </Dialog>

    );
  }
}
<|endoftext|>


<commit_before>import BorderPropTypes from '../../propTypes/BorderPropTypes';
import ColorPropType from '../../propTypes/ColorPropType';
import ImageResizeMode from './ImageResizeMode';
import LayoutPropTypes from '../../propTypes/LayoutPropTypes';
import { PropTypes } from 'react';
import TransformPropTypes from '../../propTypes/TransformPropTypes';

const hiddenOrVisible = PropTypes.oneOf([ 'hidden', 'visible' ]);

module.exports = {
  ...BorderPropTypes,
  ...LayoutPropTypes,
  ...TransformPropTypes,
  backfaceVisibility: hiddenOrVisible,
  backgroundColor: ColorPropType,
  resizeMode: PropTypes.oneOf(Object.keys(ImageResizeMode)),
  /**
   * @platform web
   */
  boxShadow: PropTypes.string,
  opacity: PropTypes.number,
  overflow: hiddenOrVisible,
  /**
   * @platform web
   */
  visibility: hiddenOrVisible
};
<commit_msg>[fix] add shadow style props to Image styles<commit_after>import BorderPropTypes from '../../propTypes/BorderPropTypes';
import ColorPropType from '../../propTypes/ColorPropType';
import ImageResizeMode from './ImageResizeMode';
import LayoutPropTypes from '../../propTypes/LayoutPropTypes';
import { PropTypes } from 'react';
import ShadowPropTypes from '../../propTypes/ShadowPropTypes';
import TransformPropTypes from '../../propTypes/TransformPropTypes';

const hiddenOrVisible = PropTypes.oneOf([ 'hidden', 'visible' ]);

module.exports = {
  ...BorderPropTypes,
  ...LayoutPropTypes,
  ...ShadowPropTypes,
  ...TransformPropTypes,
  backfaceVisibility: hiddenOrVisible,
  backgroundColor: ColorPropType,
  resizeMode: PropTypes.oneOf(Object.keys(ImageResizeMode)),
  /**
   * @platform web
   */
  boxShadow: PropTypes.string,
  opacity: PropTypes.number,
  overflow: hiddenOrVisible,
  /**
   * @platform web
   */
  visibility: hiddenOrVisible
};
<|endoftext|>


<commit_before>import {QueryBuilder} from 'react-querybuilder';
import React, {Component} from 'react';
import { Button, Glyphicon, Well, Modal, Tabs, Tab, Grid, Row, Col, Alert, FormGroup, Checkbox, ControlLabel, FormControl, HelpBlock} from 'react-bootstrap';
import CreateDataViewDialog from '../Dialogs/createDataView';
import CreateAlertViewDialog from '../Dialogs/createAlertView';
const {Footer, Body, Header, Title} = Modal;
/* eslint-disable react/prop-types*/

const fields = [
    { name: 'location', label: 'Location', value: {} },
    { name: 'time', label: 'Time' },
    { name: 'keyword', label: 'Keyword' },
    { name: 'user', label: 'User' },
    { name: 'source', label: 'Source' },
    { name: 'hasMedia', label: 'Has Attachment', value: false }
];

const CSSClass = {

    combinators: 'form-control', // <select> control for combinators
    addRule: 'btn btn-primary', // <button> to add a Rule
    addGroup: 'btn btn-primary', // <button> to add a RuleGroup
    removeGroup: 'btn btn-danger', // <button> to remove a RuleGroup

    rule: String, //
 containing the Rule
    fields: 'form-control', // <select> control for fields
    operators: 'form-control', // <select> control for operators
    value: 'form-control', // <input> for the field value
    removeRule: 'btn btn-danger' // <button> to remove a Rule
};

function getEditor({field, operator, value, onChange}) {
    if (field == 'hasMedia') {
        // return empty control - we don't need another
        return (

        );
    }
    if (field == 'source') {
        return (
            <select className='form-control'>
                <option value="any">Any</option>
                <option value="twitter">Twitter</option>
                <option value="facebook">Facebook</option>
                <option value="instagram">Instagram</option>
            </select>
        )
    }
    if (field == 'time' && operator == 'last') {
        return (
            <select className='form-control'>
                <option value="last-15m">15 mins</option>
                <option value="last-h">1 hour</option>
                <option value="last-12h">12 hours</option>
                <option value="last-day">Day</option>
                <option value="last-week">Week</option>
            </select>
        )
    }
    if (field == 'keyword' && operator == 'equals') {
        return (
            <select className='form-control'>
                <option value="k-a">keyword-a</option>
                <option value="k-b">keyword-b</option>
                <option value="k-c">keyword-c</option>
                <option value="k-d">keyword-d</option>
                <option value="k-e">keyword-e</option>
            </select>
        )
    }
    if (field == 'keyword' && operator == 'savedList') {
        return (
            <select className='form-control'>
                <option value="s-a">Stores</option>
                <option value="s-b">Parties</option>
                <option value="s-c">Holidays</option>
                <option value="s-d">Sports</option>
                <option value="s-e">Schools</option>
            </select>
        )
    }
    if (field == 'location') {
        if (operator == 'na')
            return (

            );
        else return (
            <select className='form-control'>
                <option value="global">Global</option>
                <option value="map1">Current Viewport (Map1) </option>
                <optgroup label="System">
                    <option value="l-a">London Airports</option>
                    <option value="l-b">London Boroughs</option>
                </optgroup>
                <optgroup label="Locals">
                    <option value="m25">M25</option>
                    <option value="in-cafe">Internet Cafes</option>
                </optgroup>
            </select>
        )
    }
    return (
        <input type="text" className="form-control" style={{ width: '30%', minWidth: '120px', display: 'inline-block' }}/>
    )
}

function getOperators(field) {
    if (field == 'location') {
        return [{ name: 'within', label: 'within' }, { name: 'na', label: 'n/a' }];
    } else if (field == 'hasMedia') {
        return [{ name: 'true', label: 'Yes' }, { name: 'false', label: 'no' }];
    } else if (field == 'keyword') {
        return [{ name: 'true', label: 'Contains' }, { name: 'false', label: 'Doesn\'t contain' },
            { name: 'equals', label: 'Equals' },{ name: 'savedList', label: 'Saved list' } ];
    } else if (field == 'time') {
        return [{ name: 'before', label: 'Before' }, { name: 'after', label: 'After' },
            { name: 'between', label: 'Between' }, { name: 'last', label: 'Last' }];
    } else return null;

}

const startQuery = {
    combinator: 'and',
    id: '111',
    rules: [
        {
            id: '222',
            field: 'firstName',
            value: 'Test',
            operator: '='
        }
    ]
};

export default class QueryBuilderWindow extends Component {

    constructor(prop) {
        super(prop);
        this.state = { showModalView: false, showModalAlert: false };
        this.close = this.close.bind(this);
        this.open = this.open.bind(this);
         this.openAlert = this.openAlert.bind(this);
    }

    close() {
        this.setState({ showModalView: false });
        this.setState({ showModalAlert: false })
    }

    open() {
        this.setState({ showModalView: true });
    }
    openAlert() {
        this.setState({ showModalAlert: true });
    }
    render() {
        const {showModalView, showModalAlert} = this.state;
        return (

                    <Button bsStyle='danger'  ><Glyphicon glyph="remove-sign" /> </Button>
                       <Button bsStyle='primary'  ><Glyphicon glyph="question-sign" /> </Button>

                            <Well  >
                                Create your search query
                                <QueryBuilder query={startQuery} fields={fields}
                                    onQueryChange={logQuery} getEditor={getEditor} getOperators={getOperators} controlClassnames= {CSSClass}/>
                            </Well>

                    <Button bsStyle='danger' onClick={this.openAlert}  ><Glyphicon glyph="alert" />  Create Alert </Button>
                    <Button bsStyle='primary' onClick={this.open} ><Glyphicon glyph="eye-open" /> Show in Data View  </Button>

                <Modal show={showModalView} onHide={this.close}>

                        <Title>Create Data View</Title>

                        <CreateDataViewDialog/>

                        <Button  bsStyle="success"onClick={this.close}>Confirm</Button>
                        <Button onClick={this.close}>Close</Button>

                </Modal>
                <Modal show={showModalAlert} onHide={this.close}>

                        <Title>Create Alert</Title>

                        <CreateAlertViewDialog/>

                        <Button  bsStyle="success"onClick={this.close}>Confirm</Button>
                        <Button onClick={this.close}>Close</Button>

                </Modal>

)
    }
}

function logQuery(query) {
    //console.log(query);
}<commit_msg>#39 Change Icon and button Color<commit_after>import {QueryBuilder} from 'react-querybuilder';
import React, {Component} from 'react';
import { Button, Glyphicon, Well, Modal, Tabs, Tab, Grid, Row, Col, Alert, FormGroup, Checkbox, ControlLabel, FormControl, HelpBlock} from 'react-bootstrap';
import CreateDataViewDialog from '../Dialogs/createDataView';
import CreateAlertViewDialog from '../Dialogs/createAlertView';
const {Footer, Body, Header, Title} = Modal;
/* eslint-disable react/prop-types*/

const fields = [
    { name: 'location', label: 'Location', value: {} },
    { name: 'time', label: 'Time' },
    { name: 'keyword', label: 'Keyword' },
    { name: 'user', label: 'User' },
    { name: 'source', label: 'Source' },
    { name: 'hasMedia', label: 'Has Attachment', value: false }
];

const CSSClass = {

    combinators: 'form-control', // <select> control for combinators
    addRule: 'btn btn-primary', // <button> to add a Rule
    addGroup: 'btn btn-primary', // <button> to add a RuleGroup
    removeGroup: 'btn btn-danger', // <button> to remove a RuleGroup

    rule: String, //
 containing the Rule
    fields: 'form-control', // <select> control for fields
    operators: 'form-control', // <select> control for operators
    value: 'form-control', // <input> for the field value
    removeRule: 'btn btn-danger' // <button> to remove a Rule
};

function getEditor({field, operator, value, onChange}) {
    if (field == 'hasMedia') {
        // return empty control - we don't need another
        return (

        );
    }
    if (field == 'source') {
        return (
            <select className='form-control'>
                <option value="any">Any</option>
                <option value="twitter">Twitter</option>
                <option value="facebook">Facebook</option>
                <option value="instagram">Instagram</option>
            </select>
        )
    }
    if (field == 'time' && operator == 'last') {
        return (
            <select className='form-control'>
                <option value="last-15m">15 mins</option>
                <option value="last-h">1 hour</option>
                <option value="last-12h">12 hours</option>
                <option value="last-day">Day</option>
                <option value="last-week">Week</option>
            </select>
        )
    }
    if (field == 'keyword' && operator == 'equals') {
        return (
            <select className='form-control'>
                <option value="k-a">keyword-a</option>
                <option value="k-b">keyword-b</option>
                <option value="k-c">keyword-c</option>
                <option value="k-d">keyword-d</option>
                <option value="k-e">keyword-e</option>
            </select>
        )
    }
    if (field == 'keyword' && operator == 'savedList') {
        return (
            <select className='form-control'>
                <option value="s-a">Stores</option>
                <option value="s-b">Parties</option>
                <option value="s-c">Holidays</option>
                <option value="s-d">Sports</option>
                <option value="s-e">Schools</option>
            </select>
        )
    }
    if (field == 'location') {
        if (operator == 'na')
            return (

            );
        else return (
            <select className='form-control'>
                <option value="global">Global</option>
                <option value="map1">Current Viewport (Map1) </option>
                <optgroup label="System">
                    <option value="l-a">London Airports</option>
                    <option value="l-b">London Boroughs</option>
                </optgroup>
                <optgroup label="Locals">
                    <option value="m25">M25</option>
                    <option value="in-cafe">Internet Cafes</option>
                </optgroup>
            </select>
        )
    }
    return (
        <input type="text" className="form-control" style={{ width: '30%', minWidth: '120px', display: 'inline-block' }}/>
    )
}

function getOperators(field) {
    if (field == 'location') {
        return [{ name: 'within', label: 'within' }, { name: 'na', label: 'n/a' }];
    } else if (field == 'hasMedia') {
        return [{ name: 'true', label: 'Yes' }, { name: 'false', label: 'no' }];
    } else if (field == 'keyword') {
        return [{ name: 'true', label: 'Contains' }, { name: 'false', label: 'Doesn\'t contain' },
            { name: 'equals', label: 'Equals' },{ name: 'savedList', label: 'Saved list' } ];
    } else if (field == 'time') {
        return [{ name: 'before', label: 'Before' }, { name: 'after', label: 'After' },
            { name: 'between', label: 'Between' }, { name: 'last', label: 'Last' }];
    } else return null;

}

const startQuery = {
    combinator: 'and',
    id: '111',
    rules: [
        {
            id: '222',
            field: 'firstName',
            value: 'Test',
            operator: '='
        }
    ]
};

export default class QueryBuilderWindow extends Component {

    constructor(prop) {
        super(prop);
        this.state = { showModalView: false, showModalAlert: false };
        this.close = this.close.bind(this);
        this.open = this.open.bind(this);
         this.openAlert = this.openAlert.bind(this);
    }

    close() {
        this.setState({ showModalView: false });
        this.setState({ showModalAlert: false })
    }

    open() {
        this.setState({ showModalView: true });
    }
    openAlert() {
        this.setState({ showModalAlert: true });
    }
    render() {
        const {showModalView, showModalAlert} = this.state;
        return (

                    <Button bsStyle='default'  ><Glyphicon glyph="cog" /> </Button>
                       <Button bsStyle='info'  ><Glyphicon glyph="question-sign" /> </Button>

                            <Well  >
                                Create your search query
                                <QueryBuilder query={startQuery} fields={fields}
                                    onQueryChange={logQuery} getEditor={getEditor} getOperators={getOperators} controlClassnames= {CSSClass}/>
                            </Well>

                    <Button bsStyle='danger' onClick={this.openAlert}  ><Glyphicon glyph="alert" />  Create Alert </Button>
                    <Button bsStyle='primary' onClick={this.open} ><Glyphicon glyph="eye-open" /> Show in Data View  </Button>

                <Modal show={showModalView} onHide={this.close}>

                        <Title>Create Data View</Title>

                        <CreateDataViewDialog/>

                        <Button  bsStyle="success"onClick={this.close}>Confirm</Button>
                        <Button onClick={this.close}>Close</Button>

                </Modal>
                <Modal show={showModalAlert} onHide={this.close}>

                        <Title>Create Alert</Title>

                        <CreateAlertViewDialog/>

                        <Button  bsStyle="success"onClick={this.close}>Confirm</Button>
                        <Button onClick={this.close}>Close</Button>

                </Modal>

)
    }
}

function logQuery(query) {
    //console.log(query);
}<|endoftext|>


<commit_before>import React from "react";
import PropTypes from "prop-types";
import { Selection, Line } from "victory-core";
import { assign, defaults, isEqual, isFunction } from "lodash";

const toRange = (props, domain) => {
  const scale = props.scale[props.dimension];
  return [scale(Math.min(...domain)), scale(Math.max(...domain))];
};

const toDomain = (props, range) => {
  const scale = props.scale[props.dimension];
  return [scale.invert(Math.min(...range)), scale.invert(Math.max(...range))];
};

const getFullRange = (props) => {
  const scale = props.scale[props.dimension];
  return scale.range();
};

const getFullDomain = (props) => {
  const scale = props.scale[props.dimension];
  return scale.domain();
};

const getHandles = (props, range) => {
  const { handleWidth } = props;
  const min = Math.min(...range);
  const max = Math.max(...range);
  return {
    min: [min - handleWidth, min + handleWidth], max: [max - handleWidth, max + handleWidth]
  };
};

const withinBound = (value, bound) => {
  return value >= Math.min(...bound) && value <= Math.max(...bound);
};

const getMinimumDomain = () => {
  return [0, 1 / Number.MAX_SAFE_INTEGER];
};

const getCurrentDomain = (props) => {
  const { currentDomain, cachedBrushDomain, brushDomain } = props;
  // if (brushDomain && !isEqual(brushDomain, cachedBrushDomain)) {
  //   return brushDomain;
  // }
  return currentDomain || brushDomain || getFullDomain();
};

const panBox = (props, position) => {
  const { brushDomain, startPosition, currentDomain } = props;
  const range = currentDomain ? toRange(props, currentDomain) : toRange(props, brushDomain);
  const fullRange = getFullRange(props);
  const size = Math.abs(range[1] - range[0]);
  const globalMin = Math.min(...fullRange);
  const globalMax = Math.max(...fullRange);
  const delta = startPosition ? startPosition - position : 0;
  const min = Math.min(...range) - delta;
  const max = Math.max(...range) - delta;
  const constrainedMin = min > globalMax - size ? globalMax - size : Math.max(min, globalMin);
  const constrainedMax = max < globalMin + size ? globalMin + size : Math.min(max, globalMax);
  return [constrainedMin, constrainedMax];
};

export default class VictoryBrushLine extends React.Component {
  static propTypes = {
    allowDrag: PropTypes.bool,
    allowResize: PropTypes.bool,
    brushAreaComponent: PropTypes.element,
    brushAreaStyle: PropTypes.object,
    brushComponent: PropTypes.element,
    brushDimension: PropTypes.oneOf(["x", "y"]),
    brushDomain: PropTypes.array,
    brushStyle: PropTypes.object,
    brushWidth: PropTypes.number,
    className: PropTypes.string,
    dimension: PropTypes.oneOf(["x", "y"]),
    events: PropTypes.object,
    groupComponent: PropTypes.element,
    handleComponent: PropTypes.element,
    handleStyle: PropTypes.object,
    handleWidth: PropTypes.number,
    lineComponent: PropTypes.element,
    onBrushDomainChange: PropTypes.func,
    scale: PropTypes.object,
    style: PropTypes.object,
    type: PropTypes.string
  };

  static defaultProps = {
    allowDrag: true,
    allowResize: true,
    brushAreaComponent: <rect/>,
    brushAreaStyle: {
      stroke: "transparent",
      fill: "black",
      fillOpacity: 0.1
    },
    brushComponent: <rect/>,
    brushStyle: {
      stroke: "black",
      fill: "black",
      cursor: "move",
      opacity: 0.15
    },
    brushWidth: 10,
    groupComponent: <g/>,
    handleComponent: <rect/>,
    handleStyle: {
      stroke: "none",
      fill: "none"
    },
    handleWidth: 10,
    lineComponent: <Line/>
  };

  static defaultEvents = function (props) {
    return [{
      target: props.type,
      eventHandlers: {
        onMouseDown: (evt, targetProps) => {
          evt.preventDefault();
          const {
            scale, allowResize, allowDrag, dimension, brushDomain
          } = targetProps;

          // Don't trigger events for static brushes
          if (!allowResize && !allowDrag) {
            return [];
          }

          const fullDomain = targetProps.fullDomain || scale[dimension].domain();
          const currentDomain = getCurrentDomain(targetProps);
          const position = Selection.getSVGEventCoordinates(evt)[dimension];
          const range = toRange(targetProps, currentDomain);
          const handles = getHandles(targetProps, range);

          const activeHandles = allowResize &&
            (withinBound(position, handles.min)) || (withinBound(position, handles.max));
          // If the event occurs in any of the handle regions, start a resize
          if (activeHandles) {
            return [{
              mutation: () => {
                return ({
                  isSelecting: true, currentDomain, cachedBrushDomain: brushDomain,
                  startPosition: position
                });
              }
            }];
          } else if (withinBound(position, range) && !isEqual(fullDomain, currentDomain)) {
            // if the event occurs within a selected region start a panning event, unless the whole
            // domain is selected
            return [{
              mutation: () => ({
                isPanning: allowDrag, startPosition: position,
                currentDomain, cachedBrushDomain: brushDomain
              })
            }];
          } else {
            // if the event occurs outside the region, or if the whole domain is selected,
            // start a new selection
            return allowResize ? [{
              mutation: () => ({
                isSelecting: allowResize,
                currentDomain: getMinimumDomain(),
                cachedBrushDomain: brushDomain,
                startPosition: position
              })
            }] : [];
          }
        },
        onMouseMove: (evt, targetProps) => { // eslint-disable-line max-statements, complexity
          if (!targetProps.isPanning && !targetProps.isSelecting) {
            return [];
          }
          const {
            isPanning, isSelecting, allowResize, allowDrag, dimension, onBrushDomainChange,
            cachedBrushDomain
          } = targetProps;
          const position = Selection.getSVGEventCoordinates(evt)[dimension];
          if (allowDrag && isPanning) {
            const fullRange = getFullRange(targetProps);
            const range = panBox(targetProps, position);
            const currentDomain = toDomain(targetProps, range);
            const startPosition = Math.max(...range) >= Math.max(...fullRange) ||
              Math.min(...range) <= Math.min(...fullRange) ?
              targetProps.startPosition : position;
            const mutatedProps = {
              startPosition, isPanning: true, currentDomain, cachedBrushDomain
            };

            if (isFunction(onBrushDomainChange)) {
              onBrushDomainChange(currentDomain, defaults({}, mutatedProps, targetProps));
            }
            return [{
              mutation: () => mutatedProps
            }];
          } else if (allowResize && isSelecting) {
            const range = toRange(targetProps, targetProps.currentDomain);
            const handles = getHandles(targetProps, range);
            const min = withinBound(position, handles.max) ?
              Math.min(...range) : Math.min(targetProps.startPosition, position);
            const max = withinBound(position, handles.min) ?
              Math.max(...range) : Math.max(targetProps.startPosition, position);
            const currentDomain = toDomain(targetProps, [min, max]);
            const mutatedProps = {
              currentDomain, startPosition: targetProps.startPosition,
              isSelecting, cachedBrushDomain
            };
            if (isFunction(onBrushDomainChange)) {
              onBrushDomainChange(currentDomain, defaults({}, mutatedProps, targetProps));
            }
            return [{
              mutation: () => (mutatedProps)
            }];
          }
          return [];
        },
        onMouseUp(evt, targetProps) {
          const { onBrushDomainChange, currentDomain, allowResize } = targetProps;
          // if the mouse hasn't moved since a mouseDown event, select the whole domain region
          const mutatedProps = {
            isPanning: false, isSelecting: false, currentDomain, cachedBrushDomain: currentDomain,
            brushDomain: currentDomain,
            startPosition: null
          };
          if (allowResize && isFunction(onBrushDomainChange)) {
            onBrushDomainChange(currentDomain, defaults({}, mutatedProps, targetProps));
          }
          return [{
            mutation: () => mutatedProps
          }];
        },
        onMouseLeave(evt, targetProps) {
          const { currentDomain, cachedBrushDomain } = targetProps;
          return [{
            mutation: () => ({
              isPanning: false, isSelecting: false, currentDomain, cachedBrushDomain,
              startPosition: null
            })
          }];
        }
      }
    }];
  };

  // componentWillMount() {
  //   this.style = this.getStyle(this.props);
  // }

  // shouldComponentUpdate(nextProps) {
    // const { className, datum, x1, x2, y1, y2 } = this.props;
    // const style = this.getStyle(nextProps);
    // if (!Collection.allSetsEqual([
    //   [className, nextProps.className],
    //   [x1, nextProps.x1],
    //   [x2, nextProps.x2],
    //   [y1, nextProps.y1],
    //   [y2, nextProps.y2],
    //   [style, this.style],
    //   [datum, nextProps.datum]
    // ])) {
    //   this.style = style;
    //   return true;
    // }
    // return false;
  // }

  // getStyle(props) {
  //   const { style, datum, active } = props;
  //   return Helpers.evaluateStyle(assign({ stroke: "black" }, style), datum, active);
  // }

  getRectDimensions(props, domain) {
    const { dimension, brushWidth } = props;
    domain = domain || getCurrentDomain(props);
    const range = toRange(props, domain);
    const coordinates = dimension === "x" ?
      { y1: props.y1, y2: props.y2, x1: Math.min(...range), x2: Math.max(...range) } :
      { x1: props.x1, x2: props.x2, y1: Math.min(...range), y2: Math.max(...range) };
    const { x1, x2, y1, y2 } = coordinates;
    const offset = {
      x: dimension === "x" ? 0 : brushWidth / 2,
      y: dimension === "y" ? 0 : brushWidth / 2
    };

    const x = Math.min(x1, x2) - offset.x;
    const y = Math.min(y1, y2) - offset.y;
    const width = Math.max(x1, x2) + offset.x - x;
    const height = Math.max(y1, y2) + offset.y - y;
    return { x, y, width, height };
  }

  getHandleDimensions(props) {
    const { dimension, brushWidth, handleWidth, x1, x2, y1, y2 } = props;
    const domain = getCurrentDomain(props);
    const range = toRange(props, domain);
    const defaultX = Math.min(x1, x2) - (brushWidth / 2);
    const defaultY = Math.min(y1, y2) - (brushWidth / 2);
    const x = {
      min: dimension === "x" ? Math.min(...range) : defaultX,
      max: dimension === "x" ? Math.max(...range) - handleWidth : defaultX
    };
    const y = {
      min: dimension === "y" ? Math.max(...range) - handleWidth : defaultY,
      max: dimension === "y" ? Math.min(...range) : defaultY
    };
    const width = dimension === "x" ? handleWidth : brushWidth;
    const height = dimension === "x" ? brushWidth : handleWidth;

    return {
      min: { x: x.min, y: y.min, width, height },
      max: { x: x.max, y: y.max, width, height }
    };
  }

  renderHandles(props) {
    const { handleComponent, handleStyle, dimension } = props;
    const handleDimensions = this.getHandleDimensions(props);
    const cursor = dimension === "x" ? "ew-resize" : "ns-resize";
    const style = assign({ cursor }, handleStyle);
    return [
      React.cloneElement(handleComponent, assign({ key: "min", style }, handleDimensions.min)),
      React.cloneElement(handleComponent, assign({ key: "max", style }, handleDimensions.max))
    ];
  }

  renderBrush(props) {
    const { brushComponent, brushStyle } = props;
    const rectDimensions = this.getRectDimensions(props);
    const brushProps = assign({ style: brushStyle }, rectDimensions);
    return React.cloneElement(brushComponent, brushProps);
  }

  renderBrushArea(props) {
    const { brushAreaComponent, brushAreaStyle } = props;
    const rectDimensions = this.getRectDimensions(props, getFullDomain(props));
    const brushAreaProps = assign({ style: brushAreaStyle }, rectDimensions);
    return React.cloneElement(brushAreaComponent, brushAreaProps);
  }

  renderLine(props) {
    return <Line {...props}/>;
  }

  render() {
    return (
      <g {...this.props.events}>
        {this.renderLine(this.props)}
        {this.renderBrushArea(this.props)}
        {this.renderBrush(this.props)}
        {this.renderHandles(this.props)}
      </g>
    );
  }
}
<commit_msg>clean up resize logic<commit_after>import React from "react";
import PropTypes from "prop-types";
import { Selection, Line } from "victory-core";
import { assign, defaults, isEqual, isFunction } from "lodash";

const toRange = (props, domain) => {
  const scale = props.scale[props.dimension];
  return [scale(Math.min(...domain)), scale(Math.max(...domain))];
};

const toDomain = (props, range) => {
  const scale = props.scale[props.dimension];
  return [scale.invert(Math.min(...range)), scale.invert(Math.max(...range))];
};

const getFullRange = (props) => {
  const scale = props.scale[props.dimension];
  return scale.range();
};

const getFullDomain = (props) => {
  const scale = props.scale[props.dimension];
  return scale.domain();
};

const withinBound = (value, bound) => {
  return value >= Math.min(...bound) && value <= Math.max(...bound);
};

const getActiveHandle = (props, position, range) => {
  const width = props.handleWidth / 2;
  const getHandle = (type) => {
    const base = type === "min" ? Math.min(...range) : Math.max(...range);
    return [base - width, base + width];
  };
  const active = ["min", "max"].reduce((memo, type) => {
    memo[type] = withinBound(position, getHandle(type)) ? type : false;
    return memo;
  }, {});
  return active.min && active.max ? "both" : active.min || active.max;
};

const getMinimumDomain = () => {
  return [0, 1 / Number.MAX_SAFE_INTEGER];
};

const getCurrentDomain = (props) => {
  const { currentDomain, cachedBrushDomain, brushDomain } = props;
  // if (brushDomain && !isEqual(brushDomain, cachedBrushDomain)) {
  //   return brushDomain;
  // }
  return currentDomain || brushDomain || getFullDomain();
};

const panBox = (props, position) => {
  const { brushDomain, startPosition, currentDomain } = props;
  const range = currentDomain ? toRange(props, currentDomain) : toRange(props, brushDomain);
  const fullRange = getFullRange(props);
  const size = Math.abs(range[1] - range[0]);
  const globalMin = Math.min(...fullRange);
  const globalMax = Math.max(...fullRange);
  const delta = startPosition ? startPosition - position : 0;
  const min = Math.min(...range) - delta;
  const max = Math.max(...range) - delta;
  const constrainedMin = min > globalMax - size ? globalMax - size : Math.max(min, globalMin);
  const constrainedMax = max < globalMin + size ? globalMin + size : Math.min(max, globalMax);
  return [constrainedMin, constrainedMax];
};

export default class VictoryBrushLine extends React.Component {
  static propTypes = {
    allowDrag: PropTypes.bool,
    allowResize: PropTypes.bool,
    brushAreaComponent: PropTypes.element,
    brushAreaStyle: PropTypes.object,
    brushComponent: PropTypes.element,
    brushDimension: PropTypes.oneOf(["x", "y"]),
    brushDomain: PropTypes.array,
    brushStyle: PropTypes.object,
    brushWidth: PropTypes.number,
    className: PropTypes.string,
    dimension: PropTypes.oneOf(["x", "y"]),
    events: PropTypes.object,
    groupComponent: PropTypes.element,
    handleComponent: PropTypes.element,
    handleStyle: PropTypes.object,
    handleWidth: PropTypes.number,
    lineComponent: PropTypes.element,
    onBrushDomainChange: PropTypes.func,
    scale: PropTypes.object,
    style: PropTypes.object,
    type: PropTypes.string
  };

  static defaultProps = {
    allowDrag: true,
    allowResize: true,
    brushAreaComponent: <rect/>,
    brushAreaStyle: {
      stroke: "transparent",
      fill: "black",
      fillOpacity: 0.1
    },
    brushComponent: <rect/>,
    brushStyle: {
      stroke: "black",
      fill: "black",
      cursor: "move",
      opacity: 0.15
    },
    brushWidth: 10,
    groupComponent: <g/>,
    handleComponent: <rect/>,
    handleStyle: {
      stroke: "black",
      fill: "none"
    },
    handleWidth: 10,
    lineComponent: <Line/>
  };

  static defaultEvents = function (props) {
    return [{
      target: props.type,
      eventHandlers: {
        onMouseDown: (evt, targetProps) => {
          evt.preventDefault();
          const {
            scale, allowResize, allowDrag, dimension, brushDomain
          } = targetProps;

          // Don't trigger events for static brushes
          if (!allowResize && !allowDrag) {
            return [];
          }

          const fullDomain = scale[dimension].domain();
          const currentDomain = getCurrentDomain(targetProps);
          const position = Selection.getSVGEventCoordinates(evt)[dimension];
          const range = toRange(targetProps, currentDomain);
          const activeHandle = allowResize && getActiveHandle(targetProps, position, range);
          // If the event occurs in any of the handle regions, start a resize
          if (activeHandle) {
            return [{
              mutation: () => {
                return ({
                  isSelecting: true, activeHandle, currentDomain, cachedBrushDomain: brushDomain,
                  startPosition: position
                });
              }
            }];
          } else if (withinBound(position, range) && !isEqual(fullDomain, currentDomain)) {
            // if the event occurs within a selected region start a panning event, unless the whole
            // domain is selected
            return [{
              mutation: () => ({
                isPanning: allowDrag, startPosition: position,
                currentDomain, cachedBrushDomain: brushDomain
              })
            }];
          } else {
            // if the event occurs outside the region, or if the whole domain is selected,
            // start a new selection
            return allowResize ? [{
              mutation: () => ({
                isSelecting: allowResize,
                currentDomain: getMinimumDomain(),
                cachedBrushDomain: brushDomain,
                startPosition: position
              })
            }] : [];
          }
        },
        onMouseMove: (evt, targetProps) => { // eslint-disable-line max-statements, complexity
          if (!targetProps.isPanning && !targetProps.isSelecting) {
            return [];
          }
          const {
            isPanning, isSelecting, allowResize, allowDrag, dimension, onBrushDomainChange,
            cachedBrushDomain
          } = targetProps;
          const position = Selection.getSVGEventCoordinates(evt)[dimension];
          if (allowDrag && isPanning) {
            const fullRange = getFullRange(targetProps);
            const range = panBox(targetProps, position);
            const currentDomain = toDomain(targetProps, range);
            const startPosition = Math.max(...range) >= Math.max(...fullRange) ||
              Math.min(...range) <= Math.min(...fullRange) ?
              targetProps.startPosition : position;
            const mutatedProps = {
              startPosition, isPanning: true, currentDomain, cachedBrushDomain
            };

            if (isFunction(onBrushDomainChange)) {
              onBrushDomainChange(currentDomain, defaults({}, mutatedProps, targetProps));
            }
            return [{
              mutation: () => mutatedProps
            }];
          } else if (allowResize && isSelecting) {
            const range = toRange(targetProps, targetProps.currentDomain);
            const oppositeHandle = targetProps.activeHandle === "min" ? "max" : "min";
            const handle = targetProps.activeHandle &&
              getActiveHandle(targetProps, position, range) === "both" ?
                oppositeHandle : targetProps.activeHandle;
            const currentRange = handle ? [
              handle === "max" ? Math.min(...range) : position,
              handle === "min" ? Math.max(...range) : position
            ] : [targetProps.startPosition, position];
            const currentDomain = toDomain(targetProps, currentRange);
            const mutatedProps = {
              currentDomain, startPosition: targetProps.startPosition,
              isSelecting, activeHandle: handle, cachedBrushDomain
            };
            if (isFunction(onBrushDomainChange)) {
              onBrushDomainChange(currentDomain, defaults({}, mutatedProps, targetProps));
            }
            return [{
              mutation: () => (mutatedProps)
            }];
          }
          return [];
        },
        onMouseUp(evt, targetProps) {
          const { onBrushDomainChange, currentDomain, allowResize } = targetProps;
          // if the mouse hasn't moved since a mouseDown event, select the whole domain region
          const mutatedProps = {
            isPanning: false, isSelecting: false, activeHandle: false, startPosition: null,
            currentDomain, cachedBrushDomain: currentDomain, brushDomain: currentDomain
          };
          if (allowResize && isFunction(onBrushDomainChange)) {
            onBrushDomainChange(currentDomain, defaults({}, mutatedProps, targetProps));
          }
          return [{
            mutation: () => mutatedProps
          }];
        },
        onMouseLeave(evt, targetProps) {
          const { currentDomain, cachedBrushDomain } = targetProps;
          return [{
            mutation: () => ({
              isPanning: false, isSelecting: false, activeHandle: false, startPosition: null,
              currentDomain, cachedBrushDomain
            })
          }];
        }
      }
    }];
  };

  // componentWillMount() {
  //   this.style = this.getStyle(this.props);
  // }

  // shouldComponentUpdate(nextProps) {
    // const { className, datum, x1, x2, y1, y2 } = this.props;
    // const style = this.getStyle(nextProps);
    // if (!Collection.allSetsEqual([
    //   [className, nextProps.className],
    //   [x1, nextProps.x1],
    //   [x2, nextProps.x2],
    //   [y1, nextProps.y1],
    //   [y2, nextProps.y2],
    //   [style, this.style],
    //   [datum, nextProps.datum]
    // ])) {
    //   this.style = style;
    //   return true;
    // }
    // return false;
  // }

  // getStyle(props) {
  //   const { style, datum, active } = props;
  //   return Helpers.evaluateStyle(assign({ stroke: "black" }, style), datum, active);
  // }

  getRectDimensions(props, domain) {
    const { dimension, brushWidth } = props;
    domain = domain || getCurrentDomain(props);
    const range = toRange(props, domain);
    const coordinates = dimension === "x" ?
      { y1: props.y1, y2: props.y2, x1: Math.min(...range), x2: Math.max(...range) } :
      { x1: props.x1, x2: props.x2, y1: Math.min(...range), y2: Math.max(...range) };
    const { x1, x2, y1, y2 } = coordinates;
    const offset = {
      x: dimension === "x" ? 0 : brushWidth / 2,
      y: dimension === "y" ? 0 : brushWidth / 2
    };

    const x = Math.min(x1, x2) - offset.x;
    const y = Math.min(y1, y2) - offset.y;
    const width = Math.max(x1, x2) + offset.x - x;
    const height = Math.max(y1, y2) + offset.y - y;
    return { x, y, width, height };
  }

  getHandleDimensions(props) {
    const { dimension, brushWidth, handleWidth, x1, x2, y1, y2 } = props;
    const domain = getCurrentDomain(props);
    const range = toRange(props, domain);
    const defaultX = Math.min(x1, x2) - (brushWidth / 2);
    const defaultY = Math.min(y1, y2) - (brushWidth / 2);
    const x = {
      min: dimension === "x" ? Math.min(...range) - handleWidth / 2 : defaultX,
      max: dimension === "x" ? Math.max(...range) - handleWidth / 2 : defaultX
    };
    const y = {
      min: dimension === "y" ? Math.max(...range) - handleWidth / 2 : defaultY,
      max: dimension === "y" ? Math.min(...range) - handleWidth / 2 : defaultY
    };
    const width = dimension === "x" ? handleWidth : brushWidth;
    const height = dimension === "x" ? brushWidth : handleWidth;

    return {
      min: { x: x.min, y: y.min, width, height },
      max: { x: x.max, y: y.max, width, height }
    };
  }

  renderHandles(props) {
    const { handleComponent, handleStyle, dimension } = props;
    const handleDimensions = this.getHandleDimensions(props);
    const cursor = dimension === "x" ? "ew-resize" : "ns-resize";
    const style = assign({ cursor }, handleStyle);
    return [
      React.cloneElement(handleComponent, assign({ key: "min", style }, handleDimensions.min)),
      React.cloneElement(handleComponent, assign({ key: "max", style }, handleDimensions.max))
    ];
  }

  renderBrush(props) {
    const { brushComponent, brushStyle } = props;
    const rectDimensions = this.getRectDimensions(props);
    const brushProps = assign({ style: brushStyle }, rectDimensions);
    return React.cloneElement(brushComponent, brushProps);
  }

  renderBrushArea(props) {
    const { brushAreaComponent, brushAreaStyle } = props;
    const rectDimensions = this.getRectDimensions(props, getFullDomain(props));
    const brushAreaProps = assign({ style: brushAreaStyle }, rectDimensions);
    return React.cloneElement(brushAreaComponent, brushAreaProps);
  }

  renderLine(props) {
    return <Line {...props}/>;
  }

  render() {
    return (
      <g {...this.props.events}>
        {this.renderLine(this.props)}
        {this.renderBrushArea(this.props)}
        {this.renderBrush(this.props)}
        {this.renderHandles(this.props)}
      </g>
    );
  }
}
<|endoftext|>


<commit_before>/**
 * Copyright 2013-2017 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see http://www.jhipster.tech/
 * for more information.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

const crypto = require('crypto');
const ApplicationTypes = require('./jhipster/application_types');
const ApplicationOptions = require('./jhipster/application_options');
const mergeObjects = require('../utils/object_utils').merge;
const Set = require('../utils/objects/set');
const ApplicationErrorCases = require('../exceptions/error_cases').ErrorCases.applications;

class JDLApplication {
  constructor(args) {
    const merged = merge(args);
    this.config = generateConfigObject(merged.config);
    this.config = fixApplicationConfig(this.config);
    this.entities = new Set(args.entities);
  }

  static checkValidity(application) {
    const errors = [];
    if (!application || !application.config) {
      errors.push(ApplicationErrorCases.NoApplication);
      return errors;
    }
    if (!application.config.baseName) {
      errors.push(ApplicationErrorCases.NoName);
    }
    if (!application.config.authenticationType) {
      errors.push(ApplicationErrorCases.NoAuthenticationType);
    }
    if (!application.config.buildTool) {
      errors.push(ApplicationErrorCases.NoBuildTool);
    }
    if (application.config.enableTranslation && !application.config.nativeLanguage) {
      errors.push(ApplicationErrorCases.NoChosenLanguage);
    }
    if (application.config.authenticationType === ApplicationOptions.authenticationType.jwt
        && !application.config.jwtSecretKey) {
      errors.push(ApplicationErrorCases.NoJWTSecret);
    }
    if (application.config.authenticationType === ApplicationOptions.authenticationType.session
        && !application.config.rememberMeKey) {
      errors.push(ApplicationErrorCases.NoRememberMeKey);
    }
    if ((application.config.applicationType === ApplicationTypes.MICROSERVICE
        || application.config.applicationType === ApplicationTypes.UAA) && !application.config.skipClient) {
      errors.push(ApplicationErrorCases.ShouldSkipClient);
    }
    if ((application.config.applicationType === ApplicationTypes.UAA
        || application.config.applicationType === ApplicationTypes.MICROSERVICE)
      && application.config.authenticationType === ApplicationOptions.authenticationType.uaa) {
      errors.push(ApplicationErrorCases.NoUAAAppFolderPath);
    }
    return errors;
  }

  static isValid(application) {
    const errors = this.checkValidity(application);
    return errors.length === 0;
  }

  toString() {
    return `application {\n${stringifyConfig(this.config)}\n}`;
  }
}

function generateConfigObject(passedConfig) {
  const config = {};
  Object.keys(passedConfig).forEach((option) => {
    if (Array.isArray(passedConfig[option]) && (option === 'languages' || option === 'testFrameworks')) {
      config[option] = new Set(passedConfig[option]);
    } else {
      config[option] = passedConfig[option];
    }
  });
  if (config.authenticationType === 'session') {
    config.rememberMeKey = generateRememberMeKey();
  }
  if (config.authenticationType === 'jwt') {
    config.jwtSecretKey = generateJWTSecretKey();
  }
  return config;
}

function fixApplicationConfig(passedConfig) {
  if (!passedConfig.authenticationType) {
    switch (passedConfig.applicationType) {
    case ApplicationTypes.UAA:
      passedConfig.authenticationType = ApplicationOptions.authenticationType.uaa;
      break;
    default:
      passedConfig.authenticationType = ApplicationOptions.authenticationType.jwt;
    }
  }
  if (!passedConfig.baseName) {
    passedConfig.baseName = ApplicationOptions.baseName;
  }
  if (!passedConfig.buildTool) {
    passedConfig.buildTool = ApplicationOptions.buildTool.maven;
  }
  if (!passedConfig.cacheProvider) {
    switch (passedConfig.applicationType) {
    case ApplicationTypes.MICROSERVICE:
    case ApplicationTypes.UAA:
      passedConfig.cacheProvider = ApplicationOptions.cacheProvider.hazelcast;
      break;
    default:
      passedConfig.cacheProvider = ApplicationOptions.cacheProvider.ehcache;
    }
  }
  if (!passedConfig.clientFramework) {
    passedConfig.clientFramework = ApplicationOptions.clientFramework.angularX;
  }
  if (passedConfig.authenticationType === ApplicationOptions.authenticationType.jwt
    && !passedConfig.jwtSecretKey) {
    passedConfig.jwtSecretKey = generateJWTSecretKey();
  }
  if (passedConfig.enableTranslation && !passedConfig.nativeLanguage) {
    passedConfig.nativeLanguage = ApplicationOptions.nativeLanguage;
  }
  if (passedConfig.authenticationType === ApplicationOptions.authenticationType.session
    && !passedConfig.rememberMeKey) {
    passedConfig.rememberMeKey = generateRememberMeKey();
  }
  if (!passedConfig.serverPort) {
    switch (passedConfig.applicationType) {
    case ApplicationTypes.MICROSERVICE:
      passedConfig.serverPort = '8081';
      break;
    case ApplicationTypes.UAA:
      passedConfig.serverPort = '9999';
      break;
    default:
      passedConfig.serverPort = ApplicationOptions.serverPort;
    }
  }
  if ((passedConfig.applicationType === ApplicationTypes.MICROSERVICE
      || passedConfig.applicationType === ApplicationTypes.UAA) && !passedConfig.skipClient) {
    passedConfig.skipClient = true;
  }
  if ((passedConfig.applicationType === ApplicationTypes.GATEWAY && passedConfig.authenticationType.uaa)
    || passedConfig.authenticationType === ApplicationOptions.authenticationType.oauth2) {
    passedConfig.skipUserManagement = true;
  }
  if (passedConfig.skipUserManagement !== true || passedConfig.skipUserManagement !== false) {
    passedConfig.skipUserManagement = ApplicationOptions.skipUserManagement;
  }
  return passedConfig;
}

function generateJWTSecretKey() {
  return generateRememberMeKey();
}

function generateRememberMeKey() {
  return crypto.randomBytes(20).toString('hex');
}

function stringifyConfig(applicationConfig) {
  let config = '  config {';
  Object.keys(applicationConfig).forEach((option) => {
    config = `${config}\n    ${option}${stringifyOptionValue(option, applicationConfig[option])}`;
  });
  return `${config.replace(/[[\]]/g, '')}\n  }`;
}

function stringifyOptionValue(name, value) {
  if (Array.isArray(value)) {
    return value.join(', ');
  }
  if (value === null || value === undefined || (name === 'testFrameworks' && value.size() === 0)) {
    return '';
  }
  return ` ${value}`;
}

function merge(args) {
  if (args.config) {
    if (!args.config.packageName && args.config.packageFolder) {
      args.config.packageName = args.config.packageFolder.replace(/\//g, '.');
    }
    if (!args.config.packageFolder && args.config.packageName) {
      args.config.packageFolder = args.config.packageName.replace(/\./g, '/');
    }
  }
  return {
    config: mergeObjects(ApplicationOptions.defaults(), args.config)
  };
}

module.exports = JDLApplication;
<commit_msg>Fixed bug with uaaBaseName<commit_after>/**
 * Copyright 2013-2017 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see http://www.jhipster.tech/
 * for more information.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

const crypto = require('crypto');
const ApplicationTypes = require('./jhipster/application_types');
const ApplicationOptions = require('./jhipster/application_options');
const mergeObjects = require('../utils/object_utils').merge;
const Set = require('../utils/objects/set');
const ApplicationErrorCases = require('../exceptions/error_cases').ErrorCases.applications;

class JDLApplication {
  constructor(args) {
    const merged = merge(args);
    this.config = generateConfigObject(merged.config);
    this.config = fixApplicationConfig(this.config);
    this.entities = new Set(args.entities);
  }

  static checkValidity(application) {
    const errors = [];
    if (!application || !application.config) {
      errors.push(ApplicationErrorCases.NoApplication);
      return errors;
    }
    if (!application.config.baseName) {
      errors.push(ApplicationErrorCases.NoName);
    }
    if (!application.config.authenticationType) {
      errors.push(ApplicationErrorCases.NoAuthenticationType);
    }
    if (!application.config.buildTool) {
      errors.push(ApplicationErrorCases.NoBuildTool);
    }
    if (application.config.enableTranslation && !application.config.nativeLanguage) {
      errors.push(ApplicationErrorCases.NoChosenLanguage);
    }
    if (application.config.authenticationType === ApplicationOptions.authenticationType.jwt
        && !application.config.jwtSecretKey) {
      errors.push(ApplicationErrorCases.NoJWTSecret);
    }
    if (application.config.authenticationType === ApplicationOptions.authenticationType.session
        && !application.config.rememberMeKey) {
      errors.push(ApplicationErrorCases.NoRememberMeKey);
    }
    if ((application.config.applicationType === ApplicationTypes.MICROSERVICE
        || application.config.applicationType === ApplicationTypes.UAA) && !application.config.skipClient) {
      errors.push(ApplicationErrorCases.ShouldSkipClient);
    }
    if (!application.config.uaaBaseName && (application.config.applicationType === ApplicationTypes.UAA
        || application.config.applicationType === ApplicationTypes.MICROSERVICE)
      && application.config.authenticationType === ApplicationOptions.authenticationType.uaa) {
      errors.push(ApplicationErrorCases.NoUAAAppFolderPath);
    }
    return errors;
  }

  static isValid(application) {
    const errors = this.checkValidity(application);
    return errors.length === 0;
  }

  toString() {
    return `application {\n${stringifyConfig(this.config)}\n}`;
  }
}

function generateConfigObject(passedConfig) {
  const config = {};
  Object.keys(passedConfig).forEach((option) => {
    if (Array.isArray(passedConfig[option]) && (option === 'languages' || option === 'testFrameworks')) {
      config[option] = new Set(passedConfig[option]);
    } else {
      config[option] = passedConfig[option];
    }
  });
  if (config.authenticationType === 'session') {
    config.rememberMeKey = generateRememberMeKey();
  }
  if (config.authenticationType === 'jwt') {
    config.jwtSecretKey = generateJWTSecretKey();
  }
  return config;
}

function fixApplicationConfig(passedConfig) {
  if (!passedConfig.authenticationType) {
    switch (passedConfig.applicationType) {
    case ApplicationTypes.UAA:
      passedConfig.authenticationType = ApplicationOptions.authenticationType.uaa;
      break;
    default:
      passedConfig.authenticationType = ApplicationOptions.authenticationType.jwt;
    }
  }
  if (!passedConfig.baseName) {
    passedConfig.baseName = ApplicationOptions.baseName;
  }
  if (!passedConfig.buildTool) {
    passedConfig.buildTool = ApplicationOptions.buildTool.maven;
  }
  if (!passedConfig.cacheProvider) {
    switch (passedConfig.applicationType) {
    case ApplicationTypes.MICROSERVICE:
    case ApplicationTypes.UAA:
      passedConfig.cacheProvider = ApplicationOptions.cacheProvider.hazelcast;
      break;
    default:
      passedConfig.cacheProvider = ApplicationOptions.cacheProvider.ehcache;
    }
  }
  if (!passedConfig.clientFramework) {
    passedConfig.clientFramework = ApplicationOptions.clientFramework.angularX;
  }
  if (passedConfig.authenticationType === ApplicationOptions.authenticationType.jwt
    && !passedConfig.jwtSecretKey) {
    passedConfig.jwtSecretKey = generateJWTSecretKey();
  }
  if (passedConfig.enableTranslation && !passedConfig.nativeLanguage) {
    passedConfig.nativeLanguage = ApplicationOptions.nativeLanguage;
  }
  if (passedConfig.authenticationType === ApplicationOptions.authenticationType.session
    && !passedConfig.rememberMeKey) {
    passedConfig.rememberMeKey = generateRememberMeKey();
  }
  if (!passedConfig.serverPort) {
    switch (passedConfig.applicationType) {
    case ApplicationTypes.MICROSERVICE:
      passedConfig.serverPort = '8081';
      break;
    case ApplicationTypes.UAA:
      passedConfig.serverPort = '9999';
      break;
    default:
      passedConfig.serverPort = ApplicationOptions.serverPort;
    }
  }
  if ((passedConfig.applicationType === ApplicationTypes.MICROSERVICE
      || passedConfig.applicationType === ApplicationTypes.UAA) && !passedConfig.skipClient) {
    passedConfig.skipClient = true;
  }
  if ((passedConfig.applicationType === ApplicationTypes.GATEWAY && passedConfig.authenticationType.uaa)
    || passedConfig.authenticationType === ApplicationOptions.authenticationType.oauth2) {
    passedConfig.skipUserManagement = true;
  }
  if (passedConfig.skipUserManagement !== true || passedConfig.skipUserManagement !== false) {
    passedConfig.skipUserManagement = ApplicationOptions.skipUserManagement;
  }
  return passedConfig;
}

function generateJWTSecretKey() {
  return generateRememberMeKey();
}

function generateRememberMeKey() {
  return crypto.randomBytes(20).toString('hex');
}

function stringifyConfig(applicationConfig) {
  let config = '  config {';
  Object.keys(applicationConfig).forEach((option) => {
    config = `${config}\n    ${option}${stringifyOptionValue(option, applicationConfig[option])}`;
  });
  return `${config.replace(/[[\]]/g, '')}\n  }`;
}

function stringifyOptionValue(name, value) {
  if (Array.isArray(value)) {
    return value.join(', ');
  }
  if (value === null || value === undefined || (name === 'testFrameworks' && value.size() === 0)) {
    return '';
  }
  return ` ${value}`;
}

function merge(args) {
  if (args.config) {
    if (!args.config.packageName && args.config.packageFolder) {
      args.config.packageName = args.config.packageFolder.replace(/\//g, '.');
    }
    if (!args.config.packageFolder && args.config.packageName) {
      args.config.packageFolder = args.config.packageName.replace(/\./g, '/');
    }
  }
  return {
    config: mergeObjects(ApplicationOptions.defaults(), args.config)
  };
}

module.exports = JDLApplication;
<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import React from 'react';
import { injectIntl } from 'react-intl';
import Dialog from '@material-ui/core/Dialog';
import DialogTitle from '@material-ui/core/DialogTitle';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import AppButton from './AppButton';
import { intlIfObject } from '../../lib/stringUtil';

class ConfirmationDialog extends React.Component {
  handleOk = () => {
    const { onOk } = this.props;
    onOk();
  }

  handleCancel = () => {
    const { onCancel } = this.props;
    onCancel();
  }

  render() {
    const { open, title, children, okText } = this.props;
    const { formatMessage } = this.props.intl;
    const actions = [
      <AppButton
        key={1}
        label="Cancel"
        onClick={this.handleCancel}
      />,
      <AppButton
        key={2}
        label={intlIfObject(formatMessage, okText)}
        primary
        onClick={this.handleOk}
      />,
    ];
    return (
      <div>
        <Dialog
          className="app-dialog"
          open={open}
          onClose={this.handleCancel}
        >
          <DialogTitle>{intlIfObject(formatMessage, title)}</DialogTitle>
          <DialogContent>
            {children}
          </DialogContent>
          <DialogActions>{actions}</DialogActions>
        </Dialog>
      </div>
    );
  }
}

ConfirmationDialog.propTypes = {
  // from composition
  intl: PropTypes.object.isRequired,
  children: PropTypes.node.isRequired,
  // from parent
  open: PropTypes.bool.isRequired,
  title: PropTypes.oneOfType([PropTypes.string, PropTypes.object]).isRequired,
  okText: PropTypes.oneOfType([PropTypes.string, PropTypes.object]).isRequired,
  onOk: PropTypes.func.isRequired,
  onCancel: PropTypes.func.isRequired,
};

export default injectIntl(ConfirmationDialog);
<commit_msg>Update to be stateless component<commit_after>import PropTypes from 'prop-types';
import React from 'react';
import { injectIntl } from 'react-intl';
import Dialog from '@material-ui/core/Dialog';
import DialogTitle from '@material-ui/core/DialogTitle';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import AppButton from './AppButton';
import { intlIfObject } from '../../lib/stringUtil';
import messages from '../../resources/messages';

const ConfirmationDialog = ({ open, title, children, okText, onCancel, onOk, intl }) => (
  <Dialog
    className="app-dialog"
    open={open}
    onClose={onCancel}
  >
    <DialogTitle>{intlIfObject(intl.formatMessage, title)}</DialogTitle>
    <DialogContent>
      {children}
    </DialogContent>
    <DialogActions>
      <AppButton
        label={messages.cancel}
        onClick={onCancel}
      />
      <AppButton
        label={intlIfObject(intl.formatMessage, okText)}
        primary
        onClick={onOk}
      />
    </DialogActions>
  </Dialog>
);

ConfirmationDialog.propTypes = {
  // from composition
  intl: PropTypes.object.isRequired,
  children: PropTypes.node.isRequired,
  // from parent
  open: PropTypes.bool.isRequired,
  title: PropTypes.oneOfType([PropTypes.string, PropTypes.object]).isRequired,
  okText: PropTypes.oneOfType([PropTypes.string, PropTypes.object]).isRequired,
  onOk: PropTypes.func.isRequired,
  onCancel: PropTypes.func.isRequired,
};

export default injectIntl(ConfirmationDialog);
<|endoftext|>