]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/eg2/src/app/share/fm-editor/fm-editor.component.ts
LP#1775466 Angular(6) base application
[working/Evergreen.git] / Open-ILS / src / eg2 / src / app / share / fm-editor / fm-editor.component.ts
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';
8
9 interface CustomFieldTemplate {
10     template: TemplateRef<any>;
11
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};
16 }
17
18 interface CustomFieldContext {
19     // Current create/edit/view record
20     record: IdlObject;
21
22     // IDL field definition blob
23     field: any;
24
25     // additional context values passed via CustomFieldTemplate
26     [fields: string]: any;
27 }
28
29 @Component({
30   selector: 'eg-fm-record-editor',
31   templateUrl: './fm-editor.component.html'
32 })
33 export class FmRecordEditorComponent
34     extends DialogComponent implements OnInit {
35
36     // IDL class hint (e.g. "aou")
37     @Input() idlClass: string;
38
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';
43     recId: any;
44     // IDL record we are editing
45     // TODO: allow this to be update in real time by the caller?
46     record: IdlObject;
47
48     // Permissions extracted from the permacrud defs in the IDL
49     // for the current IDL class
50     modePerms: {[mode: string]: string};
51
52     @Input() customFieldTemplates:
53         {[fieldName: string]: CustomFieldTemplate} = {};
54
55     // list of fields that should not be displayed
56     @Input() hiddenFieldsList: string[] = [];
57     @Input() hiddenFields: string; // comma-separated string version
58
59     // list of fields that should always be read-only
60     @Input() readonlyFieldsList: string[] = [];
61     @Input() readonlyFields: string; // comma-separated string version
62
63     // list of required fields; this supplements what the IDL considers
64     // required
65     @Input() requiredFieldsList: string[] = [];
66     @Input() requiredFields: string; // comma-separated string version
67
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
72
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};
80
81     // IDL record display label.  Defaults to the IDL label.
82     @Input() recordLabel: string;
83
84     // Emit the modified object when the save action completes.
85     @Output() onSave$ = new EventEmitter<IdlObject>();
86
87     // Emit the original object when the save action is canceled.
88     @Output() onCancel$ = new EventEmitter<IdlObject>();
89
90     // Emit an error message when the save action fails.
91     @Output() onError$ = new EventEmitter<string>();
92
93     // IDL info for the the selected IDL class
94     idlDef: any;
95
96     // Can we edit the primary key?
97     pkeyIsEditable = false;
98
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.
101     fields: any[];
102
103     @Input() editMode(mode: 'create' | 'update' | 'view') {
104         this.mode = mode;
105     }
106
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; }
111     }
112
113     constructor(
114       private modal: NgbModal, // required for passing to parent
115       private idl: IdlService,
116       private auth: AuthService,
117       private pcrud: PcrudService) {
118       super(modal);
119     }
120
121     // Avoid fetching data on init since that may lead to unnecessary
122     // data retrieval.
123     ngOnInit() {
124         this.listifyInputs();
125         this.idlDef = this.idl.classes[this.idlClass];
126         this.recordLabel = this.idlDef.label;
127     }
128
129     // Opening dialog, fetch data.
130     open(options?: NgbModalOptions): Promise<any> {
131         return this.initRecord().then(
132             ok => super.open(options),
133             err => console.warn(`Error fetching FM data: ${err}`)
134         );
135     }
136
137     // Translate comma-separated string versions of various inputs
138     // to arrays.
139     private listifyInputs() {
140         if (this.hiddenFields) {
141             this.hiddenFieldsList = this.hiddenFields.split(/,/);
142         }
143         if (this.readonlyFields) {
144             this.readonlyFieldsList = this.readonlyFields.split(/,/);
145         }
146         if (this.requiredFields) {
147             this.requiredFieldsList = this.requiredFields.split(/,/);
148         }
149         if (this.orgDefaultAllowed) {
150             this.orgDefaultAllowedList = this.orgDefaultAllowed.split(/,/);
151         }
152     }
153
154     private initRecord(): Promise<any> {
155
156         const pc = this.idlDef.permacrud || {};
157         this.modePerms = {
158             view:   pc.retrieve ? pc.retrieve.perms : [],
159             create: pc.create ? pc.create.perms : [],
160             update: pc.update ? pc.update.perms : [],
161         };
162
163         if (this.mode === 'update' || this.mode === 'view') {
164             return this.pcrud.retrieve(this.idlClass, this.recId)
165             .toPromise().then(rec => {
166
167                 if (!rec) {
168                     return Promise.reject(`No '${this.idlClass}'
169                         record found with id ${this.recId}`);
170                 }
171
172                 this.record = rec;
173                 this.convertDatatypesToJs();
174                 return this.getFieldList();
175             });
176         }
177
178         // create a new record from scratch
179         this.pkeyIsEditable = !('pkey_sequence' in this.idlDef);
180         this.record = this.idl.create(this.idlClass);
181         return this.getFieldList();
182     }
183
184     // Modifies the FM record in place, replacing IDL-compatible values
185     // with native JS values.
186     private convertDatatypesToJs() {
187         this.idlDef.fields.forEach(field => {
188             if (field.datatype === 'bool') {
189                 if (this.record[field.name]() === 't') {
190                     this.record[field.name](true);
191                 } else if (this.record[field.name]() === 'f') {
192                     this.record[field.name](false);
193                 }
194             }
195         });
196     }
197
198     // Modifies the provided FM record in place, replacing JS values
199     // with IDL-compatible values.
200     convertDatatypesToIdl(rec: IdlObject) {
201         const fields = this.idlDef.fields;
202         fields.forEach(field => {
203             if (field.datatype === 'bool') {
204                 if (rec[field.name]() === true) {
205                     rec[field.name]('t');
206                 // } else if (rec[field.name]() === false) {
207                 } else { // TODO: some bools can be NULL
208                     rec[field.name]('f');
209                 }
210             } else if (field.datatype === 'org_unit') {
211                 const org = rec[field.name]();
212                 if (org && typeof org === 'object') {
213                     rec[field.name](org.id());
214                 }
215             }
216         });
217     }
218
219
220     private flattenLinkedValues(cls: string, list: IdlObject[]): any[] {
221         const idField = this.idl.classes[cls].pkey;
222         const selector =
223             this.idl.classes[cls].field_map[idField].selector || idField;
224
225         return list.map(item => {
226             return {id: item[idField](), name: item[selector]()};
227         });
228     }
229
230     private getFieldList(): Promise<any> {
231
232         this.fields = this.idlDef.fields.filter(f =>
233             !f.virtual && !this.hiddenFieldsList.includes(f.name)
234         );
235
236         const promises = [];
237
238         this.fields.forEach(field => {
239             field.readOnly = this.mode === 'view'
240                 || this.readonlyFieldsList.includes(field.name);
241
242             if (this.isRequiredOverride &&
243                 field.name in this.isRequiredOverride) {
244                 field.isRequired = () => {
245                     return this.isRequiredOverride[field.name](field.name, this.record);
246                 };
247             } else {
248                 field.isRequired = () => {
249                     return field.required ||
250                         this.requiredFieldsList.includes(field.name);
251                 };
252             }
253
254             if (field.datatype === 'link') {
255                 promises.push(
256                     this.pcrud.retrieveAll(field.class, {}, {atomic : true})
257                     .toPromise().then(list => {
258                         field.linkedValues =
259                             this.flattenLinkedValues(field.class, list);
260                     })
261                 );
262             } else if (field.datatype === 'org_unit') {
263                 field.orgDefaultAllowed =
264                     this.orgDefaultAllowedList.includes(field.name);
265             }
266
267             if (this.customFieldTemplates[field.name]) {
268                 field.template = this.customFieldTemplates[field.name].template;
269                 field.context = this.customFieldTemplates[field.name].context;
270             }
271
272         });
273
274         // Wait for all network calls to complete
275         return Promise.all(promises);
276     }
277
278     // Returns a context object to be inserted into a custom
279     // field template.
280     customTemplateFieldContext(fieldDef: any): CustomFieldContext {
281         return Object.assign(
282             {   record : this.record,
283                 field: fieldDef // from this.fields
284             },  fieldDef.context || {}
285         );
286     }
287
288     save() {
289         const recToSave = this.idl.clone(this.record);
290         this.convertDatatypesToIdl(recToSave);
291         this.pcrud[this.mode]([recToSave]).toPromise().then(
292             result => this.close(result),
293             error  => this.dismiss(error)
294         );
295     }
296
297     cancel() {
298         this.dismiss('canceled');
299     }
300 }
301
302