· 5 years ago · Mar 10, 2020, 11:22 AM
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);
6jQuery.sap.require("com.tutorial.util.Utils" + m_urlVersion);
7
8
9var varPath;
10var contextID;
11var productName;
12var productID;
13var that;
14var that2;
15var moKey;
16var userID;
17var extendedAttributesTableData;
18var extendedAttributes;
19var globalType;
20var customExtAttr;
21var technicalName;
22var valueListArray;
23
24sap.ui.controller("ui5_routing.AddPackage", {
25 //the method handleNavBack is triggered when the back button is pressed
26 handleNavBack: function (evt) {
27 this.resetField();
28 var router = sap.ui.core.UIComponent.getRouterFor(this);
29 var oHistory = sap.ui.core.routing.History.getInstance();
30 var sPreviousHash = oHistory.getPreviousHash();
31
32 if (sPreviousHash !== undefined) {
33 window.history.go(-1);
34 } else {
35 var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
36 router.navTo("main");
37 }
38
39 },
40
41 onInit: function () {
42 this.router = sap.ui.core.UIComponent.getRouterFor(this);
43 console.log("Hi in add for MO --" + this._oRouter);
44 this.router.attachRoutePatternMatched(this._handleRouteMatched, this);
45 that = this;
46 that2=this;
47 },
48
49 onStereorypeSelect: function (oEvent) {
50 var table = that.getView().byId(that.createId("addPackageTable"));
51 table.setVisible(true);
52
53 var stereoTypeList = oEvent.getParameters().value;
54 var stereoTypeArray = stereoTypeList.split('/');
55
56 var stereoType = stereoTypeArray[stereoTypeArray.length - 1];
57
58 that.loadTableData(stereoType);
59
60 },
61
62 loadTableData: function (stereoType) {
63 jQuery.ajax({
64 url : "https://ifd.wdf.sap.corp/usag/morepository/MOREPOSITORY/Usage.xsodata/ATTRIBUTE_VALUES",
65 method : 'GET',
66 dataType : 'xml',
67 success : function(data) {
68
69 valueListArray = []; //destroy all elements to prevent duplication
70 var tempArray = data.getElementsByTagName("m:properties");
71 for(var x = 0;x < tempArray.length;x++){
72 var attribute_ID = tempArray[x].childNodes[1].innerHTML;
73 var value_ID = tempArray[x].childNodes[2].innerHTML;
74 var value_text = tempArray[x].childNodes[3].innerHTML;
75 var description = tempArray[x].childNodes[4].innerHTML;
76
77 valueListArray.push({ATTRIBUTE_ID: attribute_ID, //Creates objects based on number of entries in EXTDEF_LIST_VALUES HANA table
78 VALUE_ID: value_ID,
79 VALUE_TEXT: value_text,
80 DESCRIPTION: description});
81
82 }
83
84
85 },
86 error : function(XHR, Status, Error) {
87 alert(Error);
88 }
89 });
90
91 //to do
92 // 1. move this paths from here
93 //2. stereotype here is hardcoded, is not use the function parameter
94 var usageServicePath = com.tutorial.util.Utils.getUsageURL();;
95 var model = "/CL_ALL_ATTRIBUTES_FOR_STEREOTYPEParameters";
96 var viewPath = model + "(IP_STEREOTYPE_ID='" + stereoType + "')/Results";
97 that=this;
98 $.ajax({
99 async: true,
100 url: usageServicePath + viewPath,
101 type: 'GET',
102 cache: false,
103 dataType: 'JSON',
104 success: function (data) {
105 var results = data.d.results;
106 if (results.length > 0) {
107
108 that.bindTable(results);
109
110 } else {
111 that.bindTable([]);
112 }
113 },
114 error: function () {
115 //trace some errors
116 }
117 });
118
119 },
120
121
122 bindTable: function (results) {
123 var table = this.getView().byId(this.createId("addPackageTable"));
124 table.destroyItems();
125
126 that = this;
127 that.extendedAttributes = [];
128 for (var i = 0; i < results.length; i++) {
129 //to do -> put the correct fields
130 var attributeListValues = valueListArray.filter(x => x.ATTRIBUTE_ID === results[i].NAME); //Filters on entries in EXTDEF_LIST_VALUES to get specific attribute entries as objects for loop instance
131
132 var attribute = results[i].NAME;
133 var description = results[i].DESCRIPTION;
134 var placeholder = results[i].DEFAULTVALUE;
135 var displaytext = results[i].NAME;
136 var calculatedExpression = results[i].CALCULATED_EXPRESSION;
137 if(calculatedExpression != null && calculatedExpression != 'null' && calculatedExpression != ''){
138 calculatedExpression = calculatedExpression.replace('{', '()()').replace('}', '<><>')
139 }
140 var mandatory = false;
141 if(placeholder == null || placeholder == undefined || placeholder == "")
142 {
143 placeholder = "Package " + attribute;
144 }
145
146 if(results[i].MANDATORY =='Y'){
147 mandatory = true;
148 displaytext = displaytext + '*';
149 }
150
151 var managedBy = calculatedExpression == null || calculatedExpression == 'null' || calculatedExpression == '' ? "Stereotype" : "Stereotype_Calculated" ;
152 var type = managedBy == "SYSTEM" || managedBy =="Stereotype_Calculated" ? 'Inactive' :'Active';
153
154 that.extendedAttributes.push(results[i].NAME);
155
156 if(attributeListValues.length == 0){
157 var columnListItem = new sap.m.ColumnListItem({
158 cells: [
159 new sap.m.Label({
160 id: "Text" + attribute,
161 text: displaytext
162 }),
163 this.quickhelp(new sap.m.Input({
164 //todo --> map the input fields to the attribute or counter etc..
165 id: "Value" + attribute,
166 value: placeholder,
167 required: mandatory,
168 width: "80%",
169 editable: type=='Active' ? true : false,
170 change : function(){that.CalculateExtendedAttributes()}
171 }),description),
172 new sap.m.Text({
173 id: "Managed" + attribute,
174 text: managedBy
175 }),
176 new sap.m.Label({
177 id: "Stereotype_Calculated" + attribute,
178 text: calculatedExpression,
179 customData : [new sap.ui.core.CustomData({'key':'calculatedAtr','value':calculatedExpression})],
180 visible : false
181 })
182 ]
183 })
184 }else{
185 var arraySpecificValues = new Array(); //create array to store current loop attribute values as ListItems
186
187 for(var x = 0; x < attributeListValues.length;x++){
188 var oItem = new sap.ui.core.ListItem(); //create ListItem for each value of current loop attribute to be used by ComboBox
189 oItem.setText(attributeListValues[x].VALUE_TEXT);
190 oItem.setAdditionalText(attributeListValues[x].DESCRIPTION);
191 arraySpecificValues.push(oItem);
192 }
193
194 var columnListItem = new sap.m.ColumnListItem({
195
196 cells: [
197 new sap.m.Label({
198 id: "Text" + attribute,
199 text: displaytext
200 }),
201 this.quickhelp( new sap.m.ComboBox({
202 id: "Value" + attribute,
203 value: results[i].VALUE,
204 items: arraySpecificValues,
205 showSecondaryValues: true
206 }),description),
207 new sap.m.Text({
208 id: "Managed" + attribute,
209 text: managedBy
210 }),
211 new sap.m.Label({
212 id: "Stereotype_Calculated" + attribute,
213 text: calculatedExpression,
214 customData : [new sap.ui.core.CustomData({'key' : 'calculatedAtr','value' : calculatedExpression})],
215 visible : false
216 })
217
218 ],
219 type:type
220 })
221 }
222
223
224 table.addItem(columnListItem);
225 }
226
227 for(var i = 0; i < customExtAttr.length; i++){
228 var attribute = customExtAttr[i].NAME;
229 var val = customExtAttr[i].VALUE;
230
231
232 var columnListItem = new sap.m.ColumnListItem({
233 cells: [
234 new sap.m.Label({
235 id: "Text" + attribute,
236 text: attribute
237 }),
238 new sap.m.Input({
239 //todo --> map the input fields to the attribute or counter etc..
240 id: "Value" + attribute,
241 value: "Test",
242 required: true,
243 width: "80%"
244 }),
245 new sap.m.Text({
246 id: "Managed" + attribute,
247 text: userID
248 })
249 ]
250 })
251
252
253 table.addItem(columnListItem);
254 }
255 that.CalculateExtendedAttributes();
256
257 },
258
259
260 AddRecord: function(oEvent){
261
262 var that = this;
263
264 var oDialogAddRow = sap.ui.getCore().byId(this.createId('Dialog'));
265 var oDialogSaveButton = sap.ui.getCore().byId(this.createId('oDialogSaveButton'));
266 oDialogAddRow.setTitle("ADD A NEW RECORD");
267 var oLayout = new sap.ui.commons.layout.MatrixLayout({
268 columns: 2,
269 width: "100%"
270 });
271
272 var oFirstLabel= sap.ui.getCore().byId(this.createId('oFirstLabel'));
273 var oFirstTF = sap.ui.getCore().byId(this.createId('attrid'));
274 oFirstTF.setValue('');
275 oLayout.createRow(oFirstLabel, oFirstTF);
276
277 var oSecondLabel = sap.ui.getCore().byId(this.createId('oSecondLabel'));
278 var oSecondTF = sap.ui.getCore().byId(this.createId('valueid'));
279 oSecondTF.setValue('');
280 oLayout.createRow(oSecondLabel, oSecondTF);
281
282 oDialogAddRow.addContent(oLayout);
283 oDialogAddRow.open();
284
285 },
286
287 saveRecord: function(oEvent){
288
289 var that = this;
290 var attrTable = sap.ui.getCore().byId(this.createId('addPackageTable'));
291 var oFirstTF = sap.ui.getCore().byId(this.createId('attrid'));
292 var oSecondTF = sap.ui.getCore().byId(this.createId('valueid'));
293 var attribute = oFirstTF.getValue();
294 var value = oSecondTF.getValue();
295 var existing = false;
296 attrTable.getItems().forEach(function(collListItem){
297 if(collListItem.getCells()[0].getText() == attribute){
298 existing = true;
299 }
300 })
301 if(attribute == "" || value == ""){
302 sap.m.MessageToast.show('Both values are mandatory!');
303 }
304 else if(attribute.indexOf(' ') > -1){
305 sap.m.MessageToast.show('Attribute name can not contain spaces');
306 }
307 else if(existing){
308 sap.m.MessageToast.show('Attribute allready exists');
309 }
310 else{
311 var columnListItem = new sap.m.ColumnListItem({
312
313 cells: [
314 new sap.m.Text({
315
316 text : attribute
317 }),
318 new sap.m.Input({
319
320 value : value,
321 width: "80%"
322 }),
323 new sap.m.Text({
324 text: userID
325 })
326
327 ],
328
329 type: 'Active'
330 })
331
332 attrTable.addItem(columnListItem);
333 customExtAttr.push({ DATATYPE: "String",
334 MANAGED_BY: userID,
335 NAME: attribute,
336 VALUE: value});
337 sap.ui.getCore().byId(this.createId('Dialog')).close();
338 }
339 },
340
341
342
343 DeleteRecord: function(){
344 var that = this;
345 var attrTable = sap.ui.getCore().byId(this.createId('addPackageTable'));
346 var toBeDeleted = attrTable.getSelectedItems();
347 toBeDeleted.forEach(function(attr){
348 if(attr.getCells()[2].getText() != "Stereotype" && attr.getCells()[2].getText() != "Stereotype_Calculated"){
349 customExtAttr = customExtAttr.filter(toDelete => toDelete.NAME != attr.getCells()[0].getText() );
350
351 attrTable.removeItem(attr);
352 attr.destroy();
353 }
354 else{
355 sap.m.MessageToast.show('One or more attributes can not be deleted because they are managed by the stereotype');;
356 }
357 })
358 },
359
360 CalculateExtendedAttributes: function(){
361 var existingAttributes = {};
362
363 var attrTable = sap.ui.getCore().byId(this.createId('addPackageTable'));
364 var tableItems= attrTable.getItems();
365
366 for(var i=0;i< tableItems.length;i++){
367 var currentListItem = tableItems[i].getCells();
368 if(currentListItem[2].getText()=="Stereotype"){
369 var attrName ="";
370 var attrValue = "";
371 try{
372 attrName = currentListItem[0].getId().split("Text")[1];
373 attrValue = currentListItem[1].getValue();
374 }
375 catch(error){
376 console.log(error.toString());
377 }
378 existingAttributes[attrName] = attrValue;
379 }
380 }
381
382 var currentObject = {
383
384 "NAME": this.byId('nameFieldId').getValue(),
385 "TECHNICAL_NAME": this.byId('technicalNameFieldId').getValue(),
386 "DESCRIPTION": this.byId('descriptionFieldId').getValue(),
387 "STEREOTYPE": this.byId('stereotypeFieldId1').getValue().split('/').pop(),
388 "OWNER": sap.ui.getCore().byId('ownerFieldId').getText(),
389 "ACTIVE": 'yes',
390 "TYPE": "custom",
391 "STEP": "2",
392 "PARENTID": varPath,
393 "INDICATOR": 0
394
395 };
396
397 for(var i=0;i< tableItems.length;i++){
398 var currentListItem = tableItems[i].getCells();
399 if(currentListItem[2].getText()=="Stereotype_Calculated"){
400 var calculatedExpression = currentListItem[3].getCustomData()[0].getValue();
401 calculatedExpression = calculatedExpression.replace( '()()', '{').replace( '<><>', '}');
402
403 var attributeValue = "";
404
405 try{
406 eval(calculatedExpression);
407 }
408 catch (error){
409 console.log(error.toString());
410 }
411
412 currentListItem[1].setValue(attributeValue);
413 }
414 }
415
416
417
418 },
419
420 //the method _handleRouteMatched is triggered after navigation to this page (this is necessary for routing)
421 _handleRouteMatched: function (oEvent) {
422
423 var oParam = oEvent.getParameter("name");
424 globalType = oEvent.getParameter("arguments").contextPath;
425 if (oParam !== "AddPackage") {
426 return;
427 }
428 that = this;
429 varPath = oEvent.getParameter("arguments").contextPath;
430 contextID = oEvent.getParameter("arguments").contextID;
431
432 console.log("Inside : " + varPath);
433
434 var oDataMOdel = new sap.ui.model.odata.ODataModel(m_xsodata);
435 oDataMOdel.read("/CV_PACKAGES_ALLParameters(PAR_NODE=\'" + varPath + "\')/Results", null, null, true, fSuccessPack, fErrorPack);
436 function fSuccessPack(oEvent) {
437
438 var oModelMo = new sap.ui.model.json.JSONModel();
439 oModelMo.setData(oEvent.results[0]);
440 that.getView().setModel(oModelMo);
441
442 oModelMo.updateBindings(true);
443 productName = oEvent.results[0].PRODUCT_NAME;
444 productID = oEvent.results[0].KEY;
445 var type = oEvent.results[0].TYPE;
446 sap.ui.getCore().byId("productTextForPackageId").setText(productName);
447 }
448
449 function fErrorPack(oEvent) {
450 }
451
452 var oDataMOdel = new sap.ui.model.odata.ODataModel(m_xsodata);
453 oDataMOdel.read("/CV_NODE_PARENTSParameters(P_NODEID=\'" + varPath + "\')/Results/?$orderby=LEVEL", null, null, true, fSuccess, fError);
454 function fSuccess(oEvent) {
455
456 var parents = [];
457 parents = oEvent.results;
458 sap.ui.getCore().byId("PanelIdPakageNav").removeAllContentMiddle();
459 for (var i in parents) {
460 if (i != 0) {
461 var breadcrumb = sap.ui.getCore().byId("PanelIdPakageNav").addContentMiddle(new sap.m.Text({
462 text: ">"
463
464 }).addStyleClass("textForArrow"))
465 }
466
467 var oLink = new sap.m.Button({
468 text: parents[i].NAME,
469 enabled: false
470 });
471 oLink.nodeid = parents[i].RESULT_NODE;
472 if (i == parents.length - 1)
473 oLink.addStyleClass("lastBreadcrumb");
474 var breadcrumb = sap.ui.getCore().byId("PanelIdPakageNav").addContentMiddle(oLink);
475 }
476 }
477 ;
478 function fError(oEvent) {
479 console.log("An error occured while reading Parents Data!")
480 }
481 ;
482
483 jQuery.ajax({
484 url : "https://ifd.wdf.sap.corp/usag/morepository/MOREPOSITORY/Usage.xsodata/ATTRIBUTE_VALUES",
485 method : 'GET',
486 dataType : 'xml',
487 success : function(data) {
488
489 valueListArray = []; //destroy all elements to prevent duplication
490 var tempArray = data.getElementsByTagName("m:properties");
491 for(var x = 0;x < tempArray.length;x++){
492 var attribute_ID = tempArray[x].childNodes[1].innerHTML;
493 var value_ID = tempArray[x].childNodes[2].innerHTML;
494 var value_text = tempArray[x].childNodes[3].innerHTML;
495 var description = tempArray[x].childNodes[4].innerHTML;
496
497 valueListArray.push({ATTRIBUTE_ID: attribute_ID, //Creates objects based on number of entries in EXTDEF_LIST_VALUES HANA table
498 VALUE_ID: value_ID,
499 VALUE_TEXT: value_text,
500 DESCRIPTION: description});
501 }
502
503 },
504 error : function(XHR, Status, Error) {
505 alert(Error);
506 }
507 });
508
509
510 jQuery.ajax({
511 url: userUrl,
512 method: 'GET',
513 dataType: 'json',
514 success: function (user) {
515 username = user.USER;
516 userID = username;
517 var url = employeeUrl + "?query=" + userID;
518 sap.ui.getCore().byId('ownerFieldId').setText(userID);
519 },
520 error: function (XHR, Status, Error) {
521
522 var error = Error;
523 console.log(XHR.responseText);
524 username = "default";
525 }
526 });
527
528
529 var oDataModelStereotypes = new sap.ui.model.odata.ODataModel(m_xsodata);
530 // oDataModelStereotypes.read("/CL_STEREOTYPESParameters" + "(IP_OBJ_TYPE='" + 'PACKAGE' + "')/Results", null, null, true, fSuccessStereotypes, fErrorStereotypes);
531 oDataModelStereotypes.read("/CL_STEREOTYPE_HIER_DETAILParameters" + "(IP_TYPE='" + 'PACKAGE' + "')/Results", null, null, true, fSuccessStereotypes, fErrorStereotypes);
532
533 function fSuccessStereotypes(oEvent) {
534
535 data = oEvent.results;
536 that.dataForStereotypes(data);
537 };
538
539 function fErrorStereotypes(oEvent) {
540 console.log("An error occured while reading the data!")
541 };
542
543 customExtAttr = [];
544
545 },
546 //the method generateKey is triggered from addMo method to generate a new key for the new psckage that will be added
547 generateKey: function () {
548 var key = Math.floor((Math.random() * 10000) + 1);
549 return key.toString();
550 },
551
552 validateExtendedAttributeField: function(){
553
554 if(this.extendedAttributes == null || this.extendedAttributes == undefined){
555 return true
556 }else{
557 for(var attribute of this.extendedAttributes){
558 var name = attribute;
559 var value = sap.ui.getCore().byId('Value' + attribute).getValue();
560 var managedBy = sap.ui.getCore().byId('Managed' + attribute).getText();
561 var mandatory = sap.ui.getCore().byId('Value' + attribute).getRequired(); ;
562
563
564 if(value == "" || value == null || value == undefined){
565 if(mandatory == true){
566 var inputField = sap.ui.getCore().byId('Value' + attribute);
567 inputField.setValueState("Error");
568 sap.m.MessageToast.show("Please fill in the required Extended Attribute Values");
569 return false;
570 }
571
572 }
573 }
574 }
575 return true;
576
577 },
578
579 checkSameMoPackName: function(technicalName){
580
581 var url = com.tutorial.util.Utils.getServerBaseURL() + "/usag/morepository/MOREPOSITORY/WebContent/checkMoChildren.xsjs" + "?parent_key=" + technicalName; // + "&child_key=" + child_key + "&action_type=" + action_type + "&changed_By=" + changed_By + "&changed_at=" + changed_at + "&pkgchanged_Date=" + pkgchanged_Date;
582 var result = [];
583 jQuery.ajax({
584 url: url,
585 async: false,
586 method: 'GET',
587 dataType: 'json',
588 success: function(response)
589 {
590 for(var i = 0 ; i < response.length; i++){
591 result.push(response[i]);
592 }
593
594
595 },
596 error: function(error){
597 alert("error");
598 }
599
600 });
601 return result;
602 },
603 //the method addMO is triggered when it's intended to add a package (add button is pressed)
604 //before adding the new entry, the technical name is checked to see if it already exists
605 // a new entry is added in usag.morepository::Z_USAG_PACKAGE with the type 'custom'
606 addMo: function (evt) {
607 that2.CalculateExtendedAttributes();
608
609 var packageService = com.tutorial.service.measureobject.MeasurementObjectPKPrimaryInfoFactory.getInstance();
610 that=this;
611
612 var key_value;
613 packageService.loadModel({
614 endpointParam: varPath,
615 successFunc: function (moData, response) {
616 var oModelMo = new sap.ui.model.json.JSONModel();
617 oModelMo.setData(moData.results[0]);
618
619 if (moData.results[0].TYPE = "product") {
620 key_value = moData.results[0].KEY;
621 } else {
622 key_value = varPath;
623 }
624 },
625 errorFunc: function () {
626 console.log('error');
627 }
628 });
629 var specialCharactersName = /[!@#$%^&*+\=\[\]{};'"\\|,<>\/?]/;
630 var specialCharactersTechnicalName = /[!@#$%^&*()+\=\[\]{};':"\\|,<>\/?]/;
631
632 var moService = com.tutorial.service.measureobject.MeasurementObjectPackageTableFactory.getInstance();
633 var packageMappingService = com.tutorial.service.measureobject.MOPackageMappingFactory.getInstance();
634 moKey = this.generateKey();
635 var dateNew = com.tutorial.util.Formatter.GetUnformattedDate();
636 var that = this;
637
638 if(!that.validateExtendedAttributeField()){
639 return;
640 }
641
642 //only scenario where type is not custom is at root level User-defined
643 var typeDetect = "custom";
644
645 if(globalType == "User-defined"){
646 typeDetect = "cup"
647 }
648
649
650
651 var moOb = {
652
653 "NAME": this.byId('nameFieldId').getValue(),
654 "TECHNICAL_NAME": this.byId('technicalNameFieldId').getValue(),
655 "KEY": moKey,
656 "DESCRIPTION": this.byId('descriptionFieldId').getValue(),
657 "STEREOTYPE": this.byId('stereotypeFieldId1').getValue().split('/').pop(),
658 "OWNER": sap.ui.getCore().byId('ownerFieldId').getText(),
659 "ACTIVE": 'yes',
660 "TYPE": typeDetect,
661 "STEP": "2",
662 "PARENTID": varPath,
663 "INDICATOR": 0,
664 "MAIN_TECHNICAL_NAME": this.byId('technicalNameFieldId').getValue() + '_Copy',
665 "CHANGED_BY": sap.ui.getCore().byId('ownerFieldId').getText(),
666 "CHANGED_DATE": dateNew,
667 "CHANGED_AT": dateNew
668
669 };
670
671
672
673 var packageMapping =
674 {
675 "PARENT_KEY": varPath,
676 "CHILD_KEY": moKey,
677 "CHANGED_BY": sap.ui.getCore().byId('ownerFieldId').getText(),
678 "CHANGED_AT": dateNew,
679 "STEREOTYPE":'CUSTOM'
680 };
681
682 var found = false;
683
684 if(varPath != "" && varPath != undefined){
685 var resultCheck = this.checkSameMoPackName(varPath);
686 for(var packageTechnicalName of resultCheck){
687 if(packageTechnicalName == moOb.TECHNICAL_NAME){
688 that.byId('technicalNameFieldId').setValueState("Error");
689 var msg = "Due to technical restrictions in the processing systems it is not allowed to have MO's and Packages with the same technical name assigned" +
690 " to the same parent package. Please use another technical name or change the assignment";
691 sap.m.MessageToast.show(msg);
692 return;
693 }
694
695 }
696
697 }
698
699 if (moOb.TECHNICAL_NAME && moOb.NAME) {
700 that.byId('technicalNameFieldId').setValueState("None");
701 that.byId('nameFieldId').setValueState("None");
702
703 var specialCharactersFlag=false;
704 if (specialCharactersTechnicalName.test(moOb.TECHNICAL_NAME) == true) {
705 that.byId('technicalNameFieldId').setValueState("Error");
706 var msg = 'Special Characters are not allowed for Technical Name';
707 sap.m.MessageToast.show(msg);
708 specialCharactersFlag=true;
709
710 }
711
712 if (specialCharactersName.test(moOb.NAME) == true) {
713 that.byId('nameFieldId').setValueState("Error");
714 var msg = 'Special Characters are not allowed for Name';
715 sap.m.MessageToast.show(msg);
716 specialCharactersFlag=true;
717
718 }
719
720 if(specialCharactersFlag == true) {
721 return;
722 }
723 var oDataMOdel = new sap.ui.model.odata.ODataModel(m_xsodata);
724
725 var share = "Y";
726 var authObj = {USER: userID, ID_PACKAGE: moOb.KEY, SHARE_EDIT: share};
727 oDataMOdel.create('/USERS_PACKAGES', authObj, null, function(){
728 ;
729 },function(){
730 sap.m.MessageToast.show("Share failed");
731 });
732
733
734 oDataMOdel.read("/PACKTABLE?$filter=TECHNICAL_NAME eq '" + moOb.TECHNICAL_NAME + "' or NAME eq '" + moOb.NAME + "'", null, null, true, fSuccess, fError);
735 function fSuccess(oEvent) {
736 if (oEvent.results.length != 0) {
737 var name = false;
738 var techname = false;
739 for (var i in oEvent.results) {
740 if (oEvent.results[i].TECHNICAL_NAME === moOb.TECHNICAL_NAME) {
741 techname = true;
742
743 }
744 }
745
746 var oMeasureOb = new sap.ui.model.json.JSONModel(oEvent.results);
747 found = true;
748 console.log(oEvent.results[0]);
749 }
750
751
752
753 if (techname) {
754 that.byId('technicalNameFieldId').setValueState("Error");
755 var msg = 'Technical Name already exists';
756 sap.m.MessageToast.show(msg);
757 }
758
759 else {
760 var nameErr = that.byId('technicalNameFieldId').getValueState();
761 console.log("nume eroare" + nameErr);
762
763 if (nameErr == "Error") {
764
765 sap.m.MessageToast.show("Make sure you fill in the allowed characters only.")
766 } else {
767 moService.createModel({
768 moData: moOb,
769 successFunc: function (notesData) {
770 packageMappingService.createModel({
771 moData: packageMapping,
772 successFunc: function () { that.addExtendedAttributes(); },
773 errorFunc: function () { }
774 });
775
776 var msg = 'Package successfully added';
777
778 that.resetField();
779 that.byId('technicalNameFieldId').setValue("");
780 that.byId('technicalNameFieldId').setValueState("None");
781
782 sap.m.MessageToast.show(msg, {
783 duration: 800,
784 onClose: function () {
785
786 if(globalType == "User-defined"){
787 var query = "cup";
788 router.navTo("main", {
789 query :
790 {
791 tab : query
792 }
793 }, true /* without history */);
794 }else{
795 router.navTo("Detail", {
796 contextPath: varPath,
797 contextID: "1"
798 });
799 }
800
801 }
802 });
803
804 },
805 errorFunc: function () {
806 var msg = 'failed to add the Package';
807 sap.m.MessageToast.show(msg);
808 }
809 });
810 }
811 }
812 }
813 ;
814 function fError(oEvent) {
815 console.log("An error occured while reading Package Data!")
816 }
817 ;
818 } else {
819 if (!moOb.TECHNICAL_NAME && !moOb.NAME) {
820 this.byId('technicalNameFieldId').setValueState("Error");
821 this.byId('nameFieldId').setValueState("Error");
822 sap.m.MessageToast.show("Please fill in Technical name and Name");
823 } else if (!moOb.TECHNICAL_NAME) {
824 this.byId('technicalNameFieldId').setValueState("Error");
825 sap.m.MessageToast.show("Please fill in Technical name");
826 } else if (!moOb.NAME) {
827 this.byId('nameFieldId').setValueState("Error");
828 sap.m.MessageToast.show("Please fill in name");
829 }
830
831 }
832
833 },
834
835 saveExtendedAttributes: function (moKey) {
836 extendedAttributesTableData = {
837 packId: moKey,
838 extendedAttributesValues: []
839 };
840
841 if(this.extendedAttributes == null || this.extendedAttributes == undefined)
842 return;
843 this.extendedAttributes.forEach(attribute => {
844 var name = attribute;
845 var value = sap.ui.getCore().byId('Value' + attribute).getValue();
846 var managedBy = sap.ui.getCore().byId('Managed' + attribute).getText();
847 extendedAttributesTableData.extendedAttributesValues.push({name: name, value: value, managedBy: managedBy});
848 });
849
850 },
851
852
853 // after the package was successfully added, the method resetField is called to reset all the fields to null value
854 resetField: function () {
855 this.byId('technicalNameFieldId').setValue("");
856 this.byId('technicalNameFieldId').setValueState("None");
857 this.byId('nameFieldId').setValue("");
858 this.byId('descriptionFieldId').setValue("");
859 this.byId('stereotypeFieldId1').setValue("");
860 var table = this.byId(this.createId("addPackageTable"));
861 table.destroyItems();
862 sap.ui.getCore().byId('ownerFieldId').setText("");
863 },
864
865 //provide the list of stereotypes to the input field
866 dataForStereotypes: function (data) {
867 var newData = new Array();
868 newData.push({ "ID": "", "NAME": "" });
869 for (var i = 0; i < data.length; i++)
870 newData.push({ "ID": data[i].ID, "NAME": data[i].PATH });
871 var oModel = new sap.ui.model.json.JSONModel();
872 oModel.setData({ modelData: newData });
873
874 var stereotypeFieldId = this.getView().byId(this.createId('stereotypeFieldId1'));
875 stereotypeFieldId.setModel(oModel);
876 stereotypeFieldId.bindItems({
877 path: "/modelData",
878 template: that.quickhelp (new sap.ui.core.ListItem({
879 key: "{ID}",
880 text: "{NAME}"
881 }), "{= (${DESCRIPTION} !== null && ${DESCRIPTION} !== 'null' && ${DESCRIPTION} !== '') ? ${DESCRIPTION} : 'No description available'}")
882 });
883
884 },
885
886 addExtendedAttributes: function(){
887 var that=this;
888 var table = this.getView().byId(this.createId("addPackageTable"));
889 table.getItems().forEach(function(ColListItem){
890 var attribute={};
891 attribute.name = ColListItem.getCells()[0].getText();
892 if(attribute.name[attribute.name.length-1] == '*'){
893 attribute.name = attribute.name.slice(0, -1);
894 }
895 attribute.value = ColListItem.getCells()[1].getValue();
896 attribute.managedBy = ColListItem.getCells()[2].getText();
897 that.saveAttribute(attribute);
898 })
899 },
900
901 saveAttribute: function(attribute){
902 var that = this;
903 var obj_type = 'Z_USAG_PACKAGE';
904 var action_type = 'insert';
905 var datatype = 'String';
906
907
908 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;
909 jQuery.ajax({
910 url: url,
911 method: 'GET',
912 //dataType: 'json',
913 success: function(XHR, Status, Error)
914 {
915 if(Error){console.log(Error)}
916
917 },
918 error: function(XHR, Status, Error)
919 {
920 console.log(Error)
921 }
922 });
923
924 },
925
926 //quickhelp function
927 quickhelp: function(oControl, sText, bCustomize){
928 // create the RichTooltip control
929 var oRichTooltip = new sap.ui.commons.RichTooltip({
930 text: sText,
931 title: "Quick Help",
932 imageSrc: "images/Tip.gif"
933 });
934 // Change position and durations if required
935 if (bCustomize) {
936 oRichTooltip.setMyPosition("begin top");
937 oRichTooltip.setAtPosition("end top");
938 oRichTooltip.setOpenDuration(300);
939 oRichTooltip.setCloseDuration(300);
940 }
941 // add it to the control
942 oControl.setTooltip(oRichTooltip);
943 // return the control itself (makes this function a
944 // decorator function)
945 return oControl;
946 },
947});