public async Task CreateSale(SaleInputModel sale, string distributor)
        {
            var distributorId = await db.Distributors
                                .Where(n => n.Name == distributor)
                                .Select(i => i.Id)
                                .FirstOrDefaultAsync();

            if (sale.PharmacyId != 0 &&
                sale.ProductId != 0 &&
                sale.Date != null &&
                sale.Count != 0 &&
                distributorId != 0)
            {
                var saleDbModel = new Sale
                {
                    PharmacyId    = sale.PharmacyId,
                    ProductId     = sale.ProductId,
                    Date          = sale.Date,
                    Count         = sale.Count,
                    DistributorId = distributorId
                };

                await db.Sales.AddAsync(saleDbModel);

                await db.SaveChangesAsync();
            }
        }
示例#2
0
        public async Task <PowerUsageResponse> GetPowerUsageInfoAsync(SaleInputModel inputModel, CancellationToken cancellationToken = default)
        {
            string path = $"api/PowerUsage/GetPowerUsage/{inputModel.BILL_IDENTIFIER}";

            try
            {
                var response = await _httpClient.GetAsync(path, cancellationToken);

                //response.EnsureSuccessStatusCode
                _logger.LogInformation($"API usage call Result Code {response.StatusCode}");
                if (!response.IsSuccessStatusCode)
                {
                    _logger.LogInformation($"API usage call is failed");
                    return(null);
                }

                var content = await response.Content.ReadAsAsync <PowerUsageResponse>(cancellationToken);

                return(content);
            }
            catch (HttpRequestException e)
            {
                _logger.LogError(e, "Failed to get PowerUsage data from internal API");
            }

            return(null);
        }
示例#3
0
        public async Task <PowerUsageResponse> PostForSalesData(SaleInputModel inputModel, CancellationToken cancellationToken = default)
        {
            try
            {
                var serializeSalesInput = JsonConvert.SerializeObject(inputModel);
                var postRequest         = new HttpRequestMessage(HttpMethod.Post, _optionsDelegate.CurrentValue.SaleEndpoint);
                postRequest.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                postRequest.Content = new StringContent(serializeSalesInput);
                postRequest.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

                var response = await _httpClient.SendAsync(postRequest);

                response.EnsureSuccessStatusCode();

                _logger.LogInformation($"API For Sales call Result Code {response.StatusCode}");
                if (!response.IsSuccessStatusCode)
                {
                    _logger.LogInformation($"API For Sales call is failed");
                    return(null);
                }

                var content = await response.Content.ReadAsAsync <PowerUsageResponse>(cancellationToken);

                return(content);
            }
            catch (HttpRequestException e)
            {
                _logger.LogError(e, "Failed to get PowerUsage data from internal API");
            }

            return(null);
        }
        public async Task <IActionResult> OnGetEditMissionAsync(string postId)
        {
            var user = await _userManager.GetUserAsync(User);

            var post = await _fleaMarket.GetMissionById(postId);

            if (user == null || !user.StudentIdentityConfirmed || post.PostUserId != user.Id || post.DeletedMark)
            {
                return(RedirectToPage("Index"));
            }
            SaleInput = new SaleInputModel
            {
                PostUserId        = user.Id,
                GoodsName         = post.GoodsName,
                GoodsPrice        = post.GoodsPrice,
                GoodsQuality      = post.GoodsQuality,
                GoodsDescription  = post.GoodsDescription,
                MissionNotes      = post.MissionNotes,
                PosterAddress1    = post.PosterAddress1,
                PosterAddress2    = post.PosterAddress2,
                PosterPhoneNumber = post.PosterPhoneNumber,
            };
            PostId     = post.Id;
            GoodsUrl   = post.GoodsPhotoUrl;
            PostUserId = user.Id;
            EditMark   = true;
            return(Page());
        }
        public async Task <IActionResult> OnGetAsync()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null || !user.StudentIdentityConfirmed)
            {
                return(RedirectToPage("Index"));
            }
            var post = await _fleaMarket.GetLastMissionInfoAsync(user.Id);

            SaleInput = new SaleInputModel
            {
                PostUserId = user.Id
            };
            if (post != null)
            {
                SaleInput.PosterAddress1    = post.PosterAddress1;
                SaleInput.PosterAddress2    = post.PosterAddress2;
                SaleInput.PosterPhoneNumber = post.PosterPhoneNumber;
            }
            PostUserId = user.Id;
            EditMark   = false;
            return(Page());
        }
