LP#1807458 Angular admin grid Edit Selected option
[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('translator') translator: TranslateComponent;
73
74     idlClassDef: any;
75     pkeyField: string;
76     createNew: () => void;
77     deleteSelected: (rows: IdlObject[]) => void;
78     editSelected: (rows: IdlObject[]) => void;
79
80     // True if any columns on the object support translations
81     translateRowIdx: number;
82     translateFieldIdx: number;
83     translatableFields: string[];
84     translate: () => void;
85
86     contextOrg: IdlObject;
87     orgFieldLabel: string;
88     viewPerms: string;
89     canCreate: boolean;
90
91     constructor(
92         private idl: IdlService,
93         private org: OrgService,
94         private auth: AuthService,
95         private pcrud: PcrudService,
96         private perm: PermService,
97         private toast: ToastService
98     ) {
99         this.translatableFields = [];
100     }
101
102     applyOrgValues() {
103
104         if (this.disableOrgFilter) {
105             this.orgField = null;
106             return;
107         }
108
109         if (!this.orgField) {
110             // If no org unit field is specified, try to find one.
111             // If an object type has multiple org unit fields, the
112             // caller should specify one or disable org unit filter.
113             this.idlClassDef.fields.forEach(field => {
114                 if (field['class'] === 'aou') {
115                     this.orgField = field.name;
116                 }
117             });
118         }
119
120         if (this.orgField) {
121             this.orgFieldLabel = this.idlClassDef.field_map[this.orgField].label;
122             this.contextOrg = this.org.root();
123         }
124     }
125
126     ngOnInit() {
127         this.idlClassDef = this.idl.classes[this.idlClass];
128         this.pkeyField = this.idlClassDef.pkey || 'id';
129
130         this.translatableFields =
131             this.idlClassDef.fields.filter(f => f.i18n).map(f => f.name);
132
133         if (!this.persistKey) {
134             this.persistKey =
135                 'admin.' +
136                 (this.persistKeyPfx ? this.persistKeyPfx + '.' : '') +
137                 this.idlClassDef.table;
138         }
139
140         // Limit the view org selector to orgs where the user has
141         // permacrud-encoded view permissions.
142         const pc = this.idlClassDef.permacrud;
143         if (pc && pc.retrieve) {
144             this.viewPerms = pc.retrieve.perms;
145         }
146
147         this.checkCreatePerms();
148         this.applyOrgValues();
149
150         // If the caller provides not data source, create a generic one.
151         if (!this.dataSource) {
152             this.initDataSource();
153         }
154
155         // TODO: pass the row activate handler via the grid markup
156         this.grid.onRowActivate.subscribe(
157             (idlThing: IdlObject) => this.showEditDialog(idlThing)
158         );
159
160         this.editSelected = (idlThings: IdlObject[]) => {
161
162             // Edit each IDL thing one at a time
163             const editOneThing = (thing: IdlObject) => {
164                 if (!thing) return;
165
166                 this.showEditDialog(thing).then(
167                     () => editOneThing(idlThings.shift()));
168             }
169
170             editOneThing(idlThings.shift()); };
171
172         this.createNew = () => {
173             this.editDialog.mode = 'create';
174             this.editDialog.open({size: this.dialogSize}).then(
175                 ok => {
176                     this.createString.current()
177                         .then(str => this.toast.success(str));
178                     this.grid.reload();
179                 },
180                 err => {}
181             );
182         };
183
184         this.deleteSelected = (idlThings: IdlObject[]) => {
185             idlThings.forEach(idlThing => idlThing.isdeleted(true));
186             this.pcrud.autoApply(idlThings).subscribe(
187                 val => console.debug('deleted: ' + val),
188                 err => {},
189                 ()  => this.grid.reload()
190             );
191         };
192
193         // Open the field translation dialog.
194         // Link the next/previous actions to cycle through each translatable
195         // field on each row.
196         this.translate = () => {
197             this.translateRowIdx = 0;
198             this.translateFieldIdx = 0;
199             this.translator.fieldName = this.translatableFields[this.translateFieldIdx];
200             this.translator.idlObject = this.dataSource.data[this.translateRowIdx];
201
202             this.translator.nextString = () => {
203
204                 if (this.translateFieldIdx < this.translatableFields.length - 1) {
205                     this.translateFieldIdx++;
206
207                 } else if (this.translateRowIdx < this.dataSource.data.length - 1) {
208                     this.translateRowIdx++;
209                     this.translateFieldIdx = 0;
210                 }
211
212                 this.translator.idlObject =
213                     this.dataSource.data[this.translateRowIdx];
214                 this.translator.fieldName =
215                     this.translatableFields[this.translateFieldIdx];
216             };
217
218             this.translator.prevString = () => {
219
220                 if (this.translateFieldIdx > 0) {
221                     this.translateFieldIdx--;
222
223                 } else if (this.translateRowIdx > 0) {
224                     this.translateRowIdx--;
225                     this.translateFieldIdx = 0;
226                 }
227
228                 this.translator.idlObject =
229                     this.dataSource.data[this.translateRowIdx];
230                 this.translator.fieldName =
231                     this.translatableFields[this.translateFieldIdx];
232             };
233
234             this.translator.open({size: 'lg'});
235         };
236     }
237
238     checkCreatePerms() {
239         this.canCreate = false;
240         const pc = this.idlClassDef.permacrud || {};
241         const perms = pc.create ? pc.create.perms : [];
242         if (perms.length === 0) { return; }
243
244         this.perm.hasWorkPermAt(perms, true).then(permMap => {
245             Object.keys(permMap).forEach(key => {
246                 if (permMap[key].length > 0) {
247                     this.canCreate = true;
248                 }
249             });
250         });
251     }
252
253     orgOnChange(org: IdlObject) {
254         this.contextOrg = org;
255         this.grid.reload();
256     }
257
258     initDataSource() {
259         this.dataSource = new GridDataSource();
260
261         this.dataSource.getRows = (pager: Pager, sort: any[]) => {
262             const orderBy: any = {};
263
264             if (sort.length) {
265                 // Sort specified from grid
266                 orderBy[this.idlClass] = sort[0].name + ' ' + sort[0].dir;
267
268             } else if (this.sortField) {
269                 // Default sort field
270                 orderBy[this.idlClass] = this.sortField;
271             }
272
273             const searchOps = {
274                 offset: pager.offset,
275                 limit: pager.limit,
276                 order_by: orderBy
277             };
278
279             if (this.contextOrg) {
280                 // Filter rows by those linking to the context org and
281                 // optionally ancestor and descendant org units.
282
283                 let orgs = [this.contextOrg.id()];
284
285                 if (this.includeOrgAncestors) {
286                     orgs = this.org.ancestors(this.contextOrg, true);
287                 }
288
289                 if (this.includeOrgDescendants) {
290                     // can result in duplicate workstation org IDs... meh
291                     orgs = orgs.concat(
292                         this.org.descendants(this.contextOrg, true));
293                 }
294
295                 const search = {};
296                 search[this.orgField] = orgs;
297                 return this.pcrud.search(this.idlClass, search, searchOps);
298             }
299
300             // No org filter -- fetch all rows
301             return this.pcrud.retrieveAll(this.idlClass, searchOps);
302         };
303     }
304
305     disableAncestorSelector(): boolean {
306         return this.contextOrg &&
307             this.contextOrg.id() === this.org.root().id();
308     }
309
310     disableDescendantSelector(): boolean {
311         return this.contextOrg && this.contextOrg.children().length === 0;
312     }
313
314     showEditDialog(idlThing: IdlObject) {
315         this.editDialog.mode = 'update';
316         this.editDialog.recId = idlThing[this.pkeyField]();
317         return this.editDialog.open({size: this.dialogSize}).then(
318             ok => {
319                 this.successString.current()
320                     .then(str => this.toast.success(str));
321                 this.grid.reload();
322             },
323             err => {}
324         );
325     }
326
327 }
328
329