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