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
179 this.listifyInputs();
180 this.idlDef = this.idl.classes[this.idlClass];
181 this.recordLabel = this.idlDef.label;
183 // Add some randomness to the generated DOM IDs to ensure against clobbering
184 this.idPrefix = 'fm-editor-' + Math.floor(Math.random() * 100000);
186 if (this.isDialog()) {
187 this.onOpen$.subscribe(() => this.initRecord());
193 open(args?: NgbModalOptions): Observable<any> {
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;
203 return super.open(args);
206 isDialog(): boolean {
207 return this.displayMode === 'dialog';
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;
217 // Translate comma-separated string versions of various inputs
219 private listifyInputs() {
220 if (this.hiddenFields) {
221 this.hiddenFieldsList = this.hiddenFields.split(/,/);
223 if (this.readonlyFields) {
224 this.readonlyFieldsList = this.readonlyFields.split(/,/);
226 if (this.requiredFields) {
227 this.requiredFieldsList = this.requiredFields.split(/,/);
229 if (this.orgDefaultAllowed) {
230 this.orgDefaultAllowedList = this.orgDefaultAllowed.split(/,/);
234 private initRecord(): Promise<any> {
236 const pc = this.idlDef.permacrud || {};
238 view: pc.retrieve ? pc.retrieve.perms : [],
239 create: pc.create ? pc.create.perms : [],
240 update: pc.update ? pc.update.perms : [],
243 this.pkeyIsEditable = !('pkey_sequence' in this.idlDef);
245 if (this.mode === 'update' || this.mode === 'view') {
248 if (this.record && this.recId === null) {
249 promise = Promise.resolve(this.record);
252 this.pcrud.retrieve(this.idlClass, this.recId).toPromise();
255 return promise.then(rec => {
258 return Promise.reject(`No '${this.idlClass}'
259 record found with id ${this.recId}`);
263 this.convertDatatypesToJs();
264 return this.getFieldList();
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));
274 return this.getFieldList();
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);
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');
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());
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 {
316 const linkedClass = this.idl.classes[class_];
317 return linkedClass.pkey ?
318 linkedClass.field_map[linkedClass.pkey].selector : null;
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;
328 const selector = fieldOptions.linkedSearchField
329 || this.getClassSelector(class_) || idField;
331 return list.map(item => {
332 return {id: item[idField](), label: item[selector]()};
336 private getFieldList(): Promise<any> {
338 this.fields = this.idlDef.fields.filter(f =>
339 !f.virtual && !this.hiddenFieldsList.includes(f.name)
342 // Wait for all network calls to complete
344 this.fields.map(field => this.constructOneField(field)));
347 private constructOneField(field: any): Promise<any> {
350 const fieldOptions = this.fieldOptions[field.name] || {};
352 field.readOnly = this.mode === 'view'
353 || fieldOptions.isReadonly === true
354 || this.readonlyFieldsList.includes(field.name);
356 if (fieldOptions.isRequiredOverride) {
357 field.isRequired = () => {
358 return fieldOptions.isRequiredOverride(field.name, this.record);
361 field.isRequired = () => {
362 return field.required
363 || fieldOptions.isRequired
364 || this.requiredFieldsList.includes(field.name);
368 if (fieldOptions.customValues) {
370 field.linkedValues = fieldOptions.customValues;
372 } else if (field.datatype === 'link' && field.readOnly) {
374 // no need to fetch all possible values for read-only fields
375 const idToFetch = this.record[field.name]();
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);
386 if (selector && selector !== field.name) {
387 promise = this.pcrud.retrieve(field.class, idToFetch)
388 .toPromise().then(list => {
390 this.flattenLinkedValues(field, Array(list));
393 // No selector, display the raw id/key value.
394 field.linkedValues = [{id: idToFetch, name: idToFetch}];
398 } else if (field.datatype === 'link') {
400 promise = this.wireUpCombobox(field);
402 } else if (field.datatype === 'org_unit') {
403 field.orgDefaultAllowed =
404 this.orgDefaultAllowedList.includes(field.name);
407 if (fieldOptions.customTemplate) {
408 field.template = fieldOptions.customTemplate.template;
409 field.context = fieldOptions.customTemplate.context;
412 return promise || Promise.resolve();
415 wireUpCombobox(field: any): Promise<any> {
417 const fieldOptions = this.fieldOptions[field.name] || {};
419 // globally preloading unless a field-specific value is set.
420 if (this.preloadLinkedValues) {
421 if (!('preloadLinkedValues' in fieldOptions)) {
422 fieldOptions.preloadLinkedValues = true;
426 const selector = fieldOptions.linkedSearchField ||
427 this.getClassSelector(field.class);
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`);
436 if (fieldOptions.preloadLinkedValues || !selector) {
437 return this.pcrud.retrieveAll(field.class, {}, {atomic : true})
438 .toPromise().then(list => {
440 this.flattenLinkedValues(field, list);
444 // If we have a selector, wire up for async data retrieval
445 field.linkedValuesSource =
446 (term: string): Observable<ComboboxEntry> => {
449 const orderBy = {order_by: {}};
450 const idField = this.idl.classes[field.class].pkey || 'id';
452 search[selector] = {'ilike': `%${term}%`};
453 orderBy.order_by[field.class] = selector;
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]
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()
471 this.flattenLinkedValues(field, Array(idlThing));
475 // No linked value applied, nothing to pre-fetch.
476 return Promise.resolve();
479 // Returns a context object to be inserted into a custom
481 customTemplateFieldContext(fieldDef: any): CustomFieldContext {
482 return Object.assign(
483 { record : this.record,
484 field: fieldDef // from this.fields
485 }, fieldDef.context || {}
490 const recToSave = this.idl.clone(this.record);
492 this.preSave(this.mode, recToSave);
494 this.convertDatatypesToIdl(recToSave);
495 this.pcrud[this.mode]([recToSave]).toPromise().then(
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); }
502 this.onError$.emit(error);
503 this.failStr.current().then(msg => this.toast.warning(msg));
504 if (this.isDialog()) { this.error(error); }
510 this.onCancel$.emit(this.record);
511 this.record = undefined;
516 this.record = undefined;
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
524 inputType(field: any): string {
526 if (field.template) {
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;
537 if (field.readOnly) {
538 if (field.datatype === 'money') {
539 return 'readonly-money';
542 if (field.datatype === 'link' || field.linkedValues) {
543 return 'readonly-list';
549 if (field.datatype === 'id' && !this.pkeyIsEditable) {
553 if ( field.datatype === 'int'
554 || field.datatype === 'float'
555 || field.datatype === 'money') {
556 return field.datatype;
559 if (field.datatype === 'link' || field.linkedValues) {
563 // datatype == text / interval / editable-pkey
567 openTranslator(field: string) {
568 this.translator.fieldName = field;
569 this.translator.idlObject = this.record;
571 this.translator.open().subscribe(
574 this.record[field](newValue);