コード例 #1
0
        public ActionResult CorporateUpload()
        {
            var uploadMediaLocation = _mediaRepository.GetSamplesLocation();
            var model = new CorporateUploadEditModel
            {
                UploadCsvMediaUrl = uploadMediaLocation.Url
            };

            return(View(model));
        }
コード例 #2
0
        private bool ParseMemberUploadbyAces(string file, CorporateAccount corporateAccount, List <long> customerList, IEnumerable <Language> languages, IEnumerable <Lab> labs)
        {
            try
            {
                _logger.Info("Start converting data from CSV to data table :" + DateTime.Now);

                var mediaLocation = _mediaRepository.GetMemberUploadbyAcesFolderLocation();
                var fileToParse   = GetFileName(file, mediaLocation);
                var memberData    = GetRows(fileToParse);

                var corportateUpload = _memberUploadByAcesHelper.Upload(fileToParse, corporateAccount);

                if (memberData == null)
                {
                    return(false);
                }

                var rowCountInFile = memberData.Rows.Count;

                _logger.Info("Data coverted from CSV to Data Table :" + DateTime.Now + " & Row count is : " + rowCountInFile);

                if (IsAnyColumnMissing(memberData))
                {
                    return(false);
                }

                //var failedCustomers = new List<MemberUploadbyAcesFailedCustomerModel>();
                var adjustOrderCustomer = new List <EventCusomerAdjustOrderViewModel>();

                var rows = memberData.AsEnumerable();

                var orgRoleUser = new OrganizationRoleUser()
                {
                    Id = OrgRoleUserId, RoleId = OrgRoleId
                };
                var corporateModel = new CorporateUploadEditModel {
                    Tag = corporateAccount.Tag, CorporateAccountId = corporateAccount.Id, UploadCorporateId = corportateUpload.Id
                };

                var accountAdditionalFields = _accountAdditionalFieldRepository.GetAccountAdditionalFieldsEditModelByAccountId(corporateAccount.Id);
                var index = 1;
                var customerIdWithSameAcesId = new List <CustomerWithDuplicateAcesModel>();

                foreach (DataRow row in rows)
                {
                    _logger.Info(index + " out of " + rowCountInFile + " processing");

                    var customerEditModel = CreateEditModel(row);

                    if (customerEditModel == null)
                    {
                        continue;
                    }
                    var sb = new StringBuilder();

                    try
                    {
                        _logger.Info("Record:  First Name :" + customerEditModel.FirstName + ", Last Name :" + customerEditModel.LastName + " and ACES Id :" + customerEditModel.AcesId);
                        var customerWithDuplicateAcesModel = new CustomerWithDuplicateAcesModel();
                        _corporateUploadService.CorporateUploadDataRow(customerEditModel, languages, labs, null, corporateModel, accountAdditionalFields,
                                                                       adjustOrderCustomer, orgRoleUser, OrgRoleId, customerList, (long)MemberUploadSource.Aces, sb, corportateUpload.Id, out customerWithDuplicateAcesModel);

                        if (customerWithDuplicateAcesModel != null && customerWithDuplicateAcesModel.CustomerId > 0)
                        {
                            customerIdWithSameAcesId.Add(customerWithDuplicateAcesModel);
                        }
                    }
                    catch (Exception ex)
                    {
                        customerEditModel.ErrorMessage = sb.ToString();
                        if (!string.IsNullOrEmpty(ex.Message))
                        {
                            customerEditModel.ErrorMessage += " Error Message: " + ex.Message;
                        }
                        _logger.Error("While Saving customer");
                        _logger.Error(customerEditModel.ErrorMessage);
                        //var model = _memberUploadbyAcesFailedCustomerFactory.Create(customerEditModel);
                        //failedCustomers.Add(model);
                    }
                    _logger.Info(index + " out of " + rowCountInFile + " completed");

                    var memberUploadParseDetail = _memberUploadParseDetailFactory.GetDomain(customerEditModel, corportateUpload.Id);
                    _memberUploadParseDetailRepository.Save(memberUploadParseDetail);

                    index++;
                }

                if (!customerIdWithSameAcesId.IsNullOrEmpty())
                {
                    _customerWithDuplicateAcesIdFileGenerator.GenerateCsvFile(corportateUpload.Id, customerIdWithSameAcesId);
                }

                var failedRecords   = _memberUploadParseDetailRepository.GetByCorporateUploadId(corportateUpload.Id, false);
                var failedCustomers = _memberUploadParseDetailFactory.GetMemberUploadbyAcesFailedCustomerListModel(failedRecords, corportateUpload.SourceId);

                CreateFailedUploadFile(file, mediaLocation, failedCustomers, corportateUpload);

                CreateAdjustOrderUploadFile(file, mediaLocation, adjustOrderCustomer, corportateUpload);

                corportateUpload.ParseStatus = (int)MemberUploadParseStatus.Start;
                corportateUpload             = _memberUploadByAcesHelper.UpdateCorporateUpload(corportateUpload, failedCustomers.Count(), rowCountInFile);

                if (corportateUpload.SuccessfullUploadCount > 0)
                {
                    _logger.Info("Set IsTermByAbsence is True");
                    corportateUpload.IsTermByAbsence = true;
                    _corporateUploadRepository.Save(corportateUpload);

                    _logger.Info("Publishing: Corporate Upload Id: " + corportateUpload.Id);
                    _memberTermByAbsencePublisher.PublishCorporateUpload(corportateUpload.Id);
                    _logger.Info("Publish Successfully: Corporate Upload Id: " + corportateUpload.Id);
                }

                return(failedCustomers.Any() || accountAdditionalFields.Any() || customerList.Any());
            }
            catch (Exception ex)
            {
                _logger.Error(string.Format("Error occurred while processing the {0}.\nMessage: {1}\n\tStackTrace: {2}", file, ex.Message, ex.StackTrace));
                return(false);
            }
        }
