blob: bcac6a993505ae7dabb25c4a37ea756db00c3f0d [file] [log] [blame]
Matteo Scandolofb46ae62017-08-08 09:10:50 -07001
2/*
3 * Copyright 2017-present Open Networking Foundation
4
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8
9 * http://www.apache.org/licenses/LICENSE-2.0
10
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18
Matteo Scandolo9f87f302016-12-13 18:11:10 -080019import {IXosTableCfg} from '../../core/table/table';
Matteo Scandolo47860fe2017-02-02 12:05:55 -080020import {IXosModelStoreService} from '../../datasources/stores/model.store';
Matteo Scandolod58d5042016-12-16 16:59:21 -080021import {IXosConfigHelpersService} from '../../core/services/helpers/config.helpers';
Matteo Scandoloee655a12016-12-19 15:38:43 -080022import * as _ from 'lodash';
Matteo Scandolo80c3a652017-01-06 10:48:31 -080023import {IXosResourceService} from '../../datasources/rest/model.rest';
Matteo Scandolo04964232017-01-07 12:53:46 -080024import {IStoreHelpersService} from '../../datasources/helpers/store.helpers';
Matteo Scandolo580033a2017-08-17 11:16:39 -070025import {IXosModelDiscovererService, IXosModel} from '../../datasources/helpers/model-discoverer.service';
Matteo Scandolo5d962a32017-08-01 18:16:14 -070026import './crud.scss';
27import {IXosCrudRelationService} from './crud.relations.service';
Matteo Scandoloc8a58c82017-08-17 17:14:38 -070028import {IXosDebugService, IXosDebugStatus} from '../../core/debug/debug.service';
29import {IXosKeyboardShortcutService} from '../../core/services/keyboard-shortcut';
Matteo Scandolo1aee1982017-02-17 08:33:23 -080030
31export interface IXosModelRelation {
32 model: string;
33 type: string;
Matteo Scandolo5d962a32017-08-01 18:16:14 -070034 on_field: string;
Matteo Scandolo9f87f302016-12-13 18:11:10 -080035}
36
37class CrudController {
Matteo Scandolo1aee1982017-02-17 08:33:23 -080038 static $inject = [
39 '$scope',
Matteo Scandolo5d962a32017-08-01 18:16:14 -070040 '$log',
Matteo Scandolo1aee1982017-02-17 08:33:23 -080041 '$state',
42 '$stateParams',
43 'XosModelStore',
44 'ConfigHelpers',
45 'ModelRest',
46 'StoreHelpers',
Matteo Scandolo5d962a32017-08-01 18:16:14 -070047 'XosModelDiscoverer',
Matteo Scandoloc8a58c82017-08-17 17:14:38 -070048 'XosCrudRelation',
49 'XosDebug',
50 'XosKeyboardShortcut'
Matteo Scandolo1aee1982017-02-17 08:33:23 -080051 ];
Matteo Scandolo9f87f302016-12-13 18:11:10 -080052
Matteo Scandolo5d962a32017-08-01 18:16:14 -070053 // bindings
54
Matteo Scandolo1aee1982017-02-17 08:33:23 -080055 public data: {model: string};
Matteo Scandolo9f87f302016-12-13 18:11:10 -080056 public tableCfg: IXosTableCfg;
Matteo Scandoloee655a12016-12-19 15:38:43 -080057 public formCfg: any;
Matteo Scandoloee655a12016-12-19 15:38:43 -080058 public baseUrl: string;
59 public list: boolean;
Matteo Scandolo580033a2017-08-17 11:16:39 -070060 public modelName: string;
61 public pluralTitle: string;
62 public singularTitle: string;
Matteo Scandolo9f87f302016-12-13 18:11:10 -080063 public tableData: any[];
Matteo Scandolo580033a2017-08-17 11:16:39 -070064 public model: any; // holds the real model
65 public modelDef: IXosModel;
Matteo Scandolo5d962a32017-08-01 18:16:14 -070066 public related: {manytoone: IXosModelRelation[], onetomany: IXosModelRelation[]} = {
67 manytoone: [],
68 onetomany: []
69 };
70 public relatedModels: {manytoone: any, onetomany: any} = {
71 manytoone: {},
72 onetomany: {}
73 };
Matteo Scandoloc8a58c82017-08-17 17:14:38 -070074 public debugTab: boolean;
Matteo Scandolo9f87f302016-12-13 18:11:10 -080075
76 constructor(
Matteo Scandolof2c3ed62016-12-15 14:32:50 -080077 private $scope: angular.IScope,
Matteo Scandolo5d962a32017-08-01 18:16:14 -070078 private $log: angular.ILogService,
Matteo Scandoloee655a12016-12-19 15:38:43 -080079 private $state: angular.ui.IStateService,
80 private $stateParams: ng.ui.IStateParamsService,
Matteo Scandolo47860fe2017-02-02 12:05:55 -080081 private store: IXosModelStoreService,
Matteo Scandolo80c3a652017-01-06 10:48:31 -080082 private ConfigHelpers: IXosConfigHelpersService,
Matteo Scandolo04964232017-01-07 12:53:46 -080083 private ModelRest: IXosResourceService,
Matteo Scandolo1aee1982017-02-17 08:33:23 -080084 private StoreHelpers: IStoreHelpersService,
Matteo Scandolo5d962a32017-08-01 18:16:14 -070085 private XosModelDiscovererService: IXosModelDiscovererService,
Matteo Scandoloc8a58c82017-08-17 17:14:38 -070086 private XosCrudRelation: IXosCrudRelationService,
87 private XosDebug: IXosDebugService,
88 private XosKeyboardShortcut: IXosKeyboardShortcutService
Matteo Scandolo9f87f302016-12-13 18:11:10 -080089 ) {
Matteo Scandoloa4718592017-08-10 14:54:51 -070090 this.$log.info('[XosCrud] Setup', $state.current.data);
Matteo Scandolo5d962a32017-08-01 18:16:14 -070091
Matteo Scandolo9f87f302016-12-13 18:11:10 -080092 this.data = this.$state.current.data;
Matteo Scandolo580033a2017-08-17 11:16:39 -070093 this.modelDef = this.XosModelDiscovererService.get(this.data.model);
94 this.modelName = this.modelDef.verbose_name ? this.modelDef.verbose_name : this.modelDef.name;
95 this.pluralTitle = this.ConfigHelpers.pluralize(this.modelName);
96 this.singularTitle = this.ConfigHelpers.pluralize(this.modelName, 1);
Matteo Scandolo9f87f302016-12-13 18:11:10 -080097
Matteo Scandoloee655a12016-12-19 15:38:43 -080098 this.list = true;
Matteo Scandolo1aee1982017-02-17 08:33:23 -080099
100 // TODO get the proper URL from model discoverer
Matteo Scandolo580033a2017-08-17 11:16:39 -0700101 this.baseUrl = '#/' + this.modelDef.clientUrl.replace(':id?', '');
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800102
Matteo Scandolo580033a2017-08-17 11:16:39 -0700103 this.tableCfg = this.modelDef.tableCfg;
104 this.formCfg = this.modelDef.formCfg;
Matteo Scandoloee655a12016-12-19 15:38:43 -0800105
Matteo Scandoloc8a58c82017-08-17 17:14:38 -0700106 this.debugTab = this.XosDebug.status.modelsTab;
107 this.$scope.$on('xos.debug.status', (e, status: IXosDebugStatus) => {
108 this.debugTab = status.modelsTab;
109 this.$scope.$apply();
110 });
111
Matteo Scandolof2c3ed62016-12-15 14:32:50 -0800112 this.store.query(this.data.model)
Matteo Scandolo035c5932016-12-14 09:55:15 -0800113 .subscribe(
114 (event) => {
115 // NOTE Observable mess with $digest cycles, we need to schedule the expression later
116 $scope.$evalAsync(() => {
117 this.tableData = event;
Matteo Scandoloee655a12016-12-19 15:38:43 -0800118
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800119 // if it is a detail page for an existing model
120 if ($stateParams['id'] && $stateParams['id'] !== 'add') {
Matteo Scandolo5d962a32017-08-01 18:16:14 -0700121 this.related.onetomany = _.filter($state.current.data.relations, {type: 'onetomany'});
122 this.related.manytoone = _.filter($state.current.data.relations, {type: 'manytoone'});
Matteo Scandoloee655a12016-12-19 15:38:43 -0800123 this.model = _.find(this.tableData, {id: parseInt($stateParams['id'], 10)});
Matteo Scandolo5d962a32017-08-01 18:16:14 -0700124 this.getRelatedModels(this.related, this.model);
Matteo Scandoloee655a12016-12-19 15:38:43 -0800125 }
Matteo Scandolo035c5932016-12-14 09:55:15 -0800126 });
127 }
128 );
Matteo Scandoloee655a12016-12-19 15:38:43 -0800129
130 // if it is a detail page
131 if ($stateParams['id']) {
132 this.list = false;
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800133
134 // if it is the create page
135 if ($stateParams['id'] === 'add') {
136 // generate a resource for an empty model
Matteo Scandolo47c53fc2017-03-23 14:11:32 -0700137 const endpoint = this.XosModelDiscovererService.getApiUrlFromModel(this.XosModelDiscovererService.get(this.data.model));
Matteo Scandolo80c3a652017-01-06 10:48:31 -0800138 const resource = this.ModelRest.getResource(endpoint);
139 this.model = new resource({});
140 }
Matteo Scandoloc8a58c82017-08-17 17:14:38 -0700141
142 this.XosKeyboardShortcut.registerKeyBinding({
143 key: 'A',
144 cb: () => this.XosDebug.toggleDebug('modelsTab'),
145 description: 'Toggle Debug tab in model details view'
146 }, 'view');
147
148 this.XosKeyboardShortcut.registerKeyBinding({
149 key: 'delete',
150 cb: () => {
151 this.$state.go(this.$state.current.name, {id: null});
152 },
153 description: 'Go back to the list view'
154 }, 'view');
155 }
156 // list page
157 else {
158 this.tableCfg.selectedRow = -1;
159
160 this.XosKeyboardShortcut.registerKeyBinding({
161 key: 'Tab',
162 cb: () => this.iterateItems(),
163 description: 'Iterate trough items in the list'
164 }, 'view');
165
166 this.XosKeyboardShortcut.registerKeyBinding({
167 key: 'Enter',
168 cb: () => {
169 if (this.tableCfg.selectedRow < 0) {
170 return;
171 }
172 this.$state.go(this.$state.current.name, {id: this.tableCfg.filteredData[this.tableCfg.selectedRow].id});
173 },
174 description: 'View details of selected item'
175 }, 'view');
176
177 this.XosKeyboardShortcut.registerKeyBinding({
178 key: 'Delete',
179 cb: () => {
180 if (this.tableCfg.selectedRow < 0) {
181 return;
182 }
183 const deleteFn = _.find(this.tableCfg.actions, {label: 'delete'});
184 deleteFn.cb(this.tableCfg.filteredData[this.tableCfg.selectedRow]);
185 },
186 description: 'View details of selected item'
187 }, 'view');
188
189 // FIXME XosKeyboardShortcut modifiers does not look to work
190 // this.XosKeyboardShortcut.registerKeyBinding({
191 // key: 'Tab',
192 // modifiers: ['alt'],
193 // cb: () => {
194 // this.tableCfg.selectedRow = -1;
195 // },
196 // description: 'Clear selected item'
197 // }, 'view');
Matteo Scandoloee655a12016-12-19 15:38:43 -0800198 }
Matteo Scandolo9f87f302016-12-13 18:11:10 -0800199 }
Matteo Scandolo00d97892016-12-23 17:53:12 -0800200
Matteo Scandoloc8a58c82017-08-17 17:14:38 -0700201 public iterateItems() {
202 const rowCount = this.tableCfg.filteredData.length > this.tableCfg.pagination.pageSize ? this.tableCfg.pagination.pageSize : this.tableCfg.filteredData.length;
203 if ((this.tableCfg.selectedRow + 1) < rowCount) {
204 this.tableCfg.selectedRow++;
205 }
206 else {
207 this.tableCfg.selectedRow = 0;
208 }
209 this.$scope.$apply();
210 }
Matteo Scandolo5d962a32017-08-01 18:16:14 -0700211
212 public getRelatedItemId(relation: IXosModelRelation, item: any): boolean {
213 return this.XosCrudRelation.existsRelatedItem(relation, item);
214 }
215
216 public getHumanReadableOnField(r: IXosModelRelation) {
217 return this.XosCrudRelation.getHumanReadableOnField(r, this.data.model);
218 }
219
220 public getRelatedModels(relations: {manytoone: IXosModelRelation[], onetomany: IXosModelRelation[]}, item: any) {
Matteo Scandoloa4718592017-08-10 14:54:51 -0700221 this.$log.debug(`[XosCrud] Managing relation for ${this.data.model}:`, relations);
Matteo Scandolo5d962a32017-08-01 18:16:14 -0700222
223 // loading many to one relations (you'll get a model)
224 _.forEach(relations.manytoone, (r: IXosModelRelation) => {
225 if (!item || !item[`${r.on_field.toLowerCase()}_id`]) {
226 return;
227 }
228
229 this.$log.debug(`[XosCrud] Loading manytoone relation with ${r.model} on ${r.on_field}`);
230
231 if (!angular.isDefined(this.relatedModels.manytoone[r.model])) {
232 this.relatedModels.manytoone[r.model] = {};
233 }
234
235 this.XosCrudRelation.getModel(r, item[`${r.on_field.toLowerCase()}_id`])
236 .then(res => {
237 this.relatedModels.manytoone[r.model][r.on_field] = res;
238 })
239 .catch(err => {
240 this.$log.error(`[XosCrud] Error loading manytoone relation with ${r.model} on ${r.on_field}`, err);
241 });
242 });
243
244 // loading onetomany relations (you'll get a list of models)
245 _.forEach(relations.onetomany, (r: IXosModelRelation) => {
246 if (!item) {
247 return;
248 }
249
250 this.$log.debug(`[XosCrud] Loading onetomany relation with ${r.model} on ${r.on_field}`);
251
252 if (!angular.isDefined(this.relatedModels.onetomany[r.model])) {
253 this.relatedModels.onetomany[r.model] = {};
254 }
255
256 this.XosCrudRelation.getModels(r, item.id)
257 .then(res => {
258 this.relatedModels.onetomany[r.model][r.on_field] = res;
259 })
260 .catch(err => {
261 this.$log.error(`[XosCrud] Error loading onetomany relation with ${r.model} on ${r.on_field}`, err);
262 });
263 });
Matteo Scandolo00d97892016-12-23 17:53:12 -0800264 }
Matteo Scandolo9f87f302016-12-13 18:11:10 -0800265}
266
267export const xosCrud: angular.IComponentOptions = {
268 template: require('./crud.html'),
269 controllerAs: 'vm',
270 controller: CrudController
271};