blob: ed3f0c0487e8fb5d6b2571e38fbb84ca33388f2f [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');
83 pluralize.addPluralRule(/imagedeployments/i, 'imagedeploymentses');
84 pluralize.addPluralRule(/controllerimages/i, 'controllerimageses');
Matteo Scandolo72181592017-07-25 14:49:40 -070085 pluralize.addPluralRule(/servicedependency/i, 'servicedependencies');
Matteo Scandolod58d5042016-12-16 16:59:21 -080086 }
87
Matteo Scandolo1c5905f2017-01-04 17:41:15 -080088 public pluralize(string: string, quantity?: number, count?: boolean): string {
Matteo Scandolod58d5042016-12-16 16:59:21 -080089 return pluralize(string, quantity, count);
90 }
91
Matteo Scandolo1c5905f2017-01-04 17:41:15 -080092 public toLabels(strings: string[], pluralize?: boolean): string[] {
Matteo Scandoloe0d71ea2016-12-19 11:56:12 -080093 if (angular.isArray(strings)) {
94 return _.map(strings, s => {
Matteo Scandolod58d5042016-12-16 16:59:21 -080095 return this.toLabel(s, pluralize);
96 });
97 }
Matteo Scandoloe0d71ea2016-12-19 11:56:12 -080098 }
99
Matteo Scandolo1c5905f2017-01-04 17:41:15 -0800100 public toLabel(string: string, pluralize?: boolean): string {
Matteo Scandolod58d5042016-12-16 16:59:21 -0800101
102 if (pluralize) {
103 string = this.pluralize(string);
104 }
105
106 string = this.fromCamelCase(string);
107 string = this.fromSnakeCase(string);
108 string = this.fromKebabCase(string);
109
110 return this.capitalizeFirst(string);
111 }
112
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800113 public modelToTableCfg(model: IXosModeldef, baseUrl: string): IXosTableCfg {
Matteo Scandolocb466ed2017-01-04 17:16:24 -0800114 const cfg = {
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800115 columns: this.modelFieldsToColumnsCfg(model),
Matteo Scandolocb466ed2017-01-04 17:16:24 -0800116 filter: 'fulltext',
117 order: {field: 'id', reverse: false},
Matteo Scandolo8b2370c2017-02-02 17:19:07 -0800118 pagination: {
119 pageSize: 10
120 },
Matteo Scandolocb466ed2017-01-04 17:16:24 -0800121 actions: [
122 {
123 label: 'delete',
124 icon: 'remove',
125 color: 'red',
126 cb: (item) => {
127 let obj = angular.copy(item);
128
129 item.$delete()
130 .then((res) => {
131 if (res.status === 404) {
132 // TODO understand why it does not go directly in catch
133 throw new Error();
134 }
135 this.toastr.info(`${model.name} ${obj.name} succesfully deleted`);
136 })
137 .catch(() => {
138 this.toastr.error(`Error while deleting ${obj.name}`);
139 });
140 }
141 }
142 ]
143 };
144 return cfg;
145 }
146
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800147 public modelFieldsToColumnsCfg(model: IXosModeldef): IXosTableColumn[] {
148 const fields: IXosModelDefsField[] = model.fields;
149 const modelName: string = model.name;
Matteo Scandolo231de262017-01-04 16:33:14 -0800150 const columns = _.map(fields, (f) => {
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800151 if (!angular.isDefined(f) || this.excluded_fields.indexOf(f.name) > -1) {
Matteo Scandolod58d5042016-12-16 16:59:21 -0800152 return;
153 }
154 const col: IXosTableColumn = {
155 label: this.toLabel(f.name),
156 prop: f.name
157 };
158
Matteo Scandoloa8a6fbb2016-12-21 16:59:08 -0800159 if (f.name === 'id' || f.name === 'name') {
Matteo Scandoloa242c872017-01-12 15:13:00 -0800160 col.link = item => this.stateWithParams(modelName, item);
Matteo Scandoloee655a12016-12-19 15:38:43 -0800161 }
162
Matteo Scandolo04964232017-01-07 12:53:46 -0800163 // if the field identify a relation, create a link
Matteo Scandolo18975142017-08-01 14:48:04 -0700164 if (f.relation && f.relation.type === 'manytoone') {
Matteo Scandolo04964232017-01-07 12:53:46 -0800165 col.type = 'custom';
166 col.formatter = item => {
167 this.populateRelated(item, item[f.name], f);
168 return item[f.name];
169 };
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800170 col.link = item => {
171 return this.stateWithParams(f.relation.model, item);
172 };
Matteo Scandolo04964232017-01-07 12:53:46 -0800173 }
174
Matteo Scandolod53ac1d2017-08-01 15:06:09 -0700175 if (f.name === 'backend_status' || f.name === 'policy_status') {
Matteo Scandolod58d5042016-12-16 16:59:21 -0800176 col.type = 'icon';
Matteo Scandolo8b2370c2017-02-02 17:19:07 -0800177 col.hover = (item) => {
178 return item[f.name];
179 };
Matteo Scandolod58d5042016-12-16 16:59:21 -0800180 col.formatter = (item) => {
Matteo Scandolod53ac1d2017-08-01 15:06:09 -0700181 if (item[f.name].indexOf('1') > -1) {
Matteo Scandolod58d5042016-12-16 16:59:21 -0800182 return 'check';
183 }
Matteo Scandolod53ac1d2017-08-01 15:06:09 -0700184 if (item[f.name].indexOf('2') > -1) {
Matteo Scandolod58d5042016-12-16 16:59:21 -0800185 return 'exclamation-circle';
186 }
Matteo Scandolod53ac1d2017-08-01 15:06:09 -0700187 if (item[f.name].indexOf('0') > -1) {
Matteo Scandolod58d5042016-12-16 16:59:21 -0800188 return 'clock-o';
189 }
190 };
191 }
Matteo Scandoloa8a6fbb2016-12-21 16:59:08 -0800192
Matteo Scandolod58d5042016-12-16 16:59:21 -0800193 return col;
194 })
195 .filter(v => angular.isDefined(v));
196
Matteo Scandolo231de262017-01-04 16:33:14 -0800197 return columns;
Matteo Scandolod58d5042016-12-16 16:59:21 -0800198 };
199
Matteo Scandoloa242c872017-01-12 15:13:00 -0800200 public stateFromCoreModel(name: string): string {
201 const state: ng.ui.IState = _.find(this.$state.get(), (s: IXosState) => {
202 if (s.data) {
203 return s.data.model === name;
204 }
205 return false;
206 });
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800207 return state ? state.name : null;
Matteo Scandoloa242c872017-01-12 15:13:00 -0800208 }
209
210 public stateWithParams(name: string, model: any): string {
211 const state = this.stateFromCoreModel(name);
212 return `${state}({id: ${model['id']}})`;
213 }
214
Matteo Scandolo86bc26a2017-01-18 11:06:47 -0800215 public stateWithParamsForJs(name: string, model: any): any {
216 // TODO test and interface
217 const state = this.stateFromCoreModel(name);
218 return {name: state, params: {id: model.id}};
219 }
220
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800221 public modelFieldToInputCfg(fields: IXosModelDefsField[]): IXosFormInput[] {
222
Matteo Scandolo6f45e262017-01-09 14:47:26 -0800223 return _.map(fields, (f: IXosModelDefsField) => {
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800224 const input: IXosFormInput = {
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800225 name: f.name,
226 label: this.toLabel(f.name),
227 type: f.type,
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800228 validators: this.formatValidators(f.validators),
Matteo Scandoloe7e052d2017-07-31 19:54:31 -0700229 hint: f.hint,
230 default: f.default || null
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800231 };
Matteo Scandoloe7e052d2017-07-31 19:54:31 -0700232
233 // NOTE populate drop-downs based on relation
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800234 if (f.relation) {
235 input.type = 'select';
236 this.populateSelectField(f, input);
Matteo Scandoloe7e052d2017-07-31 19:54:31 -0700237 }
238 // NOTE if static options are defined in modeldefs
239 // the f.options field is already populated,
240 // we just need to move it to the input
241 else if (f.options && f.options.length > 0) {
242 input.options = f.options;
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800243 }
244 return input;
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800245 })
Matteo Scandolod53ac1d2017-08-01 15:06:09 -0700246 .filter(f => this.form_excluded_fields.indexOf(f.name) === -1);
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800247 }
248
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800249 public modelToFormCfg(model: IXosModeldef): IXosFormCfg {
250 const formCfg: IXosFormCfg = {
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800251 formName: `${model.name}Form`,
Matteo Scandolod53ac1d2017-08-01 15:06:09 -0700252 exclude: this.form_excluded_fields,
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800253 actions: [{
254 label: 'Save',
255 class: 'success',
256 icon: 'ok',
Matteo Scandolo6f45e262017-01-09 14:47:26 -0800257 cb: null
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800258 }],
259 inputs: this.modelFieldToInputCfg(model.fields)
260 };
Matteo Scandolo6f45e262017-01-09 14:47:26 -0800261
262 formCfg.actions[0].cb = (item, form: angular.IFormController) => {
263
264 if (!form.$valid) {
265 formCfg.feedback = {
266 show: true,
267 message: 'Form is invalid',
268 type: 'danger',
269 closeBtn: true
270 };
Matteo Scandoloac8c8c22017-01-09 15:04:32 -0800271
Matteo Scandolo6f45e262017-01-09 14:47:26 -0800272 return;
273 }
274
275 const model = angular.copy(item);
276
277 // TODO remove ManyToMany relations and save them separately (how??)
278 delete item.networks;
279
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800280 // remove field added by xosTable
281 _.forEach(Object.keys(item), prop => {
282 if (prop.indexOf('-formatted') > -1) {
283 delete item[prop];
284 }
285 });
Matteo Scandolo6f45e262017-01-09 14:47:26 -0800286
287 item.$save()
288 .then((res) => {
Matteo Scandoloac8c8c22017-01-09 15:04:32 -0800289 formCfg.feedback = {
290 show: true,
291 message: `${model.name} succesfully saved`,
292 type: 'success',
293 closeBtn: true
294 };
Matteo Scandolo6f45e262017-01-09 14:47:26 -0800295 this.toastr.success(`${model.name} succesfully saved`);
296 })
297 .catch(err => {
Matteo Scandolo42c66922017-05-01 17:24:59 -0700298 formCfg.feedback = {
299 show: true,
300 message: `Error while saving ${model.name}: ${err.error}. ${err.specific_error || ''}`,
301 type: 'danger',
302 closeBtn: true
303 };
304 this.toastr.error(err.specific_error || '', `Error while saving ${model.name}: ${err.error}`);
Matteo Scandolo6f45e262017-01-09 14:47:26 -0800305 });
306 };
307
308 return formCfg;
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800309 }
310
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800311 private formatValidators(validators: IXosModelDefsFieldValidators[]): IXosFormInputValidator {
312 // convert validators as expressed from modelDefs,
313 // to the object required by xosForm
314 return _.reduce(validators, (formValidators: IXosFormInputValidator, v: IXosModelDefsFieldValidators) => {
315 formValidators[v.name] = v.bool_value ? v.bool_value : v.int_value;
316 return formValidators;
317 }, {});
318 }
319
Matteo Scandolod58d5042016-12-16 16:59:21 -0800320 private fromCamelCase(string: string): string {
321 return string.split(/(?=[A-Z])/).map(w => w.toLowerCase()).join(' ');
322 }
323
324 private fromSnakeCase(string: string): string {
325 return string.split('_').join(' ').trim();
326 }
327
328 private fromKebabCase(string: string): string {
329 return string.split('-').join(' ').trim();
330 }
331
332 private capitalizeFirst(string: string): string {
333 return string.slice(0, 1).toUpperCase() + string.slice(1);
334 }
Matteo Scandolo04964232017-01-07 12:53:46 -0800335
336 private populateRelated(item: any, fk: string, field: IXosModelDefsField): any {
337 // if the relation is not defined return
338 if (!fk || angular.isUndefined(fk) || fk === null) {
339 return;
340 }
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800341 this.XosModelStore.query(field.relation.model)
Matteo Scandolo04964232017-01-07 12:53:46 -0800342 .subscribe(res => {
343 if (angular.isDefined(res) && angular.isDefined(fk)) {
344 let ri = _.find(res, {id: fk});
345 if (angular.isDefined(ri)) {
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800346 if (angular.isDefined(ri.name)) {
347 item[`${field.name}-formatted`] = ri.name;
348 }
349 else if (angular.isDefined(ri.humanReadableName)) {
350 item[`${field.name}-formatted`] = ri.humanReadableName;
351 }
352 else {
353 item[`${field.name}-formatted`] = ri.id;
354 }
Matteo Scandolo04964232017-01-07 12:53:46 -0800355 }
356 }
357 });
358 }
Matteo Scandolo07e2f622017-01-09 10:54:13 -0800359
360 // augment a select field with related model informations
361 private populateSelectField(field: IXosModelDefsField, input: IXosFormInput): void {
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800362 this.XosModelStore.query(field.relation.model)
Matteo Scandolo07e2f622017-01-09 10:54:13 -0800363 .subscribe(res => {
364 input.options = _.map(res, item => {
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800365 let opt = {id: item.id, label: item.humanReadableName ? item.humanReadableName : item.name};
366 if (!angular.isDefined(item.humanReadableName) && !angular.isDefined(item.name)) {
367 opt.label = item.id;
368 }
369 return opt;
Matteo Scandolo07e2f622017-01-09 10:54:13 -0800370 });
371 });
372 }
Matteo Scandolod58d5042016-12-16 16:59:21 -0800373}