public async Task <bool> ShareTaxToPhasesIthereIsAsync(purch_plpo currentLpo)
        {
            var paymentPhases = _dataContext.cor_paymentterms.Where(q => q.LPOId == currentLpo.PLPOId && q.ProposedBy == (int)Proposer.STAFF).ToList();

            var selected = currentLpo.Taxes.Split(',').Select(int.Parse).ToList();
            var taxes    = _dataContext.cor_taxsetup.Where(e => selected.Contains(e.TaxSetupId)).ToList();

            if (paymentPhases.Count() > 0)
            {
                foreach (var phase in paymentPhases)
                {
                    if (phase.Amount != 0)
                    {
                        decimal charge    = new decimal();
                        decimal deduction = new decimal();
                        foreach (var tax in taxes)
                        {
                            if (tax.Type == "+")
                            {
                                charge = phase.Amount / 100 * Convert.ToDecimal(tax.Percentage) + charge;
                            }
                            if (tax.Type == "-")
                            {
                                deduction = phase.Amount / 100 * Convert.ToDecimal(tax.Percentage) + deduction;
                            }
                        }
                        phase.NetAmount  = phase.Amount - deduction + charge;
                        phase.TaxPercent = Convert.ToDouble(phase.NetAmount - phase.Amount);
                    }
                    await AddUpdatePaymentTermsAsync(phase);
                }
            }
            return(await Task.Run(() => true));
        }
        public purch_plpo BuildThisBidLPO(purch_plpo thisBidLpo, cor_bid_and_tender currentBid)
        {
            try
            {
                var TaxSetup = _supRepo.GetTaxSetupSupplierTypeWithAsync(currentBid.SupplierId).Result;
                var supplier = _supRepo.GetSupplierAsync(currentBid.SupplierId).Result;
                var amount   = _dataContext.cor_paymentterms.Where(e => e.BidAndTenderId == currentBid.BidAndTenderId && e.ProposedBy == (int)Proposer.STAFF).Sum(q => q.Amount);
                if (supplier != null)
                {
                    var supplierType = _supRepo.GetSupplierTypeAsync(supplier.SupplierTypeId).Result;
                    thisBidLpo.JobStatus        = (int)JobProgressStatus.Not_Started;
                    thisBidLpo.BidComplete      = true;
                    thisBidLpo.Name             = supplier.Name;
                    thisBidLpo.SupplierAddress  = currentBid.Location;
                    thisBidLpo.GrossAmount      = currentBid.Total;
                    thisBidLpo.BidAndTenderId   = currentBid.BidAndTenderId;
                    thisBidLpo.Description      = currentBid.DescriptionOfRequest;
                    thisBidLpo.WinnerSupplierId = currentBid.SupplierId;
                    thisBidLpo.Total            = currentBid.Total;
                    thisBidLpo.ApprovalStatusId = (int)ApprovalStatus.Pending;
                    thisBidLpo.Location         = currentBid.Location;
                    thisBidLpo.Quantity         = currentBid.Quantity;
                    thisBidLpo.AmountPayable    = amount;
                    thisBidLpo.CompanyId        = currentBid.CompanyId;
                    thisBidLpo.SupplierAddress  = supplier.Address;
                    thisBidLpo.SupplierNumber   = supplier.SupplierNumber;
                    thisBidLpo.Description      = currentBid.DescriptionOfRequest;
                }

                if (TaxSetup.Count() > 0)
                {
                    decimal charge    = new decimal();
                    decimal deduction = new decimal();
                    thisBidLpo.Taxes = string.Join(',', TaxSetup.Select(s => s.TaxSetupId));
                    foreach (var tax in TaxSetup)
                    {
                        if (tax.Type == "+")
                        {
                            // (80 / 100) * 25
                            charge = thisBidLpo.GrossAmount / 100 * Convert.ToDecimal(tax.Percentage) + charge;
                        }
                        if (tax.Type == "-")
                        {
                            deduction = thisBidLpo.GrossAmount / 100 * Convert.ToDecimal(tax.Percentage) + deduction;
                        }
                    }
                    thisBidLpo.AmountPayable = thisBidLpo.GrossAmount - deduction + charge;
                    thisBidLpo.Tax           = (thisBidLpo.AmountPayable - thisBidLpo.GrossAmount);
                }
                return(thisBidLpo);
            }

            catch (Exception ex)
            {
                throw;
            }
        }
        public async Task <bool> AddUpdateLPOAsync(purch_plpo model)
        {
            if (model.PLPOId > 0)
            {
                var itemTUpdate = await _dataContext.purch_plpo.FindAsync(model.PLPOId);

                _dataContext.Entry(itemTUpdate).CurrentValues.SetValues(model);
            }
            else
            {
                await _dataContext.purch_plpo.AddAsync(model);
            }
            return(await _dataContext.SaveChangesAsync() > 0);
        }
        public async Task RemoveLostBidsAndProposals(purch_plpo lpo)
        {
            var lostbids = _dataContext.cor_bid_and_tender.Where(a => a.PLPOId == lpo.PLPOId && a.BidAndTenderId != lpo.WinnerSupplierId).ToList();

            if (lostbids.Count() > 0)
            {
                var lostProposals = _dataContext.cor_paymentterms.Where(b => lostbids.Select(q => q.BidAndTenderId).Contains(b.BidAndTenderId)).ToList();
                if (lostProposals.Count() > 0)
                {
                    _dataContext.cor_paymentterms.RemoveRange(lostProposals);
                }
                _dataContext.cor_bid_and_tender.RemoveRange(lostbids);
            }
        }