示例#6
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("Started PowerSource reading service.");
            try
            {
                using (var scope = _serviceScopeFactory.CreateScope())
                {
                    var mediator = scope.ServiceProvider.GetRequiredService <IMediator>();
                    var powerSourceHttpClient = scope.ServiceProvider.GetRequiredService <IPowerCounterSrcApiClient>();
                    var powerCounters         = await mediator.Send(new GetPowerCounterListQuery());

                    int totalCounter  = powerCounters.Count();
                    var processedList = new List <string>();
                    _logger.LogInformation($"Total PowerCounters {totalCounter}");
                    int ccounter = 1;

                    while (!stoppingToken.IsCancellationRequested)
                    {
                        // Cache Not implemented yet
                        foreach (var counter in powerCounters)
                        {
                            if (!processedList.Contains(counter.bill_identifier))
                            {
                                processedList.Add(counter.bill_identifier);
                                // We should extend our Configuration to get this info from there
                                var salesInputModel = new SaleInputModel
                                {
                                    BILL_IDENTIFIER = counter.bill_identifier,
                                    fromyear        = 92,
                                    MobileNo        = "0999999999"
                                };
                                _logger.LogInformation($"Processing {counter.bill_identifier} current= {ccounter++} from {totalCounter}");
                                // We have our own HttpClient Extension to support extra Authentication scenarios
                                var usageResponse = await powerSourceHttpClient.PostForSalesData(salesInputModel, stoppingToken);

                                // We should send the response to ElasticSearch Repository which is not implemented yet
                                _logger.LogInformation($"Sucessfully recieved {usageResponse.data.Count()} bills Info");
                                foreach (var usageItem in usageResponse.data)
                                {
                                    usageItem.helper_flag = false;
                                    await mediator.Send(new InsertNewUsageV2Command
                                    {
                                        UsageItem = usageItem
                                    });
                                }
                                // Awaitable Request for Payment Info here
                                _logger.LogInformation($"Processing {counter.bill_identifier} compleeted");
                            }
                            else
                            {
                                _logger.LogInformation($"Already Exists {counter.bill_identifier}");
                            }
                        }

                        await Task.Delay(TimeSpan.FromSeconds(3), stoppingToken);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error Occured ", null);
            }
        }
示例#7
0
        public async Task <ActionResult> ImportAsync(PharmnetInputModel pharmnetInput)
        {
            IFormFile file = Request.Form.Files[0];

            DateTime dateForDb = DateTime.ParseExact(pharmnetInput.Date, "dd-MM-yyyy", null);

            string folderName = "UploadExcel";

            string webRootPath = hostEnvironment.WebRootPath;

            string newPath = Path.Combine(webRootPath, folderName);

            var errorDictionary = new Dictionary <int, string>();

            if (!Directory.Exists(newPath))

            {
                Directory.CreateDirectory(newPath);
            }

            if (file.Length > 0)

            {
                string sFileExtension = Path.GetExtension(file.FileName).ToLower();

                ISheet sheet;

                string fullPath = Path.Combine(newPath, file.FileName);

                using (var stream = new FileStream(fullPath, FileMode.Create))

                {
                    file.CopyTo(stream);

                    stream.Position = 0;

                    if (sFileExtension == ".xls")

                    {
                        HSSFWorkbook hssfwb = new HSSFWorkbook(stream); //This will read the Excel 97-2000 formats

                        sheet = hssfwb.GetSheetAt(0);                   //get first sheet from workbook
                    }

                    else

                    {
                        XSSFWorkbook hssfwb = new XSSFWorkbook(stream); //This will read 2007 Excel format

                        sheet = hssfwb.GetSheetAt(0);                   //get first sheet from workbook
                    }

                    IRow headerRow = sheet.GetRow(0); //Get Header Row

                    int cellCount = headerRow.LastCellNum;

                    for (int j = 0; j < cellCount; j++)
                    {
                        ICell cell = headerRow.GetCell(j);

                        if (cell == null || string.IsNullOrWhiteSpace(cell.ToString()))
                        {
                            continue;
                        }
                    }

                    for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) //Read Excel File

                    {
                        IRow row = sheet.GetRow(i);

                        if (row == null)
                        {
                            continue;
                        }

                        if (row.Cells.All(d => d.CellType == CellType.Blank))
                        {
                            continue;
                        }

                        var newSale = new SaleInputModel();
                        newSale.Date = dateForDb;


                        for (int j = row.FirstCellNum; j < cellCount; j++)

                        {
                            string currentRow = "";

                            if (row.GetCell(j) != null)
                            {
                                currentRow = row.GetCell(j).ToString().TrimEnd();
                            }

                            switch (j)
                            {
                            case 2:
                                if (numbersChecker.WholeNumberCheck(currentRow))
                                {
                                    var producId = await this.productsService.ProductIdByDistributor(currentRow, Pharmnet);

                                    if (producId != 0)
                                    {
                                        //var producId = await this.productsService.ProductIdByDistributor(currentRow, Pharmnet);
                                        newSale.ProductId = producId;
                                    }

                                    else
                                    {
                                        errorDictionary[i] = currentRow;
                                    }
                                }

                                else
                                {
                                    errorDictionary[i] = currentRow;
                                }
                                break;

                            case 4:
                                if (numbersChecker.WholeNumberCheck(currentRow))
                                {
                                    var pharmacyId = await this.pharmaciesService.PharmacyIdByDistributor(currentRow, Pharmnet);

                                    if (pharmacyId != 0)
                                    {
                                        //var pharmacyId = await this.pharmaciesService.PharmacyIdByDistributor(currentRow, Pharmnet);
                                        newSale.PharmacyId = pharmacyId;
                                    }
                                    else
                                    {
                                        errorDictionary[i] = currentRow;
                                    }
                                }

                                else
                                {
                                    errorDictionary[i] = currentRow;
                                }
                                break;

                            case 9:
                                var currRowDate = DateTime.Parse(currentRow);
                                if (currentRow != null)
                                {
                                    newSale.Date = currRowDate;
                                }
                                break;

                            case 11:
                                if (this.numbersChecker.NegativeNumberIncludedCheck(currentRow))
                                {
                                    int countProduct = int.Parse(currentRow);
                                    newSale.Count = countProduct;
                                }
                                else
                                {
                                    errorDictionary[i] = currentRow;
                                }
                                break;
                            }
                        }

                        await salesService.CreateSale(newSale, Pharmnet);
                    }
                }
            }

            var pharmnetOutputModel = new PharmnetOutputModel {
                Date   = pharmnetInput.Date,
                Errors = errorDictionary
            };

            return(this.View(pharmnetOutputModel));
        }