コード例 #3
0
        public void CorporateUploadDataRow(CorporateCustomerEditModel customerEditModel, IEnumerable <Language> languages, IEnumerable <Lab> labs,
                                           List <string> customTags, CorporateUploadEditModel corporateModel, IEnumerable <AccountAdditionalFieldsEditModel> accountAdditionalFields,
                                           List <EventCusomerAdjustOrderViewModel> adjustOrderForCustomerEditModel, OrganizationRoleUser createdByOrgRoleUser, long organizationRoleUserId,
                                           List <long> customerList, long?source, StringBuilder sb, long corporateUploadId, out CustomerWithDuplicateAcesModel customerIdWithSameAcesId)
        {
            var    customerWithSameAcesId = new CustomerWithDuplicateAcesModel();
            string errorMessage           = _corporateUploadHelper.CheckAddtionalField(customerEditModel, accountAdditionalFields);

            if (!string.IsNullOrEmpty(errorMessage))
            {
                throw new InvalidOperationException("System will not parse the customer data as " + errorMessage + " is not added for this corporate account.");
            }

            if (!string.IsNullOrEmpty(customerEditModel.PreApprovedPackage))
            {
                var preApprovedPackage = _packageRepository.GetByName(customerEditModel.PreApprovedPackage);
                if (preApprovedPackage == null)
                {
                    throw new InvalidOperationException("Package does not exist");
                }
                customerEditModel.PreApprovedPackageId = preApprovedPackage.Id;
            }

            //Customer customerWithAcesId = null;
            List <Customer> customersWithAcesId = null;

            var isMemberUploadByAces = false;

            isMemberUploadByAces = (source.HasValue && source.Value == (long)MemberUploadSource.Aces);

            if (!string.IsNullOrWhiteSpace(customerEditModel.AcesId))
            {
                customersWithAcesId = _customerRegistrationService.GetCustomersByAcesId(customerEditModel.AcesId);
                //if (!customersWithAcesId.IsNullOrEmpty() && customersWithAcesId.Count() > 1)
                //{
                //    throw new InvalidOperationException("Aces Id can not be duplicate, Aces Id : " + customerEditModel.AcesId + " already assigned.");
                //}

                //customerWithAcesId = customersWithAcesId.IsNullOrEmpty() ? null : customersWithAcesId.First();
            }

            if (customerEditModel.PreApprovedTest != null && customerEditModel.PreApprovedTest.Any())
            {
                var pairs = TestType.A1C.GetNameValuePairs();
                var preApprovedTestExists = pairs.Where(x => customerEditModel.PreApprovedTest.Contains(x.SecondValue.ToLower())).Select(x => x.SecondValue.ToLower());

                var testNotExist = string.Empty;

                if (preApprovedTestExists != null && preApprovedTestExists.Any() && (preApprovedTestExists.Count() != customerEditModel.PreApprovedTest.Count()))
                {
                    var testNotExistInSystem = customerEditModel.PreApprovedTest.Where(x => !preApprovedTestExists.Contains(x.ToLower())).Select(x => x).ToArray();

                    testNotExist = string.Join(",", testNotExistInSystem);
                }
                else if (preApprovedTestExists == null || !preApprovedTestExists.Any())
                {
                    testNotExist = string.Join(",", customerEditModel.PreApprovedTest);
                }

                if (!string.IsNullOrEmpty(testNotExist))
                {
                    throw new InvalidOperationException(testNotExist + " test alias name does not exist in HIP");
                }
            }

            if (string.IsNullOrEmpty(customerEditModel.Activity))
            {
                throw new InvalidOperationException("Activity cannot be blank.");
            }

            if (!isMemberUploadByAces && !(customerEditModel.Activity.ToLower() == UploadActivityType.MailOnly.GetDescription().ToLower() || customerEditModel.Activity.ToLower() == UploadActivityType.OnlyCall.GetDescription().ToLower() ||
                                           customerEditModel.Activity.ToLower() == UploadActivityType.BothMailAndCall.GetDescription().ToLower()))
            {
                throw new InvalidOperationException("Activity value invalid.");
            }

            if (isMemberUploadByAces && !(customerEditModel.Activity.ToLower() == UploadActivityType.MailOnly.GetDescription().ToLower() ||
                                          customerEditModel.Activity.ToLower() == UploadActivityType.None.GetDescription().ToLower() || customerEditModel.Activity.ToLower() == UploadActivityType.BothMailAndCall.GetDescription().ToLower() ||
                                          customerEditModel.Activity.ToLower() == UploadActivityType.DoNotCallDoNotMail.GetDescription().ToLower()))
            {
                throw new InvalidOperationException("Activity value invalid.");
            }

            if (!string.IsNullOrEmpty(customerEditModel.PredictedZip))
            {
                var invalidZipMessage = _customerRegistrationService.ValidateZipCodes(customerEditModel.PredictedZip);
                if (!string.IsNullOrEmpty(invalidZipMessage))
                {
                    throw new InvalidOperationException(invalidZipMessage);
                }
            }

            //if (string.IsNullOrEmpty(customerEditModel.TargetYear))
            //{
            //    throw new InvalidOperationException("Target Year is required");
            //}

            if (!string.IsNullOrEmpty(customerEditModel.TargetYear))
            {
                int targetYear;
                var validTargetYear = int.TryParse(customerEditModel.TargetYear, out targetYear);
                if (!validTargetYear || targetYear < DateTime.Now.Year || targetYear > (DateTime.Now.Year + 2))
                {
                    throw new InvalidOperationException("Invalid Target Year");
                }
            }

            if (!isMemberUploadByAces && !string.IsNullOrEmpty(customerEditModel.Email) && !IsValidEmailAddress(customerEditModel.Email))
            {
                throw new InvalidOperationException("Invalid Customer Email Address.");
            }

            if (!isMemberUploadByAces && !string.IsNullOrEmpty(customerEditModel.AlternateEmail) && !IsValidEmailAddress(customerEditModel.AlternateEmail))
            {
                throw new InvalidOperationException("Invalid Customer Alternate Email Address.");
            }

            if (!isMemberUploadByAces && !string.IsNullOrEmpty(customerEditModel.PcpEmail) && !IsValidEmailAddress(customerEditModel.PcpEmail))
            {
                throw new InvalidOperationException("Invalid PCP Email Address.");
            }

            if (!isMemberUploadByAces)
            {
                if ((!string.IsNullOrEmpty(customerEditModel.BillingMemberId) || !string.IsNullOrEmpty(customerEditModel.BillingMemberPlan)) && (customerEditModel.BillingMemberPlanYear == null || customerEditModel.BillingMemberPlanYear == 0))
                {
                    throw new InvalidOperationException("Billing Year is required");
                }

                if (customerEditModel.BillingMemberPlanYear.HasValue && customerEditModel.BillingMemberPlanYear.Value > 0 && string.IsNullOrEmpty(customerEditModel.BillingMemberId) && string.IsNullOrEmpty(customerEditModel.BillingMemberPlan))
                {
                    throw new InvalidOperationException("Billing MemberID or Billing Plan Name or both is required");
                }

                if (!string.IsNullOrEmpty(customerEditModel.WarmTransferAllowed) && (customerEditModel.WarmTransferAllowed.ToLower() != "yes" && customerEditModel.WarmTransferAllowed.ToLower() != "no"))
                {
                    throw new InvalidOperationException("Invalid WarmTransfer Allowed Value");
                }

                if (!string.IsNullOrEmpty(customerEditModel.WarmTransferAllowed) && string.IsNullOrEmpty(customerEditModel.WarmTransferYear))
                {
                    throw new InvalidOperationException("WarmTransfer Year is required");
                }
                if (!string.IsNullOrEmpty(customerEditModel.WarmTransferYear))
                {
                    int warmTransferYear;
                    var validWarmTransferYear = int.TryParse(customerEditModel.WarmTransferYear, out warmTransferYear);
                    if (!validWarmTransferYear || warmTransferYear < DateTime.Now.Year || warmTransferYear > (DateTime.Now.Year + 2))
                    {
                        throw new InvalidOperationException("Invalid WarmTransfer Year");
                    }
                }

                //if (customerEditModel.RequiredTest != null && customerEditModel.RequiredTest.Any())
                //{
                //    var pairs = TestType.A1C.GetNameValuePairs();
                //    var requiredTestExists = pairs.Where(x => customerEditModel.RequiredTest.Contains(x.SecondValue.ToLower())).Select(x => x.SecondValue.ToLower());

                //    var testNotExist = string.Empty;

                //    if (requiredTestExists != null && requiredTestExists.Any() && (requiredTestExists.Count() != customerEditModel.RequiredTest.Count()))
                //    {
                //        var testNotExistInSystem = customerEditModel.RequiredTest.Where(x => !requiredTestExists.Contains(x.ToLower())).Select(x => x).ToArray();

                //        testNotExist = string.Join(",", testNotExistInSystem);
                //    }
                //    else if (requiredTestExists == null || !requiredTestExists.Any())
                //    {
                //        testNotExist = string.Join(",", customerEditModel.RequiredTest);
                //    }

                //    if (!string.IsNullOrEmpty(testNotExist))
                //        throw new InvalidOperationException(testNotExist + " test alias name does not exist in HIP (Required Test)");

                //    if (string.IsNullOrEmpty(customerEditModel.ForYear))
                //    {
                //        throw new InvalidOperationException("For Year is required");
                //    }
                //    int forYear;
                //    var validforYear = int.TryParse(customerEditModel.ForYear, out forYear);
                //    if (!validforYear || forYear < DateTime.Now.Year || forYear > (DateTime.Now.Year + 2))
                //    {
                //        throw new InvalidOperationException("Invalid For Year");
                //    }
                //}
            }

            if (string.IsNullOrEmpty(customerEditModel.EligibilityYear))
            {
                throw new InvalidOperationException("Eligibility Year is required");
            }

            int eligibilityYear;
            var validEligibilityYear = int.TryParse(customerEditModel.EligibilityYear, out eligibilityYear);

            if (!validEligibilityYear || eligibilityYear < DateTime.Now.Year || eligibilityYear > (DateTime.Now.Year + 2))
            {
                throw new InvalidOperationException("Invalid Eligibility Year");
            }

            var activityPairs = UploadActivityType.MailOnly.GetNameValuePairs();
            var activityId    = activityPairs.First(x => customerEditModel.Activity.ToLower() == x.SecondValue.ToLower()).FirstValue;

            bool isNewCustomer = false;

            DateTime?dob = null;

            if (!string.IsNullOrEmpty(customerEditModel.Dob))
            {
                try
                {
                    dob = Convert.ToDateTime(customerEditModel.Dob);
                }
                catch (Exception ex)
                {
                    throw new Exception("DOB is not in correct format. Please Provide in MM/DD/YYYY", ex);
                }
            }

            if (isMemberUploadByAces)
            {
                if (string.IsNullOrEmpty(customerEditModel.Product))
                {
                    throw new InvalidOperationException("Product Type is required");
                }

                if (!string.IsNullOrEmpty(customerEditModel.Product))
                {
                    var productTypePairs = ProductType.CHA.GetNameValuePairs();

                    if (!productTypePairs.Any(x => x.SecondValue.ToLower() == customerEditModel.Product.ToLower()))
                    {
                        throw new InvalidOperationException("Invalid Product Type");
                    }
                }

                if (string.IsNullOrEmpty(customerEditModel.DNCFlag))
                {
                    throw new InvalidOperationException("DNC is required");
                }
                if (!string.IsNullOrEmpty(customerEditModel.DNCFlag))
                {
                    if (customerEditModel.DNCFlag.Trim() == "1")
                    {
                        customerEditModel.DNCFlag = "yes";
                    }
                    else if (customerEditModel.DNCFlag.Trim() == "0")
                    {
                        customerEditModel.DNCFlag = "no";
                    }
                    else
                    {
                        throw new InvalidOperationException("Invalid DNC, Only 0/1 is accepted.");
                    }
                }
            }
            var customer = _customerRepository.GetCustomerForCorporate(customerEditModel.FirstName, customerEditModel.MiddleName, customerEditModel.LastName,
                                                                       customerEditModel.Email, PhoneNumber.ToNumber(customerEditModel.PhoneHome), PhoneNumber.ToNumber(customerEditModel.PhoneCell),
                                                                       dob, corporateModel == null ? string.Empty : corporateModel.Tag, sb);

            if (customer == null && (sb != null && sb.ToString() != ""))
            {
                throw new Exception("");
            }
            else
            {
                sb = new StringBuilder();
            }

            //IEnumerable<EventCustomer> eventCustomers = null;

            //if (customer != null && customer.CustomerId > 0)
            //{
            //    eventCustomers = _eventCustomerPreApprovedTestService.GetFutureEventCustomers(customer.CustomerId);
            //}

            if (string.IsNullOrWhiteSpace(customerEditModel.State) || string.IsNullOrWhiteSpace(customerEditModel.City) || string.IsNullOrWhiteSpace(customerEditModel.Zip))
            {
                var addressErrorMessage = "";
                if (string.IsNullOrWhiteSpace(customerEditModel.State))
                {
                    addressErrorMessage = addressErrorMessage + "State";
                }

                if (string.IsNullOrWhiteSpace(customerEditModel.City))
                {
                    addressErrorMessage = string.IsNullOrWhiteSpace(addressErrorMessage) ? "City" : addressErrorMessage + ", City";
                }

                if (string.IsNullOrWhiteSpace(customerEditModel.Zip))
                {
                    addressErrorMessage = string.IsNullOrWhiteSpace(addressErrorMessage) ? "Zip" : addressErrorMessage + ", Zip";
                }

                addressErrorMessage = addressErrorMessage + " is required.";

                throw new Exception(addressErrorMessage);
            }

            AddressSanitizingInvalidZip(customerEditModel);

            if (customer != null && !customersWithAcesId.IsNullOrEmpty())
            {
                customersWithAcesId = customersWithAcesId.Where(x => x.CustomerId != customer.CustomerId).ToList();
            }

            if (!customersWithAcesId.IsNullOrEmpty())
            {
                customersWithAcesId.ForEach(x => x.AcesId = "");
            }

            using (var scope = new TransactionScope())
            {
                if (!customersWithAcesId.IsNullOrEmpty())
                {
                    foreach (var member in customersWithAcesId)
                    {
                        _customerService.SaveCustomerOnly(member, organizationRoleUserId);
                    }

                    customerWithSameAcesId.AcesId     = customerEditModel.AcesId;
                    customerWithSameAcesId.CustomerId = customer != null ? customer.CustomerId : 0;
                    customerWithSameAcesId.CustomersWithSameAcesId = string.Join(",", customersWithAcesId.Select(x => x.CustomerId));
                }

                var updatedCustomer = _customerRegistrationService.RegisterCorporateCustomer(customer, customerEditModel, corporateModel == null ? string.Empty : corporateModel.Tag,
                                                                                             createdByOrgRoleUser, languages, labs, sb, activityId, source, out isNewCustomer);

                if (customTags != null && customTags.Any() && updatedCustomer != null)
                {
                    foreach (var customTag in customTags)
                    {
                        _corporateCustomerCustomTagService.Save(new CorporateCustomerCustomTag
                        {
                            CustomerId           = updatedCustomer.CustomerId,
                            IsActive             = true,
                            Tag                  = customTag,
                            DataRecorderMetaData = new DataRecorderMetaData(new OrganizationRoleUser(organizationRoleUserId), DateTime.Now, null)
                        });
                    }
                }

                customerEditModel.CustomerId = updatedCustomer.CustomerId;

                //if (!eventCustomers.IsNullOrEmpty())
                //{
                //    var list = _eventCustomerPreApprovedTestService.MarkcustomerForAdjustOrder(customerEditModel, eventCustomers, createdByOrgRoleUser, updatedCustomer, corporateModel.UploadCorporateId);

                //    if (!list.IsNullOrEmpty())
                //        adjustOrderForCustomerEditModel = adjustOrderForCustomerEditModel.Concat(list).ToList();
                //}

                scope.Complete();
            }

            UpdateNeedVerificationAddress(customerEditModel);

            if (isNewCustomer && customerList != null)
            {
                customerList.Add(customerEditModel.CustomerId);
            }

            UpdateCorporateMemberUpload(corporateUploadId, customerEditModel);

            customerIdWithSameAcesId = customerWithSameAcesId;
        }
