]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/eg2/src/app/share/item-location-select/item-location-select.component.ts
4317500fc46ce863c3b36095ba8d57ef2e06e4d2
[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     private _contextOrgId: number;
41     @Input() set contextOrgId(value: number) {
42         this._contextOrgId = value;
43         this.ngOnInit();
44     }
45
46     @Input() orgUnitLabelField = 'shortname';
47
48     // Emits an acpl object or null on combobox value change
49     @Output() valueChange: EventEmitter<IdlObject>;
50
51     @Input() required: boolean;
52
53     @Input() domId = 'eg-item-location-select-' +
54         ItemLocationSelectComponent.domIdAuto++;
55
56     @ViewChild('comboBox', {static: false}) comboBox: ComboboxComponent;
57     @ViewChild('unsetString', {static: false}) unsetString: StringComponent;
58
59     startId: number = null;
60     filterOrgs: number[] = [];
61     cache: {[id: number]: IdlObject} = {};
62
63     initDone = false; // true after first data load
64     propagateChange = (id: number) => {};
65     propagateTouch = () => {};
66
67     constructor(
68         private org: OrgService,
69         private auth: AuthService,
70         private perm: PermService,
71         private pcrud: PcrudService
72     ) {
73         this.valueChange = new EventEmitter<IdlObject>();
74     }
75
76     ngOnInit() {
77         this.setFilterOrgs()
78         .then(_ => this.getLocations())
79         .then(_ => this.initDone = true);
80     }
81
82     ngAfterViewInit() {
83
84         // Format the display of locations to include the org unit
85         this.comboBox.formatDisplayString = (result: ComboboxEntry) => {
86             let display = result.label || result.id;
87             display = (display + '').trim();
88             if (result.userdata) {
89                 display += ' (' +
90                     this.orgName(result.userdata.owning_lib()) + ')';
91             }
92             return display;
93         };
94     }
95
96     getLocations(): Promise<any> {
97
98         if (this.filterOrgs.length === 0) {
99             this.comboBox.entries = [];
100             return Promise.resolve();
101         }
102
103         const search: any = {deleted: 'f'};
104
105         if (this.startId) {
106             // Guarantee we have the load-time copy location, which
107             // may not be included in the org-scoped set of locations
108             // we fetch by default.
109             search['-or'] = [
110                 {id: this.startId},
111                 {owning_lib: this.filterOrgs}
112             ];
113         } else {
114             search.owning_lib = this.filterOrgs;
115         }
116
117         const entries: ComboboxEntry[] = [];
118
119         if (!this.required) {
120             entries.push({id: null, label: this.unsetString.text});
121         }
122
123         return this.pcrud.search('acpl', search, {order_by: {acpl: 'name'}}
124         ).pipe(map(loc => {
125             this.cache[loc.id()] = loc;
126             entries.push({id: loc.id(), label: loc.name(), userdata: loc});
127         })).toPromise().then(_ => {
128             this.comboBox.entries = entries;
129         });
130     }
131
132     registerOnChange(fn) {
133         this.propagateChange = fn;
134     }
135
136     registerOnTouched(fn) {
137         this.propagateTouch = fn;
138     }
139
140     cboxChanged(entry: ComboboxEntry) {
141         const id = entry ? entry.id : null;
142         this.propagateChange(id);
143         this.valueChange.emit(id ? this.cache[id] : null);
144     }
145
146     writeValue(id: number) {
147         if (this.initDone) {
148             this.getOneLocation(id).then(_ => this.comboBox.selectedId = id);
149         } else {
150             this.startId = id;
151         }
152     }
153
154     getOneLocation(id: number) {
155         if (!id || this.cache[id]) { return Promise.resolve(); }
156
157         return this.pcrud.retrieve('acpl', id).toPromise()
158         .then(loc => {
159             this.cache[loc.id()] = loc;
160             this.comboBox.addAsyncEntry(
161                 {id: loc.id(), label: loc.name(), userdata: loc});
162         });
163     }
164
165     setFilterOrgs(): Promise<number[]> {
166         const org = this._contextOrgId || this.auth.user().ws_ou();
167         const contextOrgIds = this.org.ancestors(org, true);
168
169         if (!this.permFilter) {
170             return Promise.resolve(this.filterOrgs = contextOrgIds);
171         }
172
173         return this.perm.hasWorkPermAt([this.permFilter], true)
174         .then(values => {
175             // Always limit the org units to /at most/ those within
176             // scope of the context org ID.
177
178             const permOrgIds = values[this.permFilter];
179             const trimmedOrgIds = [];
180             permOrgIds.forEach(orgId => {
181                 if (contextOrgIds.includes(orgId)) {
182                     trimmedOrgIds.push(orgId);
183                 }
184             });
185
186             return this.filterOrgs = trimmedOrgIds;
187         });
188     }
189
190     orgName(orgId: number): string {
191         return this.org.get(orgId)[this.orgUnitLabelField]();
192     }
193 }
194
195
196