public async Task ShouldAddNewPlace()
        {
            var targetEntityGuid = Guid.NewGuid();
            var dataAccessModel  = new EntitySalesDataAccessModel
            {
                Id           = Guid.NewGuid(),
                ActiveEntity = new[]
                {
                    new EntityEntityDataAccessModel
                    {
                        Id             = targetEntityGuid,
                        Places         = Array.Empty <EntityPlaceDataAccessModel>(),
                        SystematicType = EntitySystematicType.ElioET
                    },
                    new EntityEntityDataAccessModel
                    {
                        Id             = Guid.NewGuid(),
                        Places         = Array.Empty <EntityPlaceDataAccessModel>(),
                        SystematicType = EntitySystematicType.ElioET
                    }
                }
            };


            var EntitySales = new EntitySales(dataAccessModel);

            GetRepository().EntitySalesToReturn = EntitySales;

            var now = DateTime.Now;

            GetDatetimeProvider().LocalNow = now;

            await GetService().AttachNewPlace(dataAccessModel.Id, targetEntityGuid, "MOW1", PredefinedUsers.MockUser);

            var Place = EntitySales.ActiveEntity.First(v => v.Id == targetEntityGuid).EntityPlaces.FirstOrDefault(v => v.Pcc == "MOW1");

            Assert.NotNull(Place);
            Assert.Equal("MOW1", Place.Pcc);
            Assert.NotEqual(Guid.Empty, (Guid)Place.Id);
            Assert.Equal(now.Date, Place.AuthorizationDate);
        }
        private async Task AssureThatNewPlaceCreated(EntitySales EntitySales, DateTime validFrom, DateTime updatedAt)
        {
            using (var context = _container.Resolve <EntityContext>())
            {
                var Ep = await context.Ep.FirstOrDefaultAsync(x => x.PlaceId == NewPlaceId);

                Assert.NotEqual(Guid.Empty, Ep.EpGuid);
                Assert.Equal(EntitySales.Deal.Code, Ep.ASIACode);
                Assert.Equal(_UesEtBasePoint.BasePointGuid, Ep.BasePointGuid);
                Assert.Equal(NewPlaceId, Ep.PlaceId);
                Assert.Equal(EpSystems.Ues, Ep.EpSystem);
                Assert.Equal(validFrom.Date, Ep.AutorizeDate);
                Assert.Equal("test", Ep.AK);
                Assert.False(Ep.EMD);
                Assert.Equal(string.Empty, Ep.Comment);
                Assert.Equal(string.Empty, Ep.OFFC);
                Assert.True(Ep.Status);
                Assert.Equal(PredefinedUsers.MockUser.Identity.Name, Ep.CreatedBy);
                Assert.Equal(PredefinedUsers.MockUser.Identity.Name, Ep.ModifiedBy);
                Assert.Equal(updatedAt, Ep.ModifiedDate);
                Assert.Equal(updatedAt, Ep.CreatedDate);
            }
        }
예제 #3
0
 public Task UpdateEntitySale(EntitySales EntitySales, IPrincipal user, DateTime updatedAt) => Task.CompletedTask;
