PageRenderTime 39ms CodeModel.GetById 2ms app.highlight 29ms RepoModel.GetById 1ms app.codeStats 1ms

/BC.Intercompany.Api/BC.Intercompany.Domain/DomainManager/UserManagementDomainManager.cs

https://bitbucket.org/abhishekmaitrey/bc.intercompanyportal
C# | 448 lines | 314 code | 105 blank | 29 comment | 22 complexity | 0999bb0e825df01e1e6a26bbfe829428 MD5 | raw file
  1using BC.Intercompany.Domain.DataManager;
  2using BC.Intercompany.Models;
  3using System;
  4using System.IO;
  5using System.Collections.Generic;
  6using System.Linq;
  7using System.Text;
  8using System.Threading.Tasks;
  9using Newtonsoft.Json;
 10using Newtonsoft.Json.Linq;
 11using System.Linq;
 12using System.Xml;
 13using System.Xml.Linq;
 14using BC.Intercompany.Domain.Enums;
 15using System.Runtime.Caching;
 16using System.Configuration;
 17
 18namespace BC.Intercompany.Domain.DomainManager
 19    {
 20    public class UserManagementDomainManager : IUserManagementDomainManager
 21        {
 22        private readonly IUserManagementDataManager _userDataManager;
 23        private readonly ICommonDomainManager _commonDomainManager;
 24        private readonly ICompanyCodeDomainManager _companyCodeDomainManager;
 25
 26        public UserManagementDomainManager(IUserManagementDataManager userDataManager,
 27            ICommonDomainManager commonDomainManager, ICompanyCodeDomainManager companyCodeDomainManager)
 28            {
 29            this._userDataManager = userDataManager;
 30            this._commonDomainManager = commonDomainManager;
 31            this._companyCodeDomainManager = companyCodeDomainManager;
 32            }
 33
 34
 35        public async Task<IEnumerable<MenuModel>> GetAllMenusByRoleId(int roleId)
 36            {
 37            return await this._userDataManager.GetAllMenusByRoleId(roleId);
 38            }
 39
 40        public async Task<UserManagementModel> FindUserAsync(string userName, string password)
 41            {
 42            //Call GetUser1
 43            //Call IsAuthenticated
 44            //If authentical and not present in DB, insert into DB, else pick data from db
 45
 46            var userManagementModel = new UserManagementModel();
 47            userManagementModel = this._userDataManager.GetUser1(userName, password);
 48            if (!this._userDataManager.IsAuthenticated(userName, password))
 49                {
 50                //The user does not exist in AD, login not possible
 51
 52                return userManagementModel;
 53                }
 54            else
 55                {
 56                //The user exists in AD, check if user available in DB
 57                var userModel = new UserManagementModel();
 58
 59
 60                try
 61                    {
 62                    userModel = await this._userDataManager.FindUserOnlyAsync(userName, password);
 63                    }
 64                catch (Exception ex)
 65                    {
 66
 67                    }
 68
 69                if (String.IsNullOrEmpty(userModel.UserName))
 70                    {
 71                    //User not available in DB; Insert the user with guest role.
 72                    userModel = _userDataManager.LoadADUsersByEmailId(userManagementModel.Email);
 73                    _userDataManager.AddNewUserToDatabase(userModel);
 74                    }
 75                }
 76            return await this._userDataManager.FindUserAsync(userName, password);
 77            }
 78
 79        public async Task<IEnumerable<AuthoriserDetailsModel>> GetAllLimitsForAuthorisers(long UserId)
 80            {
 81            return await this._userDataManager.GetAllLimitsForAuthorisers(UserId);
 82            }
 83
 84        public async Task<bool> AddADUer(UserManagementModel newUser)
 85            {
 86            return await this._userDataManager.AddADUer(newUser);
 87            }
 88
 89        public async Task<ResultModel> SaveAuthoriserImportMessage(string Type, string Message)
 90            {
 91            return await this._userDataManager.SaveAuthoriserImportMessage(Type, Message);
 92            }
 93
 94        public ResultModel SaveAuthoriserErrorMessage(string Type, string Message)
 95            {
 96            return this._userDataManager.SaveAuthoriserErrorMessage(Type, Message);
 97            }
 98
 99        public async Task<ResultModel> AddUserLoginRecord(UserManagementModel userModel)
100            {
101            return await this._userDataManager.AddUserLoginRecord(userModel);
102            }
103
104        public async Task<IEnumerable<UserManagementModel>> SearchADUser(string SearchUsername)
105            {
106            return await this._userDataManager.SearchADUser(SearchUsername);
107
108            }
109
110        public async Task<UserManagementModel> LoadBlankUserDetails()
111            {
112            UserManagementModel objUserManagement = new UserManagementModel();
113            objUserManagement.UserRolesList = await this._commonDomainManager.GetAllRoles();
114            objUserManagement.CountryList = await this._commonDomainManager.GetAllCountries();
115            return objUserManagement;
116            }
117
118        public bool CheckUserEmail_Exists(string email)
119            {
120            return _userDataManager.CheckUserEmail_Exists(email);
121            }
122
123
124        public async Task<ResultModel> CreateUser(UserManagementModel userModel)
125            {
126            ResultModel resultModel = new ResultModel();
127            bool isClientEmailExists = this.CheckUserEmail_Exists(userModel.Email);
128
129            if (isClientEmailExists)
130                {
131                resultModel.IsSuccessful = false;
132                resultModel.ResponseMessage =
133                    "User with this email already exists into the system. User details not saved.";
134                // This messages should be come from some constants file or some xml file.. we will do it later..
135                return resultModel;
136                }
137            else
138                {
139                return await this._userDataManager.CreateUser(userModel);
140                }
141            }
142
143        public async Task<ResultModel> UpdateAuthoriser(string xmlStream)
144            {
145            ResultModel resultModel = new ResultModel();
146
147              List<UserManagementModel> sapUserList = new List<UserManagementModel>();
148
149             sapUserList = await this.GetUserListFromSAPStram(xmlStream);
150
151            resultModel = await this._userDataManager.SAVESAPAuthorisers(sapUserList);
152
153            int batchjobid = resultModel.Id;
154
155            if (batchjobid > 0)
156            { 
157                    resultModel = await this._userDataManager.MarkBatchJobDataInvalid(batchjobid);
158                    resultModel = await this.UpdateAuthoriserUsersFromSAP(batchjobid);
159            }
160            return resultModel;
161
162            }
163
164        private async Task<ResultModel> UpdateAuthoriserUsersFromSAP(int BatchjobMainId)
165            {
166            ResultModel resultModel = new ResultModel();
167
168            IEnumerable<UserManagementModel> BatchJobListData = new List<UserManagementModel>();
169            IEnumerable<UserManagementModel> AuthotisrList = new List<UserManagementModel>();
170
171
172
173            BatchJobListData = await this._commonDomainManager.GetAllValidAuthoriserImportDataByMainId(BatchjobMainId);
174
175
176
177            foreach (var batJobData in BatchJobListData)
178                {
179                UserManagementModel objModel = new UserManagementModel();
180
181
182                objModel = await this.IsUserDataAlreadyExists(batJobData.SAP_USER_ID, batJobData.COMPANY_CODE, batJobData.RELEASE_ROLE, batJobData.EMAIL_ID);
183
184
185                if (objModel == null)
186                    {
187                    resultModel = await this._userDataManager.InsertDataForAuthoriser(batJobData.BatchJobId);
188                    }
189                else if (!String.IsNullOrEmpty(objModel.COMPANY_CODE))
190                    {
191                    //SAP returns status as string. We have stored status as boolean in table. Either active or in active.. 
192                     objModel.USER_STATUS = objModel.USER_STATUS == "Active" ? "Active" : "Inactive";
193                     if (objModel.VALID_TO_DATE != batJobData.VALID_TO_DATE || objModel.USER_STATUS.ToUpper() != batJobData.USER_STATUS.ToUpper())
194                        {
195                       
196                        resultModel = await this._userDataManager.UpdateAuthoriserDetailsFromSAP(objModel.AuthoriserLimitId, batJobData.BatchJobId);
197                        }
198                    }
199
200                }
201
202
203            AuthotisrList = await this._userDataManager.GetAllAuthoriserDataForBatchJobProcess();
204
205            foreach (var objAuthoriserData in AuthotisrList)
206                {
207                UserManagementModel objModel = new UserManagementModel();
208
209                resultModel = await this._userDataManager.DeleteAuthorisersFromSAP(objAuthoriserData.AuthoriserLimitId, BatchjobMainId);
210                
211
212                }
213
214           
215            return resultModel;
216
217            }
218
219        private async Task<UserManagementModel> IsUserDataAlreadyExists(string SAPUserName, string CompanyCode, string Release_Role, string Email)
220            {
221
222            UserManagementModel objUserManageModel = new UserManagementModel();
223            return await this._userDataManager.IsAuthoriserDataExists(SAPUserName, CompanyCode, Release_Role, Email);
224
225            }
226
227
228        private async Task<List<UserManagementModel>> GetUserListFromSAPStram(string xmlStream)
229            {
230            List<UserManagementModel> userModelList = new List<UserManagementModel>();
231            ResultModel resultModel = new ResultModel();
232
233            XmlDocument xmlDoc = new XmlDocument();
234
235            xmlDoc.LoadXml(xmlStream);
236            XmlNodeList nodeList = xmlDoc.DocumentElement.SelectNodes("LIST_OF_PO_APPROVERS/ITEM");
237
238            foreach (XmlNode node in nodeList)
239                {
240                UserManagementModel sapUserModel = new UserManagementModel();
241                sapUserModel.USER_FIRST_NAME = node.SelectSingleNode("USER_FIRST_NAME").InnerText;
242                sapUserModel.USER_LAST_NAME = node.SelectSingleNode("USER_LAST_NAME").InnerText;
243                sapUserModel.COMPANY_CODE = node.SelectSingleNode("COMPANY_CODE").InnerText;
244                sapUserModel.RELEASE_ROLE = node.SelectSingleNode("RELEASE_ROLE").InnerText;
245                sapUserModel.USER_STATUS = node.SelectSingleNode("USER_STATUS").InnerText;
246                sapUserModel.EMAIL_ID = node.SelectSingleNode("EMAIL_ID").InnerText;
247                sapUserModel.SAP_USER_ID = node.SelectSingleNode("SAP_USER_ID").InnerText;
248                if (!string.IsNullOrEmpty(node.SelectSingleNode("VALID_TO_DATE").InnerText.ToString()))
249                    sapUserModel.VALID_TO_DATE = Convert.ToDateTime(node.SelectSingleNode("VALID_TO_DATE").InnerText);
250                sapUserModel.ALIAS = node.SelectSingleNode("ALIAS").InnerText;
251                userModelList.Add(sapUserModel);
252                }
253
254
255
256
257
258            return userModelList;
259
260            }
261
262        public static string StreamToString(Stream str)
263            {
264            using (BinaryReader rdr = new BinaryReader(str))
265                {
266                using (MemoryStream mem = new MemoryStream())
267                    {
268                    byte[] buf = new byte[256];
269                    int bt;
270                    int bts = 0;
271                    while ((bt = rdr.Read(buf, 0, 256)) > 0)
272                        {
273                        mem.Write(buf, 0, bt);
274                        bts += bt;
275                        }
276                    mem.Position = 0;
277                    byte[] bytes = new byte[bts];
278                    mem.Read(bytes, 0, bytes.Length);
279                    return Encoding.ASCII.GetString(bytes);
280                    }
281                }
282            }
283
284        public async Task<UserDetailsModel> LoadCurrentUserDetails(long userId)
285            {
286            return await this._userDataManager.LoadCurrentUserDetails(userId);
287            }
288
289        /*
290        //This code will be used once we integrate import of authorisers from SAP, I am keeping it commented for future use..- Shailesh Gaikwad
291        public async Task<UserDetailsModel> SearchDbForUserByEmail(string email)
292        {
293           
294                // If exists, return User details from Db
295                return await _userDataManager.SearchDbForUserByEmail(email);
296        }
297        */
298        public async Task<UserDetailsModel> SearchDbForUserByEmail(string email)
299            {
300            // Check if User exists in Db
301            if (_userDataManager.IsUserFoundInDb(email))
302                {
303                // If exists, return User details from Db
304                return await _userDataManager.SearchDbForUserByEmail(email);
305                }
306            // If User doesn't exist in Db
307            else
308                {
309                // Check if User exists in AD
310                if (_userDataManager.IsUserFoundInAd(email))
311                    {
312                    // If exists in AD, find the user and store in DB
313                    try
314                        {
315                        // load user model from AD
316                        var userManagementModel = _userDataManager.LoadADUsersByEmailId(email);
317
318                        // Add User to Db
319                        _userDataManager.AddNewUserToDatabase(userManagementModel);
320
321                        // return User details from Db
322                        return await _userDataManager.SearchDbForUserByEmail(email);
323
324                        }
325                    catch (Exception ex)
326                        {
327                        return new UserDetailsModel();
328                        }
329
330                    }
331                // If User does not exist in AD
332                else
333                    {
334                    // Return empty User details object
335                    return new UserDetailsModel();
336                    }
337                }
338            }
339        //
340
341
342
343        public async Task<ResultModel> ToggleUser(string guid, bool status, long ModifiedBy)
344            {
345            return await this._userDataManager.ToggleUser(guid, status, ModifiedBy);
346            }
347
348        public async Task<UserManagementModel> GetUserDetailsFromDB(string guid)
349            {
350            return await this._userDataManager.GetUserDetailsFromDB(guid);
351            }
352
353        public async Task<IEnumerable<AuthoriserDetailsModel>> GetAllAuthorizers()
354            {
355
356            IEnumerable<AuthoriserDetailsModel> AuthoriserList;
357
358            MemoryCache memoryCache = MemoryCache.Default;
359            var res = memoryCache.Get("AuthoriserList");
360            if (res != null)
361                {
362                return (IEnumerable<AuthoriserDetailsModel>)res;
363                }
364            else
365                {
366                AuthoriserList = await _userDataManager.GetAllAuthorizers();
367                memoryCache.Add("AuthoriserList", AuthoriserList, DateTimeOffset.UtcNow.AddMinutes(60));
368                return AuthoriserList;
369                }
370            }
371
372        public async Task<IEnumerable<AuthoriserDetailsModel>> GetAllAuthorizersBySearchString(String SearchString)
373            {
374
375            return await _userDataManager.GetAllAuthorizersBySearchString(SearchString);
376            }
377
378        public async Task<IEnumerable<UserSelectModel>> GetAllUsersForHomePageSearch()
379            {
380
381            return await _userDataManager.GetAllUsersForHomePageSearch();
382            }
383
384
385
386
387        public async Task<IEnumerable<AuthoriserDetailsModel>> GetSpecificAuthorizersList(long AuthoriserId)
388            {
389            var Authorizers = await this._userDataManager.GetSpecificAuthorizersList(AuthoriserId);
390
391            return Authorizers;
392
393            }
394
395
396
397        public async Task<IEnumerable<UserManagementModel>> GetAllUsers(int userId)
398            {
399            return await this._userDataManager.GetAllUsers(userId);
400            }
401
402        public async Task<UserManagementModel> GetUserDetails(string guid)
403            {
404            UserManagementModel objUser = new UserManagementModel();
405            if (!string.IsNullOrEmpty(guid.Trim()))
406                objUser = await this._userDataManager.GetUserDetails(guid);
407
408            objUser.UserRolesList = await this.GetUserRolesWithoutAuthorizerAndRequestor();
409            objUser.CountryList = await this._commonDomainManager.GetAllCountries();
410
411            return objUser;
412            }
413
414        private async Task<IEnumerable<UserRoleModel>> GetUserRolesWithoutAuthorizerAndRequestor()
415            {
416            List<UserRoleModel> userRoles = await this._commonDomainManager.GetAllRoles() as List<UserRoleModel>;
417           // userRoles.RemoveAll(x => x.RoleId == (int)Roles.AUTHORISER);
418
419            userRoles.RemoveAll(x => x.RoleId == (int)Roles.GUEST);
420            userRoles.RemoveAll(x => x.RoleId == (int)Roles.ADMIN);
421            return userRoles;
422
423            }
424
425        public async Task<ResultModel> EditUser(UserManagementModel userModel)
426            {
427
428            var result = new ResultModel();
429            try
430                {
431
432                return await this._userDataManager.EditUser(userModel);
433
434                }
435            catch (Exception ex)
436                {
437                result.IsSuccessful = false;
438                result.ResponseMessage = ex.Message;
439                return result;
440                }
441
442            }
443        public async Task<ResultModel> DeleteUser(Guid guid)
444            {
445            return await this._userDataManager.DeleteUser(guid);
446            }
447        }
448    }