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 // 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;
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;
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;
60 // Disable the auto-matic org unit field filter
61 @Input() disableOrgFilter: boolean;
63 // Include objects linking to org units which are ancestors
64 // of the selected org unit.
65 @Input() includeOrgAncestors: boolean;
67 // Ditto includeOrgAncestors, but descendants.
68 @Input() includeOrgDescendants: boolean;
70 // Optional grid persist key. This is the part of the key
72 @Input() persistKey: string;
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;
79 // Optional comma-separated list of read-only fields
80 @Input() readonlyFields: string;
82 // Optional template containing help/about text which will
83 // be added to the page, above the grid.
84 @Input() helpTemplate: TemplateRef<any>;
86 // Override field options for create/edit dialog
87 @Input() fieldOptions: {[field: string]: FmFieldOptions};
89 // Override default values for fm-editor
90 @Input() defaultNewRecord: IdlObject;
92 // Used as the first part of the routerLink path when creating
93 // links to related tables via configField's.
94 @Input() configLinkBasePath: string;
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;
108 configFields: any[]; // IDL field definitions
110 // True if any columns on the object support translations
111 translateRowIdx: number;
112 translateFieldIdx: number;
113 translatableFields: string[];
115 contextOrg: IdlObject;
116 searchOrgs: OrgFamily;
117 orgFieldLabel: string;
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};
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
136 this.translatableFields = [];
137 this.configFields = [];
140 applyOrgValues(orgId?: number) {
142 if (this.disableOrgFilter) {
143 this.orgField = null;
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;
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()};
167 this.idlClassDef = this.idl.classes[this.idlClass];
168 this.pkeyField = this.idlClassDef.pkey || 'id';
170 this.translatableFields =
171 this.idlClassDef.fields.filter(f => f.i18n).map(f => f.name);
173 if (!this.persistKey) {
176 (this.persistKeyPfx ? this.persistKeyPfx + '.' : '') +
177 this.idlClassDef.table;
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');
188 this.idlClassDef.fields.filter(f => f.config_field);
190 // gridFilters are a JSON encoded string
191 const filters = this.route.snapshot.queryParamMap.get('gridFilters');
194 this.gridFilters = JSON.parse(filters);
196 console.error('Invalid grid filters provided: ', filters);
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]);
210 this.defaultNewRecord = rec;
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;
221 const contextOrg = this.route.snapshot.queryParamMap.get('contextOrg');
222 this.checkCreatePerms();
223 this.applyOrgValues(Number(contextOrg));
225 // If the caller provides not data source, create a generic one.
226 if (!this.dataSource) {
227 this.initDataSource();
230 // TODO: pass the row activate handler via the grid markup
231 this.grid.onRowActivate.subscribe(
232 (idlThing: IdlObject) => this.showEditDialog(idlThing)
237 this.canCreate = false;
238 const pc = this.idlClassDef.permacrud || {};
239 const perms = pc.create ? pc.create.perms : [];
240 if (perms.length === 0) { return; }
242 this.perm.hasWorkPermAt(perms, true).then(permMap => {
243 Object.keys(permMap).forEach(key => {
244 if (permMap[key].length > 0) {
245 this.canCreate = true;
252 this.dataSource = new GridDataSource();
254 this.dataSource.getRows = (pager: Pager, sort: any[]) => {
255 const orderBy: any = {};
258 // Sort specified from grid
259 orderBy[this.idlClass] = sort[0].name + ' ' + sort[0].dir;
261 } else if (this.sortField) {
262 // Default sort field
263 orderBy[this.idlClass] = this.sortField;
267 offset: pager.offset,
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});
278 const search: any = new Array();
279 const orgFilter: any = {};
281 if (this.orgField && (this.searchOrgs || this.contextOrg)) {
282 orgFilter[this.orgField] =
283 this.searchOrgs.orgIds || [this.contextOrg.id()];
284 search.push(orgFilter);
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]);
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
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];
303 return this.pcrud.search(
304 this.idlClass, search, searchOps, {fleshSelectors: true});
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(
314 this.successString.current()
315 .then(str => this.toast.success(str));
320 this.updateFailedString.current()
321 .then(str => this.toast.danger(str));
328 editSelected(idlThings: IdlObject[]) {
330 // Edit each IDL thing one at a time
331 const editOneThing = (thing: IdlObject) => {
332 if (!thing) { return; }
334 this.showEditDialog(thing).then(
335 () => editOneThing(idlThings.shift()));
338 editOneThing(idlThings.shift());
341 deleteSelected(idlThings: IdlObject[]) {
342 idlThings.forEach(idlThing => idlThing.isdeleted(true));
343 this.pcrud.autoApply(idlThings).subscribe(
345 this.deleteSuccessString.current()
346 .then(str => this.toast.success(str));
349 this.deleteFailedString.current()
350 .then(str => this.toast.danger(str));
352 () => this.grid.reload()
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(
364 this.createString.current()
365 .then(str => this.toast.success(str));
369 if (!rejection.dismissed) {
370 this.createErrString.current()
371 .then(str => this.toast.danger(str));
376 // Open the field translation dialog.
377 // Link the next/previous actions to cycle through each translatable
378 // field on each row.
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];
385 this.translator.nextString = () => {
387 if (this.translateFieldIdx < this.translatableFields.length - 1) {
388 this.translateFieldIdx++;
390 } else if (this.translateRowIdx < this.dataSource.data.length - 1) {
391 this.translateRowIdx++;
392 this.translateFieldIdx = 0;
395 this.translator.idlObject =
396 this.dataSource.data[this.translateRowIdx];
397 this.translator.fieldName =
398 this.translatableFields[this.translateFieldIdx];
401 this.translator.prevString = () => {
403 if (this.translateFieldIdx > 0) {
404 this.translateFieldIdx--;
406 } else if (this.translateRowIdx > 0) {
407 this.translateRowIdx--;
408 this.translateFieldIdx = 0;
411 this.translator.idlObject =
412 this.dataSource.data[this.translateRowIdx];
413 this.translator.fieldName =
414 this.translatableFields[this.translateFieldIdx];
417 this.translator.open({size: 'lg'});
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]}`;
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
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);
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](); }
441 const filter: any = {};
442 filter[cf.key] = value;
444 return {gridFilters : JSON.stringify(filter)};
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']];
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.
462 cf.reltype === 'has_many' ?
463 (linkClass.field_map[cf.key].key || this.pkeyField) : cf.name;
465 return row[localField]();
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
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);
479 return this.ngLocation.prepareExternalUrl(url);
482 configLinkLabel(row: any, col: GridColumn): string {
483 const cf = this.configFields.filter(field => field.name === col.name)[0];
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; }
489 return this.format.transform({
490 value: row[col.name](),
491 idlClass: this.idlClass,
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);