Exemplo n.º 5
0
            private inv_invoice BuildInvoiceDomainObject(cor_paymentterms phase, purch_plpo lpo, UserDataResponseObj user)
            {
                ///var supplierdetails = GetGLFromSupplierTypeAsync(lpo.WinnerSupplierId).Result;
                var invoiceNumber = $"{DateTime.Now.Year - 1234}{DateTime.Now.Month}{DateTime.Now.Day}{lpo.PurchaseReqNoteId}{phase.PaymentTermId}";

                return(new inv_invoice
                {
                    Address = lpo.Address,
                    LPOId = lpo.PLPOId,
                    AmountPayable = lpo.AmountPayable,
                    ApprovalStatusId = (int)ApprovalStatus.Pending,
                    CompanyId = lpo.CompanyId,
                    DeliveryDate = lpo.DeliveryDate,
                    Description = lpo.Description,
                    Amount = phase.NetAmount,
                    InvoiceNumber = invoiceNumber,
                    LPONumber = lpo.LPONumber,
                    PaymentTermId = phase.PaymentTermId,
                    RequestDate = lpo.RequestDate,
                    SupplierId = lpo.WinnerSupplierId,
                });
            }
 private purch_plpo ReturnAmountPayable(List <cor_taxsetup> TaxSetup, purch_plpo thisBidLpo)
 {
     if (TaxSetup.Count() > 0)
     {
         decimal charge    = new decimal();
         decimal deduction = new decimal();
         thisBidLpo.Taxes = string.Join(',', TaxSetup.Select(s => s.TaxSetupId));
         foreach (var tax in TaxSetup)
         {
             if (tax.Type == "+")
             {
                 charge = thisBidLpo.GrossAmount / 100 * Convert.ToDecimal(tax.Percentage);
             }
             if (tax.Type == "-")
             {
                 deduction = thisBidLpo.GrossAmount / 100 * Convert.ToDecimal(tax.Percentage);
             }
         }
         thisBidLpo.AmountPayable = thisBidLpo.GrossAmount - deduction + charge;
         thisBidLpo.Tax           = (thisBidLpo.AmountPayable - thisBidLpo.GrossAmount);
         return(thisBidLpo);
     }
     return(new purch_plpo());
 }
            public async Task <PaymentTermsRegRespObj> Handle(SaveUpdateLPOCommand request, CancellationToken cancellationToken)
            {
                var response = new PaymentTermsRegRespObj {
                    Status = new APIResponseStatus {
                        IsSuccessful = false, Message = new APIResponseMessage()
                    }
                };

                try
                {
                    var user = await _serverRequest.UserDataAsync();

                    if (user == null)
                    {
                        response.Status.Message.FriendlyMessage = "Unable To Process This User";
                        return(response);
                    }
                    purch_plpo currentlpo = new purch_plpo();
                    currentlpo = await _repo.GetLPOsAsync(request.LPOId);

                    if (currentlpo == null)
                    {
                        response.Status.Message.FriendlyMessage = "Unable To Identify LPO associated to this payment proposal (s)";
                        return(response);
                    }
                    var phases = _dataContext.cor_paymentterms.Where(q => q.LPOId == currentlpo.PLPOId && q.ProposedBy == (int)Proposer.STAFF).ToList();
                    if (phases.Count() > 0 && phases.Any(q => q.PaymentStatus == (int)PaymentStatus.Not_Paid || q.PaymentStatus == (int)PaymentStatus.Paid))
                    {
                        response.Status.Message.FriendlyMessage = "Payment process already started for this LPO";
                        return(response);
                    }

                    if (!string.IsNullOrEmpty(currentlpo.Taxes))
                    {
                        if (request.TaxId.Count() > 0)
                        {
                            var taxselected = currentlpo.Taxes.Split(',').Select(int.Parse).Except(request.TaxId).ToList();
                            currentlpo.Taxes = string.Join(',', taxselected);
                            if (taxselected.Count() > 0)
                            {
                                var appliedTaxes = await GetAppliedTaxes(taxselected);

                                var lpo = ReturnAmountPayable(appliedTaxes, currentlpo);
                                currentlpo.AmountPayable = lpo.AmountPayable;
                                currentlpo.Tax           = lpo.Tax;
                            }
                            if (taxselected.Count() == 0)
                            {
                                currentlpo.AmountPayable = currentlpo.GrossAmount;
                                currentlpo.Tax           = 0;
                            }
                        }
                    }
                    currentlpo.ServiceTerm = request.ServicetermsId;
                    using (var _transaction = await _dataContext.Database.BeginTransactionAsync())
                    {
                        try
                        {
                            var targetList = new List <int>();
                            targetList.Add(currentlpo.PLPOId);
                            GoForApprovalRequest wfRequest = new GoForApprovalRequest
                            {
                                Comment                = "Bidded LPO",
                                OperationId            = (int)OperationsEnum.PurchaseLPOApproval,
                                TargetId               = targetList,
                                ApprovalStatus         = (int)ApprovalStatus.Processing,
                                DeferredExecution      = true,
                                StaffId                = user.StaffId,
                                CompanyId              = user.CompanyId,
                                EmailNotification      = false,
                                ExternalInitialization = false,
                                StatusId               = (int)ApprovalStatus.Processing,
                            };

                            var result = await _serverRequest.GotForApprovalAsync(wfRequest);

                            if (!result.IsSuccessStatusCode)
                            {
                                response.Status.IsSuccessful            = false;
                                response.Status.Message.FriendlyMessage = $"{result.ReasonPhrase} {result.StatusCode}";
                                return(response);
                            }
                            var stringData = await result.Content.ReadAsStringAsync();

                            GoForApprovalRespObj res = JsonConvert.DeserializeObject <GoForApprovalRespObj>(stringData);

                            if (res.ApprovalProcessStarted)
                            {
                                currentlpo.ApprovalStatusId = (int)ApprovalStatus.Processing;
                                currentlpo.WorkflowToken    = res.Status.CustomToken;
                                await _repo.AddUpdateLPOAsync(currentlpo);

                                await _transaction.CommitAsync();

                                response.Status.IsSuccessful = res.Status.IsSuccessful;
                                response.Status.Message      = res.Status.Message;
                                return(response);
                            }

                            if (res.EnableWorkflow || !res.HasWorkflowAccess)
                            {
                                response.Status.IsSuccessful = res.Status.IsSuccessful;
                                response.Status.Message      = res.Status.Message;
                                return(response);
                            }
                            if (!res.EnableWorkflow)
                            {
                                currentlpo.ApprovalStatusId = (int)ApprovalStatus.Approved;
                                await _repo.AddUpdateLPOAsync(currentlpo);

                                await _repo.ShareTaxToPhasesIthereIsAsync(currentlpo);

                                await _repo.RemoveLostBidsAndProposals(currentlpo);

                                await _transaction.CommitAsync();

                                response.Status.IsSuccessful            = true;
                                response.Status.Message.FriendlyMessage = "LPO Updated";
                                return(response);
                            }
                            response.Status.IsSuccessful = res.Status.IsSuccessful;
                            response.Status.Message      = res.Status.Message;
                            return(response);
                        }
                        catch (Exception ex)
                        {
                            await _transaction.RollbackAsync();

                            #region Log error to file
                            var errorCode = ErrorID.Generate(4);
                            _logger.Error($"ErrorID : {errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}");
                            response.Status.Message.FriendlyMessage  = "Error occured!! Please try again later";
                            response.Status.Message.MessageId        = errorCode;
                            response.Status.Message.TechnicalMessage = $"ErrorID : {errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}";
                            return(response);

                            #endregion
                        }
                        finally { await _transaction.DisposeAsync(); }
                    }
                }
                catch (Exception ex)
                {
                    #region Log error to file
                    var errorCode = ErrorID.Generate(4);
                    _logger.Error($"ErrorID : {errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}");
                    return(new PaymentTermsRegRespObj
                    {
                        Status = new APIResponseStatus
                        {
                            IsSuccessful = false,
                            Message = new APIResponseMessage
                            {
                                FriendlyMessage = "Error occured!! Unable to process item",
                                MessageId = errorCode,
                                TechnicalMessage = $"ErrorID : {errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}"
                            }
                        }
                    });

                    #endregion
                }
            }
        private cor_approvaldetail BuildApprovalDetailObject(LPOStaffApprovalCommand request, purch_plpo currentItem, int staffId)
        {
            var approvalDeatil = new cor_approvaldetail();
            var previousDetail = _detailService.GetApprovalDetailsAsync(request.TargetId, currentItem.WorkflowToken).Result;

            approvalDeatil.ArrivalDate = currentItem.RequestDate;

            if (previousDetail.Count() > 0)
            {
                approvalDeatil.ArrivalDate = previousDetail.OrderByDescending(s => s.ApprovalDetailId).FirstOrDefault().Date;
            }

            approvalDeatil.Comment         = request.ApprovalComment;
            approvalDeatil.Date            = DateTime.Today;
            approvalDeatil.StatusId        = request.ApprovalStatus;
            approvalDeatil.TargetId        = request.TargetId;
            approvalDeatil.StaffId         = staffId;
            approvalDeatil.ReferredStaffId = request.ReferredStaffId;
            approvalDeatil.WorkflowToken   = currentItem.WorkflowToken;
            return(approvalDeatil);
        }
 public cor_bid_and_tender BuildBidAndTenderDomianObjectForNonSelectedSuppliers(purch_plpo lpo, int Requstingdpt, purch_prndetails model)
 {
     return(new cor_bid_and_tender
     {
         PurchaseReqNoteId = model.PurchaseReqNoteId,
         DescriptionOfRequest = lpo.Description,
         Location = lpo.Address,
         LPOnumber = lpo.LPONumber,
         ProposedAmount = 0,
         RequestDate = DateTime.Today,
         RequestingDepartment = Requstingdpt,
         SupplierName = string.Empty,
         Suppliernumber = string.Empty,
         AmountApproved = lpo.Total,
         DecisionResult = (int)DecisionResult.Non_Applicable,
         PLPOId = lpo.PLPOId,
         SupplierId = 0,
         Quantity = model.Quantity,
         Total = model.SubTotal,
         ApprovalStatusId = (int)ApprovalStatus.Awaiting,
         SupplierAddress = string.Empty,
         ExpectedDeliveryDate = lpo.DeliveryDate,
         CompanyId = model.CompanyId,
         Comment = model.Comment,
         SelectedSuppliers = string.Join(',', lpo.SupplierIds),
     });
 }
            public async Task SendEmailToOfficerForPaymentAsync(cor_paymentterms phase, purch_plpo lpo)
            {
                var userid = _accessor.HttpContext.User?.FindFirst(q => q.Type == "userId")?.Value;
                var user   = await _userManager.FindByIdAsync(userid);

                if (user != null)
                {
                    EmailMessageObj em = new EmailMessageObj {
                        ToAddresses = new List <EmailAddressObj>(), FromAddresses = new List <EmailAddressObj>()
                    };

                    var supplier = _dataContext.cor_supplier.FirstOrDefault(q => q.Email == user.Email);
                    var path     = $"#/purchases-and-supplier/lpo?id={phase.LPOId}";

                    var path2 = $"{_uRIs.MainClient}/{path}";


                    em.Subject = $"Payment Request";
                    em.Content = $"Supplier with supplier number {supplier.SupplierNumber} <br> is requesting for payment for " +
                                 $"the supply of {lpo.Description} <br> on  Phase '{phase.Phase}'" +
                                 $" with project status of '{ Convert.ToString((JobProgressStatus)phase.Status)} '" +
                                 $"<br> Please click <a href='{path2}'> here </a> to see details of Payment";

                    var frm = new EmailAddressObj
                    {
                        Address = supplier.Email,
                        Name    = supplier.Name,
                    };
                    em.FromAddresses.Add(frm);
                    em.ActivitIds = new List <int>();
                    em.ActivitIds.Add(14);
                    em.SendIt   = true;
                    em.SaveIt   = false;
                    em.Template = (int)EmailTemplate.Advert;

                    await _serverRequest.SendSpecificMessageAsync(em);
                }
            }