· 6 years ago · Sep 20, 2019, 02:26 PM
1jQuery.sap.require('com.tutorial.service.measureobject.MeasurementObjectPackageTableFactory' + m_urlVersion);
2jQuery.sap.require('com.tutorial.service.measureobject.MeasurementObjectPKPrimaryInfoFactory' + m_urlVersion);
3jQuery.sap.require('com.tutorial.service.measureobject.MeasurementObjectAssignmentsPackageFactory' + m_urlVersion);
4jQuery.sap.require('com.tutorial.service.measureobject.MOPackageMappingFactory' + m_urlVersion);
5jQuery.sap.require("com.tutorial.util.Formatter" + m_urlVersion);
6
7var varPath;
8var contextID;
9var productName;
10var productID;
11var that;
12var moKey;
13var userID;
14var extendedAttributesTableData;
15var extendedAttributes;
16var globalType;
17var customExtAttr;
18var technicalName;
19
20sap.ui.controller("ui5_routing.AddPackage", {
21 //the method handleNavBack is triggered when the back button is pressed
22 handleNavBack: function (evt) {
23 this.resetField();
24 var router = sap.ui.core.UIComponent.getRouterFor(this);
25 var oHistory = sap.ui.core.routing.History.getInstance();
26 var sPreviousHash = oHistory.getPreviousHash();
27
28 if (sPreviousHash !== undefined) {
29 window.history.go(-1);
30 } else {
31 var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
32 router.navTo("main");
33 }
34
35 },
36
37 onInit: function () {
38 this.router = sap.ui.core.UIComponent.getRouterFor(this);
39 console.log("Hi in add for MO --" + this._oRouter);
40 this.router.attachRoutePatternMatched(this._handleRouteMatched, this);
41 that = this;
42 },
43
44 onStereorypeSelect: function (oEvent) {
45 var table = that.getView().byId(that.createId("addPackageTable"));
46 table.setVisible(true);
47
48 var stereoTypeList = oEvent.getParameters().value;
49 var stereoTypeArray = stereoTypeList.split('/');
50
51 var stereoType = stereoTypeArray[stereoTypeArray.length - 1];
52
53 that.loadTableData(stereoType);
54
55 },
56
57 loadTableData: function (stereoType) {
58 //to do
59 // 1. move this paths from here
60 //2. stereotype here is hardcoded, is not use the function parameter
61 var usageServicePath = "https://ifd.wdf.sap.corp/usag/morepository/MOREPOSITORY/Usage.xsodata";
62 var model = "/CL_ALL_ATTRIBUTES_FOR_STEREOTYPEParameters";
63 var viewPath = model + "(IP_STEREOTYPE_ID='" + stereoType + "')/Results";
64 that=this;
65 $.ajax({
66 async: true,
67 url: usageServicePath + viewPath,
68 type: 'GET',
69 cache: false,
70 dataType: 'JSON',
71 success: function (data) {
72 var results = data.d.results;
73 if (results.length > 0) {
74
75 that.bindTable(results);
76
77 } else {
78 that.bindTable([]);
79 }
80 },
81 error: function () {
82 //trace some errors
83 }
84 });
85
86 },
87
88
89 bindTable: function (results) {
90 var table = this.getView().byId(this.createId("addPackageTable"));
91 table.destroyItems();
92 that = this;
93 that.extendedAttributes = [];
94 for (var i = 0; i < results.length; i++) {
95 //to do -> put the correct fields
96 var attribute = results[i].NAME;
97 var description = results[i].DESCRIPTION;
98 var placeholder = results[i].DEFAULTVALUE;
99 if(placeholder == null || placeholder == undefined || placeholder == "")
100 {
101 placeholder = "Package " + attribute;
102 }
103
104
105 that.extendedAttributes.push(results[i].NAME);
106
107 var columnListItem = new sap.m.ColumnListItem({
108 cells: [
109 new sap.m.Label({
110 id: "Text" + attribute,
111 text: attribute
112 }),
113 this.quickhelp(new sap.m.Input({
114 //todo --> map the input fields to the attribute or counter etc..
115 id: "Value" + attribute,
116 value: placeholder,
117 required: true,
118 width: "80%"
119 }),description),
120 new sap.m.Text({
121 id: "Managed" + attribute,
122 text: "Stereotype"
123 })
124 ]
125 })
126
127 table.addItem(columnListItem);
128 }
129
130 for(var i = 0; i < customExtAttr.length; i++){
131 var attribute = customExtAttr[i].NAME;
132 var val = customExtAttr[i].VALUE;
133
134 var columnListItem = new sap.m.ColumnListItem({
135 cells: [
136 new sap.m.Label({
137 id: "Text" + attribute,
138 text: attribute
139 }),
140 new sap.m.Input({
141 //todo --> map the input fields to the attribute or counter etc..
142 id: "Value" + attribute,
143 value: val,
144 required: true,
145 width: "80%"
146 }),
147 new sap.m.Text({
148 id: "Managed" + attribute,
149 text: userID
150 })
151 ]
152 })
153
154 table.addItem(columnListItem);
155 }
156
157 },
158
159
160 AddRecord: function(oEvent){
161
162 var that = this;
163
164 var oDialogAddRow = sap.ui.getCore().byId(this.createId('Dialog'));
165 var oDialogSaveButton = sap.ui.getCore().byId(this.createId('oDialogSaveButton'));
166 oDialogAddRow.setTitle("ADD A NEW RECORD");
167 var oLayout = new sap.ui.commons.layout.MatrixLayout({
168 columns: 2,
169 width: "100%"
170 });
171
172 var oFirstLabel= sap.ui.getCore().byId(this.createId('oFirstLabel'));
173 var oFirstTF = sap.ui.getCore().byId(this.createId('attrid'));
174 oFirstTF.setValue('');
175 oLayout.createRow(oFirstLabel, oFirstTF);
176
177 var oSecondLabel = sap.ui.getCore().byId(this.createId('oSecondLabel'));
178 var oSecondTF = sap.ui.getCore().byId(this.createId('valueid'));
179 oSecondTF.setValue('');
180 oLayout.createRow(oSecondLabel, oSecondTF);
181
182 oDialogAddRow.addContent(oLayout);
183 oDialogAddRow.open();
184
185 },
186
187 saveRecord: function(oEvent){
188
189 var that = this;
190 var attrTable = sap.ui.getCore().byId(this.createId('addPackageTable'));
191 var oFirstTF = sap.ui.getCore().byId(this.createId('attrid'));
192 var oSecondTF = sap.ui.getCore().byId(this.createId('valueid'));
193 var attribute = oFirstTF.getValue();
194 var value = oSecondTF.getValue();
195 var existing = false;
196 attrTable.getItems().forEach(function(collListItem){
197 if(collListItem.getCells()[0].getText() == attribute){
198 existing = true;
199 }
200 })
201 if(attribute == "" || value == ""){
202 sap.m.MessageToast.show('Both values are mandatory!');
203 }
204 else if(attribute.indexOf(' ') > -1){
205 sap.m.MessageToast.show('Attribute name can not contain spaces');
206 }
207 else if(existing){
208 sap.m.MessageToast.show('Attribute allready exists');
209 }
210 else{
211 var columnListItem = new sap.m.ColumnListItem({
212
213 cells: [
214 new sap.m.Text({
215
216 text : attribute
217 }),
218 new sap.m.Input({
219
220 value : value,
221 width: "80%"
222 }),
223 new sap.m.Text({
224 text: userID
225 })
226
227 ],
228
229 type: 'Active'
230 })
231
232 attrTable.addItem(columnListItem);
233 customExtAttr.push({ DATATYPE: "String",
234 MANAGED_BY: userID,
235 NAME: attribute,
236 VALUE: value});
237 sap.ui.getCore().byId(this.createId('Dialog')).close();
238 }
239 },
240
241 DeleteRecord: function(){
242 var that = this;
243 var attrTable = sap.ui.getCore().byId(this.createId('addPackageTable'));
244 var toBeDeleted = attrTable.getSelectedItems();
245 toBeDeleted.forEach(function(attr){
246 if(attr.getCells()[2].getText() != "Stereotype"){
247 customExtAttr = customExtAttr.filter(toDelete => toDelete.NAME != attr.getCells()[0].getText() );
248
249 attrTable.removeItem(attr);
250 attr.destroy();
251 }
252 else{
253 sap.m.MessageToast.show('One or more attributes can not be deleted because they are managed by the stereotype');;
254 }
255 })
256 },
257
258 //the method _handleRouteMatched is triggered after navigation to this page (this is necessary for routing)
259 _handleRouteMatched: function (oEvent) {
260
261 var oParam = oEvent.getParameter("name");
262 globalType = oEvent.getParameter("arguments").contextPath;
263 if (oParam !== "AddPackage") {
264 return;
265 }
266 that = this;
267 that.resetField();
268 varPath = oEvent.getParameter("arguments").contextPath;
269 contextID = oEvent.getParameter("arguments").contextID;
270
271 console.log("Inside : " + varPath);
272
273 var oDataMOdel = new sap.ui.model.odata.ODataModel(m_xsodata);
274 oDataMOdel.read("/CV_PACKAGES_ALLParameters(PAR_NODE=\'" + varPath + "\')/Results", null, null, true, fSuccessPack, fErrorPack);
275 function fSuccessPack(oEvent) {
276
277 var oModelMo = new sap.ui.model.json.JSONModel();
278 oModelMo.setData(oEvent.results[0]);
279 that.getView().setModel(oModelMo);
280
281 oModelMo.updateBindings(true);
282 productName = oEvent.results[0].PRODUCT_NAME;
283 productID = oEvent.results[0].KEY;
284 var type = oEvent.results[0].TYPE;
285 sap.ui.getCore().byId("productTextForPackageId").setText(productName);
286 }
287
288 function fErrorPack(oEvent) {
289 }
290
291 var oDataMOdel = new sap.ui.model.odata.ODataModel(m_xsodata);
292 oDataMOdel.read("/CV_NODE_PARENTSParameters(P_NODEID=\'" + varPath + "\')/Results/?$orderby=LEVEL", null, null, true, fSuccess, fError);
293 function fSuccess(oEvent) {
294
295 var parents = [];
296 parents = oEvent.results;
297 sap.ui.getCore().byId("PanelIdPakageNav").removeAllContentMiddle();
298 for (var i in parents) {
299 if (i != 0) {
300 var breadcrumb = sap.ui.getCore().byId("PanelIdPakageNav").addContentMiddle(new sap.m.Text({
301 text: ">"
302
303 }).addStyleClass("textForArrow"))
304 }
305
306 var oLink = new sap.m.Button({
307 text: parents[i].NAME,
308 enabled: false
309 });
310 oLink.nodeid = parents[i].RESULT_NODE;
311 if (i == parents.length - 1)
312 oLink.addStyleClass("lastBreadcrumb");
313 var breadcrumb = sap.ui.getCore().byId("PanelIdPakageNav").addContentMiddle(oLink);
314 }
315 }
316 ;
317 function fError(oEvent) {
318 console.log("An error occured while reading Parents Data!")
319 }
320 ;
321
322
323
324 jQuery.ajax({
325 url: userUrl,
326 method: 'GET',
327 dataType: 'json',
328 success: function (user) {
329 username = user.USER;
330 userID = username;
331 var url = employeeUrl + "?query=" + userID;
332 sap.ui.getCore().byId('ownerFieldId').setText(userID);
333 },
334 error: function (XHR, Status, Error) {
335
336 var error = Error;
337 console.log(XHR.responseText);
338 username = "default";
339 }
340 });
341
342
343 var oDataModelStereotypes = new sap.ui.model.odata.ODataModel(m_xsodata);
344 // oDataModelStereotypes.read("/CL_STEREOTYPESParameters" + "(IP_OBJ_TYPE='" + 'PACKAGE' + "')/Results", null, null, true, fSuccessStereotypes, fErrorStereotypes);
345 oDataModelStereotypes.read("/CL_STEREOTYPE_HIER_DETAILParameters" + "(IP_TYPE='" + 'PACKAGE' + "')/Results", null, null, true, fSuccessStereotypes, fErrorStereotypes);
346
347 function fSuccessStereotypes(oEvent) {
348 data = oEvent.results;
349 that.dataForStereotypes(data);
350 };
351
352 function fErrorStereotypes(oEvent) {
353 console.log("An error occured while reading the data!")
354 };
355
356 customExtAttr = [];
357
358 },
359 //the method generateKey is triggered from addMo method to generate a new key for the new psckage that will be added
360 generateKey: function () {
361 var key = Math.floor((Math.random() * 10000) + 1);
362 return key.toString();
363 },
364
365 validateExtendedAttributeField: function(){
366
367 if(this.extendedAttributes == null || this.extendedAttributes == undefined){
368 //todo
369 }else{
370 for(var attribute of this.extendedAttributes){
371 var name = attribute;
372 var value = sap.ui.getCore().byId('Value' + attribute).getValue();
373 var managedBy = sap.ui.getCore().byId('Managed' + attribute).getText();
374
375
376 if(value == "" || value == null || value == undefined){
377 var inputField = sap.ui.getCore().byId('Value' + attribute);
378 inputField.setValueState("Error");
379 sap.m.MessageToast.show("Please fill in Extended Attribute Values");
380
381 }
382 }
383 }
384
385 },
386
387 //the method addMO is triggered when it's intended to add a package (add button is pressed)
388 //before adding the new entry, the technical name is checked to see if it already exists
389 // a new entry is added in usag.morepository::Z_USAG_PACKAGE with the type 'custom'
390 addMo: function (evt) {
391
392 var packageService = com.tutorial.service.measureobject.MeasurementObjectPKPrimaryInfoFactory.getInstance();
393 that=this;
394
395 var key_value;
396 packageService.loadModel({
397 endpointParam: varPath,
398 successFunc: function (moData, response) {
399 var oModelMo = new sap.ui.model.json.JSONModel();
400 oModelMo.setData(moData.results[0]);
401
402 if (moData.results[0].TYPE = "product") {
403 key_value = moData.results[0].KEY;
404 } else {
405 key_value = varPath;
406 }
407 },
408 errorFunc: function () {
409 console.log('error');
410 }
411 });
412 var specialCharacters = /[!@#$%^&*()+\-=\[\]{};':"\\|,<>\/?]/;
413
414 var moService = com.tutorial.service.measureobject.MeasurementObjectPackageTableFactory.getInstance();
415 var packageMappingService = com.tutorial.service.measureobject.MOPackageMappingFactory.getInstance();
416 moKey = this.generateKey();
417 var dateNew = com.tutorial.util.Formatter.GetUnformattedDate();
418 var that = this;
419
420 //only scenario where type is not custom is at root level User-defined
421 var typeDetect = "custom";
422
423 if(globalType == "User-defined"){
424 typeDetect = "cup"
425 }
426
427
428
429 var moOb = {
430
431 "NAME": this.byId('nameFieldId').getValue(),
432 "TECHNICAL_NAME": this.byId('technicalNameFieldId').getValue(),
433 "KEY": moKey,
434 "DESCRIPTION": this.byId('descriptionFieldId').getValue(),
435 "STEREOTYPE": this.byId('stereotypeFieldId1').getValue().split('/').pop(),
436 "OWNER": sap.ui.getCore().byId('ownerFieldId').getText(),
437 "ACTIVE": 'yes',
438 "TYPE": typeDetect,
439 "STEP": "2",
440 "PARENTID": varPath,
441 "INDICATOR": 0,
442 "MAIN_TECHNICAL_NAME": this.byId('technicalNameFieldId').getValue() + '_Copy',
443 "CHANGED_BY": sap.ui.getCore().byId('ownerFieldId').getText(),
444 "CHANGED_DATE": dateNew,
445 "CHANGED_AT": dateNew
446
447 };
448
449 var packageMapping =
450 {
451 "PARENT_KEY": varPath,
452 "CHILD_KEY": moKey,
453 "CHANGED_BY": sap.ui.getCore().byId('ownerFieldId').getText(),
454 "CHANGED_AT": dateNew
455 };
456
457 var found = false;
458
459 if (moOb.TECHNICAL_NAME && moOb.NAME) {
460
461 var specialCharactersFlag=false;
462 if (specialCharacters.test(moOb.TECHNICAL_NAME) == true) {
463 that.byId('technicalNameFieldId').setValueState("Error");
464 var msg = 'Special Characters are not allowed for Technical Name';
465 sap.m.MessageToast.show(msg);
466 specialCharactersFlag=true;
467
468 }
469
470 if (specialCharacters.test(moOb.NAME) == true) {
471 that.byId('nameFieldId').setValueState("Error");
472 var msg = 'Special Characters are not allowed for Name';
473 sap.m.MessageToast.show(msg);
474 specialCharactersFlag=true;
475
476 }
477
478 if(specialCharactersFlag == true) {
479 return;
480 }
481
482 }
483
484 var oDataMOdel = new sap.ui.model.odata.ODataModel(m_xsodata);
485 oDataMOdel.read("/PACKTABLE?$filter=TECHNICAL_NAME eq '" + moOb.TECHNICAL_NAME + "' or NAME eq '" + moOb.NAME + "'", null, null, true, fSuccess, fError);
486 function fSuccess(oEvent) {
487
488 if (oEvent.results.length != 0) {
489 var name = false;
490 var techname = false;
491 for (var i in oEvent.results) {
492 if (oEvent.results[i].TECHNICAL_NAME === moOb.TECHNICAL_NAME) {
493 techname = true;
494
495 }
496 }
497
498 var oMeasureOb = new sap.ui.model.json.JSONModel(oEvent.results);
499 found = true;
500 console.log(oEvent.results[0]);
501 }
502
503
504
505 if (techname) {
506 that.byId('technicalNameFieldId').setValueState("Error");
507 var msg = 'Technical Name already exists';
508 sap.m.MessageToast.show(msg);
509 }
510
511// else {
512// var nameErr = that.byId('technicalNameFieldId').getValueState();
513// console.log("nume eroare" + nameErr);
514//
515// if (nameErr == "Error") {
516//
517// sap.m.MessageToast.show("Make sure you fill in the allowed characters only.")
518// }
519 else {
520 moService.createModel({
521 moData: moOb,
522 successFunc: function (notesData) {
523 packageMappingService.createModel({
524 moData: packageMapping,
525 successFunc: function () {
526 that.addExtendedAttributes();
527
528 },
529 errorFunc: function () { }
530 });
531
532 var msg = 'Package successfully added';
533
534 that.resetField();
535 that.byId('technicalNameFieldId').setValue("");
536 that.byId('technicalNameFieldId').setValueState("None");
537
538 sap.m.MessageToast.show(msg, {
539 duration: 800,
540 onClose: function () {
541
542 if(globalType == "User-defined"){
543 var query = "cup";
544 router.navTo("main", {
545 query :
546 {
547 tab : query
548 }
549 }, true /* without history */);
550 }else{
551 router.navTo("Detail", {
552 contextPath: varPath,
553 contextID: "1"
554 });
555 }
556
557 }
558 });
559
560 },
561 errorFunc: function () {
562 var msg = 'failed to add the Package';
563 sap.m.MessageToast.show(msg);
564 }
565 });
566 }
567 }
568// }
569 ;
570 function fError(oEvent) {
571 console.log("An error occured while reading Package Data!")
572 }
573 ;
574// } else {
575 if (!moOb.TECHNICAL_NAME && !moOb.NAME) {
576 this.byId('technicalNameFieldId').setValueState("Error");
577 this.byId('nameFieldId').setValueState("Error");
578 sap.m.MessageToast.show("Please fill in Technical name and Name");
579 } else if (!moOb.TECHNICAL_NAME) {
580 this.byId('technicalNameFieldId').setValueState("Error");
581 sap.m.MessageToast.show("Please fill in Technical name");
582 } else if (!moOb.NAME) {
583 this.byId('nameFieldId').setValueState("Error");
584 sap.m.MessageToast.show("Please fill in name");
585 }
586
587 },
588
589// },
590
591 saveExtendedAttributes: function (moKey) {
592 extendedAttributesTableData = {
593 packId: moKey,
594 extendedAttributesValues: []
595 };
596
597 if(this.extendedAttributes == null || this.extendedAttributes == undefined)
598 return;
599 this.extendedAttributes.forEach(attribute => {
600 var name = attribute;
601 var value = sap.ui.getCore().byId('Value' + attribute).getValue();
602 var managedBy = sap.ui.getCore().byId('Managed' + attribute).getText();
603 extendedAttributesTableData.extendedAttributesValues.push({name: name, value: value, managedBy: managedBy});
604 });
605
606 },
607
608
609 // after the package was successfully added, the method resetField is called to reset all the fields to null value
610 resetField: function () {
611 this.byId('technicalNameFieldId').setValue("");
612 this.byId('technicalNameFieldId').setValueState("None");
613 this.byId('nameFieldId').setValue("");
614 this.byId('descriptionFieldId').setValue("");
615 this.byId('stereotypeFieldId1').clearSelection();
616// var combo = this.byId(this.createId("stereotypeFieldId1"));
617// combo.destroyItems();
618 var table = this.byId(this.createId("addPackageTable"));
619 table.destroyItems();
620 sap.ui.getCore().byId('ownerFieldId').setText("");
621 },
622
623 //provide the list of stereotypes to the input field
624 dataForStereotypes: function (data) {
625 var newData = new Array();
626 newData.push({ "ID": "", "NAME": "" });
627 for (var i = 0; i < data.length; i++)
628 newData.push({ "ID": data[i].ID, "NAME": data[i].PATH });
629 var oModel = new sap.ui.model.json.JSONModel();
630 oModel.setData({ modelData: newData });
631
632 var stereotypeFieldId = this.getView().byId(this.createId('stereotypeFieldId1'));
633 stereotypeFieldId.setModel(oModel);
634 stereotypeFieldId.bindItems({
635 path: "/modelData",
636 template: new sap.ui.core.ListItem({
637 key: "{ID}",
638 text: "{NAME}"
639 })
640 });
641
642 },
643
644 addExtendedAttributes: function(){
645 var that=this;
646 var table = this.getView().byId(this.createId("addPackageTable"));
647 table.getItems().forEach(function(ColListItem){
648 var attribute={};
649 attribute.name = ColListItem.getCells()[0].getText();
650 attribute.value = ColListItem.getCells()[1].getValue();
651 attribute.managedBy = ColListItem.getCells()[2].getText();
652 that.saveAttribute(attribute);
653 })
654 },
655
656 saveAttribute: function(attribute){
657 var that = this;
658 var obj_type = 'Z_USAG_PACKAGE';
659 var action_type = 'insert';
660 var datatype = 'String';
661
662
663 var url = UpdateExtendedAttributesDataURL + "?obj_type=" + obj_type + "&action_type=" + action_type + "&datatype=" + datatype + "&obj_id=" + moKey + "&attribute=" + attribute.name + "&value=" + attribute.value + "&managed_by=" + attribute.managedBy;
664 jQuery.ajax({
665 url: url,
666 method: 'GET',
667 //dataType: 'json',
668 success: function(XHR, Status, Error)
669 {
670 if(Error){console.log(Error)}
671
672 },
673 error: function(XHR, Status, Error)
674 {
675 console.log(Error)
676 }
677 });
678
679 },
680
681 //quickhelp function
682 quickhelp: function(oControl, sText, bCustomize){
683 // create the RichTooltip control
684 var oRichTooltip = new sap.ui.commons.RichTooltip({
685 text: sText,
686 title: "Quick Help",
687 imageSrc: "images/Tip.gif"
688 });
689 // Change position and durations if required
690 if (bCustomize) {
691 oRichTooltip.setMyPosition("begin top");
692 oRichTooltip.setAtPosition("end top");
693 oRichTooltip.setOpenDuration(300);
694 oRichTooltip.setCloseDuration(300);
695 }
696 // add it to the control
697 oControl.setTooltip(oRichTooltip);
698 // return the control itself (makes this function a
699 // decorator function)
700 return oControl;
701 },
702});