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';
21 * General purpose CRUD interface for IDL objects
23 * Object types using this component must be editable via PCRUD.
27 selector: 'eg-admin-page',
28 templateUrl: './admin-page.component.html'
31 export class AdminPageComponent implements OnInit {
33 @Input() idlClass: string;
35 // Default sort field, used when no grid sorting is applied.
36 @Input() sortField: string;
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;
44 // Size of create/edito dialog. Uses large by default.
45 @Input() dialogSize: 'sm' | 'lg' = 'lg';
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;
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;
56 // Disable the auto-matic org unit field filter
57 @Input() disableOrgFilter: boolean;
59 // Include objects linking to org units which are ancestors
60 // of the selected org unit.
61 @Input() includeOrgAncestors: boolean;
63 // Ditto includeOrgAncestors, but descendants.
64 @Input() includeOrgDescendants: boolean;
66 // Optional grid persist key. This is the part of the key
68 @Input() persistKey: string;
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;
75 // Optional comma-separated list of read-only fields
76 @Input() readonlyFields: string;
78 // Optional template containing help/about text which will
79 // be added to the page, above the grid.
80 @Input() helpTemplate: TemplateRef<any>;
82 // Override field options for create/edit dialog
83 @Input() fieldOptions: {[field: string]: FmFieldOptions};
85 // Override default values for fm-editor
86 @Input() defaultNewRecord: IdlObject;
88 // Used as the first part of the routerLink path when creating
89 // links to related tables via configField's.
90 @Input() configLinkBasePath: string;
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;
104 configFields: any[]; // IDL field definitions
106 // True if any columns on the object support translations
107 translateRowIdx: number;
108 translateFieldIdx: number;
109 translatableFields: string[];
111 contextOrg: IdlObject;
112 searchOrgs: OrgFamily;
113 orgFieldLabel: string;
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};
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
132 this.translatableFields = [];
133 this.configFields = [];
136 applyOrgValues(orgId?: number) {
138 if (this.disableOrgFilter) {
139 this.orgField = null;
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;
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()};
163 this.idlClassDef = this.idl.classes[this.idlClass];
164 this.pkeyField = this.idlClassDef.pkey || 'id';
166 this.translatableFields =
167 this.idlClassDef.fields.filter(f => f.i18n).map(f => f.name);
169 if (!this.persistKey) {
172 (this.persistKeyPfx ? this.persistKeyPfx + '.' : '') +
173 this.idlClassDef.table;
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');
184 this.idlClassDef.fields.filter(f => f.config_field);
186 // gridFilters are a JSON encoded string
187 const filters = this.route.snapshot.queryParamMap.get('gridFilters');
190 this.gridFilters = JSON.parse(filters);
192 console.error('Invalid grid filters provided: ', filters);
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;
203 const contextOrg = this.route.snapshot.queryParamMap.get('contextOrg');
204 this.checkCreatePerms();
205 this.applyOrgValues(Number(contextOrg));
207 // If the caller provides not data source, create a generic one.
208 if (!this.dataSource) {
209 this.initDataSource();
212 // TODO: pass the row activate handler via the grid markup
213 this.grid.onRowActivate.subscribe(
214 (idlThing: IdlObject) => this.showEditDialog(idlThing)
219 this.canCreate = false;
220 const pc = this.idlClassDef.permacrud || {};
221 const perms = pc.create ? pc.create.perms : [];
222 if (perms.length === 0) { return; }
224 this.perm.hasWorkPermAt(perms, true).then(permMap => {
225 Object.keys(permMap).forEach(key => {
226 if (permMap[key].length > 0) {
227 this.canCreate = true;
234 this.dataSource = new GridDataSource();
236 this.dataSource.getRows = (pager: Pager, sort: any[]) => {
237 const orderBy: any = {};
240 // Sort specified from grid
241 orderBy[this.idlClass] = sort[0].name + ' ' + sort[0].dir;
243 } else if (this.sortField) {
244 // Default sort field
245 orderBy[this.idlClass] = this.sortField;
249 offset: pager.offset,
254 if (!this.contextOrg && !this.gridFilters) {
255 // No org filter -- fetch all rows
256 return this.pcrud.retrieveAll(
257 this.idlClass, searchOps, {fleshSelectors: true});
260 const search: any = {};
263 search[this.orgField] =
264 this.searchOrgs.orgIds || [this.contextOrg.id()];
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];
274 return this.pcrud.search(
275 this.idlClass, search, searchOps, {fleshSelectors: true});
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(
285 this.successString.current()
286 .then(str => this.toast.success(str));
291 this.updateFailedString.current()
292 .then(str => this.toast.danger(str));
299 editSelected(idlThings: IdlObject[]) {
301 // Edit each IDL thing one at a time
302 const editOneThing = (thing: IdlObject) => {
303 if (!thing) { return; }
305 this.showEditDialog(thing).then(
306 () => editOneThing(idlThings.shift()));
309 editOneThing(idlThings.shift());
312 deleteSelected(idlThings: IdlObject[]) {
313 idlThings.forEach(idlThing => idlThing.isdeleted(true));
314 this.pcrud.autoApply(idlThings).subscribe(
316 console.debug('deleted: ' + val);
317 this.deleteSuccessString.current()
318 .then(str => this.toast.success(str));
321 this.deleteFailedString.current()
322 .then(str => this.toast.danger(str));
324 () => this.grid.reload()
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(
336 this.createString.current()
337 .then(str => this.toast.success(str));
341 if (!rejection.dismissed) {
342 this.createErrString.current()
343 .then(str => this.toast.danger(str));
348 // Open the field translation dialog.
349 // Link the next/previous actions to cycle through each translatable
350 // field on each row.
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];
357 this.translator.nextString = () => {
359 if (this.translateFieldIdx < this.translatableFields.length - 1) {
360 this.translateFieldIdx++;
362 } else if (this.translateRowIdx < this.dataSource.data.length - 1) {
363 this.translateRowIdx++;
364 this.translateFieldIdx = 0;
367 this.translator.idlObject =
368 this.dataSource.data[this.translateRowIdx];
369 this.translator.fieldName =
370 this.translatableFields[this.translateFieldIdx];
373 this.translator.prevString = () => {
375 if (this.translateFieldIdx > 0) {
376 this.translateFieldIdx--;
378 } else if (this.translateRowIdx > 0) {
379 this.translateRowIdx--;
380 this.translateFieldIdx = 0;
383 this.translator.idlObject =
384 this.dataSource.data[this.translateRowIdx];
385 this.translator.fieldName =
386 this.translatableFields[this.translateFieldIdx];
389 this.translator.open({size: 'lg'});
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]}`;
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
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);
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](); }
413 const filter: any = {};
414 filter[cf.key] = value;
416 return {gridFilters : JSON.stringify(filter)};
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']];
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.
434 cf.reltype === 'has_many' ?
435 (linkClass.field_map[cf.key].key || this.pkeyField) : cf.name;
437 return row[localField]();
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
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);
451 return this.ngLocation.prepareExternalUrl(url);
454 configLinkLabel(row: any, col: GridColumn): string {
455 const cf = this.configFields.filter(field => field.name === col.name)[0];
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; }
461 return this.format.transform({
462 value: row[col.name](),
463 idlClass: this.idlClass,