1 import {Component, OnInit, Input,
2 Output, EventEmitter, TemplateRef} from '@angular/core';
3 import {IdlService, IdlObject} from '@eg/core/idl.service';
4 import {AuthService} from '@eg/core/auth.service';
5 import {PcrudService} from '@eg/core/pcrud.service';
6 import {DialogComponent} from '@eg/share/dialog/dialog.component';
7 import {NgbModal, NgbModalOptions} from '@ng-bootstrap/ng-bootstrap';
9 interface CustomFieldTemplate {
10 template: TemplateRef<any>;
12 // Allow the caller to pass in a free-form context blob to
13 // be addedto the caller's custom template context, along
14 // with our stock context.
15 context?: {[fields: string]: any};
18 interface CustomFieldContext {
19 // Current create/edit/view record
22 // IDL field definition blob
25 // additional context values passed via CustomFieldTemplate
26 [fields: string]: any;
30 selector: 'eg-fm-record-editor',
31 templateUrl: './fm-editor.component.html'
33 export class FmRecordEditorComponent
34 extends DialogComponent implements OnInit {
36 // IDL class hint (e.g. "aou")
37 @Input() idlClass: string;
39 // mode: 'create' for creating a new record,
40 // 'update' for editing an existing record
41 // 'view' for viewing an existing record without editing
42 mode: 'create' | 'update' | 'view' = 'create';
44 // IDL record we are editing
45 // TODO: allow this to be update in real time by the caller?
48 // Permissions extracted from the permacrud defs in the IDL
49 // for the current IDL class
50 modePerms: {[mode: string]: string};
52 @Input() customFieldTemplates:
53 {[fieldName: string]: CustomFieldTemplate} = {};
55 // list of fields that should not be displayed
56 @Input() hiddenFieldsList: string[] = [];
57 @Input() hiddenFields: string; // comma-separated string version
59 // list of fields that should always be read-only
60 @Input() readonlyFieldsList: string[] = [];
61 @Input() readonlyFields: string; // comma-separated string version
63 // list of required fields; this supplements what the IDL considers
65 @Input() requiredFieldsList: string[] = [];
66 @Input() requiredFields: string; // comma-separated string version
68 // list of org_unit fields where a default value may be applied by
69 // the org-select if no value is present.
70 @Input() orgDefaultAllowedList: string[] = [];
71 @Input() orgDefaultAllowed: string; // comma-separated string version
73 // hash, keyed by field name, of functions to invoke to check
74 // whether a field is required. Each callback is passed the field
75 // name and the record and should return a boolean value. This
76 // supports cases where whether a field is required or not depends
77 // on the current value of another field.
78 @Input() isRequiredOverride:
79 {[field: string]: (field: string, record: IdlObject) => boolean};
81 // IDL record display label. Defaults to the IDL label.
82 @Input() recordLabel: string;
84 // Emit the modified object when the save action completes.
85 @Output() onSave$ = new EventEmitter<IdlObject>();
87 // Emit the original object when the save action is canceled.
88 @Output() onCancel$ = new EventEmitter<IdlObject>();
90 // Emit an error message when the save action fails.
91 @Output() onError$ = new EventEmitter<string>();
93 // IDL info for the the selected IDL class
96 // Can we edit the primary key?
97 pkeyIsEditable = false;
99 // List of IDL field definitions. This is a subset of the full
100 // list of fields on the IDL, since some are hidden, virtual, etc.
103 @Input() editMode(mode: 'create' | 'update' | 'view') {
107 // Record ID to view/update. Value is dynamic. Records are not
108 // fetched until .open() is called.
109 @Input() set recordId(id: any) {
110 if (id) { this.recId = id; }
116 private modal: NgbModal, // required for passing to parent
117 private idl: IdlService,
118 private auth: AuthService,
119 private pcrud: PcrudService) {
123 // Avoid fetching data on init since that may lead to unnecessary
126 this.listifyInputs();
127 this.idlDef = this.idl.classes[this.idlClass];
128 this.recordLabel = this.idlDef.label;
130 // Add some randomness to the generated DOM IDs to ensure against clobbering
131 this.idPrefix = 'fm-editor-' + Math.floor(Math.random() * 100000);
134 // Opening dialog, fetch data.
135 open(options?: NgbModalOptions): Promise<any> {
136 return this.initRecord().then(
137 ok => super.open(options),
138 err => console.warn(`Error fetching FM data: ${err}`)
142 // Translate comma-separated string versions of various inputs
144 private listifyInputs() {
145 if (this.hiddenFields) {
146 this.hiddenFieldsList = this.hiddenFields.split(/,/);
148 if (this.readonlyFields) {
149 this.readonlyFieldsList = this.readonlyFields.split(/,/);
151 if (this.requiredFields) {
152 this.requiredFieldsList = this.requiredFields.split(/,/);
154 if (this.orgDefaultAllowed) {
155 this.orgDefaultAllowedList = this.orgDefaultAllowed.split(/,/);
159 private initRecord(): Promise<any> {
161 const pc = this.idlDef.permacrud || {};
163 view: pc.retrieve ? pc.retrieve.perms : [],
164 create: pc.create ? pc.create.perms : [],
165 update: pc.update ? pc.update.perms : [],
168 if (this.mode === 'update' || this.mode === 'view') {
169 return this.pcrud.retrieve(this.idlClass, this.recId)
170 .toPromise().then(rec => {
173 return Promise.reject(`No '${this.idlClass}'
174 record found with id ${this.recId}`);
178 this.convertDatatypesToJs();
179 return this.getFieldList();
183 // create a new record from scratch
184 this.pkeyIsEditable = !('pkey_sequence' in this.idlDef);
185 this.record = this.idl.create(this.idlClass);
186 return this.getFieldList();
189 // Modifies the FM record in place, replacing IDL-compatible values
190 // with native JS values.
191 private convertDatatypesToJs() {
192 this.idlDef.fields.forEach(field => {
193 if (field.datatype === 'bool') {
194 if (this.record[field.name]() === 't') {
195 this.record[field.name](true);
196 } else if (this.record[field.name]() === 'f') {
197 this.record[field.name](false);
203 // Modifies the provided FM record in place, replacing JS values
204 // with IDL-compatible values.
205 convertDatatypesToIdl(rec: IdlObject) {
206 const fields = this.idlDef.fields;
207 fields.forEach(field => {
208 if (field.datatype === 'bool') {
209 if (rec[field.name]() === true) {
210 rec[field.name]('t');
211 // } else if (rec[field.name]() === false) {
212 } else { // TODO: some bools can be NULL
213 rec[field.name]('f');
215 } else if (field.datatype === 'org_unit') {
216 const org = rec[field.name]();
217 if (org && typeof org === 'object') {
218 rec[field.name](org.id());
225 private flattenLinkedValues(cls: string, list: IdlObject[]): any[] {
226 const idField = this.idl.classes[cls].pkey;
228 this.idl.classes[cls].field_map[idField].selector || idField;
230 return list.map(item => {
231 return {id: item[idField](), name: item[selector]()};
235 private getFieldList(): Promise<any> {
237 this.fields = this.idlDef.fields.filter(f =>
238 !f.virtual && !this.hiddenFieldsList.includes(f.name)
243 this.fields.forEach(field => {
244 field.readOnly = this.mode === 'view'
245 || this.readonlyFieldsList.includes(field.name);
247 if (this.isRequiredOverride &&
248 field.name in this.isRequiredOverride) {
249 field.isRequired = () => {
250 return this.isRequiredOverride[field.name](field.name, this.record);
253 field.isRequired = () => {
254 return field.required ||
255 this.requiredFieldsList.includes(field.name);
259 if (field.datatype === 'link') {
261 this.pcrud.retrieveAll(field.class, {}, {atomic : true})
262 .toPromise().then(list => {
264 this.flattenLinkedValues(field.class, list);
267 } else if (field.datatype === 'org_unit') {
268 field.orgDefaultAllowed =
269 this.orgDefaultAllowedList.includes(field.name);
272 if (this.customFieldTemplates[field.name]) {
273 field.template = this.customFieldTemplates[field.name].template;
274 field.context = this.customFieldTemplates[field.name].context;
279 // Wait for all network calls to complete
280 return Promise.all(promises);
283 // Returns a context object to be inserted into a custom
285 customTemplateFieldContext(fieldDef: any): CustomFieldContext {
286 return Object.assign(
287 { record : this.record,
288 field: fieldDef // from this.fields
289 }, fieldDef.context || {}
294 const recToSave = this.idl.clone(this.record);
295 this.convertDatatypesToIdl(recToSave);
296 this.pcrud[this.mode]([recToSave]).toPromise().then(
297 result => this.close(result),
298 error => this.dismiss(error)
303 this.dismiss('canceled');