509f95cce68185abce8dc4f7bd2804804fd41817
[Evergreen.git] / Open-ILS / src / eg2 / src / app / staff / share / admin-page / admin-page.component.ts
1 import {Component, Input, OnInit, TemplateRef, ViewChild} from '@angular/core';
2 import {ActivatedRoute} from '@angular/router';
3 import {IdlService, IdlObject} from '@eg/core/idl.service';
4 import {GridDataSource} from '@eg/share/grid/grid';
5 import {GridComponent} from '@eg/share/grid/grid.component';
6 import {TranslateComponent} from '@eg/staff/share/translate/translate.component';
7 import {ToastService} from '@eg/share/toast/toast.service';
8 import {Pager} from '@eg/share/util/pager';
9 import {PcrudService} from '@eg/core/pcrud.service';
10 import {OrgService} from '@eg/core/org.service';
11 import {PermService} from '@eg/core/perm.service';
12 import {AuthService} from '@eg/core/auth.service';
13 import {FmRecordEditorComponent} from '@eg/share/fm-editor/fm-editor.component';
14 import {StringComponent} from '@eg/share/string/string.component';
15
16 /**
17  * General purpose CRUD interface for IDL objects
18  *
19  * Object types using this component must be editable via PCRUD.
20  */
21
22 @Component({
23     selector: 'eg-admin-page',
24     templateUrl: './admin-page.component.html'
25 })
26
27 export class AdminPageComponent implements OnInit {
28
29     @Input() idlClass: string;
30
31     // Default sort field, used when no grid sorting is applied.
32     @Input() sortField: string;
33
34     // Data source may be provided by the caller.  This gives the caller
35     // complete control over the contents of the grid.  If no data source
36     // is provided, a generic one is create which is sufficient for data
37     // that requires no special handling, filtering, etc.
38     @Input() dataSource: GridDataSource;
39
40     // Size of create/edito dialog.  Uses large by default.
41     @Input() dialogSize: 'sm' | 'lg' = 'lg';
42
43     // If an org unit field is specified, an org unit filter
44     // is added to the top of the page.
45     @Input() orgField: string;
46
47     // Disable the auto-matic org unit field filter
48     @Input() disableOrgFilter: boolean;
49
50     // Include objects linking to org units which are ancestors
51     // of the selected org unit.
52     @Input() includeOrgAncestors: boolean;
53
54     // Ditto includeOrgAncestors, but descendants.
55     @Input() includeOrgDescendants: boolean;
56
57     // Optional grid persist key.  This is the part of the key
58     // following eg.grid.
59     @Input() persistKey: string;
60
61     // Optional path component to add to the generated grid persist key,
62     // formatted as (for example):
63     // 'eg.grid.admin.${persistKeyPfx}.config.billing_type'
64     @Input() persistKeyPfx: string;
65
66     // Optional comma-separated list of read-only fields
67     @Input() readonlyFields: string;
68
69     @ViewChild('grid') grid: GridComponent;
70     @ViewChild('editDialog') editDialog: FmRecordEditorComponent;
71     @ViewChild('successString') successString: StringComponent;
72     @ViewChild('createString') createString: StringComponent;
73     @ViewChild('createErrString') createErrString: StringComponent;
74     @ViewChild('updateFailedString') updateFailedString: StringComponent;
75     @ViewChild('translator') translator: TranslateComponent;
76
77     idlClassDef: any;
78     pkeyField: string;
79
80     // True if any columns on the object support translations
81     translateRowIdx: number;
82     translateFieldIdx: number;
83     translatableFields: string[];
84
85     contextOrg: IdlObject;
86     orgFieldLabel: string;
87     viewPerms: string;
88     canCreate: boolean;
89
90     // Filters may be passed via URL query param.
91     // They are used to augment the grid data search query.
92     gridFilters: {[key: string]: string | number};
93
94     constructor(
95         private route: ActivatedRoute,
96         private idl: IdlService,
97         private org: OrgService,
98         private auth: AuthService,
99         private pcrud: PcrudService,
100         private perm: PermService,
101         private toast: ToastService
102     ) {
103         this.translatableFields = [];
104     }
105
106     applyOrgValues(orgId?: number) {
107
108         if (this.disableOrgFilter) {
109             this.orgField = null;
110             return;
111         }
112
113         if (!this.orgField) {
114             // If no org unit field is specified, try to find one.
115             // If an object type has multiple org unit fields, the
116             // caller should specify one or disable org unit filter.
117             this.idlClassDef.fields.forEach(field => {
118                 if (field['class'] === 'aou') {
119                     this.orgField = field.name;
120                 }
121             });
122         }
123
124         if (this.orgField) {
125             this.orgFieldLabel = this.idlClassDef.field_map[this.orgField].label;
126             this.contextOrg = this.org.get(orgId) || this.org.root();
127         }
128     }
129
130     ngOnInit() {
131         this.idlClassDef = this.idl.classes[this.idlClass];
132         this.pkeyField = this.idlClassDef.pkey || 'id';
133
134         this.translatableFields =
135             this.idlClassDef.fields.filter(f => f.i18n).map(f => f.name);
136
137         if (!this.persistKey) {
138             this.persistKey =
139                 'admin.' +
140                 (this.persistKeyPfx ? this.persistKeyPfx + '.' : '') +
141                 this.idlClassDef.table;
142         }
143
144         // gridFilters are a JSON encoded string
145         const filters = this.route.snapshot.queryParamMap.get('gridFilters');
146         if (filters) {
147             try {
148                 this.gridFilters = JSON.parse(filters);
149             } catch (E) {
150                 console.error('Invalid grid filters provided: ', filters);
151             }
152         }
153
154         // Limit the view org selector to orgs where the user has
155         // permacrud-encoded view permissions.
156         const pc = this.idlClassDef.permacrud;
157         if (pc && pc.retrieve) {
158             this.viewPerms = pc.retrieve.perms;
159         }
160
161         const contextOrg = this.route.snapshot.queryParamMap.get('contextOrg');
162         this.checkCreatePerms();
163         this.applyOrgValues(Number(contextOrg));
164
165         // If the caller provides not data source, create a generic one.
166         if (!this.dataSource) {
167             this.initDataSource();
168         }
169
170         // TODO: pass the row activate handler via the grid markup
171         this.grid.onRowActivate.subscribe(
172             (idlThing: IdlObject) => this.showEditDialog(idlThing)
173         );
174     }
175
176     checkCreatePerms() {
177         this.canCreate = false;
178         const pc = this.idlClassDef.permacrud || {};
179         const perms = pc.create ? pc.create.perms : [];
180         if (perms.length === 0) { return; }
181
182         this.perm.hasWorkPermAt(perms, true).then(permMap => {
183             Object.keys(permMap).forEach(key => {
184                 if (permMap[key].length > 0) {
185                     this.canCreate = true;
186                 }
187             });
188         });
189     }
190
191     orgOnChange(org: IdlObject) {
192         this.contextOrg = org;
193         this.grid.reload();
194     }
195
196     initDataSource() {
197         this.dataSource = new GridDataSource();
198
199         this.dataSource.getRows = (pager: Pager, sort: any[]) => {
200             const orderBy: any = {};
201
202             if (sort.length) {
203                 // Sort specified from grid
204                 orderBy[this.idlClass] = sort[0].name + ' ' + sort[0].dir;
205
206             } else if (this.sortField) {
207                 // Default sort field
208                 orderBy[this.idlClass] = this.sortField;
209             }
210
211             const searchOps = {
212                 offset: pager.offset,
213                 limit: pager.limit,
214                 order_by: orderBy
215             };
216
217             if (!this.contextOrg && !this.gridFilters) {
218                 // No org filter -- fetch all rows
219                 return this.pcrud.retrieveAll(
220                     this.idlClass, searchOps, {fleshSelectors: true});
221             }
222
223             const search: any = {};
224
225             if (this.contextOrg) {
226                 // Filter rows by those linking to the context org and
227                 // optionally ancestor and descendant org units.
228
229                 let orgs = [this.contextOrg.id()];
230
231                 if (this.includeOrgAncestors) {
232                     orgs = this.org.ancestors(this.contextOrg, true);
233                 }
234
235                 if (this.includeOrgDescendants) {
236                     // can result in duplicate workstation org IDs... meh
237                     orgs = orgs.concat(
238                         this.org.descendants(this.contextOrg, true));
239                 }
240
241                 search[this.orgField] = orgs;
242             }
243
244             if (this.gridFilters) {
245                 // Lay the URL grid filters over our search object.
246                 Object.keys(this.gridFilters).forEach(key => {
247                     search[key] = this.gridFilters[key];
248                 });
249             }
250
251             return this.pcrud.search(
252                 this.idlClass, search, searchOps, {fleshSelectors: true});
253         };
254     }
255
256     disableAncestorSelector(): boolean {
257         return this.contextOrg &&
258             this.contextOrg.id() === this.org.root().id();
259     }
260
261     disableDescendantSelector(): boolean {
262         return this.contextOrg && this.contextOrg.children().length === 0;
263     }
264
265     showEditDialog(idlThing: IdlObject) {
266         this.editDialog.mode = 'update';
267         this.editDialog.recId = idlThing[this.pkeyField]();
268         return this.editDialog.open({size: this.dialogSize}).then(
269             ok => {
270                 this.successString.current()
271                     .then(str => this.toast.success(str));
272                 this.grid.reload();
273             },
274             rejection => {
275                 if (!rejection.dismissed) {
276                     this.updateFailedString.current()
277                         .then(str => this.toast.danger(str));
278                 }
279             }
280         );
281     }
282
283     editSelected(idlThings: IdlObject[]) {
284
285         // Edit each IDL thing one at a time
286         const editOneThing = (thing: IdlObject) => {
287             if (!thing) { return; }
288
289             this.showEditDialog(thing).then(
290                 () => editOneThing(idlThings.shift()));
291         };
292
293         editOneThing(idlThings.shift());
294     }
295
296     deleteSelected(idlThings: IdlObject[]) {
297         idlThings.forEach(idlThing => idlThing.isdeleted(true));
298         this.pcrud.autoApply(idlThings).subscribe(
299             val => console.debug('deleted: ' + val),
300             err => {},
301             ()  => this.grid.reload()
302         );
303     }
304
305     createNew() {
306         this.editDialog.mode = 'create';
307         // We reuse the same editor for all actions.  Be sure
308         // create action does not try to modify an existing record.
309         this.editDialog.recId = null;
310         this.editDialog.record = null;
311         this.editDialog.open({size: this.dialogSize}).then(
312             ok => {
313                 this.createString.current()
314                     .then(str => this.toast.success(str));
315                 this.grid.reload();
316             },
317             rejection => {
318                 if (!rejection.dismissed) {
319                     this.createErrString.current()
320                         .then(str => this.toast.danger(str));
321                 }
322             }
323         );
324     }
325     // Open the field translation dialog.
326     // Link the next/previous actions to cycle through each translatable
327     // field on each row.
328     translate() {
329         this.translateRowIdx = 0;
330         this.translateFieldIdx = 0;
331         this.translator.fieldName = this.translatableFields[this.translateFieldIdx];
332         this.translator.idlObject = this.dataSource.data[this.translateRowIdx];
333
334         this.translator.nextString = () => {
335
336             if (this.translateFieldIdx < this.translatableFields.length - 1) {
337                 this.translateFieldIdx++;
338
339             } else if (this.translateRowIdx < this.dataSource.data.length - 1) {
340                 this.translateRowIdx++;
341                 this.translateFieldIdx = 0;
342             }
343
344             this.translator.idlObject =
345                 this.dataSource.data[this.translateRowIdx];
346             this.translator.fieldName =
347                 this.translatableFields[this.translateFieldIdx];
348         };
349
350         this.translator.prevString = () => {
351
352             if (this.translateFieldIdx > 0) {
353                 this.translateFieldIdx--;
354
355             } else if (this.translateRowIdx > 0) {
356                 this.translateRowIdx--;
357                 this.translateFieldIdx = 0;
358             }
359
360             this.translator.idlObject =
361                 this.dataSource.data[this.translateRowIdx];
362             this.translator.fieldName =
363                 this.translatableFields[this.translateFieldIdx];
364         };
365
366         this.translator.open({size: 'lg'});
367     }
368 }
369
370