]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/eg2/src/app/share/fm-editor/fm-editor.component.ts
LP1811288 Admin grids preload combobox values
[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 {Observable} from 'rxjs';
5 import {map} from 'rxjs/operators';
6 import {AuthService} from '@eg/core/auth.service';
7 import {PcrudService} from '@eg/core/pcrud.service';
8 import {DialogComponent} from '@eg/share/dialog/dialog.component';
9 import {NgbModal, NgbModalOptions} from '@ng-bootstrap/ng-bootstrap';
10 import {ComboboxEntry} from '@eg/share/combobox/combobox.component';
11
12 interface CustomFieldTemplate {
13     template: TemplateRef<any>;
14
15     // Allow the caller to pass in a free-form context blob to
16     // be addedto the caller's custom template context, along
17     // with our stock context.
18     context?: {[fields: string]: any};
19 }
20
21 interface CustomFieldContext {
22     // Current create/edit/view record
23     record: IdlObject;
24
25     // IDL field definition blob
26     field: any;
27
28     // additional context values passed via CustomFieldTemplate
29     [fields: string]: any;
30 }
31
32 // Collection of extra options that may be applied to fields
33 // for controling non-default behaviour.
34 export interface FmFieldOptions {
35
36     // Render the field as a combobox using these values, regardless
37     // of the field's datatype.
38     customValues?: {[field: string]: ComboboxEntry[]};
39
40     // Provide / override the "selector" value for the linked class.
41     // This is the field the combobox will search for typeahead.  If no
42     // field is defined, the "selector" field is used.  If no "selector"
43     // field exists, the combobox will pre-load all linked values so
44     // the user can click to navigate.
45     linkedSearchField?: string;
46
47     // When true for combobox fields, pre-fetch the combobox data
48     // so the user can click or type to find values.
49     preloadLinkedValues?: boolean;
50
51     // Directly override the required state of the field.
52     // This only has an affect if the value is true.
53     isRequired?: boolean;
54
55     // If this function is defined, the function will be called
56     // at render time to see if the field should be marked are required.
57     // This supersedes all other isRequired specifiers.
58     isRequiredOverride?: (field: string, record: IdlObject) => boolean;
59
60     // Directly apply the readonly status of the field.
61     // This only has an affect if the value is true.
62     isReadonly?: boolean;
63
64     // Render the field using this custom template instead of chosing
65     // from the default set of form inputs.
66     customTemplate?: CustomFieldTemplate;
67 }
68
69 @Component({
70   selector: 'eg-fm-record-editor',
71   templateUrl: './fm-editor.component.html',
72   /* align checkboxes when not using class="form-check" */
73   styles: ['input[type="checkbox"] {margin-left: 0px;}']
74 })
75 export class FmRecordEditorComponent
76     extends DialogComponent implements OnInit {
77
78     // IDL class hint (e.g. "aou")
79     @Input() idlClass: string;
80
81     // mode: 'create' for creating a new record,
82     //       'update' for editing an existing record
83     //       'view' for viewing an existing record without editing
84     mode: 'create' | 'update' | 'view' = 'create';
85     recId: any;
86
87     // IDL record we are editing
88     // TODO: allow this to be update in real time by the caller?
89     record: IdlObject;
90
91     // Permissions extracted from the permacrud defs in the IDL
92     // for the current IDL class
93     modePerms: {[mode: string]: string};
94
95     // Collection of FmFieldOptions for specifying non-default
96     // behaviour for each field (by field name).
97     @Input() fieldOptions: {[fieldName: string]: FmFieldOptions} = {};
98
99     // list of fields that should not be displayed
100     @Input() hiddenFieldsList: string[] = [];
101     @Input() hiddenFields: string; // comma-separated string version
102
103     // list of fields that should always be read-only
104     @Input() readonlyFieldsList: string[] = [];
105     @Input() readonlyFields: string; // comma-separated string version
106
107     // list of required fields; this supplements what the IDL considers
108     // required
109     @Input() requiredFieldsList: string[] = [];
110     @Input() requiredFields: string; // comma-separated string version
111
112     // list of org_unit fields where a default value may be applied by
113     // the org-select if no value is present.
114     @Input() orgDefaultAllowedList: string[] = [];
115     @Input() orgDefaultAllowed: string; // comma-separated string version
116
117     // IDL record display label.  Defaults to the IDL label.
118     @Input() recordLabel: string;
119
120     // When true at the component level, pre-fetch the combobox data
121     // for all combobox fields.  See also FmFieldOptions.
122     @Input() preloadLinkedValues: boolean;
123
124     // Emit the modified object when the save action completes.
125     @Output() onSave$ = new EventEmitter<IdlObject>();
126
127     // Emit the original object when the save action is canceled.
128     @Output() onCancel$ = new EventEmitter<IdlObject>();
129
130     // Emit an error message when the save action fails.
131     @Output() onError$ = new EventEmitter<string>();
132
133     // IDL info for the the selected IDL class
134     idlDef: any;
135
136     // Can we edit the primary key?
137     pkeyIsEditable = false;
138
139     // List of IDL field definitions.  This is a subset of the full
140     // list of fields on the IDL, since some are hidden, virtual, etc.
141     fields: any[];
142
143     // DOM id prefix to prevent id collisions.
144     idPrefix: string;
145
146     @Input() editMode(mode: 'create' | 'update' | 'view') {
147         this.mode = mode;
148     }
149
150     // Record ID to view/update.  Value is dynamic.  Records are not
151     // fetched until .open() is called.
152     @Input() set recordId(id: any) {
153         if (id) { this.recId = id; }
154     }
155
156     constructor(
157       private modal: NgbModal, // required for passing to parent
158       private idl: IdlService,
159       private auth: AuthService,
160       private pcrud: PcrudService) {
161       super(modal);
162     }
163
164     // Avoid fetching data on init since that may lead to unnecessary
165     // data retrieval.
166     ngOnInit() {
167         this.listifyInputs();
168         this.idlDef = this.idl.classes[this.idlClass];
169         this.recordLabel = this.idlDef.label;
170
171         // Add some randomness to the generated DOM IDs to ensure against clobbering
172         this.idPrefix = 'fm-editor-' + Math.floor(Math.random() * 100000);
173     }
174
175     // Opening dialog, fetch data.
176     open(options?: NgbModalOptions): Promise<any> {
177         return this.initRecord().then(
178             ok => super.open(options),
179             err => console.warn(`Error fetching FM data: ${err}`)
180         );
181     }
182
183     // Translate comma-separated string versions of various inputs
184     // to arrays.
185     private listifyInputs() {
186         if (this.hiddenFields) {
187             this.hiddenFieldsList = this.hiddenFields.split(/,/);
188         }
189         if (this.readonlyFields) {
190             this.readonlyFieldsList = this.readonlyFields.split(/,/);
191         }
192         if (this.requiredFields) {
193             this.requiredFieldsList = this.requiredFields.split(/,/);
194         }
195         if (this.orgDefaultAllowed) {
196             this.orgDefaultAllowedList = this.orgDefaultAllowed.split(/,/);
197         }
198     }
199
200     private initRecord(): Promise<any> {
201
202         const pc = this.idlDef.permacrud || {};
203         this.modePerms = {
204             view:   pc.retrieve ? pc.retrieve.perms : [],
205             create: pc.create ? pc.create.perms : [],
206             update: pc.update ? pc.update.perms : [],
207         };
208
209         if (this.mode === 'update' || this.mode === 'view') {
210             return this.pcrud.retrieve(this.idlClass, this.recId)
211             .toPromise().then(rec => {
212
213                 if (!rec) {
214                     return Promise.reject(`No '${this.idlClass}'
215                         record found with id ${this.recId}`);
216                 }
217
218                 this.record = rec;
219                 this.convertDatatypesToJs();
220                 return this.getFieldList();
221             });
222         }
223
224         // create a new record from scratch or from a stub record
225         // provided by the caller.
226         this.pkeyIsEditable = !('pkey_sequence' in this.idlDef);
227         if (!this.record) {
228             this.record = this.idl.create(this.idlClass);
229         }
230         return this.getFieldList();
231     }
232
233     // Modifies the FM record in place, replacing IDL-compatible values
234     // with native JS values.
235     private convertDatatypesToJs() {
236         this.idlDef.fields.forEach(field => {
237             if (field.datatype === 'bool') {
238                 if (this.record[field.name]() === 't') {
239                     this.record[field.name](true);
240                 } else if (this.record[field.name]() === 'f') {
241                     this.record[field.name](false);
242                 }
243             }
244         });
245     }
246
247     // Modifies the provided FM record in place, replacing JS values
248     // with IDL-compatible values.
249     convertDatatypesToIdl(rec: IdlObject) {
250         const fields = this.idlDef.fields;
251         fields.forEach(field => {
252             if (field.datatype === 'bool') {
253                 if (rec[field.name]() === true) {
254                     rec[field.name]('t');
255                 // } else if (rec[field.name]() === false) {
256                 } else { // TODO: some bools can be NULL
257                     rec[field.name]('f');
258                 }
259             } else if (field.datatype === 'org_unit') {
260                 const org = rec[field.name]();
261                 if (org && typeof org === 'object') {
262                     rec[field.name](org.id());
263                 }
264             }
265         });
266     }
267
268     // Returns the name of the field on a class (typically via a linked
269     // field) that acts as the selector value for display / search.
270     getClassSelector(class_: string): string {
271         if (class_) {
272             const linkedClass = this.idl.classes[class_];
273             return linkedClass.pkey ?
274                 linkedClass.field_map[linkedClass.pkey].selector : null;
275         }
276         return null;
277     }
278
279     private flattenLinkedValues(field: any, list: IdlObject[]): ComboboxEntry[] {
280         const class_ = field.class;
281         const fieldOptions = this.fieldOptions[field.name] || {};
282         const idField = this.idl.classes[class_].pkey;
283
284         const selector = fieldOptions.linkedSearchField
285             || this.getClassSelector(class_) || idField;
286
287         return list.map(item => {
288             return {id: item[idField](), label: item[selector]()};
289         });
290     }
291
292     private getFieldList(): Promise<any> {
293
294         this.fields = this.idlDef.fields.filter(f =>
295             !f.virtual && !this.hiddenFieldsList.includes(f.name)
296         );
297
298         // Wait for all network calls to complete
299         return Promise.all(
300             this.fields.map(field => this.constructOneField(field)));
301     }
302
303     private constructOneField(field: any): Promise<any> {
304
305         let promise = null;
306         const fieldOptions = this.fieldOptions[field.name] || {};
307
308         field.readOnly = this.mode === 'view'
309             || fieldOptions.isReadonly === true
310             || this.readonlyFieldsList.includes(field.name);
311
312         if (fieldOptions.isRequiredOverride) {
313             field.isRequired = () => {
314                 return fieldOptions.isRequiredOverride(field.name, this.record);
315             };
316         } else {
317             field.isRequired = () => {
318                 return field.required
319                     || fieldOptions.isRequired
320                     || this.requiredFieldsList.includes(field.name);
321             };
322         }
323
324         if (fieldOptions.customValues) {
325
326             field.linkedValues = fieldOptions.customValues;
327
328         } else if (field.datatype === 'link' && field.readOnly) {
329
330             // no need to fetch all possible values for read-only fields
331             const idToFetch = this.record[field.name]();
332
333             if (idToFetch) {
334
335                 // If the linked class defines a selector field, fetch the
336                 // linked data so we can display the data within the selector
337                 // field.  Otherwise, avoid the network lookup and let the
338                 // bare value (usually an ID) be displayed.
339                 const selector = fieldOptions.linkedSearchField ||
340                     this.getClassSelector(field.class);
341
342                 if (selector && selector !== field.name) {
343                     promise = this.pcrud.retrieve(field.class, idToFetch)
344                         .toPromise().then(list => {
345                             field.linkedValues =
346                                 this.flattenLinkedValues(field, Array(list));
347                         });
348                 } else {
349                     // No selector, display the raw id/key value.
350                     field.linkedValues = [{id: idToFetch, name: idToFetch}];
351                 }
352             }
353
354         } else if (field.datatype === 'link') {
355
356             promise = this.wireUpCombobox(field);
357
358         } else if (field.datatype === 'org_unit') {
359             field.orgDefaultAllowed =
360                 this.orgDefaultAllowedList.includes(field.name);
361         }
362
363         if (fieldOptions.customTemplate) {
364             field.template = fieldOptions.customTemplate.template;
365             field.context = fieldOptions.customTemplate.context;
366         }
367
368         return promise || Promise.resolve();
369     }
370
371     wireUpCombobox(field: any): Promise<any> {
372
373         const fieldOptions = this.fieldOptions[field.name] || {};
374
375         // globally preloading unless a field-specific value is set.
376         if (this.preloadLinkedValues) {
377             if (!('preloadLinkedValues' in fieldOptions)) {
378                 fieldOptions.preloadLinkedValues = true;
379             }
380         }
381
382         const selector = fieldOptions.linkedSearchField ||
383             this.getClassSelector(field.class);
384
385         if (!selector && !fieldOptions.preloadLinkedValues) {
386             // User probably expects an async data source, but we can't
387             // provide one without a selector.  Warn the user.
388             console.warn(`Class ${field.class} has no selector.
389                 Pre-fetching all rows for combobox`);
390         }
391
392         if (fieldOptions.preloadLinkedValues || !selector) {
393             return this.pcrud.retrieveAll(field.class, {}, {atomic : true})
394             .toPromise().then(list => {
395                 field.linkedValues =
396                     this.flattenLinkedValues(field, list);
397             });
398         }
399
400         // If we have a selector, wire up for async data retrieval
401         field.linkedValuesSource =
402             (term: string): Observable<ComboboxEntry> => {
403
404             const search = {};
405             const orderBy = {order_by: {}};
406             const idField = this.idl.classes[field.class].pkey || 'id';
407
408             search[selector] = {'ilike': `%${term}%`};
409             orderBy.order_by[field.class] = selector;
410
411             return this.pcrud.search(field.class, search, orderBy)
412             .pipe(map(idlThing =>
413                 // Map each object into a ComboboxEntry upon arrival
414                 this.flattenLinkedValues(field, [idlThing])[0]
415             ));
416         };
417
418         // Using an async data source, but a value is already set
419         // on the field.  Fetch the linked object and add it to the
420         // combobox entry list so it will be avilable for display
421         // at dialog load time.
422         const linkVal = this.record[field.name]();
423         if (linkVal !== null && linkVal !== undefined) {
424             return this.pcrud.retrieve(field.class, linkVal).toPromise()
425             .then(idlThing => {
426                 field.linkedValues =
427                     this.flattenLinkedValues(field, Array(idlThing));
428             });
429         }
430
431         // No linked value applied, nothing to pre-fetch.
432         return Promise.resolve();
433     }
434
435     // Returns a context object to be inserted into a custom
436     // field template.
437     customTemplateFieldContext(fieldDef: any): CustomFieldContext {
438         return Object.assign(
439             {   record : this.record,
440                 field: fieldDef // from this.fields
441             },  fieldDef.context || {}
442         );
443     }
444
445     save() {
446         const recToSave = this.idl.clone(this.record);
447         this.convertDatatypesToIdl(recToSave);
448         this.pcrud[this.mode]([recToSave]).toPromise().then(
449             result => this.close(result),
450             error  => this.dismiss(error)
451         );
452     }
453
454     cancel() {
455         this.dismiss('canceled');
456     }
457
458     // Returns a string describing the type of input to display
459     // for a given field.  This helps cut down on the if/else
460     // nesti-ness in the template.  Each field will match
461     // exactly one type.
462     inputType(field: any): string {
463
464         if (field.template) {
465             return 'template';
466         }
467
468         // Some widgets handle readOnly for us.
469         if (   field.datatype === 'timestamp'
470             || field.datatype === 'org_unit'
471             || field.datatype === 'bool') {
472             return field.datatype;
473         }
474
475         if (field.readOnly) {
476             if (field.datatype === 'money') {
477                 return 'readonly-money';
478             }
479
480             if (field.datatype === 'link' || field.linkedValues) {
481                 return 'readonly-list';
482             }
483
484             return 'readonly';
485         }
486
487         if (field.datatype === 'id' && !this.pkeyIsEditable) {
488             return 'readonly';
489         }
490
491         if (   field.datatype === 'int'
492             || field.datatype === 'float'
493             || field.datatype === 'money') {
494             return field.datatype;
495         }
496
497         if (field.datatype === 'link' || field.linkedValues) {
498             return 'list';
499         }
500
501         // datatype == text / interval / editable-pkey
502         return 'text';
503     }
504 }
505
506