blob: 78a767e37dbdc8bd5985981b399e3d1c4eb9213d [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 = [
43 '$state',
44 'toastr',
Matteo Scandolo1aee1982017-02-17 08:33:23 -080045 'XosModelStore'];
Matteo Scandolod58d5042016-12-16 16:59:21 -080046
Matteo Scandolo1aee1982017-02-17 08:33:23 -080047 public excluded_fields = [
Matteo Scandoloee655a12016-12-19 15:38:43 -080048 'created',
49 'updated',
50 'enacted',
51 'policed',
52 'backend_register',
53 'deleted',
54 'write_protect',
55 'lazy_blocked',
56 'no_sync',
57 'no_policy',
58 'omf_friendly',
59 'enabled',
Matteo Scandolod62ea792016-12-22 14:02:28 -080060 'validators',
Matteo Scandolo80c3a652017-01-06 10:48:31 -080061 'password',
62 'backend_need_delete',
63 'backend_need_reap'
Matteo Scandoloee655a12016-12-19 15:38:43 -080064 ];
65
Matteo Scandolocb466ed2017-01-04 17:16:24 -080066 constructor(
Matteo Scandoloa242c872017-01-12 15:13:00 -080067 private $state: ng.ui.IStateService,
Matteo Scandolo0a8b02e2017-01-06 14:43:36 -080068 private toastr: ng.toastr.IToastrService,
Matteo Scandolo1aee1982017-02-17 08:33:23 -080069 private XosModelStore: IXosModelStoreService
Matteo Scandolocb466ed2017-01-04 17:16:24 -080070 ) {
Matteo Scandolo08464e52017-01-17 13:35:27 -080071 pluralize.addIrregularRule('xos', 'xoses');
Matteo Scandolod58d5042016-12-16 16:59:21 -080072 pluralize.addPluralRule(/slice$/i, 'slices');
Matteo Scandolo80c3a652017-01-06 10:48:31 -080073 pluralize.addSingularRule(/slice$/i, 'slice');
Matteo Scandolo1aee1982017-02-17 08:33:23 -080074 pluralize.addPluralRule(/library$/i, 'librarys');
75 pluralize.addPluralRule(/imagedeployments/i, 'imagedeploymentses');
76 pluralize.addPluralRule(/controllerimages/i, 'controllerimageses');
Matteo Scandolod4878532017-03-20 17:39:55 -070077 pluralize.addPluralRule(/servicedependency/i, 'servicedependencys');
Matteo Scandolod58d5042016-12-16 16:59:21 -080078 }
79
Matteo Scandolo1c5905f2017-01-04 17:41:15 -080080 public pluralize(string: string, quantity?: number, count?: boolean): string {
Matteo Scandolod58d5042016-12-16 16:59:21 -080081 return pluralize(string, quantity, count);
82 }
83
Matteo Scandolo1c5905f2017-01-04 17:41:15 -080084 public toLabels(strings: string[], pluralize?: boolean): string[] {
Matteo Scandoloe0d71ea2016-12-19 11:56:12 -080085 if (angular.isArray(strings)) {
86 return _.map(strings, s => {
Matteo Scandolod58d5042016-12-16 16:59:21 -080087 return this.toLabel(s, pluralize);
88 });
89 }
Matteo Scandoloe0d71ea2016-12-19 11:56:12 -080090 }
91
Matteo Scandolo1c5905f2017-01-04 17:41:15 -080092 public toLabel(string: string, pluralize?: boolean): string {
Matteo Scandolod58d5042016-12-16 16:59:21 -080093
94 if (pluralize) {
95 string = this.pluralize(string);
96 }
97
98 string = this.fromCamelCase(string);
99 string = this.fromSnakeCase(string);
100 string = this.fromKebabCase(string);
101
102 return this.capitalizeFirst(string);
103 }
104
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800105 public modelToTableCfg(model: IXosModeldef, baseUrl: string): IXosTableCfg {
Matteo Scandolocb466ed2017-01-04 17:16:24 -0800106 const cfg = {
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800107 columns: this.modelFieldsToColumnsCfg(model),
Matteo Scandolocb466ed2017-01-04 17:16:24 -0800108 filter: 'fulltext',
109 order: {field: 'id', reverse: false},
Matteo Scandolo8b2370c2017-02-02 17:19:07 -0800110 pagination: {
111 pageSize: 10
112 },
Matteo Scandolocb466ed2017-01-04 17:16:24 -0800113 actions: [
114 {
Matteo Scandolo2c61b882017-08-07 13:11:47 -0700115 label: 'details',
116 icon: 'search',
117 cb: (item) => {
118 this.$state.go(this.$state.current.name, {id: item.id});
119 }
120 },
121 {
Matteo Scandolocb466ed2017-01-04 17:16:24 -0800122 label: 'delete',
123 icon: 'remove',
124 color: 'red',
125 cb: (item) => {
126 let obj = angular.copy(item);
127
128 item.$delete()
129 .then((res) => {
130 if (res.status === 404) {
131 // TODO understand why it does not go directly in catch
132 throw new Error();
133 }
134 this.toastr.info(`${model.name} ${obj.name} succesfully deleted`);
135 })
136 .catch(() => {
137 this.toastr.error(`Error while deleting ${obj.name}`);
138 });
139 }
140 }
141 ]
142 };
143 return cfg;
144 }
145
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800146 public modelFieldsToColumnsCfg(model: IXosModeldef): IXosTableColumn[] {
147 const fields: IXosModelDefsField[] = model.fields;
148 const modelName: string = model.name;
Matteo Scandolo231de262017-01-04 16:33:14 -0800149 const columns = _.map(fields, (f) => {
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800150 if (!angular.isDefined(f) || this.excluded_fields.indexOf(f.name) > -1) {
Matteo Scandolod58d5042016-12-16 16:59:21 -0800151 return;
152 }
153 const col: IXosTableColumn = {
154 label: this.toLabel(f.name),
155 prop: f.name
156 };
157
Matteo Scandoloa8a6fbb2016-12-21 16:59:08 -0800158 if (f.name === 'id' || f.name === 'name') {
Matteo Scandoloa242c872017-01-12 15:13:00 -0800159 col.link = item => this.stateWithParams(modelName, item);
Matteo Scandoloee655a12016-12-19 15:38:43 -0800160 }
161
Matteo Scandolo04964232017-01-07 12:53:46 -0800162 // if the field identify a relation, create a link
163 if (f.relation && f.relation.type === 'many_to_one') {
Matteo Scandolo04964232017-01-07 12:53:46 -0800164 col.type = 'custom';
165 col.formatter = item => {
166 this.populateRelated(item, item[f.name], f);
167 return item[f.name];
168 };
Matteo Scandolocf5a9932017-08-09 13:46:04 -0700169 col.link = item => this.relatedStateWithParams(f.relation.model, item[col.prop]);
Matteo Scandolo04964232017-01-07 12:53:46 -0800170 }
171
Matteo Scandolod58d5042016-12-16 16:59:21 -0800172 if (f.name === 'backend_status') {
173 col.type = 'icon';
Matteo Scandolo8b2370c2017-02-02 17:19:07 -0800174 col.hover = (item) => {
175 return item[f.name];
176 };
Matteo Scandolod58d5042016-12-16 16:59:21 -0800177 col.formatter = (item) => {
178 if (item.backend_status.indexOf('1') > -1) {
179 return 'check';
180 }
181 if (item.backend_status.indexOf('2') > -1) {
182 return 'exclamation-circle';
183 }
184 if (item.backend_status.indexOf('0') > -1) {
185 return 'clock-o';
186 }
187 };
188 }
Matteo Scandoloa8a6fbb2016-12-21 16:59:08 -0800189
Matteo Scandolod58d5042016-12-16 16:59:21 -0800190 return col;
191 })
192 .filter(v => angular.isDefined(v));
193
Matteo Scandolo231de262017-01-04 16:33:14 -0800194 return columns;
Matteo Scandolod58d5042016-12-16 16:59:21 -0800195 };
196
Matteo Scandoloa242c872017-01-12 15:13:00 -0800197 public stateFromCoreModel(name: string): string {
198 const state: ng.ui.IState = _.find(this.$state.get(), (s: IXosState) => {
199 if (s.data) {
200 return s.data.model === name;
201 }
202 return false;
203 });
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800204 return state ? state.name : null;
Matteo Scandoloa242c872017-01-12 15:13:00 -0800205 }
206
207 public stateWithParams(name: string, model: any): string {
208 const state = this.stateFromCoreModel(name);
209 return `${state}({id: ${model['id']}})`;
210 }
211
Matteo Scandolocf5a9932017-08-09 13:46:04 -0700212 public relatedStateWithParams(name: string, id: string): string {
213 const state = this.stateFromCoreModel(name);
214 return `${state}({id: ${id}})`;
215 }
216
Matteo Scandolo86bc26a2017-01-18 11:06:47 -0800217 public stateWithParamsForJs(name: string, model: any): any {
Matteo Scandolo86bc26a2017-01-18 11:06:47 -0800218 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),
230 hint: f.hint
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800231 };
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800232 if (f.relation) {
233 input.type = 'select';
234 this.populateSelectField(f, input);
235 return input;
236 }
237 return input;
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800238 })
239 .filter(f => this.excluded_fields.indexOf(f.name) === -1);
240 }
241
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800242 public modelToFormCfg(model: IXosModeldef): IXosFormCfg {
243 const formCfg: IXosFormCfg = {
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800244 formName: `${model.name}Form`,
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800245 exclude: ['backend_status', 'creator', 'id'],
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800246 actions: [{
247 label: 'Save',
248 class: 'success',
249 icon: 'ok',
Matteo Scandolo6f45e262017-01-09 14:47:26 -0800250 cb: null
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800251 }],
252 inputs: this.modelFieldToInputCfg(model.fields)
253 };
Matteo Scandolo6f45e262017-01-09 14:47:26 -0800254
255 formCfg.actions[0].cb = (item, form: angular.IFormController) => {
256
257 if (!form.$valid) {
258 formCfg.feedback = {
259 show: true,
260 message: 'Form is invalid',
261 type: 'danger',
262 closeBtn: true
263 };
Matteo Scandoloac8c8c22017-01-09 15:04:32 -0800264
Matteo Scandolo6f45e262017-01-09 14:47:26 -0800265 return;
266 }
267
268 const model = angular.copy(item);
269
270 // TODO remove ManyToMany relations and save them separately (how??)
271 delete item.networks;
272
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800273 // remove field added by xosTable
274 _.forEach(Object.keys(item), prop => {
275 if (prop.indexOf('-formatted') > -1) {
276 delete item[prop];
277 }
278 });
Matteo Scandolo6f45e262017-01-09 14:47:26 -0800279
280 item.$save()
281 .then((res) => {
Matteo Scandoloac8c8c22017-01-09 15:04:32 -0800282 formCfg.feedback = {
283 show: true,
284 message: `${model.name} succesfully saved`,
285 type: 'success',
286 closeBtn: true
287 };
Matteo Scandolo6f45e262017-01-09 14:47:26 -0800288 this.toastr.success(`${model.name} succesfully saved`);
289 })
290 .catch(err => {
Matteo Scandolo7d5af1c2017-05-01 17:24:59 -0700291 formCfg.feedback = {
292 show: true,
293 message: `Error while saving ${model.name}: ${err.error}. ${err.specific_error || ''}`,
294 type: 'danger',
295 closeBtn: true
296 };
297 this.toastr.error(err.specific_error || '', `Error while saving ${model.name}: ${err.error}`);
Matteo Scandolo6f45e262017-01-09 14:47:26 -0800298 });
299 };
300
301 return formCfg;
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800302 }
303
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800304 private formatValidators(validators: IXosModelDefsFieldValidators[]): IXosFormInputValidator {
305 // convert validators as expressed from modelDefs,
306 // to the object required by xosForm
307 return _.reduce(validators, (formValidators: IXosFormInputValidator, v: IXosModelDefsFieldValidators) => {
308 formValidators[v.name] = v.bool_value ? v.bool_value : v.int_value;
309 return formValidators;
310 }, {});
311 }
312
Matteo Scandolod58d5042016-12-16 16:59:21 -0800313 private fromCamelCase(string: string): string {
314 return string.split(/(?=[A-Z])/).map(w => w.toLowerCase()).join(' ');
315 }
316
317 private fromSnakeCase(string: string): string {
318 return string.split('_').join(' ').trim();
319 }
320
321 private fromKebabCase(string: string): string {
322 return string.split('-').join(' ').trim();
323 }
324
325 private capitalizeFirst(string: string): string {
326 return string.slice(0, 1).toUpperCase() + string.slice(1);
327 }
Matteo Scandolo04964232017-01-07 12:53:46 -0800328
329 private populateRelated(item: any, fk: string, field: IXosModelDefsField): any {
330 // if the relation is not defined return
331 if (!fk || angular.isUndefined(fk) || fk === null) {
332 return;
333 }
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800334 this.XosModelStore.query(field.relation.model)
Matteo Scandolo04964232017-01-07 12:53:46 -0800335 .subscribe(res => {
336 if (angular.isDefined(res) && angular.isDefined(fk)) {
337 let ri = _.find(res, {id: fk});
338 if (angular.isDefined(ri)) {
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800339 if (angular.isDefined(ri.name)) {
340 item[`${field.name}-formatted`] = ri.name;
341 }
342 else if (angular.isDefined(ri.humanReadableName)) {
343 item[`${field.name}-formatted`] = ri.humanReadableName;
344 }
345 else {
346 item[`${field.name}-formatted`] = ri.id;
347 }
Matteo Scandolo04964232017-01-07 12:53:46 -0800348 }
349 }
350 });
351 }
Matteo Scandolo07e2f622017-01-09 10:54:13 -0800352
353 // augment a select field with related model informations
354 private populateSelectField(field: IXosModelDefsField, input: IXosFormInput): void {
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800355 this.XosModelStore.query(field.relation.model)
Matteo Scandolo07e2f622017-01-09 10:54:13 -0800356 .subscribe(res => {
357 input.options = _.map(res, item => {
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800358 let opt = {id: item.id, label: item.humanReadableName ? item.humanReadableName : item.name};
359 if (!angular.isDefined(item.humanReadableName) && !angular.isDefined(item.name)) {
360 opt.label = item.id;
361 }
362 return opt;
Matteo Scandolo07e2f622017-01-09 10:54:13 -0800363 });
364 });
365 }
Matteo Scandolod58d5042016-12-16 16:59:21 -0800366}