]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/eg2/src/app/share/org-select/org-select.component.ts
LP1908743 Org select now supports disabled org unit
[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     selected: OrgDisplay;
45     click$ = new Subject<string>();
46     valueFromSetting: number = null;
47     sortedOrgs: IdlObject[] = [];
48
49     // Disable the entire input
50     @Input() disabled: boolean;
51
52     @ViewChild('instance', { static: false }) instance: NgbTypeahead;
53
54     // Placeholder text for selector input
55     @Input() placeholder = '';
56
57     // ID to display in the DOM for this selector
58     @Input() domId = 'eg-org-select-' + OrgSelectComponent.domId++;
59
60     // Org unit field displayed in the selector
61     @Input() displayField = 'shortname';
62
63     // if no initialOrg is provided, none could be found via persist
64     // setting, and no fallbackoOrg is provided, apply a sane default.
65     // First tries workstation org unit, then user home org unit.
66     // An onChange event WILL be generated when a default is applied.
67     @Input() applyDefault = false;
68
69     @Input() readOnly = false;
70
71     // List of org unit IDs to exclude from the selector
72     hidden: number[] = [];
73     @Input() set hideOrgs(ids: number[]) {
74         if (ids) { this.hidden = ids; }
75     }
76
77     // List of org unit IDs to disable in the selector
78     _disabledOrgs: number[] = [];
79     @Input() set disableOrgs(ids: number[]) {
80         if (ids) { this._disabledOrgs = ids; }
81     }
82
83     get disableOrgs(): number[] {
84         return this._disabledOrgs;
85     }
86
87     // Apply an org unit value at load time.
88     // These will NOT result in an onChange event.
89     @Input() initialOrg: IdlObject;
90     @Input() initialOrgId: number;
91
92     // Value is persisted via server setting with this key.
93     // Key is prepended with 'eg.orgselect.'
94     @Input() persistKey: string;
95
96     // If no initialOrg is provided and no value could be found
97     // from a persist setting, fall back to one of these values.
98     // These WILL result in an onChange event
99     @Input() fallbackOrg: IdlObject;
100     @Input() fallbackOrgId: number;
101
102     // Modify the selected org unit via data binding.
103     // This WILL NOT result in an onChange event firing.
104     @Input() set applyOrg(org: IdlObject) {
105         this.selected = org ? this.formatForDisplay(org) : null;
106     }
107
108     // Modify the selected org unit by ID via data binding.
109     // This WILL NOT result in an onChange event firing.
110     @Input() set applyOrgId(id: number) {
111         this.selected = id ? this.formatForDisplay(this.org.get(id)) : null;
112     }
113
114     // Limit org unit display to those where the logged in user
115     // has the following permissions.
116     permLimitOrgs: number[];
117     @Input() set limitPerms(perms: string[]) {
118         this.applyPermLimitOrgs(perms);
119     }
120
121     // Emitted when the org unit value is changed via the selector.
122     // Does not fire on initialOrg
123     @Output() onChange = new EventEmitter<IdlObject>();
124
125     // Emitted once when the component is done fetching settings
126     // and applying its initial value.  For apps that use the value
127     // of this selector to load data, this event can be used to reliably
128     // detect when the selector is done with all of its automated
129     // underground shuffling and landed on a value.
130     @Output() componentLoaded: EventEmitter<void> = new EventEmitter<void>();
131
132     // convenience method to get an IdlObject representing the current
133     // selected org unit. One way of invoking this is via a template
134     // reference variable.
135     selectedOrg(): IdlObject {
136         if (this.selected == null) {
137             return null;
138         }
139         return this.org.get(this.selected.id);
140     }
141
142     constructor(
143       private auth: AuthService,
144       private store: StoreService,
145       private serverStore: ServerStoreService,
146       private org: OrgService,
147       private perm: PermService
148     ) { }
149
150     ngOnInit() {
151
152         // Sort the tree and reabsorb to propagate the sorted nodes to
153         // the org.list() used by this component.  Maintain our own
154         // copy of the org list in case the org service is sorted in a
155         // different manner by other parts of the code.
156         this.org.sortTree(this.displayField);
157         this.org.absorbTree();
158         this.sortedOrgs = this.org.list();
159
160         const promise = this.persistKey ?
161             this.getFromSetting() : Promise.resolve(null);
162
163         promise.then((startupOrgId: number) => {
164
165             if (!startupOrgId) {
166
167                 if (this.selected) {
168                     // A value may have been applied while we were
169                     // talking to the network.
170                     startupOrgId = this.selected.id;
171
172                 } else if (this.initialOrg) {
173                     startupOrgId = this.initialOrg.id();
174
175                 } else if (this.initialOrgId) {
176                     startupOrgId = this.initialOrgId;
177
178                 } else if (this.fallbackOrgId) {
179                     startupOrgId = this.fallbackOrgId;
180
181                 } else if (this.fallbackOrg) {
182                     startupOrgId = this.org.get(this.fallbackOrg).id();
183
184                 } else if (this.applyDefault && this.auth.user()) {
185                     startupOrgId = this.auth.user().ws_ou();
186                 }
187             }
188
189             let startupOrg;
190             if (startupOrgId) {
191                 startupOrg = this.org.get(startupOrgId);
192                 this.selected = this.formatForDisplay(startupOrg);
193             }
194
195             this.markAsLoaded(startupOrg);
196         });
197     }
198
199     getFromSetting(): Promise<number> {
200
201         const key = `eg.orgselect.${this.persistKey}`;
202
203         return this.serverStore.getItem(key).then(
204             value => this.valueFromSetting = value
205         );
206     }
207
208     // Indicate all load-time shuffling has completed.
209     markAsLoaded(onChangeOrg?: IdlObject) {
210         setTimeout(() => { // Avoid emitting mid-digest
211             this.componentLoaded.emit();
212             this.componentLoaded.complete();
213             if (onChangeOrg) { this.onChange.emit(onChangeOrg); }
214         });
215     }
216
217     //
218     applyPermLimitOrgs(perms: string[]) {
219
220         if (!perms) {
221             return;
222         }
223
224         // handle lazy clients that pass null perm names
225         perms = perms.filter(p => p !== null && p !== undefined);
226
227         if (perms.length === 0) {
228             return;
229         }
230
231         // NOTE: If permLimitOrgs is useful in a non-staff context
232         // we need to change this to support non-staff perm checks.
233         this.perm.hasWorkPermAt(perms, true).then(permMap => {
234             this.permLimitOrgs =
235                 // safari-friendly version of Array.flat()
236                 Object.values(permMap).reduce((acc, val) => acc.concat(val), []);
237         });
238     }
239
240     // Format for display in the selector drop-down and input.
241     formatForDisplay(org: IdlObject): OrgDisplay {
242         let label = org[this.displayField]();
243         if (!this.readOnly) {
244             label = PAD_SPACE.repeat(org.ou_type().depth()) + label;
245         }
246         return {
247             id : org.id(),
248             label : label,
249             disabled : this.disableOrgs.includes(org.id())
250         };
251     }
252
253     // Fired by the typeahead to inform us of a change.
254     // TODO: this does not fire when the value is cleared :( -- implement
255     // change detection on this.selected to look specifically for NULL.
256     orgChanged(selEvent: NgbTypeaheadSelectItemEvent) {
257         // console.debug('org unit change occurred ' + selEvent.item);
258         this.onChange.emit(this.org.get(selEvent.item.id));
259
260         if (this.persistKey && this.valueFromSetting !== selEvent.item.id) {
261             // persistKey is active.  Update the persisted value when changed.
262
263             const key = `eg.orgselect.${this.persistKey}`;
264             this.valueFromSetting = selEvent.item.id;
265             this.serverStore.setItem(key, this.valueFromSetting);
266         }
267     }
268
269     // Remove the tree-padding spaces when matching.
270     formatter = (result: OrgDisplay) => result ? result.label.trim() : '';
271
272     // reset the state of the component
273     reset() {
274         this.selected = null;
275     }
276
277     // NgbTypeahead doesn't offer a way to style the dropdown
278     // button directly, so we have to reach up and style it ourselves.
279     applyDisableStyle() {
280         this.disableOrgs.forEach(id => {
281             const node = document.getElementById(`${this.domId}-${id}`);
282             if (node) {
283                 const button = node.parentNode as HTMLElement;
284                 button.classList.add('disabled');
285             }
286         });
287     }
288
289     filter = (text$: Observable<string>): Observable<OrgDisplay[]> => {
290
291         return text$.pipe(
292             debounceTime(200),
293             distinctUntilChanged(),
294             merge(
295                 // Inject a specifier indicating the source of the
296                 // action is a user click
297                 this.click$.pipe(filter(() => !this.instance.isPopupOpen()))
298                 .pipe(mapTo('_CLICK_'))
299             ),
300             map(term => {
301
302                 let orgs = this.sortedOrgs.filter(org =>
303                     this.hidden.filter(id => org.id() === id).length === 0
304                 );
305
306                 if (this.permLimitOrgs) {
307                     // Avoid showing org units where the user does
308                     // not have the requested permission.
309                     orgs = orgs.filter(org =>
310                         this.permLimitOrgs.includes(org.id()));
311                 }
312
313                 if (term !== '_CLICK_') {
314                     // For search-driven events, limit to the matching
315                     // org units.
316                     orgs = orgs.filter(org => {
317                         return term === '' || // show all
318                             org[this.displayField]()
319                                 .toLowerCase().indexOf(term.toLowerCase()) > -1;
320
321                     });
322                 }
323
324                 // Give the typeahead a chance to open before applying
325                 // the disabled org unit styling.
326                 setTimeout(() => this.applyDisableStyle());
327
328                 return orgs.map(org => this.formatForDisplay(org));
329             })
330         );
331     }
332 }
333
334