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);
195 // Use the grid filters as the basis for our default
196 // new record (passed to fm-editor).
197 if (!this.defaultNewRecord) {
198 const rec = this.idl.create(this.idlClass);
199 Object.keys(this.gridFilters).forEach(field => {
200 // When filtering on the primary key of the current
201 // object type, avoid using it in the default new object.
202 if (rec[field] && this.pkeyField !== field) {
203 rec[field](this.gridFilters[field]);
206 this.defaultNewRecord = rec;
210 // Limit the view org selector to orgs where the user has
211 // permacrud-encoded view permissions.
212 const pc = this.idlClassDef.permacrud;
213 if (pc && pc.retrieve) {
214 this.viewPerms = pc.retrieve.perms;
217 const contextOrg = this.route.snapshot.queryParamMap.get('contextOrg');
218 this.checkCreatePerms();
219 this.applyOrgValues(Number(contextOrg));
221 // If the caller provides not data source, create a generic one.
222 if (!this.dataSource) {
223 this.initDataSource();
226 // TODO: pass the row activate handler via the grid markup
227 this.grid.onRowActivate.subscribe(
228 (idlThing: IdlObject) => this.showEditDialog(idlThing)
233 this.canCreate = false;
234 const pc = this.idlClassDef.permacrud || {};
235 const perms = pc.create ? pc.create.perms : [];
236 if (perms.length === 0) { return; }
238 this.perm.hasWorkPermAt(perms, true).then(permMap => {
239 Object.keys(permMap).forEach(key => {
240 if (permMap[key].length > 0) {
241 this.canCreate = true;
248 this.dataSource = new GridDataSource();
250 this.dataSource.getRows = (pager: Pager, sort: any[]) => {
251 const orderBy: any = {};
254 // Sort specified from grid
255 orderBy[this.idlClass] = sort[0].name + ' ' + sort[0].dir;
257 } else if (this.sortField) {
258 // Default sort field
259 orderBy[this.idlClass] = this.sortField;
263 offset: pager.offset,
268 if (!this.contextOrg && !this.gridFilters && !Object.keys(this.dataSource.filters).length) {
269 // No org filter -- fetch all rows
270 return this.pcrud.retrieveAll(
271 this.idlClass, searchOps, {fleshSelectors: true});
274 const search: any = new Array();
275 const orgFilter: any = {};
277 if (this.orgField && (this.searchOrgs || this.contextOrg)) {
278 orgFilter[this.orgField] =
279 this.searchOrgs.orgIds || [this.contextOrg.id()];
280 search.push(orgFilter);
283 Object.keys(this.dataSource.filters).forEach(key => {
284 Object.keys(this.dataSource.filters[key]).forEach(key2 => {
285 search.push(this.dataSource.filters[key][key2]);
289 // FIXME - do we want to remove this, whose only present user
290 // is the booking grid, in favor of switching it to the built-in
292 if (this.gridFilters) {
293 // Lay the URL grid filters over our search object.
294 Object.keys(this.gridFilters).forEach(key => {
295 search[key] = this.gridFilters[key];
299 return this.pcrud.search(
300 this.idlClass, search, searchOps, {fleshSelectors: true});
304 showEditDialog(idlThing: IdlObject): Promise<any> {
305 this.editDialog.mode = 'update';
306 this.editDialog.recordId = idlThing[this.pkeyField]();
307 return new Promise((resolve, reject) => {
308 this.editDialog.open({size: this.dialogSize}).subscribe(
310 this.successString.current()
311 .then(str => this.toast.success(str));
316 this.updateFailedString.current()
317 .then(str => this.toast.danger(str));
324 editSelected(idlThings: IdlObject[]) {
326 // Edit each IDL thing one at a time
327 const editOneThing = (thing: IdlObject) => {
328 if (!thing) { return; }
330 this.showEditDialog(thing).then(
331 () => editOneThing(idlThings.shift()));
334 editOneThing(idlThings.shift());
337 deleteSelected(idlThings: IdlObject[]) {
338 idlThings.forEach(idlThing => idlThing.isdeleted(true));
339 this.pcrud.autoApply(idlThings).subscribe(
341 this.deleteSuccessString.current()
342 .then(str => this.toast.success(str));
345 this.deleteFailedString.current()
346 .then(str => this.toast.danger(str));
348 () => this.grid.reload()
353 this.editDialog.mode = 'create';
354 // We reuse the same editor for all actions. Be sure
355 // create action does not try to modify an existing record.
356 this.editDialog.recordId = null;
357 this.editDialog.record = null;
358 this.editDialog.open({size: this.dialogSize}).subscribe(
360 this.createString.current()
361 .then(str => this.toast.success(str));
365 if (!rejection.dismissed) {
366 this.createErrString.current()
367 .then(str => this.toast.danger(str));
372 // Open the field translation dialog.
373 // Link the next/previous actions to cycle through each translatable
374 // field on each row.
376 this.translateRowIdx = 0;
377 this.translateFieldIdx = 0;
378 this.translator.fieldName = this.translatableFields[this.translateFieldIdx];
379 this.translator.idlObject = this.dataSource.data[this.translateRowIdx];
381 this.translator.nextString = () => {
383 if (this.translateFieldIdx < this.translatableFields.length - 1) {
384 this.translateFieldIdx++;
386 } else if (this.translateRowIdx < this.dataSource.data.length - 1) {
387 this.translateRowIdx++;
388 this.translateFieldIdx = 0;
391 this.translator.idlObject =
392 this.dataSource.data[this.translateRowIdx];
393 this.translator.fieldName =
394 this.translatableFields[this.translateFieldIdx];
397 this.translator.prevString = () => {
399 if (this.translateFieldIdx > 0) {
400 this.translateFieldIdx--;
402 } else if (this.translateRowIdx > 0) {
403 this.translateRowIdx--;
404 this.translateFieldIdx = 0;
407 this.translator.idlObject =
408 this.dataSource.data[this.translateRowIdx];
409 this.translator.fieldName =
410 this.translatableFields[this.translateFieldIdx];
413 this.translator.open({size: 'lg'});
416 // Construct a routerLink path for a configField.
417 configFieldRouteLink(row: any, col: GridColumn): string {
418 const cf = this.configFields.filter(field => field.name === col.name)[0];
419 const linkClass = this.idl.classes[cf['class']];
420 const pathParts = linkClass.table.split(/\./); // schema.tablename
421 return `${this.configLinkBasePath}/${pathParts[0]}/${pathParts[1]}`;
424 // Compiles a gridFilter value used when navigating to a linked
425 // class via configField. The filter ensures the linked page
426 // only shows rows which refer back to the object from which the
428 configFieldRouteParams(row: any, col: GridColumn): any {
429 const cf = this.configFields.filter(field => field.name === col.name)[0];
430 let value = this.configFieldLinkedValue(row, col);
432 // For certain has-a relationships, the linked object will be
433 // fleshed so its display (selector) value can be used.
434 // Extract the scalar value found at the remote target field.
435 if (value && typeof value === 'object') { value = value[cf.key](); }
437 const filter: any = {};
438 filter[cf.key] = value;
440 return {gridFilters : JSON.stringify(filter)};
443 // Returns the value on the local object for the field which
444 // refers to the remote object. This may be a scalar or a
445 // fleshed IDL object.
446 configFieldLinkedValue(row: any, col: GridColumn): any {
447 const cf = this.configFields.filter(field => field.name === col.name)[0];
448 const linkClass = this.idl.classes[cf['class']];
450 // cf.key is the name of the field on the linked object that matches
451 // the value on our local object.
452 // In as has_many relationship, the remote field has its own
453 // 'key' value which determines which field on the local object
454 // represents the other end of the relationship. This is
455 // typically, but not always the local pkey field.
458 cf.reltype === 'has_many' ?
459 (linkClass.field_map[cf.key].key || this.pkeyField) : cf.name;
461 return row[localField]();
464 // Returns a URL suitable for using as an href.
465 // We use an href to jump to the secondary admin page because
466 // routerLink within the same base component results in component
467 // reuse of a series of components which were not designed with
469 configFieldLinkUrl(row: any, col: GridColumn): string {
470 const path = this.configFieldRouteLink(row, col);
471 const filters = this.configFieldRouteParams(row, col);
472 const url = path + '?gridFilters=' +
473 encodeURIComponent(filters.gridFilters);
475 return this.ngLocation.prepareExternalUrl(url);
478 configLinkLabel(row: any, col: GridColumn): string {
479 const cf = this.configFields.filter(field => field.name === col.name)[0];
481 // Has-many links have no specific value to use for display
482 // so just use the column label.
483 if (cf.reltype === 'has_many') { return col.label; }
485 return this.format.transform({
486 value: row[col.name](),
487 idlClass: this.idlClass,
492 clearGridFiltersUrl(): string {
493 const parts = this.idlClassDef.table.split(/\./);
494 const url = this.configLinkBasePath + '/' + parts[0] + '/' + parts[1];
495 return this.ngLocation.prepareExternalUrl(url);