github.com/mdaxf/iac@v0.0.0-20240519030858-58a061660378/controllers/collectionop/collectionop.go (about) 1 package collectionop 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "reflect" 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/logger" 18 19 "github.com/mdaxf/iac/documents" 20 21 "github.com/mdaxf/iac/controllers/common" 22 ) 23 24 type CollectionController struct { 25 } 26 27 type CollectionData struct { 28 CollectionName string `json:"collectionname"` 29 Data map[string]interface{} `json:"data"` 30 Operation string `json:"operation"` 31 Keys []string `json:"keys"` 32 } 33 34 // GetListofCollectionData retrieves a list of collection data. 35 // It reads the request body, unmarshals the data into a struct, 36 // and queries the collection in the database based on the collection name and projection. 37 // The retrieved collection items are then returned as a JSON response. 38 39 func (c *CollectionController) GetListofCollectionData(ctx *gin.Context) { 40 iLog := logger.Log{ModuleName: logger.API, User: "System", ControllerName: "GetListofCollectionData"} 41 42 startTime := time.Now() 43 defer func() { 44 elapsed := time.Since(startTime) 45 iLog.PerformanceWithDuration("collectionop.GetListofCollectionData", elapsed) 46 }() 47 48 /* defer func() { 49 err := recover() 50 if err != nil { 51 iLog.Error(fmt.Sprintf("Panic Error: %v", err)) 52 ctx.JSON(http.StatusBadRequest, gin.H{"error": err}) 53 } 54 }() 55 */ 56 /* 57 _, user, clientid, err := common.GetRequestUser(ctx) 58 if err != nil { 59 iLog.Error(fmt.Sprintf("Get user information Error: %v", err)) 60 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 61 return 62 } 63 iLog.ClientID = clientid 64 iLog.User = user 65 66 iLog.Debug(fmt.Sprintf("Get collection list from respository")) 67 68 body, err := ioutil.ReadAll(ctx.Request.Body) 69 if err != nil { 70 iLog.Error(fmt.Sprintf("Error reading body: %v", err)) 71 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 72 return 73 } 74 defer ctx.Request.Body.Close() 75 76 iLog.Debug(fmt.Sprintf("Get collection list from respository with body: %s", body)) 77 */ 78 body, clientid, user, err := common.GetRequestBodyandUser(ctx) 79 if err != nil { 80 iLog.Error(fmt.Sprintf("Error reading body: %v", err)) 81 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 82 return 83 } 84 iLog.ClientID = clientid 85 iLog.User = user 86 87 var data CollectionData 88 /*if err := ctx.BindJSON(&data); err != nil { 89 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 90 return 91 } 92 */ 93 iLog.Debug(fmt.Sprintf("Get collection list from respository with body: %s", body)) 94 95 err = json.Unmarshal(body, &data) 96 if err != nil { 97 iLog.Error(fmt.Sprintf("Error umarshal body: %v", err)) 98 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 99 return 100 } 101 102 collectionName := data.CollectionName 103 operation := data.Operation 104 items := data.Data 105 /* 106 condition := map[string]interface{}{} 107 for _, key := range Keys { 108 condition[key] = 1 109 } 110 */ 111 jsonData, err := json.Marshal(items) 112 if err != nil { 113 iLog.Error(fmt.Sprintf("Error marshaling json: %v", err)) 114 } 115 116 iLog.Debug(fmt.Sprintf("Collection Name: %s, operation: %s data: %s", collectionName, operation, jsonData)) 117 118 if collectionName == "" { 119 ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid collection name"}) 120 return 121 } 122 123 projection, _ := c.buildProjectionFromJSON(jsonData, "projection") 124 125 collectionitems, err := documents.DocDBCon.QueryCollection(collectionName, nil, projection) 126 127 if err != nil { 128 129 iLog.Error(fmt.Sprintf("failed to retrieve the list from collection: %v", err)) 130 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 131 return 132 } 133 iLog.Debug(fmt.Sprintf("Get collection list from respository with data: %s", logger.ConvertJson(collectionitems))) 134 135 ctx.JSON(http.StatusOK, gin.H{"data": collectionitems}) 136 } 137 138 // GetDetailCollectionData retrieves the detail data of a collection. 139 // It reads the request body, unmarshals it into a CollectionData struct, 140 // and uses the collection name, operation, and data from the struct 141 // to query the collection in the database. 142 // The retrieved collection items are returned as a JSON response. 143 144 func (c *CollectionController) GetDetailCollectionData(ctx *gin.Context) { 145 startTime := time.Now() 146 iLog := logger.Log{ModuleName: logger.API, User: "System", ControllerName: "GetDetailCollectionData"} 147 defer func() { 148 elapsed := time.Since(startTime) 149 iLog.PerformanceWithDuration("collectionop.GetDetailCollectionData", elapsed) 150 }() 151 /* defer func() { 152 err := recover() 153 if err != nil { 154 iLog.Error(fmt.Sprintf("Error: %v", err)) 155 ctx.JSON(http.StatusBadRequest, gin.H{"error": err}) 156 } 157 }() 158 */ 159 /* 160 _, user, clientid, err := common.GetRequestUser(ctx) 161 if err != nil { 162 iLog.Error(fmt.Sprintf("Get user information Error: %v", err)) 163 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 164 return 165 } 166 iLog.ClientID = clientid 167 iLog.User = user 168 169 iLog.Debug(fmt.Sprintf("Get collection detail data from respository")) 170 171 var data CollectionData 172 if err := ctx.BindJSON(&data); err != nil { 173 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 174 return 175 } 176 */ 177 body, clientid, user, err := common.GetRequestBodyandUser(ctx) 178 if err != nil { 179 iLog.Error(fmt.Sprintf("Error reading body: %v", err)) 180 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 181 return 182 } 183 iLog.ClientID = clientid 184 iLog.User = user 185 186 var data CollectionData 187 188 iLog.Debug(fmt.Sprintf("Get collection list from respository with body: %s", body)) 189 190 err = json.Unmarshal(body, &data) 191 if err != nil { 192 iLog.Error(fmt.Sprintf("Error umarshal body: %v", err)) 193 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 194 return 195 } 196 197 collectionName := data.CollectionName 198 operation := data.Operation 199 list := data.Data 200 201 iLog.Debug(fmt.Sprintf("Collection Name: %s, operation: %s data: %s", collectionName, operation, list)) 202 if collectionName == "" { 203 ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid collection name"}) 204 return 205 } 206 filter := bson.M(list) 207 208 iLog.Debug(fmt.Sprintf("Collection Name: %s, operation: %s data: %s", collectionName, operation, filter)) 209 collectionitems, err := documents.DocDBCon.QueryCollection(collectionName, filter, nil) 210 211 if err != nil { 212 213 iLog.Error(fmt.Sprintf("failed to retrieve the detail data from collection: %v", err)) 214 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 215 return 216 } 217 218 ctx.JSON(http.StatusOK, gin.H{"data": collectionitems}) 219 } 220 221 func (c *CollectionController) GetDetailCollectionDatabyID(ctx *gin.Context) { 222 iLog := logger.Log{ModuleName: logger.API, User: "System", ControllerName: "GetDetailCollectionData"} 223 startTime := time.Now() 224 225 defer func() { 226 elapsed := time.Since(startTime) 227 iLog.PerformanceWithDuration("collectionop.GetDetailCollectionDatabyID", elapsed) 228 }() 229 /* defer func() { 230 err := recover() 231 if err != nil { 232 iLog.Error(fmt.Sprintf("Error: %v", err)) 233 ctx.JSON(http.StatusBadRequest, gin.H{"error": err}) 234 } 235 }() 236 237 _, user, clientid, err := common.GetRequestUser(ctx) 238 if err != nil { 239 iLog.Error(fmt.Sprintf("Get user information Error: %v", err)) 240 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 241 return 242 } 243 iLog.ClientID = clientid 244 iLog.User = user 245 246 iLog.Debug(fmt.Sprintf("Get collection detail data from respository")) 247 248 var data CollectionData 249 if err := ctx.BindJSON(&data); err != nil { 250 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 251 return 252 } 253 */ 254 body, clientid, user, err := common.GetRequestBodyandUser(ctx) 255 if err != nil { 256 iLog.Error(fmt.Sprintf("Error reading body: %v", err)) 257 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 258 return 259 } 260 iLog.ClientID = clientid 261 iLog.User = user 262 263 var data CollectionData 264 /*if err := ctx.BindJSON(&data); err != nil { 265 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 266 return 267 } 268 */ 269 iLog.Debug(fmt.Sprintf("GetDetailCollectionDatabyID from respository with body: %s", body)) 270 271 err = json.Unmarshal(body, &data) 272 if err != nil { 273 // Handle the error 274 iLog.Error(fmt.Sprintf("Error umarshal body: %v", err)) 275 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 276 return 277 } 278 279 collectionName := data.CollectionName 280 operation := data.Operation 281 list := data.Data 282 value := list["_id"] 283 284 iLog.Debug(fmt.Sprintf("Collection Name: %s, operation: %s data: %s", collectionName, operation, list)) 285 if collectionName == "" { 286 ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid collection name"}) 287 return 288 } 289 290 if value == nil || value == "" { 291 ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid id"}) 292 return 293 } 294 /* jsonData, err := json.Marshal(list) 295 296 if err != nil { 297 iLog.Error(fmt.Sprintf("Error marshaling json: %v", err)) 298 } 299 //filter, _ := c.buildProjectionFromJSON(jsonData, "projection") 300 parsedObjectID, _ := primitive.ObjectIDFromHex(value.(string)) 301 filter := bson.M{"_id": parsedObjectID} 302 303 iLog.Debug(fmt.Sprintf("Collection Name: %s, operation: %s data: %s", collectionName, operation, filter)) 304 */ 305 collectionitems, err := documents.DocDBCon.GetItembyID(collectionName, value.(string)) 306 307 if err != nil { 308 309 iLog.Error(fmt.Sprintf("failed to retrieve the detail data from collection: %v", err)) 310 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 311 return 312 } 313 314 ctx.JSON(http.StatusOK, gin.H{"data": collectionitems}) 315 } 316 317 // GetDetailCollectionDatabyName retrieves the detail data of a collection by its name. 318 // It expects a JSON request body containing the collection name and data. 319 // The function returns the detail data of the collection as a JSON response. 320 // The function also logs the performance of the function. 321 // The function also logs any errors that occur. 322 func (c *CollectionController) GetDetailCollectionDatabyName(ctx *gin.Context) { 323 iLog := logger.Log{ModuleName: logger.API, User: "System", ControllerName: "GetDetailCollectionDatabyName"} 324 startTime := time.Now() 325 326 defer func() { 327 elapsed := time.Since(startTime) 328 iLog.PerformanceWithDuration("collectionop.GetDetailCollectionDatabyName", elapsed) 329 }() 330 /* defer func() { 331 err := recover() 332 if err != nil { 333 iLog.Error(fmt.Sprintf("Error: %v", err)) 334 ctx.JSON(http.StatusBadRequest, gin.H{"error": err}) 335 } 336 }() 337 338 _, user, clientid, err := common.GetRequestUser(ctx) 339 if err != nil { 340 iLog.Error(fmt.Sprintf("Get user information Error: %v", err)) 341 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 342 return 343 } 344 iLog.ClientID = clientid 345 iLog.User = user 346 347 iLog.Debug(fmt.Sprintf("Get default collection detail data from respository")) 348 349 var data CollectionData 350 if err := ctx.BindJSON(&data); err != nil { 351 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 352 return 353 } 354 */ 355 body, clientid, user, err := common.GetRequestBodyandUser(ctx) 356 if err != nil { 357 iLog.Error(fmt.Sprintf("Error reading body: %v", err)) 358 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 359 return 360 } 361 iLog.ClientID = clientid 362 iLog.User = user 363 364 var data CollectionData 365 366 iLog.Debug(fmt.Sprintf("GetDetailCollectionDatabyName from respository with body: %s", body)) 367 368 err = json.Unmarshal(body, &data) 369 if err != nil { 370 iLog.Error(fmt.Sprintf("Error umarshal body: %v", err)) 371 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 372 return 373 } 374 375 collectionName := data.CollectionName 376 377 list := data.Data 378 value := list["name"] 379 380 iLog.Debug(fmt.Sprintf("Collection Name: %s, data: %s", collectionName, list)) 381 if collectionName == "" { 382 ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid collection name"}) 383 return 384 } 385 386 collectionitems, err := documents.DocDBCon.GetDefaultItembyName(collectionName, value.(string)) 387 388 if err != nil { 389 390 iLog.Error(fmt.Sprintf("failed to retrieve the detail data from collection: %v", err)) 391 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 392 return 393 } 394 395 ctx.JSON(http.StatusOK, gin.H{"data": collectionitems}) 396 } 397 398 func (c *CollectionController) GetDetailCollectionDatabyUUID(ctx *gin.Context) { 399 iLog := logger.Log{ModuleName: logger.API, User: "System", ControllerName: "GetDetailCollectionDatabyName"} 400 startTime := time.Now() 401 402 defer func() { 403 elapsed := time.Since(startTime) 404 iLog.PerformanceWithDuration("collectionop.GetDetailCollectionDatabyName", elapsed) 405 }() 406 /* defer func() { 407 err := recover() 408 if err != nil { 409 iLog.Error(fmt.Sprintf("Error: %v", err)) 410 ctx.JSON(http.StatusBadRequest, gin.H{"error": err}) 411 } 412 }() 413 414 _, user, clientid, err := common.GetRequestUser(ctx) 415 if err != nil { 416 iLog.Error(fmt.Sprintf("Get user information Error: %v", err)) 417 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 418 return 419 } 420 iLog.ClientID = clientid 421 iLog.User = user 422 423 iLog.Debug(fmt.Sprintf("Get default collection detail data from respository")) 424 425 var data CollectionData 426 if err := ctx.BindJSON(&data); err != nil { 427 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 428 return 429 } 430 */ 431 body, clientid, user, err := common.GetRequestBodyandUser(ctx) 432 if err != nil { 433 iLog.Error(fmt.Sprintf("Error reading body: %v", err)) 434 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 435 return 436 } 437 iLog.ClientID = clientid 438 iLog.User = user 439 440 var data CollectionData 441 442 iLog.Debug(fmt.Sprintf("GetDetailCollectionDatabyName from respository with body: %s", body)) 443 444 err = json.Unmarshal(body, &data) 445 if err != nil { 446 iLog.Error(fmt.Sprintf("Error umarshal body: %v", err)) 447 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 448 return 449 } 450 451 collectionName := data.CollectionName 452 453 list := data.Data 454 value := list["uuid"] 455 456 iLog.Debug(fmt.Sprintf("Collection Name: %s, data: %s", collectionName, list)) 457 if collectionName == "" { 458 ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid collection name"}) 459 return 460 } 461 462 collectionitems, err := documents.DocDBCon.GetItembyUUID(collectionName, value.(string)) 463 464 if err != nil { 465 466 iLog.Error(fmt.Sprintf("failed to retrieve the detail data from collection: %v", err)) 467 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 468 return 469 } 470 471 ctx.JSON(http.StatusOK, gin.H{"data": collectionitems}) 472 } 473 474 // UpdateCollectionData updates the collection data in the repository. 475 // It retrieves the user information from the request context and binds the JSON data. 476 // If the collection name is invalid, it returns an error response. 477 // If the data contains an "_id" field, it updates the collection with the specified ID. 478 // If the data does not contain an "_id" field, it inserts a new collection into the repository. 479 // The updated or inserted collection is then returned as a response. 480 481 func (c *CollectionController) UpdateCollectionData(ctx *gin.Context) { 482 iLog := logger.Log{ModuleName: logger.API, User: "System", ControllerName: "UpdateCollectionData"} 483 startTime := time.Now() 484 485 defer func() { 486 elapsed := time.Since(startTime) 487 iLog.PerformanceWithDuration("collectionop.UpdateCollectionData", elapsed) 488 }() 489 /* defer func() { 490 err := recover() 491 if err != nil { 492 iLog.Error(fmt.Sprintf("Error: %v", err)) 493 ctx.JSON(http.StatusBadRequest, gin.H{"error": err}) 494 } 495 }() 496 497 _, user, clientid, err := common.GetRequestUser(ctx) 498 if err != nil { 499 iLog.Error(fmt.Sprintf("Get user information Error: %v", err)) 500 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 501 return 502 } 503 iLog.ClientID = clientid 504 iLog.User = user 505 506 iLog.Debug(fmt.Sprintf("update collection data to respository")) 507 508 var data CollectionData 509 if err := ctx.BindJSON(&data); err != nil { 510 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 511 return 512 } 513 */ 514 body, clientid, user, err := common.GetRequestBodyandUser(ctx) 515 if err != nil { 516 iLog.Error(fmt.Sprintf("Error reading body: %v", err)) 517 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 518 return 519 } 520 iLog.ClientID = clientid 521 iLog.User = user 522 523 var data CollectionData 524 525 iLog.Debug(fmt.Sprintf("UpdateCollectionData in respository with body: %s", body)) 526 527 err = json.Unmarshal(body, &data) 528 if err != nil { 529 iLog.Error(fmt.Sprintf("Error umarshal body: %v", err)) 530 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 531 return 532 } 533 534 collectionName := data.CollectionName 535 operation := data.Operation 536 list := data.Data 537 idata := reflect.ValueOf(list) 538 Keys := data.Keys 539 540 iLog.Debug(fmt.Sprintf("Collection Name: %s, operation: %s data: %s", collectionName, operation, list)) 541 if collectionName == "" { 542 ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid collection name"}) 543 return 544 } 545 546 /*_, err := json.Marshal(list) 547 548 if err != nil { 549 iLog.Error(fmt.Sprintf("Error marshaling json: %v", err)) 550 } */ 551 552 id := "" 553 ok := false 554 if id, ok = list["_id"].(string); ok { 555 iLog.Debug(fmt.Sprintf("Update collection to respository with _id: %s", id)) 556 } 557 558 isdefault := false 559 if isdefault, ok = list["isdefault"].(bool); ok { 560 iLog.Debug(fmt.Sprintf("Update collection to respository with isdefault: %t", isdefault)) 561 } 562 name := "" 563 if name, ok = list["name"].(string); ok { 564 iLog.Debug(fmt.Sprintf("Update collection to respository with name: %s", name)) 565 } 566 567 if isdefault { 568 569 condition := map[string]interface{}{} 570 condition["isdefault"] = true 571 for _, key := range Keys { 572 condition[key] = list[key] 573 } 574 575 iLog.Debug(fmt.Sprintf("Update collection to in respository to set default to false: %s", condition)) 576 577 con, err := json.Marshal(condition) 578 579 if err != nil { 580 iLog.Error(fmt.Sprintf("Error marshaling json: %v", err)) 581 } 582 583 filter, _ := c.buildProjectionFromJSON(con, "filter") 584 585 collectionitems, err := documents.DocDBCon.QueryCollection(collectionName, filter, nil) 586 587 if err == nil && collectionitems != nil { 588 /* 589 update := bson.M{"$set": bson.M{"isdefault": false, "system.updatedon": time.Now()}, "system.updatedby": "system"} 590 591 iLog.Debug(fmt.Sprintf("Update collection to in respository with filter: %v", filter)) 592 iLog.Debug(fmt.Sprintf("Update collection to in respository with update: %v", update)) 593 594 err = documents.DocDBCon.UpdateCollection(collectionName, filter, update, nil) 595 if err != nil { 596 iLog.Error(fmt.Sprintf("failed to update collection: %v", err)) 597 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 598 return 599 } 600 */ 601 } 602 603 } 604 if id == "" && list != nil { 605 utcTime := time.Now().UTC() 606 system := map[string]interface{}{ 607 "updatedon": utcTime, 608 "updatedby": "system", 609 "createdon": utcTime, 610 "createdby": "system", 611 } 612 613 list["system"] = system 614 delete(list, "_id") 615 iLog.Debug(fmt.Sprintf("Insert collection to respository: %s", collectionName)) 616 insertResult, err := documents.DocDBCon.InsertCollection(collectionName, list) 617 if err != nil { 618 iLog.Error(fmt.Sprintf("failed to insert collection: %v", err)) 619 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 620 return 621 } 622 id = insertResult.InsertedID.(primitive.ObjectID).Hex() 623 // list["_id"] = id 624 625 } else if list != nil { 626 627 parsedObjectID, err := primitive.ObjectIDFromHex(id) 628 if err != nil { 629 iLog.Error(fmt.Sprintf("failed to parse object id: %v", err)) 630 } 631 632 iLog.Debug(fmt.Sprintf("Update transaction code to respository with code: %s", name)) 633 //filedvalue := primitive.ObjectID(param.ID) 634 filter := bson.M{"_id": parsedObjectID} 635 iLog.Debug(fmt.Sprintf("Update transaction code to respository with filter: %v", filter)) 636 system := list["system"].(map[string]interface{}) 637 system["updatedon"] = time.Now().UTC() 638 system["updatedby"] = "system" 639 list["system"] = system 640 //list["system.updatedon"] = time.Now().UTC() 641 //list["system.updatedby"] = "system" 642 643 delete(list, "_id") 644 645 iLog.Debug(fmt.Sprintf("Update transaction code to respository with data: %s", logger.ConvertJson(idata))) 646 647 err = documents.DocDBCon.UpdateCollection(collectionName, filter, nil, list) 648 if err != nil { 649 iLog.Error(fmt.Sprintf("failed to update collection: %v", err)) 650 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 651 return 652 } 653 } 654 rdata := make(map[string]interface{}) 655 rdata["id"] = id 656 657 result := map[string]interface{}{ 658 "data": rdata, 659 "status": "Success", 660 } 661 ctx.JSON(http.StatusOK, gin.H{"data": result}) 662 } 663 664 // DeleteCollectionDatabyID deletes a collection data by its ID. 665 // It takes a gin.Context as input and returns the deleted data as JSON response. 666 // If there is an error, it returns an error message as JSON response. 667 668 func (c *CollectionController) DeleteCollectionDatabyID(ctx *gin.Context) { 669 iLog := logger.Log{ModuleName: logger.API, User: "System", ControllerName: "DeleteCollectionData"} 670 startTime := time.Now() 671 672 defer func() { 673 elapsed := time.Since(startTime) 674 iLog.PerformanceWithDuration("collectionop.DeleteCollectionDatabyID", elapsed) 675 }() 676 /* defer func() { 677 err := recover() 678 if err != nil { 679 iLog.Error(fmt.Sprintf("collectionop.DeleteCollectionDatabyID Error: %v", err)) 680 ctx.JSON(http.StatusBadRequest, gin.H{"error": err}) 681 } 682 }() 683 684 _, user, clientid, err := common.GetRequestUser(ctx) 685 if err != nil { 686 iLog.Error(fmt.Sprintf("Get user information Error: %v", err)) 687 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 688 return 689 } 690 iLog.ClientID = clientid 691 iLog.User = user 692 693 iLog.Debug(fmt.Sprintf("delete collection data to respository")) 694 var data CollectionData 695 if err := ctx.BindJSON(&data); err != nil { 696 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 697 return 698 } 699 */ 700 body, clientid, user, err := common.GetRequestBodyandUser(ctx) 701 if err != nil { 702 iLog.Error(fmt.Sprintf("Error reading body: %v", err)) 703 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 704 return 705 } 706 iLog.ClientID = clientid 707 iLog.User = user 708 709 var data CollectionData 710 711 iLog.Debug(fmt.Sprintf("DeleteCollectionDatabyID from respository with body: %s", body)) 712 713 err = json.Unmarshal(body, &data) 714 if err != nil { 715 iLog.Error(fmt.Sprintf("Error umarshal body: %v", err)) 716 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 717 return 718 } 719 720 collectionName := data.CollectionName 721 operation := data.Operation 722 list := data.Data 723 value := list["_id"] 724 725 iLog.Debug(fmt.Sprintf("Collection Name: %s, operation: %s data: %s", collectionName, operation, list)) 726 if collectionName == "" { 727 ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid collection name"}) 728 return 729 } 730 731 if value == nil || value == "" { 732 ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid id"}) 733 return 734 } 735 736 err = documents.DocDBCon.DeleteItemFromCollection(collectionName, value.(string)) 737 738 if err != nil { 739 ctx.JSON(http.StatusBadRequest, gin.H{"error": "Delete item from collection error!"}) 740 return 741 } 742 743 rdata := make(map[string]interface{}) 744 rdata["id"] = value 745 result := map[string]interface{}{ 746 "data": rdata, 747 "status": "Success", 748 } 749 750 ctx.JSON(http.StatusOK, gin.H{"data": result}) 751 } 752 753 // CollectionObjectRevision is a function that handles the revision of a collection object. 754 // It takes a gin.Context as a parameter and returns no values. 755 // The function retrieves the request body and user information from the context, 756 // validates the request, queries the collection object, updates the default status if necessary, 757 // revises the collection object, and inserts the revised object into the collection. 758 759 func (c *CollectionController) CollectionObjectRevision(ctx *gin.Context) { 760 761 iLog := logger.Log{ModuleName: logger.API, User: "System", ControllerName: "CollectionObjectRevision"} 762 startTime := time.Now() 763 764 defer func() { 765 elapsed := time.Since(startTime) 766 iLog.PerformanceWithDuration("collectionop.CollectionObjectRevision", elapsed) 767 }() 768 /* defer func() { 769 err := recover() 770 if err != nil { 771 iLog.Error(fmt.Sprintf("collectionop.CollectionObjectRevision Error: %v", err)) 772 ctx.JSON(http.StatusBadRequest, gin.H{"error": err}) 773 } 774 }() 775 776 _, user, clientid, err := common.GetRequestUser(ctx) 777 if err != nil { 778 iLog.Error(fmt.Sprintf("Get user information Error: %v", err)) 779 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 780 return 781 } 782 iLog.ClientID = clientid 783 iLog.User = user 784 785 iLog.Debug(fmt.Sprintf("Revision collection to respository!")) 786 787 request, err := common.GetRequestBodybyJson(ctx) 788 if err != nil { 789 iLog.Error(fmt.Sprintf("Failed to get request body: %v", err)) 790 ctx.JSON(http.StatusBadRequest, gin.H{"error": "Failed to get request body"}) 791 return 792 } 793 */ 794 request, clientid, user, err := common.GetRequestBodyandUserbyJson(ctx) 795 if err != nil { 796 iLog.Error(fmt.Sprintf("Error reading body: %v", err)) 797 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 798 return 799 } 800 iLog.ClientID = clientid 801 iLog.User = user 802 803 iLog.Debug(fmt.Sprintf("CollectionObjectRevision in respository with body: %v", request)) 804 805 id, ok := request["_id"].(string) 806 if !ok { 807 iLog.Error(fmt.Sprintf("Failed to get _id from request")) 808 ctx.JSON(http.StatusBadRequest, gin.H{"error": "Failed to get _id from request"}) 809 return 810 } 811 iLog.Debug(fmt.Sprintf("Revision collection object to respository with _id: %s", id)) 812 813 parsedObjectID, err := primitive.ObjectIDFromHex(id) 814 if err != nil { 815 iLog.Error(fmt.Sprintf("Failed to parse object id: %v", err)) 816 ctx.JSON(http.StatusBadRequest, gin.H{"error": "Failed to parse object id"}) 817 return 818 } 819 if err != nil { 820 iLog.Error(fmt.Sprintf("failed to parse object id: %v", err)) 821 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 822 return 823 } 824 825 filter := bson.M{"_id": parsedObjectID} 826 iLog.Debug(fmt.Sprintf("Revision collection object to respository with filter: %v", filter)) 827 828 newvision := request["version"].(string) 829 iLog.Debug(fmt.Sprintf("Revision collection object to respository with version: %s", newvision)) 830 newname := request["name"].(string) 831 iLog.Debug(fmt.Sprintf("Revision collection object to respository with new name: %s", newname)) 832 isdefault := request["isdefault"].(bool) 833 iLog.Debug(fmt.Sprintf("Revision collection object to respository with isdefault: %s", isdefault)) 834 collectionname := request["collectionname"].(string) 835 iLog.Debug(fmt.Sprintf("Revision collection object to respository with collectionname: %s", collectionname)) 836 if collectionname == "" { 837 iLog.Error(fmt.Sprintf("Failed to get collection name from request")) 838 ctx.JSON(http.StatusBadRequest, gin.H{"error": "Failed to get collection name from request"}) 839 return 840 } 841 842 vfilter := bson.M{"name": newname, "version": newvision} 843 iLog.Debug(fmt.Sprintf("Revision collection object to respository with vfilter: %v", vfilter)) 844 ifexist, err := ValidateIfObjectExist(collectionname, vfilter, user) 845 if err != nil { 846 iLog.Error(fmt.Sprintf("Failed to query collection object: %v", err)) 847 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 848 return 849 } 850 851 if ifexist { 852 iLog.Error(fmt.Sprintf("collection %s with name %s and version %s alrweady exists!", collectionname, newname, newvision)) 853 ctx.JSON(http.StatusBadRequest, gin.H{"error": "Failed to query collection object"}) 854 return 855 } 856 857 tcitems, err := documents.DocDBCon.QueryCollection(collectionname, filter, nil) 858 if err != nil { 859 iLog.Error(fmt.Sprintf("Failed to query collection object: %v", err)) 860 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 861 return 862 } 863 864 if len(tcitems) == 0 { 865 iLog.Error(fmt.Sprintf("Failed to query collection object: %v", err)) 866 ctx.JSON(http.StatusBadRequest, gin.H{"error": "Failed to query collection object"}) 867 return 868 } 869 870 tcitem := tcitems[0] 871 iLog.Debug(fmt.Sprintf("Revision collection object to respository with tcitem: %v", tcitem)) 872 873 name := tcitem["name"].(string) 874 iLog.Debug(fmt.Sprintf("Revision collection object to respository with trancodename: %s", name)) 875 876 if isdefault { 877 iLog.Debug(fmt.Sprintf("Revision collection object to in respository to set default to false: %s", name)) 878 filter := bson.M{"isdefault": true, 879 "name": newname} 880 update := bson.M{"$set": bson.M{"isdefault": false, "system.updatedon": time.Now().UTC(), "system.updatedby": "system"}} 881 882 iLog.Debug(fmt.Sprintf("Revision collection object to in respository with filter: %v", filter)) 883 iLog.Debug(fmt.Sprintf("Revision collection object to in respository with update: %v", update)) 884 err := documents.DocDBCon.UpdateCollection(collectionname, filter, update, nil) 885 if err != nil { 886 iLog.Error(fmt.Sprintf("failed to update collection object: %v", err)) 887 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 888 return 889 } 890 } 891 892 utcTime := time.Now().UTC() 893 tcitem["system.updatedon"] = utcTime 894 tcitem["system.updatedby"] = "system" 895 tcitem["system.createdon"] = utcTime 896 tcitem["system.createdby"] = "system" 897 tcitem["name"] = newname 898 tcitem["version"] = newvision 899 900 tcitem["isdefault"] = isdefault 901 902 tcitem["status"] = 1 903 904 tcitem["uuid"] = uuid.New().String() 905 906 if tcitem["description"] == nil { 907 tcitem["description"] = "" 908 } 909 910 tcitem["description"] = utcTime.String() + ": Revision collection object " + name + " to " + newname + " with version " + newvision + " \n " + tcitem["description"].(string) 911 912 delete(tcitem, "_id") 913 914 iLog.Debug(fmt.Sprintf("Revision collection object to respository with tcitem: %v", tcitem)) 915 916 insertResult, err := documents.DocDBCon.InsertCollection(collectionname, tcitem) 917 918 if err != nil { 919 iLog.Error(fmt.Sprintf("failed to insert collection object: %v", err)) 920 ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) 921 return 922 } 923 id = insertResult.InsertedID.(primitive.ObjectID).Hex() 924 925 tcitem["_id"] = id 926 result := map[string]interface{}{ 927 "id": id, 928 "data": tcitem, 929 "status": "Success", 930 } 931 ctx.JSON(http.StatusOK, gin.H{"data": result}) 932 933 } 934 935 // buildProjectionFromJSON parses the given JSON data into a Go map and builds a projection based on the map. 936 // It takes the JSON data as a byte slice and the convert type as a string. 937 // The function returns the built projection as a bson.M map and an error if any occurred during parsing or building. 938 func (c *CollectionController) buildProjectionFromJSON(jsonData []byte, converttype string) (bson.M, error) { 939 // Parse JSON into a Go map 940 var jsonMap map[string]interface{} 941 err := json.Unmarshal(jsonData, &jsonMap) 942 if err != nil { 943 return nil, err 944 } 945 946 // Build the projection 947 projection := bson.M{} 948 c.buildProjection(jsonMap, "", projection, converttype) 949 950 return projection, nil 951 } 952 953 // buildProjection recursively builds a projection document based on the provided JSON map. 954 // The projection document is used to specify which fields to include or exclude in a MongoDB query. 955 // Parameters: 956 // - jsonMap: The JSON map containing the field names and values. 957 // - prefix: The prefix to be added to the field names. 958 // - projection: The projection document being built. 959 // - converttype: The type of conversion being performed (e.g., "filter"). 960 961 func (c *CollectionController) buildProjection(jsonMap map[string]interface{}, prefix string, projection bson.M, converttype string) { 962 for key, value := range jsonMap { 963 fieldName := key 964 if prefix != "" { 965 fieldName = prefix + "." + key 966 } 967 968 if key == "_id" && converttype == "filter" { 969 parsedObjectID, _ := primitive.ObjectIDFromHex(value.(string)) 970 projection[fieldName] = parsedObjectID 971 } else { 972 switch v := value.(type) { 973 case bool: 974 projection[fieldName] = v 975 976 case map[string]interface{}: 977 subProjection := bson.M{} 978 c.buildProjection(v, fieldName, subProjection, converttype) 979 if len(subProjection) > 0 { 980 projection[fieldName] = subProjection 981 } 982 default: 983 projection[fieldName] = value 984 } 985 } 986 } 987 } 988 989 // ValidateIfObjectExist checks if an object exists in a collection based on the provided collection name and filter. 990 // It returns a boolean value indicating whether the object exists or not, and an error if any. 991 992 func ValidateIfObjectExist(collectionname string, filter bson.M, User string) (bool, error) { 993 iLog := logger.Log{ModuleName: logger.API, User: User, ControllerName: "ValidateIfObjectExist"} 994 /* startTime := time.Now() 995 996 defer func() { 997 elapsed := time.Since(startTime) 998 iLog.PerformanceWithDuration("collectionop.ValidateIfObjectExist", elapsed) 999 }() 1000 defer func() { 1001 err := recover() 1002 if err != nil { 1003 iLog.Error(fmt.Sprintf("collectionop.ValidateIfObjectExist Error: %v", err)) 1004 } 1005 }() */ 1006 iLog.Debug(fmt.Sprintf("Validate if object exist in collection")) 1007 1008 collectionitems, err := documents.DocDBCon.QueryCollection(collectionname, filter, nil) 1009 if err != nil { 1010 iLog.Error(fmt.Sprintf("failed to query collection: %v", err)) 1011 return false, err 1012 } 1013 if len(collectionitems) == 0 { 1014 return false, nil 1015 } 1016 return true, nil 1017 }