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';
16 interface CustomFieldTemplate {
17 template: TemplateRef<any>;
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};
25 export interface CustomFieldContext {
26 // Current create/edit/view record
29 // IDL field definition blob
32 // additional context values passed via CustomFieldTemplate
33 [fields: string]: any;
36 // Collection of extra options that may be applied to fields
37 // for controling non-default behaviour.
38 export interface FmFieldOptions {
40 // Render the field as a combobox using these values, regardless
41 // of the field's datatype.
42 customValues?: {[field: string]: ComboboxEntry[]};
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;
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;
55 // Directly override the required state of the field.
56 // This only has an affect if the value is true.
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;
64 // Directly apply the readonly status of the field.
65 // This only has an affect if the value is true.
68 // Render the field using this custom template instead of chosing
69 // from the default set of form inputs.
70 customTemplate?: CustomFieldTemplate;
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;}']
79 export class FmRecordEditorComponent
80 extends DialogComponent implements OnInit {
82 // IDL class hint (e.g. "aou")
83 @Input() idlClass: string;
87 // IDL record we are editing
90 // Permissions extracted from the permacrud defs in the IDL
91 // for the current IDL class
92 modePerms: {[mode: string]: string};
94 // Collection of FmFieldOptions for specifying non-default
95 // behaviour for each field (by field name).
96 @Input() fieldOptions: {[fieldName: string]: FmFieldOptions} = {};
98 // list of fields that should not be displayed
99 @Input() hiddenFieldsList: string[] = [];
100 @Input() hiddenFields: string; // comma-separated string version
102 // list of fields that should always be read-only
103 @Input() readonlyFieldsList: string[] = [];
104 @Input() readonlyFields: string; // comma-separated string version
106 // list of required fields; this supplements what the IDL considers
108 @Input() requiredFieldsList: string[] = [];
109 @Input() requiredFields: string; // comma-separated string version
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
116 // IDL record display label. Defaults to the IDL label.
117 @Input() recordLabel: string;
119 // When true at the component level, pre-fetch the combobox data
120 // for all combobox fields. See also FmFieldOptions.
121 @Input() preloadLinkedValues: boolean;
123 // Display within a modal dialog window or inline in the page.
124 @Input() displayMode: 'dialog' | 'inline' = 'dialog';
126 // Emit the modified object when the save action completes.
127 @Output() onSave$ = new EventEmitter<IdlObject>();
129 // Emit the original object when the save action is canceled.
130 @Output() onCancel$ = new EventEmitter<IdlObject>();
132 // Emit an error message when the save action fails.
133 @Output() onError$ = new EventEmitter<string>();
135 @ViewChild('translator') private translator: TranslateComponent;
136 @ViewChild('successStr') successStr: StringComponent;
137 @ViewChild('failStr') failStr: StringComponent;
139 // IDL info for the the selected IDL class
142 // Can we edit the primary key?
143 pkeyIsEditable = false;
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.
149 // DOM id prefix to prevent id collisions.
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';
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; }
163 // custom function for munging the record before it gets saved;
164 // will get passed mode and the record itself
165 @Input() preSave: Function;
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) {
176 // Avoid fetching data on init since that may lead to unnecessary
180 // In case the caller sets the value to null / undef.
181 if (!this.fieldOptions) { this.fieldOptions = {}; }
183 this.listifyInputs();
184 this.idlDef = this.idl.classes[this.idlClass];
185 this.recordLabel = this.idlDef.label;
187 // Add some randomness to the generated DOM IDs to ensure against clobbering
188 this.idPrefix = 'fm-editor-' + Math.floor(Math.random() * 100000);
190 if (this.isDialog()) {
191 this.onOpen$.subscribe(() => this.initRecord());
197 open(args?: NgbModalOptions): Observable<any> {
201 // ensure we don't hang on to our copy of the record
202 // if the user dismisses the dialog
203 args.beforeDismiss = () => {
204 this.record = undefined;
207 return super.open(args);
210 isDialog(): boolean {
211 return this.displayMode === 'dialog';
214 // Set the record value and clear the recId value to
215 // indicate the record is our current source of data.
216 setRecord(record: IdlObject) {
217 this.record = record;
221 // Translate comma-separated string versions of various inputs
223 private listifyInputs() {
224 if (this.hiddenFields) {
225 this.hiddenFieldsList = this.hiddenFields.split(/,/);
227 if (this.readonlyFields) {
228 this.readonlyFieldsList = this.readonlyFields.split(/,/);
230 if (this.requiredFields) {
231 this.requiredFieldsList = this.requiredFields.split(/,/);
233 if (this.orgDefaultAllowed) {
234 this.orgDefaultAllowedList = this.orgDefaultAllowed.split(/,/);
238 private initRecord(): Promise<any> {
240 const pc = this.idlDef.permacrud || {};
242 view: pc.retrieve ? pc.retrieve.perms : [],
243 create: pc.create ? pc.create.perms : [],
244 update: pc.update ? pc.update.perms : [],
247 this.pkeyIsEditable = !('pkey_sequence' in this.idlDef);
249 if (this.mode === 'update' || this.mode === 'view') {
252 if (this.record && this.recId === null) {
253 promise = Promise.resolve(this.record);
256 this.pcrud.retrieve(this.idlClass, this.recId).toPromise();
259 return promise.then(rec => {
262 return Promise.reject(`No '${this.idlClass}'
263 record found with id ${this.recId}`);
267 this.convertDatatypesToJs();
268 return this.getFieldList();
274 // Create a new record from the stub record provided by the
275 // caller or a new from-scratch record
276 this.setRecord(this.record || this.idl.create(this.idlClass));
278 return this.getFieldList();
281 // Modifies the FM record in place, replacing IDL-compatible values
282 // with native JS values.
283 private convertDatatypesToJs() {
284 this.idlDef.fields.forEach(field => {
285 if (field.datatype === 'bool') {
286 if (this.record[field.name]() === 't') {
287 this.record[field.name](true);
288 } else if (this.record[field.name]() === 'f') {
289 this.record[field.name](false);
295 // Modifies the provided FM record in place, replacing JS values
296 // with IDL-compatible values.
297 convertDatatypesToIdl(rec: IdlObject) {
298 const fields = this.idlDef.fields;
299 fields.forEach(field => {
300 if (field.datatype === 'bool') {
301 if (rec[field.name]() === true) {
302 rec[field.name]('t');
303 // } else if (rec[field.name]() === false) {
304 } else { // TODO: some bools can be NULL
305 rec[field.name]('f');
307 } else if (field.datatype === 'org_unit') {
308 const org = rec[field.name]();
309 if (org && typeof org === 'object') {
310 rec[field.name](org.id());
316 // Returns the name of the field on a class (typically via a linked
317 // field) that acts as the selector value for display / search.
318 getClassSelector(class_: string): string {
320 const linkedClass = this.idl.classes[class_];
321 return linkedClass.pkey ?
322 linkedClass.field_map[linkedClass.pkey].selector : null;
327 private flattenLinkedValues(field: any, list: IdlObject[]): ComboboxEntry[] {
328 const class_ = field.class;
329 const fieldOptions = this.fieldOptions[field.name] || {};
330 const idField = this.idl.classes[class_].pkey;
332 const selector = fieldOptions.linkedSearchField
333 || this.getClassSelector(class_) || idField;
335 return list.map(item => {
336 return {id: item[idField](), label: item[selector]()};
340 private getFieldList(): Promise<any> {
342 this.fields = this.idlDef.fields.filter(f =>
343 !f.virtual && !this.hiddenFieldsList.includes(f.name)
346 // Wait for all network calls to complete
348 this.fields.map(field => this.constructOneField(field)));
351 private constructOneField(field: any): Promise<any> {
354 const fieldOptions = this.fieldOptions[field.name] || {};
356 field.readOnly = this.mode === 'view'
357 || fieldOptions.isReadonly === true
358 || this.readonlyFieldsList.includes(field.name);
360 if (fieldOptions.isRequiredOverride) {
361 field.isRequired = () => {
362 return fieldOptions.isRequiredOverride(field.name, this.record);
365 field.isRequired = () => {
366 return field.required
367 || fieldOptions.isRequired
368 || this.requiredFieldsList.includes(field.name);
372 if (fieldOptions.customValues) {
374 field.linkedValues = fieldOptions.customValues;
376 } else if (field.datatype === 'link' && field.readOnly) {
378 // no need to fetch all possible values for read-only fields
379 const idToFetch = this.record[field.name]();
383 // If the linked class defines a selector field, fetch the
384 // linked data so we can display the data within the selector
385 // field. Otherwise, avoid the network lookup and let the
386 // bare value (usually an ID) be displayed.
387 const selector = fieldOptions.linkedSearchField ||
388 this.getClassSelector(field.class);
390 if (selector && selector !== field.name) {
391 promise = this.pcrud.retrieve(field.class, idToFetch)
392 .toPromise().then(list => {
394 this.flattenLinkedValues(field, Array(list));
397 // No selector, display the raw id/key value.
398 field.linkedValues = [{id: idToFetch, name: idToFetch}];
402 } else if (field.datatype === 'link') {
404 promise = this.wireUpCombobox(field);
406 } else if (field.datatype === 'org_unit') {
407 field.orgDefaultAllowed =
408 this.orgDefaultAllowedList.includes(field.name);
411 if (fieldOptions.customTemplate) {
412 field.template = fieldOptions.customTemplate.template;
413 field.context = fieldOptions.customTemplate.context;
416 return promise || Promise.resolve();
419 wireUpCombobox(field: any): Promise<any> {
421 const fieldOptions = this.fieldOptions[field.name] || {};
423 // globally preloading unless a field-specific value is set.
424 if (this.preloadLinkedValues) {
425 if (!('preloadLinkedValues' in fieldOptions)) {
426 fieldOptions.preloadLinkedValues = true;
430 const selector = fieldOptions.linkedSearchField ||
431 this.getClassSelector(field.class);
433 if (!selector && !fieldOptions.preloadLinkedValues) {
434 // User probably expects an async data source, but we can't
435 // provide one without a selector. Warn the user.
436 console.warn(`Class ${field.class} has no selector.
437 Pre-fetching all rows for combobox`);
440 if (fieldOptions.preloadLinkedValues || !selector) {
441 return this.pcrud.retrieveAll(field.class, {}, {atomic : true})
442 .toPromise().then(list => {
444 this.flattenLinkedValues(field, list);
448 // If we have a selector, wire up for async data retrieval
449 field.linkedValuesSource =
450 (term: string): Observable<ComboboxEntry> => {
453 const orderBy = {order_by: {}};
454 const idField = this.idl.classes[field.class].pkey || 'id';
456 search[selector] = {'ilike': `%${term}%`};
457 orderBy.order_by[field.class] = selector;
459 return this.pcrud.search(field.class, search, orderBy)
460 .pipe(map(idlThing =>
461 // Map each object into a ComboboxEntry upon arrival
462 this.flattenLinkedValues(field, [idlThing])[0]
466 // Using an async data source, but a value is already set
467 // on the field. Fetch the linked object and add it to the
468 // combobox entry list so it will be avilable for display
469 // at dialog load time.
470 const linkVal = this.record[field.name]();
471 if (linkVal !== null && linkVal !== undefined) {
472 return this.pcrud.retrieve(field.class, linkVal).toPromise()
475 this.flattenLinkedValues(field, Array(idlThing));
479 // No linked value applied, nothing to pre-fetch.
480 return Promise.resolve();
483 // Returns a context object to be inserted into a custom
485 customTemplateFieldContext(fieldDef: any): CustomFieldContext {
486 return Object.assign(
487 { record : this.record,
488 field: fieldDef // from this.fields
489 }, fieldDef.context || {}
494 const recToSave = this.idl.clone(this.record);
496 this.preSave(this.mode, recToSave);
498 this.convertDatatypesToIdl(recToSave);
499 this.pcrud[this.mode]([recToSave]).toPromise().then(
501 this.onSave$.emit(result);
502 this.successStr.current().then(msg => this.toast.success(msg));
503 if (this.isDialog()) { this.record = undefined; this.close(result); }
506 this.onError$.emit(error);
507 this.failStr.current().then(msg => this.toast.warning(msg));
508 if (this.isDialog()) { this.error(error); }
514 this.onCancel$.emit(this.record);
515 this.record = undefined;
520 this.record = undefined;
524 // Returns a string describing the type of input to display
525 // for a given field. This helps cut down on the if/else
526 // nesti-ness in the template. Each field will match
528 inputType(field: any): string {
530 if (field.template) {
534 // Some widgets handle readOnly for us.
535 if ( field.datatype === 'timestamp'
536 || field.datatype === 'org_unit'
537 || field.datatype === 'bool') {
538 return field.datatype;
541 if (field.readOnly) {
542 if (field.datatype === 'money') {
543 return 'readonly-money';
546 if (field.datatype === 'link' || field.linkedValues) {
547 return 'readonly-list';
553 if (field.datatype === 'id' && !this.pkeyIsEditable) {
557 if ( field.datatype === 'int'
558 || field.datatype === 'float'
559 || field.datatype === 'money') {
560 return field.datatype;
563 if (field.datatype === 'link' || field.linkedValues) {
567 // datatype == text / interval / editable-pkey
571 openTranslator(field: string) {
572 this.translator.fieldName = field;
573 this.translator.idlObject = this.record;
575 this.translator.open().subscribe(
578 this.record[field](newValue);