project-management -> project_management, user-management->user_management
[osm/UI.git] / skyquake / plugins / user_management / src / dashboard / dashboard.jsx
1 /*
2  * STANDARD_RIFT_IO_COPYRIGHT
3  */
4
5 import React from 'react';
6 import ReactDOM from 'react-dom';
7 import AppHeader from 'widgets/header/header.jsx';
8 import UserManagementStore from './userMgmtStore.js';
9 import SkyquakeComponent from 'widgets/skyquake_container/skyquakeComponent.jsx';
10 import 'style/layout.scss';
11 import './userMgmt.scss';
12 import {Panel, PanelWrapper} from 'widgets/panel/panel';
13
14
15 import TextInput from 'widgets/form_controls/textInput.jsx';
16 import Input from 'widgets/form_controls/input.jsx';
17 import Button, {ButtonGroup} from 'widgets/button/sq-button.jsx';
18 import SelectOption from 'widgets/form_controls/selectOption.jsx';
19 import 'widgets/form_controls/formControls.scss';
20 import imgAdd from '../../node_modules/open-iconic/svg/plus.svg'
21 import imgRemove from '../../node_modules/open-iconic/svg/trash.svg'
22
23 class UserManagementDashboard extends React.Component {
24     constructor(props) {
25         super(props);
26         this.Store = this.props.flux.stores.hasOwnProperty('UserManagementStore') ? this.props.flux.stores.UserManagementStore : this.props.flux.createStore(UserManagementStore);
27         this.Store.getUsers();
28         this.state = this.Store.getState();
29         this.actions = this.state.actions;
30     }
31     componentDidUpdate() {
32         let self = this;
33         ReactDOM.findDOMNode(this.UserList).addEventListener('transitionend', this.onTransitionEnd, false);
34         setTimeout(function() {
35             let element = self[`user-ref-${self.state.activeIndex}`]
36             element && !isElementInView(element) && element.scrollIntoView({block: 'end', behavior: 'smooth'});
37         })
38     }
39     componentWillMount() {
40         this.Store.listen(this.updateState);
41     }
42     componentWillUnmount() {
43         this.Store.unlisten(this.updateState);
44     }
45     updateState = (state) => {
46         this.setState(state);
47     }
48     updateInput = (key, e) => {
49         let property = key;
50         this.actions.handleUpdateInput({
51             [property]:e.target.value
52         })
53     }
54     disabledChange = (e) => {
55         this.actions.handleDisabledChange(e.target.checked);
56     }
57     platformChange = (platformRole, e) => {
58         this.actions.handlePlatformRoleUpdate(platformRole, e.currentTarget.checked);
59     }
60     addProjectRole = (e) => {
61         this.actions.handleAddProjectItem();
62     }
63     removeProjectRole = (i, e) => {
64         this.actions.handleRemoveProjectItem(i);
65     }
66     updateProjectRole = (i, e) => {
67         this.actions.handleUpdateProjectRole(i, e)
68     }
69     addUser = () => {
70         this.actions.handleAddUser();
71     }
72     viewUser = (un, index) => {
73         this.actions.viewUser(un, index);
74     }
75     editUser = () => {
76         this.actions.editUser(false);
77     }
78     cancelEditUser = () => {
79         this.actions.editUser(true)
80     }
81     closePanel = () => {
82         this.actions.handleCloseUserPanel();
83     }
84     // updateUser = (e) => {
85     //     e.preventDefault();
86     //     e.stopPropagation();
87
88     //     this.Store.updateUser();
89     // }
90     deleteUser = (e) => {
91         e.preventDefault();
92         e.stopPropagation();
93         this.Store.deleteUser({
94                 'user-name': this.state['user-name'],
95                 'user-domain': this.state['user-domain']
96             });
97     }
98     createUser = (e) => {
99         e.preventDefault();
100         e.stopPropagation();
101         if(this.state['new-password'] != this.state['confirm-password']) {
102             this.props.actions.showNotification('Passwords do not match')
103         } else {
104             this.Store.createUser({
105                 'user-name': this.state['user-name'],
106                 'user-domain': this.state['user-domain'],
107                 'password': this.state['new-password']
108                 // 'confirm-password': this.state['confirm-password']
109             });
110         }
111     }
112     updateUser = (e) => {
113         let self = this;
114         e.preventDefault();
115         e.stopPropagation();
116         let validatedPasswords = validatePasswordFields(this.state);
117         if(validatedPasswords) {
118             this.Store.updateUser(_.merge({
119                             'user-name': this.state['user-name'],
120                             'user-domain': this.state['user-domain'],
121                             'password': this.state['new-password']
122                         }));
123         }
124         function validatePasswordFields(state) {
125             let oldOne = state['old-password'];
126             let newOne = state['new-password'];
127             let confirmOne = state['confirm-password'];
128             if(true) {
129                 if(oldOne == newOne) {
130                     self.props.actions.showNotification('Your new password must not match your old one');
131                     return false;
132                 }
133                 if(newOne != confirmOne) {
134                     self.props.actions.showNotification('Passwords do not match');
135                     return false;
136                 }
137                 return {
138                     // 'old-password': oldOne,
139                     'new-password': newOne,
140                     'confirm-password': confirmOne
141                 }
142             } else {
143                 return {};
144             }
145         }
146     }
147      evaluateSubmit = (e) => {
148         if (e.keyCode == 13) {
149             if (this.props.isEdit) {
150                 this.updateUser(e);
151             } else {
152                 this.createUser(e);
153             }
154             e.preventDefault();
155             e.stopPropagation();
156         }
157     }
158     onTransitionEnd = (e) => {
159         this.actions.handleHideColumns(e);
160         console.log('transition end')
161     }
162     disableChange = (e) => {
163         let value = e.target.value;
164         value = value.toUpperCase();
165         if (value=="TRUE") {
166             value = true;
167         } else {
168             value = false;
169         }
170         console.log(value)
171     }
172     render() {
173         let self = this;
174         let html;
175         let props = this.props;
176         let state = this.state;
177         let passwordSectionHTML = null;
178         let formButtonsHTML = (
179             <ButtonGroup className="buttonGroup">
180                 <Button label="EDIT" type="submit" onClick={this.editUser} />
181             </ButtonGroup>
182         );
183         if(!this.state.isReadOnly) {
184             passwordSectionHTML = ( this.state.isEdit ?
185                                         (
186                                             <FormSection title="PASSWORD CHANGE">
187                                                 <Input label="NEW PASSWORD" type="password" value={state['new-password']}  onChange={this.updateInput.bind(null, 'new-password')}/>
188                                                 <Input label="REPEAT NEW PASSWORD" type="password"  value={state['confirm-password']}  onChange={this.updateInput.bind(null, 'confirm-password')}/>
189                                             </FormSection>
190                                         ) :
191                                         (
192                                             <FormSection title="CREATE PASSWORD">
193                                                 <Input label="CREATE PASSWORD" type="password" value={state.newPassword}  onChange={this.updateInput.bind(null, 'new-password')}/>
194                                                 <Input label="REPEAT PASSWORD" type="password"  value={state.repeatNewPassword}  onChange={this.updateInput.bind(null, 'confirm-password')}/>
195                                             </FormSection>
196                                         )
197                                     );
198             formButtonsHTML = (
199                                 state.isEdit ?
200                                 (
201                                     <ButtonGroup className="buttonGroup">
202                                         <Button label="Update" type="submit" onClick={this.updateUser} />
203                                         <Button label="Delete" onClick={this.deleteUser} />
204                                         <Button label="Cancel" onClick={this.cancelEditUser} />
205                                     </ButtonGroup>
206                                 )
207                                 : (
208                                     <ButtonGroup className="buttonGroup">
209                                         <Button label="Create" type="submit" onClick={this.createUser}  />
210                                     </ButtonGroup>
211                                 )
212                             )
213         }
214
215         html = (
216             <PanelWrapper className={`row userManagement ${!this.state.userOpen ? 'userList-open' : ''}`} style={{'flexDirection': 'row'}} >
217                 <PanelWrapper ref={(div) => { this.UserList = div}} className={`column userList expanded ${this.state.userOpen ? 'collapsed ' : ' '} ${this.state.hideColumns ? 'hideColumns ' : ' '}`}>
218                     <Panel title="User List" style={{marginBottom: 0}} no-corners>
219                         <div className="tableRow tableRow--header">
220                             <div className="userName">
221                                 Username
222                             </div>
223                             <div>
224                                 Domain
225                             </div>
226                         </div>
227                         {state.users && state.users.map((u, k) => {
228                             let platformRoles = [];
229                             for(let role in u.platformRoles) {
230                                 platformRoles.push(<div>{`${role}: ${u.platformRoles[role]}`}</div>)
231                             }
232                             return (
233                                 <div ref={(el) => this[`user-ref-${k}`] = el} className={`tableRow tableRow--data ${((self.state.activeIndex == k) && self.state.userOpen) ? 'tableRow--data-active' : ''}`} key={k}>
234                                     <div
235                                         className={`userName userName-header ${((self.state.activeIndex == k) && self.state.userOpen) ? 'activeUser' : ''}`}
236                                         onClick={self.viewUser.bind(null, u, k)}>
237                                         {u['user-name']}
238                                     </div>
239                                     <div>
240                                         {u['user-domain']}
241                                     </div>
242
243
244                                 </div>
245                             )
246                         })}
247                     </Panel>
248                     <ButtonGroup  className="buttonGroup" style={{margin: '0 0.5rem 0.5rem', background: '#ddd', paddingBottom: '0.5rem'}}>
249                         <Button label="Add User" onClick={this.addUser} />
250                     </ButtonGroup>
251                 </PanelWrapper>
252                 <PanelWrapper onKeyUp={this.evaluateSubmit}
253                     className={`userAdmin column`}>
254                     <Panel
255                         title={state.isEdit ? state['user-name'] : 'Create User'}
256                         style={{marginBottom: 0}}
257                         hasCloseButton={this.closePanel}
258                         no-corners>
259                         <FormSection title="USER INFO">
260                         {
261                             this.state.isEdit ?
262                                 null
263                                 : <Input  readonly={state.isReadOnly}  label="Username" value={state['user-name']} onChange={this.updateInput.bind(null, 'user-name')} />
264                         }
265                             <Input readonly={true} label="Domain" value={state['user-domain']}  onChange={this.updateInput.bind(null, 'user-domain')}></Input>
266
267                             <Input type="radiogroup" readonly={state.isReadOnly} label="Disabled" value={state.disabled} options={[{value: true, label: 'YES'}, {value: false, label: 'NO'}]}  onChange={this.disableChange} />
268                         </FormSection>
269                         <FormSection title="PLATFORM ROLES" style={{display:'none'}}>
270                             <Input label="Super Admin" onChange={this.platformChange.bind(null, 'super_admin')} checked={state.platformRoles.super_admin} type="checkbox" />
271                             <Input label="Platform Admin" onChange={this.platformChange.bind(null, 'platform_admin')}  checked={state.platformRoles.platform_admin} type="checkbox" />
272                             <Input label="Platform Oper" onChange={this.platformChange.bind(null, 'platform_oper')}  checked={state.platformRoles.platform_oper} type="checkbox" />
273                         </FormSection>
274                         <FormSection title="PROJECT ROLES" style={{display:'none'}}>
275                             <InputCollection
276                                 inital={true}
277                                 type='select'
278                                 readonly={state.isReadOnly}
279                                 options={state.projectRolesOptions}
280                                 collection={state.projectRoles}
281                                 onChange={this.updateProjectRole}
282                                 AddItemFn={this.addProjectRole}
283                                 RemoveItemFn={this.removeProjectRole}
284                                 />
285                         </FormSection>
286                         {passwordSectionHTML}
287
288                     </Panel>
289                         {formButtonsHTML}
290
291                 </PanelWrapper>
292
293
294             </PanelWrapper>
295         );
296         return html;
297     }
298 }
299 // onClick={this.Store.update.bind(null, Account)}
300 UserManagementDashboard.contextTypes = {
301     router: React.PropTypes.object
302 };
303
304 UserManagementDashboard.defaultProps = {
305     userList: [],
306     selectedUser: {}
307 }
308
309 export default SkyquakeComponent(UserManagementDashboard);
310
311
312 function isElementInView(el) {
313     var rect = el && el.getBoundingClientRect() || {};
314
315     return (
316         rect.top >= 0 &&
317         rect.left >= 0 &&
318         rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
319         rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
320     );
321 }
322
323
324 // isReadOnly={state.isReadOnly} disabled={state.disabled} onChange={this.disableChange}
325
326 class isDisabled extends React.Component {
327     constructor(props) {
328         super(props);
329     }
330     render() {
331         let props = this.props;
332         return (<div/>)
333     }
334 }
335
336 /**
337  * AddItemFn:
338  */
339 class InputCollection extends React.Component {
340     constructor(props) {
341         super(props);
342         this.collection = props.collection;
343     }
344     buildTextInput(onChange, v, i) {
345         return (
346             <Input
347                 readonly={this.props.readonly}
348                 style={{flex: '1 1'}}
349                 key={i}
350                 value={v}
351                 onChange= {onChange.bind(null, i)}
352             />
353         )
354     }
355     buildSelectOption(initial, options, onChange, v, i) {
356         return (
357             <SelectOption
358                 readonly={this.props.readonly}
359                 key={`${i}-${v.replace(' ', '_')}`}
360                 intial={initial}
361                 defaultValue={v}
362                 options={options}
363                 onChange={onChange.bind(null, i)}
364             />
365         );
366     }
367     showInput() {
368
369     }
370     render() {
371         const props = this.props;
372         let inputType;
373         let className = "InputCollection";
374         if (props.className) {
375             className = `${className} ${props.className}`;
376         }
377         if (props.type == 'select') {
378             inputType = this.buildSelectOption.bind(this, props.initial, props.options, props.onChange);
379         } else {
380             inputType = this.buildTextInput.bind(this, props.onChange)
381         }
382         let html = (
383             <div className="InputCollection-wrapper">
384                 {props.collection.map((v,i) => {
385                     return (
386                         <div key={i} className={className} >
387                             {inputType(v, i)}
388                             {
389                                 props.readonly ? null : <span onClick={props.RemoveItemFn.bind(null, i)} className="removeInput"><img src={imgRemove} />Remove</span>}
390                         </div>
391                     )
392                 })}
393                 { props.readonly ? null : <span onClick={props.AddItemFn} className="addInput"><img src={imgAdd} />Add</span>}
394             </div>
395         );
396         return html;
397     }
398 }
399
400 InputCollection.defaultProps = {
401     input: Input,
402     collection: [],
403     onChange: function(i, e) {
404         console.log(`
405                         Updating with: ${e.target.value}
406                         At index of: ${i}
407                     `)
408     },
409     AddItemFn: function(e) {
410         console.log(`Adding a new item to collection`)
411     },
412     RemoveItemFn: function(i, e) {
413         console.log(`Removing item from collection at index of: ${i}`)
414     }
415 }
416
417 class FormSection extends React.Component {
418     render() {
419         let className = 'FormSection ' + this.props.className;
420         let html = (
421             <div
422                 style={this.props.style}
423                 className={className}
424             >
425                 <div className="FormSection-title">
426                     {this.props.title}
427                 </div>
428                 <div className="FormSection-body">
429                     {this.props.children}
430                 </div>
431             </div>
432         );
433         return html;
434     }
435 }
436
437 FormSection.defaultProps = {
438     className: ''
439 }