public bool Save(ModelStateDictionary modelState, int userID, int employeeID, List <int> warehouseIDs) { QueryOutput queryResult; if (!Validate(modelState)) { return(Result = false); } if (ID == 0 && Query <bool>(new DbQuery(userID, employeeID, DbAction.Login.View, String.Format("select case when (select top 1 ID from Login where BussinessID = {0} and Username = N'{1}' and Status = 'active') is null then 0 else 1 end", BussinessID, Username)), out queryResult).FirstOrDefault()) { Messages.Add("Tài khoản đã được sử dụng"); ErrorFields.Add("Username"); return(Result = false); } if (Username != "admin" && Permission == null) { Messages.Add("Tài khoản chưa được cấp quyền"); return(Result = false); } var query = ""; var id = ID.ToString(); var action = ""; if (ID > 0) { query = String.Format(@"update Login set Username = (case when Username = '******' then 'admin' else N'{0}' end), Password = N'{1}', EmployeeID = {2}, Type = N'{4}' where ID = {3}", new object[] { Username, Password, EmployeeID.DbValue(), ID, Type }); action = DbAction.Login.Modify; } else { query = String.Format(@"declare @ID table (ID int) insert Login(Username, Password, BussinessID, EmployeeID, Status, Type) output inserted.ID into @ID values ('{0}', N'{1}', {2}, {3}, 'active', N'{4}')", new object[] { Username, Password, BussinessID, EmployeeID.DbValue(), Type }); id = "(select top 1 ID from @ID)"; action = DbAction.Login.Create; } if (Username != "admin") { query += String.Format( " if ((select count(Username) from Login where ID = {0} and Username = '******') = 0) begin delete LoginPermission where LoginID = {0}", id); var permissions = Permission.AuthorizedPermissions(); if (permissions.Count > 0) { query += String.Format(" insert into LoginPermission(LoginID, Action) values {0}", String.Join(",", permissions.Select(p => String.Format("({0}, N'{1}')", id, p)))); } if (warehouseIDs != null && warehouseIDs.Count > 0) { query += String.Format(" insert into LoginWarehouse(LoginID, WarehouseID) values {0}", String.Join(",", warehouseIDs.Select(wh => String.Format("({0}, {1})", id, wh)))); } query += " end"; } Result = Execute(new DbQuery(userID, employeeID, action, query, true, id, "Username"), out queryResult); if (Result) { Messages = new List <string>() { "Lưu thông tin thành công" } } ; return(Result); }