blob: 5dbd74e0f4266b64661b4783c8f995cb2297fe69 [file] [log] [blame]
Matteo Scandolod58d5042016-12-16 16:59:21 -08001import * as _ from 'lodash';
2import * as pluralize from 'pluralize';
Matteo Scandolocb466ed2017-01-04 17:16:24 -08003import {IXosTableColumn, IXosTableCfg} from '../../table/table';
Matteo Scandolo1aee1982017-02-17 08:33:23 -08004import {IXosModeldef} from '../../../datasources/rest/modeldefs.rest';
Matteo Scandoloe7e052d2017-07-31 19:54:31 -07005import {IXosFormCfg, IXosFormInput, IXosFormInputValidator, IXosFormInputOptions} from '../../form/form';
Matteo Scandolo47860fe2017-02-02 12:05:55 -08006import {IXosModelStoreService} from '../../../datasources/stores/model.store';
Matteo Scandolo1aee1982017-02-17 08:33:23 -08007import {IXosState} from '../runtime-states';
8
9export interface IXosModelDefsFieldValidators {
10 name: string;
11 bool_value?: boolean;
12 int_value?: number;
13}
Matteo Scandolod58d5042016-12-16 16:59:21 -080014
15export interface IXosModelDefsField {
16 name: string;
17 type: string;
Matteo Scandolo1aee1982017-02-17 08:33:23 -080018 validators?: IXosModelDefsFieldValidators[];
Matteo Scandolo04964232017-01-07 12:53:46 -080019 hint?: string;
20 relation?: {
21 model: string;
22 type: string;
23 };
Matteo Scandoloe7e052d2017-07-31 19:54:31 -070024 options?: IXosFormInputOptions[];
25 default?: any | null;
Matteo Scandolod58d5042016-12-16 16:59:21 -080026}
27
28export interface IXosConfigHelpersService {
Matteo Scandoloee655a12016-12-19 15:38:43 -080029 excluded_fields: string[];
Matteo Scandolo1aee1982017-02-17 08:33:23 -080030 modelFieldsToColumnsCfg(model: IXosModeldef): IXosTableColumn[];
31 modelToTableCfg(model: IXosModeldef, modelName: string): IXosTableCfg;
Matteo Scandolo80c3a652017-01-06 10:48:31 -080032 modelFieldToInputCfg(fields: IXosModelDefsField[]): IXosFormInput[];
Matteo Scandolo1aee1982017-02-17 08:33:23 -080033 modelToFormCfg(model: IXosModeldef): IXosFormCfg;
Matteo Scandolod58d5042016-12-16 16:59:21 -080034 pluralize(string: string, quantity?: number, count?: boolean): string;
35 toLabel(string: string, pluralize?: boolean): string;
Matteo Scandoloe0d71ea2016-12-19 11:56:12 -080036 toLabels(string: string[], pluralize?: boolean): string[];
Matteo Scandoloa242c872017-01-12 15:13:00 -080037 stateFromCoreModel(name: string): string;
38 stateWithParams(name: string, model: any): string;
Matteo Scandolo86bc26a2017-01-18 11:06:47 -080039 stateWithParamsForJs(name: string, model: any): any;
Matteo Scandolod58d5042016-12-16 16:59:21 -080040}
41
Matteo Scandolo8b2370c2017-02-02 17:19:07 -080042export class ConfigHelpers implements IXosConfigHelpersService {
Matteo Scandolo1aee1982017-02-17 08:33:23 -080043 static $inject = [
44 '$state',
45 'toastr',
Matteo Scandolo1aee1982017-02-17 08:33:23 -080046 'XosModelStore'];
Matteo Scandolod58d5042016-12-16 16:59:21 -080047
Matteo Scandolo1aee1982017-02-17 08:33:23 -080048 public excluded_fields = [
Matteo Scandoloee655a12016-12-19 15:38:43 -080049 'created',
50 'updated',
51 'enacted',
52 'policed',
53 'backend_register',
54 'deleted',
55 'write_protect',
56 'lazy_blocked',
57 'no_sync',
58 'no_policy',
59 'omf_friendly',
60 'enabled',
Matteo Scandolod62ea792016-12-22 14:02:28 -080061 'validators',
Matteo Scandolo80c3a652017-01-06 10:48:31 -080062 'password',
63 'backend_need_delete',
Matteo Scandolod53ac1d2017-08-01 15:06:09 -070064 'backend_need_reap',
65 'leaf_model_name'
Matteo Scandoloee655a12016-12-19 15:38:43 -080066 ];
67
Matteo Scandolod53ac1d2017-08-01 15:06:09 -070068 public form_excluded_fields = this.excluded_fields.concat([
69 'id',
70 'policy_status',
71 'backend_status',
72 ]);
73
Matteo Scandolocb466ed2017-01-04 17:16:24 -080074 constructor(
Matteo Scandoloa242c872017-01-12 15:13:00 -080075 private $state: ng.ui.IStateService,
Matteo Scandolo0a8b02e2017-01-06 14:43:36 -080076 private toastr: ng.toastr.IToastrService,
Matteo Scandolo1aee1982017-02-17 08:33:23 -080077 private XosModelStore: IXosModelStoreService
Matteo Scandolocb466ed2017-01-04 17:16:24 -080078 ) {
Matteo Scandolo08464e52017-01-17 13:35:27 -080079 pluralize.addIrregularRule('xos', 'xoses');
Matteo Scandolod58d5042016-12-16 16:59:21 -080080 pluralize.addPluralRule(/slice$/i, 'slices');
Matteo Scandolo80c3a652017-01-06 10:48:31 -080081 pluralize.addSingularRule(/slice$/i, 'slice');
Matteo Scandolo1aee1982017-02-17 08:33:23 -080082 pluralize.addPluralRule(/library$/i, 'librarys');
Matteo Scandolo5d962a32017-08-01 18:16:14 -070083 pluralize.addPluralRule(/imagedeployments/i, 'imagedeploymentss');
84 pluralize.addPluralRule(/controllerimages/i, 'controllerimagess');
85 pluralize.addPluralRule(/servicedependency/i, 'servicedependencys');
86 pluralize.addPluralRule(/servicemonitoringagentinfo/i, 'servicemonitoringagentinfoes');
Matteo Scandolod58d5042016-12-16 16:59:21 -080087 }
88
Matteo Scandolo1c5905f2017-01-04 17:41:15 -080089 public pluralize(string: string, quantity?: number, count?: boolean): string {
Matteo Scandolod58d5042016-12-16 16:59:21 -080090 return pluralize(string, quantity, count);
91 }
92
Matteo Scandolo1c5905f2017-01-04 17:41:15 -080093 public toLabels(strings: string[], pluralize?: boolean): string[] {
Matteo Scandoloe0d71ea2016-12-19 11:56:12 -080094 if (angular.isArray(strings)) {
95 return _.map(strings, s => {
Matteo Scandolod58d5042016-12-16 16:59:21 -080096 return this.toLabel(s, pluralize);
97 });
98 }
Matteo Scandoloe0d71ea2016-12-19 11:56:12 -080099 }
100
Matteo Scandolo1c5905f2017-01-04 17:41:15 -0800101 public toLabel(string: string, pluralize?: boolean): string {
Matteo Scandolod58d5042016-12-16 16:59:21 -0800102
103 if (pluralize) {
104 string = this.pluralize(string);
105 }
106
107 string = this.fromCamelCase(string);
108 string = this.fromSnakeCase(string);
109 string = this.fromKebabCase(string);
110
111 return this.capitalizeFirst(string);
112 }
113
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800114 public modelToTableCfg(model: IXosModeldef, baseUrl: string): IXosTableCfg {
Matteo Scandolocb466ed2017-01-04 17:16:24 -0800115 const cfg = {
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800116 columns: this.modelFieldsToColumnsCfg(model),
Matteo Scandolocb466ed2017-01-04 17:16:24 -0800117 filter: 'fulltext',
118 order: {field: 'id', reverse: false},
Matteo Scandolo8b2370c2017-02-02 17:19:07 -0800119 pagination: {
120 pageSize: 10
121 },
Matteo Scandolocb466ed2017-01-04 17:16:24 -0800122 actions: [
123 {
124 label: 'delete',
125 icon: 'remove',
126 color: 'red',
127 cb: (item) => {
128 let obj = angular.copy(item);
129
130 item.$delete()
131 .then((res) => {
132 if (res.status === 404) {
133 // TODO understand why it does not go directly in catch
134 throw new Error();
135 }
136 this.toastr.info(`${model.name} ${obj.name} succesfully deleted`);
137 })
138 .catch(() => {
139 this.toastr.error(`Error while deleting ${obj.name}`);
140 });
141 }
142 }
143 ]
144 };
145 return cfg;
146 }
147
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800148 public modelFieldsToColumnsCfg(model: IXosModeldef): IXosTableColumn[] {
149 const fields: IXosModelDefsField[] = model.fields;
150 const modelName: string = model.name;
Matteo Scandolo231de262017-01-04 16:33:14 -0800151 const columns = _.map(fields, (f) => {
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800152 if (!angular.isDefined(f) || this.excluded_fields.indexOf(f.name) > -1) {
Matteo Scandolod58d5042016-12-16 16:59:21 -0800153 return;
154 }
155 const col: IXosTableColumn = {
156 label: this.toLabel(f.name),
157 prop: f.name
158 };
159
Matteo Scandoloa8a6fbb2016-12-21 16:59:08 -0800160 if (f.name === 'id' || f.name === 'name') {
Matteo Scandoloa242c872017-01-12 15:13:00 -0800161 col.link = item => this.stateWithParams(modelName, item);
Matteo Scandoloee655a12016-12-19 15:38:43 -0800162 }
163
Matteo Scandolo04964232017-01-07 12:53:46 -0800164 // if the field identify a relation, create a link
Matteo Scandolo18975142017-08-01 14:48:04 -0700165 if (f.relation && f.relation.type === 'manytoone') {
Matteo Scandolo04964232017-01-07 12:53:46 -0800166 col.type = 'custom';
167 col.formatter = item => {
168 this.populateRelated(item, item[f.name], f);
169 return item[f.name];
170 };
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800171 col.link = item => {
172 return this.stateWithParams(f.relation.model, item);
173 };
Matteo Scandolo04964232017-01-07 12:53:46 -0800174 }
175
Matteo Scandolod53ac1d2017-08-01 15:06:09 -0700176 if (f.name === 'backend_status' || f.name === 'policy_status') {
Matteo Scandolod58d5042016-12-16 16:59:21 -0800177 col.type = 'icon';
Matteo Scandolo8b2370c2017-02-02 17:19:07 -0800178 col.hover = (item) => {
179 return item[f.name];
180 };
Matteo Scandolod58d5042016-12-16 16:59:21 -0800181 col.formatter = (item) => {
Matteo Scandolod53ac1d2017-08-01 15:06:09 -0700182 if (item[f.name].indexOf('1') > -1) {
Matteo Scandolod58d5042016-12-16 16:59:21 -0800183 return 'check';
184 }
Matteo Scandolod53ac1d2017-08-01 15:06:09 -0700185 if (item[f.name].indexOf('2') > -1) {
Matteo Scandolod58d5042016-12-16 16:59:21 -0800186 return 'exclamation-circle';
187 }
Matteo Scandolod53ac1d2017-08-01 15:06:09 -0700188 if (item[f.name].indexOf('0') > -1) {
Matteo Scandolod58d5042016-12-16 16:59:21 -0800189 return 'clock-o';
190 }
191 };
192 }
Matteo Scandoloa8a6fbb2016-12-21 16:59:08 -0800193
Matteo Scandolod58d5042016-12-16 16:59:21 -0800194 return col;
195 })
196 .filter(v => angular.isDefined(v));
197
Matteo Scandolo231de262017-01-04 16:33:14 -0800198 return columns;
Matteo Scandolod58d5042016-12-16 16:59:21 -0800199 };
200
Matteo Scandoloa242c872017-01-12 15:13:00 -0800201 public stateFromCoreModel(name: string): string {
202 const state: ng.ui.IState = _.find(this.$state.get(), (s: IXosState) => {
203 if (s.data) {
204 return s.data.model === name;
205 }
206 return false;
207 });
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800208 return state ? state.name : null;
Matteo Scandoloa242c872017-01-12 15:13:00 -0800209 }
210
211 public stateWithParams(name: string, model: any): string {
212 const state = this.stateFromCoreModel(name);
213 return `${state}({id: ${model['id']}})`;
214 }
215
Matteo Scandolo86bc26a2017-01-18 11:06:47 -0800216 public stateWithParamsForJs(name: string, model: any): any {
217 // TODO test and interface
218 const state = this.stateFromCoreModel(name);
219 return {name: state, params: {id: model.id}};
220 }
221
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800222 public modelFieldToInputCfg(fields: IXosModelDefsField[]): IXosFormInput[] {
223
Matteo Scandolo6f45e262017-01-09 14:47:26 -0800224 return _.map(fields, (f: IXosModelDefsField) => {
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800225 const input: IXosFormInput = {
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800226 name: f.name,
227 label: this.toLabel(f.name),
228 type: f.type,
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800229 validators: this.formatValidators(f.validators),
Matteo Scandoloe7e052d2017-07-31 19:54:31 -0700230 hint: f.hint,
231 default: f.default || null
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800232 };
Matteo Scandoloe7e052d2017-07-31 19:54:31 -0700233
234 // NOTE populate drop-downs based on relation
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800235 if (f.relation) {
236 input.type = 'select';
237 this.populateSelectField(f, input);
Matteo Scandoloe7e052d2017-07-31 19:54:31 -0700238 }
239 // NOTE if static options are defined in modeldefs
240 // the f.options field is already populated,
241 // we just need to move it to the input
242 else if (f.options && f.options.length > 0) {
243 input.options = f.options;
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800244 }
245 return input;
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800246 })
Matteo Scandolod53ac1d2017-08-01 15:06:09 -0700247 .filter(f => this.form_excluded_fields.indexOf(f.name) === -1);
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800248 }
249
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800250 public modelToFormCfg(model: IXosModeldef): IXosFormCfg {
251 const formCfg: IXosFormCfg = {
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800252 formName: `${model.name}Form`,
Matteo Scandolod53ac1d2017-08-01 15:06:09 -0700253 exclude: this.form_excluded_fields,
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800254 actions: [{
255 label: 'Save',
256 class: 'success',
257 icon: 'ok',
Matteo Scandolo6f45e262017-01-09 14:47:26 -0800258 cb: null
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800259 }],
260 inputs: this.modelFieldToInputCfg(model.fields)
261 };
Matteo Scandolo6f45e262017-01-09 14:47:26 -0800262
263 formCfg.actions[0].cb = (item, form: angular.IFormController) => {
264
265 if (!form.$valid) {
266 formCfg.feedback = {
267 show: true,
268 message: 'Form is invalid',
269 type: 'danger',
270 closeBtn: true
271 };
Matteo Scandoloac8c8c22017-01-09 15:04:32 -0800272
Matteo Scandolo6f45e262017-01-09 14:47:26 -0800273 return;
274 }
275
276 const model = angular.copy(item);
277
278 // TODO remove ManyToMany relations and save them separately (how??)
279 delete item.networks;
280
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800281 // remove field added by xosTable
282 _.forEach(Object.keys(item), prop => {
283 if (prop.indexOf('-formatted') > -1) {
284 delete item[prop];
285 }
286 });
Matteo Scandolo6f45e262017-01-09 14:47:26 -0800287
288 item.$save()
289 .then((res) => {
Matteo Scandoloac8c8c22017-01-09 15:04:32 -0800290 formCfg.feedback = {
291 show: true,
292 message: `${model.name} succesfully saved`,
293 type: 'success',
294 closeBtn: true
295 };
Matteo Scandolo6f45e262017-01-09 14:47:26 -0800296 this.toastr.success(`${model.name} succesfully saved`);
297 })
298 .catch(err => {
Matteo Scandolo42c66922017-05-01 17:24:59 -0700299 formCfg.feedback = {
300 show: true,
301 message: `Error while saving ${model.name}: ${err.error}. ${err.specific_error || ''}`,
302 type: 'danger',
303 closeBtn: true
304 };
305 this.toastr.error(err.specific_error || '', `Error while saving ${model.name}: ${err.error}`);
Matteo Scandolo6f45e262017-01-09 14:47:26 -0800306 });
307 };
308
309 return formCfg;
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800310 }
311
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800312 private formatValidators(validators: IXosModelDefsFieldValidators[]): IXosFormInputValidator {
313 // convert validators as expressed from modelDefs,
314 // to the object required by xosForm
315 return _.reduce(validators, (formValidators: IXosFormInputValidator, v: IXosModelDefsFieldValidators) => {
316 formValidators[v.name] = v.bool_value ? v.bool_value : v.int_value;
317 return formValidators;
318 }, {});
319 }
320
Matteo Scandolod58d5042016-12-16 16:59:21 -0800321 private fromCamelCase(string: string): string {
322 return string.split(/(?=[A-Z])/).map(w => w.toLowerCase()).join(' ');
323 }
324
325 private fromSnakeCase(string: string): string {
326 return string.split('_').join(' ').trim();
327 }
328
329 private fromKebabCase(string: string): string {
330 return string.split('-').join(' ').trim();
331 }
332
333 private capitalizeFirst(string: string): string {
334 return string.slice(0, 1).toUpperCase() + string.slice(1);
335 }
Matteo Scandolo04964232017-01-07 12:53:46 -0800336
337 private populateRelated(item: any, fk: string, field: IXosModelDefsField): any {
338 // if the relation is not defined return
339 if (!fk || angular.isUndefined(fk) || fk === null) {
340 return;
341 }
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800342 this.XosModelStore.query(field.relation.model)
Matteo Scandolo04964232017-01-07 12:53:46 -0800343 .subscribe(res => {
344 if (angular.isDefined(res) && angular.isDefined(fk)) {
345 let ri = _.find(res, {id: fk});
346 if (angular.isDefined(ri)) {
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800347 if (angular.isDefined(ri.name)) {
348 item[`${field.name}-formatted`] = ri.name;
349 }
350 else if (angular.isDefined(ri.humanReadableName)) {
351 item[`${field.name}-formatted`] = ri.humanReadableName;
352 }
353 else {
354 item[`${field.name}-formatted`] = ri.id;
355 }
Matteo Scandolo04964232017-01-07 12:53:46 -0800356 }
357 }
358 });
359 }
Matteo Scandolo07e2f622017-01-09 10:54:13 -0800360
361 // augment a select field with related model informations
362 private populateSelectField(field: IXosModelDefsField, input: IXosFormInput): void {
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800363 this.XosModelStore.query(field.relation.model)
Matteo Scandolo07e2f622017-01-09 10:54:13 -0800364 .subscribe(res => {
365 input.options = _.map(res, item => {
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800366 let opt = {id: item.id, label: item.humanReadableName ? item.humanReadableName : item.name};
367 if (!angular.isDefined(item.humanReadableName) && !angular.isDefined(item.name)) {
368 opt.label = item.id;
369 }
370 return opt;
Matteo Scandolo07e2f622017-01-09 10:54:13 -0800371 });
372 });
373 }
Matteo Scandolod58d5042016-12-16 16:59:21 -0800374}