blob: 8ff81a2a0951333b8abe256de3bcc01e686a948c [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';
5import {IXosFormCfg, IXosFormInput, IXosFormInputValidator} 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 Scandolod58d5042016-12-16 16:59:21 -080024}
25
26export interface IXosConfigHelpersService {
Matteo Scandoloee655a12016-12-19 15:38:43 -080027 excluded_fields: string[];
Matteo Scandolo1aee1982017-02-17 08:33:23 -080028 modelFieldsToColumnsCfg(model: IXosModeldef): IXosTableColumn[];
29 modelToTableCfg(model: IXosModeldef, modelName: string): IXosTableCfg;
Matteo Scandolo80c3a652017-01-06 10:48:31 -080030 modelFieldToInputCfg(fields: IXosModelDefsField[]): IXosFormInput[];
Matteo Scandolo1aee1982017-02-17 08:33:23 -080031 modelToFormCfg(model: IXosModeldef): IXosFormCfg;
Matteo Scandolod58d5042016-12-16 16:59:21 -080032 pluralize(string: string, quantity?: number, count?: boolean): string;
33 toLabel(string: string, pluralize?: boolean): string;
Matteo Scandoloe0d71ea2016-12-19 11:56:12 -080034 toLabels(string: string[], pluralize?: boolean): string[];
Matteo Scandoloa242c872017-01-12 15:13:00 -080035 stateFromCoreModel(name: string): string;
36 stateWithParams(name: string, model: any): string;
Matteo Scandolocf5a9932017-08-09 13:46:04 -070037 relatedStateWithParams(name: string, id: string): string;
Matteo Scandolo86bc26a2017-01-18 11:06:47 -080038 stateWithParamsForJs(name: string, model: any): any;
Matteo Scandolod58d5042016-12-16 16:59:21 -080039}
40
Matteo Scandolo8b2370c2017-02-02 17:19:07 -080041export class ConfigHelpers implements IXosConfigHelpersService {
Matteo Scandolo1aee1982017-02-17 08:33:23 -080042 static $inject = [
Matteo Scandolo88be90f2017-09-11 12:21:39 -070043 '$log',
Matteo Scandolo1aee1982017-02-17 08:33:23 -080044 '$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',
64 'backend_need_reap'
Matteo Scandoloee655a12016-12-19 15:38:43 -080065 ];
66
Matteo Scandolocb466ed2017-01-04 17:16:24 -080067 constructor(
Matteo Scandolo88be90f2017-09-11 12:21:39 -070068 private $log: ng.ILogService,
Matteo Scandoloa242c872017-01-12 15:13:00 -080069 private $state: ng.ui.IStateService,
Matteo Scandolo0a8b02e2017-01-06 14:43:36 -080070 private toastr: ng.toastr.IToastrService,
Matteo Scandolo1aee1982017-02-17 08:33:23 -080071 private XosModelStore: IXosModelStoreService
Matteo Scandolocb466ed2017-01-04 17:16:24 -080072 ) {
Matteo Scandolo08464e52017-01-17 13:35:27 -080073 pluralize.addIrregularRule('xos', 'xoses');
Matteo Scandolod58d5042016-12-16 16:59:21 -080074 pluralize.addPluralRule(/slice$/i, 'slices');
Matteo Scandolo80c3a652017-01-06 10:48:31 -080075 pluralize.addSingularRule(/slice$/i, 'slice');
Matteo Scandolo1aee1982017-02-17 08:33:23 -080076 pluralize.addPluralRule(/library$/i, 'librarys');
77 pluralize.addPluralRule(/imagedeployments/i, 'imagedeploymentses');
78 pluralize.addPluralRule(/controllerimages/i, 'controllerimageses');
Matteo Scandolod4878532017-03-20 17:39:55 -070079 pluralize.addPluralRule(/servicedependency/i, 'servicedependencys');
Matteo Scandolod58d5042016-12-16 16:59:21 -080080 }
81
Matteo Scandolo1c5905f2017-01-04 17:41:15 -080082 public pluralize(string: string, quantity?: number, count?: boolean): string {
Matteo Scandolod58d5042016-12-16 16:59:21 -080083 return pluralize(string, quantity, count);
84 }
85
Matteo Scandolo1c5905f2017-01-04 17:41:15 -080086 public toLabels(strings: string[], pluralize?: boolean): string[] {
Matteo Scandoloe0d71ea2016-12-19 11:56:12 -080087 if (angular.isArray(strings)) {
88 return _.map(strings, s => {
Matteo Scandolod58d5042016-12-16 16:59:21 -080089 return this.toLabel(s, pluralize);
90 });
91 }
Matteo Scandoloe0d71ea2016-12-19 11:56:12 -080092 }
93
Matteo Scandolo1c5905f2017-01-04 17:41:15 -080094 public toLabel(string: string, pluralize?: boolean): string {
Matteo Scandolod58d5042016-12-16 16:59:21 -080095
96 if (pluralize) {
97 string = this.pluralize(string);
98 }
99
100 string = this.fromCamelCase(string);
101 string = this.fromSnakeCase(string);
102 string = this.fromKebabCase(string);
103
104 return this.capitalizeFirst(string);
105 }
106
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800107 public modelToTableCfg(model: IXosModeldef, baseUrl: string): IXosTableCfg {
Matteo Scandolocb466ed2017-01-04 17:16:24 -0800108 const cfg = {
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800109 columns: this.modelFieldsToColumnsCfg(model),
Matteo Scandolocb466ed2017-01-04 17:16:24 -0800110 filter: 'fulltext',
111 order: {field: 'id', reverse: false},
Matteo Scandolo8b2370c2017-02-02 17:19:07 -0800112 pagination: {
113 pageSize: 10
114 },
Matteo Scandolocb466ed2017-01-04 17:16:24 -0800115 actions: [
116 {
Matteo Scandolo2c61b882017-08-07 13:11:47 -0700117 label: 'details',
118 icon: 'search',
119 cb: (item) => {
120 this.$state.go(this.$state.current.name, {id: item.id});
121 }
122 },
123 {
Matteo Scandolocb466ed2017-01-04 17:16:24 -0800124 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
165 if (f.relation && f.relation.type === 'many_to_one') {
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 Scandolocf5a9932017-08-09 13:46:04 -0700171 col.link = item => this.relatedStateWithParams(f.relation.model, item[col.prop]);
Matteo Scandolo04964232017-01-07 12:53:46 -0800172 }
173
Matteo Scandolod58d5042016-12-16 16:59:21 -0800174 if (f.name === 'backend_status') {
175 col.type = 'icon';
Matteo Scandolo8b2370c2017-02-02 17:19:07 -0800176 col.hover = (item) => {
177 return item[f.name];
178 };
Matteo Scandolod58d5042016-12-16 16:59:21 -0800179 col.formatter = (item) => {
180 if (item.backend_status.indexOf('1') > -1) {
181 return 'check';
182 }
183 if (item.backend_status.indexOf('2') > -1) {
184 return 'exclamation-circle';
185 }
186 if (item.backend_status.indexOf('0') > -1) {
187 return 'clock-o';
188 }
189 };
190 }
Matteo Scandoloa8a6fbb2016-12-21 16:59:08 -0800191
Matteo Scandolod58d5042016-12-16 16:59:21 -0800192 return col;
193 })
194 .filter(v => angular.isDefined(v));
195
Matteo Scandolo231de262017-01-04 16:33:14 -0800196 return columns;
Matteo Scandolod58d5042016-12-16 16:59:21 -0800197 };
198
Matteo Scandoloa242c872017-01-12 15:13:00 -0800199 public stateFromCoreModel(name: string): string {
200 const state: ng.ui.IState = _.find(this.$state.get(), (s: IXosState) => {
201 if (s.data) {
202 return s.data.model === name;
203 }
204 return false;
205 });
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800206 return state ? state.name : null;
Matteo Scandoloa242c872017-01-12 15:13:00 -0800207 }
208
209 public stateWithParams(name: string, model: any): string {
210 const state = this.stateFromCoreModel(name);
211 return `${state}({id: ${model['id']}})`;
212 }
213
Matteo Scandolocf5a9932017-08-09 13:46:04 -0700214 public relatedStateWithParams(name: string, id: string): string {
215 const state = this.stateFromCoreModel(name);
216 return `${state}({id: ${id}})`;
217 }
218
Matteo Scandolo86bc26a2017-01-18 11:06:47 -0800219 public stateWithParamsForJs(name: string, model: any): any {
Matteo Scandolo86bc26a2017-01-18 11:06:47 -0800220 const state = this.stateFromCoreModel(name);
221 return {name: state, params: {id: model.id}};
222 }
223
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800224 public modelFieldToInputCfg(fields: IXosModelDefsField[]): IXosFormInput[] {
225
Matteo Scandolo6f45e262017-01-09 14:47:26 -0800226 return _.map(fields, (f: IXosModelDefsField) => {
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800227 const input: IXosFormInput = {
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800228 name: f.name,
229 label: this.toLabel(f.name),
230 type: f.type,
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800231 validators: this.formatValidators(f.validators),
232 hint: f.hint
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800233 };
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800234 if (f.relation) {
235 input.type = 'select';
236 this.populateSelectField(f, input);
237 return input;
238 }
239 return input;
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800240 })
241 .filter(f => this.excluded_fields.indexOf(f.name) === -1);
242 }
243
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800244 public modelToFormCfg(model: IXosModeldef): IXosFormCfg {
245 const formCfg: IXosFormCfg = {
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800246 formName: `${model.name}Form`,
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800247 exclude: ['backend_status', 'creator', 'id'],
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800248 actions: [{
249 label: 'Save',
250 class: 'success',
251 icon: 'ok',
Matteo Scandolo6f45e262017-01-09 14:47:26 -0800252 cb: null
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800253 }],
254 inputs: this.modelFieldToInputCfg(model.fields)
255 };
Matteo Scandolo6f45e262017-01-09 14:47:26 -0800256
257 formCfg.actions[0].cb = (item, form: angular.IFormController) => {
258
259 if (!form.$valid) {
260 formCfg.feedback = {
261 show: true,
262 message: 'Form is invalid',
263 type: 'danger',
264 closeBtn: true
265 };
Matteo Scandoloac8c8c22017-01-09 15:04:32 -0800266
Matteo Scandolo6f45e262017-01-09 14:47:26 -0800267 return;
268 }
269
270 const model = angular.copy(item);
271
272 // TODO remove ManyToMany relations and save them separately (how??)
273 delete item.networks;
274
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800275 // remove field added by xosTable
276 _.forEach(Object.keys(item), prop => {
277 if (prop.indexOf('-formatted') > -1) {
278 delete item[prop];
279 }
280 });
Matteo Scandolo6f45e262017-01-09 14:47:26 -0800281
282 item.$save()
283 .then((res) => {
Matteo Scandoloac8c8c22017-01-09 15:04:32 -0800284 formCfg.feedback = {
285 show: true,
286 message: `${model.name} succesfully saved`,
287 type: 'success',
288 closeBtn: true
289 };
Matteo Scandolo6f45e262017-01-09 14:47:26 -0800290 this.toastr.success(`${model.name} succesfully saved`);
291 })
292 .catch(err => {
Matteo Scandolo7d5af1c2017-05-01 17:24:59 -0700293 formCfg.feedback = {
294 show: true,
295 message: `Error while saving ${model.name}: ${err.error}. ${err.specific_error || ''}`,
296 type: 'danger',
297 closeBtn: true
298 };
299 this.toastr.error(err.specific_error || '', `Error while saving ${model.name}: ${err.error}`);
Matteo Scandolo6f45e262017-01-09 14:47:26 -0800300 });
301 };
302
303 return formCfg;
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800304 }
305
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800306 private formatValidators(validators: IXosModelDefsFieldValidators[]): IXosFormInputValidator {
307 // convert validators as expressed from modelDefs,
308 // to the object required by xosForm
309 return _.reduce(validators, (formValidators: IXosFormInputValidator, v: IXosModelDefsFieldValidators) => {
310 formValidators[v.name] = v.bool_value ? v.bool_value : v.int_value;
311 return formValidators;
312 }, {});
313 }
314
Matteo Scandolod58d5042016-12-16 16:59:21 -0800315 private fromCamelCase(string: string): string {
316 return string.split(/(?=[A-Z])/).map(w => w.toLowerCase()).join(' ');
317 }
318
319 private fromSnakeCase(string: string): string {
320 return string.split('_').join(' ').trim();
321 }
322
323 private fromKebabCase(string: string): string {
324 return string.split('-').join(' ').trim();
325 }
326
327 private capitalizeFirst(string: string): string {
328 return string.slice(0, 1).toUpperCase() + string.slice(1);
329 }
Matteo Scandolo04964232017-01-07 12:53:46 -0800330
331 private populateRelated(item: any, fk: string, field: IXosModelDefsField): any {
332 // if the relation is not defined return
333 if (!fk || angular.isUndefined(fk) || fk === null) {
334 return;
335 }
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800336 this.XosModelStore.query(field.relation.model)
Matteo Scandolo04964232017-01-07 12:53:46 -0800337 .subscribe(res => {
338 if (angular.isDefined(res) && angular.isDefined(fk)) {
339 let ri = _.find(res, {id: fk});
340 if (angular.isDefined(ri)) {
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800341 if (angular.isDefined(ri.name)) {
342 item[`${field.name}-formatted`] = ri.name;
343 }
344 else if (angular.isDefined(ri.humanReadableName)) {
345 item[`${field.name}-formatted`] = ri.humanReadableName;
346 }
347 else {
348 item[`${field.name}-formatted`] = ri.id;
349 }
Matteo Scandolo04964232017-01-07 12:53:46 -0800350 }
351 }
352 });
353 }
Matteo Scandolo07e2f622017-01-09 10:54:13 -0800354
355 // augment a select field with related model informations
356 private populateSelectField(field: IXosModelDefsField, input: IXosFormInput): void {
Matteo Scandolo88be90f2017-09-11 12:21:39 -0700357
358 if (field.relation.model.indexOf('_decl') > -1) {
359 field.relation.model = field.relation.model.replace('_decl', '');
360 }
361
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800362 this.XosModelStore.query(field.relation.model)
Matteo Scandolo88be90f2017-09-11 12:21:39 -0700363 .subscribe(
364 res => {
365 input.options = _.map(res, item => {
366 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;
371 });
372 },
373 err => {
374 this.$log.error(`[XOSConfigHelpers] Failed to build relations for ${field.relation.model}`);
375 }
376 );
Matteo Scandolo07e2f622017-01-09 10:54:13 -0800377 }
Matteo Scandolod58d5042016-12-16 16:59:21 -0800378}