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