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;
79 createNew: () => void;
80 deleteSelected: (rows: IdlObject[]) => void;
81 editSelected: (rows: IdlObject[]) => void;
83 // True if any columns on the object support translations
84 translateRowIdx: number;
85 translateFieldIdx: number;
86 translatableFields: string[];
87 translate: () => void;
89 contextOrg: IdlObject;
90 orgFieldLabel: string;
94 // Filters may be passed via URL query param.
95 // They are used to augment the grid data search query.
96 gridFilters: {[key: string]: string | number};
99 private route: ActivatedRoute,
100 private idl: IdlService,
101 private org: OrgService,
102 private auth: AuthService,
103 private pcrud: PcrudService,
104 private perm: PermService,
105 private toast: ToastService
107 this.translatableFields = [];
110 applyOrgValues(orgId?: number) {
112 if (this.disableOrgFilter) {
113 this.orgField = null;
117 if (!this.orgField) {
118 // If no org unit field is specified, try to find one.
119 // If an object type has multiple org unit fields, the
120 // caller should specify one or disable org unit filter.
121 this.idlClassDef.fields.forEach(field => {
122 if (field['class'] === 'aou') {
123 this.orgField = field.name;
129 this.orgFieldLabel = this.idlClassDef.field_map[this.orgField].label;
130 this.contextOrg = this.org.get(orgId) || this.org.root();
135 this.idlClassDef = this.idl.classes[this.idlClass];
136 this.pkeyField = this.idlClassDef.pkey || 'id';
138 this.translatableFields =
139 this.idlClassDef.fields.filter(f => f.i18n).map(f => f.name);
141 if (!this.persistKey) {
144 (this.persistKeyPfx ? this.persistKeyPfx + '.' : '') +
145 this.idlClassDef.table;
148 // gridFilters are a JSON encoded string
149 const filters = this.route.snapshot.queryParamMap.get('gridFilters');
152 this.gridFilters = JSON.parse(filters);
154 console.error('Invalid grid filters provided: ', filters)
158 // Limit the view org selector to orgs where the user has
159 // permacrud-encoded view permissions.
160 const pc = this.idlClassDef.permacrud;
161 if (pc && pc.retrieve) {
162 this.viewPerms = pc.retrieve.perms;
165 const contextOrg = this.route.snapshot.queryParamMap.get('contextOrg');
166 this.checkCreatePerms();
167 this.applyOrgValues(Number(contextOrg));
169 // If the caller provides not data source, create a generic one.
170 if (!this.dataSource) {
171 this.initDataSource();
174 // TODO: pass the row activate handler via the grid markup
175 this.grid.onRowActivate.subscribe(
176 (idlThing: IdlObject) => this.showEditDialog(idlThing)
179 this.editSelected = (idlThings: IdlObject[]) => {
181 // Edit each IDL thing one at a time
182 const editOneThing = (thing: IdlObject) => {
183 if (!thing) { return; }
185 this.showEditDialog(thing).then(
186 () => editOneThing(idlThings.shift()));
189 editOneThing(idlThings.shift());
192 this.createNew = () => {
193 this.editDialog.mode = 'create';
194 // We reuse the same editor for all actions. Be sure
195 // create action does not try to modify an existing record.
196 this.editDialog.recId = null;
197 this.editDialog.record = null;
198 this.editDialog.open({size: this.dialogSize}).then(
200 this.createString.current()
201 .then(str => this.toast.success(str));
205 if (!rejection.dismissed) {
206 this.createErrString.current()
207 .then(str => this.toast.danger(str));
213 this.deleteSelected = (idlThings: IdlObject[]) => {
214 idlThings.forEach(idlThing => idlThing.isdeleted(true));
215 this.pcrud.autoApply(idlThings).subscribe(
216 val => console.debug('deleted: ' + val),
218 () => this.grid.reload()
222 // Open the field translation dialog.
223 // Link the next/previous actions to cycle through each translatable
224 // field on each row.
225 this.translate = () => {
226 this.translateRowIdx = 0;
227 this.translateFieldIdx = 0;
228 this.translator.fieldName = this.translatableFields[this.translateFieldIdx];
229 this.translator.idlObject = this.dataSource.data[this.translateRowIdx];
231 this.translator.nextString = () => {
233 if (this.translateFieldIdx < this.translatableFields.length - 1) {
234 this.translateFieldIdx++;
236 } else if (this.translateRowIdx < this.dataSource.data.length - 1) {
237 this.translateRowIdx++;
238 this.translateFieldIdx = 0;
241 this.translator.idlObject =
242 this.dataSource.data[this.translateRowIdx];
243 this.translator.fieldName =
244 this.translatableFields[this.translateFieldIdx];
247 this.translator.prevString = () => {
249 if (this.translateFieldIdx > 0) {
250 this.translateFieldIdx--;
252 } else if (this.translateRowIdx > 0) {
253 this.translateRowIdx--;
254 this.translateFieldIdx = 0;
257 this.translator.idlObject =
258 this.dataSource.data[this.translateRowIdx];
259 this.translator.fieldName =
260 this.translatableFields[this.translateFieldIdx];
263 this.translator.open({size: 'lg'});
268 this.canCreate = false;
269 const pc = this.idlClassDef.permacrud || {};
270 const perms = pc.create ? pc.create.perms : [];
271 if (perms.length === 0) { return; }
273 this.perm.hasWorkPermAt(perms, true).then(permMap => {
274 Object.keys(permMap).forEach(key => {
275 if (permMap[key].length > 0) {
276 this.canCreate = true;
282 orgOnChange(org: IdlObject) {
283 this.contextOrg = org;
288 this.dataSource = new GridDataSource();
290 this.dataSource.getRows = (pager: Pager, sort: any[]) => {
291 const orderBy: any = {};
294 // Sort specified from grid
295 orderBy[this.idlClass] = sort[0].name + ' ' + sort[0].dir;
297 } else if (this.sortField) {
298 // Default sort field
299 orderBy[this.idlClass] = this.sortField;
303 offset: pager.offset,
308 if (!this.contextOrg && !this.gridFilters) {
309 // No org filter -- fetch all rows
310 return this.pcrud.retrieveAll(
311 this.idlClass, searchOps, {fleshSelectors: true});
314 const search: any = {};
316 if (this.contextOrg) {
317 // Filter rows by those linking to the context org and
318 // optionally ancestor and descendant org units.
320 let orgs = [this.contextOrg.id()];
322 if (this.includeOrgAncestors) {
323 orgs = this.org.ancestors(this.contextOrg, true);
326 if (this.includeOrgDescendants) {
327 // can result in duplicate workstation org IDs... meh
329 this.org.descendants(this.contextOrg, true));
332 search[this.orgField] = orgs;
335 if (this.gridFilters) {
336 // Lay the URL grid filters over our search object.
337 Object.keys(this.gridFilters).forEach(key => {
338 search[key] = this.gridFilters[key];
342 return this.pcrud.search(
343 this.idlClass, search, searchOps, {fleshSelectors: true});
347 disableAncestorSelector(): boolean {
348 return this.contextOrg &&
349 this.contextOrg.id() === this.org.root().id();
352 disableDescendantSelector(): boolean {
353 return this.contextOrg && this.contextOrg.children().length === 0;
356 showEditDialog(idlThing: IdlObject) {
357 this.editDialog.mode = 'update';
358 this.editDialog.recId = idlThing[this.pkeyField]();
359 return this.editDialog.open({size: this.dialogSize}).then(
361 this.successString.current()
362 .then(str => this.toast.success(str));
366 if (!rejection.dismissed) {
367 this.updateFailedString.current()
368 .then(str => this.toast.danger(str));