]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/eg2/src/app/share/org-select/org-select.component.ts
LP1904036 org-select rejects invalid free text
[working/Evergreen.git] / Open-ILS / src / eg2 / src / app / share / org-select / org-select.component.ts
1 /** TODO PORT ME TO <eg-combobox> */
2 import {Component, OnInit, Input, Output, ViewChild, EventEmitter} from '@angular/core';
3 import {Observable, Subject} from 'rxjs';
4 import {map, mapTo, debounceTime, distinctUntilChanged, merge, filter} from 'rxjs/operators';
5 import {AuthService} from '@eg/core/auth.service';
6 import {StoreService} from '@eg/core/store.service';
7 import {ServerStoreService} from '@eg/core/server-store.service';
8 import {OrgService} from '@eg/core/org.service';
9 import {IdlObject} from '@eg/core/idl.service';
10 import {PermService} from '@eg/core/perm.service';
11 import {NgbTypeahead, NgbTypeaheadSelectItemEvent} from '@ng-bootstrap/ng-bootstrap';
12
13 /** Org unit selector
14  *
15  * The following precedence is used when applying a load-time value
16  *
17  * 1. initialOrg / initialOrgId
18  * 2. Value from server setting specificed with persistKey (fires onload).
19  * 3. Value from fallbackOrg / fallbackOrgId (fires onload).
20  * 4. Default applyed when applyDefault is set (fires onload).
21  *
22  * Users can detect when the component has completed its load-time
23  * machinations by subscribing to the componentLoaded Output which
24  * fires exactly once when loading is completed.
25  */
26
27 // Use a unicode char for spacing instead of ASCII=32 so the browser
28 // won't collapse the nested display entries down to a single space.
29 const PAD_SPACE = ' '; // U+2007
30
31 interface OrgDisplay {
32   id: number;
33   label: string;
34   disabled: boolean;
35 }
36
37 @Component({
38   selector: 'eg-org-select',
39   templateUrl: './org-select.component.html'
40 })
41 export class OrgSelectComponent implements OnInit {
42     static domId = 0;
43
44     showCombinedNames = false; // Managed via user/workstation setting
45
46     _selected: OrgDisplay;
47     set selected(s: OrgDisplay) {
48         if (s !== this._selected) {
49             this._selected = s;
50
51             // orgChanged() does not fire when the value is cleared,
52             // so emit the onChange here for cleared values only.
53             if (!s) { // may be '' or null
54                 this._selected = null;
55                 this.onChange.emit(null);
56             }
57         }
58     }
59
60     get selected(): OrgDisplay {
61         return this._selected;
62     }
63
64     click$ = new Subject<string>();
65     valueFromSetting: number = null;
66     sortedOrgs: IdlObject[] = [];
67
68     // Disable the entire input
69     @Input() disabled: boolean;
70
71     @ViewChild('instance', { static: false }) instance: NgbTypeahead;
72
73     // Placeholder text for selector input
74     @Input() placeholder = '';
75
76     // ID to display in the DOM for this selector
77     @Input() domId = 'eg-org-select-' + OrgSelectComponent.domId++;
78
79     @Input() name = '';
80
81     // Org unit field displayed in the selector
82     @Input() displayField = 'shortname';
83
84     // if no initialOrg is provided, none could be found via persist
85     // setting, and no fallbackoOrg is provided, apply a sane default.
86     // First tries workstation org unit, then user home org unit.
87     // An onChange event WILL be generated when a default is applied.
88     @Input() applyDefault = false;
89
90     @Input() readOnly = false;
91
92     @Input() required = false;
93
94     // List of org unit IDs to exclude from the selector
95     hidden: number[] = [];
96     @Input() set hideOrgs(ids: number[]) {
97         if (ids) { this.hidden = ids; }
98     }
99
100     // List of org unit IDs to disable in the selector
101     _disabledOrgs: number[] = [];
102     @Input() set disableOrgs(ids: number[]) {
103         if (ids) { this._disabledOrgs = ids; }
104     }
105
106     get disableOrgs(): number[] {
107         return this._disabledOrgs;
108     }
109
110     // Apply an org unit value at load time.
111     // These will NOT result in an onChange event.
112     @Input() initialOrg: IdlObject;
113     @Input() initialOrgId: number;
114
115     // Value is persisted via server setting with this key.
116     // Key is prepended with 'eg.orgselect.'
117     @Input() persistKey: string;
118
119     // If no initialOrg is provided and no value could be found
120     // from a persist setting, fall back to one of these values.
121     // These WILL result in an onChange event
122     @Input() fallbackOrg: IdlObject;
123     @Input() fallbackOrgId: number;
124
125     // Modify the selected org unit via data binding.
126     // This WILL NOT result in an onChange event firing.
127     @Input() set applyOrg(org: IdlObject) {
128         this.selected = org ? this.formatForDisplay(org) : null;
129     }
130
131     // Modify the selected org unit by ID via data binding.
132     // This WILL NOT result in an onChange event firing.
133     @Input() set applyOrgId(id: number) {
134         this.selected = id ? this.formatForDisplay(this.org.get(id)) : null;
135     }
136
137     // Limit org unit display to those where the logged in user
138     // has the following permissions.
139     permLimitOrgs: number[];
140     @Input() set limitPerms(perms: string[]) {
141         this.applyPermLimitOrgs(perms);
142     }
143
144     // Function which should return a string value representing
145     // a CSS class name to use for styling each org unit label
146     // in the selector.
147     @Input() orgClassCallback: (orgId: number) => string;
148
149     // Emitted when the org unit value is changed via the selector.
150     // Does not fire on initialOrg
151     @Output() onChange = new EventEmitter<IdlObject>();
152
153     // Emitted once when the component is done fetching settings
154     // and applying its initial value.  For apps that use the value
155     // of this selector to load data, this event can be used to reliably
156     // detect when the selector is done with all of its automated
157     // underground shuffling and landed on a value.
158     @Output() componentLoaded: EventEmitter<void> = new EventEmitter<void>();
159
160     // convenience method to get an IdlObject representing the current
161     // selected org unit. One way of invoking this is via a template
162     // reference variable.
163     selectedOrg(): IdlObject {
164         if (this.selected == null) {
165             return null;
166         }
167         return this.org.get(this.selected.id);
168     }
169
170     selectedOrgId(): number {
171         return this.selected ? this.selected.id : null;
172     }
173
174     constructor(
175       private auth: AuthService,
176       private store: StoreService,
177       private serverStore: ServerStoreService,
178       private org: OrgService,
179       private perm: PermService
180     ) {
181         this.orgClassCallback = (orgId: number): string => '';
182     }
183
184     ngOnInit() {
185
186
187         let promise = this.persistKey ?
188             this.getFromSetting() : Promise.resolve(null);
189
190         promise = promise.then(startupOrg => {
191             return this.serverStore.getItem('eg.orgselect.show_combined_names')
192             .then(show => {
193                 const sortField = show ? 'name' : this.displayField;
194
195                 // Sort the tree and reabsorb to propagate the sorted
196                 // nodes to the org.list() used by this component.
197                 // Maintain our own copy of the org list in case the
198                 // org service is sorted in a different manner by other
199                 // parts of the code.
200                 this.org.sortTree(sortField);
201                 this.org.absorbTree();
202                 this.sortedOrgs = this.org.list();
203
204                 this.showCombinedNames = show;
205             })
206             .then(_ => startupOrg);
207         });
208
209         promise.then((startupOrgId: number) => {
210
211             if (!startupOrgId) {
212
213                 if (this.selected) {
214                     // A value may have been applied while we were
215                     // talking to the network.
216                     startupOrgId = this.selected.id;
217
218                 } else if (this.initialOrg) {
219                     startupOrgId = this.initialOrg.id();
220
221                 } else if (this.initialOrgId) {
222                     startupOrgId = this.initialOrgId;
223
224                 } else if (this.fallbackOrgId) {
225                     startupOrgId = this.fallbackOrgId;
226
227                 } else if (this.fallbackOrg) {
228                     startupOrgId = this.org.get(this.fallbackOrg).id();
229
230                 } else if (this.applyDefault && this.auth.user()) {
231                     startupOrgId = this.auth.user().ws_ou();
232                 }
233             }
234
235             let startupOrg;
236             if (startupOrgId) {
237                 startupOrg = this.org.get(startupOrgId);
238                 this.selected = this.formatForDisplay(startupOrg);
239             }
240
241             this.markAsLoaded(startupOrg);
242         });
243     }
244
245     getDisplayLabel(org: IdlObject): string {
246         if (this.showCombinedNames) {
247             return `${org.name()} (${org.shortname()})`;
248         } else {
249             return org[this.displayField]();
250         }
251     }
252
253     getFromSetting(): Promise<number> {
254
255         const key = `eg.orgselect.${this.persistKey}`;
256
257         return this.serverStore.getItem(key).then(
258             value => this.valueFromSetting = value
259         );
260     }
261
262     // Indicate all load-time shuffling has completed.
263     markAsLoaded(onChangeOrg?: IdlObject) {
264         setTimeout(() => { // Avoid emitting mid-digest
265             this.componentLoaded.emit();
266             this.componentLoaded.complete();
267             if (onChangeOrg) { this.onChange.emit(onChangeOrg); }
268         });
269     }
270
271     //
272     applyPermLimitOrgs(perms: string[]) {
273
274         if (!perms) {
275             return;
276         }
277
278         // handle lazy clients that pass null perm names
279         perms = perms.filter(p => p !== null && p !== undefined);
280
281         if (perms.length === 0) {
282             return;
283         }
284
285         // NOTE: If permLimitOrgs is useful in a non-staff context
286         // we need to change this to support non-staff perm checks.
287         this.perm.hasWorkPermAt(perms, true).then(permMap => {
288             this.permLimitOrgs =
289                 // safari-friendly version of Array.flat()
290                 Object.values(permMap).reduce((acc, val) => acc.concat(val), []);
291         });
292     }
293
294     // Format for display in the selector drop-down and input.
295     formatForDisplay(org: IdlObject): OrgDisplay {
296         let label = this.getDisplayLabel(org);
297         if (!this.readOnly) {
298             label = PAD_SPACE.repeat(org.ou_type().depth()) + label;
299         }
300         return {
301             id : org.id(),
302             label : label,
303             disabled : this.disableOrgs.includes(org.id())
304         };
305     }
306
307     // Fired by the typeahead to inform us of a change.
308     orgChanged(selEvent: NgbTypeaheadSelectItemEvent) {
309         // console.debug('org unit change occurred ' + selEvent.item);
310         this.onChange.emit(this.org.get(selEvent.item.id));
311
312         if (this.persistKey && this.valueFromSetting !== selEvent.item.id) {
313             // persistKey is active.  Update the persisted value when changed.
314
315             const key = `eg.orgselect.${this.persistKey}`;
316             this.valueFromSetting = selEvent.item.id;
317             this.serverStore.setItem(key, this.valueFromSetting);
318         }
319     }
320
321     // Remove the tree-padding spaces when matching.
322     formatter = (result: OrgDisplay) => result ? result.label.trim() : '';
323
324     // reset the state of the component
325     reset() {
326         this.selected = null;
327     }
328
329     // NgbTypeahead doesn't offer a way to style the dropdown
330     // button directly, so we have to reach up and style it ourselves.
331     applyDisableStyle() {
332         this.disableOrgs.forEach(id => {
333             const node = document.getElementById(`${this.domId}-${id}`);
334             if (node) {
335                 const button = node.parentNode as HTMLElement;
336                 button.classList.add('disabled');
337             }
338         });
339     }
340
341     // Free-text values are not allowed.
342     handleBlur() {
343         if (typeof this.selected === 'string') {
344             this.selected = null;
345         }
346     }
347
348     filter = (text$: Observable<string>): Observable<OrgDisplay[]> => {
349
350         return text$.pipe(
351             debounceTime(200),
352             distinctUntilChanged(),
353             merge(
354                 // Inject a specifier indicating the source of the
355                 // action is a user click
356                 this.click$.pipe(filter(() => !this.instance.isPopupOpen()))
357                 .pipe(mapTo('_CLICK_'))
358             ),
359             map(term => {
360
361                 let orgs = this.sortedOrgs.filter(org =>
362                     this.hidden.filter(id => org.id() === id).length === 0
363                 );
364
365                 if (this.permLimitOrgs) {
366                     // Avoid showing org units where the user does
367                     // not have the requested permission.
368                     orgs = orgs.filter(org =>
369                         this.permLimitOrgs.includes(org.id()));
370                 }
371
372                 if (term !== '_CLICK_') {
373                     // For search-driven events, limit to the matching
374                     // org units.
375                     orgs = orgs.filter(org => {
376                         return term === '' || // show all
377                             this.getDisplayLabel(org)
378                                 .toLowerCase().indexOf(term.toLowerCase()) > -1;
379
380                     });
381                 }
382
383                 // Give the typeahead a chance to open before applying
384                 // the disabled org unit styling.
385                 setTimeout(() => this.applyDisableStyle());
386
387                 return orgs.map(org => this.formatForDisplay(org));
388             })
389         );
390     }
391 }
392
393