]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/eg2/src/app/staff/share/admin-page/admin-page.component.ts
LP1847800 Admin grids support config_field links
[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 {ActivatedRoute} from '@angular/router';
3 import {Location} from '@angular/common';
4 import {IdlService, IdlObject} from '@eg/core/idl.service';
5 import {FormatService} from '@eg/core/format.service';
6 import {GridDataSource, GridColumn} from '@eg/share/grid/grid';
7 import {GridComponent} from '@eg/share/grid/grid.component';
8 import {TranslateComponent} from '@eg/share/translate/translate.component';
9 import {ToastService} from '@eg/share/toast/toast.service';
10 import {Pager} from '@eg/share/util/pager';
11 import {PcrudService} from '@eg/core/pcrud.service';
12 import {OrgService} from '@eg/core/org.service';
13 import {PermService} from '@eg/core/perm.service';
14 import {AuthService} from '@eg/core/auth.service';
15 import {FmRecordEditorComponent, FmFieldOptions
16     } from '@eg/share/fm-editor/fm-editor.component';
17 import {StringComponent} from '@eg/share/string/string.component';
18 import {OrgFamily} from '@eg/share/org-family-select/org-family-select.component';
19
20 /**
21  * General purpose CRUD interface for IDL objects
22  *
23  * Object types using this component must be editable via PCRUD.
24  */
25
26 @Component({
27     selector: 'eg-admin-page',
28     templateUrl: './admin-page.component.html'
29 })
30
31 export class AdminPageComponent implements OnInit {
32
33     @Input() idlClass: string;
34
35     // Default sort field, used when no grid sorting is applied.
36     @Input() sortField: string;
37
38     // Data source may be provided by the caller.  This gives the caller
39     // complete control over the contents of the grid.  If no data source
40     // is provided, a generic one is create which is sufficient for data
41     // that requires no special handling, filtering, etc.
42     @Input() dataSource: GridDataSource;
43
44     // Size of create/edito dialog.  Uses large by default.
45     @Input() dialogSize: 'sm' | 'lg' = 'lg';
46
47     // comma-separated list of fields to hide.
48     // This does not imply all other fields should be visible, only that
49     // the selected fields will be hidden.
50     @Input() hideGridFields: string;
51
52     // If an org unit field is specified, an org unit filter
53     // is added to the top of the page.
54     @Input() orgField: string;
55
56     // Disable the auto-matic org unit field filter
57     @Input() disableOrgFilter: boolean;
58
59     // Include objects linking to org units which are ancestors
60     // of the selected org unit.
61     @Input() includeOrgAncestors: boolean;
62
63     // Ditto includeOrgAncestors, but descendants.
64     @Input() includeOrgDescendants: boolean;
65
66     // Optional grid persist key.  This is the part of the key
67     // following eg.grid.
68     @Input() persistKey: string;
69
70     // Optional path component to add to the generated grid persist key,
71     // formatted as (for example):
72     // 'eg.grid.admin.${persistKeyPfx}.config.billing_type'
73     @Input() persistKeyPfx: string;
74
75     // Optional comma-separated list of read-only fields
76     @Input() readonlyFields: string;
77
78     // Optional template containing help/about text which will
79     // be added to the page, above the grid.
80     @Input() helpTemplate: TemplateRef<any>;
81
82     // Override field options for create/edit dialog
83     @Input() fieldOptions: {[field: string]: FmFieldOptions};
84
85     // Override default values for fm-editor
86     @Input() defaultNewRecord: IdlObject;
87
88     // Used as the first part of the routerLink path when creating
89     // links to related tables via configField's.
90     @Input() configLinkBasePath: string;
91
92     @ViewChild('grid', { static: true }) grid: GridComponent;
93     @ViewChild('editDialog', { static: true }) editDialog: FmRecordEditorComponent;
94     @ViewChild('successString', { static: true }) successString: StringComponent;
95     @ViewChild('createString', { static: true }) createString: StringComponent;
96     @ViewChild('createErrString', { static: true }) createErrString: StringComponent;
97     @ViewChild('updateFailedString', { static: true }) updateFailedString: StringComponent;
98     @ViewChild('deleteFailedString', { static: true }) deleteFailedString: StringComponent;
99     @ViewChild('deleteSuccessString', { static: true }) deleteSuccessString: StringComponent;
100     @ViewChild('translator', { static: true }) translator: TranslateComponent;
101
102     idlClassDef: any;
103     pkeyField: string;
104     configFields: any[]; // IDL field definitions
105
106     // True if any columns on the object support translations
107     translateRowIdx: number;
108     translateFieldIdx: number;
109     translatableFields: string[];
110
111     contextOrg: IdlObject;
112     searchOrgs: OrgFamily;
113     orgFieldLabel: string;
114     viewPerms: string;
115     canCreate: boolean;
116
117     // Filters may be passed via URL query param.
118     // They are used to augment the grid data search query.
119     gridFilters: {[key: string]: string | number};
120
121     constructor(
122         private route: ActivatedRoute,
123         private ngLocation: Location,
124         private format: FormatService,
125         public idl: IdlService,
126         private org: OrgService,
127         public auth: AuthService,
128         public pcrud: PcrudService,
129         private perm: PermService,
130         public toast: ToastService
131     ) {
132         this.translatableFields = [];
133         this.configFields = [];
134     }
135
136     applyOrgValues(orgId?: number) {
137
138         if (this.disableOrgFilter) {
139             this.orgField = null;
140             return;
141         }
142
143         if (!this.orgField) {
144             // If no org unit field is specified, try to find one.
145             // If an object type has multiple org unit fields, the
146             // caller should specify one or disable org unit filter.
147             this.idlClassDef.fields.forEach(field => {
148                 if (field['class'] === 'aou') {
149                     this.orgField = field.name;
150                 }
151             });
152         }
153
154         if (this.orgField) {
155             this.orgFieldLabel = this.idlClassDef.field_map[this.orgField].label;
156             this.contextOrg = this.org.get(orgId) || this.org.root();
157             this.searchOrgs = {primaryOrgId: this.contextOrg.id()};
158         }
159     }
160
161     ngOnInit() {
162
163         this.idlClassDef = this.idl.classes[this.idlClass];
164         this.pkeyField = this.idlClassDef.pkey || 'id';
165
166         this.translatableFields =
167             this.idlClassDef.fields.filter(f => f.i18n).map(f => f.name);
168
169         if (!this.persistKey) {
170             this.persistKey =
171                 'admin.' +
172                 (this.persistKeyPfx ? this.persistKeyPfx + '.' : '') +
173                 this.idlClassDef.table;
174         }
175
176
177         // Note the field filter could be based purely on fields
178         // which are links, but that leads to cases where links
179         // are created to tables which are too big and/or admin
180         // interfaces which are not otherwise used because they
181         // have custom UI's instead.
182         // this.idlClassDef.fields.filter(f => f.datatype === 'link');
183         this.configFields =
184             this.idlClassDef.fields.filter(f => f.config_field);
185
186         // gridFilters are a JSON encoded string
187         const filters = this.route.snapshot.queryParamMap.get('gridFilters');
188         if (filters) {
189             try {
190                 this.gridFilters = JSON.parse(filters);
191             } catch (E) {
192                 console.error('Invalid grid filters provided: ', filters);
193             }
194         }
195
196         // Limit the view org selector to orgs where the user has
197         // permacrud-encoded view permissions.
198         const pc = this.idlClassDef.permacrud;
199         if (pc && pc.retrieve) {
200             this.viewPerms = pc.retrieve.perms;
201         }
202
203         const contextOrg = this.route.snapshot.queryParamMap.get('contextOrg');
204         this.checkCreatePerms();
205         this.applyOrgValues(Number(contextOrg));
206
207         // If the caller provides not data source, create a generic one.
208         if (!this.dataSource) {
209             this.initDataSource();
210         }
211
212         // TODO: pass the row activate handler via the grid markup
213         this.grid.onRowActivate.subscribe(
214             (idlThing: IdlObject) => this.showEditDialog(idlThing)
215         );
216     }
217
218     checkCreatePerms() {
219         this.canCreate = false;
220         const pc = this.idlClassDef.permacrud || {};
221         const perms = pc.create ? pc.create.perms : [];
222         if (perms.length === 0) { return; }
223
224         this.perm.hasWorkPermAt(perms, true).then(permMap => {
225             Object.keys(permMap).forEach(key => {
226                 if (permMap[key].length > 0) {
227                     this.canCreate = true;
228                 }
229             });
230         });
231     }
232
233     initDataSource() {
234         this.dataSource = new GridDataSource();
235
236         this.dataSource.getRows = (pager: Pager, sort: any[]) => {
237             const orderBy: any = {};
238
239             if (sort.length) {
240                 // Sort specified from grid
241                 orderBy[this.idlClass] = sort[0].name + ' ' + sort[0].dir;
242
243             } else if (this.sortField) {
244                 // Default sort field
245                 orderBy[this.idlClass] = this.sortField;
246             }
247
248             const searchOps = {
249                 offset: pager.offset,
250                 limit: pager.limit,
251                 order_by: orderBy
252             };
253
254             if (!this.contextOrg && !this.gridFilters) {
255                 // No org filter -- fetch all rows
256                 return this.pcrud.retrieveAll(
257                     this.idlClass, searchOps, {fleshSelectors: true});
258             }
259
260             const search: any = {};
261
262             if (this.orgField) {
263                 search[this.orgField] =
264                     this.searchOrgs.orgIds || [this.contextOrg.id()];
265             }
266
267             if (this.gridFilters) {
268                 // Lay the URL grid filters over our search object.
269                 Object.keys(this.gridFilters).forEach(key => {
270                     search[key] = this.gridFilters[key];
271                 });
272             }
273
274             return this.pcrud.search(
275                 this.idlClass, search, searchOps, {fleshSelectors: true});
276         };
277     }
278
279     showEditDialog(idlThing: IdlObject): Promise<any> {
280         this.editDialog.mode = 'update';
281         this.editDialog.recordId = idlThing[this.pkeyField]();
282         return new Promise((resolve, reject) => {
283             this.editDialog.open({size: this.dialogSize}).subscribe(
284                 result => {
285                     this.successString.current()
286                         .then(str => this.toast.success(str));
287                     this.grid.reload();
288                     resolve(result);
289                 },
290                 error => {
291                     this.updateFailedString.current()
292                         .then(str => this.toast.danger(str));
293                     reject(error);
294                 }
295             );
296         });
297     }
298
299     editSelected(idlThings: IdlObject[]) {
300
301         // Edit each IDL thing one at a time
302         const editOneThing = (thing: IdlObject) => {
303             if (!thing) { return; }
304
305             this.showEditDialog(thing).then(
306                 () => editOneThing(idlThings.shift()));
307         };
308
309         editOneThing(idlThings.shift());
310     }
311
312     deleteSelected(idlThings: IdlObject[]) {
313         idlThings.forEach(idlThing => idlThing.isdeleted(true));
314         this.pcrud.autoApply(idlThings).subscribe(
315             val => {
316                 console.debug('deleted: ' + val);
317                 this.deleteSuccessString.current()
318                     .then(str => this.toast.success(str));
319             },
320             err => {
321                 this.deleteFailedString.current()
322                     .then(str => this.toast.danger(str));
323             },
324             ()  => this.grid.reload()
325         );
326     }
327
328     createNew() {
329         this.editDialog.mode = 'create';
330         // We reuse the same editor for all actions.  Be sure
331         // create action does not try to modify an existing record.
332         this.editDialog.recordId = null;
333         this.editDialog.record = null;
334         this.editDialog.open({size: this.dialogSize}).subscribe(
335             ok => {
336                 this.createString.current()
337                     .then(str => this.toast.success(str));
338                 this.grid.reload();
339             },
340             rejection => {
341                 if (!rejection.dismissed) {
342                     this.createErrString.current()
343                         .then(str => this.toast.danger(str));
344                 }
345             }
346         );
347     }
348     // Open the field translation dialog.
349     // Link the next/previous actions to cycle through each translatable
350     // field on each row.
351     translate() {
352         this.translateRowIdx = 0;
353         this.translateFieldIdx = 0;
354         this.translator.fieldName = this.translatableFields[this.translateFieldIdx];
355         this.translator.idlObject = this.dataSource.data[this.translateRowIdx];
356
357         this.translator.nextString = () => {
358
359             if (this.translateFieldIdx < this.translatableFields.length - 1) {
360                 this.translateFieldIdx++;
361
362             } else if (this.translateRowIdx < this.dataSource.data.length - 1) {
363                 this.translateRowIdx++;
364                 this.translateFieldIdx = 0;
365             }
366
367             this.translator.idlObject =
368                 this.dataSource.data[this.translateRowIdx];
369             this.translator.fieldName =
370                 this.translatableFields[this.translateFieldIdx];
371         };
372
373         this.translator.prevString = () => {
374
375             if (this.translateFieldIdx > 0) {
376                 this.translateFieldIdx--;
377
378             } else if (this.translateRowIdx > 0) {
379                 this.translateRowIdx--;
380                 this.translateFieldIdx = 0;
381             }
382
383             this.translator.idlObject =
384                 this.dataSource.data[this.translateRowIdx];
385             this.translator.fieldName =
386                 this.translatableFields[this.translateFieldIdx];
387         };
388
389         this.translator.open({size: 'lg'});
390     }
391
392     // Construct a routerLink path for a configField.
393     configFieldRouteLink(row: any, col: GridColumn): string {
394         const cf = this.configFields.filter(field => field.name === col.name)[0];
395         const linkClass = this.idl.classes[cf['class']];
396         const pathParts = linkClass.table.split(/\./); // schema.tablename
397         return `${this.configLinkBasePath}/${pathParts[0]}/${pathParts[1]}`;
398     }
399
400     // Compiles a gridFilter value used when navigating to a linked
401     // class via configField.  The filter ensures the linked page
402     // only shows rows which refer back to the object from which the
403     // link was clicked.
404     configFieldRouteParams(row: any, col: GridColumn): any {
405         const cf = this.configFields.filter(field => field.name === col.name)[0];
406         let value = this.configFieldLinkedValue(row, col);
407
408         // For certain has-a relationships, the linked object will be
409         // fleshed so its display (selector) value can be used.
410         // Extract the scalar value found at the remote target field.
411         if (value && typeof value === 'object') { value = value[cf.key](); }
412
413         const filter: any = {};
414         filter[cf.key] = value;
415
416         return {gridFilters : JSON.stringify(filter)};
417     }
418
419     // Returns the value on the local object for the field which
420     // refers to the remote object.  This may be a scalar or a
421     // fleshed IDL object.
422     configFieldLinkedValue(row: any, col: GridColumn): any {
423         const cf = this.configFields.filter(field => field.name === col.name)[0];
424         const linkClass = this.idl.classes[cf['class']];
425
426         // cf.key is the name of the field on the linked object that matches
427         // the value on our local object.
428         // In as has_many relationship, the remote field has its own
429         // 'key' value which determines which field on the local object
430         // represents the other end of the relationship.  This is
431         // typically, but not always the local pkey field.
432
433         const localField =
434             cf.reltype === 'has_many' ?
435             (linkClass.field_map[cf.key].key || this.pkeyField) : cf.name;
436
437         return row[localField]();
438     }
439
440     // Returns a URL suitable for using as an href.
441     // We use an href to jump to the secondary admin page because
442     // routerLink within the same base component results in component
443     // reuse of a series of components which were not designed with
444     // reuse in mind.
445     configFieldLinkUrl(row: any, col: GridColumn): string {
446         const path = this.configFieldRouteLink(row, col);
447         const filters = this.configFieldRouteParams(row, col);
448         const url = path + '?gridFilters=' +
449             encodeURIComponent(filters.gridFilters);
450
451         return this.ngLocation.prepareExternalUrl(url);
452     }
453
454     configLinkLabel(row: any, col: GridColumn): string {
455         const cf = this.configFields.filter(field => field.name === col.name)[0];
456
457         // Has-many links have no specific value to use for display
458         // so just use the column label.
459         if (cf.reltype === 'has_many') { return col.label; }
460
461         return this.format.transform({
462             value: row[col.name](),
463             idlClass: this.idlClass,
464             idlField: col.name
465         });
466     }
467 }
468
469