예제 #4
0
        public IHttpActionResult ParseExcel(EntitySales model)
        {
            try
            {
                #region Upload file, Save records to database

                this.IsFinanceFile = model.IsFinanceFile;

                if (!HasRight(new string[] { "SLSIMPRT" }))
                {
                    return(Ok <dynamic>(new { Status = HttpStatusCode.BadRequest, Model = new { Message = "Unauthorized Operation" } }));
                }

                DataResponse response = new DataResponse();

                if (model.Files != null && model.Files.Count > 0)
                {
                    StringBuilder logString = new StringBuilder();
                    string        logPath   = HttpContext.Current.Server.MapPath(Path.Combine("~/Assets", CurrentBusinessId.Value.ToString(), "Sales", "Sales-Archives", "Uploads", "Logs"));
                    if (!Directory.Exists(logPath))
                    {
                        Directory.CreateDirectory(logPath);
                    }
                    string logFilePath = Path.Combine(logPath, string.Format("{0}.txt", DateTime.Now.ToString("MMddyyhhmmssttfff")));

                    if (!File.Exists(logFilePath))
                    {
                        FileStream fs = File.Create(logFilePath);
                        fs.Dispose();
                    }

                    logString.AppendLine("Parsing starts @ " + DateTime.Now);
                    logString.AppendLine("BusinessId \t:\t" + CurrentBusinessId.Value);

                    List <FileInfo> FilesList   = new List <FileInfo>();
                    string          serviceName = new RepositoryLookups().GetServiceNameById(model.ServiceId);

                    foreach (var file in model.Files)
                    {
                        string FileName = SaveFile(file.Base64, file.FileName, serviceName);
                        FilesList.Add(new FileInfo
                        {
                            SavedFileName    = FileName,
                            IncomingFileName = file.FileName
                        });
                    }

                    logString.AppendLine(string.Format("Total Files \t:\t{0}\t\nService Id \t:\t{1}", FilesList.Count(), model.ServiceId));

                    foreach (var fileInfo in FilesList)
                    {
                        XmlHelper xmlHelper = new XmlHelper();

                        string uploadPath   = Path.Combine(CurrentBusinessId.Value.ToString(), "Sales", "Sales-Archives", "Uploads", serviceName, fileInfo.SavedFileName);
                        string excelFile    = HttpContext.Current.Server.MapPath(Path.Combine("~/Assets", uploadPath));
                        string importedPath = Path.Combine("Assets", uploadPath);
                        this.ServiceId = model.ServiceId;

                        if (this.MapperFilePath == null)
                        {
                            logString.Append(string.Format("XML mapper file is missing for the service \"{0}\"", serviceName));
                            continue;
                        }
                        xmlHelper.XmlMapper = XDocument.Load(this.MapperFilePath);

                        int RecordCount;

                        xmlHelper.xmlString = new ExcelToXml().GetXMLString(excelFile, true, out RecordCount);

                        logString.AppendLine(string.Format("File Name \t:\t{0} \t Starts @{1}", fileInfo.SavedFileName, DateTime.UtcNow));

                        using (System.IO.StreamWriter logWriter = new System.IO.StreamWriter(logFilePath))
                        {
                            logWriter.WriteLine(logString);
                            logString.Clear();
                            int importSummeryId;
                            response = new RepositorySales().Insert(xmlHelper, RecordCount, CurrentBusinessId, CurrentUserId, model.ServiceId, IsFinanceFile, out importSummeryId, logWriter, "Web Upload", importedPath, fileInfo.IncomingFileName);
                            logString.AppendLine("File Successfully Processed");
                            logString.AppendLine("File moved to :" + excelFile);
                            logWriter.WriteLine(logString);
                        }
                    }
                    new Exception(logString.ToString()).Log(logFilePath, true);
                }

                HttpRuntime.Cache[CurrentUserId.ToString()] = true;
                return(Ok <DataResponse>(response));

                #endregion
            }
            catch (Exception ex)
            {
                ex.Log();
                return(Ok <dynamic>(new { Status = HttpStatusCode.BadRequest, Model = new { Message = string.Format("{0}|{1}", ex.Message, ex.InnerException != null ? ex.InnerException.Message : "") } }));
            }
        }
        public async Task UpdateEntitySale(EntitySales EntitySales, IPrincipal user, DateTime updatedAt)
        {
            if (EntitySales == null)
            {
                throw new ArgumentNullException(nameof(EntitySales));
            }

            if (user?.Identity == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            var MainPoint = await _context.EusMainPoint.FirstOrDefaultAsync(s => s.Id == EntitySales.Id);

            if (MainPoint == null)
            {
                throw new NotFoundException($"MainPoint({EntitySales.Id}) не найден для обновления");
            }

#warning В целях экономии времени в данный момент реализовано только добавление новых EntityPlace-ов(они же пульты, они же терминалы) для БП Entity01.
            var EntityPlaces = EntitySales.ActiveEntity.SelectMany(v => v.EntityPlaces).ToList();

            var RnTerminals = EntitySales.ActiveEntity.Select(v => v.RnGroup).ToList();

            var EntityPlacesMissingInDatabase = EntityPlaces.Where(Place => _context.Lt.Any(Lt => Lt.LtGuid == Place.Id) == false).ToList();

            var activeEntityIds          = EntitySales.ActiveEntity.Select(x => x.Id).ToList();
            var activeDbExpirationEntity = await _context
                                           .EntityExpiration
                                           .Where(ve => activeEntityIds.Contains(ve.EntityExpirationGuid))
                                           .ToListAsync();


            var dataForNewPlaces = new List <MapPlaceEntityEntityExpiration>();
            foreach (var Place in EntityPlacesMissingInDatabase)
            {
                var EntityForPlace     = EntitySales.ActiveEntity.First(v => v.EntityPlaces.Any(o => o.Id == Place.Id));
                var expirationForPlace = activeDbExpirationEntity.First(v => v.EntityExpirationGuid == EntityForPlace.Id);
                var map = new MapPlaceEntityEntityExpiration(Place, EntityForPlace, expirationForPlace);
                dataForNewPlaces.Add(map);
            }


            var newLts = dataForNewPlaces.Select(data => new Lt
            {
                LtGuid        = data.Place.Id,
                ASIACode      = EntitySales.Agent.Code,
                MainPointGuid = data.EntityExpiration.MainPointGuid,
                PlaceId       = data.Place.Pcc,
                LtSystem      = data.Entity.Sys.ToLtSystem(),
                AutorizeDate  = data.Place.AuthorizationDate,
                AK            = "Test",
                EMD           = false,
#warning Обязательное поле в БД, изменить при рефакторинге
                Comment      = string.Empty,
                OFFC         = string.Empty,
                Status       = true,
                CreatedBy    = user.Identity.Name,
                ModifiedBy   = user.Identity.Name,
                CreatedDate  = updatedAt,
                ModifiedDate = updatedAt
            });

            _context.Lt.AddRange(newLts);
            await _context.SaveChangesAsync();
        }