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, of} from 'rxjs';
5 import {tap, map, switchMap} 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 import {ItemLocationService} from './item-location-select.service';
16 * Item (Copy) Location Selector.
18 * <eg-item-location-select [(ngModel)]="myAcplId"
19 [contextOrgId]="anOrgId" permFilter="ADMIN_STUFF">
20 * </eg-item-location-select>
24 selector: 'eg-item-location-select',
25 templateUrl: './item-location-select.component.html',
27 provide: NG_VALUE_ACCESSOR,
28 useExisting: forwardRef(() => ItemLocationSelectComponent),
32 export class ItemLocationSelectComponent
33 implements OnInit, AfterViewInit, ControlValueAccessor {
36 // Limit copy locations to those owned at or above org units where
37 // the user has work permissions for the provided permission code.
38 @Input() permFilter: string;
40 // Limit copy locations to those owned at or above this org unit.
41 private _contextOrgId: number;
42 @Input() set contextOrgId(value: number) {
43 this._contextOrgId = value;
47 get contextOrgId(): number {
48 return this._contextOrgId;
51 // Load locations for multiple context org units.
52 private _contextOrgIds = [];
53 @Input() set contextOrgIds(value: number[]) {
54 this._contextOrgIds = value;
57 get contextOrgIds(): number[] {
58 return this._contextOrgIds;
61 @Input() orgUnitLabelField = 'shortname';
63 // Emits an acpl object or null on combobox value change
64 @Output() valueChange: EventEmitter<IdlObject>;
66 @Input() required: boolean;
68 @Input() domId = 'eg-item-location-select-' +
69 ItemLocationSelectComponent.domIdAuto++;
71 // If false, selector will be click-able
72 @Input() loadAsync = true;
74 @Input() disabled = false;
76 // Display the selected value as text instead of within
78 @Input() readOnly = false;
80 @ViewChild('comboBox', {static: false}) comboBox: ComboboxComponent;
81 @ViewChild('unsetString', {static: false}) unsetString: StringComponent;
83 @Input() startId: number = null;
84 filterOrgs: number[] = [];
85 filterOrgsApplied = false;
87 initDone = false; // true after first data load
88 propagateChange = (id: number) => {};
89 propagateTouch = () => {};
91 getLocationsAsyncHandler = term => this.getLocationsAsync(term);
94 private org: OrgService,
95 private auth: AuthService,
96 private perm: PermService,
97 private pcrud: PcrudService,
98 private loc: ItemLocationService
100 this.valueChange = new EventEmitter<IdlObject>();
104 if (this.loadAsync) {
105 this.initDone = true;
108 .then(_ => this.getLocations())
109 .then(_ => this.initDone = true);
115 // Format the display of locations to include the org unit
116 this.comboBox.formatDisplayString = (result: ComboboxEntry) => {
117 let display = result.label || result.id;
118 display = (display + '').trim();
119 if (result.userdata) {
121 this.orgName(result.userdata.owning_lib()) + ')';
127 getLocations(): Promise<any> {
129 if (this.filterOrgs.length === 0) {
130 this.comboBox.entries = [];
131 return Promise.resolve();
134 const search: any = {deleted: 'f'};
137 // Guarantee we have the load-time copy location, which
138 // may not be included in the org-scoped set of locations
139 // we fetch by default.
142 {owning_lib: this.filterOrgs}
145 search.owning_lib = this.filterOrgs;
148 const entries: ComboboxEntry[] = [];
150 if (!this.required) {
151 entries.push({id: null, label: this.unsetString.text});
154 return this.pcrud.search('acpl', search, {order_by: {acpl: 'name'}}
156 this.loc.locationCache[loc.id()] = loc;
157 entries.push({id: loc.id(), label: loc.name(), userdata: loc});
158 })).toPromise().then(_ => {
159 this.comboBox.entries = entries;
163 getLocationsAsync(term: string): Observable<ComboboxEntry> {
166 if (!this.filterOrgsApplied) {
167 // Apply filter orgs the first time they are needed.
168 obs = from(this.setFilterOrgs());
171 return obs.pipe(switchMap(_ => this.getLocationsAsync2(term)));
174 getLocationsAsync2(term: string): Observable<ComboboxEntry> {
176 if (this.filterOrgs.length === 0) {
180 const search: any = {
182 name: {'ilike': `%${term}%`}
186 // Guarantee we have the load-time copy location, which
187 // may not be included in the org-scoped set of locations
188 // we fetch by default.
191 {owning_lib: this.filterOrgs}
194 search.owning_lib = this.filterOrgs;
197 return new Observable<ComboboxEntry>(observer => {
198 if (!this.required) {
199 observer.next({id: null, label: this.unsetString.text});
202 this.pcrud.search('acpl', search, {order_by: {acpl: 'name'}}
205 this.loc.locationCache[loc.id()] = loc;
206 observer.next({id: loc.id(), label: loc.name(), userdata: loc});
209 () => observer.complete()
215 registerOnChange(fn) {
216 this.propagateChange = fn;
219 registerOnTouched(fn) {
220 this.propagateTouch = fn;
223 cboxChanged(entry: ComboboxEntry) {
224 const id = entry ? entry.id : null;
225 this.propagateChange(id);
226 this.valueChange.emit(id ? this.loc.locationCache[id] : null);
229 writeValue(id: number) {
231 this.getOneLocation(id).then(_ => this.comboBox.selectedId = id);
237 getOneLocation(id: number) {
238 if (!id) { return Promise.resolve(); }
240 const promise = this.loc.locationCache[id] ?
241 Promise.resolve(this.loc.locationCache[id]) :
242 this.pcrud.retrieve('acpl', id).toPromise();
244 return promise.then(loc => {
246 this.loc.locationCache[loc.id()] = loc;
247 const entry: ComboboxEntry = {
248 id: loc.id(), label: loc.name(), userdata: loc};
250 if (this.comboBox.entries) {
251 this.comboBox.entries.push(entry);
253 this.comboBox.entries = [entry];
258 setFilterOrgs(): Promise<number[]> {
259 let contextOrgIds: number[] = [];
261 if (this.contextOrgIds.length) {
262 contextOrgIds = this.contextOrgIds;
264 contextOrgIds = [this.contextOrgId || this.auth.user().ws_ou()];
268 contextOrgIds.forEach(id => orgIds = orgIds.concat(this.org.ancestors(id, true)));
270 this.filterOrgsApplied = true;
272 if (!this.permFilter) {
273 return Promise.resolve(this.filterOrgs = [...new Set(orgIds)]);
276 const orgsFromCache = this.loc.filterOrgsCache[this.permFilter];
278 return Promise.resolve(this.filterOrgs = orgsFromCache);
281 return this.perm.hasWorkPermAt([this.permFilter], true)
283 // Include ancestors of perm-approved org units (shared item locations)
285 const permOrgIds = values[this.permFilter];
286 let trimmedOrgIds = [];
287 permOrgIds.forEach(orgId => {
288 if (orgIds.includes(orgId)) {
289 trimmedOrgIds = trimmedOrgIds.concat(this.org.ancestors(orgId, true));
293 this.filterOrgs = [...new Set(trimmedOrgIds)];
294 this.loc.filterOrgsCache[this.permFilter] = this.filterOrgs;
296 return this.filterOrgs;
300 orgName(orgId: number): string {
301 return this.org.get(orgId)[this.orgUnitLabelField]();