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