コード例 #4
0
        public JsonResult UploadCustomers(UploadCorporateCustomers model)
        {
            var fileName          = model.FileName;
            var pageSize          = model.PageSize;
            var tag               = model.Tag;
            var failedRecordsFile = model.FailedRecordsFile;
            var adjustOrderFile   = model.AdjustOrderRecordsFile;
            var pageNumber        = model.PageNumber;
            var customTags        = model.CustomTags;

            if (customTags != null)
            {
                customTags = customTags.Where(s => !string.IsNullOrEmpty(s)).Select(s => s).ToList();
            }
            var corporateModel = new CorporateUploadEditModel {
                Tag = tag, FileName = fileName, UploadCorporateId = model.UploadCorporateId
            };

            var mediaLocation = _mediaRepository.GetUploadCsvMediaFileLocation();
            var file          = mediaLocation.PhysicalPath + corporateModel.FileName;

            var csvReader = IoC.Resolve <ICsvReader>();

            var languages = _languageRepository.GetAll();
            var labs      = _labRepository.GetAll();

            var failureRecords         = mediaLocation.PhysicalPath + failedRecordsFile;
            var adjustOrderRecordsFile = mediaLocation.PhysicalPath + model.AdjustOrderRecordsFile;

            var customerTable        = csvReader.ReadWithTextQualifier(file);
            var createdByOrgRoleUser = Mapper.Map <OrganizationRoleUserModel, OrganizationRoleUser>(_sessionContext.UserSession.CurrentOrganizationRole);

            var customerIdWithSameAcesId = new List <CustomerWithDuplicateAcesModel>();

            try
            {
                //var failedCustomers = new List<CorporateCustomerEditModel>();
                var adjustOrderForCustomerEditModel = new List <EventCusomerAdjustOrderViewModel>();

                var query = customerTable.AsEnumerable();

                var rows                    = query.Skip(pageSize * (pageNumber - 1)).Take(pageSize);
                var customerToRender        = rows.Count();
                var corporateAccount        = _corporateAccountRepository.GetByTag(tag);
                var accountAdditionalFields = _accountAdditionalFieldRepository.GetAccountAdditionalFieldsEditModelByAccountId(corporateAccount.Id);
                var customerEditModel       = new CorporateCustomerEditModel();

                foreach (DataRow row in rows)
                {
                    var sb = new StringBuilder();
                    try
                    {
                        customerEditModel = _corporateUploadHelper.GetCorporateCustomerEditModel(row);

                        var customerWithDuplicateAcesModel = new CustomerWithDuplicateAcesModel();
                        _corporateUploadService.CorporateUploadDataRow(customerEditModel, languages, labs, customTags, corporateModel,
                                                                       accountAdditionalFields, adjustOrderForCustomerEditModel, createdByOrgRoleUser,
                                                                       _sessionContext.UserSession.CurrentOrganizationRole.OrganizationRoleUserId, null,
                                                                       (long)MemberUploadSource.CorporateUplaod, sb, model.UploadCorporateId.Value, out customerWithDuplicateAcesModel);

                        if (customerWithDuplicateAcesModel != null && customerWithDuplicateAcesModel.CustomerId > 0)
                        {
                            customerIdWithSameAcesId.Add(customerWithDuplicateAcesModel);
                        }
                    }
                    catch (Exception ex)
                    {
                        customerEditModel.ErrorMessage = sb.ToString();
                        if (!string.IsNullOrEmpty(ex.Message))
                        {
                            customerEditModel.ErrorMessage += " Error Message: " + ex.Message;
                        }
                        //failedCustomers.Add(customerEditModel);
                    }

                    var memberUploadParseDetail = _memberUploadParseDetailFactory.GetDomain(customerEditModel, model.UploadCorporateId.Value);
                    _memberUploadParseDetailRepository.Save(memberUploadParseDetail);
                }

                if (!customerIdWithSameAcesId.IsNullOrEmpty())
                {
                    _customerWithDuplicateAcesIdFileGenerator.GenerateCsvFile(model.UploadCorporateId.Value, customerIdWithSameAcesId);
                }

                corporateModel.TotalCustomers = customerTable.Rows.Count;

                var totalPages      = corporateModel.TotalCustomers / pageSize + (corporateModel.TotalCustomers % pageSize != 0 ? 1 : 0);
                var failedCustomers = _memberUploadParseDetailRepository.GetByCorporateUploadId(model.UploadCorporateId.Value, false);
                corporateModel.FailedCustomers = failedCustomers != null?failedCustomers.Count() : 0;

                corporateModel.UploadedCustomers = customerToRender - corporateModel.FailedCustomers;
                corporateModel.IsParseSucceded   = totalPages == pageNumber;

                if (corporateModel.IsParseSucceded)
                {
                    var corporateUploadedBy = _sessionContext.UserSession.FullName;

                    string corporateName = string.Empty;
                    if (corporateAccount != null)
                    {
                        var organization = _organizationRepository.GetOrganizationbyId(corporateAccount.Id);
                        if (organization != null)
                        {
                            corporateName = organization.Name;
                        }
                    }

                    var corporateUploadNotificationModel = _emailNotificationModelsFactory.GetCorporateUploadNotificationViewModel(corporateName, corporateUploadedBy, corporateModel.TotalCustomers, (corporateModel.TotalCustomers - corporateModel.FailedCustomers), corporateModel.FailedCustomers);

                    _notifier.NotifySubscribersViaEmail(NotificationTypeAlias.CorporateUploadNotification, EmailTemplateAlias.CorporateUploadNotification, corporateUploadNotificationModel, 0, 1, "System: Corporate Upload Notification");
                    _logger.Info("Corporate Upload Notification:Mail Send for upload corporate :" + tag + " UploadedBy:  " + corporateUploadedBy + " on : " + DateTime.Now);
                }

                corporateModel.FailedRecordsFile = failedRecordsFile;

                if (failedCustomers != null && failedCustomers.Any())
                {
                    var failedMember = _memberUploadParseDetailFactory.GetCorporateCustomerListModel(failedCustomers, model.UploadCorporateId.Value);
                    _corporateUploadHelper.UpdateFailedRecords(failureRecords, failedMember);

                    if (model.LogFileId < 1)
                    {
                        var fileInfo = new FileInfo(failureRecords);

                        var files = new Core.Application.Domain.File
                        {
                            Path       = fileInfo.Name,
                            FileSize   = fileInfo.Length,
                            Type       = FileType.Csv,
                            UploadedBy = new OrganizationRoleUser(_sessionContext.UserSession.CurrentOrganizationRole.OrganizationRoleUserId),
                            UploadedOn = DateTime.Now
                        };

                        files = _fileRepository.Save(files);

                        model.LogFileId = files.Id;
                    }
                }

                if (adjustOrderForCustomerEditModel.Any())
                {
                    _corporateUploadHelper.UpdateAdjustOrderRecords(adjustOrderRecordsFile, adjustOrderForCustomerEditModel);
                    if (model.AdjustOrderLogFileId < 1)
                    {
                        var fileInfo = new FileInfo(adjustOrderRecordsFile);
                        var files    = new Core.Application.Domain.File
                        {
                            Path       = fileInfo.Name,
                            FileSize   = fileInfo.Length,
                            Type       = FileType.Csv,
                            UploadedBy = new OrganizationRoleUser(_sessionContext.UserSession.CurrentOrganizationRole.OrganizationRoleUserId),
                            UploadedOn = DateTime.Now
                        };

                        files = _fileRepository.Save(files);

                        model.AdjustOrderLogFileId = files.Id;
                    }
                }

                if (model.UploadCorporateId.HasValue && corporateModel.IsParseSucceded)
                {
                    var count = _corporateUploadHelper.FailedCustomerCount(failedRecordsFile, mediaLocation);

                    var uploadCorporate = _corporateUploadRepository.GetById(model.UploadCorporateId.Value);
                    uploadCorporate.SuccessfullUploadCount = (corporateModel.TotalCustomers - count);
                    uploadCorporate.FailedUploadCount      = count;

                    if (model.LogFileId > 0)
                    {
                        uploadCorporate.LogFileId = model.LogFileId;
                    }

                    if (model.AdjustOrderLogFileId > 0)
                    {
                        uploadCorporate.AdjustOrderLogFileId = model.AdjustOrderLogFileId;
                    }

                    uploadCorporate.ParseStatus = (int)MemberUploadParseStatus.Start;
                    _corporateUploadRepository.Save(uploadCorporate);
                }

                corporateModel.FailedCustomersListPath = _corporateUploadHelper.CheckIsFileContainsRecord(corporateModel.IsParseSucceded, mediaLocation, failedRecordsFile);
                corporateModel.AdjustOrderRecordsFile  = _corporateUploadHelper.CheckIsFileContainsRecord(corporateModel.IsParseSucceded, mediaLocation, adjustOrderFile);
            }
            catch (Exception ex)
            {
                corporateModel.FeedbackMessage = FeedbackMessageModel.CreateFailureMessage(ex.Message);
            }

            return(Json(new
            {
                corporateModel.FileName,
                corporateModel.UploadedCustomers,
                corporateModel.Tag,
                corporateModel.FailedCustomers,
                corporateModel.IsParseSucceded,
                PageNumber = pageNumber + 1,
                corporateModel.FailedCustomersListPath,
                LogFileId = model.LogFileId,
                corporateModel.AdjustOrderRecordsFile,
                model.AdjustOrderLogFileId
            }, JsonRequestBehavior.AllowGet));
        }
