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';
15 import {OrgFamily} from '@eg/share/org-family-select/org-family-select.component';
18 * General purpose CRUD interface for IDL objects
20 * Object types using this component must be editable via PCRUD.
24 selector: 'eg-admin-page',
25 templateUrl: './admin-page.component.html'
28 export class AdminPageComponent implements OnInit {
30 @Input() idlClass: string;
32 // Default sort field, used when no grid sorting is applied.
33 @Input() sortField: string;
35 // Data source may be provided by the caller. This gives the caller
36 // complete control over the contents of the grid. If no data source
37 // is provided, a generic one is create which is sufficient for data
38 // that requires no special handling, filtering, etc.
39 @Input() dataSource: GridDataSource;
41 // Size of create/edito dialog. Uses large by default.
42 @Input() dialogSize: 'sm' | 'lg' = 'lg';
44 // If an org unit field is specified, an org unit filter
45 // is added to the top of the page.
46 @Input() orgField: string;
48 // Disable the auto-matic org unit field filter
49 @Input() disableOrgFilter: boolean;
51 // Include objects linking to org units which are ancestors
52 // of the selected org unit.
53 @Input() includeOrgAncestors: boolean;
55 // Ditto includeOrgAncestors, but descendants.
56 @Input() includeOrgDescendants: boolean;
58 // Optional grid persist key. This is the part of the key
60 @Input() persistKey: string;
62 // Optional path component to add to the generated grid persist key,
63 // formatted as (for example):
64 // 'eg.grid.admin.${persistKeyPfx}.config.billing_type'
65 @Input() persistKeyPfx: string;
67 // Optional comma-separated list of read-only fields
68 @Input() readonlyFields: string;
70 @ViewChild('grid') grid: GridComponent;
71 @ViewChild('editDialog') editDialog: FmRecordEditorComponent;
72 @ViewChild('successString') successString: StringComponent;
73 @ViewChild('createString') createString: StringComponent;
74 @ViewChild('createErrString') createErrString: StringComponent;
75 @ViewChild('updateFailedString') updateFailedString: StringComponent;
76 @ViewChild('translator') translator: TranslateComponent;
81 // True if any columns on the object support translations
82 translateRowIdx: number;
83 translateFieldIdx: number;
84 translatableFields: string[];
86 contextOrg: IdlObject;
87 searchOrgs: OrgFamily;
88 orgFieldLabel: string;
92 // Filters may be passed via URL query param.
93 // They are used to augment the grid data search query.
94 gridFilters: {[key: string]: string | number};
97 private route: ActivatedRoute,
98 private idl: IdlService,
99 private org: OrgService,
100 private auth: AuthService,
101 private pcrud: PcrudService,
102 private perm: PermService,
103 private toast: ToastService
105 this.translatableFields = [];
108 applyOrgValues(orgId?: number) {
110 if (this.disableOrgFilter) {
111 this.orgField = null;
115 if (!this.orgField) {
116 // If no org unit field is specified, try to find one.
117 // If an object type has multiple org unit fields, the
118 // caller should specify one or disable org unit filter.
119 this.idlClassDef.fields.forEach(field => {
120 if (field['class'] === 'aou') {
121 this.orgField = field.name;
127 this.orgFieldLabel = this.idlClassDef.field_map[this.orgField].label;
128 this.contextOrg = this.org.get(orgId) || this.org.root();
129 this.searchOrgs = {primaryOrgId: this.contextOrg.id()};
134 this.idlClassDef = this.idl.classes[this.idlClass];
135 this.pkeyField = this.idlClassDef.pkey || 'id';
137 this.translatableFields =
138 this.idlClassDef.fields.filter(f => f.i18n).map(f => f.name);
140 if (!this.persistKey) {
143 (this.persistKeyPfx ? this.persistKeyPfx + '.' : '') +
144 this.idlClassDef.table;
147 // gridFilters are a JSON encoded string
148 const filters = this.route.snapshot.queryParamMap.get('gridFilters');
151 this.gridFilters = JSON.parse(filters);
153 console.error('Invalid grid filters provided: ', filters);
157 // Limit the view org selector to orgs where the user has
158 // permacrud-encoded view permissions.
159 const pc = this.idlClassDef.permacrud;
160 if (pc && pc.retrieve) {
161 this.viewPerms = pc.retrieve.perms;
164 const contextOrg = this.route.snapshot.queryParamMap.get('contextOrg');
165 this.checkCreatePerms();
166 this.applyOrgValues(Number(contextOrg));
168 // If the caller provides not data source, create a generic one.
169 if (!this.dataSource) {
170 this.initDataSource();
173 // TODO: pass the row activate handler via the grid markup
174 this.grid.onRowActivate.subscribe(
175 (idlThing: IdlObject) => this.showEditDialog(idlThing)
180 this.canCreate = false;
181 const pc = this.idlClassDef.permacrud || {};
182 const perms = pc.create ? pc.create.perms : [];
183 if (perms.length === 0) { return; }
185 this.perm.hasWorkPermAt(perms, true).then(permMap => {
186 Object.keys(permMap).forEach(key => {
187 if (permMap[key].length > 0) {
188 this.canCreate = true;
195 this.dataSource = new GridDataSource();
197 this.dataSource.getRows = (pager: Pager, sort: any[]) => {
198 const orderBy: any = {};
201 // Sort specified from grid
202 orderBy[this.idlClass] = sort[0].name + ' ' + sort[0].dir;
204 } else if (this.sortField) {
205 // Default sort field
206 orderBy[this.idlClass] = this.sortField;
210 offset: pager.offset,
215 if (!this.contextOrg && !this.gridFilters) {
216 // No org filter -- fetch all rows
217 return this.pcrud.retrieveAll(
218 this.idlClass, searchOps, {fleshSelectors: true});
221 const search: any = {};
223 search[this.orgField] = this.searchOrgs.orgIds || [this.contextOrg.id()];
225 if (this.gridFilters) {
226 // Lay the URL grid filters over our search object.
227 Object.keys(this.gridFilters).forEach(key => {
228 search[key] = this.gridFilters[key];
232 return this.pcrud.search(
233 this.idlClass, search, searchOps, {fleshSelectors: true});
237 showEditDialog(idlThing: IdlObject): Promise<any> {
238 this.editDialog.mode = 'update';
239 this.editDialog.recId = idlThing[this.pkeyField]();
240 return new Promise((resolve, reject) => {
241 this.editDialog.open({size: this.dialogSize}).subscribe(
243 this.successString.current()
244 .then(str => this.toast.success(str));
249 this.updateFailedString.current()
250 .then(str => this.toast.danger(str));
257 editSelected(idlThings: IdlObject[]) {
259 // Edit each IDL thing one at a time
260 const editOneThing = (thing: IdlObject) => {
261 if (!thing) { return; }
263 this.showEditDialog(thing).then(
264 () => editOneThing(idlThings.shift()));
267 editOneThing(idlThings.shift());
270 deleteSelected(idlThings: IdlObject[]) {
271 idlThings.forEach(idlThing => idlThing.isdeleted(true));
272 this.pcrud.autoApply(idlThings).subscribe(
273 val => console.debug('deleted: ' + val),
275 () => this.grid.reload()
280 this.editDialog.mode = 'create';
281 // We reuse the same editor for all actions. Be sure
282 // create action does not try to modify an existing record.
283 this.editDialog.recId = null;
284 this.editDialog.record = null;
285 this.editDialog.open({size: this.dialogSize}).subscribe(
287 this.createString.current()
288 .then(str => this.toast.success(str));
292 if (!rejection.dismissed) {
293 this.createErrString.current()
294 .then(str => this.toast.danger(str));
299 // Open the field translation dialog.
300 // Link the next/previous actions to cycle through each translatable
301 // field on each row.
303 this.translateRowIdx = 0;
304 this.translateFieldIdx = 0;
305 this.translator.fieldName = this.translatableFields[this.translateFieldIdx];
306 this.translator.idlObject = this.dataSource.data[this.translateRowIdx];
308 this.translator.nextString = () => {
310 if (this.translateFieldIdx < this.translatableFields.length - 1) {
311 this.translateFieldIdx++;
313 } else if (this.translateRowIdx < this.dataSource.data.length - 1) {
314 this.translateRowIdx++;
315 this.translateFieldIdx = 0;
318 this.translator.idlObject =
319 this.dataSource.data[this.translateRowIdx];
320 this.translator.fieldName =
321 this.translatableFields[this.translateFieldIdx];
324 this.translator.prevString = () => {
326 if (this.translateFieldIdx > 0) {
327 this.translateFieldIdx--;
329 } else if (this.translateRowIdx > 0) {
330 this.translateRowIdx--;
331 this.translateFieldIdx = 0;
334 this.translator.idlObject =
335 this.dataSource.data[this.translateRowIdx];
336 this.translator.fieldName =
337 this.translatableFields[this.translateFieldIdx];
340 this.translator.open({size: 'lg'});