github.com/mdaxf/iac@v0.0.0-20240519030858-58a061660378/controllers/trans/trans.go (about) 1 package trans 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "io/ioutil" 7 "time" 8 9 //"log" 10 "net/http" 11 12 "github.com/gin-gonic/gin" 13 "github.com/google/uuid" 14 "go.mongodb.org/mongo-driver/bson" 15 "go.mongodb.org/mongo-driver/bson/primitive" 16 17 "github.com/mdaxf/iac/config" 18 "github.com/mdaxf/iac/engine/trancode" 19 "github.com/mdaxf/iac/engine/types" 20 "github.com/mdaxf/iac/logger" 21 22 "github.com/mdaxf/iac/documents" 23 24 "github.com/mdaxf/iac/controllers/common" 25 ) 26 27 type TranCodeController struct { 28 } 29 30 // ExecuteTranCode executes the transaction code based on the request context. 31 // It retrieves the user information from the request, fetches the transaction code data, 32 // and executes the transaction flow. The outputs of the transaction are returned in the response. 33 func (e *TranCodeController) ExecuteTranCode(ctx *gin.Context) { 34 /* jsonString, err := json.Marshal(ctx.Request) 35 if err != nil { 36 fmt.Println("Error marshaling json:", err) 37 return 38 } 39 log.Println(string(jsonString)) */ 40 iLog := logger.Log{ModuleName: logger.API, User: "System", ControllerName: "TranCode"} 41 startTime := time.Now() 42 defer func() { 43 elapsed := time.Since(startTime) 44 iLog.PerformanceWithDuration("controllers.trans.ExecuteTranCode", elapsed) 45 }() 46 /* 47 defer func() { 48 if err := recover(); err != nil { 49 iLog.Error(fmt.Sprintf("ExecuteTranCode defer error: %s", err)) 50 ctx.JSON(http.StatusBadRequest, gin.H{"error": err}) 51 } 52 }() 53 */ 54 _, userno, clientid, err := common.GetRequestUser(ctx) 55 if err != nil { 56 iLog.Error(fmt.Sprintf("GetRequestUser error: %s", err)) 57 ctx.JSON(http.StatusBadRequest, gin.H{"error": err}) 58 return 59 } 60 61 iLog.User = userno 62 iLog.ClientID = clientid 63 64 //var tcdata TranCodeData 65 tcdata, err := getDataFromRequest(ctx) 66 67 iLog.Info(fmt.Sprintf("Start process transaction code %s's %s: %s", tcdata.TranCode, "Execute", tcdata.Inputs)) 68 69 //tcode, err := e.getTransCode(tcdata.TranCode) 70 filter := bson.M{"trancodename": tcdata.TranCode, "isdefault": true} 71 72 tcode, err := documents.DocDBCon.QueryCollection("Transaction_Code", filter, nil) 73 74 if err != nil { 75 iLog.Error(fmt.Sprintf("Get transaction code %s's error", tcdata.TranCode)) 76 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 77 return 78 } 79 iLog.Debug(fmt.Sprintf("transaction code %s's data: %s", tcdata.TranCode, tcode)) 80 jsonString, err := json.Marshal(tcode[0]) 81 if err != nil { 82 83 iLog.Error(fmt.Sprintf("Error marshaling json:", err.Error())) 84 return 85 } 86 87 iLog.Debug(fmt.Sprintf("transaction code %s's json: %s", tcdata.TranCode, string(jsonString))) 88 /*trancode := types.TranCode{} 89 err = json.Unmarshal(jsonString, &trancode) 90 if err != nil { 91 iLog.Error(fmt.Sprintf("Error unmarshaling json:", err.Error())) 92 return 93 } */ 94 code, err := trancode.Configtoobj(string(jsonString)) 95 if err != nil { 96 iLog.Error(fmt.Sprintf("Error unmarshaling json:", err.Error())) 97 return 98 } 99 100 /*var inputs_json map[string]interface{} 101 err = json.Unmarshal([]byte(tcdata.inputs), &inputs_json) 102 if err != nil { 103 iLog.Error(fmt.Sprintf("Error unmarshaling json:", err.Error())) 104 inputs_json = nil 105 } 106 iLog.Debug(fmt.Sprintf("transaction code %s's json inputs: %s", tcdata.TranCode, inputs_json)) 107 */ 108 systemsessions := make(map[string]interface{}) 109 systemsessions["UserNo"] = userno 110 systemsessions["ClientID"] = clientid 111 tf := trancode.NewTranFlow(code, tcdata.Inputs, systemsessions, nil, nil, nil) 112 outputs, err := tf.Execute() 113 114 if err == nil { 115 iLog.Debug(fmt.Sprintf("End process transaction code %s's %s ", tcdata.TranCode, "Execute")) 116 ctx.JSON(http.StatusOK, gin.H{"Outputs": outputs}) 117 return 118 } else { 119 iLog.Error(fmt.Sprintf("End process transaction code %s's %s with error %s", tcdata.TranCode, "Execute", err.Error())) 120 ctx.JSON(http.StatusBadRequest, gin.H{"execution failed": err.Error()}) 121 } 122 } 123 124 func (e *TranCodeController) TestTranCode(ctx *gin.Context) { 125 iLog := logger.Log{ModuleName: logger.API, User: "System", ControllerName: "TestTranCode"} 126 startTime := time.Now() 127 defer func() { 128 elapsed := time.Since(startTime) 129 iLog.PerformanceWithDuration("controllers.trans.TestTranCode", elapsed) 130 }() 131 defer func() { 132 if err := recover(); err != nil { 133 iLog.Error(fmt.Sprintf("ExecuteTranCode defer error: %s", err)) 134 ctx.JSON(http.StatusBadRequest, gin.H{"error": err}) 135 } 136 }() 137 138 requestobj, clientid, user, err := common.GetRequestBodyandUserbyJson(ctx) 139 if err != nil { 140 iLog.Error(fmt.Sprintf("Get request information Error: %v", err)) 141 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 142 return 143 } 144 iLog.ClientID = clientid 145 iLog.User = user 146 147 iLog.Debug(fmt.Sprintf("Test transaction code with request: %s", logger.ConvertJson(requestobj))) 148 149 tcobj := requestobj["trancodeobj"].(map[string]interface{}) 150 151 iLog.Debug(fmt.Sprintf("Test transaction code with tcobj: %s", logger.ConvertJson(tcobj))) 152 153 inputs := requestobj["inputs"].(map[string]interface{}) 154 155 iLog.Debug(fmt.Sprintf("Test transaction code with inputs: %s", logger.ConvertJson(inputs))) 156 157 remotedebug := requestobj["remote"].(bool) 158 159 iLog.Debug(fmt.Sprintf("Remote Debug available? %v", remotedebug)) 160 /* 161 data:{ 162 "trancodeobj": tccode, 163 "inputs": inputs, 164 } 165 166 167 */ 168 169 iLog.Info(fmt.Sprintf("Start process transaction code %s's %s: %s", tcobj["TranCodeName"], "Test", inputs)) 170 171 tcobjJSON, err := json.Marshal(tcobj) 172 if err != nil { 173 iLog.Error(fmt.Sprintf("Error marshaling json:", err.Error())) 174 return 175 } 176 code, err := trancode.Configtoobj(string(tcobjJSON)) 177 if err != nil { 178 iLog.Error(fmt.Sprintf("Error unmarshaling json:", err.Error())) 179 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 180 return 181 } 182 183 systemsessions := make(map[string]interface{}) 184 systemsessions["UserNo"] = user 185 systemsessions["ClientID"] = clientid 186 tf := trancode.NewTranFlow(code, inputs, systemsessions, nil, nil, nil) 187 188 tf.TestwithSc = true 189 190 _, err = tf.Execute() 191 192 if err != nil { 193 iLog.Error(fmt.Sprintf("End process transaction code %s's %s with error %s", code.Name, "Test", err.Error())) 194 ctx.JSON(http.StatusBadRequest, gin.H{"Test failed": err.Error()}) 195 return 196 } 197 198 TestResults := tf.TestResults 199 200 // TestSessionID,err := uuid.NewUUID(); 201 202 if remotedebug { 203 TestSessionID := fmt.Sprintf("%s/%s", clientid, code.UUID) 204 TestResults["SessionID"] = TestSessionID 205 206 isexist, err := config.TestSessionCache.IsExist(ctx, TestSessionID) 207 208 if err != nil { 209 iLog.Error(fmt.Sprintf("End process transaction code %s's %s with error %s", code.Name, "Test", err.Error())) 210 ctx.JSON(http.StatusBadRequest, gin.H{"Test failed": err.Error()}) 211 return 212 } 213 214 if isexist { 215 config.TestSessionCache.Delete(ctx, TestSessionID) 216 } 217 218 config.TestSessionCache.Put(ctx, TestSessionID, TestResults, time.Duration(time.Duration(config.ObjectCacheTimeout).Seconds())) 219 } 220 221 iLog.Debug(fmt.Sprintf("End process transaction code %s's %s ", code.Name, "Test")) 222 ctx.JSON(http.StatusOK, gin.H{"results": TestResults}) 223 224 } 225 226 func (e *TranCodeController) RemoteTestTranCode(ctx *gin.Context) { 227 iLog := logger.Log{ModuleName: logger.API, User: "System", ControllerName: "TestTranCode"} 228 startTime := time.Now() 229 defer func() { 230 elapsed := time.Since(startTime) 231 iLog.PerformanceWithDuration("controllers.trans.TestTranCode", elapsed) 232 }() 233 defer func() { 234 if err := recover(); err != nil { 235 iLog.Error(fmt.Sprintf("ExecuteTranCode defer error: %s", err)) 236 ctx.JSON(http.StatusBadRequest, gin.H{"error": err}) 237 } 238 }() 239 240 requestobj, clientid, user, err := common.GetRequestBodyandUserbyJson(ctx) 241 if err != nil { 242 iLog.Error(fmt.Sprintf("Get request information Error: %v", err)) 243 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 244 return 245 } 246 iLog.ClientID = clientid 247 iLog.User = user 248 249 iLog.Debug(fmt.Sprintf("Test transaction code with request: %s", logger.ConvertJson(requestobj))) 250 251 TestSessionID := requestobj["testsessionid"].(string) 252 253 iLog.Debug(fmt.Sprintf("Test SessionID: %s", TestSessionID)) 254 255 TestResults, err := config.TestSessionCache.Get(ctx, TestSessionID) 256 257 if err != nil { 258 iLog.Error(fmt.Sprintf("There is error to get the remote test result by testsessionid %s with error: %v", TestSessionID, err.Error())) 259 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 260 return 261 } 262 263 ctx.JSON(http.StatusOK, gin.H{"results": TestResults}) 264 } 265 266 func (e *TranCodeController) DeleteRemoteTestCache(ctx *gin.Context) { 267 iLog := logger.Log{ModuleName: logger.API, User: "System", ControllerName: "TestTranCode"} 268 startTime := time.Now() 269 defer func() { 270 elapsed := time.Since(startTime) 271 iLog.PerformanceWithDuration("controllers.trans.TestTranCode", elapsed) 272 }() 273 defer func() { 274 if err := recover(); err != nil { 275 iLog.Error(fmt.Sprintf("ExecuteTranCode defer error: %s", err)) 276 ctx.JSON(http.StatusBadRequest, gin.H{"error": err}) 277 } 278 }() 279 280 requestobj, clientid, user, err := common.GetRequestBodyandUserbyJson(ctx) 281 if err != nil { 282 iLog.Error(fmt.Sprintf("Get request information Error: %v", err)) 283 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 284 return 285 } 286 iLog.ClientID = clientid 287 iLog.User = user 288 289 iLog.Debug(fmt.Sprintf("Test transaction code with request: %s", logger.ConvertJson(requestobj))) 290 291 TestSessionID := requestobj["testsessionid"].(string) 292 293 iLog.Debug(fmt.Sprintf("Test SessionID: %s", TestSessionID)) 294 295 config.TestSessionCache.Delete(ctx, TestSessionID) 296 297 if err != nil { 298 iLog.Error(fmt.Sprintf("There is error to delete the remote test result by testsessionid %s with error: %v", TestSessionID, err.Error())) 299 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 300 return 301 } 302 303 ctx.JSON(http.StatusOK, gin.H{"status": "Success"}) 304 } 305 306 // UnitTest is a handler function for performing unit tests on transaction codes. 307 // It retrieves the user information from the request context, gets the transaction code data, 308 // and executes the unit test using the transaction code and system sessions. 309 // The outputs of the unit test are returned in the response. 310 func (e *TranCodeController) UnitTest(ctx *gin.Context) { 311 iLog := logger.Log{ModuleName: logger.API, User: "System", ControllerName: "TranCode"} 312 startTime := time.Now() 313 defer func() { 314 elapsed := time.Since(startTime) 315 iLog.PerformanceWithDuration("controllers.trans.UnitTest", elapsed) 316 }() 317 318 /* defer func() { 319 if err := recover(); err != nil { 320 iLog.Error(fmt.Sprintf("UnitTest defer error: %s", err)) 321 ctx.JSON(http.StatusBadRequest, gin.H{"error": err}) 322 } 323 }() 324 */ 325 _, userno, clientid, err := common.GetRequestUser(ctx) 326 if err != nil { 327 iLog.Error(fmt.Sprintf("GetRequestUser error: %s", err)) 328 ctx.JSON(http.StatusBadRequest, gin.H{"error": err}) 329 return 330 } 331 332 iLog.User = userno 333 iLog.ClientID = clientid 334 systemsessions := make(map[string]interface{}) 335 systemsessions["UserNo"] = userno 336 systemsessions["ClientID"] = clientid 337 338 //var tcdata TranCodeData 339 tcdata, err := getDataFromRequest(ctx) 340 if err != nil { 341 iLog.Error(fmt.Sprintf("Get transaction code %s's error", tcdata.TranCode)) 342 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 343 return 344 } 345 346 iLog.Info(fmt.Sprintf("Start process transaction code %s's %s: %s", tcdata.TranCode, "Unit Test", tcdata.Inputs)) 347 348 outputs, err := trancode.ExecuteUnitTest(tcdata.TranCode, systemsessions) 349 350 if err == nil { 351 iLog.Debug(fmt.Sprintf("End process transaction code %s's %s ", tcdata.TranCode, "Unit Test")) 352 ctx.JSON(http.StatusOK, gin.H{"Outputs": outputs}) 353 return 354 } else { 355 iLog.Error(fmt.Sprintf("End process transaction code %s's %s with error %s", tcdata.TranCode, "Unit Test", err.Error())) 356 ctx.JSON(http.StatusBadRequest, gin.H{"execution failed": err.Error()}) 357 } 358 359 } 360 361 // TestbyTestData is a function that handles the testing of transaction codes using test data. 362 // It receives a gin.Context object as a parameter. 363 // The function retrieves the user information from the request context and logs it. 364 // It then retrieves the transaction code data from the request and performs unit testing using the provided test data. 365 // The function returns the outputs of the unit testing or an error if the execution fails. 366 367 func (e *TranCodeController) TestbyTestData(ctx *gin.Context) { 368 iLog := logger.Log{ModuleName: logger.API, User: "System", ControllerName: "TranCode"} 369 startTime := time.Now() 370 defer func() { 371 elapsed := time.Since(startTime) 372 iLog.PerformanceWithDuration("controllers.trans.TestbyTestData", elapsed) 373 }() 374 /* 375 defer func() { 376 if err := recover(); err != nil { 377 iLog.Error(fmt.Sprintf("TestbyTestData defer error: %s", err)) 378 ctx.JSON(http.StatusBadRequest, gin.H{"error": err}) 379 } 380 }() 381 */ 382 _, userno, clientid, err := common.GetRequestUser(ctx) 383 if err != nil { 384 iLog.Error(fmt.Sprintf("GetRequestUser error: %s", err)) 385 ctx.JSON(http.StatusBadRequest, gin.H{"error": err}) 386 return 387 } 388 389 iLog.User = userno 390 iLog.ClientID = clientid 391 //var 392 //var tcdata TranCodeData 393 tcdata, err := getDataFromRequest(ctx) 394 if err != nil { 395 iLog.Error(fmt.Sprintf("Get transaction code %s's error", tcdata.TranCode)) 396 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 397 return 398 } 399 systemsessions := make(map[string]interface{}) 400 systemsessions["UserNo"] = userno 401 systemsessions["ClientID"] = clientid 402 iLog.Info(fmt.Sprintf("Start process transaction code %s's %s: %s", tcdata.TranCode, "Unit Test", tcdata.Inputs)) 403 404 outputs, err := trancode.ExecuteUnitTestWithTestData(tcdata.TranCode, tcdata.Inputs, systemsessions) 405 406 if err == nil { 407 iLog.Debug(fmt.Sprintf("End process transaction code %s's %s ", tcdata.TranCode, "Unit Test")) 408 ctx.JSON(http.StatusOK, gin.H{"Outputs": outputs}) 409 return 410 } else { 411 iLog.Error(fmt.Sprintf("End process transaction code %s's %s with error %s", tcdata.TranCode, "Unit Test", err.Error())) 412 ctx.JSON(http.StatusBadRequest, gin.H{"execution failed": err.Error()}) 413 } 414 } 415 416 // Execute executes the transaction code with the given inputs, user, and client ID. 417 // It returns the outputs of the transaction code and any error that occurred during execution. 418 419 func (e *TranCodeController) Execute(Code string, externalinputs map[string]interface{}, user string, clientid string) (map[string]interface{}, error) { 420 iLog := logger.Log{ModuleName: logger.API, User: user, ClientID: clientid, ControllerName: "TranCode"} 421 startTime := time.Now() 422 defer func() { 423 elapsed := time.Since(startTime) 424 iLog.PerformanceWithDuration("controllers.trans.Execute", elapsed) 425 }() 426 /* 427 defer func() { 428 if err := recover(); err != nil { 429 iLog.Error(fmt.Sprintf("Execute defer error: %s", err)) 430 // ctx.JSON(http.StatusBadRequest, gin.H{"error": err}) 431 } 432 }() 433 */ 434 iLog.Info(fmt.Sprintf("Start process transaction code %s with inputs: %s ", Code, externalinputs)) 435 436 iLog.Info(fmt.Sprintf("Start process transaction code %s's %s ", Code, "Execute")) 437 /* 438 filter := bson.M{"trancodename": Code, "isdefault": true} 439 440 tcode, err := documents.DocDBCon.QueryCollection("Transaction_Code", filter, nil) 441 442 if err != nil { 443 iLog.Error(fmt.Sprintf("Get transaction code %s's error", Code)) 444 445 return nil, err 446 } 447 iLog.Debug(fmt.Sprintf("transaction code %s's data: %s", Code, tcode)) 448 jsonString, err := json.Marshal(tcode[0]) 449 if err != nil { 450 451 iLog.Error(fmt.Sprintf("Error marshaling json:", err.Error())) 452 return nil, err 453 } 454 455 trancodeobj, err := trancode.Configtoobj(string(jsonString)) 456 if err != nil { 457 iLog.Error(fmt.Sprintf("Error unmarshaling json:", err.Error())) 458 return nil, err 459 } 460 461 iLog.Debug(fmt.Sprintf("transaction code %s's json: %s", trancodeobj, string(jsonString))) 462 463 if err != nil { 464 iLog.Error(fmt.Sprintf("Error unmarshaling json:", err.Error())) 465 return nil, err 466 } 467 */ 468 trancodeobj, err := trancode.GetTranCodeDatabyCode(Code) 469 470 if err != nil { 471 iLog.Error(fmt.Sprintf("Error unmarshaling json:", err.Error())) 472 return nil, err 473 } 474 iLog.Debug(fmt.Sprintf("transaction code %s's json: %s", Code, trancodeobj)) 475 systemsessions := make(map[string]interface{}) 476 systemsessions["UserNo"] = user 477 systemsessions["ClientID"] = clientid 478 tf := trancode.NewTranFlow(trancodeobj, externalinputs, systemsessions, nil, nil, nil) 479 outputs, err := tf.Execute() 480 481 if err == nil { 482 iLog.Debug(fmt.Sprintf("End process transaction code %s's %s ", Code, "Execute")) 483 return outputs, nil 484 485 } else { 486 iLog.Error(fmt.Sprintf("End process transaction code %s's %s with error %s", Code, "Execute", err.Error())) 487 return nil, err 488 } 489 } 490 491 // getTransCode retrieves the transaction code for a given name, user, and client ID. 492 // It reads the transaction code data from a JSON file and converts it into a TranCode object. 493 // The function logs debug, error, and performance information using the logger package. 494 // Parameters: 495 // - name: the name of the transaction code 496 // - user: the user associated with the transaction code 497 // - clientid: the client ID associated with the transaction code 498 // Returns: 499 // - types.TranCode: the retrieved transaction code 500 // - error: any error that occurred during the retrieval process 501 502 func (e *TranCodeController) getTransCode(name string, user string, clientid string) (types.TranCode, error) { 503 iLog := logger.Log{ModuleName: logger.API, User: user, ClientID: clientid, ControllerName: "TranCode"} 504 startTime := time.Now() 505 defer func() { 506 elapsed := time.Since(startTime) 507 iLog.PerformanceWithDuration("controllers.trans.getTransCode", elapsed) 508 }() 509 /* 510 defer func() { 511 if err := recover(); err != nil { 512 iLog.Error(fmt.Sprintf("getTransCode defer error: %s", err)) 513 // ctx.JSON(http.StatusBadRequest, gin.H{"error": err}) 514 } 515 }() 516 */ 517 iLog.Debug(fmt.Sprintf("Get transaction code /%s/%s%s", "trancodes", name, ".json")) 518 519 data, err := ioutil.ReadFile(fmt.Sprintf("./%s/%s%s", "trancodes", name, ".json")) 520 if err != nil { 521 522 iLog.Error(fmt.Sprintf("failed to read configuration file: %v", err)) 523 return types.TranCode{}, fmt.Errorf("failed to read configuration file: %v", err) 524 } 525 526 //filter := bson.M{"trancodename": name} 527 //iLog.Debug(fmt.Sprintf("Get transaction code detail data from respository with filter: %v", filter)) 528 //data, err := documents.DocDBCon.QueryCollection("Transaction_Code", filter, nil) 529 530 iLog.Debug(fmt.Sprintf("Get transaction code data: %s%s%s", "trancodes", name, ".json", string(data))) 531 return trancode.Bytetoobj(data) 532 } 533 534 // GetTranCodeListFromRespository retrieves the transaction code list from the repository. 535 // It requires a valid gin.Context as input. 536 // It returns the transaction code list as JSON data in the gin.Context response. 537 538 func (e *TranCodeController) GetTranCodeListFromRespository(ctx *gin.Context) { 539 iLog := logger.Log{ModuleName: logger.API, User: "System", ControllerName: "GetTranCodeListFromRespository"} 540 541 startTime := time.Now() 542 defer func() { 543 elapsed := time.Since(startTime) 544 iLog.PerformanceWithDuration("controllers.trans.GetTranCodeListFromRespository", elapsed) 545 }() 546 /* 547 defer func() { 548 if err := recover(); err != nil { 549 iLog.Error(fmt.Sprintf("GetTranCodeListFromRespository defer error: %s", err)) 550 // ctx.JSON(http.StatusBadRequest, gin.H{"error": err}) 551 } 552 }() 553 */ 554 _, userno, clientid, err := common.GetRequestUser(ctx) 555 if err != nil { 556 iLog.Error(fmt.Sprintf("GetRequestUser error: %s", err)) 557 ctx.JSON(http.StatusBadRequest, gin.H{"error": err}) 558 return 559 } 560 561 iLog.User = userno 562 iLog.ClientID = clientid 563 iLog.Debug(fmt.Sprintf("Get transaction code list from respository")) 564 565 projection := bson.M{ 566 "_id": 1, 567 "trancodename": 1, 568 "version": 1, 569 "status": 1, 570 "firstfuncgroup": 1, 571 "system": 1, 572 "description": 1, 573 } 574 tcitems, err := documents.DocDBCon.QueryCollection("Transaction_Code", nil, projection) 575 576 if err != nil { 577 578 iLog.Error(fmt.Sprintf("failed to retrieve the transaction code list: %v", err)) 579 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 580 return 581 } 582 for _, tcitem := range tcitems { 583 iLog.Debug(fmt.Sprintf("Get transaction code %s", tcitem["trancodename"])) 584 } 585 /* 586 outputs := map[string]interface{}{ 587 "trancode": tcitems, 588 } */ 589 590 ctx.JSON(http.StatusOK, gin.H{"data": tcitems}) 591 } 592 593 // GetTranCodeDetailFromRespository retrieves transaction code details from the repository. 594 // It expects a JSON payload containing the transaction code data. 595 // The function first extracts the user information from the request context. 596 // Then, it binds the JSON payload to the TranCodeData struct. 597 // Next, it constructs a filter based on the TranCodeData.TranCode field. 598 // Finally, it queries the "Transaction_Code" collection in the database using the filter and returns the results as JSON. 599 // If any error occurs during the process, it returns an error response. 600 601 func (e *TranCodeController) GetTranCodeDetailFromRespository(ctx *gin.Context) { 602 iLog := logger.Log{ModuleName: logger.API, User: "System", ControllerName: "GetTranCodeDetailFromRespository"} 603 startTime := time.Now() 604 defer func() { 605 elapsed := time.Since(startTime) 606 iLog.PerformanceWithDuration("controllers.trans.GetTranCodeDetailFromRespository", elapsed) 607 }() 608 /* 609 defer func() { 610 if err := recover(); err != nil { 611 iLog.Error(fmt.Sprintf("GetTranCodeDetailFromRespository defer error: %s", err)) 612 // ctx.JSON(http.StatusBadRequest, gin.H{"error": err}) 613 } 614 }() 615 */_, userno, clientid, err := common.GetRequestUser(ctx) 616 if err != nil { 617 iLog.Error(fmt.Sprintf("GetRequestUser error: %s", err)) 618 ctx.JSON(http.StatusBadRequest, gin.H{"error": err}) 619 return 620 } 621 622 iLog.User = userno 623 iLog.ClientID = clientid 624 iLog.Debug(fmt.Sprintf("Get transaction code detail data from respository: %v", ctx.Params)) 625 626 var tcdata TranCodeData 627 if err := ctx.BindJSON(&tcdata); err != nil { 628 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 629 return 630 } 631 //log.Print(tcdata.TranCode) 632 633 iLog.Debug(fmt.Sprintf("Get transaction code detail data from respository with code: %s", tcdata.TranCode)) 634 //filedvalue := primitive.ObjectID(param.ID) 635 filter := bson.M{"trancodename": tcdata.TranCode} 636 iLog.Debug(fmt.Sprintf("Get transaction code detail data from respository with filter: %v", filter)) 637 tcitems, err := documents.DocDBCon.QueryCollection("Transaction_Code", filter, nil) 638 639 if err != nil { 640 641 iLog.Error(fmt.Sprintf("failed to retrieve the transaction code list: %v", err)) 642 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 643 return 644 } 645 for _, tcitem := range tcitems { 646 iLog.Debug(fmt.Sprintf("Get transaction code %s", tcitem["trancodename"])) 647 } 648 649 ctx.JSON(http.StatusOK, gin.H{"Outputs": tcitems}) 650 } 651 652 // UpdateTranCodeToRespository updates the transaction code in the repository. 653 // It receives a gin.Context object as a parameter and returns no values. 654 // The function first logs the start time and defer logs the elapsed time. 655 // It then retrieves the user information from the request using common.GetRequestUser. 656 // If there is an error retrieving the user information, it logs the error and returns a JSON response with the error message. 657 // The function then binds the JSON data from the request to a TranCodeData struct. 658 // It logs the transaction code, UUID, and data. 659 // The function marshals the data to JSON and unmarshals it into a TranCode struct. 660 // If the name or UUID is empty in the request data but not in the TranCode struct, it updates the name or UUID accordingly. 661 // If the isdefault flag is true, it updates the existing transaction code with the same name to set isdefault to false. 662 // If there is no ID in the request data, it inserts a new transaction code with the provided data. 663 // If there is an ID in the request data, it updates the existing transaction code with the provided data. 664 // Finally, it returns a JSON response with the ID and status. 665 666 func (e *TranCodeController) UpdateTranCodeToRespository(ctx *gin.Context) { 667 iLog := logger.Log{ModuleName: logger.API, User: "System", ControllerName: "TranCodeController"} 668 startTime := time.Now() 669 defer func() { 670 elapsed := time.Since(startTime) 671 iLog.PerformanceWithDuration("controllers.trans.UpdateTranCodeToRespository", elapsed) 672 }() 673 /* 674 defer func() { 675 if err := recover(); err != nil { 676 iLog.Error(fmt.Sprintf("UpdateTranCodeToRespository defer error: %s", err)) 677 // ctx.JSON(http.StatusBadRequest, gin.H{"error": err}) 678 } 679 }() 680 */_, userno, clientid, err := common.GetRequestUser(ctx) 681 if err != nil { 682 iLog.Error(fmt.Sprintf("GetRequestUser error: %s", err)) 683 ctx.JSON(http.StatusBadRequest, gin.H{"error": err}) 684 return 685 } 686 687 iLog.User = userno 688 iLog.ClientID = clientid 689 690 iLog.Debug(fmt.Sprintf("Update transaction code to respository!")) 691 692 var tcdata TranCodeData 693 if err := ctx.BindJSON(&tcdata); err != nil { 694 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 695 return 696 } 697 698 name := tcdata.TranCode 699 uuid := tcdata.UUID 700 idata := tcdata.Data 701 702 iLog.Debug(fmt.Sprintf("Update transaction code to respository with code: %s", name)) 703 iLog.Debug(fmt.Sprintf("Update transaction code to respository with uuid: %s", uuid)) 704 iLog.Debug(fmt.Sprintf("Update transaction code to respository with data: %s", logger.ConvertJson(idata))) 705 706 jsonData, err := json.Marshal(idata) 707 if err != nil { 708 iLog.Error(fmt.Sprintf("failed to Marshal data: %v", err)) 709 } 710 711 var tData TranCode 712 713 err = json.Unmarshal(jsonData, &tData) 714 if err != nil { 715 iLog.Error(fmt.Sprintf("failed to unmarshal data: %v", err)) 716 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 717 return 718 } 719 720 if name == "" && tData.TranCodeName != "" { 721 name = tData.TranCodeName 722 } 723 724 if uuid == "" && tData.UUID != "" { 725 uuid = tData.UUID 726 } 727 iLog.Debug(fmt.Sprintf("Update transaction code to respository with code: %s", name)) 728 iLog.Debug(fmt.Sprintf("Update transaction code to respository with uuid: %s", uuid)) 729 id := "" 730 ok := false 731 if id, ok = idata["_id"].(string); ok { 732 iLog.Debug(fmt.Sprintf("Update transaction code to respository with _id: %s", id)) 733 734 } 735 736 isdefault := tData.IsDefault 737 738 iLog.Debug(fmt.Sprintf("Update transaction code to respository with _id: %s", id)) 739 740 if isdefault { 741 iLog.Debug(fmt.Sprintf("Update transaction code to in respository to set default to false: %s", name)) 742 filter := bson.M{"isdefault": true, 743 "trancodename": name} 744 update := bson.M{"$set": bson.M{"isdefault": false, "system.updatedon": time.Now().UTC(), "system.updatedby": "system"}} 745 746 iLog.Debug(fmt.Sprintf("Update transaction code to in respository with filter: %v", filter)) 747 iLog.Debug(fmt.Sprintf("Update transaction code to in respository with update: %v", update)) 748 err := documents.DocDBCon.UpdateCollection("Transaction_Code", filter, update, nil) 749 if err != nil { 750 iLog.Error(fmt.Sprintf("failed to update transaction code: %v", err)) 751 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 752 return 753 } 754 } 755 756 if id == "" && idata != nil { 757 utcTime := time.Now().UTC() 758 idata["system.updatedon"] = utcTime 759 idata["system.updatedby"] = "system" 760 idata["system.createdon"] = utcTime 761 idata["system.createdby"] = "system" 762 763 iLog.Debug(fmt.Sprintf("Insert transaction code to respository with code: %s", name)) 764 insertResult, err := documents.DocDBCon.InsertCollection("Transaction_Code", idata) 765 if err != nil { 766 iLog.Error(fmt.Sprintf("failed to insert transaction code: %v", err)) 767 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 768 return 769 } 770 id = insertResult.InsertedID.(primitive.ObjectID).Hex() 771 } else if idata != nil { 772 773 parsedObjectID, err := primitive.ObjectIDFromHex(id) 774 if err != nil { 775 iLog.Error(fmt.Sprintf("failed to parse object id: %v", err)) 776 } 777 778 iLog.Debug(fmt.Sprintf("Update transaction code to respository with code: %s", name)) 779 //filedvalue := primitive.ObjectID(param.ID) 780 filter := bson.M{"_id": parsedObjectID} 781 iLog.Debug(fmt.Sprintf("Update transaction code to respository with filter: %v", filter)) 782 783 idata["system.updatedon"] = time.Now().UTC() 784 idata["system.updatedby"] = "system" 785 delete(idata, "_id") 786 787 iLog.Debug(fmt.Sprintf("Update transaction code to respository with data: %s", logger.ConvertJson(idata))) 788 789 err = documents.DocDBCon.UpdateCollection("Transaction_Code", filter, nil, idata) 790 if err != nil { 791 iLog.Error(fmt.Sprintf("failed to update transaction code: %v", err)) 792 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 793 return 794 } 795 } 796 797 result := map[string]interface{}{ 798 "id": id, 799 "status": "Success", 800 } 801 ctx.JSON(http.StatusOK, gin.H{"Outputs": result}) 802 803 } 804 805 // TranCodeRevision is a function that handles the revision of transaction codes. 806 // It receives a gin.Context object as a parameter and returns no values. 807 // The function performs the following steps: 808 // 1. Logs the start time of the function execution. 809 // 2. Defer a function to log the performance duration of the function. 810 // 3. Retrieves the user information from the request context. 811 // 4. Sets the user and client ID in the logger. 812 // 5. Retrieves the request body from the JSON request. 813 // 6. Validates and extracts the necessary fields from the request body. 814 // 7. Checks if the transaction code already exists. 815 // 8. Queries the transaction code from the database. 816 // 9. Updates the existing transaction code if the isdefault flag is set. 817 // 10. Prepares the new transaction code object with the revised information. 818 // 11. Inserts the new transaction code into the database. 819 // 12. Returns the ID and status of the inserted transaction code as a JSON response. 820 821 func (e *TranCodeController) TranCodeRevision(ctx *gin.Context) { 822 iLog := logger.Log{ModuleName: logger.API, User: "System", ControllerName: "TranCodeController"} 823 startTime := time.Now() 824 defer func() { 825 elapsed := time.Since(startTime) 826 iLog.PerformanceWithDuration("controllers.trans.TranCodeRevision", elapsed) 827 }() 828 /* 829 defer func() { 830 if err := recover(); err != nil { 831 iLog.Error(fmt.Sprintf("TranCodeRevision defer error: %s", err)) 832 // ctx.JSON(http.StatusBadRequest, gin.H{"error": err}) 833 } 834 }() 835 */_, userno, clientid, err := common.GetRequestUser(ctx) 836 if err != nil { 837 iLog.Error(fmt.Sprintf("GetRequestUser error: %s", err)) 838 ctx.JSON(http.StatusBadRequest, gin.H{"error": err}) 839 return 840 } 841 842 iLog.User = userno 843 iLog.ClientID = clientid 844 845 iLog.Debug(fmt.Sprintf("Revision transaction code to respository!")) 846 847 request, err := common.GetRequestBodybyJson(ctx) 848 if err != nil { 849 iLog.Error(fmt.Sprintf("Failed to get request body: %v", err)) 850 ctx.JSON(http.StatusBadRequest, gin.H{"error": "Failed to get request body"}) 851 return 852 } 853 854 id, ok := request["_id"].(string) 855 if !ok { 856 iLog.Error(fmt.Sprintf("Failed to get _id from request")) 857 ctx.JSON(http.StatusBadRequest, gin.H{"error": "Failed to get _id from request"}) 858 return 859 } 860 iLog.Debug(fmt.Sprintf("Revision transaction code to respository with _id: %s", id)) 861 862 parsedObjectID, err := primitive.ObjectIDFromHex(id) 863 if err != nil { 864 iLog.Error(fmt.Sprintf("Failed to parse object id: %v", err)) 865 ctx.JSON(http.StatusBadRequest, gin.H{"error": "Failed to parse object id"}) 866 return 867 } 868 if err != nil { 869 iLog.Error(fmt.Sprintf("failed to parse object id: %v", err)) 870 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 871 return 872 } 873 874 filter := bson.M{"_id": parsedObjectID} 875 iLog.Debug(fmt.Sprintf("Revision transaction code to respository with filter: %v", filter)) 876 877 newvision := request["version"].(string) 878 iLog.Debug(fmt.Sprintf("Revision transaction code to respository with version: %s", newvision)) 879 newname := request["trancodename"].(string) 880 iLog.Debug(fmt.Sprintf("Revision transaction code to respository with trancodename: %s", newname)) 881 isdefault := request["isdefault"].(bool) 882 iLog.Debug(fmt.Sprintf("Revision transaction code to respository with isdefault: %s", isdefault)) 883 884 vfilter := bson.M{"trancodename": newname, "version": newvision} 885 886 existedobj, err := ValidateIfObjectExist(vfilter, userno, clientid) 887 if err != nil { 888 iLog.Error(fmt.Sprintf("Failed to query transaction code: %v", err)) 889 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 890 return 891 } 892 if existedobj { 893 iLog.Error(fmt.Sprintf("The trancode: %s with version: %s already exist!", newname, newvision)) 894 ctx.JSON(http.StatusBadRequest, gin.H{"error": "the trancode alreay exist!"}) 895 return 896 } 897 898 tcitems, err := documents.DocDBCon.QueryCollection("Transaction_Code", filter, nil) 899 if err != nil { 900 iLog.Error(fmt.Sprintf("Failed to query transaction code: %v", err)) 901 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 902 return 903 } 904 905 if len(tcitems) == 0 { 906 iLog.Error(fmt.Sprintf("Failed to query transaction code: %v", err)) 907 ctx.JSON(http.StatusBadRequest, gin.H{"error": "Failed to query transaction code"}) 908 return 909 } 910 911 tcitem := tcitems[0] 912 iLog.Debug(fmt.Sprintf("Revision transaction code to respository with tcitem: %v", tcitem)) 913 914 trancodename := tcitem["trancodename"].(string) 915 iLog.Debug(fmt.Sprintf("Revision transaction code to respository with trancodename: %s", trancodename)) 916 917 if isdefault { 918 iLog.Debug(fmt.Sprintf("Revision transaction code to in respository to set default to false: %s", trancodename)) 919 filter := bson.M{"isdefault": true, 920 "trancodename": newname} 921 update := bson.M{"$set": bson.M{"isdefault": false, "system.updatedon": time.Now().UTC(), "system.updatedby": "system"}} 922 923 iLog.Debug(fmt.Sprintf("Revision transaction code to in respository with filter: %v", filter)) 924 iLog.Debug(fmt.Sprintf("Revision transaction code to in respository with update: %v", update)) 925 err := documents.DocDBCon.UpdateCollection("Transaction_Code", filter, update, nil) 926 if err != nil { 927 iLog.Error(fmt.Sprintf("failed to update transaction code: %v", err)) 928 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 929 return 930 } 931 } 932 933 utcTime := time.Now().UTC() 934 tcitem["system.updatedon"] = utcTime 935 tcitem["system.updatedby"] = "system" 936 tcitem["system.createdon"] = utcTime 937 tcitem["system.createdby"] = "system" 938 tcitem["trancodename"] = newname 939 tcitem["version"] = newvision 940 tcitem["isdefault"] = isdefault 941 tcitem["status"] = 1 942 tcitem["uuid"] = uuid.New().String() 943 tcitem["description"] = utcTime.String() + ": Revision transaction code " + trancodename + " to " + newname + " with version " + newvision + " \n " + tcitem["description"].(string) 944 delete(tcitem, "_id") 945 946 iLog.Debug(fmt.Sprintf("Revision transaction code to respository with tcitem: %v", tcitem)) 947 948 insertResult, err := documents.DocDBCon.InsertCollection("Transaction_Code", tcitem) 949 950 if err != nil { 951 iLog.Error(fmt.Sprintf("failed to insert transaction code: %v", err)) 952 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 953 return 954 } 955 id = insertResult.InsertedID.(primitive.ObjectID).Hex() 956 957 result := map[string]interface{}{ 958 "id": id, 959 "status": "Success", 960 } 961 ctx.JSON(http.StatusOK, gin.H{"Outputs": result}) 962 963 } 964 965 // ValidateIfObjectExist checks if an object exists in the collection based on the provided filter. 966 // It takes the filter, user number, and client ID as parameters. 967 // It returns a boolean indicating whether the object exists and an error if any. 968 969 func ValidateIfObjectExist(filter bson.M, userno string, clientid string) (bool, error) { 970 iLog := logger.Log{ModuleName: logger.API, User: "System", ControllerName: "ValidateIfObjectExist"} 971 startTime := time.Now() 972 defer func() { 973 elapsed := time.Since(startTime) 974 iLog.PerformanceWithDuration("controllers.trans.ValidateIfObjectExist", elapsed) 975 }() 976 /* 977 defer func() { 978 if err := recover(); err != nil { 979 iLog.Error(fmt.Sprintf("ValidateIfObjectExist defer error: %s", err)) 980 // ctx.JSON(http.StatusBadRequest, gin.H{"error": err}) 981 } 982 }() 983 */ 984 iLog.User = userno 985 iLog.ClientID = clientid 986 iLog.Debug(fmt.Sprintf("Validate if object exist in collection")) 987 988 collectionitems, err := documents.DocDBCon.QueryCollection("Transaction_Code", filter, nil) 989 if err != nil { 990 iLog.Error(fmt.Sprintf("failed to query collection: %v", err)) 991 return false, err 992 } 993 if len(collectionitems) == 0 { 994 return false, nil 995 } 996 return true, nil 997 } 998 999 // getDataFromRequest is a function that retrieves data from the request context and returns it as a TranCodeData struct. 1000 // It also logs performance metrics and any errors encountered during the process. 1001 // The function takes a gin.Context parameter and returns a TranCodeData struct and an error. 1002 1003 func getDataFromRequest(ctx *gin.Context) (TranCodeData, error) { 1004 iLog := logger.Log{ModuleName: logger.API, User: "System", ControllerName: "GetDataFromRequest"} 1005 startTime := time.Now() 1006 defer func() { 1007 elapsed := time.Since(startTime) 1008 iLog.PerformanceWithDuration("controllers.trans.getDataFromRequest", elapsed) 1009 }() 1010 /* 1011 defer func() { 1012 if err := recover(); err != nil { 1013 iLog.Error(fmt.Sprintf("getDataFromRequest defer error: %s", err)) 1014 // ctx.JSON(http.StatusBadRequest, gin.H{"error": err}) 1015 } 1016 }() */ 1017 _, userno, clientid, err := common.GetRequestUser(ctx) 1018 if err != nil { 1019 iLog.Error(fmt.Sprintf("GetRequestUser error: %s", err)) 1020 ctx.JSON(http.StatusBadRequest, gin.H{"error": err}) 1021 return TranCodeData{}, err 1022 } 1023 1024 iLog.User = userno 1025 iLog.ClientID = clientid 1026 1027 iLog.Debug(fmt.Sprintf("GetDataFromRequest")) 1028 1029 var data TranCodeData 1030 body, err := ioutil.ReadAll(ctx.Request.Body) 1031 iLog.Debug(fmt.Sprintf("GetDataFromRequest body: %s", body)) 1032 if err != nil { 1033 iLog.Error(fmt.Sprintf("GetDataFromRequest error: %s", err.Error())) 1034 return data, err 1035 } 1036 err = json.Unmarshal(body, &data) 1037 if err != nil { 1038 iLog.Error(fmt.Sprintf("GetDataFromRequest Unmarshal error: %s", err.Error())) 1039 return data, err 1040 } 1041 iLog.Debug(fmt.Sprintf("GetDataFromRequest data: %s", data)) 1042 return data, nil 1043 } 1044 1045 type TranCodeData struct { 1046 TranCode string `json:"code"` 1047 Version string `json:"version"` 1048 UUID string `json:"uuid"` 1049 Data map[string]interface{} `json:"data"` 1050 Inputs map[string]interface{} `json:"inputs"` 1051 } 1052 1053 type TranCode struct { 1054 ID string "json:'_id'" 1055 UUID string "json:'uuid'" 1056 TranCodeName string "json:'trancodename'" 1057 Version string "json:'version'" 1058 IsDefault bool "json:'isdefault'" 1059 Status int "json:'status'" 1060 Firstfuncgroup string "json:'firstfuncgroup'" 1061 SystemData types.SystemData "json:'system'" 1062 Description string "json:'description'" 1063 }