1 import {Component, Input, OnInit, TemplateRef, ViewChild} from '@angular/core';
2 import {ActivatedRoute} from '@angular/router';
3 import {IdlService, IdlObject} from '@eg/core/idl.service';
4 import {GridDataSource} from '@eg/share/grid/grid';
5 import {GridComponent} from '@eg/share/grid/grid.component';
6 import {TranslateComponent} from '@eg/staff/share/translate/translate.component';
7 import {ToastService} from '@eg/share/toast/toast.service';
8 import {Pager} from '@eg/share/util/pager';
9 import {PcrudService} from '@eg/core/pcrud.service';
10 import {OrgService} from '@eg/core/org.service';
11 import {PermService} from '@eg/core/perm.service';
12 import {AuthService} from '@eg/core/auth.service';
13 import {FmRecordEditorComponent} from '@eg/share/fm-editor/fm-editor.component';
14 import {StringComponent} from '@eg/share/string/string.component';
17 * General purpose CRUD interface for IDL objects
19 * Object types using this component must be editable via PCRUD.
23 selector: 'eg-admin-page',
24 templateUrl: './admin-page.component.html'
27 export class AdminPageComponent implements OnInit {
29 @Input() idlClass: string;
31 // Default sort field, used when no grid sorting is applied.
32 @Input() sortField: string;
34 // Data source may be provided by the caller. This gives the caller
35 // complete control over the contents of the grid. If no data source
36 // is provided, a generic one is create which is sufficient for data
37 // that requires no special handling, filtering, etc.
38 @Input() dataSource: GridDataSource;
40 // Size of create/edito dialog. Uses large by default.
41 @Input() dialogSize: 'sm' | 'lg' = 'lg';
43 // If an org unit field is specified, an org unit filter
44 // is added to the top of the page.
45 @Input() orgField: string;
47 // Disable the auto-matic org unit field filter
48 @Input() disableOrgFilter: boolean;
50 // Include objects linking to org units which are ancestors
51 // of the selected org unit.
52 @Input() includeOrgAncestors: boolean;
54 // Ditto includeOrgAncestors, but descendants.
55 @Input() includeOrgDescendants: boolean;
57 // Optional grid persist key. This is the part of the key
59 @Input() persistKey: string;
61 // Optional path component to add to the generated grid persist key,
62 // formatted as (for example):
63 // 'eg.grid.admin.${persistKeyPfx}.config.billing_type'
64 @Input() persistKeyPfx: string;
66 // Optional comma-separated list of read-only fields
67 @Input() readonlyFields: string;
69 @ViewChild('grid') grid: GridComponent;
70 @ViewChild('editDialog') editDialog: FmRecordEditorComponent;
71 @ViewChild('successString') successString: StringComponent;
72 @ViewChild('createString') createString: StringComponent;
73 @ViewChild('createErrString') createErrString: StringComponent;
74 @ViewChild('updateFailedString') updateFailedString: StringComponent;
75 @ViewChild('translator') translator: TranslateComponent;
80 // True if any columns on the object support translations
81 translateRowIdx: number;
82 translateFieldIdx: number;
83 translatableFields: string[];
85 contextOrg: IdlObject;
86 orgFieldLabel: string;
90 // Filters may be passed via URL query param.
91 // They are used to augment the grid data search query.
92 gridFilters: {[key: string]: string | number};
95 private route: ActivatedRoute,
96 private idl: IdlService,
97 private org: OrgService,
98 private auth: AuthService,
99 private pcrud: PcrudService,
100 private perm: PermService,
101 private toast: ToastService
103 this.translatableFields = [];
106 applyOrgValues(orgId?: number) {
108 if (this.disableOrgFilter) {
109 this.orgField = null;
113 if (!this.orgField) {
114 // If no org unit field is specified, try to find one.
115 // If an object type has multiple org unit fields, the
116 // caller should specify one or disable org unit filter.
117 this.idlClassDef.fields.forEach(field => {
118 if (field['class'] === 'aou') {
119 this.orgField = field.name;
125 this.orgFieldLabel = this.idlClassDef.field_map[this.orgField].label;
126 this.contextOrg = this.org.get(orgId) || this.org.root();
131 this.idlClassDef = this.idl.classes[this.idlClass];
132 this.pkeyField = this.idlClassDef.pkey || 'id';
134 this.translatableFields =
135 this.idlClassDef.fields.filter(f => f.i18n).map(f => f.name);
137 if (!this.persistKey) {
140 (this.persistKeyPfx ? this.persistKeyPfx + '.' : '') +
141 this.idlClassDef.table;
144 // gridFilters are a JSON encoded string
145 const filters = this.route.snapshot.queryParamMap.get('gridFilters');
148 this.gridFilters = JSON.parse(filters);
150 console.error('Invalid grid filters provided: ', filters);
154 // Limit the view org selector to orgs where the user has
155 // permacrud-encoded view permissions.
156 const pc = this.idlClassDef.permacrud;
157 if (pc && pc.retrieve) {
158 this.viewPerms = pc.retrieve.perms;
161 const contextOrg = this.route.snapshot.queryParamMap.get('contextOrg');
162 this.checkCreatePerms();
163 this.applyOrgValues(Number(contextOrg));
165 // If the caller provides not data source, create a generic one.
166 if (!this.dataSource) {
167 this.initDataSource();
170 // TODO: pass the row activate handler via the grid markup
171 this.grid.onRowActivate.subscribe(
172 (idlThing: IdlObject) => this.showEditDialog(idlThing)
177 this.canCreate = false;
178 const pc = this.idlClassDef.permacrud || {};
179 const perms = pc.create ? pc.create.perms : [];
180 if (perms.length === 0) { return; }
182 this.perm.hasWorkPermAt(perms, true).then(permMap => {
183 Object.keys(permMap).forEach(key => {
184 if (permMap[key].length > 0) {
185 this.canCreate = true;
191 orgOnChange(org: IdlObject) {
192 this.contextOrg = org;
197 this.dataSource = new GridDataSource();
199 this.dataSource.getRows = (pager: Pager, sort: any[]) => {
200 const orderBy: any = {};
203 // Sort specified from grid
204 orderBy[this.idlClass] = sort[0].name + ' ' + sort[0].dir;
206 } else if (this.sortField) {
207 // Default sort field
208 orderBy[this.idlClass] = this.sortField;
212 offset: pager.offset,
217 if (!this.contextOrg && !this.gridFilters) {
218 // No org filter -- fetch all rows
219 return this.pcrud.retrieveAll(
220 this.idlClass, searchOps, {fleshSelectors: true});
223 const search: any = {};
225 if (this.contextOrg) {
226 // Filter rows by those linking to the context org and
227 // optionally ancestor and descendant org units.
229 let orgs = [this.contextOrg.id()];
231 if (this.includeOrgAncestors) {
232 orgs = this.org.ancestors(this.contextOrg, true);
235 if (this.includeOrgDescendants) {
236 // can result in duplicate workstation org IDs... meh
238 this.org.descendants(this.contextOrg, true));
241 search[this.orgField] = orgs;
244 if (this.gridFilters) {
245 // Lay the URL grid filters over our search object.
246 Object.keys(this.gridFilters).forEach(key => {
247 search[key] = this.gridFilters[key];
251 return this.pcrud.search(
252 this.idlClass, search, searchOps, {fleshSelectors: true});
256 disableAncestorSelector(): boolean {
257 return this.contextOrg &&
258 this.contextOrg.id() === this.org.root().id();
261 disableDescendantSelector(): boolean {
262 return this.contextOrg && this.contextOrg.children().length === 0;
265 showEditDialog(idlThing: IdlObject) {
266 this.editDialog.mode = 'update';
267 this.editDialog.recId = idlThing[this.pkeyField]();
268 return this.editDialog.open({size: this.dialogSize}).then(
270 this.successString.current()
271 .then(str => this.toast.success(str));
275 if (!rejection.dismissed) {
276 this.updateFailedString.current()
277 .then(str => this.toast.danger(str));
283 editSelected(idlThings: IdlObject[]) {
285 // Edit each IDL thing one at a time
286 const editOneThing = (thing: IdlObject) => {
287 if (!thing) { return; }
289 this.showEditDialog(thing).then(
290 () => editOneThing(idlThings.shift()));
293 editOneThing(idlThings.shift());
296 deleteSelected(idlThings: IdlObject[]) {
297 idlThings.forEach(idlThing => idlThing.isdeleted(true));
298 this.pcrud.autoApply(idlThings).subscribe(
299 val => console.debug('deleted: ' + val),
301 () => this.grid.reload()
306 this.editDialog.mode = 'create';
307 // We reuse the same editor for all actions. Be sure
308 // create action does not try to modify an existing record.
309 this.editDialog.recId = null;
310 this.editDialog.record = null;
311 this.editDialog.open({size: this.dialogSize}).then(
313 this.createString.current()
314 .then(str => this.toast.success(str));
318 if (!rejection.dismissed) {
319 this.createErrString.current()
320 .then(str => this.toast.danger(str));
325 // Open the field translation dialog.
326 // Link the next/previous actions to cycle through each translatable
327 // field on each row.
329 this.translateRowIdx = 0;
330 this.translateFieldIdx = 0;
331 this.translator.fieldName = this.translatableFields[this.translateFieldIdx];
332 this.translator.idlObject = this.dataSource.data[this.translateRowIdx];
334 this.translator.nextString = () => {
336 if (this.translateFieldIdx < this.translatableFields.length - 1) {
337 this.translateFieldIdx++;
339 } else if (this.translateRowIdx < this.dataSource.data.length - 1) {
340 this.translateRowIdx++;
341 this.translateFieldIdx = 0;
344 this.translator.idlObject =
345 this.dataSource.data[this.translateRowIdx];
346 this.translator.fieldName =
347 this.translatableFields[this.translateFieldIdx];
350 this.translator.prevString = () => {
352 if (this.translateFieldIdx > 0) {
353 this.translateFieldIdx--;
355 } else if (this.translateRowIdx > 0) {
356 this.translateRowIdx--;
357 this.translateFieldIdx = 0;
360 this.translator.idlObject =
361 this.dataSource.data[this.translateRowIdx];
362 this.translator.fieldName =
363 this.translatableFields[this.translateFieldIdx];
366 this.translator.open({size: 'lg'});