github.com/mdaxf/iac@v0.0.0-20240519030858-58a061660378/notifications/notifications.go (about)

     1  package notifications
     2  
     3  import (
     4  	"fmt"
     5  	"time"
     6  
     7  	"go.mongodb.org/mongo-driver/bson"
     8  
     9  	"github.com/mdaxf/iac/com"
    10  	"github.com/mdaxf/iac/logger"
    11  
    12  	"github.com/mdaxf/iac/documents"
    13  )
    14  
    15  // GetNotificationsbyUser retrieves notifications for a specific user.
    16  // It takes a user string as input and returns a list of notifications and an error.
    17  // The function first logs the start time and defer logs the performance duration.
    18  // It also recovers from any panics and logs the error if any.
    19  // The function constructs a filter using the user parameter and other conditions.
    20  // It queries the "Notifications" collection using the constructed filter.
    21  // If there is an error in querying the collection, it logs the error and returns nil and the error.
    22  // Otherwise, it logs the retrieved notification list and returns it along with nil error.
    23  
    24  func GetNotificationsbyUser(user string) (interface{}, error) {
    25  	iLog := logger.Log{ModuleName: logger.Framework, User: "System", ControllerName: "Notifications"}
    26  
    27  	startTime := time.Now()
    28  	defer func() {
    29  		elapsed := time.Since(startTime)
    30  		iLog.PerformanceWithDuration("notification.GetNotificationsbyUser", elapsed)
    31  	}()
    32  
    33  	/*	defer func() {
    34  			err := recover()
    35  			if err != nil {
    36  				iLog.Error(fmt.Sprintf("Error: %v", err))
    37  			}
    38  		}()
    39  	*/
    40  	var filter bson.M
    41  	filter = bson.M{
    42  		"$or": []bson.M{
    43  			{"receipts." + user: bson.M{"$in": []int{1, 2, 3}}},
    44  			{
    45  				"$and": []bson.M{
    46  					{"receipts." + user: bson.M{"$exists": false}},
    47  					{"receipts.all": bson.M{"$exists": true}},
    48  				},
    49  			},
    50  			{"sender": user},
    51  		},
    52  		"status": bson.M{"$in": []int{1, 2}},
    53  	}
    54  
    55  	collectionitems, err := documents.DocDBCon.QueryCollection("Notifications", filter, nil)
    56  
    57  	if err != nil {
    58  
    59  		iLog.Error(fmt.Sprintf("failed to retrieve the list from notification: %v", err))
    60  		return nil, err
    61  	}
    62  	iLog.Debug(fmt.Sprintf("Get notification list from respository with data: %s", logger.ConvertJson(collectionitems)))
    63  
    64  	return collectionitems, nil
    65  }
    66  
    67  // SaveNotification saves a notification for a specific user.
    68  // It takes ndata, which is the data of the notification, and user, which is the username of the user.
    69  // It returns an error if there was a problem saving the notification.
    70  
    71  func SaveNotification(ndata interface{}, user string) error {
    72  	iLog := logger.Log{ModuleName: logger.Framework, User: user, ControllerName: "Notifications"}
    73  
    74  	startTime := time.Now()
    75  	defer func() {
    76  		elapsed := time.Since(startTime)
    77  		iLog.PerformanceWithDuration("notification.GetNotificationsbyUser", elapsed)
    78  	}()
    79  
    80  	/*	defer func() {
    81  			err := recover()
    82  			if err != nil {
    83  				iLog.Error(fmt.Sprintf("Error: %v", err))
    84  			}
    85  		}()
    86  	*/
    87  	_, err := documents.DocDBCon.InsertCollection("Notifications", ndata)
    88  	if err != nil {
    89  		iLog.Error(fmt.Sprintf("failed to save notification: %v", err))
    90  		return err
    91  	}
    92  	return nil
    93  }
    94  
    95  func UpdateNotification(ndata interface{}, user string, comments string, status int) error {
    96  	iLog := logger.Log{ModuleName: logger.Framework, User: user, ControllerName: "Notifications"}
    97  
    98  	startTime := time.Now()
    99  	defer func() {
   100  		elapsed := time.Since(startTime)
   101  		iLog.PerformanceWithDuration("notification.UpdateNotification", elapsed)
   102  	}()
   103  
   104  	defer func() {
   105  		err := recover()
   106  		if err != nil {
   107  			iLog.Error(fmt.Sprintf("Error: %v", err))
   108  		}
   109  	}()
   110  
   111  	newdata := ndata.(map[string]interface{})
   112  	newdata["system.updatedby"] = user
   113  	newdata["system.updatedon"] = time.Now()
   114  
   115  	if newdata["sender"] != user && newdata["receipts.all"] == 1 && (newdata["receipts."+user] == nil || newdata["receipts."+user] == 1) {
   116  		newdata["receipts."+user] = 2
   117  	}
   118  	userhisitem := make(map[string]interface{})
   119  	userhisitem["status"] = newdata["receipts."+user]
   120  	userhisitem["updatedby"] = user
   121  	userhisitem["updatedon"] = time.Now()
   122  	userhisitem["comments"] = comments
   123  	userhistory := newdata["histories"]
   124  	if userhistory == nil {
   125  		userhistory = make([]map[string]interface{}, 1)
   126  		userhistory.([]map[string]interface{})[0] = userhisitem
   127  		newdata["histories"] = userhistory
   128  	} else {
   129  		userhistory = append(userhistory.([]interface{}), userhisitem)
   130  		newdata["histories"] = userhistory
   131  	}
   132  	if status != 0 {
   133  		newdata["status"] = status
   134  	}
   135  	var filter bson.M
   136  	filter = bson.M{"uuid": newdata["uuid"]}
   137  	/*	objectid, err := primitive.ObjectIDFromHex(newdata["_id"])
   138  		if err != nil {
   139  			doc.iLog.Error(fmt.Sprintf("failed to convert id to objectid with error: %s", err))
   140  			return err
   141  		}
   142  
   143  		filter := bson.M{"_id": objectid}  */
   144  
   145  	delete(newdata, "_id")
   146  	err := documents.DocDBCon.UpdateCollection("Notifications", filter, nil, newdata)
   147  	if err != nil {
   148  		iLog.Error(fmt.Sprintf("failed to update notification: %v", err))
   149  		return err
   150  	}
   151  
   152  	go com.IACMessageBusClient.Invoke("send", "IAC_SERVER_NOTIICATION_UPDATE", newdata, "")
   153  
   154  	return nil
   155  }
   156  
   157  func UpdateNotificationbyUUID(uuid string, user string, comments string) error {
   158  	iLog := logger.Log{ModuleName: logger.Framework, User: user, ControllerName: "Notifications"}
   159  
   160  	startTime := time.Now()
   161  	defer func() {
   162  		elapsed := time.Since(startTime)
   163  		iLog.PerformanceWithDuration("notification.UpdateNotificationbyUUID", elapsed)
   164  	}()
   165  
   166  	defer func() {
   167  		err := recover()
   168  		if err != nil {
   169  			iLog.Error(fmt.Sprintf("Error: %v", err))
   170  		}
   171  	}()
   172  
   173  	var filter bson.M
   174  	filter = bson.M{"uuid": uuid}
   175  
   176  	update := bson.M{
   177  		"$set": bson.M{
   178  			"system.updatedby": user,
   179  			"system.updatedon": time.Now(),
   180  			"receipts." + user: 2,
   181  			"histories": bson.M{
   182  				"$push": bson.M{
   183  					"status":    1,
   184  					"updatedby": user,
   185  					"updatedon": time.Now(),
   186  					"comments":  comments,
   187  				},
   188  			},
   189  		},
   190  	}
   191  
   192  	err := documents.DocDBCon.UpdateCollection("Notifications", filter, nil, update)
   193  	if err != nil {
   194  		iLog.Error(fmt.Sprintf("failed to update notification: %v", err))
   195  		return err
   196  	}
   197  
   198  	data := make(map[string]interface{})
   199  	data["uuid"] = uuid
   200  	data["comments"] = comments
   201  	data["user"] = user
   202  
   203  	go com.IACMessageBusClient.Invoke("send", "IAC_SERVER_NOTIICATION_REPLY", data, "")
   204  
   205  	return nil
   206  }
   207  
   208  // CreateNewNotification creates a new notification with the given notification data and user.
   209  // It sets various system fields such as created by, created on, updated by, updated on, and status.
   210  // If receipts are not provided, it sets the receipts to "all".
   211  // It also adds a history entry with status, updated by, updated on, and comments.
   212  // The notification data is then inserted into the "Notifications" collection in the database.
   213  // Returns an error if there was a failure in saving the notification.
   214  
   215  func CreateNewNotification(notificationdata interface{}, user string) error {
   216  	iLog := logger.Log{ModuleName: logger.Framework, User: "System", ControllerName: "Notifications"}
   217  
   218  	startTime := time.Now()
   219  	defer func() {
   220  		elapsed := time.Since(startTime)
   221  		iLog.PerformanceWithDuration("notification.CreateNewNotification", elapsed)
   222  	}()
   223  
   224  	/*	defer func() {
   225  		err := recover()
   226  		if err != nil {
   227  			iLog.Error(fmt.Sprintf("Error: %v", err))
   228  		}
   229  	}()  */
   230  	ndata := notificationdata.(map[string]interface{})
   231  	ndata["system.createdby"] = user
   232  	ndata["system.createdon"] = time.Now()
   233  	ndata["system.updatedby"] = user
   234  	ndata["system.updatedon"] = time.Now()
   235  	ndata["status"] = 1
   236  	ndata["sender"] = user
   237  	if ndata["receipts"] == nil {
   238  		ndata["receipts"] = map[string]interface{}{"all": 1}
   239  	}
   240  	history := make([]map[string]interface{}, 1)
   241  	history[0] = make(map[string]interface{})
   242  	history[0]["status"] = 1
   243  	history[0]["updatedby"] = user
   244  	history[0]["updatedon"] = time.Now()
   245  	history[0]["comments"] = "New Notification"
   246  	ndata["histories"] = history
   247  	_, err := documents.DocDBCon.InsertCollection("Notifications", ndata)
   248  	if err != nil {
   249  		iLog.Error(fmt.Sprintf("failed to save notification: %v", err))
   250  		return err
   251  	}
   252  
   253  	go com.IACMessageBusClient.Invoke("send", "IAC_SERVER_NOTIICATION", ndata, "")
   254  
   255  	return nil
   256  }