]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/eg2/src/app/staff/share/admin-page/admin-page.component.ts
80fd2fdf6c89db622bccffb454aa11ab9d78aa83
[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('translator') translator: TranslateComponent;
73
74     idlClassDef: any;
75     pkeyField: string;
76     createNew: () => void;
77     deleteSelected: (rows: IdlObject[]) => void;
78
79     // True if any columns on the object support translations
80     translateRowIdx: number;
81     translateFieldIdx: number;
82     translatableFields: string[];
83     translate: () => void;
84
85     contextOrg: IdlObject;
86     orgFieldLabel: string;
87     viewPerms: string;
88     canCreate: boolean;
89
90     constructor(
91         private idl: IdlService,
92         private org: OrgService,
93         private auth: AuthService,
94         private pcrud: PcrudService,
95         private perm: PermService,
96         private toast: ToastService
97     ) {
98         this.translatableFields = [];
99     }
100
101     applyOrgValues() {
102
103         if (this.disableOrgFilter) {
104             this.orgField = null;
105             return;
106         }
107
108         if (!this.orgField) {
109             // If no org unit field is specified, try to find one.
110             // If an object type has multiple org unit fields, the
111             // caller should specify one or disable org unit filter.
112             this.idlClassDef.fields.forEach(field => {
113                 if (field['class'] === 'aou') {
114                     this.orgField = field.name;
115                 }
116             });
117         }
118
119         if (this.orgField) {
120             this.orgFieldLabel = this.idlClassDef.field_map[this.orgField].label;
121             this.contextOrg = this.org.root();
122         }
123     }
124
125     ngOnInit() {
126         this.idlClassDef = this.idl.classes[this.idlClass];
127         this.pkeyField = this.idlClassDef.pkey || 'id';
128
129         this.translatableFields =
130             this.idlClassDef.fields.filter(f => f.i18n).map(f => f.name);
131
132         if (!this.persistKey) {
133             this.persistKey =
134                 'admin.' +
135                 (this.persistKeyPfx ? this.persistKeyPfx + '.' : '') +
136                 this.idlClassDef.table;
137         }
138
139         // Limit the view org selector to orgs where the user has
140         // permacrud-encoded view permissions.
141         const pc = this.idlClassDef.permacrud;
142         if (pc && pc.retrieve) {
143             this.viewPerms = pc.retrieve.perms;
144         }
145
146         this.checkCreatePerms();
147         this.applyOrgValues();
148
149         // If the caller provides not data source, create a generic one.
150         if (!this.dataSource) {
151             this.initDataSource();
152         }
153
154         // TODO: pass the row activate handler via the grid markup
155         this.grid.onRowActivate.subscribe(
156             (idlThing: IdlObject) => {
157                 this.editDialog.mode = 'update';
158                 this.editDialog.recId = idlThing[this.pkeyField]();
159                 this.editDialog.open({size: this.dialogSize}).then(
160                     ok => {
161                         this.successString.current()
162                             .then(str => this.toast.success(str));
163                         this.grid.reload();
164                     },
165                     err => {}
166                 );
167             }
168         );
169
170         this.createNew = () => {
171             this.editDialog.mode = 'create';
172             this.editDialog.open({size: this.dialogSize}).then(
173                 ok => {
174                     this.createString.current()
175                         .then(str => this.toast.success(str));
176                     this.grid.reload();
177                 },
178                 err => {}
179             );
180         };
181
182         this.deleteSelected = (idlThings: IdlObject[]) => {
183             idlThings.forEach(idlThing => idlThing.isdeleted(true));
184             this.pcrud.autoApply(idlThings).subscribe(
185                 val => console.debug('deleted: ' + val),
186                 err => {},
187                 ()  => this.grid.reload()
188             );
189         };
190
191         // Open the field translation dialog.
192         // Link the next/previous actions to cycle through each translatable
193         // field on each row.
194         this.translate = () => {
195             this.translateRowIdx = 0;
196             this.translateFieldIdx = 0;
197             this.translator.fieldName = this.translatableFields[this.translateFieldIdx];
198             this.translator.idlObject = this.dataSource.data[this.translateRowIdx];
199
200             this.translator.nextString = () => {
201
202                 if (this.translateFieldIdx < this.translatableFields.length - 1) {
203                     this.translateFieldIdx++;
204
205                 } else if (this.translateRowIdx < this.dataSource.data.length - 1) {
206                     this.translateRowIdx++;
207                     this.translateFieldIdx = 0;
208                 }
209
210                 this.translator.idlObject =
211                     this.dataSource.data[this.translateRowIdx];
212                 this.translator.fieldName =
213                     this.translatableFields[this.translateFieldIdx];
214             };
215
216             this.translator.prevString = () => {
217
218                 if (this.translateFieldIdx > 0) {
219                     this.translateFieldIdx--;
220
221                 } else if (this.translateRowIdx > 0) {
222                     this.translateRowIdx--;
223                     this.translateFieldIdx = 0;
224                 }
225
226                 this.translator.idlObject =
227                     this.dataSource.data[this.translateRowIdx];
228                 this.translator.fieldName =
229                     this.translatableFields[this.translateFieldIdx];
230             };
231
232             this.translator.open({size: 'lg'});
233         };
234     }
235
236     checkCreatePerms() {
237         this.canCreate = false;
238         const pc = this.idlClassDef.permacrud || {};
239         const perms = pc.create ? pc.create.perms : [];
240         if (perms.length === 0) { return; }
241
242         this.perm.hasWorkPermAt(perms, true).then(permMap => {
243             Object.keys(permMap).forEach(key => {
244                 if (permMap[key].length > 0) {
245                     this.canCreate = true;
246                 }
247             });
248         });
249     }
250
251     orgOnChange(org: IdlObject) {
252         this.contextOrg = org;
253         this.grid.reload();
254     }
255
256     initDataSource() {
257         this.dataSource = new GridDataSource();
258
259         this.dataSource.getRows = (pager: Pager, sort: any[]) => {
260             const orderBy: any = {};
261
262             if (sort.length) {
263                 // Sort specified from grid
264                 orderBy[this.idlClass] = sort[0].name + ' ' + sort[0].dir;
265
266             } else if (this.sortField) {
267                 // Default sort field
268                 orderBy[this.idlClass] = this.sortField;
269             }
270
271             const searchOps = {
272                 offset: pager.offset,
273                 limit: pager.limit,
274                 order_by: orderBy
275             };
276
277             if (this.contextOrg) {
278                 // Filter rows by those linking to the context org and
279                 // optionally ancestor and descendant org units.
280
281                 let orgs = [this.contextOrg.id()];
282
283                 if (this.includeOrgAncestors) {
284                     orgs = this.org.ancestors(this.contextOrg, true);
285                 }
286
287                 if (this.includeOrgDescendants) {
288                     // can result in duplicate workstation org IDs... meh
289                     orgs = orgs.concat(
290                         this.org.descendants(this.contextOrg, true));
291                 }
292
293                 const search = {};
294                 search[this.orgField] = orgs;
295                 return this.pcrud.search(this.idlClass, search, searchOps);
296             }
297
298             // No org filter -- fetch all rows
299             return this.pcrud.retrieveAll(this.idlClass, searchOps);
300         };
301     }
302
303     disableAncestorSelector(): boolean {
304         return this.contextOrg &&
305             this.contextOrg.id() === this.org.root().id();
306     }
307
308     disableDescendantSelector(): boolean {
309         return this.contextOrg && this.contextOrg.children().length === 0;
310     }
311
312 }
313
314