1 import {Component, OnInit, Input,
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 {NgbModal, NgbModalOptions} from '@ng-bootstrap/ng-bootstrap';
10 import {ComboboxEntry} from '@eg/share/combobox/combobox.component';
12 interface CustomFieldTemplate {
13 template: TemplateRef<any>;
15 // Allow the caller to pass in a free-form context blob to
16 // be addedto the caller's custom template context, along
17 // with our stock context.
18 context?: {[fields: string]: any};
21 interface CustomFieldContext {
22 // Current create/edit/view record
25 // IDL field definition blob
28 // additional context values passed via CustomFieldTemplate
29 [fields: string]: any;
32 // Collection of extra options that may be applied to fields
33 // for controling non-default behaviour.
34 export interface FmFieldOptions {
36 // Render the field as a combobox using these values, regardless
37 // of the field's datatype.
38 customValues?: {[field: string]: ComboboxEntry[]};
40 // Provide / override the "selector" value for the linked class.
41 // This is the field the combobox will search for typeahead. If no
42 // field is defined, the "selector" field is used. If no "selector"
43 // field exists, the combobox will pre-load all linked values so
44 // the user can click to navigate.
45 linkedSearchField?: string;
47 // When true for combobox fields, pre-fetch the combobox data
48 // so the user can click or type to find values.
49 preloadLinkedValues?: boolean;
51 // Directly override the required state of the field.
52 // This only has an affect if the value is true.
55 // If this function is defined, the function will be called
56 // at render time to see if the field should be marked are required.
57 // This supersedes all other isRequired specifiers.
58 isRequiredOverride?: (field: string, record: IdlObject) => boolean;
60 // Directly apply the readonly status of the field.
61 // This only has an affect if the value is true.
64 // Render the field using this custom template instead of chosing
65 // from the default set of form inputs.
66 customTemplate?: CustomFieldTemplate;
70 selector: 'eg-fm-record-editor',
71 templateUrl: './fm-editor.component.html',
72 /* align checkboxes when not using class="form-check" */
73 styles: ['input[type="checkbox"] {margin-left: 0px;}']
75 export class FmRecordEditorComponent
76 extends DialogComponent implements OnInit {
78 // IDL class hint (e.g. "aou")
79 @Input() idlClass: string;
81 // mode: 'create' for creating a new record,
82 // 'update' for editing an existing record
83 // 'view' for viewing an existing record without editing
84 mode: 'create' | 'update' | 'view' = 'create';
87 // IDL record we are editing
88 // TODO: allow this to be update in real time by the caller?
91 // Permissions extracted from the permacrud defs in the IDL
92 // for the current IDL class
93 modePerms: {[mode: string]: string};
95 // Collection of FmFieldOptions for specifying non-default
96 // behaviour for each field (by field name).
97 @Input() fieldOptions: {[fieldName: string]: FmFieldOptions} = {};
99 // list of fields that should not be displayed
100 @Input() hiddenFieldsList: string[] = [];
101 @Input() hiddenFields: string; // comma-separated string version
103 // list of fields that should always be read-only
104 @Input() readonlyFieldsList: string[] = [];
105 @Input() readonlyFields: string; // comma-separated string version
107 // list of required fields; this supplements what the IDL considers
109 @Input() requiredFieldsList: string[] = [];
110 @Input() requiredFields: string; // comma-separated string version
112 // list of org_unit fields where a default value may be applied by
113 // the org-select if no value is present.
114 @Input() orgDefaultAllowedList: string[] = [];
115 @Input() orgDefaultAllowed: string; // comma-separated string version
117 // IDL record display label. Defaults to the IDL label.
118 @Input() recordLabel: string;
120 // Emit the modified object when the save action completes.
121 @Output() onSave$ = new EventEmitter<IdlObject>();
123 // Emit the original object when the save action is canceled.
124 @Output() onCancel$ = new EventEmitter<IdlObject>();
126 // Emit an error message when the save action fails.
127 @Output() onError$ = new EventEmitter<string>();
129 // IDL info for the the selected IDL class
132 // Can we edit the primary key?
133 pkeyIsEditable = false;
135 // List of IDL field definitions. This is a subset of the full
136 // list of fields on the IDL, since some are hidden, virtual, etc.
139 // DOM id prefix to prevent id collisions.
142 @Input() editMode(mode: 'create' | 'update' | 'view') {
146 // Record ID to view/update. Value is dynamic. Records are not
147 // fetched until .open() is called.
148 @Input() set recordId(id: any) {
149 if (id) { this.recId = id; }
153 private modal: NgbModal, // required for passing to parent
154 private idl: IdlService,
155 private auth: AuthService,
156 private pcrud: PcrudService) {
160 // Avoid fetching data on init since that may lead to unnecessary
163 this.listifyInputs();
164 this.idlDef = this.idl.classes[this.idlClass];
165 this.recordLabel = this.idlDef.label;
167 // Add some randomness to the generated DOM IDs to ensure against clobbering
168 this.idPrefix = 'fm-editor-' + Math.floor(Math.random() * 100000);
171 // Opening dialog, fetch data.
172 open(options?: NgbModalOptions): Promise<any> {
173 return this.initRecord().then(
174 ok => super.open(options),
175 err => console.warn(`Error fetching FM data: ${err}`)
179 // Translate comma-separated string versions of various inputs
181 private listifyInputs() {
182 if (this.hiddenFields) {
183 this.hiddenFieldsList = this.hiddenFields.split(/,/);
185 if (this.readonlyFields) {
186 this.readonlyFieldsList = this.readonlyFields.split(/,/);
188 if (this.requiredFields) {
189 this.requiredFieldsList = this.requiredFields.split(/,/);
191 if (this.orgDefaultAllowed) {
192 this.orgDefaultAllowedList = this.orgDefaultAllowed.split(/,/);
196 private initRecord(): Promise<any> {
198 const pc = this.idlDef.permacrud || {};
200 view: pc.retrieve ? pc.retrieve.perms : [],
201 create: pc.create ? pc.create.perms : [],
202 update: pc.update ? pc.update.perms : [],
205 if (this.mode === 'update' || this.mode === 'view') {
206 return this.pcrud.retrieve(this.idlClass, this.recId)
207 .toPromise().then(rec => {
210 return Promise.reject(`No '${this.idlClass}'
211 record found with id ${this.recId}`);
215 this.convertDatatypesToJs();
216 return this.getFieldList();
220 // create a new record from scratch or from a stub record
221 // provided by the caller.
222 this.pkeyIsEditable = !('pkey_sequence' in this.idlDef);
224 this.record = this.idl.create(this.idlClass);
226 return this.getFieldList();
229 // Modifies the FM record in place, replacing IDL-compatible values
230 // with native JS values.
231 private convertDatatypesToJs() {
232 this.idlDef.fields.forEach(field => {
233 if (field.datatype === 'bool') {
234 if (this.record[field.name]() === 't') {
235 this.record[field.name](true);
236 } else if (this.record[field.name]() === 'f') {
237 this.record[field.name](false);
243 // Modifies the provided FM record in place, replacing JS values
244 // with IDL-compatible values.
245 convertDatatypesToIdl(rec: IdlObject) {
246 const fields = this.idlDef.fields;
247 fields.forEach(field => {
248 if (field.datatype === 'bool') {
249 if (rec[field.name]() === true) {
250 rec[field.name]('t');
251 // } else if (rec[field.name]() === false) {
252 } else { // TODO: some bools can be NULL
253 rec[field.name]('f');
255 } else if (field.datatype === 'org_unit') {
256 const org = rec[field.name]();
257 if (org && typeof org === 'object') {
258 rec[field.name](org.id());
264 // Returns the name of the field on a class (typically via a linked
265 // field) that acts as the selector value for display / search.
266 getClassSelector(class_: string): string {
268 const linkedClass = this.idl.classes[class_];
269 return linkedClass.pkey ?
270 linkedClass.field_map[linkedClass.pkey].selector : null;
275 private flattenLinkedValues(field: any, list: IdlObject[]): ComboboxEntry[] {
276 const class_ = field.class;
277 const fieldOptions = this.fieldOptions[field.name] || {};
278 const idField = this.idl.classes[class_].pkey;
280 const selector = fieldOptions.linkedSearchField
281 || this.getClassSelector(class_) || idField;
283 return list.map(item => {
284 return {id: item[idField](), label: item[selector]()};
288 private getFieldList(): Promise<any> {
290 this.fields = this.idlDef.fields.filter(f =>
291 !f.virtual && !this.hiddenFieldsList.includes(f.name)
294 // Wait for all network calls to complete
296 this.fields.map(field => this.constructOneField(field)));
299 private constructOneField(field: any): Promise<any> {
302 const fieldOptions = this.fieldOptions[field.name] || {};
304 field.readOnly = this.mode === 'view'
305 || fieldOptions.isReadonly === true
306 || this.readonlyFieldsList.includes(field.name);
308 if (fieldOptions.isRequiredOverride) {
309 field.isRequired = () => {
310 return fieldOptions.isRequiredOverride(field.name, this.record);
313 field.isRequired = () => {
314 return field.required
315 || fieldOptions.isRequired
316 || this.requiredFieldsList.includes(field.name);
320 if (fieldOptions.customValues) {
322 field.linkedValues = fieldOptions.customValues;
324 } else if (field.datatype === 'link' && field.readOnly) {
326 // no need to fetch all possible values for read-only fields
327 const idToFetch = this.record[field.name]();
331 // If the linked class defines a selector field, fetch the
332 // linked data so we can display the data within the selector
333 // field. Otherwise, avoid the network lookup and let the
334 // bare value (usually an ID) be displayed.
335 const selector = fieldOptions.linkedSearchField ||
336 this.getClassSelector(field.class);
338 if (selector && selector !== field.name) {
339 promise = this.pcrud.retrieve(field.class, idToFetch)
340 .toPromise().then(list => {
342 this.flattenLinkedValues(field, Array(list));
345 // No selector, display the raw id/key value.
346 field.linkedValues = [{id: idToFetch, name: idToFetch}];
350 } else if (field.datatype === 'link') {
352 promise = this.wireUpCombobox(field);
354 } else if (field.datatype === 'org_unit') {
355 field.orgDefaultAllowed =
356 this.orgDefaultAllowedList.includes(field.name);
359 if (fieldOptions.customTemplate) {
360 field.template = fieldOptions.customTemplate.template;
361 field.context = fieldOptions.customTemplate.context;
364 return promise || Promise.resolve();
367 wireUpCombobox(field: any): Promise<any> {
369 const fieldOptions = this.fieldOptions[field.name] || {};
371 const selector = fieldOptions.linkedSearchField ||
372 this.getClassSelector(field.class);
374 if (!selector && !fieldOptions.preloadLinkedValues) {
375 // User probably expects an async data source, but we can't
376 // provide one without a selector. Warn the user.
377 console.warn(`Class ${field.class} has no selector.
378 Pre-fetching all rows for combobox`);
381 if (fieldOptions.preloadLinkedValues || !selector) {
382 return this.pcrud.retrieveAll(field.class, {}, {atomic : true})
383 .toPromise().then(list => {
385 this.flattenLinkedValues(field, list);
389 // If we have a selector, wire up for async data retrieval
390 field.linkedValuesSource =
391 (term: string): Observable<ComboboxEntry> => {
394 const orderBy = {order_by: {}};
395 const idField = this.idl.classes[field.class].pkey || 'id';
397 search[selector] = {'ilike': `%${term}%`};
398 orderBy.order_by[field.class] = selector;
400 return this.pcrud.search(field.class, search, orderBy)
401 .pipe(map(idlThing =>
402 // Map each object into a ComboboxEntry upon arrival
403 this.flattenLinkedValues(field, [idlThing])[0]
407 // Using an async data source, but a value is already set
408 // on the field. Fetch the linked object and add it to the
409 // combobox entry list so it will be avilable for display
410 // at dialog load time.
411 const linkVal = this.record[field.name]();
412 if (linkVal !== null && linkVal !== undefined) {
413 return this.pcrud.retrieve(field.class, linkVal).toPromise()
416 this.flattenLinkedValues(field, Array(idlThing));
420 // No linked value applied, nothing to pre-fetch.
421 return Promise.resolve();
424 // Returns a context object to be inserted into a custom
426 customTemplateFieldContext(fieldDef: any): CustomFieldContext {
427 return Object.assign(
428 { record : this.record,
429 field: fieldDef // from this.fields
430 }, fieldDef.context || {}
435 const recToSave = this.idl.clone(this.record);
436 this.convertDatatypesToIdl(recToSave);
437 this.pcrud[this.mode]([recToSave]).toPromise().then(
438 result => this.close(result),
439 error => this.dismiss(error)
444 this.dismiss('canceled');
447 // Returns a string describing the type of input to display
448 // for a given field. This helps cut down on the if/else
449 // nesti-ness in the template. Each field will match
451 inputType(field: any): string {
453 if (field.template) {
457 // Some widgets handle readOnly for us.
458 if ( field.datatype === 'timestamp'
459 || field.datatype === 'org_unit'
460 || field.datatype === 'bool') {
461 return field.datatype;
464 if (field.readOnly) {
465 if (field.datatype === 'money') {
466 return 'readonly-money';
469 if (field.datatype === 'link' || field.linkedValues) {
470 return 'readonly-list';
476 if (field.datatype === 'id' && !this.pkeyIsEditable) {
480 if ( field.datatype === 'int'
481 || field.datatype === 'float'
482 || field.datatype === 'money') {
483 return field.datatype;
486 if (field.datatype === 'link' || field.linkedValues) {
490 // datatype == text / interval / editable-pkey