Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { Component } from 'react';
- import withRedux from 'next-redux-wrapper';
- import Checkbox from 'material-ui/Checkbox';
- import { getProducts, uploadFiles, uploadImage } from 'utils';
- import { connect } from 'react-redux';
- import fetch from 'isomorphic-unfetch';
- import { Product } from './Product';
- import CircularProgress from 'material-ui/CircularProgress';
- import Paper from 'material-ui/Paper';
- import List from 'material-ui/List';
- import TextField from 'material-ui/TextField';
- import RaisedButton from 'material-ui/RaisedButton';
- import ActionAndroid from 'material-ui/svg-icons/action/android';
- import FontIcon from 'material-ui/FontIcon';
- import FileUpload from 'components/elements/FileUpload';
- import Dialog from 'material-ui/Dialog';
- import FlatButton from 'material-ui/FlatButton';
- import { Operation } from 'components/content/elements/Operation';
- import { OperationProducts } from 'components/content/elements/OperationProducts';
- import SelectField from 'material-ui/SelectField';
- import SubType from 'components/content/elements/SubType';
- import MenuItem from 'material-ui/MenuItem';
- String.prototype.format = function() {
- var formatted = this;
- if(typeof arguments[0] === "object"){
- const replacer = arguments[0];
- for(var prop in replacer){
- var regexp = new RegExp('\\{'+prop+'\\}', 'gi');
- formatted = formatted.replace(regexp, replacer[prop]);
- }
- return formatted;
- }
- for (var i = 0; i < arguments.length; i++) {
- var regexp = new RegExp('\\{'+i+'\\}', 'gi');
- formatted = formatted.replace(regexp, arguments[i]);
- }
- return formatted;
- };
- const styles = {
- button: {
- marginTop: 30,
- float: 'right',
- marginBottom: 20
- },
- editor: {
- height: 200
- }
- };
- export class Form extends Component {
- modules = {
- toolbar: [
- [{ 'header': [1, 2, false] }],
- ['bold', 'italic', 'underline', 'strike', 'blockquote'],
- [{ 'list': 'ordered' }, { 'list': 'bullet' }, { 'indent': '-1' }, { 'indent': '+1' }],
- ['link'],
- ['clean']
- ],
- };
- formats = [
- 'header',
- 'bold', 'italic', 'underline', 'strike', 'blockquote',
- 'list', 'bullet', 'indent',
- 'link'
- ];
- constructor(props) {
- super(props);
- this.selectedOfficesId = [];
- this.selectedRolesId = [];
- this.selectedProductsId = [];
- if (typeof window !== 'undefined') {
- this.ReactQuill = require('react-quill')
- }
- this.selectedAllProductsOperations = [];
- this.getOperations();
- this.createNews = this.createNews.bind(this);
- this.state = {
- operations: [],
- products: [],
- offices: [],
- roles: [],
- title: "",
- selectedOperations: [],
- description: "",
- content: "",
- actualProducts: [],
- actualOffices: [],
- actualRoles: [],
- loadingOperations: true,
- loadingOffices: false,
- loadingRoles: false,
- loadingImage: false,
- showProducts: false,
- showOffices: false,
- showRoles: false,
- openSuccessDialog: false,
- dialogMessage: [],
- dialogTitle: "",
- titleError: "",
- descriptionError: "",
- contentError: "",
- allProducts: [],
- subtypes: [],
- subtype: "",
- roles2: [],
- filterText: ""
- };
- this.getSubtypes();
- }
- async getOperations() {
- var response = await fetch(ENV.localUrl + "/cmsproxy/content/operations?login=" + this.props.user.login, {
- method: 'GET',
- headers: {
- "Accept": "application/json",
- "Content-Type": "application/json"
- }
- });
- var jsonOperations = await response.json();
- if (typeof jsonOperations.operations !== "undefined") {
- var operations = jsonOperations.operations;
- this.setState({ operations });
- this.setState({ loadingOperations: false });
- }
- }
- async getSubtypes(){
- var response = await fetch(ENV.localUrl + "/cmsproxy/content/subtypes?menu=biblioteca&submenu=principal", {
- method: 'GET',
- headers: {
- "Accept": "application/json",
- "Content-Type": "application/json"
- }
- });
- var json = await response.json();
- var subtypes = json.subtypes;
- this.setState({ subtypes });
- }
- async getProducts(operation) {
- this.setState({ loadingProducts: true });
- var url = ENV.localUrl + "/cmsproxy/content/operations/products?operations=" + operation.id;
- var response = await fetch(url, {
- method: 'GET',
- headers: {
- "Accept": "application/json",
- "Content-Type": "application/json"
- }
- });
- var jsonProducts = await response.json();
- var products = await jsonProducts.products;
- this.updateSelectedOperationProducts(operation, products);
- }
- async getAllProducts(operations){
- var url = ENV.localUrl + "/cmsproxy/content/operations/products?operations="+operations+"&all=true"
- var response = await fetch(url, {
- method: 'GET',
- headers: {
- "Accept": "application/json",
- "Content-Type": "application/json"
- }
- });
- var jsonProducts = await response.json();
- var products = await jsonProducts.products;
- this.setState({allProducts: products});
- }
- updateSelectedOperationProducts(operation, products) {
- var ops = this.state.selectedOperations;
- operation.products = products;
- ops.push(operation);
- this.setState({ selectedOperations: ops });
- }
- async getOffices() {
- var response = await fetch(ENV.localUrl + "/cmsproxy/content/operations/offices?products=" + this.selectedProductsId.join(',') + "&operations=" + this.getSelectedCheckboxes('operations').join(','), {
- method: 'GET',
- headers: {
- "Accept": "application/json",
- "Content-Type": "application/json"
- }
- });
- var jsonOffices = await response.json();
- if (typeof jsonOffices.offices !== "undefined") {
- var offices = jsonOffices.offices;
- this.setState({ offices });
- if (offices.length > 0) {
- this.setState({ loadingOffices: false, showOffices: true });
- } else {
- this.setState({ loadingOffices: false, showOffices: false });
- }
- }
- }
- async getRoles() {
- var response = await fetch(ENV.localUrl + "/cmsproxy/content/operations/offices/roles?offices=" + this.selectedOfficesId.join(','), {
- method: 'GET',
- headers: {
- "Accept": "application/json",
- "Content-Type": "application/json"
- }
- });
- var jsonRoles = await response.json();
- if (typeof jsonRoles.roles !== "undefined") {
- var roles = jsonRoles.roles;
- this.setState({ roles });
- this.setState({ roles2: roles });
- if (roles.length > 0) {
- this.setState({ loadingRoles: false, showRoles: true });
- } else {
- this.setState({ loadingRoles: false, showRoles: false });
- }
- }
- }
- showOperations() {
- return this.state.operations.map(operation => <Operation key={operation.id} onCheck={this.operationSelected} operation={operation} />)
- }
- showProducts() {
- return (
- <div>
- {this.state.selectedOperations.map(operation => {
- if (operation.products.length > 0) {
- return (
- <OperationProducts operation={operation} onCheckAll={this.checkAllProductsOperation} >
- {operation.products.map(product => <Product product={product} key={product.id} checked={product.checked} onChange={this.onAddProductId} />)}
- </OperationProducts>
- )
- } else {
- return null;
- }
- })}
- </div>
- )
- }
- showOffices() {
- return this.state.offices.map(office => <Checkbox key={office.id} label={office.nome} value={office.id} onCheck={this.officeSelected} style={{ whiteSpace: 'nowrap', width: '25%', marginRight: '10px', boxSizing: 'border-box' }} />)
- }
- showRoles() {
- return this.state.roles.map(role => <Checkbox key={role.id} label={role.office_name + "/" + role.nome} value={role.id} onCheck={this.roleSelected} checked={role.checked} style={{ whiteSpace: 'nowrap', width: '45%', marginRight: '10px', boxSizing: 'border-box' }} />)
- }
- onAddProductId = (productId, add) => {
- if (add) {
- this.selectedProductsId.push(productId);
- } else {
- this.selectedProductsId = this.selectedProductsId.filter(id => id !== productId);
- }
- this.getOffices();
- }
- checkAllProductsOperation = (operation, checked) => {
- if (checked) {
- this.selectedAllProductsOperations.push(operation.id);
- } else {
- this.selectedAllProductsOperations = this.selectedAllProductsOperations.filter(id => id !== operation.id);
- }
- this.getOffices();
- this.getAllProducts(this.selectedAllProductsOperations.join(','));
- }
- operationSelected = (operation, isInputChecked) => {
- const operationId = operation.id;
- if (isInputChecked) {
- this.getProducts(operation, false);
- this.setState({ showProducts: true, loadingProducts: false });
- } else {
- this.setState({ selectedOperations: this.state.selectedOperations.filter(operation => operation.id !== operationId) });
- }
- }
- officeSelected = (event, isInputChecked) => {
- var officeId = event.target.value;
- if (isInputChecked) {
- this.selectedOfficesId.push(officeId);
- ;
- } else {
- this.selectedOfficesId = this.selectedOfficesId.filter(id => id !== officeId);
- }
- this.getRoles();
- this.setState({ showRoles: true });
- }
- roleSelected = (event, isInputChecked) => {
- var roleId = event.target.value;
- if (isInputChecked) {
- this.selectedRolesId.push(roleId);
- } else {
- this.selectedRolesId = this.selectedRolesId.filter(id => id !== roleId);
- }
- const checkedRole = this.state.roles.map(role => {
- console.log(role, roleId);
- if (role.id == roleId) {
- role.checked = isInputChecked;
- }
- return role;
- });
- this.setState({ roles: checkedRole });
- }
- async createNews() {
- var operations = this.getSelectedCheckboxes('operations');
- var products = this.getSelectedCheckboxes('products .__container');
- var offices = this.getSelectedCheckboxes('offices');
- var roles = this.getSelectedCheckboxes('roles');
- var title = this.state.title;
- var description = this.state.description;
- var content = this.state.content;
- var subtype = this.state.subtype;
- var products = products.concat(this.state.allProducts.map(p => p.id));
- var user_type_id = this.props.user.user_info.user_type_id;
- var errors = [];
- var error = false;
- if (operations.length === 0) {
- errors.push("Selecione operações");
- }
- if (products.length === 0) {
- errors.push("Selecione cateiras");
- }
- if (offices.length === 0) {
- errors.push("Selecione empresas");
- }
- if (roles.length === 0) {
- errors.push("Selecione cargos");
- }
- if (subtype.length === 0) {
- errors.push("Selecione um subtipo");
- }
- if (title.length === 0) {
- this.setState({ titleError: "Adicione um título o artigo" });
- error = true;
- }
- if (description.length === 0) {
- this.setState({ descriptionError: "Adicione um descrição o artigo" });
- error = true;
- }
- if (content.length === 0) {
- this.setState({ contentError: "Adicione conteúdo o artigo" });
- error = true;
- }
- if(errors.length > 0){
- this.setState({ dialogMessage: errors, dialogTitle: "Alguns erros com as informações inseridas", openSuccessDialog: true });
- return;
- }
- if (error == false && errors.length == 0) {
- this.setState({ loadingImage: true });
- console.log('aqui meus arquivos salvos', products);
- const body = { operations, products, offices, roles, title, description, content, content_type: subtype.slug,user_type_id };
- try{
- const fileResponse = await uploadFiles();
- if (!fileResponse.success) {
- this.setState({ fileResponse: false });
- alert(fileResponse.message);
- this.setState({ loadingImage: false });
- return;
- }
- let url = fileResponse.url;
- if(url.length > 0){
- body.files = fileResponse.url;
- }
- this.setState({ loadingImage: false });
- }catch(e){
- this.setState({ loadingImage: false });
- }
- console.log(body);
- var response = await fetch(ENV.localUrl + "/cmsproxy/content/create/" + subtype.slug.trim(), {
- method: 'POST',
- headers: {
- "Accept": "application/json",
- "Content-Type": "application/json"
- },
- body: JSON.stringify(body)
- });
- var jsonNews = await response.json();
- if (jsonNews.success) {
- this.setState({ dialogTitle: "Artigo publicado com sucesso!", openSuccessDialog: true });
- } else {
- var messages = [];
- if (jsonNews.title) {
- messages.push(jsonNews.title[0]);
- }
- if (jsonNews.description) {
- messages.push(jsonNews.description[0]);
- }
- if (jsonNews.content) {
- messages.push(jsonNews.content[0]);
- }
- if (jsonNews.products) {
- messages.push(jsonNews.products[0]);
- }
- if (jsonNews.offices) {
- messages.push(jsonNews.offices[0]);
- }
- if (jsonNews.roles) {
- messages.push(jsonNews.roles[0]);
- }
- this.setState({ dialogMessage: messages, dialogTitle: "Artigo não pode ser publicado!", openSuccessDialog: true });
- }
- }
- }
- getSelectedCheckboxes(section) {
- var checkboxes = document.querySelectorAll('.' + section + ' input[type=checkbox]:checked');
- var ids = [];
- checkboxes.forEach(checkbox => {
- ids.push(checkbox.value);
- });
- return ids;
- }
- getSelectedOffices() {
- var offices = document.querySelectorAll('.offices input[type=checkbox]:checked');
- }
- getSelectedRoles() {
- var roles = document.querySelectorAll('.roles input[type=checkbox]:checked');
- }
- getSuccessDialogActions = () => {
- return [
- <FlatButton
- label="OK"
- primary={true}
- onClick={this.handleClose}
- />
- ];
- }
- descriptionChange = (event, description) => {
- this.setState({ description });
- }
- titleChange = (event, title) => {
- this.setState({ title });
- }
- contentChange = (content) => {
- this.setState({ content });
- }
- handleClose = () => {
- this.setState({ openSuccessDialog: false });
- };
- handleOpen = () => {
- this.setState({ openSuccessDialog: true });
- };
- handleSubTypeChange = (subtype) => {
- console.log(subtype);
- this.setState({subtype});
- }
- cargoChange = (event, filterText) => {
- var inputMalvadao = this.setState({ changeRole: filterText });
- if (filterText.trim().length > 0) {
- const filteredRoles = this.state.roles.filter((role) => {
- return role.nome.toLowerCase().search(filterText.toLowerCase()) !== -1;
- });
- this.setState({ roles: filteredRoles, filterText });
- } else {
- this.setState({ roles: this.state.roles2 })
- }
- var recebedorEstado = [];
- recebedorEstado.push(filterText);
- }
- handleClick = (event) => {
- if (this.state.filterText.length > 0) {
- let roles = this.state.roles;
- let rolesWithCheckedAttr = roles.map((role) => {
- role.checked = true;
- return role;
- });
- this.setState({ roles: rolesWithCheckedAttr, roles: this.state.roles2 })
- }
- }
- handleClean = (event) => {
- if (this.state.filterText.length > 0) {
- let roles = this.state.roles;
- let rolesWithCheckedAttr = roles.map((role) => {
- role.checked = false;
- return role;
- });
- this.setState({ roles: rolesWithCheckedAttr })
- }
- }
- render() {
- const actions = this.getSuccessDialogActions();
- const ReactQuill = this.ReactQuill;
- return (
- <div className="form-content" style={{ width: '100%' }}>
- <link rel="stylesheet" href="//cdn.quilljs.com/1.2.6/quill.snow.css"/>
- <div className="operations">
- <div className="__title">
- <h3>Operações</h3>
- <p>Selecione operações para carregar as respectivas carteiras:</p>
- </div>
- <div className="__container">
- {this.state.loadingOperations ? <CircularProgress /> : null}
- <div style={{ display: 'flex', flexDirection: 'row', flexWrap: 'wrap' }} className="__container" >
- {this.showOperations()}
- </div>
- </div>
- </div>
- {this.state.loadingProducts ? <div><CircularProgress style={{ marginTop: 20 }} /> <p>Carregando produtos...</p></div> : null}
- {this.state.showProducts ?
- <div className="products" >
- <div className="__title">
- <h3>Carteiras</h3>
- <p>Selecione carteiras e sub carteiras das operações selecionadas:</p>
- </div>
- {this.showProducts()}
- </div> : null}
- {this.state.loadingOffices ? <div><CircularProgress style={{ marginTop: 20 }} /> <p>Carregando empresas...</p></div> : null}
- {this.state.showOffices ?
- <div className="offices" >
- <div className="__title">
- <h3>Empresas</h3>
- <p>Selecione empresas dos produtos selecionados:</p>
- </div>
- <div style={{ display: 'flex', flexDirection: 'row', flexWrap: 'wrap' }} className="__container" >
- {this.showOffices()}
- <div style={{ display: "table", clear: "both" }}></div>
- </div>
- </div> : null}
- {this.state.loadingRoles ? <div><CircularProgress style={{ marginTop: 20 }} /> <p>Carregando cargos...</p></div> : null}
- {this.state.showRoles ?
- <div className="roles" >
- <div className="__title">
- <h3>Cargos</h3>
- <p>Selecione cargos das empresas selecionadas:</p>
- </div>
- <div className="__title">
- <TextField hintText="Insira o nome do cargo" onChange={this.cargoChange} style={{ marginTop: 20, marginLeft: 10 }} /> <br />
- </div>
- <div className="__title">
- <RaisedButton label="Selecionar" onClick={this.handleClick} primary={true} style={{ marginTop: 20, marginLeft: 10, marginBottom: 20 }} />
- <RaisedButton label="Limpar" onClick={this.handleClean} secondary={true} style={{ marginTop: 20, marginLeft: 10, marginBottom: 20 }} />
- </div>
- <div style={{ display: 'flex', flexDirection: 'row', flexWrap: 'wrap' }} className="__container" >
- {this.showRoles()}
- <div style={{ display: "table", clear: "both" }}></div>
- </div>
- </div> : null}
- <div style={{ display: 'block' }}>
- <h3>Detalhes do artigo</h3>
- </div>
- <div style={{ display: 'block', marginTop: '0px', position: 'relative' }}>
- <SubType subtypes={this.state.subtypes} handleSubtypeChange={this.handleSubTypeChange}/>
- </div>
- <div style={{ display: 'block', marginTop: '0px' }}>
- <TextField floatingLabelText="Insira um título para o artigo." errorText={this.state.titleError} style={{ width: '100%' }} onChange={this.titleChange} />
- </div>
- <div style={{ display: 'block', marginTop: '0px' }}>
- <TextField floatingLabelText="Insira uma descrição para o artigo." errorText={this.state.descriptionError} style={{ width: '100%' }} onChange={this.descriptionChange} />
- </div>
- <div style={{ display: 'block', marginTop: 30, height: 300 }}>
- {(typeof window !== 'undefined' && ReactQuill)?<ReactQuill value={this.state.content} onChange={this.contentChange} style={styles.editor} modules={this.modules} formats={this.formats} />:<TextField floatingLabelText="Insira o conteúdo do artigo" errorText={this.state.contentError} multiLine={true} rows={10} rowsMax={10} style={{ width: '100%' }} onChange={this.contentChange} />}
- </div>
- <div style={{ display: 'block' }}>
- <div style={{ display: 'inline', float: 'left' }}>
- <FileUpload label="Insira os arquivos do artigo." />
- </div>
- {this.state.loadingImage ? <div style={{ display: 'inline', float: 'left', paddingLeft: '20px' }}><CircularProgress style={{ marginTop: 20 }} /> <p style={{ display: 'inline', lineHeight: '40px', verticalAlign: 'text-bottom' }}>Enviando imagem...</p></div> : null}
- </div>
- <div style={{ display: "table", clear: "both" }}></div>
- <div style={{ display: 'block' }}>
- <RaisedButton
- label="Enviar artigo"
- labelPosition="before"
- primary={true}
- style={styles.button}
- onClick={this.createNews}
- />
- </div>
- <Dialog actions={actions} modal={false} open={this.state.openSuccessDialog} onRequestClose={this.handleClose} title={this.state.dialogTitle} style={{ textAlign: "center" }}>
- {this.state.dialogMessage.map(message => <List>{message}</List>)}
- </Dialog>
- </div>
- );
- }
- }
- export default connect(null, {})(Form);
Add Comment
Please, Sign In to add comment