lp1857911 follow-up: remove console.log
[evergreen-equinox.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 {ConfirmDialogComponent} from '@eg/share/dialog/confirm.component';
11 import {Pager} from '@eg/share/util/pager';
12 import {PcrudService} from '@eg/core/pcrud.service';
13 import {OrgService} from '@eg/core/org.service';
14 import {PermService} from '@eg/core/perm.service';
15 import {AuthService} from '@eg/core/auth.service';
16 import {FmRecordEditorComponent, FmFieldOptions
17     } from '@eg/share/fm-editor/fm-editor.component';
18 import {StringComponent} from '@eg/share/string/string.component';
19 import {OrgFamily} from '@eg/share/org-family-select/org-family-select.component';
20
21 /**
22  * General purpose CRUD interface for IDL objects
23  *
24  * Object types using this component must be editable via PCRUD.
25  */
26
27 @Component({
28     selector: 'eg-admin-page',
29     templateUrl: './admin-page.component.html'
30 })
31
32 export class AdminPageComponent implements OnInit {
33
34     @Input() idlClass: string;
35
36     // Default sort field, used when no grid sorting is applied.
37     @Input() sortField: string;
38
39     // Data source may be provided by the caller.  This gives the caller
40     // complete control over the contents of the grid.  If no data source
41     // is provided, a generic one is create which is sufficient for data
42     // that requires no special handling, filtering, etc.
43     @Input() dataSource: GridDataSource;
44
45     // Size of create/edito dialog.  Uses large by default.
46     @Input() dialogSize: 'sm' | 'lg' = 'lg';
47
48     // Optional comma-separated list of field names defining the order in which
49     // fields should be rendered in the fm-editor and grid.
50     @Input() fieldOrder: string;
51
52     // comma-separated list of fields to hide.
53     // This does not imply all other fields should be visible, only that
54     // the selected fields will be hidden.
55     @Input() hideGridFields: string;
56
57     // If an org unit field is specified, an org unit filter
58     // is added to the top of the page.
59     @Input() orgField: string;
60
61     // Disable the auto-matic org unit field filter
62     @Input() disableOrgFilter: boolean;
63
64     // Give the grid an option to undelete any deleted rows
65     @Input() enableUndelete: boolean;
66
67     // Remove the ability to delete rows
68     @Input() disableDelete: boolean;
69
70     // Optional: Replace the default deletion confirmation text with this
71     @Input() deleteConfirmation: string;
72
73     // Remove the ability to edit rows
74     @Input() disableEdit: boolean;
75
76     // Include objects linking to org units which are ancestors
77     // of the selected org unit.
78     @Input() includeOrgAncestors: boolean;
79
80     // Ditto includeOrgAncestors, but descendants.
81     @Input() includeOrgDescendants: boolean;
82
83     // Optional grid persist key.  This is the part of the key
84     // following eg.grid.
85     @Input() persistKey: string;
86
87     // If present, will be applied to the org selector for the grid
88     @Input() contextOrgSelectorPersistKey: string;
89
90     // Optional path component to add to the generated grid persist key,
91     // formatted as (for example):
92     // 'eg.grid.admin.${persistKeyPfx}.config.billing_type'
93     @Input() persistKeyPfx: string;
94
95     // Optional comma-separated list of read-only fields
96     @Input() readonlyFields: string;
97
98     // Optional record label to use instead of the IDL label
99     @Input() recordLabel: string;
100
101     // optional flag to hide the Clear Filters action for gridFilters
102     @Input() hideClearFilters: boolean;
103
104     // optional list of org fields which are allowed a default if unset
105     @Input() orgDefaultAllowed: string;
106
107     // list of org fields to receive the context org as their default for new records
108     @Input() orgFieldsDefaultingToContextOrg: string;
109
110     // Optional template containing help/about text which will
111     // be added to the page, above the grid.
112     @Input() helpTemplate: TemplateRef<any>;
113
114     // Override field options for create/edit dialog
115     @Input() fieldOptions: {[field: string]: FmFieldOptions};
116
117     // Override default values for fm-editor
118     @Input() defaultNewRecord: IdlObject;
119
120     // Used as the first part of the routerLink path when creating
121     // links to related tables via configField's.
122     @Input() configLinkBasePath: string;
123
124     // Bonus fields to add to the grid by passing arbitrary templates,
125     // for example, a column created by callbacks based on data from
126     // other columns
127     @Input() templateFields: TemplateField[];
128
129     @ViewChild('grid', { static: true }) grid: GridComponent;
130     @ViewChild('editDialog', { static: true }) editDialog: FmRecordEditorComponent;
131     @ViewChild('successString', { static: true }) successString: StringComponent;
132     @ViewChild('createString', { static: true }) createString: StringComponent;
133     @ViewChild('createErrString', { static: true }) createErrString: StringComponent;
134     @ViewChild('updateFailedString', { static: true }) updateFailedString: StringComponent;
135     @ViewChild('deleteFailedString', { static: true }) deleteFailedString: StringComponent;
136     @ViewChild('deleteSuccessString', { static: true }) deleteSuccessString: StringComponent;
137     @ViewChild('undeleteFailedString', { static: true }) undeleteFailedString: StringComponent;
138     @ViewChild('undeleteSuccessString', { static: true }) undeleteSuccessString: StringComponent;
139     @ViewChild('translator', { static: true }) translator: TranslateComponent;
140     @ViewChild('deleteConfirmDialog', { static: true })
141     private deleteConfirmDialog: ConfirmDialogComponent;
142
143     idlClassDef: any;
144     pkeyField: string;
145     configFields: any[]; // IDL field definitions
146
147     // True if any columns on the object support translations
148     translateRowIdx: number;
149     translateFieldIdx: number;
150     translatableFields: string[];
151
152     contextOrg: IdlObject;
153     searchOrgs: OrgFamily;
154     orgFieldLabel: string;
155     viewPerms: string;
156     canCreate: boolean;
157
158     // Filters may be passed via URL query param.
159     // They are used to augment the grid data search query.
160     gridFilters: {[key: string]: string | number};
161
162     constructor(
163         private route: ActivatedRoute,
164         private ngLocation: Location,
165         private format: FormatService,
166         public idl: IdlService,
167         private org: OrgService,
168         public auth: AuthService,
169         public pcrud: PcrudService,
170         private perm: PermService,
171         public toast: ToastService
172     ) {
173         this.translatableFields = [];
174         this.configFields = [];
175     }
176
177     applyOrgValues(orgId?: number) {
178
179         if (this.disableOrgFilter) {
180             this.orgField = null;
181             return;
182         }
183
184         if (!this.orgField) {
185             // If no org unit field is specified, try to find one.
186             // If an object type has multiple org unit fields, the
187             // caller should specify one or disable org unit filter.
188             this.idlClassDef.fields.forEach(field => {
189                 if (field['class'] === 'aou') {
190                     this.orgField = field.name;
191                 }
192             });
193         }
194
195         if (this.orgField) {
196             this.orgFieldLabel = this.idlClassDef.field_map[this.orgField].label;
197             this.contextOrg = this.org.get(orgId) || this.org.get(this.auth.user().ws_ou()) || this.org.root();
198             this.searchOrgs = {primaryOrgId: this.contextOrg.id()};
199         }
200     }
201
202     contextOrgChanged(orgEvent: any) {
203         this.grid.reload();
204         this.setDefaultNewRecordOrgFieldDefaults( orgEvent['primaryOrgId'] );
205     }
206
207     ngOnInit() {
208
209         this.idlClassDef = this.idl.classes[this.idlClass];
210         this.pkeyField = this.idlClassDef.pkey || 'id';
211
212         this.translatableFields =
213             this.idlClassDef.fields.filter(f => f.i18n).map(f => f.name);
214
215         if (!this.persistKey) {
216             this.persistKey =
217                 'admin.' +
218                 (this.persistKeyPfx ? this.persistKeyPfx + '.' : '') +
219                 this.idlClassDef.table;
220         }
221
222
223         // Note the field filter could be based purely on fields
224         // which are links, but that leads to cases where links
225         // are created to tables which are too big and/or admin
226         // interfaces which are not otherwise used because they
227         // have custom UI's instead.
228         // this.idlClassDef.fields.filter(f => f.datatype === 'link');
229         this.configFields =
230             this.idlClassDef.fields.filter(f => f.config_field);
231
232         // gridFilters are a JSON encoded string
233         const filters = this.route.snapshot.queryParamMap.get('gridFilters');
234         if (filters) {
235             try {
236                 this.gridFilters = JSON.parse(filters);
237             } catch (E) {
238                 console.error('Invalid grid filters provided: ', filters);
239             }
240
241             // Use the grid filters as the basis for our default
242             // new record (passed to fm-editor).
243             if (!this.defaultNewRecord) {
244                 const rec = this.idl.create(this.idlClass);
245                 Object.keys(this.gridFilters).forEach(field => {
246                     // When filtering on the primary key of the current
247                     // object type, avoid using it in the default new object.
248                     if (rec[field] && this.pkeyField !== field) {
249                         rec[field](this.gridFilters[field]);
250                     }
251                 });
252                 this.defaultNewRecord = rec;
253             }
254         }
255
256         // Limit the view org selector to orgs where the user has
257         // permacrud-encoded view permissions.
258         const pc = this.idlClassDef.permacrud;
259         if (pc && pc.retrieve) {
260             this.viewPerms = pc.retrieve.perms;
261         }
262
263         const contextOrg = this.route.snapshot.queryParamMap.get('contextOrg');
264         this.checkCreatePerms();
265         this.applyOrgValues(Number(contextOrg));
266
267         this.setDefaultNewRecordOrgFieldDefaults( Number(contextOrg) );
268
269         // If the caller provides not data source, create a generic one.
270         if (!this.dataSource) {
271             this.initDataSource();
272         }
273     }
274
275     setDefaultNewRecordOrgFieldDefaults(contextOrg: number) {
276         // however we get a defaultNewRecord, we may want to default some org fields to the context org
277         if (this.orgFieldsDefaultingToContextOrg) {
278             if (!this.defaultNewRecord) {
279                 this.defaultNewRecord = this.idl.create(this.idlClass);
280             }
281             this.orgFieldsDefaultingToContextOrg.split(/,/).forEach( field => {
282                 if (this.defaultNewRecord[field] && this.pkeyField !== field) {
283                     if (contextOrg) {
284                         // since this can change often, we'll just blow away anything that might have come in a different way
285                         this.defaultNewRecord[field]( contextOrg );
286                     }
287                 }
288             });
289         }
290     }
291
292     checkCreatePerms() {
293         this.canCreate = false;
294         const pc = this.idlClassDef.permacrud || {};
295         const perms = pc.create ? pc.create.perms : [];
296         if (perms.length === 0) { return; }
297
298         this.perm.hasWorkPermAt(perms, true).then(permMap => {
299             Object.keys(permMap).forEach(key => {
300                 if (permMap[key].length > 0) {
301                     this.canCreate = true;
302                 }
303             });
304         });
305     }
306
307     initDataSource() {
308         this.dataSource = new GridDataSource();
309
310         this.dataSource.getRows = (pager: Pager, sort: any[]) => {
311             const orderBy: any = {};
312
313             if (sort.length) {
314                 // Sort specified from grid
315                 orderBy[this.idlClass] = sort[0].name + ' ' + sort[0].dir;
316
317             } else if (this.sortField) {
318                 // Default sort field
319                 orderBy[this.idlClass] = this.sortField;
320             }
321
322             const searchOps = {
323                 offset: pager.offset,
324                 limit: pager.limit,
325                 order_by: orderBy
326             };
327
328             if (!this.contextOrg && !this.gridFilters && !Object.keys(this.dataSource.filters).length) {
329                 // No org filter -- fetch all rows
330                 return this.pcrud.retrieveAll(
331                     this.idlClass, searchOps, {fleshSelectors: true});
332             }
333
334             const search: any[] = new Array();
335             const orgFilter: any = {};
336
337             if (this.orgField && (this.searchOrgs || this.contextOrg)) {
338                 orgFilter[this.orgField] =
339                     this.searchOrgs.orgIds || [this.contextOrg.id()];
340                 search.push(orgFilter);
341             }
342
343             Object.keys(this.dataSource.filters).forEach(key => {
344                 Object.keys(this.dataSource.filters[key]).forEach(key2 => {
345                     search.push(this.dataSource.filters[key][key2]);
346                 });
347             });
348
349             // FIXME - do we want to remove this, which is used in several
350             // secondary admin pages, in favor of switching it to the built-in
351             // grid filtering?
352             if (this.gridFilters) {
353                 // Lay the URL grid filters over our search object.
354                 Object.keys(this.gridFilters).forEach(key => {
355                     const urlProvidedFilters = {};
356                     urlProvidedFilters[key] = this.gridFilters[key];
357                     search.push(urlProvidedFilters);
358                 });
359             }
360
361             return this.pcrud.search(
362                 this.idlClass, search, searchOps, {fleshSelectors: true});
363         };
364     }
365
366     showEditDialog(idlThing: IdlObject): Promise<any> {
367         if (this.disableEdit) {
368             return;
369         }
370         this.editDialog.mode = 'update';
371         this.editDialog.recordId = idlThing[this.pkeyField]();
372         return new Promise((resolve, reject) => {
373             this.editDialog.open({size: this.dialogSize}).subscribe(
374                 result => {
375                     this.successString.current()
376                         .then(str => this.toast.success(str));
377                     this.grid.reload();
378                     resolve(result);
379                 },
380                 error => {
381                     this.updateFailedString.current()
382                         .then(str => this.toast.danger(str));
383                     reject(error);
384                 }
385             );
386         });
387     }
388
389     editSelected(idlThings: IdlObject[]) {
390
391         // Edit each IDL thing one at a time
392         const editOneThing = (thing: IdlObject) => {
393             if (!thing) { return; }
394
395             this.showEditDialog(thing).then(
396                 () => editOneThing(idlThings.shift()));
397         };
398
399         editOneThing(idlThings.shift());
400     }
401
402     undeleteSelected(idlThings: IdlObject[]) {
403         idlThings.forEach(idlThing => idlThing.deleted(false));
404         this.pcrud.update(idlThings).subscribe(
405             val => {
406                 this.undeleteSuccessString.current()
407                     .then(str => this.toast.success(str));
408             },
409             err => {
410                 this.undeleteFailedString.current()
411                     .then(str => this.toast.danger(str));
412             },
413             ()  => this.grid.reload()
414         );
415     }
416
417     deleteSelected(idlThings: IdlObject[]) {
418         this.deleteConfirmDialog.open().subscribe(confirmed => {
419             if ( confirmed ) {
420                 idlThings.forEach(idlThing => idlThing.isdeleted(true));
421                 this.pcrud.autoApply(idlThings).subscribe(
422                     val => {
423                         this.deleteSuccessString.current()
424                             .then(str => this.toast.success(str));
425                     },
426                     err => {
427                         this.deleteFailedString.current()
428                             .then(str => this.toast.danger(str));
429                     },
430                     ()  => this.grid.reload()
431                 );
432             }
433         });
434     }
435
436     shouldDisableDelete(rows: IdlObject[]): boolean {
437         if (rows.length === 0) {
438             return true;
439         } else {
440             const deletedRows = rows.filter((row) => {
441                 if (row.deleted && row.deleted() === 't') {
442                     return true;
443                 } else if (row.isdeleted) {
444                     return row.isdeleted();
445                 }
446             });
447             return deletedRows.length > 0;
448         }
449     }
450
451     shouldDisableUndelete(rows: IdlObject[]): boolean {
452         if (rows.length === 0) {
453             return true;
454         } else {
455             const deletedRows = rows.filter((row) => {
456                 if (row.deleted && row.deleted() === 't') {
457                     return true;
458                 } else if (row.isdeleted) {
459                     return row.isdeleted();
460                 }
461             });
462             return deletedRows.length !== rows.length;
463         }
464     }
465
466     createNew() {
467         this.editDialog.mode = 'create';
468         // We reuse the same editor for all actions.  Be sure
469         // create action does not try to modify an existing record.
470         this.editDialog.recordId = null;
471         this.editDialog.record = null;
472         this.editDialog.open({size: this.dialogSize}).subscribe(
473             ok => {
474                 this.createString.current()
475                     .then(str => this.toast.success(str));
476                 this.grid.reload();
477             },
478             rejection => {
479                 if (!rejection.dismissed) {
480                     this.createErrString.current()
481                         .then(str => this.toast.danger(str));
482                 }
483             }
484         );
485     }
486     // Open the field translation dialog.
487     // Link the next/previous actions to cycle through each translatable
488     // field on each row.
489     translate() {
490         this.translateRowIdx = 0;
491         this.translateFieldIdx = 0;
492         this.translator.fieldName = this.translatableFields[this.translateFieldIdx];
493         this.translator.idlObject = this.dataSource.data[this.translateRowIdx];
494
495         this.translator.nextString = () => {
496
497             if (this.translateFieldIdx < this.translatableFields.length - 1) {
498                 this.translateFieldIdx++;
499
500             } else if (this.translateRowIdx < this.dataSource.data.length - 1) {
501                 this.translateRowIdx++;
502                 this.translateFieldIdx = 0;
503             }
504
505             this.translator.idlObject =
506                 this.dataSource.data[this.translateRowIdx];
507             this.translator.fieldName =
508                 this.translatableFields[this.translateFieldIdx];
509         };
510
511         this.translator.prevString = () => {
512
513             if (this.translateFieldIdx > 0) {
514                 this.translateFieldIdx--;
515
516             } else if (this.translateRowIdx > 0) {
517                 this.translateRowIdx--;
518                 this.translateFieldIdx = 0;
519             }
520
521             this.translator.idlObject =
522                 this.dataSource.data[this.translateRowIdx];
523             this.translator.fieldName =
524                 this.translatableFields[this.translateFieldIdx];
525         };
526
527         this.translator.open({size: 'lg'});
528     }
529
530     // Construct a routerLink path for a configField.
531     configFieldRouteLink(row: any, col: GridColumn): string {
532         const cf = this.configFields.filter(field => field.name === col.name)[0];
533         const linkClass = this.idl.classes[cf['class']];
534         const pathParts = linkClass.table.split(/\./); // schema.tablename
535         return `${this.configLinkBasePath}/${pathParts[0]}/${pathParts[1]}`;
536     }
537
538     // Compiles a gridFilter value used when navigating to a linked
539     // class via configField.  The filter ensures the linked page
540     // only shows rows which refer back to the object from which the
541     // link was clicked.
542     configFieldRouteParams(row: any, col: GridColumn): any {
543         const cf = this.configFields.filter(field => field.name === col.name)[0];
544         let value = this.configFieldLinkedValue(row, col);
545
546         // For certain has-a relationships, the linked object will be
547         // fleshed so its display (selector) value can be used.
548         // Extract the scalar value found at the remote target field.
549         if (value && typeof value === 'object') { value = value[cf.key](); }
550
551         const filter: any = {};
552         filter[cf.key] = value;
553
554         return {gridFilters : JSON.stringify(filter)};
555     }
556
557     // Returns the value on the local object for the field which
558     // refers to the remote object.  This may be a scalar or a
559     // fleshed IDL object.
560     configFieldLinkedValue(row: any, col: GridColumn): any {
561         const cf = this.configFields.filter(field => field.name === col.name)[0];
562         const linkClass = this.idl.classes[cf['class']];
563
564         // cf.key is the name of the field on the linked object that matches
565         // the value on our local object.
566         // In as has_many relationship, the remote field has its own
567         // 'key' value which determines which field on the local object
568         // represents the other end of the relationship.  This is
569         // typically, but not always the local pkey field.
570
571         const localField =
572             cf.reltype === 'has_many' ?
573             (linkClass.field_map[cf.key].key || this.pkeyField) : cf.name;
574
575         return row[localField]();
576     }
577
578     // Returns a URL suitable for using as an href.
579     // We use an href to jump to the secondary admin page because
580     // routerLink within the same base component results in component
581     // reuse of a series of components which were not designed with
582     // reuse in mind.
583     configFieldLinkUrl(row: any, col: GridColumn): string {
584         const path = this.configFieldRouteLink(row, col);
585         const filters = this.configFieldRouteParams(row, col);
586         const url = path + '?gridFilters=' +
587             encodeURIComponent(filters.gridFilters);
588
589         return this.ngLocation.prepareExternalUrl(url);
590     }
591
592     configLinkLabel(row: any, col: GridColumn): string {
593         const cf = this.configFields.filter(field => field.name === col.name)[0];
594
595         // Has-many links have no specific value to use for display
596         // so just use the column label.
597         if (cf.reltype === 'has_many') { return col.label; }
598
599         return this.format.transform({
600             value: row[col.name](),
601             idlClass: this.idlClass,
602             idlField: col.name
603         });
604     }
605
606     clearGridFiltersUrl(): string {
607         const parts = this.idlClassDef.table.split(/\./);
608         const url = this.configLinkBasePath + '/' + parts[0] + '/' + parts[1];
609         return this.ngLocation.prepareExternalUrl(url);
610     }
611
612     hasNoHistory(): boolean {
613         return history.length === 0;
614     }
615
616     goBack() {
617         history.back();
618     }
619
620 }
621
622 export interface TemplateField {
623     cellTemplate: TemplateRef<any>;
624     name: string;
625 }
626