Debug, logging, about added to ADMIN dropdown
[osm/UI.git] / skyquake / plugins / user_management / src / userProfile / userProfile.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 UserProfileStore from './userProfileStore.js';
9 import SkyquakeComponent from 'widgets/skyquake_container/skyquakeComponent.jsx';
10 import 'style/layout.scss';
11 import '../dashboard/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 UserProfileDashboard extends React.Component {
24     constructor(props) {
25         super(props);
26         this.Store = this.props.flux.stores.hasOwnProperty('UserProfileStore') ? this.props.flux.stores.UserProfileStore : this.props.flux.createStore(UserProfileStore);
27        this.state = this.Store.getState();
28        this.actions = this.state.actions;
29
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         this.Store.getUsers();
42     }
43     componentWillUnmount() {
44         this.Store.unlisten(this.updateState);
45     }
46     updateState = (state) => {
47         this.setState(state);
48     }
49     updateInput = (key, e) => {
50         let property = key;
51         this.actions.handleUpdateInput({
52             [property]:e.target.value
53         })
54     }
55     disabledChange = (e) => {
56         this.actions.handleDisabledChange(e.target.checked);
57     }
58     platformChange = (platformRole, e) => {
59         this.actions.handlePlatformRoleUpdate(platformRole, e.currentTarget.checked);
60     }
61     addProjectRole = (e) => {
62         this.actions.handleAddProjectItem();
63     }
64     removeProjectRole = (i, e) => {
65         this.actions.handleRemoveProjectItem(i);
66     }
67     updateProjectRole = (i, e) => {
68         this.actions.handleUpdateProjectRole(i, e)
69     }
70     addUser = () => {
71         this.actions.handleAddUser();
72     }
73     viewUser = (un, index) => {
74         this.actions.viewUser(un, index);
75     }
76     editUser = () => {
77         this.actions.editUser(false);
78     }
79     cancelEditUser = () => {
80         this.actions.editUser(true)
81     }
82     osePanel = () => {
83         this.actions.handleCloseUserPanel();
84     }
85     // updateUser = (e) => {
86     //     e.preventDefault();
87     //     e.stopPropagation();
88
89     //     this.Store.updateUser();
90     // }
91     deleteUser = (e) => {
92         e.preventDefault();
93         e.stopPropagation();
94         this.Store.deleteUser({
95                 'user-name': this.state['user-name'],
96                 'user-domain': this.state['user-domain']
97             });
98     }
99     createUser = (e) => {
100         e.preventDefault();
101         e.stopPropagation();
102         if(this.state['new-password'] != this.state['confirm-password']) {
103             this.props.actions.showNotification('Passwords do not match')
104         } else {
105             this.Store.createUser({
106                 'user-name': this.state['user-name'],
107                 'user-domain': this.state['user-domain'],
108                 'password': this.state['new-password']
109                 // 'confirm-password': this.state['confirm-password']
110             });
111         }
112     }
113     updateUser = (e) => {
114         let self = this;
115         e.preventDefault();
116         e.stopPropagation();
117         let validatedPasswords = validatePasswordFields(this.state);
118         if(validatedPasswords) {
119             this.Store.updateUser(_.merge({
120                             'user-name': this.context.userProfile.userId,
121                             'user-domain': this.state['user-domain'],
122                             'password': this.state['new-password']
123                         }));
124         }
125         function validatePasswordFields(state) {
126             let oldOne = state['old-password'];
127             let newOne = state['new-password'];
128             let confirmOne = state['confirm-password'];
129             if(true) {
130                 if(oldOne == newOne) {
131                     self.props.actions.showNotification('Your new password must not match your old one');
132                     return false;
133                 }
134                 if(newOne != confirmOne) {
135                     self.props.actions.showNotification('Passwords do not match');
136                     return false;
137                 }
138                 return {
139                     // 'old-password': oldOne,
140                     'new-password': newOne,
141                     'confirm-password': confirmOne
142                 }
143             } else {
144                 return {};
145             }
146         }
147     }
148      evaluateSubmit = (e) => {
149         if (e.keyCode == 13) {
150             if (this.props.isEdit) {
151                 this.updateUser(e);
152             } else {
153                 this.createUser(e);
154             }
155             e.preventDefault();
156             e.stopPropagation();
157         }
158     }
159     onTransitionEnd = (e) => {
160         this.actions.handleHideColumns(e);
161         console.log('transition end')
162     }
163     disableChange = (e) => {
164         let value = e.target.value;
165         value = value.toUpperCase();
166         if (value=="TRUE") {
167             value = true;
168         } else {
169             value = false;
170         }
171         console.log(value)
172     }
173     render() {
174
175         let self = this;
176         let html;
177         let props = this.props;
178         let state = this.state;
179         let passwordSectionHTML = null;
180         let formButtonsHTML = (
181             <ButtonGroup className="buttonGroup">
182                 <Button label="EDIT" type="submit" onClick={this.editUser} />
183             </ButtonGroup>
184         );
185         const User = this.context.userProfile || {};
186             passwordSectionHTML = (
187                                         (
188                                             <FormSection title="PASSWORD CHANGE">
189                                                 <Input label="NEW PASSWORD" type="password" value={state['new-password']}  onChange={this.updateInput.bind(null, 'new-password')}/>
190                                                 <Input label="REPEAT NEW PASSWORD" type="password"  value={state['confirm-password']}  onChange={this.updateInput.bind(null, 'confirm-password')}/>
191                                             </FormSection>
192                                         )
193                                     );
194             formButtonsHTML = (
195
196
197                                     <ButtonGroup className="buttonGroup">
198                                         <Button label="Update" type="submit" onClick={this.updateUser} />
199                                     </ButtonGroup>
200
201
202                             )
203
204         html = (
205             <PanelWrapper column>
206                 <PanelWrapper className={`row userManagement ${!this.state.userOpen ? 'userList-open' : ''}`} style={{'flexDirection': 'row'}} >
207                     <PanelWrapper ref={(div) => { this.UserList = div}} className={`column userList expanded hideColumns`}>
208                         <Panel title={User.userId} style={{marginBottom: 0}} no-corners>
209                             <table>
210                                 <thead>
211                                     <tr>
212                                         <td>User Name</td>
213                                         {
214                                             state.roles.map((r,i) => {
215                                                 return <td key={i}>{r}</td>
216                                             })
217                                         }
218                                     </tr>
219                                 </thead>
220                                 <tbody>
221                                     {
222                                         User.projects && User.projects.map((p,i)=> {
223                                             let projectConfig = p['project-config'];
224                                             let userRoles = [];
225                                             if(projectConfig && projectConfig.user) {
226                                                 projectConfig.user.map((u) => {
227                                                     if(u['user-name'] == User.userId) {
228                                                         userRoles = u.role && u.role.map((r) => {
229                                                             return r.role;
230                                                         })
231                                                     }
232                                                 })
233                                             }
234                                             return (
235                                                 <tr key={i}>
236                                                     <td>
237                                                         {p.name}
238                                                     </td>
239                                                     {
240                                                         state.roles.map((r,j) => {
241                                                             return <td key={j}><Input readonly={state.isReadOnly} type="checkbox" checked={(userRoles.indexOf(r) > -1)} /></td>
242                                                         })
243                                                     }
244                                                 </tr>
245                                             )
246                                         })
247                                     }
248                                 </tbody>
249                             </table>
250                             {passwordSectionHTML}
251                         </Panel>
252                         {formButtonsHTML}
253                     </PanelWrapper>
254
255                 </PanelWrapper>
256             </PanelWrapper>
257         );
258         return html;
259     }
260 }
261 // onClick={this.Store.update.bind(null, Account)}
262 UserProfileDashboard.contextTypes = {
263     router: React.PropTypes.object,
264     userProfile: React.PropTypes.object
265 };
266
267 UserProfileDashboard.defaultProps = {
268     userList: [],
269     selectedUser: {}
270 }
271
272 export default SkyquakeComponent(UserProfileDashboard);
273
274
275 function isElementInView(el) {
276     var rect = el && el.getBoundingClientRect() || {};
277
278     return (
279         rect.top >= 0 &&
280         rect.left >= 0 &&
281         rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
282         rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
283     );
284 }
285
286
287 // isReadOnly={state.isReadOnly} disabled={state.disabled} onChange={this.disableChange}
288
289 class isDisabled extends React.Component {
290     constructor(props) {
291         super(props);
292     }
293     render() {
294         let props = this.props;
295         return (<div/>)
296     }
297 }
298
299 /**
300  * AddItemFn:
301  */
302 class InputCollection extends React.Component {
303     constructor(props) {
304         super(props);
305         this.collection = props.collection;
306     }
307     buildTextInput(onChange, v, i) {
308         return (
309             <Input
310                 readonly={this.props.readonly}
311                 style={{flex: '1 1'}}
312                 key={i}
313                 value={v}
314                 onChange= {onChange.bind(null, i)}
315             />
316         )
317     }
318     buildSelectOption(initial, options, onChange, v, i) {
319         return (
320             <SelectOption
321                 readonly={this.props.readonly}
322                 key={`${i}-${v.replace(' ', '_')}`}
323                 intial={initial}
324                 defaultValue={v}
325                 options={options}
326                 onChange={onChange.bind(null, i)}
327             />
328         );
329     }
330     showInput() {
331
332     }
333     render() {
334         const props = this.props;
335         let inputType;
336         let className = "InputCollection";
337         if (props.className) {
338             className = `${className} ${props.className}`;
339         }
340         if (props.type == 'select') {
341             inputType = this.buildSelectOption.bind(this, props.initial, props.options, props.onChange);
342         } else {
343             inputType = this.buildTextInput.bind(this, props.onChange)
344         }
345         let html = (
346             <div className="InputCollection-wrapper">
347                 {props.collection.map((v,i) => {
348                     return (
349                         <div key={i} className={className} >
350                             {inputType(v, i)}
351                             {
352                                 props.readonly ? null : <span onClick={props.RemoveItemFn.bind(null, i)} className="removeInput"><img src={imgRemove} />Remove</span>}
353                         </div>
354                     )
355                 })}
356                 { props.readonly ? null : <span onClick={props.AddItemFn} className="addInput"><img src={imgAdd} />Add</span>}
357             </div>
358         );
359         return html;
360     }
361 }
362
363 InputCollection.defaultProps = {
364     input: Input,
365     collection: [],
366     onChange: function(i, e) {
367         console.log(`
368                         Updating with: ${e.target.value}
369                         At index of: ${i}
370                     `)
371     },
372     AddItemFn: function(e) {
373         console.log(`Adding a new item to collection`)
374     },
375     RemoveItemFn: function(i, e) {
376         console.log(`Removing item from collection at index of: ${i}`)
377     }
378 }
379
380 class FormSection extends React.Component {
381     render() {
382         let className = 'FormSection ' + this.props.className;
383         let html = (
384             <div
385                 style={this.props.style}
386                 className={className}
387             >
388                 <div className="FormSection-title">
389                     {this.props.title}
390                 </div>
391                 <div className="FormSection-body">
392                     {this.props.children}
393                 </div>
394             </div>
395         );
396         return html;
397     }
398 }
399
400 FormSection.defaultProps = {
401     className: ''
402 }