]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/eg2/src/app/share/item-location-select/item-location-select.component.ts
LP1888723 Item location select honors context org
[Evergreen.git] / Open-ILS / src / eg2 / src / app / share / item-location-select / item-location-select.component.ts
1 import {Component, OnInit, AfterViewInit, Input, Output, ViewChild,
2     EventEmitter, forwardRef} from '@angular/core';
3 import {ControlValueAccessor, FormGroup, FormControl, NG_VALUE_ACCESSOR} from '@angular/forms';
4 import {Observable} from 'rxjs';
5 import {map} from 'rxjs/operators';
6 import {IdlObject} from '@eg/core/idl.service';
7 import {OrgService} from '@eg/core/org.service';
8 import {AuthService} from '@eg/core/auth.service';
9 import {PermService} from '@eg/core/perm.service';
10 import {PcrudService} from '@eg/core/pcrud.service';
11 import {ComboboxComponent, ComboboxEntry} from '@eg/share/combobox/combobox.component';
12 import {StringComponent} from '@eg/share/string/string.component';
13
14 /**
15  * Item (Copy) Location Selector.
16  *
17  * <eg-item-location-select [(ngModel)]="myAcplId"
18     [contextOrgId]="anOrgId" permFilter="ADMIN_STUFF">
19  * </eg-item-location-select>
20  */
21
22 @Component({
23   selector: 'eg-item-location-select',
24   templateUrl: './item-location-select.component.html',
25   providers: [{
26       provide: NG_VALUE_ACCESSOR,
27       useExisting: forwardRef(() => ItemLocationSelectComponent),
28       multi: true
29   }]
30 })
31 export class ItemLocationSelectComponent
32     implements OnInit, AfterViewInit, ControlValueAccessor {
33     static domIdAuto = 0;
34
35     // Limit copy locations to those owned at or above org units where
36     // the user has work permissions for the provided permission code.
37     @Input() permFilter: string;
38
39     // Limit copy locations to those owned at or above this org unit.
40     @Input() contextOrgId: number;
41
42     @Input() orgUnitLabelField = 'shortname';
43
44     // Emits an acpl object or null on combobox value change
45     @Output() valueChange: EventEmitter<IdlObject>;
46
47     @Input() required: boolean;
48
49     @Input() domId = 'eg-item-location-select-' +
50         ItemLocationSelectComponent.domIdAuto++;
51
52     @ViewChild('comboBox', {static: false}) comboBox: ComboboxComponent;
53     @ViewChild('unsetString', {static: false}) unsetString: StringComponent;
54
55     startId: number = null;
56     filterOrgs: number[] = [];
57     cache: {[id: number]: IdlObject} = {};
58
59     initDone = false; // true after first data load
60     propagateChange = (id: number) => {};
61     propagateTouch = () => {};
62
63     constructor(
64         private org: OrgService,
65         private auth: AuthService,
66         private perm: PermService,
67         private pcrud: PcrudService
68     ) {
69         this.valueChange = new EventEmitter<IdlObject>();
70     }
71
72     ngOnInit() {
73         this.setFilterOrgs()
74         .then(_ => this.getLocations())
75         .then(_ => this.initDone = true);
76     }
77
78     ngAfterViewInit() {
79
80         // Format the display of locations to include the org unit
81         this.comboBox.formatDisplayString = (result: ComboboxEntry) => {
82             let display = result.label || result.id;
83             display = (display + '').trim();
84             if (result.userdata) {
85                 display += ' (' +
86                     this.orgName(result.userdata.owning_lib()) + ')';
87             }
88             return display;
89         };
90     }
91
92     getLocations(): Promise<any> {
93
94         if (this.filterOrgs.length === 0) {
95             this.comboBox.entries = [];
96             return Promise.resolve();
97         }
98
99         const search: any = {deleted: 'f'};
100
101         if (this.startId) {
102             // Guarantee we have the load-time copy location, which
103             // may not be included in the org-scoped set of locations
104             // we fetch by default.
105             search['-or'] = [
106                 {id: this.startId},
107                 {owning_lib: this.filterOrgs}
108             ];
109         } else {
110             search.owning_lib = this.filterOrgs;
111         }
112
113         const entries: ComboboxEntry[] = [];
114
115         if (!this.required) {
116             entries.push({id: null, label: this.unsetString.text});
117         }
118
119         return this.pcrud.search('acpl', search, {order_by: {acpl: 'name'}}
120         ).pipe(map(loc => {
121             this.cache[loc.id()] = loc;
122             entries.push({id: loc.id(), label: loc.name(), userdata: loc});
123         })).toPromise().then(_ => {
124             this.comboBox.entries = entries;
125         });
126     }
127
128     registerOnChange(fn) {
129         this.propagateChange = fn;
130     }
131
132     registerOnTouched(fn) {
133         this.propagateTouch = fn;
134     }
135
136     cboxChanged(entry: ComboboxEntry) {
137         const id = entry ? entry.id : null;
138         this.propagateChange(id);
139         this.valueChange.emit(id ? this.cache[id] : null);
140     }
141
142     writeValue(id: number) {
143         if (this.initDone) {
144             this.getOneLocation(id).then(_ => this.comboBox.selectedId = id);
145         } else {
146             this.startId = id;
147         }
148     }
149
150     getOneLocation(id: number) {
151         if (!id || this.cache[id]) { return Promise.resolve(); }
152
153         return this.pcrud.retrieve('acpl', id).toPromise()
154         .then(loc => {
155             this.cache[loc.id()] = loc;
156             this.comboBox.addAsyncEntry(
157                 {id: loc.id(), label: loc.name(), userdata: loc});
158         });
159     }
160
161     setFilterOrgs(): Promise<number[]> {
162         const org = this.contextOrgId || this.auth.user().ws_ou();
163         const contextOrgIds = this.org.ancestors(org, true);
164
165         if (!this.permFilter) {
166             return Promise.resolve(this.filterOrgs = contextOrgIds);
167         }
168
169         return this.perm.hasWorkPermAt([this.permFilter], true)
170         .then(values => {
171             // Always limit the org units to /at most/ those within
172             // scope of the context org ID.
173
174             const permOrgIds = values[this.permFilter];
175             const trimmedOrgIds = [];
176             permOrgIds.forEach(orgId => {
177                 if (contextOrgIds.includes(orgId)) {
178                     trimmedOrgIds.push(orgId);
179                 }
180             });
181
182             return this.filterOrgs = trimmedOrgIds;
183         });
184     }
185
186     orgName(orgId: number): string {
187         return this.org.get(orgId)[this.orgUnitLabelField]();
188     }
189 }
190
191
192