Guest User

Untitled

a guest
Jan 16th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 23.71 KB | None | 0 0
  1. import React, { Component } from 'react';
  2. import withRedux from 'next-redux-wrapper';
  3. import Checkbox from 'material-ui/Checkbox';
  4. import { getProducts, uploadFiles, uploadImage } from 'utils';
  5. import { connect } from 'react-redux';
  6. import fetch from 'isomorphic-unfetch';
  7. import { Product } from './Product';
  8. import CircularProgress from 'material-ui/CircularProgress';
  9. import Paper from 'material-ui/Paper';
  10. import List from 'material-ui/List';
  11. import TextField from 'material-ui/TextField';
  12. import RaisedButton from 'material-ui/RaisedButton';
  13. import ActionAndroid from 'material-ui/svg-icons/action/android';
  14. import FontIcon from 'material-ui/FontIcon';
  15. import FileUpload from 'components/elements/FileUpload';
  16. import Dialog from 'material-ui/Dialog';
  17. import FlatButton from 'material-ui/FlatButton';
  18. import { Operation } from 'components/content/elements/Operation';
  19. import { OperationProducts } from 'components/content/elements/OperationProducts';
  20. import SelectField from 'material-ui/SelectField';
  21. import SubType from 'components/content/elements/SubType';
  22. import MenuItem from 'material-ui/MenuItem';
  23.  
  24. String.prototype.format = function() {
  25. var formatted = this;
  26. if(typeof arguments[0] === "object"){
  27. const replacer = arguments[0];
  28. for(var prop in replacer){
  29. var regexp = new RegExp('\\{'+prop+'\\}', 'gi');
  30. formatted = formatted.replace(regexp, replacer[prop]);
  31. }
  32. return formatted;
  33. }
  34. for (var i = 0; i < arguments.length; i++) {
  35. var regexp = new RegExp('\\{'+i+'\\}', 'gi');
  36. formatted = formatted.replace(regexp, arguments[i]);
  37. }
  38. return formatted;
  39. };
  40. const styles = {
  41. button: {
  42. marginTop: 30,
  43. float: 'right',
  44. marginBottom: 20
  45. },
  46. editor: {
  47. height: 200
  48. }
  49. };
  50.  
  51. export class Form extends Component {
  52.  
  53.  
  54. modules = {
  55. toolbar: [
  56. [{ 'header': [1, 2, false] }],
  57. ['bold', 'italic', 'underline', 'strike', 'blockquote'],
  58. [{ 'list': 'ordered' }, { 'list': 'bullet' }, { 'indent': '-1' }, { 'indent': '+1' }],
  59. ['link'],
  60. ['clean']
  61. ],
  62. };
  63.  
  64. formats = [
  65. 'header',
  66. 'bold', 'italic', 'underline', 'strike', 'blockquote',
  67. 'list', 'bullet', 'indent',
  68. 'link'
  69. ];
  70.  
  71. constructor(props) {
  72. super(props);
  73. this.selectedOfficesId = [];
  74. this.selectedRolesId = [];
  75. this.selectedProductsId = [];
  76. if (typeof window !== 'undefined') {
  77. this.ReactQuill = require('react-quill')
  78. }
  79. this.selectedAllProductsOperations = [];
  80. this.getOperations();
  81. this.createNews = this.createNews.bind(this);
  82. this.state = {
  83. operations: [],
  84. products: [],
  85. offices: [],
  86. roles: [],
  87. title: "",
  88. selectedOperations: [],
  89. description: "",
  90. content: "",
  91. actualProducts: [],
  92. actualOffices: [],
  93. actualRoles: [],
  94. loadingOperations: true,
  95. loadingOffices: false,
  96. loadingRoles: false,
  97. loadingImage: false,
  98. showProducts: false,
  99. showOffices: false,
  100. showRoles: false,
  101. openSuccessDialog: false,
  102. dialogMessage: [],
  103. dialogTitle: "",
  104. titleError: "",
  105. descriptionError: "",
  106. contentError: "",
  107. allProducts: [],
  108. subtypes: [],
  109. subtype: "",
  110. roles2: [],
  111. filterText: ""
  112. };
  113. this.getSubtypes();
  114. }
  115.  
  116. async getOperations() {
  117. var response = await fetch(ENV.localUrl + "/cmsproxy/content/operations?login=" + this.props.user.login, {
  118. method: 'GET',
  119. headers: {
  120. "Accept": "application/json",
  121. "Content-Type": "application/json"
  122. }
  123. });
  124. var jsonOperations = await response.json();
  125. if (typeof jsonOperations.operations !== "undefined") {
  126. var operations = jsonOperations.operations;
  127. this.setState({ operations });
  128. this.setState({ loadingOperations: false });
  129. }
  130. }
  131.  
  132. async getSubtypes(){
  133. var response = await fetch(ENV.localUrl + "/cmsproxy/content/subtypes?menu=biblioteca&submenu=principal", {
  134. method: 'GET',
  135. headers: {
  136. "Accept": "application/json",
  137. "Content-Type": "application/json"
  138. }
  139. });
  140. var json = await response.json();
  141. var subtypes = json.subtypes;
  142. this.setState({ subtypes });
  143. }
  144.  
  145.  
  146. async getProducts(operation) {
  147. this.setState({ loadingProducts: true });
  148. var url = ENV.localUrl + "/cmsproxy/content/operations/products?operations=" + operation.id;
  149. var response = await fetch(url, {
  150. method: 'GET',
  151. headers: {
  152. "Accept": "application/json",
  153. "Content-Type": "application/json"
  154. }
  155. });
  156. var jsonProducts = await response.json();
  157. var products = await jsonProducts.products;
  158. this.updateSelectedOperationProducts(operation, products);
  159. }
  160.  
  161. async getAllProducts(operations){
  162. var url = ENV.localUrl + "/cmsproxy/content/operations/products?operations="+operations+"&all=true"
  163. var response = await fetch(url, {
  164. method: 'GET',
  165. headers: {
  166. "Accept": "application/json",
  167. "Content-Type": "application/json"
  168. }
  169. });
  170. var jsonProducts = await response.json();
  171. var products = await jsonProducts.products;
  172. this.setState({allProducts: products});
  173. }
  174.  
  175. updateSelectedOperationProducts(operation, products) {
  176. var ops = this.state.selectedOperations;
  177. operation.products = products;
  178. ops.push(operation);
  179. this.setState({ selectedOperations: ops });
  180. }
  181.  
  182.  
  183. async getOffices() {
  184. var response = await fetch(ENV.localUrl + "/cmsproxy/content/operations/offices?products=" + this.selectedProductsId.join(',') + "&operations=" + this.getSelectedCheckboxes('operations').join(','), {
  185. method: 'GET',
  186. headers: {
  187. "Accept": "application/json",
  188. "Content-Type": "application/json"
  189. }
  190. });
  191. var jsonOffices = await response.json();
  192. if (typeof jsonOffices.offices !== "undefined") {
  193. var offices = jsonOffices.offices;
  194. this.setState({ offices });
  195. if (offices.length > 0) {
  196. this.setState({ loadingOffices: false, showOffices: true });
  197. } else {
  198. this.setState({ loadingOffices: false, showOffices: false });
  199. }
  200. }
  201. }
  202. async getRoles() {
  203. var response = await fetch(ENV.localUrl + "/cmsproxy/content/operations/offices/roles?offices=" + this.selectedOfficesId.join(','), {
  204. method: 'GET',
  205. headers: {
  206. "Accept": "application/json",
  207. "Content-Type": "application/json"
  208. }
  209. });
  210. var jsonRoles = await response.json();
  211. if (typeof jsonRoles.roles !== "undefined") {
  212. var roles = jsonRoles.roles;
  213. this.setState({ roles });
  214. this.setState({ roles2: roles });
  215. if (roles.length > 0) {
  216. this.setState({ loadingRoles: false, showRoles: true });
  217. } else {
  218. this.setState({ loadingRoles: false, showRoles: false });
  219. }
  220. }
  221. }
  222. showOperations() {
  223. return this.state.operations.map(operation => <Operation key={operation.id} onCheck={this.operationSelected} operation={operation} />)
  224. }
  225.  
  226. showProducts() {
  227. return (
  228. <div>
  229. {this.state.selectedOperations.map(operation => {
  230. if (operation.products.length > 0) {
  231. return (
  232. <OperationProducts operation={operation} onCheckAll={this.checkAllProductsOperation} >
  233. {operation.products.map(product => <Product product={product} key={product.id} checked={product.checked} onChange={this.onAddProductId} />)}
  234. </OperationProducts>
  235. )
  236. } else {
  237. return null;
  238. }
  239. })}
  240. </div>
  241. )
  242. }
  243.  
  244. showOffices() {
  245. 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' }} />)
  246. }
  247.  
  248. showRoles() {
  249. 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' }} />)
  250. }
  251.  
  252.  
  253. onAddProductId = (productId, add) => {
  254. if (add) {
  255. this.selectedProductsId.push(productId);
  256. } else {
  257. this.selectedProductsId = this.selectedProductsId.filter(id => id !== productId);
  258. }
  259. this.getOffices();
  260. }
  261.  
  262. checkAllProductsOperation = (operation, checked) => {
  263. if (checked) {
  264. this.selectedAllProductsOperations.push(operation.id);
  265. } else {
  266. this.selectedAllProductsOperations = this.selectedAllProductsOperations.filter(id => id !== operation.id);
  267. }
  268. this.getOffices();
  269. this.getAllProducts(this.selectedAllProductsOperations.join(','));
  270. }
  271.  
  272. operationSelected = (operation, isInputChecked) => {
  273. const operationId = operation.id;
  274. if (isInputChecked) {
  275. this.getProducts(operation, false);
  276. this.setState({ showProducts: true, loadingProducts: false });
  277. } else {
  278. this.setState({ selectedOperations: this.state.selectedOperations.filter(operation => operation.id !== operationId) });
  279. }
  280. }
  281.  
  282.  
  283. officeSelected = (event, isInputChecked) => {
  284. var officeId = event.target.value;
  285. if (isInputChecked) {
  286. this.selectedOfficesId.push(officeId);
  287. ;
  288. } else {
  289. this.selectedOfficesId = this.selectedOfficesId.filter(id => id !== officeId);
  290. }
  291. this.getRoles();
  292. this.setState({ showRoles: true });
  293. }
  294.  
  295. roleSelected = (event, isInputChecked) => {
  296. var roleId = event.target.value;
  297. if (isInputChecked) {
  298. this.selectedRolesId.push(roleId);
  299. } else {
  300. this.selectedRolesId = this.selectedRolesId.filter(id => id !== roleId);
  301. }
  302. const checkedRole = this.state.roles.map(role => {
  303. console.log(role, roleId);
  304. if (role.id == roleId) {
  305. role.checked = isInputChecked;
  306. }
  307. return role;
  308. });
  309. this.setState({ roles: checkedRole });
  310. }
  311.  
  312. async createNews() {
  313. var operations = this.getSelectedCheckboxes('operations');
  314. var products = this.getSelectedCheckboxes('products .__container');
  315.  
  316. var offices = this.getSelectedCheckboxes('offices');
  317. var roles = this.getSelectedCheckboxes('roles');
  318. var title = this.state.title;
  319. var description = this.state.description;
  320. var content = this.state.content;
  321. var subtype = this.state.subtype;
  322. var products = products.concat(this.state.allProducts.map(p => p.id));
  323. var user_type_id = this.props.user.user_info.user_type_id;
  324. var errors = [];
  325. var error = false;
  326. if (operations.length === 0) {
  327. errors.push("Selecione operações");
  328. }
  329. if (products.length === 0) {
  330. errors.push("Selecione cateiras");
  331. }
  332. if (offices.length === 0) {
  333. errors.push("Selecione empresas");
  334. }
  335. if (roles.length === 0) {
  336. errors.push("Selecione cargos");
  337. }
  338. if (subtype.length === 0) {
  339. errors.push("Selecione um subtipo");
  340. }
  341. if (title.length === 0) {
  342. this.setState({ titleError: "Adicione um título o artigo" });
  343. error = true;
  344. }
  345. if (description.length === 0) {
  346. this.setState({ descriptionError: "Adicione um descrição o artigo" });
  347. error = true;
  348. }
  349. if (content.length === 0) {
  350. this.setState({ contentError: "Adicione conteúdo o artigo" });
  351. error = true;
  352. }
  353.  
  354. if(errors.length > 0){
  355. this.setState({ dialogMessage: errors, dialogTitle: "Alguns erros com as informações inseridas", openSuccessDialog: true });
  356. return;
  357. }
  358.  
  359. if (error == false && errors.length == 0) {
  360.  
  361. this.setState({ loadingImage: true });
  362. console.log('aqui meus arquivos salvos', products);
  363. const body = { operations, products, offices, roles, title, description, content, content_type: subtype.slug,user_type_id };
  364. try{
  365. const fileResponse = await uploadFiles();
  366. if (!fileResponse.success) {
  367. this.setState({ fileResponse: false });
  368. alert(fileResponse.message);
  369. this.setState({ loadingImage: false });
  370. return;
  371. }
  372. let url = fileResponse.url;
  373. if(url.length > 0){
  374. body.files = fileResponse.url;
  375. }
  376. this.setState({ loadingImage: false });
  377. }catch(e){
  378. this.setState({ loadingImage: false });
  379. }
  380. console.log(body);
  381. var response = await fetch(ENV.localUrl + "/cmsproxy/content/create/" + subtype.slug.trim(), {
  382. method: 'POST',
  383. headers: {
  384. "Accept": "application/json",
  385. "Content-Type": "application/json"
  386. },
  387. body: JSON.stringify(body)
  388. });
  389. var jsonNews = await response.json();
  390. if (jsonNews.success) {
  391. this.setState({ dialogTitle: "Artigo publicado com sucesso!", openSuccessDialog: true });
  392. } else {
  393. var messages = [];
  394. if (jsonNews.title) {
  395. messages.push(jsonNews.title[0]);
  396. }
  397. if (jsonNews.description) {
  398. messages.push(jsonNews.description[0]);
  399. }
  400. if (jsonNews.content) {
  401. messages.push(jsonNews.content[0]);
  402. }
  403. if (jsonNews.products) {
  404. messages.push(jsonNews.products[0]);
  405. }
  406. if (jsonNews.offices) {
  407. messages.push(jsonNews.offices[0]);
  408. }
  409. if (jsonNews.roles) {
  410. messages.push(jsonNews.roles[0]);
  411. }
  412. this.setState({ dialogMessage: messages, dialogTitle: "Artigo não pode ser publicado!", openSuccessDialog: true });
  413. }
  414. }
  415.  
  416. }
  417.  
  418. getSelectedCheckboxes(section) {
  419. var checkboxes = document.querySelectorAll('.' + section + ' input[type=checkbox]:checked');
  420. var ids = [];
  421. checkboxes.forEach(checkbox => {
  422. ids.push(checkbox.value);
  423. });
  424. return ids;
  425. }
  426.  
  427. getSelectedOffices() {
  428. var offices = document.querySelectorAll('.offices input[type=checkbox]:checked');
  429. }
  430.  
  431. getSelectedRoles() {
  432. var roles = document.querySelectorAll('.roles input[type=checkbox]:checked');
  433. }
  434.  
  435. getSuccessDialogActions = () => {
  436. return [
  437. <FlatButton
  438. label="OK"
  439. primary={true}
  440. onClick={this.handleClose}
  441. />
  442. ];
  443. }
  444.  
  445. descriptionChange = (event, description) => {
  446. this.setState({ description });
  447. }
  448.  
  449. titleChange = (event, title) => {
  450. this.setState({ title });
  451. }
  452.  
  453. contentChange = (content) => {
  454. this.setState({ content });
  455. }
  456.  
  457. handleClose = () => {
  458. this.setState({ openSuccessDialog: false });
  459. };
  460.  
  461. handleOpen = () => {
  462. this.setState({ openSuccessDialog: true });
  463. };
  464.  
  465. handleSubTypeChange = (subtype) => {
  466. console.log(subtype);
  467. this.setState({subtype});
  468. }
  469.  
  470. cargoChange = (event, filterText) => {
  471. var inputMalvadao = this.setState({ changeRole: filterText });
  472.  
  473. if (filterText.trim().length > 0) {
  474. const filteredRoles = this.state.roles.filter((role) => {
  475. return role.nome.toLowerCase().search(filterText.toLowerCase()) !== -1;
  476. });
  477. this.setState({ roles: filteredRoles, filterText });
  478. } else {
  479. this.setState({ roles: this.state.roles2 })
  480. }
  481.  
  482. var recebedorEstado = [];
  483. recebedorEstado.push(filterText);
  484.  
  485. }
  486.  
  487. handleClick = (event) => {
  488. if (this.state.filterText.length > 0) {
  489. let roles = this.state.roles;
  490. let rolesWithCheckedAttr = roles.map((role) => {
  491. role.checked = true;
  492. return role;
  493.  
  494. });
  495.  
  496. this.setState({ roles: rolesWithCheckedAttr, roles: this.state.roles2 })
  497. }
  498. }
  499. handleClean = (event) => {
  500. if (this.state.filterText.length > 0) {
  501. let roles = this.state.roles;
  502. let rolesWithCheckedAttr = roles.map((role) => {
  503. role.checked = false;
  504. return role;
  505. });
  506. this.setState({ roles: rolesWithCheckedAttr })
  507. }
  508. }
  509.  
  510. render() {
  511. const actions = this.getSuccessDialogActions();
  512. const ReactQuill = this.ReactQuill;
  513. return (
  514. <div className="form-content" style={{ width: '100%' }}>
  515. <link rel="stylesheet" href="//cdn.quilljs.com/1.2.6/quill.snow.css"/>
  516. <div className="operations">
  517. <div className="__title">
  518. <h3>Operações</h3>
  519. <p>Selecione operações para carregar as respectivas carteiras:</p>
  520. </div>
  521. <div className="__container">
  522. {this.state.loadingOperations ? <CircularProgress /> : null}
  523. <div style={{ display: 'flex', flexDirection: 'row', flexWrap: 'wrap' }} className="__container" >
  524. {this.showOperations()}
  525. </div>
  526. </div>
  527. </div>
  528. {this.state.loadingProducts ? <div><CircularProgress style={{ marginTop: 20 }} /> <p>Carregando produtos...</p></div> : null}
  529. {this.state.showProducts ?
  530. <div className="products" >
  531. <div className="__title">
  532. <h3>Carteiras</h3>
  533. <p>Selecione carteiras e sub carteiras das operações selecionadas:</p>
  534. </div>
  535. {this.showProducts()}
  536. </div> : null}
  537. {this.state.loadingOffices ? <div><CircularProgress style={{ marginTop: 20 }} /> <p>Carregando empresas...</p></div> : null}
  538. {this.state.showOffices ?
  539. <div className="offices" >
  540. <div className="__title">
  541. <h3>Empresas</h3>
  542. <p>Selecione empresas dos produtos selecionados:</p>
  543. </div>
  544. <div style={{ display: 'flex', flexDirection: 'row', flexWrap: 'wrap' }} className="__container" >
  545. {this.showOffices()}
  546. <div style={{ display: "table", clear: "both" }}></div>
  547. </div>
  548. </div> : null}
  549. {this.state.loadingRoles ? <div><CircularProgress style={{ marginTop: 20 }} /> <p>Carregando cargos...</p></div> : null}
  550. {this.state.showRoles ?
  551. <div className="roles" >
  552. <div className="__title">
  553. <h3>Cargos</h3>
  554. <p>Selecione cargos das empresas selecionadas:</p>
  555. </div>
  556. <div className="__title">
  557. <TextField hintText="Insira o nome do cargo" onChange={this.cargoChange} style={{ marginTop: 20, marginLeft: 10 }} /> <br />
  558. </div>
  559. <div className="__title">
  560. <RaisedButton label="Selecionar" onClick={this.handleClick} primary={true} style={{ marginTop: 20, marginLeft: 10, marginBottom: 20 }} />
  561. <RaisedButton label="Limpar" onClick={this.handleClean} secondary={true} style={{ marginTop: 20, marginLeft: 10, marginBottom: 20 }} />
  562. </div>
  563. <div style={{ display: 'flex', flexDirection: 'row', flexWrap: 'wrap' }} className="__container" >
  564. {this.showRoles()}
  565. <div style={{ display: "table", clear: "both" }}></div>
  566. </div>
  567. </div> : null}
  568. <div style={{ display: 'block' }}>
  569. <h3>Detalhes do artigo</h3>
  570. </div>
  571. <div style={{ display: 'block', marginTop: '0px', position: 'relative' }}>
  572. <SubType subtypes={this.state.subtypes} handleSubtypeChange={this.handleSubTypeChange}/>
  573. </div>
  574. <div style={{ display: 'block', marginTop: '0px' }}>
  575. <TextField floatingLabelText="Insira um título para o artigo." errorText={this.state.titleError} style={{ width: '100%' }} onChange={this.titleChange} />
  576. </div>
  577. <div style={{ display: 'block', marginTop: '0px' }}>
  578. <TextField floatingLabelText="Insira uma descrição para o artigo." errorText={this.state.descriptionError} style={{ width: '100%' }} onChange={this.descriptionChange} />
  579. </div>
  580. <div style={{ display: 'block', marginTop: 30, height: 300 }}>
  581. {(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} />}
  582. </div>
  583. <div style={{ display: 'block' }}>
  584. <div style={{ display: 'inline', float: 'left' }}>
  585. <FileUpload label="Insira os arquivos do artigo." />
  586. </div>
  587. {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}
  588. </div>
  589. <div style={{ display: "table", clear: "both" }}></div>
  590. <div style={{ display: 'block' }}>
  591. <RaisedButton
  592. label="Enviar artigo"
  593. labelPosition="before"
  594. primary={true}
  595. style={styles.button}
  596. onClick={this.createNews}
  597. />
  598. </div>
  599. <Dialog actions={actions} modal={false} open={this.state.openSuccessDialog} onRequestClose={this.handleClose} title={this.state.dialogTitle} style={{ textAlign: "center" }}>
  600. {this.state.dialogMessage.map(message => <List>{message}</List>)}
  601. </Dialog>
  602. </div>
  603. );
  604. }
  605.  
  606. }
  607. export default connect(null, {})(Form);
Add Comment
Please, Sign In to add comment