]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/eg2/src/app/staff/share/admin-page/admin-page.component.ts
LP#1904244: AdminPageComponent: move onRowActivate subscription to markup
[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.get(this.auth.user().ws_ou()) || 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
231     checkCreatePerms() {
232         this.canCreate = false;
233         const pc = this.idlClassDef.permacrud || {};
234         const perms = pc.create ? pc.create.perms : [];
235         if (perms.length === 0) { return; }
236
237         this.perm.hasWorkPermAt(perms, true).then(permMap => {
238             Object.keys(permMap).forEach(key => {
239                 if (permMap[key].length > 0) {
240                     this.canCreate = true;
241                 }
242             });
243         });
244     }
245
246     initDataSource() {
247         this.dataSource = new GridDataSource();
248
249         this.dataSource.getRows = (pager: Pager, sort: any[]) => {
250             const orderBy: any = {};
251
252             if (sort.length) {
253                 // Sort specified from grid
254                 orderBy[this.idlClass] = sort[0].name + ' ' + sort[0].dir;
255
256             } else if (this.sortField) {
257                 // Default sort field
258                 orderBy[this.idlClass] = this.sortField;
259             }
260
261             const searchOps = {
262                 offset: pager.offset,
263                 limit: pager.limit,
264                 order_by: orderBy
265             };
266
267             if (!this.contextOrg && !this.gridFilters && !Object.keys(this.dataSource.filters).length) {
268                 // No org filter -- fetch all rows
269                 return this.pcrud.retrieveAll(
270                     this.idlClass, searchOps, {fleshSelectors: true});
271             }
272
273             const search: any[] = new Array();
274             const orgFilter: any = {};
275
276             if (this.orgField && (this.searchOrgs || this.contextOrg)) {
277                 orgFilter[this.orgField] =
278                     this.searchOrgs.orgIds || [this.contextOrg.id()];
279                 search.push(orgFilter);
280             }
281
282             Object.keys(this.dataSource.filters).forEach(key => {
283                 Object.keys(this.dataSource.filters[key]).forEach(key2 => {
284                     search.push(this.dataSource.filters[key][key2]);
285                 });
286             });
287
288             // FIXME - do we want to remove this, which is used in several
289             // secondary admin pages, in favor of switching it to the built-in
290             // grid filtering?
291             if (this.gridFilters) {
292                 // Lay the URL grid filters over our search object.
293                 Object.keys(this.gridFilters).forEach(key => {
294                     const urlProvidedFilters = {};
295                     urlProvidedFilters[key] = this.gridFilters[key];
296                     search.push(urlProvidedFilters);
297                 });
298             }
299
300             return this.pcrud.search(
301                 this.idlClass, search, searchOps, {fleshSelectors: true});
302         };
303     }
304
305     showEditDialog(idlThing: IdlObject): Promise<any> {
306         this.editDialog.mode = 'update';
307         this.editDialog.recordId = idlThing[this.pkeyField]();
308         return new Promise((resolve, reject) => {
309             this.editDialog.open({size: this.dialogSize}).subscribe(
310                 result => {
311                     this.successString.current()
312                         .then(str => this.toast.success(str));
313                     this.grid.reload();
314                     resolve(result);
315                 },
316                 error => {
317                     this.updateFailedString.current()
318                         .then(str => this.toast.danger(str));
319                     reject(error);
320                 }
321             );
322         });
323     }
324
325     editSelected(idlThings: IdlObject[]) {
326
327         // Edit each IDL thing one at a time
328         const editOneThing = (thing: IdlObject) => {
329             if (!thing) { return; }
330
331             this.showEditDialog(thing).then(
332                 () => editOneThing(idlThings.shift()));
333         };
334
335         editOneThing(idlThings.shift());
336     }
337
338     deleteSelected(idlThings: IdlObject[]) {
339         idlThings.forEach(idlThing => idlThing.isdeleted(true));
340         this.pcrud.autoApply(idlThings).subscribe(
341             val => {
342                 this.deleteSuccessString.current()
343                     .then(str => this.toast.success(str));
344             },
345             err => {
346                 this.deleteFailedString.current()
347                     .then(str => this.toast.danger(str));
348             },
349             ()  => this.grid.reload()
350         );
351     }
352
353     createNew() {
354         this.editDialog.mode = 'create';
355         // We reuse the same editor for all actions.  Be sure
356         // create action does not try to modify an existing record.
357         this.editDialog.recordId = null;
358         this.editDialog.record = null;
359         this.editDialog.open({size: this.dialogSize}).subscribe(
360             ok => {
361                 this.createString.current()
362                     .then(str => this.toast.success(str));
363                 this.grid.reload();
364             },
365             rejection => {
366                 if (!rejection.dismissed) {
367                     this.createErrString.current()
368                         .then(str => this.toast.danger(str));
369                 }
370             }
371         );
372     }
373     // Open the field translation dialog.
374     // Link the next/previous actions to cycle through each translatable
375     // field on each row.
376     translate() {
377         this.translateRowIdx = 0;
378         this.translateFieldIdx = 0;
379         this.translator.fieldName = this.translatableFields[this.translateFieldIdx];
380         this.translator.idlObject = this.dataSource.data[this.translateRowIdx];
381
382         this.translator.nextString = () => {
383
384             if (this.translateFieldIdx < this.translatableFields.length - 1) {
385                 this.translateFieldIdx++;
386
387             } else if (this.translateRowIdx < this.dataSource.data.length - 1) {
388                 this.translateRowIdx++;
389                 this.translateFieldIdx = 0;
390             }
391
392             this.translator.idlObject =
393                 this.dataSource.data[this.translateRowIdx];
394             this.translator.fieldName =
395                 this.translatableFields[this.translateFieldIdx];
396         };
397
398         this.translator.prevString = () => {
399
400             if (this.translateFieldIdx > 0) {
401                 this.translateFieldIdx--;
402
403             } else if (this.translateRowIdx > 0) {
404                 this.translateRowIdx--;
405                 this.translateFieldIdx = 0;
406             }
407
408             this.translator.idlObject =
409                 this.dataSource.data[this.translateRowIdx];
410             this.translator.fieldName =
411                 this.translatableFields[this.translateFieldIdx];
412         };
413
414         this.translator.open({size: 'lg'});
415     }
416
417     // Construct a routerLink path for a configField.
418     configFieldRouteLink(row: any, col: GridColumn): string {
419         const cf = this.configFields.filter(field => field.name === col.name)[0];
420         const linkClass = this.idl.classes[cf['class']];
421         const pathParts = linkClass.table.split(/\./); // schema.tablename
422         return `${this.configLinkBasePath}/${pathParts[0]}/${pathParts[1]}`;
423     }
424
425     // Compiles a gridFilter value used when navigating to a linked
426     // class via configField.  The filter ensures the linked page
427     // only shows rows which refer back to the object from which the
428     // link was clicked.
429     configFieldRouteParams(row: any, col: GridColumn): any {
430         const cf = this.configFields.filter(field => field.name === col.name)[0];
431         let value = this.configFieldLinkedValue(row, col);
432
433         // For certain has-a relationships, the linked object will be
434         // fleshed so its display (selector) value can be used.
435         // Extract the scalar value found at the remote target field.
436         if (value && typeof value === 'object') { value = value[cf.key](); }
437
438         const filter: any = {};
439         filter[cf.key] = value;
440
441         return {gridFilters : JSON.stringify(filter)};
442     }
443
444     // Returns the value on the local object for the field which
445     // refers to the remote object.  This may be a scalar or a
446     // fleshed IDL object.
447     configFieldLinkedValue(row: any, col: GridColumn): any {
448         const cf = this.configFields.filter(field => field.name === col.name)[0];
449         const linkClass = this.idl.classes[cf['class']];
450
451         // cf.key is the name of the field on the linked object that matches
452         // the value on our local object.
453         // In as has_many relationship, the remote field has its own
454         // 'key' value which determines which field on the local object
455         // represents the other end of the relationship.  This is
456         // typically, but not always the local pkey field.
457
458         const localField =
459             cf.reltype === 'has_many' ?
460             (linkClass.field_map[cf.key].key || this.pkeyField) : cf.name;
461
462         return row[localField]();
463     }
464
465     // Returns a URL suitable for using as an href.
466     // We use an href to jump to the secondary admin page because
467     // routerLink within the same base component results in component
468     // reuse of a series of components which were not designed with
469     // reuse in mind.
470     configFieldLinkUrl(row: any, col: GridColumn): string {
471         const path = this.configFieldRouteLink(row, col);
472         const filters = this.configFieldRouteParams(row, col);
473         const url = path + '?gridFilters=' +
474             encodeURIComponent(filters.gridFilters);
475
476         return this.ngLocation.prepareExternalUrl(url);
477     }
478
479     configLinkLabel(row: any, col: GridColumn): string {
480         const cf = this.configFields.filter(field => field.name === col.name)[0];
481
482         // Has-many links have no specific value to use for display
483         // so just use the column label.
484         if (cf.reltype === 'has_many') { return col.label; }
485
486         return this.format.transform({
487             value: row[col.name](),
488             idlClass: this.idlClass,
489             idlField: col.name
490         });
491     }
492
493     clearGridFiltersUrl(): string {
494         const parts = this.idlClassDef.table.split(/\./);
495         const url = this.configLinkBasePath + '/' + parts[0] + '/' + parts[1];
496         return this.ngLocation.prepareExternalUrl(url);
497     }
498 }
499
500