]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/eg2/src/app/share/fm-editor/fm-editor.component.ts
7b90a02437ccf07ec46a5d0dd2d7f008c7530dc8
[working/Evergreen.git] / Open-ILS / src / eg2 / src / app / share / fm-editor / fm-editor.component.ts
1 import {Component, OnInit, Input,
2     Output, EventEmitter, TemplateRef} from '@angular/core';
3 import {IdlService, IdlObject} from '@eg/core/idl.service';
4 import {AuthService} from '@eg/core/auth.service';
5 import {PcrudService} from '@eg/core/pcrud.service';
6 import {DialogComponent} from '@eg/share/dialog/dialog.component';
7 import {NgbModal, NgbModalOptions} from '@ng-bootstrap/ng-bootstrap';
8
9 interface CustomFieldTemplate {
10     template: TemplateRef<any>;
11
12     // Allow the caller to pass in a free-form context blob to
13     // be addedto the caller's custom template context, along
14     // with our stock context.
15     context?: {[fields: string]: any};
16 }
17
18 interface CustomFieldContext {
19     // Current create/edit/view record
20     record: IdlObject;
21
22     // IDL field definition blob
23     field: any;
24
25     // additional context values passed via CustomFieldTemplate
26     [fields: string]: any;
27 }
28
29 @Component({
30   selector: 'eg-fm-record-editor',
31   templateUrl: './fm-editor.component.html'
32 })
33 export class FmRecordEditorComponent
34     extends DialogComponent implements OnInit {
35
36     // IDL class hint (e.g. "aou")
37     @Input() idlClass: string;
38
39     // mode: 'create' for creating a new record,
40     //       'update' for editing an existing record
41     //       'view' for viewing an existing record without editing
42     mode: 'create' | 'update' | 'view' = 'create';
43     recId: any;
44     // IDL record we are editing
45     // TODO: allow this to be update in real time by the caller?
46     record: IdlObject;
47
48     // Permissions extracted from the permacrud defs in the IDL
49     // for the current IDL class
50     modePerms: {[mode: string]: string};
51
52     @Input() customFieldTemplates:
53         {[fieldName: string]: CustomFieldTemplate} = {};
54
55     // list of fields that should not be displayed
56     @Input() hiddenFieldsList: string[] = [];
57     @Input() hiddenFields: string; // comma-separated string version
58
59     // list of fields that should always be read-only
60     @Input() readonlyFieldsList: string[] = [];
61     @Input() readonlyFields: string; // comma-separated string version
62
63     // list of required fields; this supplements what the IDL considers
64     // required
65     @Input() requiredFieldsList: string[] = [];
66     @Input() requiredFields: string; // comma-separated string version
67
68     // list of org_unit fields where a default value may be applied by
69     // the org-select if no value is present.
70     @Input() orgDefaultAllowedList: string[] = [];
71     @Input() orgDefaultAllowed: string; // comma-separated string version
72
73     // hash, keyed by field name, of functions to invoke to check
74     // whether a field is required.  Each callback is passed the field
75     // name and the record and should return a boolean value. This
76     // supports cases where whether a field is required or not depends
77     // on the current value of another field.
78     @Input() isRequiredOverride:
79         {[field: string]: (field: string, record: IdlObject) => boolean};
80
81     // IDL record display label.  Defaults to the IDL label.
82     @Input() recordLabel: string;
83
84     // Emit the modified object when the save action completes.
85     @Output() onSave$ = new EventEmitter<IdlObject>();
86
87     // Emit the original object when the save action is canceled.
88     @Output() onCancel$ = new EventEmitter<IdlObject>();
89
90     // Emit an error message when the save action fails.
91     @Output() onError$ = new EventEmitter<string>();
92
93     // IDL info for the the selected IDL class
94     idlDef: any;
95
96     // Can we edit the primary key?
97     pkeyIsEditable = false;
98
99     // List of IDL field definitions.  This is a subset of the full
100     // list of fields on the IDL, since some are hidden, virtual, etc.
101     fields: any[];
102
103     @Input() editMode(mode: 'create' | 'update' | 'view') {
104         this.mode = mode;
105     }
106
107     // Record ID to view/update.  Value is dynamic.  Records are not
108     // fetched until .open() is called.
109     @Input() set recordId(id: any) {
110         if (id) { this.recId = id; }
111     }
112
113     idPrefix: string;
114
115     constructor(
116       private modal: NgbModal, // required for passing to parent
117       private idl: IdlService,
118       private auth: AuthService,
119       private pcrud: PcrudService) {
120       super(modal);
121     }
122
123     // Avoid fetching data on init since that may lead to unnecessary
124     // data retrieval.
125     ngOnInit() {
126         this.listifyInputs();
127         this.idlDef = this.idl.classes[this.idlClass];
128         this.recordLabel = this.idlDef.label;
129
130         // Add some randomness to the generated DOM IDs to ensure against clobbering
131         this.idPrefix = 'fm-editor-' + Math.floor(Math.random() * 100000);
132     }
133
134     // Opening dialog, fetch data.
135     open(options?: NgbModalOptions): Promise<any> {
136         return this.initRecord().then(
137             ok => super.open(options),
138             err => console.warn(`Error fetching FM data: ${err}`)
139         );
140     }
141
142     // Translate comma-separated string versions of various inputs
143     // to arrays.
144     private listifyInputs() {
145         if (this.hiddenFields) {
146             this.hiddenFieldsList = this.hiddenFields.split(/,/);
147         }
148         if (this.readonlyFields) {
149             this.readonlyFieldsList = this.readonlyFields.split(/,/);
150         }
151         if (this.requiredFields) {
152             this.requiredFieldsList = this.requiredFields.split(/,/);
153         }
154         if (this.orgDefaultAllowed) {
155             this.orgDefaultAllowedList = this.orgDefaultAllowed.split(/,/);
156         }
157     }
158
159     private initRecord(): Promise<any> {
160
161         const pc = this.idlDef.permacrud || {};
162         this.modePerms = {
163             view:   pc.retrieve ? pc.retrieve.perms : [],
164             create: pc.create ? pc.create.perms : [],
165             update: pc.update ? pc.update.perms : [],
166         };
167
168         if (this.mode === 'update' || this.mode === 'view') {
169             return this.pcrud.retrieve(this.idlClass, this.recId)
170             .toPromise().then(rec => {
171
172                 if (!rec) {
173                     return Promise.reject(`No '${this.idlClass}'
174                         record found with id ${this.recId}`);
175                 }
176
177                 this.record = rec;
178                 this.convertDatatypesToJs();
179                 return this.getFieldList();
180             });
181         }
182
183         // create a new record from scratch
184         this.pkeyIsEditable = !('pkey_sequence' in this.idlDef);
185         this.record = this.idl.create(this.idlClass);
186         return this.getFieldList();
187     }
188
189     // Modifies the FM record in place, replacing IDL-compatible values
190     // with native JS values.
191     private convertDatatypesToJs() {
192         this.idlDef.fields.forEach(field => {
193             if (field.datatype === 'bool') {
194                 if (this.record[field.name]() === 't') {
195                     this.record[field.name](true);
196                 } else if (this.record[field.name]() === 'f') {
197                     this.record[field.name](false);
198                 }
199             }
200         });
201     }
202
203     // Modifies the provided FM record in place, replacing JS values
204     // with IDL-compatible values.
205     convertDatatypesToIdl(rec: IdlObject) {
206         const fields = this.idlDef.fields;
207         fields.forEach(field => {
208             if (field.datatype === 'bool') {
209                 if (rec[field.name]() === true) {
210                     rec[field.name]('t');
211                 // } else if (rec[field.name]() === false) {
212                 } else { // TODO: some bools can be NULL
213                     rec[field.name]('f');
214                 }
215             } else if (field.datatype === 'org_unit') {
216                 const org = rec[field.name]();
217                 if (org && typeof org === 'object') {
218                     rec[field.name](org.id());
219                 }
220             }
221         });
222     }
223
224
225     private flattenLinkedValues(cls: string, list: IdlObject[]): any[] {
226         const idField = this.idl.classes[cls].pkey;
227         const selector =
228             this.idl.classes[cls].field_map[idField].selector || idField;
229
230         return list.map(item => {
231             return {id: item[idField](), name: item[selector]()};
232         });
233     }
234
235     private getFieldList(): Promise<any> {
236
237         this.fields = this.idlDef.fields.filter(f =>
238             !f.virtual && !this.hiddenFieldsList.includes(f.name)
239         );
240
241         const promises = [];
242
243         this.fields.forEach(field => {
244             field.readOnly = this.mode === 'view'
245                 || this.readonlyFieldsList.includes(field.name);
246
247             if (this.isRequiredOverride &&
248                 field.name in this.isRequiredOverride) {
249                 field.isRequired = () => {
250                     return this.isRequiredOverride[field.name](field.name, this.record);
251                 };
252             } else {
253                 field.isRequired = () => {
254                     return field.required ||
255                         this.requiredFieldsList.includes(field.name);
256                 };
257             }
258
259             if (field.datatype === 'link' && field.readOnly) { // no need to fetch all possible values for read-only fields
260                 let id_to_fetch = this.record[field.name]();
261                 if (id_to_fetch) {
262                     promises.push(
263                         this.pcrud.retrieve(field.class, this.record[field.name]())
264                         .toPromise().then(list => {
265                             field.linkedValues =
266                                 this.flattenLinkedValues(field.class, Array(list));
267                         })
268                     );
269                 }
270             } else if (field.datatype === 'link') {
271                 promises.push(
272                     this.pcrud.retrieveAll(field.class, {}, {atomic : true})
273                     .toPromise().then(list => {
274                         field.linkedValues =
275                             this.flattenLinkedValues(field.class, list);
276                     })
277                 );
278             } else if (field.datatype === 'org_unit') {
279                 field.orgDefaultAllowed =
280                     this.orgDefaultAllowedList.includes(field.name);
281             }
282
283             if (this.customFieldTemplates[field.name]) {
284                 field.template = this.customFieldTemplates[field.name].template;
285                 field.context = this.customFieldTemplates[field.name].context;
286             }
287
288         });
289
290         // Wait for all network calls to complete
291         return Promise.all(promises);
292     }
293
294     // Returns a context object to be inserted into a custom
295     // field template.
296     customTemplateFieldContext(fieldDef: any): CustomFieldContext {
297         return Object.assign(
298             {   record : this.record,
299                 field: fieldDef // from this.fields
300             },  fieldDef.context || {}
301         );
302     }
303
304     save() {
305         const recToSave = this.idl.clone(this.record);
306         this.convertDatatypesToIdl(recToSave);
307         this.pcrud[this.mode]([recToSave]).toPromise().then(
308             result => this.close(result),
309             error  => this.dismiss(error)
310         );
311     }
312
313     cancel() {
314         this.dismiss('canceled');
315     }
316 }
317
318