示例#8
0
        public async Task <ActionResult> ImportAsync(PhoenixInputModel phoenixInput)
        {
            var watch = new System.Diagnostics.Stopwatch();

            watch.Start();

            IFormFile file = Request.Form.Files[0];

            DateTime dateForDb = DateTime.ParseExact(phoenixInput.Date, "dd-MM-yyyy", null);

            string folderName = "UploadExcel";

            string webRootPath = hostEnvironment.WebRootPath;

            string newPath = Path.Combine(webRootPath, folderName);

            var errorDictionary = new Dictionary <int, string>();

            if (!Directory.Exists(newPath))

            {
                Directory.CreateDirectory(newPath);
            }

            var pharmacyIdsForCheck = await pharmaciesService.PharmacyIdsByDistributorForCheck(Phoenix);

            var productIdsForCheck = await productsService.ProductsIdByDistributorForCheck(Phoenix);

            if (file.Length > 0)

            {
                string sFileExtension = Path.GetExtension(file.FileName).ToLower();

                ISheet sheet;

                string fullPath = Path.Combine(newPath, file.FileName);

                using (var stream = new FileStream(fullPath, FileMode.Create))

                {
                    file.CopyTo(stream);

                    stream.Position = 0;

                    if (sFileExtension == ".xls")

                    {
                        HSSFWorkbook hssfwb = new HSSFWorkbook(stream); //This will read the Excel 97-2000 formats

                        sheet = hssfwb.GetSheetAt(0);                   //get first sheet from workbook
                    }

                    else

                    {
                        XSSFWorkbook hssfwb = new XSSFWorkbook(stream); //This will read 2007 Excel format

                        sheet = hssfwb.GetSheetAt(0);                   //get first sheet from workbook
                    }

                    IRow headerRow = sheet.GetRow(0); //Get Header Row

                    int cellCount = headerRow.LastCellNum;

                    for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) //Read Excel File

                    {
                        IRow row = sheet.GetRow(i);

                        if (row == null)
                        {
                            continue;
                        }

                        if (row.Cells.All(d => d.CellType == CellType.Blank))
                        {
                            continue;
                        }

                        var newSale = new SaleInputModel();
                        newSale.Date = dateForDb;

                        //attempt with four if structures
                        //var productIdRow = row.GetCell(0).ToString().TrimEnd();
                        //if (this.numbersChecker.WholeNumberCheck(productIdRow))
                        //{
                        //    var productId = productIdsForCheck.Where(p => p.DistributorId == productIdRow.ToString()).Select(p => p.ProductId).FirstOrDefault();

                        //    if (productId != 0)
                        //    {
                        //        //var productId = await this.productsService.ProductIdByDistributor(currentRow, Phoenix);
                        //        newSale.ProductId = productId;
                        //    }
                        //    else
                        //    {
                        //        errorDictionary[i] = productIdRow;
                        //    }
                        //}

                        //var pharmacyIdRow = row.GetCell(2).ToString().TrimEnd();
                        //if (this.numbersChecker.WholeNumberCheck(pharmacyIdRow))
                        //{
                        //    var pharmacyId = pharmacyIdsForCheck
                        //        .Where(p => p.DistributorId == int.Parse(pharmacyIdRow))
                        //        .Select(p => p.PharmacyId)
                        //        .FirstOrDefault();

                        //    if (pharmacyId != 0)
                        //    {
                        //        //var pharmacyId = await this.pharmaciesService.PharmacyIdByDistributor(currentRow, Phoenix);
                        //        newSale.PharmacyId = pharmacyId;
                        //    }
                        //    else
                        //    {
                        //        errorDictionary[i] = pharmacyIdRow;
                        //    }
                        //}
                        //else
                        //{
                        //    errorDictionary[i] = pharmacyIdRow;
                        //}

                        //var countProductRow = row.GetCell(14).ToString().TrimEnd();
                        //if (this.numbersChecker.NegativeNumberIncludedCheck(countProductRow))
                        //{
                        //    int countProduct = int.Parse(countProductRow);
                        //    newSale.Count = countProduct;
                        //}

                        //var dateRow = row.GetCell(16).ToString().TrimEnd();
                        //var dateDb = DateTime.Parse(dateRow);
                        //if (dateRow != null)
                        //{
                        //    newSale.Date = dateDb;
                        //}

                        //await salesService.CreateSale(newSale, Phoenix);

                        // attemp with a switch
                        for (int j = row.FirstCellNum; j < cellCount; j++)
                        {
                            string currentRow = "";

                            if (row.GetCell(j) != null)
                            {
                                currentRow = row.GetCell(j).ToString().TrimEnd();
                            }

                            if (j != 0 && j != 2 && j != 14 && j != 16)
                            {
                                continue;
                            }

                            switch (j)
                            {
                            case 0:
                                if (this.numbersChecker.WholeNumberCheck(currentRow))
                                {
                                    var productId = productIdsForCheck.Where(p => p.DistributorId == currentRow.ToString()).Select(p => p.ProductId).FirstOrDefault();

                                    if (productId != 0)
                                    {
                                        //var productId = await this.productsService.ProductIdByDistributor(currentRow, Phoenix);
                                        newSale.ProductId = productId;
                                    }
                                    else
                                    {
                                        errorDictionary[i] = currentRow;
                                    }
                                }
                                else
                                {
                                    errorDictionary[i] = currentRow;
                                }
                                break;

                            case 2:
                                if (this.numbersChecker.WholeNumberCheck(currentRow))
                                {
                                    var pharmacyId = pharmacyIdsForCheck
                                                     .Where(p => p.DistributorId == int.Parse(currentRow))
                                                     .Select(p => p.PharmacyId)
                                                     .FirstOrDefault();

                                    if (pharmacyId != 0)
                                    {
                                        //var pharmacyId = await this.pharmaciesService.PharmacyIdByDistributor(currentRow, Phoenix);
                                        newSale.PharmacyId = pharmacyId;
                                    }
                                    else
                                    {
                                        errorDictionary[i] = currentRow;
                                    }
                                }
                                else
                                {
                                    errorDictionary[i] = currentRow;
                                }
                                break;

                            case 14:
                                if (this.numbersChecker.NegativeNumberIncludedCheck(currentRow))
                                {
                                    int countProduct = int.Parse(currentRow);
                                    newSale.Count = countProduct;
                                }
                                break;

                            case 16:
                                var currRowDate = DateTime.Parse(currentRow);
                                if (currentRow != null)
                                {
                                    newSale.Date = currRowDate;
                                }
                                break;
                            }
                        }

                        await salesService.CreateSale(newSale, Phoenix);
                    }
                }
            }

            var phoenixOutput = new PhoenixOutputModel();

            phoenixOutput.Date = phoenixInput.Date;

            phoenixOutput.Errors = errorDictionary;

            watch.Stop();
            var passedTime = watch.ElapsedMilliseconds;


            return(this.View(phoenixOutput));
        }