コード例 #5
0
        public ActionResult CorporateUpload(CorporateUploadEditModel model, HttpPostedFileBase corporateUploadFile)
        {
            if (Request.Files.Count < 1 || corporateUploadFile == null)
            {
                model.FeedbackMessage = FeedbackMessageModel.CreateFailureMessage("No file has been uploaded. Please upload a csv file.");
                return(View(model));
            }

            var uploadMediaLocation = _mediaRepository.GetUploadCsvMediaFileLocation();
            var account             = ((IUniqueItemRepository <CorporateAccount>)_corporateAccountRepository).GetById(model.CorporateAccountId);
            var organization        = _organizationRepository.GetOrganizationbyId(model.CorporateAccountId);

            model.Tag  = account.Tag;
            model.Name = organization.Name;
            model.UploadCsvMediaUrl = _mediaRepository.GetSamplesLocation().Url;


            HttpPostedFileBase file = Request.Files[0];
            var physicalPath        = uploadMediaLocation.PhysicalPath;
            var fileUploadedName    = (Path.GetFileNameWithoutExtension(file.FileName) + Path.GetExtension(file.FileName)).Replace("'", "").Replace("&", "");

            var fileName = (Path.GetFileNameWithoutExtension(fileUploadedName) + "_" + DateTime.Now.ToString("MMddyyyyhhmmss") + Path.GetExtension(fileUploadedName)).Replace("'", "").Replace("&", "");

            var fullPath = physicalPath + fileName;

            file.SaveAs(fullPath);

            var csvReader     = IoC.Resolve <ICsvReader>();
            var customerTable = csvReader.ReadWithTextQualifier(fullPath);

            if (customerTable.Rows.Count == 0)
            {
                model.FeedbackMessage = FeedbackMessageModel.CreateFailureMessage("Uploaded file has no data.");
                return(View(model));
            }

            var columns            = customerTable.Columns.Cast <DataColumn>().Select(x => x.ColumnName.ToLower()).ToArray();
            var missingColumnNames = _corporateUploadHelper.CheckAllColumnExist(columns);

            if (!string.IsNullOrEmpty(missingColumnNames))
            {
                model.FeedbackMessage =
                    FeedbackMessageModel.CreateFailureMessage("Missing Column Name(s) : " + missingColumnNames);

                return(View(model));
            }

            var disabledTags = _corporateTagService.DisabledTagsInUsed(model.CustomTags, model.CorporateAccountId);

            if (disabledTags != null && disabledTags.Any())
            {
                model.CustomTags = model.CustomTags.Where(x => disabledTags.Contains(x)).ToList();

                model.FeedbackMessage = FeedbackMessageModel.CreateFailureMessage("Following tag(s) has been deactivated: " + string.Join(",", disabledTags));

                return(View(model));
            }

            var files = new Core.Application.Domain.File
            {
                Path       = fileName,
                FileSize   = file.ContentLength,
                Type       = FileType.Csv,
                UploadedBy = new OrganizationRoleUser(_sessionContext.UserSession.CurrentOrganizationRole.OrganizationRoleUserId),
                UploadedOn = DateTime.Now
            };

            files = _fileRepository.Save(files);

            var corporateUpload = new CorporateUpload
            {
                FileId     = files.Id,
                UploadTime = DateTime.Now,
                UploadedBy = _sessionContext.UserSession.CurrentOrganizationRole.OrganizationRoleUserId,
                AccountId  = model.CorporateAccountId,
                SourceId   = (long)MemberUploadSource.CorporateUplaod
            };

            corporateUpload = _corporateUploadRepository.Save(corporateUpload);

            model.TotalCustomers   = customerTable.Rows.Count;
            model.IsUploadSucceded = true;
            model.IsParseSucceded  = false;
            model.FileName         = fileName;

            var failedFileName = Path.GetFileNameWithoutExtension(fileUploadedName).Replace("+", "_");

            model.FailedRecordsFile = failedFileName + "_Failure_" + DateTime.Now.ToString("MMddyyyyhhmmss") + ".csv";

            if (corporateUpload != null && corporateUpload.Id > 0)
            {
                model.UploadCorporateId = corporateUpload.Id;
            }

            var failureRecords = uploadMediaLocation.PhysicalPath + model.FailedRecordsFile;

            _corporateUploadHelper.CreateHeaderFileRecord(failureRecords, customerTable);


            model.AdjustOrderRecordsFile = failedFileName + "_AdjustOrder_" + DateTime.Now.ToString("MMddyyyyhhmmss") + ".csv";
            var adjustOrderRecordsFile = uploadMediaLocation.PhysicalPath + model.AdjustOrderRecordsFile;

            _corporateUploadHelper.CreateHeaderAdjustOrderForEventCustoerRecord(adjustOrderRecordsFile);

            return(View(model));
        }