]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/eg2/src/app/share/org-select/org-select.component.ts
39e0cff2ea04ea05ad3ff48d66e72abfe29f15c1
[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} from 'rxjs/Observable';
4 import {map} from 'rxjs/operators/map';
5 import {mapTo} from 'rxjs/operators/mapTo';
6 import {debounceTime} from 'rxjs/operators/debounceTime';
7 import {distinctUntilChanged} from 'rxjs/operators/distinctUntilChanged';
8 import {merge} from 'rxjs/operators/merge';
9 import {filter} from 'rxjs/operators/filter';
10 import {Subject} from 'rxjs/Subject';
11 import {AuthService} from '@eg/core/auth.service';
12 import {StoreService} from '@eg/core/store.service';
13 import {OrgService} from '@eg/core/org.service';
14 import {IdlObject} from '@eg/core/idl.service';
15 import {PermService} from '@eg/core/perm.service';
16 import {NgbTypeahead, NgbTypeaheadSelectItemEvent} from '@ng-bootstrap/ng-bootstrap';
17
18 // Use a unicode char for spacing instead of ASCII=32 so the browser
19 // won't collapse the nested display entries down to a single space.
20 const PAD_SPACE = ' '; // U+2007
21
22 interface OrgDisplay {
23   id: number;
24   label: string;
25   disabled: boolean;
26 }
27
28 @Component({
29   selector: 'eg-org-select',
30   templateUrl: './org-select.component.html'
31 })
32 export class OrgSelectComponent implements OnInit {
33
34     selected: OrgDisplay;
35     hidden: number[] = [];
36     disabled: number[] = [];
37     click$ = new Subject<string>();
38     startOrg: IdlObject;
39
40     @ViewChild('instance') instance: NgbTypeahead;
41
42     // Placeholder text for selector input
43     @Input() placeholder = '';
44     @Input() stickySetting: string;
45
46     // Org unit field displayed in the selector
47     @Input() displayField = 'shortname';
48
49     // Apply a default org unit value when none is set.
50     // First tries workstation org unit, then user home org unit.
51     // An onChange event WILL be generated when a default is applied.
52     @Input() applyDefault = false;
53
54     // List of org unit IDs to exclude from the selector
55     @Input() set hideOrgs(ids: number[]) {
56         if (ids) { this.hidden = ids; }
57     }
58
59     // List of org unit IDs to disable in the selector
60     @Input() set disableOrgs(ids: number[]) {
61         if (ids) { this.disabled = ids; }
62     }
63
64     // Apply an org unit value at load time.
65     // This will NOT result in an onChange event.
66     @Input() set initialOrg(org: IdlObject) {
67         if (org) { this.startOrg = org; }
68     }
69
70     // Apply an org unit value by ID at load time.
71     // This will NOT result in an onChange event.
72     @Input() set initialOrgId(id: number) {
73         if (id) { this.startOrg = this.org.get(id); }
74     }
75
76     // Modify the selected org unit via data binding.
77     // This WILL result in an onChange event firing.
78     @Input() set applyOrg(org: IdlObject) {
79         if (org) {
80             this.selected = this.formatForDisplay(org);
81         }
82     }
83
84     permLimitOrgs: number[];
85     @Input() set limitPerms(perms: string[]) {
86         this.applyPermLimitOrgs(perms);
87     }
88
89     // Modify the selected org unit by ID via data binding.
90     // This WILL result in an onChange event firing.
91     @Input() set applyOrgId(id: number) {
92         if (id) {
93             this.selected = this.formatForDisplay(this.org.get(id));
94         }
95     }
96
97     // Emitted when the org unit value is changed via the selector.
98     // Does not fire on initialOrg
99     @Output() onChange = new EventEmitter<IdlObject>();
100
101     constructor(
102       private auth: AuthService,
103       private store: StoreService,
104       private org: OrgService,
105       private perm: PermService
106     ) { }
107
108     ngOnInit() {
109
110         // Apply a default org unit if desired and possible.
111         if (!this.startOrg && this.applyDefault && this.auth.user()) {
112             // note: ws_ou defaults to home_ou on the server
113             // when when no workstation is used
114             this.startOrg = this.org.get(this.auth.user().ws_ou());
115             this.selected = this.formatForDisplay(
116                 this.org.get(this.auth.user().ws_ou())
117             );
118
119             // avoid notifying mid-digest
120             setTimeout(() => this.onChange.emit(this.startOrg), 0);
121         }
122
123         if (this.startOrg) {
124             this.selected = this.formatForDisplay(this.startOrg);
125         }
126     }
127
128     //
129     applyPermLimitOrgs(perms: string[]) {
130
131         if (!perms) {
132             return;
133         }
134
135         // handle lazy clients that pass null perm names
136         perms = perms.filter(p => p !== null && p !== undefined);
137
138         if (perms.length === 0) {
139             return;
140         }
141
142         // NOTE: If permLimitOrgs is useful in a non-staff context
143         // we need to change this to support non-staff perm checks.
144         this.perm.hasWorkPermAt(perms, true).then(permMap => {
145             this.permLimitOrgs =
146                 // safari-friendly version of Array.flat()
147                 Object.values(permMap).reduce((acc, val) => acc.concat(val), []);
148         });
149     }
150
151     // Format for display in the selector drop-down and input.
152     formatForDisplay(org: IdlObject): OrgDisplay {
153         return {
154             id : org.id(),
155             label : PAD_SPACE.repeat(org.ou_type().depth())
156               + org[this.displayField](),
157             disabled : false
158         };
159     }
160
161     // Fired by the typeahead to inform us of a change.
162     // TODO: this does not fire when the value is cleared :( -- implement
163     // change detection on this.selected to look specifically for NULL.
164     orgChanged(selEvent: NgbTypeaheadSelectItemEvent) {
165         // console.debug('org unit change occurred ' + selEvent.item);
166         this.onChange.emit(this.org.get(selEvent.item.id));
167     }
168
169     // Remove the tree-padding spaces when matching.
170     formatter = (result: OrgDisplay) => result.label.trim();
171
172     filter = (text$: Observable<string>): Observable<OrgDisplay[]> => {
173         return text$.pipe(
174             debounceTime(200),
175             distinctUntilChanged(),
176             merge(
177                 // Inject a specifier indicating the source of the
178                 // action is a user click
179                 this.click$.pipe(filter(() => !this.instance.isPopupOpen()))
180                 .pipe(mapTo('_CLICK_'))
181             ),
182             map(term => {
183
184                 let orgs = this.org.list().filter(org =>
185                     this.hidden.filter(id => org.id() === id).length === 0
186                 );
187
188                 if (this.permLimitOrgs) {
189                     // Avoid showing org units where the user does
190                     // not have the requested permission.
191                     orgs = orgs.filter(org =>
192                         this.permLimitOrgs.includes(org.id()));
193                 }
194
195                 if (term !== '_CLICK_') {
196                     // For search-driven events, limit to the matching
197                     // org units.
198                     orgs = orgs.filter(org => {
199                         return term === '' || // show all
200                             org[this.displayField]()
201                                 .toLowerCase().indexOf(term.toLowerCase()) > -1;
202
203                     });
204                 }
205
206                 return orgs.map(org => this.formatForDisplay(org));
207             })
208         );
209     }
210 }
211
212