]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/eg2/src/app/staff/share/admin-page/admin-page.component.ts
LP1830432: Make the org-family-select reusable
[working/Evergreen.git] / Open-ILS / src / eg2 / src / app / staff / share / admin-page / admin-page.component.ts
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';
16
17 /**
18  * General purpose CRUD interface for IDL objects
19  *
20  * Object types using this component must be editable via PCRUD.
21  */
22
23 @Component({
24     selector: 'eg-admin-page',
25     templateUrl: './admin-page.component.html'
26 })
27
28 export class AdminPageComponent implements OnInit {
29
30     @Input() idlClass: string;
31
32     // Default sort field, used when no grid sorting is applied.
33     @Input() sortField: string;
34
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;
40
41     // Size of create/edito dialog.  Uses large by default.
42     @Input() dialogSize: 'sm' | 'lg' = 'lg';
43
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;
47
48     // Disable the auto-matic org unit field filter
49     @Input() disableOrgFilter: boolean;
50
51     // Include objects linking to org units which are ancestors
52     // of the selected org unit.
53     @Input() includeOrgAncestors: boolean;
54
55     // Ditto includeOrgAncestors, but descendants.
56     @Input() includeOrgDescendants: boolean;
57
58     // Optional grid persist key.  This is the part of the key
59     // following eg.grid.
60     @Input() persistKey: string;
61
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;
66
67     // Optional comma-separated list of read-only fields
68     @Input() readonlyFields: string;
69
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;
77
78     idlClassDef: any;
79     pkeyField: string;
80
81     // True if any columns on the object support translations
82     translateRowIdx: number;
83     translateFieldIdx: number;
84     translatableFields: string[];
85
86     contextOrg: IdlObject;
87     searchOrgs: OrgFamily;
88     orgFieldLabel: string;
89     viewPerms: string;
90     canCreate: boolean;
91
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};
95
96     constructor(
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
104     ) {
105         this.translatableFields = [];
106     }
107
108     applyOrgValues(orgId?: number) {
109
110         if (this.disableOrgFilter) {
111             this.orgField = null;
112             return;
113         }
114
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;
122                 }
123             });
124         }
125
126         if (this.orgField) {
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()};
130         }
131     }
132
133     ngOnInit() {
134         this.idlClassDef = this.idl.classes[this.idlClass];
135         this.pkeyField = this.idlClassDef.pkey || 'id';
136
137         this.translatableFields =
138             this.idlClassDef.fields.filter(f => f.i18n).map(f => f.name);
139
140         if (!this.persistKey) {
141             this.persistKey =
142                 'admin.' +
143                 (this.persistKeyPfx ? this.persistKeyPfx + '.' : '') +
144                 this.idlClassDef.table;
145         }
146
147         // gridFilters are a JSON encoded string
148         const filters = this.route.snapshot.queryParamMap.get('gridFilters');
149         if (filters) {
150             try {
151                 this.gridFilters = JSON.parse(filters);
152             } catch (E) {
153                 console.error('Invalid grid filters provided: ', filters);
154             }
155         }
156
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;
162         }
163
164         const contextOrg = this.route.snapshot.queryParamMap.get('contextOrg');
165         this.checkCreatePerms();
166         this.applyOrgValues(Number(contextOrg));
167
168         // If the caller provides not data source, create a generic one.
169         if (!this.dataSource) {
170             this.initDataSource();
171         }
172
173         // TODO: pass the row activate handler via the grid markup
174         this.grid.onRowActivate.subscribe(
175             (idlThing: IdlObject) => this.showEditDialog(idlThing)
176         );
177     }
178
179     checkCreatePerms() {
180         this.canCreate = false;
181         const pc = this.idlClassDef.permacrud || {};
182         const perms = pc.create ? pc.create.perms : [];
183         if (perms.length === 0) { return; }
184
185         this.perm.hasWorkPermAt(perms, true).then(permMap => {
186             Object.keys(permMap).forEach(key => {
187                 if (permMap[key].length > 0) {
188                     this.canCreate = true;
189                 }
190             });
191         });
192     }
193
194     initDataSource() {
195         this.dataSource = new GridDataSource();
196
197         this.dataSource.getRows = (pager: Pager, sort: any[]) => {
198             const orderBy: any = {};
199
200             if (sort.length) {
201                 // Sort specified from grid
202                 orderBy[this.idlClass] = sort[0].name + ' ' + sort[0].dir;
203
204             } else if (this.sortField) {
205                 // Default sort field
206                 orderBy[this.idlClass] = this.sortField;
207             }
208
209             const searchOps = {
210                 offset: pager.offset,
211                 limit: pager.limit,
212                 order_by: orderBy
213             };
214
215             if (!this.contextOrg && !this.gridFilters) {
216                 // No org filter -- fetch all rows
217                 return this.pcrud.retrieveAll(
218                     this.idlClass, searchOps, {fleshSelectors: true});
219             }
220
221             const search: any = {};
222
223             search[this.orgField] = this.searchOrgs.orgIds || [this.contextOrg.id()];
224
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];
229                 });
230             }
231
232             return this.pcrud.search(
233                 this.idlClass, search, searchOps, {fleshSelectors: true});
234         };
235     }
236
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(
242                 result => {
243                     this.successString.current()
244                         .then(str => this.toast.success(str));
245                     this.grid.reload();
246                     resolve(result);
247                 },
248                 error => {
249                     this.updateFailedString.current()
250                         .then(str => this.toast.danger(str));
251                     reject(error);
252                 }
253             );
254         });
255     }
256
257     editSelected(idlThings: IdlObject[]) {
258
259         // Edit each IDL thing one at a time
260         const editOneThing = (thing: IdlObject) => {
261             if (!thing) { return; }
262
263             this.showEditDialog(thing).then(
264                 () => editOneThing(idlThings.shift()));
265         };
266
267         editOneThing(idlThings.shift());
268     }
269
270     deleteSelected(idlThings: IdlObject[]) {
271         idlThings.forEach(idlThing => idlThing.isdeleted(true));
272         this.pcrud.autoApply(idlThings).subscribe(
273             val => console.debug('deleted: ' + val),
274             err => {},
275             ()  => this.grid.reload()
276         );
277     }
278
279     createNew() {
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(
286             ok => {
287                 this.createString.current()
288                     .then(str => this.toast.success(str));
289                 this.grid.reload();
290             },
291             rejection => {
292                 if (!rejection.dismissed) {
293                     this.createErrString.current()
294                         .then(str => this.toast.danger(str));
295                 }
296             }
297         );
298     }
299     // Open the field translation dialog.
300     // Link the next/previous actions to cycle through each translatable
301     // field on each row.
302     translate() {
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];
307
308         this.translator.nextString = () => {
309
310             if (this.translateFieldIdx < this.translatableFields.length - 1) {
311                 this.translateFieldIdx++;
312
313             } else if (this.translateRowIdx < this.dataSource.data.length - 1) {
314                 this.translateRowIdx++;
315                 this.translateFieldIdx = 0;
316             }
317
318             this.translator.idlObject =
319                 this.dataSource.data[this.translateRowIdx];
320             this.translator.fieldName =
321                 this.translatableFields[this.translateFieldIdx];
322         };
323
324         this.translator.prevString = () => {
325
326             if (this.translateFieldIdx > 0) {
327                 this.translateFieldIdx--;
328
329             } else if (this.translateRowIdx > 0) {
330                 this.translateRowIdx--;
331                 this.translateFieldIdx = 0;
332             }
333
334             this.translator.idlObject =
335                 this.dataSource.data[this.translateRowIdx];
336             this.translator.fieldName =
337                 this.translatableFields[this.translateFieldIdx];
338         };
339
340         this.translator.open({size: 'lg'});
341     }
342 }
343
344