· 6 years ago · Sep 20, 2019, 02:46 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 varPath = oEvent.getParameter("arguments").contextPath;
268 contextID = oEvent.getParameter("arguments").contextID;
269
270 console.log("Inside : " + varPath);
271
272 var oDataMOdel = new sap.ui.model.odata.ODataModel(m_xsodata);
273 oDataMOdel.read("/CV_PACKAGES_ALLParameters(PAR_NODE=\'" + varPath + "\')/Results", null, null, true, fSuccessPack, fErrorPack);
274 function fSuccessPack(oEvent) {
275
276 var oModelMo = new sap.ui.model.json.JSONModel();
277 oModelMo.setData(oEvent.results[0]);
278 that.getView().setModel(oModelMo);
279
280 oModelMo.updateBindings(true);
281 productName = oEvent.results[0].PRODUCT_NAME;
282 productID = oEvent.results[0].KEY;
283 var type = oEvent.results[0].TYPE;
284 sap.ui.getCore().byId("productTextForPackageId").setText(productName);
285 }
286
287 function fErrorPack(oEvent) {
288 }
289
290 var oDataMOdel = new sap.ui.model.odata.ODataModel(m_xsodata);
291 oDataMOdel.read("/CV_NODE_PARENTSParameters(P_NODEID=\'" + varPath + "\')/Results/?$orderby=LEVEL", null, null, true, fSuccess, fError);
292 function fSuccess(oEvent) {
293
294 var parents = [];
295 parents = oEvent.results;
296 sap.ui.getCore().byId("PanelIdPakageNav").removeAllContentMiddle();
297 for (var i in parents) {
298 if (i != 0) {
299 var breadcrumb = sap.ui.getCore().byId("PanelIdPakageNav").addContentMiddle(new sap.m.Text({
300 text: ">"
301
302 }).addStyleClass("textForArrow"))
303 }
304
305 var oLink = new sap.m.Button({
306 text: parents[i].NAME,
307 enabled: false
308 });
309 oLink.nodeid = parents[i].RESULT_NODE;
310 if (i == parents.length - 1)
311 oLink.addStyleClass("lastBreadcrumb");
312 var breadcrumb = sap.ui.getCore().byId("PanelIdPakageNav").addContentMiddle(oLink);
313 }
314 }
315 ;
316 function fError(oEvent) {
317 console.log("An error occured while reading Parents Data!")
318 }
319 ;
320
321
322
323 jQuery.ajax({
324 url: userUrl,
325 method: 'GET',
326 dataType: 'json',
327 success: function (user) {
328 username = user.USER;
329 userID = username;
330 var url = employeeUrl + "?query=" + userID;
331 sap.ui.getCore().byId('ownerFieldId').setText(userID);
332 },
333 error: function (XHR, Status, Error) {
334
335 var error = Error;
336 console.log(XHR.responseText);
337 username = "default";
338 }
339 });
340
341
342 var oDataModelStereotypes = new sap.ui.model.odata.ODataModel(m_xsodata);
343 // oDataModelStereotypes.read("/CL_STEREOTYPESParameters" + "(IP_OBJ_TYPE='" + 'PACKAGE' + "')/Results", null, null, true, fSuccessStereotypes, fErrorStereotypes);
344 oDataModelStereotypes.read("/CL_STEREOTYPE_HIER_DETAILParameters" + "(IP_TYPE='" + 'PACKAGE' + "')/Results", null, null, true, fSuccessStereotypes, fErrorStereotypes);
345
346 function fSuccessStereotypes(oEvent) {
347
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 var oDataMOdel = new sap.ui.model.odata.ODataModel(m_xsodata);
483 oDataMOdel.read("/PACKTABLE?$filter=TECHNICAL_NAME eq '" + moOb.TECHNICAL_NAME + "' or NAME eq '" + moOb.NAME + "'", null, null, true, fSuccess, fError);
484 function fSuccess(oEvent) {
485 if (oEvent.results.length != 0) {
486 var name = false;
487 var techname = false;
488 for (var i in oEvent.results) {
489 if (oEvent.results[i].TECHNICAL_NAME === moOb.TECHNICAL_NAME) {
490 techname = true;
491
492 }
493 }
494
495 var oMeasureOb = new sap.ui.model.json.JSONModel(oEvent.results);
496 found = true;
497 console.log(oEvent.results[0]);
498 }
499
500
501
502 if (techname) {
503 that.byId('technicalNameFieldId').setValueState("Error");
504 var msg = 'Technical Name already exists';
505 sap.m.MessageToast.show(msg);
506 }
507
508 else {
509 var nameErr = that.byId('technicalNameFieldId').getValueState();
510 console.log("nume eroare" + nameErr);
511
512 if (nameErr == "Error") {
513
514 sap.m.MessageToast.show("Make sure you fill in the allowed characters only.")
515 } else {
516 moService.createModel({
517 moData: moOb,
518 successFunc: function (notesData) {
519 packageMappingService.createModel({
520 moData: packageMapping,
521 successFunc: function () { that.addExtendedAttributes(); },
522 errorFunc: function () { }
523 });
524
525 var msg = 'Package successfully added';
526
527 that.resetField();
528 that.byId('technicalNameFieldId').setValue("");
529 that.byId('technicalNameFieldId').setValueState("None");
530
531 sap.m.MessageToast.show(msg, {
532 duration: 800,
533 onClose: function () {
534
535 if(globalType == "User-defined"){
536 var query = "cup";
537 router.navTo("main", {
538 query :
539 {
540 tab : query
541 }
542 }, true /* without history */);
543 }else{
544 router.navTo("Detail", {
545 contextPath: varPath,
546 contextID: "1"
547 });
548 }
549
550 }
551 });
552
553 },
554 errorFunc: function () {
555 var msg = 'failed to add the Package';
556 sap.m.MessageToast.show(msg);
557 }
558 });
559 }
560 }
561 }
562 ;
563 function fError(oEvent) {
564 console.log("An error occured while reading Package Data!")
565 }
566 ;
567 } else {
568 if (!moOb.TECHNICAL_NAME && !moOb.NAME) {
569 this.byId('technicalNameFieldId').setValueState("Error");
570 this.byId('nameFieldId').setValueState("Error");
571 sap.m.MessageToast.show("Please fill in Technical name and Name");
572 } else if (!moOb.TECHNICAL_NAME) {
573 this.byId('technicalNameFieldId').setValueState("Error");
574 sap.m.MessageToast.show("Please fill in Technical name");
575 } else if (!moOb.NAME) {
576 this.byId('nameFieldId').setValueState("Error");
577 sap.m.MessageToast.show("Please fill in name");
578 }
579
580 }
581
582 },
583
584 saveExtendedAttributes: function (moKey) {
585 extendedAttributesTableData = {
586 packId: moKey,
587 extendedAttributesValues: []
588 };
589
590 if(this.extendedAttributes == null || this.extendedAttributes == undefined)
591 return;
592 this.extendedAttributes.forEach(attribute => {
593 var name = attribute;
594 var value = sap.ui.getCore().byId('Value' + attribute).getValue();
595 var managedBy = sap.ui.getCore().byId('Managed' + attribute).getText();
596 extendedAttributesTableData.extendedAttributesValues.push({name: name, value: value, managedBy: managedBy});
597 });
598
599 },
600
601
602 // after the package was successfully added, the method resetField is called to reset all the fields to null value
603 resetField: function () {
604 this.byId('technicalNameFieldId').setValue("");
605 this.byId('technicalNameFieldId').setValueState("None");
606 this.byId('nameFieldId').setValue("");
607 this.byId('descriptionFieldId').setValue("");
608 this.byId('stereotypeFieldId1').setValue("");
609 var table = this.byId(this.createId("addPackageTable"));
610 table.destroyItems();
611 sap.ui.getCore().byId('ownerFieldId').setText("");
612 },
613
614 //provide the list of stereotypes to the input field
615 dataForStereotypes: function (data) {
616 var newData = new Array();
617 newData.push({ "ID": "", "NAME": "" });
618 for (var i = 0; i < data.length; i++)
619 newData.push({ "ID": data[i].ID, "NAME": data[i].PATH });
620 var oModel = new sap.ui.model.json.JSONModel();
621 oModel.setData({ modelData: newData });
622
623 var stereotypeFieldId = this.getView().byId(this.createId('stereotypeFieldId1'));
624 stereotypeFieldId.setModel(oModel);
625 stereotypeFieldId.bindItems({
626 path: "/modelData",
627 template: new sap.ui.core.ListItem({
628 key: "{ID}",
629 text: "{NAME}"
630 })
631 });
632
633 },
634
635 addExtendedAttributes: function(){
636 var that=this;
637 var table = this.getView().byId(this.createId("addPackageTable"));
638 table.getItems().forEach(function(ColListItem){
639 var attribute={};
640 attribute.name = ColListItem.getCells()[0].getText();
641 attribute.value = ColListItem.getCells()[1].getValue();
642 attribute.managedBy = ColListItem.getCells()[2].getText();
643 that.saveAttribute(attribute);
644 })
645 },
646
647 saveAttribute: function(attribute){
648 var that = this;
649 var obj_type = 'Z_USAG_PACKAGE';
650 var action_type = 'insert';
651 var datatype = 'String';
652
653
654 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;
655 jQuery.ajax({
656 url: url,
657 method: 'GET',
658 //dataType: 'json',
659 success: function(XHR, Status, Error)
660 {
661 if(Error){console.log(Error)}
662
663 },
664 error: function(XHR, Status, Error)
665 {
666 console.log(Error)
667 }
668 });
669
670 },
671
672 //quickhelp function
673 quickhelp: function(oControl, sText, bCustomize){
674 // create the RichTooltip control
675 var oRichTooltip = new sap.ui.commons.RichTooltip({
676 text: sText,
677 title: "Quick Help",
678 imageSrc: "images/Tip.gif"
679 });
680 // Change position and durations if required
681 if (bCustomize) {
682 oRichTooltip.setMyPosition("begin top");
683 oRichTooltip.setAtPosition("end top");
684 oRichTooltip.setOpenDuration(300);
685 oRichTooltip.setCloseDuration(300);
686 }
687 // add it to the control
688 oControl.setTooltip(oRichTooltip);
689 // return the control itself (makes this function a
690 // decorator function)
691 return oControl;
692 },
693});