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