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