blob: 0fe94072e1f830ac5f4a0c21abffb68a0cde08f5 [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 Scandolo04f487c2017-09-12 10:37:48 -070030import {Subscription} from 'rxjs';
Matteo Scandolo63498472017-09-26 17:21:41 -070031import {IXosModeldefsCache} from '../../datasources/helpers/modeldefs.service';
Matteo Scandolo1aee1982017-02-17 08:33:23 -080032
33export interface IXosModelRelation {
34 model: string;
35 type: string;
Matteo Scandolo5d962a32017-08-01 18:16:14 -070036 on_field: string;
Matteo Scandolo9f87f302016-12-13 18:11:10 -080037}
38
39class CrudController {
Matteo Scandolo1aee1982017-02-17 08:33:23 -080040 static $inject = [
41 '$scope',
Matteo Scandolo5d962a32017-08-01 18:16:14 -070042 '$log',
Matteo Scandolo1aee1982017-02-17 08:33:23 -080043 '$state',
44 '$stateParams',
45 'XosModelStore',
46 'ConfigHelpers',
47 'ModelRest',
48 'StoreHelpers',
Matteo Scandolo5d962a32017-08-01 18:16:14 -070049 'XosModelDiscoverer',
Matteo Scandoloc8a58c82017-08-17 17:14:38 -070050 'XosCrudRelation',
51 'XosDebug',
Matteo Scandolo63498472017-09-26 17:21:41 -070052 'XosKeyboardShortcut',
53 'XosModeldefsCache'
Matteo Scandolo1aee1982017-02-17 08:33:23 -080054 ];
Matteo Scandolo9f87f302016-12-13 18:11:10 -080055
Matteo Scandolo5d962a32017-08-01 18:16:14 -070056 // bindings
57
Matteo Scandolo1aee1982017-02-17 08:33:23 -080058 public data: {model: string};
Matteo Scandolo9f87f302016-12-13 18:11:10 -080059 public tableCfg: IXosTableCfg;
Matteo Scandoloee655a12016-12-19 15:38:43 -080060 public formCfg: any;
Matteo Scandoloee655a12016-12-19 15:38:43 -080061 public baseUrl: string;
62 public list: boolean;
Matteo Scandolo580033a2017-08-17 11:16:39 -070063 public modelName: string;
64 public pluralTitle: string;
65 public singularTitle: string;
Matteo Scandolo9f87f302016-12-13 18:11:10 -080066 public tableData: any[];
Matteo Scandolo580033a2017-08-17 11:16:39 -070067 public model: any; // holds the real model
68 public modelDef: IXosModel;
Matteo Scandolo5d962a32017-08-01 18:16:14 -070069 public related: {manytoone: IXosModelRelation[], onetomany: IXosModelRelation[]} = {
70 manytoone: [],
71 onetomany: []
72 };
73 public relatedModels: {manytoone: any, onetomany: any} = {
74 manytoone: {},
75 onetomany: {}
76 };
Matteo Scandoloc8a58c82017-08-17 17:14:38 -070077 public debugTab: boolean;
Matteo Scandolo9f87f302016-12-13 18:11:10 -080078
Matteo Scandolo04f487c2017-09-12 10:37:48 -070079 private subscription: Subscription;
80
Matteo Scandolo9f87f302016-12-13 18:11:10 -080081 constructor(
Matteo Scandolof2c3ed62016-12-15 14:32:50 -080082 private $scope: angular.IScope,
Matteo Scandolo5d962a32017-08-01 18:16:14 -070083 private $log: angular.ILogService,
Matteo Scandoloee655a12016-12-19 15:38:43 -080084 private $state: angular.ui.IStateService,
85 private $stateParams: ng.ui.IStateParamsService,
Matteo Scandolo47860fe2017-02-02 12:05:55 -080086 private store: IXosModelStoreService,
Matteo Scandolo80c3a652017-01-06 10:48:31 -080087 private ConfigHelpers: IXosConfigHelpersService,
Matteo Scandolo04964232017-01-07 12:53:46 -080088 private ModelRest: IXosResourceService,
Matteo Scandolo1aee1982017-02-17 08:33:23 -080089 private StoreHelpers: IStoreHelpersService,
Matteo Scandolo5d962a32017-08-01 18:16:14 -070090 private XosModelDiscovererService: IXosModelDiscovererService,
Matteo Scandoloc8a58c82017-08-17 17:14:38 -070091 private XosCrudRelation: IXosCrudRelationService,
92 private XosDebug: IXosDebugService,
Matteo Scandolo63498472017-09-26 17:21:41 -070093 private XosKeyboardShortcut: IXosKeyboardShortcutService,
94 private XosModeldefsCache: IXosModeldefsCache
Matteo Scandolo9f87f302016-12-13 18:11:10 -080095 ) {
Matteo Scandoloa4718592017-08-10 14:54:51 -070096 this.$log.info('[XosCrud] Setup', $state.current.data);
Matteo Scandolo5d962a32017-08-01 18:16:14 -070097
Matteo Scandolo9f87f302016-12-13 18:11:10 -080098 this.data = this.$state.current.data;
Matteo Scandolo63498472017-09-26 17:21:41 -070099 this.modelDef = this.XosModeldefsCache.get(this.data.model);
Matteo Scandolo580033a2017-08-17 11:16:39 -0700100 this.modelName = this.modelDef.verbose_name ? this.modelDef.verbose_name : this.modelDef.name;
101 this.pluralTitle = this.ConfigHelpers.pluralize(this.modelName);
102 this.singularTitle = this.ConfigHelpers.pluralize(this.modelName, 1);
Matteo Scandolo9f87f302016-12-13 18:11:10 -0800103
Matteo Scandoloee655a12016-12-19 15:38:43 -0800104 this.list = true;
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800105
106 // TODO get the proper URL from model discoverer
Matteo Scandolo580033a2017-08-17 11:16:39 -0700107 this.baseUrl = '#/' + this.modelDef.clientUrl.replace(':id?', '');
Matteo Scandolo1aee1982017-02-17 08:33:23 -0800108
Matteo Scandolo580033a2017-08-17 11:16:39 -0700109 this.tableCfg = this.modelDef.tableCfg;
110 this.formCfg = this.modelDef.formCfg;
Matteo Scandoloee655a12016-12-19 15:38:43 -0800111
Matteo Scandolo63498472017-09-26 17:21:41 -0700112 // attach a redirect to the $save method
113 const originalSave = this.formCfg.actions[0].cb;
114 this.formCfg.actions[0].cb = (item, form: angular.IFormController) => {
115 originalSave(item, form)
116 .then(res => {
117 this.$state.go(this.$state.current, {id: res.id});
118 })
119 .catch(err => {
120 this.$log.error(`[XosCrud] Error while saving:`, item, err);
121 });
122 };
123
Matteo Scandoloc8a58c82017-08-17 17:14:38 -0700124 this.debugTab = this.XosDebug.status.modelsTab;
125 this.$scope.$on('xos.debug.status', (e, status: IXosDebugStatus) => {
126 this.debugTab = status.modelsTab;
127 this.$scope.$apply();
128 });
129
Matteo Scandoloee655a12016-12-19 15:38:43 -0800130 // 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 Scandolo63498472017-09-26 17:21:41 -0700137 const endpoint = this.XosModelDiscovererService.getApiUrlFromModel(this.XosModeldefsCache.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 Scandolo04f487c2017-09-12 10:37:48 -0700141 else {
142 this.subscription = this.store.get(this.data.model, $stateParams['id'])
143 .first(val => {
144 // NOTE emit an event only if we have an object, and only the first time we have it
145 return Object.keys(val).length > 0;
146 })
147 .subscribe(res => {
148 $scope.$evalAsync(() => {
149 this.related.onetomany = _.filter($state.current.data.relations, {type: 'onetomany'});
150 this.related.manytoone = _.filter($state.current.data.relations, {type: 'manytoone'});
151 this.model = res;
152 this.getRelatedModels(this.related, this.model);
153 });
154 });
155 }
Matteo Scandoloc8a58c82017-08-17 17:14:38 -0700156
157 this.XosKeyboardShortcut.registerKeyBinding({
158 key: 'A',
159 cb: () => this.XosDebug.toggleDebug('modelsTab'),
160 description: 'Toggle Debug tab in model details view'
161 }, 'view');
162
163 this.XosKeyboardShortcut.registerKeyBinding({
164 key: 'delete',
165 cb: () => {
166 this.$state.go(this.$state.current.name, {id: null});
167 },
168 description: 'Go back to the list view'
169 }, 'view');
170 }
171 // list page
172 else {
173 this.tableCfg.selectedRow = -1;
174
175 this.XosKeyboardShortcut.registerKeyBinding({
176 key: 'Tab',
177 cb: () => this.iterateItems(),
178 description: 'Iterate trough items in the list'
179 }, 'view');
180
181 this.XosKeyboardShortcut.registerKeyBinding({
182 key: 'Enter',
183 cb: () => {
184 if (this.tableCfg.selectedRow < 0) {
185 return;
186 }
187 this.$state.go(this.$state.current.name, {id: this.tableCfg.filteredData[this.tableCfg.selectedRow].id});
188 },
189 description: 'View details of selected item'
190 }, 'view');
191
192 this.XosKeyboardShortcut.registerKeyBinding({
193 key: 'Delete',
194 cb: () => {
195 if (this.tableCfg.selectedRow < 0) {
196 return;
197 }
198 const deleteFn = _.find(this.tableCfg.actions, {label: 'delete'});
199 deleteFn.cb(this.tableCfg.filteredData[this.tableCfg.selectedRow]);
200 },
201 description: 'View details of selected item'
202 }, 'view');
203
204 // FIXME XosKeyboardShortcut modifiers does not look to work
205 // this.XosKeyboardShortcut.registerKeyBinding({
206 // key: 'Tab',
207 // modifiers: ['alt'],
208 // cb: () => {
209 // this.tableCfg.selectedRow = -1;
210 // },
211 // description: 'Clear selected item'
212 // }, 'view');
Matteo Scandolo04f487c2017-09-12 10:37:48 -0700213
214 this.subscription = this.store.query(this.data.model)
215 .subscribe(
216 (event) => {
217 // NOTE Observable mess with $digest cycles, we need to schedule the expression later
218 $scope.$evalAsync(() => {
219 this.tableData = event;
220 });
221 }
222 );
Matteo Scandoloee655a12016-12-19 15:38:43 -0800223 }
Matteo Scandolo9f87f302016-12-13 18:11:10 -0800224 }
Matteo Scandolo00d97892016-12-23 17:53:12 -0800225
Matteo Scandolo04f487c2017-09-12 10:37:48 -0700226 $onDestroy() {
227 this.subscription.unsubscribe();
228 this.$log.info(`[XosCrud] Destroying component`);
229 }
230
Matteo Scandoloc8a58c82017-08-17 17:14:38 -0700231 public iterateItems() {
232 const rowCount = this.tableCfg.filteredData.length > this.tableCfg.pagination.pageSize ? this.tableCfg.pagination.pageSize : this.tableCfg.filteredData.length;
233 if ((this.tableCfg.selectedRow + 1) < rowCount) {
234 this.tableCfg.selectedRow++;
235 }
236 else {
237 this.tableCfg.selectedRow = 0;
238 }
239 this.$scope.$apply();
240 }
Matteo Scandolo5d962a32017-08-01 18:16:14 -0700241
242 public getRelatedItemId(relation: IXosModelRelation, item: any): boolean {
243 return this.XosCrudRelation.existsRelatedItem(relation, item);
244 }
245
246 public getHumanReadableOnField(r: IXosModelRelation) {
247 return this.XosCrudRelation.getHumanReadableOnField(r, this.data.model);
248 }
249
250 public getRelatedModels(relations: {manytoone: IXosModelRelation[], onetomany: IXosModelRelation[]}, item: any) {
Matteo Scandoloa4718592017-08-10 14:54:51 -0700251 this.$log.debug(`[XosCrud] Managing relation for ${this.data.model}:`, relations);
Matteo Scandolo5d962a32017-08-01 18:16:14 -0700252
253 // loading many to one relations (you'll get a model)
254 _.forEach(relations.manytoone, (r: IXosModelRelation) => {
255 if (!item || !item[`${r.on_field.toLowerCase()}_id`]) {
256 return;
257 }
258
259 this.$log.debug(`[XosCrud] Loading manytoone relation with ${r.model} on ${r.on_field}`);
260
261 if (!angular.isDefined(this.relatedModels.manytoone[r.model])) {
262 this.relatedModels.manytoone[r.model] = {};
263 }
264
265 this.XosCrudRelation.getModel(r, item[`${r.on_field.toLowerCase()}_id`])
266 .then(res => {
267 this.relatedModels.manytoone[r.model][r.on_field] = res;
268 })
269 .catch(err => {
270 this.$log.error(`[XosCrud] Error loading manytoone relation with ${r.model} on ${r.on_field}`, err);
271 });
272 });
273
274 // loading onetomany relations (you'll get a list of models)
275 _.forEach(relations.onetomany, (r: IXosModelRelation) => {
276 if (!item) {
277 return;
278 }
279
280 this.$log.debug(`[XosCrud] Loading onetomany relation with ${r.model} on ${r.on_field}`);
281
282 if (!angular.isDefined(this.relatedModels.onetomany[r.model])) {
283 this.relatedModels.onetomany[r.model] = {};
284 }
285
286 this.XosCrudRelation.getModels(r, item.id)
287 .then(res => {
288 this.relatedModels.onetomany[r.model][r.on_field] = res;
289 })
290 .catch(err => {
291 this.$log.error(`[XosCrud] Error loading onetomany relation with ${r.model} on ${r.on_field}`, err);
292 });
293 });
Matteo Scandolo00d97892016-12-23 17:53:12 -0800294 }
Matteo Scandolo9f87f302016-12-13 18:11:10 -0800295}
296
297export const xosCrud: angular.IComponentOptions = {
298 template: require('./crud.html'),
299 controllerAs: 'vm',
300 controller: CrudController
301};