]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/eg2/src/app/staff/share/admin-page/admin-page.component.ts
cfb01e5fa31cb9405085c44eb89addb75f9123c0
[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 {IdlService, IdlObject} from '@eg/core/idl.service';
3 import {GridDataSource} from '@eg/share/grid/grid';
4 import {GridComponent} from '@eg/share/grid/grid.component';
5 import {TranslateComponent} from '@eg/staff/share/translate/translate.component';
6 import {ToastService} from '@eg/share/toast/toast.service';
7 import {Pager} from '@eg/share/util/pager';
8 import {PcrudService} from '@eg/core/pcrud.service';
9 import {OrgService} from '@eg/core/org.service';
10 import {PermService} from '@eg/core/perm.service';
11 import {AuthService} from '@eg/core/auth.service';
12 import {FmRecordEditorComponent} from '@eg/share/fm-editor/fm-editor.component';
13 import {StringComponent} from '@eg/share/string/string.component';
14
15 /**
16  * General purpose CRUD interface for IDL objects
17  *
18  * Object types using this component must be editable via PCRUD.
19  */
20
21 @Component({
22     selector: 'eg-admin-page',
23     templateUrl: './admin-page.component.html'
24 })
25
26 export class AdminPageComponent implements OnInit {
27
28     @Input() idlClass: string;
29
30     // Default sort field, used when no grid sorting is applied.
31     @Input() sortField: string;
32
33     // Data source may be provided by the caller.  This gives the caller
34     // complete control over the contents of the grid.  If no data source
35     // is provided, a generic one is create which is sufficient for data
36     // that requires no special handling, filtering, etc.
37     @Input() dataSource: GridDataSource;
38
39     // Size of create/edito dialog.  Uses large by default.
40     @Input() dialogSize: 'sm' | 'lg' = 'lg';
41
42     // If an org unit field is specified, an org unit filter
43     // is added to the top of the page.
44     @Input() orgField: string;
45
46     // Disable the auto-matic org unit field filter
47     @Input() disableOrgFilter: boolean;
48
49     // Include objects linking to org units which are ancestors
50     // of the selected org unit.
51     @Input() includeOrgAncestors: boolean;
52
53     // Ditto includeOrgAncestors, but descendants.
54     @Input() includeOrgDescendants: boolean;
55
56     // Optional grid persist key.  This is the part of the key
57     // following eg.grid.
58     @Input() persistKey: string;
59
60     // Optional path component to add to the generated grid persist key,
61     // formatted as (for example):
62     // 'eg.grid.admin.${persistKeyPfx}.config.billing_type'
63     @Input() persistKeyPfx: string;
64
65     // Optional comma-separated list of read-only fields
66     @Input() readonlyFields: string;
67
68     @ViewChild('grid') grid: GridComponent;
69     @ViewChild('editDialog') editDialog: FmRecordEditorComponent;
70     @ViewChild('successString') successString: StringComponent;
71     @ViewChild('createString') createString: StringComponent;
72     @ViewChild('createErrString') createErrString: StringComponent;
73     @ViewChild('updateFailedString') updateFailedString: StringComponent;
74     @ViewChild('translator') translator: TranslateComponent;
75
76     idlClassDef: any;
77     pkeyField: string;
78     createNew: () => void;
79     deleteSelected: (rows: IdlObject[]) => void;
80     editSelected: (rows: IdlObject[]) => void;
81
82     // True if any columns on the object support translations
83     translateRowIdx: number;
84     translateFieldIdx: number;
85     translatableFields: string[];
86     translate: () => void;
87
88     contextOrg: IdlObject;
89     orgFieldLabel: string;
90     viewPerms: string;
91     canCreate: boolean;
92
93     constructor(
94         private idl: IdlService,
95         private org: OrgService,
96         private auth: AuthService,
97         private pcrud: PcrudService,
98         private perm: PermService,
99         private toast: ToastService
100     ) {
101         this.translatableFields = [];
102     }
103
104     applyOrgValues() {
105
106         if (this.disableOrgFilter) {
107             this.orgField = null;
108             return;
109         }
110
111         if (!this.orgField) {
112             // If no org unit field is specified, try to find one.
113             // If an object type has multiple org unit fields, the
114             // caller should specify one or disable org unit filter.
115             this.idlClassDef.fields.forEach(field => {
116                 if (field['class'] === 'aou') {
117                     this.orgField = field.name;
118                 }
119             });
120         }
121
122         if (this.orgField) {
123             this.orgFieldLabel = this.idlClassDef.field_map[this.orgField].label;
124             this.contextOrg = this.org.root();
125         }
126     }
127
128     ngOnInit() {
129         this.idlClassDef = this.idl.classes[this.idlClass];
130         this.pkeyField = this.idlClassDef.pkey || 'id';
131
132         this.translatableFields =
133             this.idlClassDef.fields.filter(f => f.i18n).map(f => f.name);
134
135         if (!this.persistKey) {
136             this.persistKey =
137                 'admin.' +
138                 (this.persistKeyPfx ? this.persistKeyPfx + '.' : '') +
139                 this.idlClassDef.table;
140         }
141
142         // Limit the view org selector to orgs where the user has
143         // permacrud-encoded view permissions.
144         const pc = this.idlClassDef.permacrud;
145         if (pc && pc.retrieve) {
146             this.viewPerms = pc.retrieve.perms;
147         }
148
149         this.checkCreatePerms();
150         this.applyOrgValues();
151
152         // If the caller provides not data source, create a generic one.
153         if (!this.dataSource) {
154             this.initDataSource();
155         }
156
157         // TODO: pass the row activate handler via the grid markup
158         this.grid.onRowActivate.subscribe(
159             (idlThing: IdlObject) => this.showEditDialog(idlThing)
160         );
161
162         this.editSelected = (idlThings: IdlObject[]) => {
163
164             // Edit each IDL thing one at a time
165             const editOneThing = (thing: IdlObject) => {
166                 if (!thing) { return; }
167
168                 this.showEditDialog(thing).then(
169                     () => editOneThing(idlThings.shift()));
170             };
171
172             editOneThing(idlThings.shift());
173         };
174
175         this.createNew = () => {
176             this.editDialog.mode = 'create';
177             this.editDialog.open({size: this.dialogSize}).then(
178                 ok => {
179                     this.createString.current()
180                         .then(str => this.toast.success(str));
181                     this.grid.reload();
182                 },
183                 err => {
184                     this.createErrString.current()
185                         .then(str => this.toast.danger(str));
186                 }
187             );
188         };
189
190         this.deleteSelected = (idlThings: IdlObject[]) => {
191             idlThings.forEach(idlThing => idlThing.isdeleted(true));
192             this.pcrud.autoApply(idlThings).subscribe(
193                 val => console.debug('deleted: ' + val),
194                 err => {},
195                 ()  => this.grid.reload()
196             );
197         };
198
199         // Open the field translation dialog.
200         // Link the next/previous actions to cycle through each translatable
201         // field on each row.
202         this.translate = () => {
203             this.translateRowIdx = 0;
204             this.translateFieldIdx = 0;
205             this.translator.fieldName = this.translatableFields[this.translateFieldIdx];
206             this.translator.idlObject = this.dataSource.data[this.translateRowIdx];
207
208             this.translator.nextString = () => {
209
210                 if (this.translateFieldIdx < this.translatableFields.length - 1) {
211                     this.translateFieldIdx++;
212
213                 } else if (this.translateRowIdx < this.dataSource.data.length - 1) {
214                     this.translateRowIdx++;
215                     this.translateFieldIdx = 0;
216                 }
217
218                 this.translator.idlObject =
219                     this.dataSource.data[this.translateRowIdx];
220                 this.translator.fieldName =
221                     this.translatableFields[this.translateFieldIdx];
222             };
223
224             this.translator.prevString = () => {
225
226                 if (this.translateFieldIdx > 0) {
227                     this.translateFieldIdx--;
228
229                 } else if (this.translateRowIdx > 0) {
230                     this.translateRowIdx--;
231                     this.translateFieldIdx = 0;
232                 }
233
234                 this.translator.idlObject =
235                     this.dataSource.data[this.translateRowIdx];
236                 this.translator.fieldName =
237                     this.translatableFields[this.translateFieldIdx];
238             };
239
240             this.translator.open({size: 'lg'});
241         };
242     }
243
244     checkCreatePerms() {
245         this.canCreate = false;
246         const pc = this.idlClassDef.permacrud || {};
247         const perms = pc.create ? pc.create.perms : [];
248         if (perms.length === 0) { return; }
249
250         this.perm.hasWorkPermAt(perms, true).then(permMap => {
251             Object.keys(permMap).forEach(key => {
252                 if (permMap[key].length > 0) {
253                     this.canCreate = true;
254                 }
255             });
256         });
257     }
258
259     orgOnChange(org: IdlObject) {
260         this.contextOrg = org;
261         this.grid.reload();
262     }
263
264     initDataSource() {
265         this.dataSource = new GridDataSource();
266
267         this.dataSource.getRows = (pager: Pager, sort: any[]) => {
268             const orderBy: any = {};
269
270             if (sort.length) {
271                 // Sort specified from grid
272                 orderBy[this.idlClass] = sort[0].name + ' ' + sort[0].dir;
273
274             } else if (this.sortField) {
275                 // Default sort field
276                 orderBy[this.idlClass] = this.sortField;
277             }
278
279             const searchOps = {
280                 offset: pager.offset,
281                 limit: pager.limit,
282                 order_by: orderBy
283             };
284
285             if (this.contextOrg) {
286                 // Filter rows by those linking to the context org and
287                 // optionally ancestor and descendant org units.
288
289                 let orgs = [this.contextOrg.id()];
290
291                 if (this.includeOrgAncestors) {
292                     orgs = this.org.ancestors(this.contextOrg, true);
293                 }
294
295                 if (this.includeOrgDescendants) {
296                     // can result in duplicate workstation org IDs... meh
297                     orgs = orgs.concat(
298                         this.org.descendants(this.contextOrg, true));
299                 }
300
301                 const search = {};
302                 search[this.orgField] = orgs;
303                 return this.pcrud.search(this.idlClass, search, searchOps);
304             }
305
306             // No org filter -- fetch all rows
307             return this.pcrud.retrieveAll(this.idlClass, searchOps);
308         };
309     }
310
311     disableAncestorSelector(): boolean {
312         return this.contextOrg &&
313             this.contextOrg.id() === this.org.root().id();
314     }
315
316     disableDescendantSelector(): boolean {
317         return this.contextOrg && this.contextOrg.children().length === 0;
318     }
319
320     showEditDialog(idlThing: IdlObject) {
321         this.editDialog.mode = 'update';
322         this.editDialog.recId = idlThing[this.pkeyField]();
323         return this.editDialog.open({size: this.dialogSize}).then(
324             ok => {
325                 this.successString.current()
326                     .then(str => this.toast.success(str));
327                 this.grid.reload();
328             },
329             err => {
330                 this.updateFailedString.current()
331                     .then(str => this.toast.danger(str));
332             }
333         );
334     }
335
336 }
337
338