]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/eg2/src/app/share/fm-editor/fm-editor.component.ts
ec8d0b1968d0bcb92cfa01934c54679f75136626
[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     // Emit the modified object when the save action completes.
121     @Output() onSave$ = new EventEmitter<IdlObject>();
122
123     // Emit the original object when the save action is canceled.
124     @Output() onCancel$ = new EventEmitter<IdlObject>();
125
126     // Emit an error message when the save action fails.
127     @Output() onError$ = new EventEmitter<string>();
128
129     // IDL info for the the selected IDL class
130     idlDef: any;
131
132     // Can we edit the primary key?
133     pkeyIsEditable = false;
134
135     // List of IDL field definitions.  This is a subset of the full
136     // list of fields on the IDL, since some are hidden, virtual, etc.
137     fields: any[];
138
139     // DOM id prefix to prevent id collisions.
140     idPrefix: string;
141
142     @Input() editMode(mode: 'create' | 'update' | 'view') {
143         this.mode = mode;
144     }
145
146     // Record ID to view/update.  Value is dynamic.  Records are not
147     // fetched until .open() is called.
148     @Input() set recordId(id: any) {
149         if (id) { this.recId = id; }
150     }
151
152     constructor(
153       private modal: NgbModal, // required for passing to parent
154       private idl: IdlService,
155       private auth: AuthService,
156       private pcrud: PcrudService) {
157       super(modal);
158     }
159
160     // Avoid fetching data on init since that may lead to unnecessary
161     // data retrieval.
162     ngOnInit() {
163         this.listifyInputs();
164         this.idlDef = this.idl.classes[this.idlClass];
165         this.recordLabel = this.idlDef.label;
166
167         // Add some randomness to the generated DOM IDs to ensure against clobbering
168         this.idPrefix = 'fm-editor-' + Math.floor(Math.random() * 100000);
169     }
170
171     // Opening dialog, fetch data.
172     open(options?: NgbModalOptions): Promise<any> {
173         return this.initRecord().then(
174             ok => super.open(options),
175             err => console.warn(`Error fetching FM data: ${err}`)
176         );
177     }
178
179     // Translate comma-separated string versions of various inputs
180     // to arrays.
181     private listifyInputs() {
182         if (this.hiddenFields) {
183             this.hiddenFieldsList = this.hiddenFields.split(/,/);
184         }
185         if (this.readonlyFields) {
186             this.readonlyFieldsList = this.readonlyFields.split(/,/);
187         }
188         if (this.requiredFields) {
189             this.requiredFieldsList = this.requiredFields.split(/,/);
190         }
191         if (this.orgDefaultAllowed) {
192             this.orgDefaultAllowedList = this.orgDefaultAllowed.split(/,/);
193         }
194     }
195
196     private initRecord(): Promise<any> {
197
198         const pc = this.idlDef.permacrud || {};
199         this.modePerms = {
200             view:   pc.retrieve ? pc.retrieve.perms : [],
201             create: pc.create ? pc.create.perms : [],
202             update: pc.update ? pc.update.perms : [],
203         };
204
205         if (this.mode === 'update' || this.mode === 'view') {
206             return this.pcrud.retrieve(this.idlClass, this.recId)
207             .toPromise().then(rec => {
208
209                 if (!rec) {
210                     return Promise.reject(`No '${this.idlClass}'
211                         record found with id ${this.recId}`);
212                 }
213
214                 this.record = rec;
215                 this.convertDatatypesToJs();
216                 return this.getFieldList();
217             });
218         }
219
220         // create a new record from scratch or from a stub record
221         // provided by the caller.
222         this.pkeyIsEditable = !('pkey_sequence' in this.idlDef);
223         if (!this.record) {
224             this.record = this.idl.create(this.idlClass);
225         }
226         return this.getFieldList();
227     }
228
229     // Modifies the FM record in place, replacing IDL-compatible values
230     // with native JS values.
231     private convertDatatypesToJs() {
232         this.idlDef.fields.forEach(field => {
233             if (field.datatype === 'bool') {
234                 if (this.record[field.name]() === 't') {
235                     this.record[field.name](true);
236                 } else if (this.record[field.name]() === 'f') {
237                     this.record[field.name](false);
238                 }
239             }
240         });
241     }
242
243     // Modifies the provided FM record in place, replacing JS values
244     // with IDL-compatible values.
245     convertDatatypesToIdl(rec: IdlObject) {
246         const fields = this.idlDef.fields;
247         fields.forEach(field => {
248             if (field.datatype === 'bool') {
249                 if (rec[field.name]() === true) {
250                     rec[field.name]('t');
251                 // } else if (rec[field.name]() === false) {
252                 } else { // TODO: some bools can be NULL
253                     rec[field.name]('f');
254                 }
255             } else if (field.datatype === 'org_unit') {
256                 const org = rec[field.name]();
257                 if (org && typeof org === 'object') {
258                     rec[field.name](org.id());
259                 }
260             }
261         });
262     }
263
264     // Returns the name of the field on a class (typically via a linked
265     // field) that acts as the selector value for display / search.
266     getClassSelector(class_: string): string {
267         if (class_) {
268             const linkedClass = this.idl.classes[class_];
269             return linkedClass.pkey ?
270                 linkedClass.field_map[linkedClass.pkey].selector : null;
271         }
272         return null;
273     }
274
275     private flattenLinkedValues(field: any, list: IdlObject[]): ComboboxEntry[] {
276         const class_ = field.class;
277         const fieldOptions = this.fieldOptions[field.name] || {};
278         const idField = this.idl.classes[class_].pkey;
279
280         const selector = fieldOptions.linkedSearchField
281             || this.getClassSelector(class_) || idField;
282
283         return list.map(item => {
284             return {id: item[idField](), label: item[selector]()};
285         });
286     }
287
288     private getFieldList(): Promise<any> {
289
290         this.fields = this.idlDef.fields.filter(f =>
291             !f.virtual && !this.hiddenFieldsList.includes(f.name)
292         );
293
294         // Wait for all network calls to complete
295         return Promise.all(
296             this.fields.map(field => this.constructOneField(field)));
297     }
298
299     private constructOneField(field: any): Promise<any> {
300
301         let promise = null;
302         const fieldOptions = this.fieldOptions[field.name] || {};
303
304         field.readOnly = this.mode === 'view'
305             || fieldOptions.isReadonly === true
306             || this.readonlyFieldsList.includes(field.name);
307
308         if (fieldOptions.isRequiredOverride) {
309             field.isRequired = () => {
310                 return fieldOptions.isRequiredOverride(field.name, this.record);
311             };
312         } else {
313             field.isRequired = () => {
314                 return field.required
315                     || fieldOptions.isRequired
316                     || this.requiredFieldsList.includes(field.name);
317             };
318         }
319
320         if (fieldOptions.customValues) {
321
322             field.linkedValues = fieldOptions.customValues;
323
324         } else if (field.datatype === 'link' && field.readOnly) {
325
326             // no need to fetch all possible values for read-only fields
327             const idToFetch = this.record[field.name]();
328
329             if (idToFetch) {
330
331                 // If the linked class defines a selector field, fetch the
332                 // linked data so we can display the data within the selector
333                 // field.  Otherwise, avoid the network lookup and let the
334                 // bare value (usually an ID) be displayed.
335                 const selector = fieldOptions.linkedSearchField ||
336                     this.getClassSelector(field.class);
337
338                 if (selector && selector !== field.name) {
339                     promise = this.pcrud.retrieve(field.class, idToFetch)
340                         .toPromise().then(list => {
341                             field.linkedValues =
342                                 this.flattenLinkedValues(field, Array(list));
343                         });
344                 } else {
345                     // No selector, display the raw id/key value.
346                     field.linkedValues = [{id: idToFetch, name: idToFetch}];
347                 }
348             }
349
350         } else if (field.datatype === 'link') {
351
352             promise = this.wireUpCombobox(field);
353
354         } else if (field.datatype === 'org_unit') {
355             field.orgDefaultAllowed =
356                 this.orgDefaultAllowedList.includes(field.name);
357         }
358
359         if (fieldOptions.customTemplate) {
360             field.template = fieldOptions.customTemplate.template;
361             field.context = fieldOptions.customTemplate.context;
362         }
363
364         return promise || Promise.resolve();
365     }
366
367     wireUpCombobox(field: any): Promise<any> {
368
369         const fieldOptions = this.fieldOptions[field.name] || {};
370
371         const selector = fieldOptions.linkedSearchField ||
372             this.getClassSelector(field.class);
373
374         if (!selector && !fieldOptions.preloadLinkedValues) {
375             // User probably expects an async data source, but we can't
376             // provide one without a selector.  Warn the user.
377             console.warn(`Class ${field.class} has no selector.
378                 Pre-fetching all rows for combobox`);
379         }
380
381         if (fieldOptions.preloadLinkedValues || !selector) {
382             return this.pcrud.retrieveAll(field.class, {}, {atomic : true})
383             .toPromise().then(list => {
384                 field.linkedValues =
385                     this.flattenLinkedValues(field, list);
386             });
387         }
388
389         // If we have a selector, wire up for async data retrieval
390         field.linkedValuesSource =
391             (term: string): Observable<ComboboxEntry> => {
392
393             const search = {};
394             const orderBy = {order_by: {}};
395             const idField = this.idl.classes[field.class].pkey || 'id';
396
397             search[selector] = {'ilike': `%${term}%`};
398             orderBy.order_by[field.class] = selector;
399
400             return this.pcrud.search(field.class, search, orderBy)
401             .pipe(map(idlThing =>
402                 // Map each object into a ComboboxEntry upon arrival
403                 this.flattenLinkedValues(field, [idlThing])[0]
404             ));
405         };
406
407         // Using an async data source, but a value is already set
408         // on the field.  Fetch the linked object and add it to the
409         // combobox entry list so it will be avilable for display
410         // at dialog load time.
411         const linkVal = this.record[field.name]();
412         if (linkVal !== null && linkVal !== undefined) {
413             return this.pcrud.retrieve(field.class, linkVal).toPromise()
414             .then(idlThing => {
415                 field.linkedValues =
416                     this.flattenLinkedValues(field, Array(idlThing));
417             });
418         }
419
420         // No linked value applied, nothing to pre-fetch.
421         return Promise.resolve();
422     }
423
424     // Returns a context object to be inserted into a custom
425     // field template.
426     customTemplateFieldContext(fieldDef: any): CustomFieldContext {
427         return Object.assign(
428             {   record : this.record,
429                 field: fieldDef // from this.fields
430             },  fieldDef.context || {}
431         );
432     }
433
434     save() {
435         const recToSave = this.idl.clone(this.record);
436         this.convertDatatypesToIdl(recToSave);
437         this.pcrud[this.mode]([recToSave]).toPromise().then(
438             result => this.close(result),
439             error  => this.dismiss(error)
440         );
441     }
442
443     cancel() {
444         this.dismiss('canceled');
445     }
446
447     // Returns a string describing the type of input to display
448     // for a given field.  This helps cut down on the if/else
449     // nesti-ness in the template.  Each field will match
450     // exactly one type.
451     inputType(field: any): string {
452
453         if (field.template) {
454             return 'template';
455         }
456
457         // Some widgets handle readOnly for us.
458         if (   field.datatype === 'timestamp'
459             || field.datatype === 'org_unit'
460             || field.datatype === 'bool') {
461             return field.datatype;
462         }
463
464         if (field.readOnly) {
465             if (field.datatype === 'money') {
466                 return 'readonly-money';
467             }
468
469             if (field.datatype === 'link' || field.linkedValues) {
470                 return 'readonly-list';
471             }
472
473             return 'readonly';
474         }
475
476         if (field.datatype === 'id' && !this.pkeyIsEditable) {
477             return 'readonly';
478         }
479
480         if (   field.datatype === 'int'
481             || field.datatype === 'float'
482             || field.datatype === 'money') {
483             return field.datatype;
484         }
485
486         if (field.datatype === 'link' || field.linkedValues) {
487             return 'list';
488         }
489
490         // datatype == text / interval / editable-pkey
491         return 'text';
492     }
493 }
494
495