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';
22 * General purpose CRUD interface for IDL objects
24 * Object types using this component must be editable via PCRUD.
28 selector: 'eg-admin-page',
29 templateUrl: './admin-page.component.html'
32 export class AdminPageComponent implements OnInit {
34 @Input() idlClass: string;
36 // Default sort field, used when no grid sorting is applied.
37 @Input() sortField: string;
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;
45 // Size of create/edito dialog. Uses large by default.
46 @Input() dialogSize: 'sm' | 'lg' = 'lg';
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;
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;
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;
61 // Disable the auto-matic org unit field filter
62 @Input() disableOrgFilter: boolean;
64 // Give the grid an option to undelete any deleted rows
65 @Input() enableUndelete: boolean;
67 // Remove the ability to delete rows
68 @Input() disableDelete: boolean;
70 // Optional: Replace the default deletion confirmation text with this
71 @Input() deleteConfirmation: string;
73 // Remove the ability to edit rows
74 @Input() disableEdit: boolean;
76 // Include objects linking to org units which are ancestors
77 // of the selected org unit.
78 @Input() includeOrgAncestors: boolean;
80 // Ditto includeOrgAncestors, but descendants.
81 @Input() includeOrgDescendants: boolean;
83 // Optional grid persist key. This is the part of the key
85 @Input() persistKey: string;
87 // If present, will be applied to the org selector for the grid
88 @Input() contextOrgSelectorPersistKey: string;
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;
95 // Optional comma-separated list of read-only fields
96 @Input() readonlyFields: string;
98 // Optional record label to use instead of the IDL label
99 @Input() recordLabel: string;
101 // optional flag to hide the Clear Filters action for gridFilters
102 @Input() hideClearFilters: boolean;
104 // optional list of org fields which are allowed a default if unset
105 @Input() orgDefaultAllowed: string;
107 // list of org fields to receive the context org as their default for new records
108 @Input() orgFieldsDefaultingToContextOrg: string;
110 // Optional template containing help/about text which will
111 // be added to the page, above the grid.
112 @Input() helpTemplate: TemplateRef<any>;
114 // Override field options for create/edit dialog
115 @Input() fieldOptions: {[field: string]: FmFieldOptions};
117 // Override default values for fm-editor
118 @Input() defaultNewRecord: IdlObject;
120 // Used as the first part of the routerLink path when creating
121 // links to related tables via configField's.
122 @Input() configLinkBasePath: string;
124 // Bonus fields to add to the grid by passing arbitrary templates,
125 // for example, a column created by callbacks based on data from
127 @Input() templateFields: TemplateField[];
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;
145 configFields: any[]; // IDL field definitions
147 // True if any columns on the object support translations
148 translateRowIdx: number;
149 translateFieldIdx: number;
150 translatableFields: string[];
152 contextOrg: IdlObject;
153 searchOrgs: OrgFamily;
154 orgFieldLabel: string;
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};
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
173 this.translatableFields = [];
174 this.configFields = [];
177 applyOrgValues(orgId?: number) {
179 if (this.disableOrgFilter) {
180 this.orgField = null;
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;
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()};
202 contextOrgChanged(orgEvent: any) {
204 this.setDefaultNewRecordOrgFieldDefaults( orgEvent['primaryOrgId'] );
209 this.idlClassDef = this.idl.classes[this.idlClass];
210 this.pkeyField = this.idlClassDef.pkey || 'id';
212 this.translatableFields =
213 this.idlClassDef.fields.filter(f => f.i18n).map(f => f.name);
215 if (!this.persistKey) {
218 (this.persistKeyPfx ? this.persistKeyPfx + '.' : '') +
219 this.idlClassDef.table;
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');
230 this.idlClassDef.fields.filter(f => f.config_field);
232 // gridFilters are a JSON encoded string
233 const filters = this.route.snapshot.queryParamMap.get('gridFilters');
236 this.gridFilters = JSON.parse(filters);
238 console.error('Invalid grid filters provided: ', filters);
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]);
252 this.defaultNewRecord = rec;
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;
263 const contextOrg = this.route.snapshot.queryParamMap.get('contextOrg');
264 this.checkCreatePerms();
265 this.applyOrgValues(Number(contextOrg));
267 this.setDefaultNewRecordOrgFieldDefaults( Number(contextOrg) );
269 // If the caller provides not data source, create a generic one.
270 if (!this.dataSource) {
271 this.initDataSource();
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);
281 this.orgFieldsDefaultingToContextOrg.split(/,/).forEach( field => {
282 if (this.defaultNewRecord[field] && this.pkeyField !== field) {
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 );
293 this.canCreate = false;
294 const pc = this.idlClassDef.permacrud || {};
295 const perms = pc.create ? pc.create.perms : [];
296 if (perms.length === 0) { return; }
298 this.perm.hasWorkPermAt(perms, true).then(permMap => {
299 Object.keys(permMap).forEach(key => {
300 if (permMap[key].length > 0) {
301 this.canCreate = true;
308 this.dataSource = new GridDataSource();
310 this.dataSource.getRows = (pager: Pager, sort: any[]) => {
311 const orderBy: any = {};
314 // Sort specified from grid
315 orderBy[this.idlClass] = sort[0].name + ' ' + sort[0].dir;
317 } else if (this.sortField) {
318 // Default sort field
319 orderBy[this.idlClass] = this.sortField;
323 offset: pager.offset,
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});
334 const search: any[] = new Array();
335 const orgFilter: any = {};
337 if (this.orgField && (this.searchOrgs || this.contextOrg)) {
338 orgFilter[this.orgField] =
339 this.searchOrgs.orgIds || [this.contextOrg.id()];
340 search.push(orgFilter);
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]);
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
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);
361 return this.pcrud.search(
362 this.idlClass, search, searchOps, {fleshSelectors: true});
366 showEditDialog(idlThing: IdlObject): Promise<any> {
367 if (this.disableEdit) {
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(
375 this.successString.current()
376 .then(str => this.toast.success(str));
381 this.updateFailedString.current()
382 .then(str => this.toast.danger(str));
389 editSelected(idlThings: IdlObject[]) {
391 // Edit each IDL thing one at a time
392 const editOneThing = (thing: IdlObject) => {
393 if (!thing) { return; }
395 this.showEditDialog(thing).then(
396 () => editOneThing(idlThings.shift()));
399 editOneThing(idlThings.shift());
402 undeleteSelected(idlThings: IdlObject[]) {
403 idlThings.forEach(idlThing => idlThing.deleted(false));
404 this.pcrud.update(idlThings).subscribe(
406 this.undeleteSuccessString.current()
407 .then(str => this.toast.success(str));
410 this.undeleteFailedString.current()
411 .then(str => this.toast.danger(str));
413 () => this.grid.reload()
417 deleteSelected(idlThings: IdlObject[]) {
418 this.deleteConfirmDialog.open().subscribe(confirmed => {
420 idlThings.forEach(idlThing => idlThing.isdeleted(true));
421 this.pcrud.autoApply(idlThings).subscribe(
423 this.deleteSuccessString.current()
424 .then(str => this.toast.success(str));
427 this.deleteFailedString.current()
428 .then(str => this.toast.danger(str));
430 () => this.grid.reload()
436 shouldDisableDelete(rows: IdlObject[]): boolean {
437 if (rows.length === 0) {
440 const deletedRows = rows.filter((row) => {
441 if (row.deleted && row.deleted() === 't') {
443 } else if (row.isdeleted) {
444 return row.isdeleted();
447 return deletedRows.length > 0;
451 shouldDisableUndelete(rows: IdlObject[]): boolean {
452 if (rows.length === 0) {
455 const deletedRows = rows.filter((row) => {
456 if (row.deleted && row.deleted() === 't') {
458 } else if (row.isdeleted) {
459 return row.isdeleted();
462 return deletedRows.length !== rows.length;
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(
474 this.createString.current()
475 .then(str => this.toast.success(str));
479 if (!rejection.dismissed) {
480 this.createErrString.current()
481 .then(str => this.toast.danger(str));
486 // Open the field translation dialog.
487 // Link the next/previous actions to cycle through each translatable
488 // field on each row.
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];
495 this.translator.nextString = () => {
497 if (this.translateFieldIdx < this.translatableFields.length - 1) {
498 this.translateFieldIdx++;
500 } else if (this.translateRowIdx < this.dataSource.data.length - 1) {
501 this.translateRowIdx++;
502 this.translateFieldIdx = 0;
505 this.translator.idlObject =
506 this.dataSource.data[this.translateRowIdx];
507 this.translator.fieldName =
508 this.translatableFields[this.translateFieldIdx];
511 this.translator.prevString = () => {
513 if (this.translateFieldIdx > 0) {
514 this.translateFieldIdx--;
516 } else if (this.translateRowIdx > 0) {
517 this.translateRowIdx--;
518 this.translateFieldIdx = 0;
521 this.translator.idlObject =
522 this.dataSource.data[this.translateRowIdx];
523 this.translator.fieldName =
524 this.translatableFields[this.translateFieldIdx];
527 this.translator.open({size: 'lg'});
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]}`;
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
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);
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](); }
551 const filter: any = {};
552 filter[cf.key] = value;
554 return {gridFilters : JSON.stringify(filter)};
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']];
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.
572 cf.reltype === 'has_many' ?
573 (linkClass.field_map[cf.key].key || this.pkeyField) : cf.name;
575 return row[localField]();
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
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);
589 return this.ngLocation.prepareExternalUrl(url);
592 configLinkLabel(row: any, col: GridColumn): string {
593 const cf = this.configFields.filter(field => field.name === col.name)[0];
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; }
599 return this.format.transform({
600 value: row[col.name](),
601 idlClass: this.idlClass,
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);
612 hasNoHistory(): boolean {
613 return history.length === 0;
622 export interface TemplateField {
623 cellTemplate: TemplateRef<any>;