public async Task <ActionResult <LoanReviewListObjRespObj> > AddLoanBooking([FromBody] LoanReviewApplicationObj model)
        {
            try
            {
                var identity = await _serverRequest.UserDataAsync();

                var user = identity.UserName;

                model.CreatedBy = user;
                model.UpdatedBy = user;

                var response = await _repo.AddUpdateLMSApplication(model);

                return(response);
            }
            catch (Exception ex)
            {
                var errorCode = ErrorID.Generate(5);
                _logger.Error($"ErrorID : {errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}");
                return(new LoanReviewListObjRespObj
                {
                    Status = new APIResponseStatus {
                        IsSuccessful = false, Message = new APIResponseMessage {
                            FriendlyMessage = "Error Occurred", TechnicalMessage = ex?.Message, MessageId = errorCode
                        }
                    }
                });
            }
        }
Example #2
0
        public async Task <ActionResult <ProductRegRespObj> > AddUpdateProductAsync([FromBody] ProductObj entity)
        {
            try
            {
                var isDone = false;
                var user   = await _identityServer.UserDataAsync();

                var createdBy = user.UserName;
                entity.CreatedBy = createdBy;
                entity.UpdatedBy = createdBy;

                var product = _repo.AddUpdateProduct(entity);

                if (product != null)
                {
                    isDone = true;
                    var allAllowableCollaterals = await _allowableCollateralRepository.GetAllowableCollateralByProductIdAsync(product.ProductId);

                    if (allAllowableCollaterals != null)
                    {
                        await _allowableCollateralRepository.DeleteListAllowableCollateralByProductIdAsync(product.ProductId);
                    }
                    var listOfAallowableCollateral = new List <AllowableCollateralObj>();
                    if (entity.AllowableCollaterals != null)
                    {
                        foreach (var id in entity.AllowableCollaterals)
                        {
                            listOfAallowableCollateral.Add(new AllowableCollateralObj {
                                CollateralTypeId = id, ProductId = product.ProductId
                            });
                        }

                        await _allowableCollateralRepository.AddAllowableCollateral(listOfAallowableCollateral);
                    }
                }
                return(new ProductRegRespObj
                {
                    Products = product,
                    Status = new APIResponseStatus {
                        IsSuccessful = isDone ? true : false, Message = new APIResponseMessage {
                            FriendlyMessage = isDone ? "Successful" : "Unsuccessful"
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                var errorCode = ErrorID.Generate(5);
                _logger.Error($"ErrorID : {errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}");
                return(new ProductRegRespObj
                {
                    Status = new APIResponseStatus {
                        IsSuccessful = false, Message = new APIResponseMessage {
                            FriendlyMessage = "Error Occurred", TechnicalMessage = ex?.Message, MessageId = errorCode
                        }
                    }
                });
            }
        }
        private void updateCASA(DepositAccountOpeningObj entity, int customerId, string accountNumber)
        {
            decimal bal       = _dataContext.deposit_accountsetup.Where(x => x.DepositAccountId == entity.AccountTypeId).FirstOrDefault().InitialDeposit;
            decimal Ledgerbal = _dataContext.deposit_accountsetup.Where(x => x.DepositAccountId == entity.AccountTypeId).FirstOrDefault().InitialDeposit;
            decimal?irate     = _dataContext.deposit_accountsetup.Where(x => x.DepositAccountId == entity.AccountTypeId).FirstOrDefault().InterestRate;
            decimal lienBal   = _dataContext.deposit_accountsetup.Where(x => x.DepositAccountId == entity.AccountTypeId).FirstOrDefault().InitialDeposit;

            var         user        = _serverRequest.UserDataAsync().Result;
            credit_casa casaAccount = null;

            casaAccount = _dataContext.credit_casa.Where(x => x.CustomerId == customerId).FirstOrDefault();
            if (casaAccount == null)
            {
                var customerAccount = new credit_casa
                {
                    AccountName     = $"{entity.Firstname}{entity.Surname}",//entity.Firstname + " " + entity.Surname,
                    AccountNumber   = accountNumber,
                    AccountStatusId = (int)CASAAccountStatusEnum.Inactive,
                    //ActionBy = entity.actionBy,
                    ActionDate       = DateTime.Now,
                    AprovalStatusId  = (int)ApprovalStatus.Pending,
                    AvailableBalance = bal,
                    BranchId         = 1,
                    CompanyId        = 7,
                    CustomerId       = customerId,
                    //CustomerSensitivityLevelId = entity.customerSensitivityLevelId,
                    EffectiveDate    = DateTime.Now,
                    HasLien          = true,
                    HasOverdraft     = true,
                    InterestRate     = irate,
                    IsCurrentAccount = false,
                    LedgerBalance    = Ledgerbal,
                    LienAmount       = lienBal,
                    //MISCode = "",
                    OperationId = (int)OperationsEnum.CasaAccountApproval,
                    //OverdraftAmount = 0,
                    //OverdraftExpiryDate = entity.overdraftExpiryDate,
                    //OverdraftInterestRate = 0,
                    //PostNoStatusId = entity.postNoStatusId,
                    ProductId             = entity.AccountTypeId,
                    RelationshipManagerId = 0,
                    RelationshipOfficerId = 0,
                    //TEAMMISCode = "",
                    FromDeposit = true,
                    //Tenor = entity.tenor,
                    //TerminalDate = entity.terminalDate,
                    Active    = true,
                    Deleted   = false,
                    CreatedBy = user.UserName,
                    CreatedOn = DateTime.Now,
                    UpdatedBy = user.UserName,
                    UpdatedOn = DateTime.Now,
                };
                _dataContext.credit_casa.Add(customerAccount);
                _dataContext.SaveChanges();
            }
        }
Example #4
0
        public override Task <int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
        {
            var user = _serverRequest.UserDataAsync().Result;

            if (user.StaffId < 0)
            {
                user.UserName = "******";
            }
            foreach (var entry in ChangeTracker.Entries <GeneralEntity>())
            {
                if (entry.State == EntityState.Added)
                {
                    entry.Entity.Active    = true;
                    entry.Entity.Deleted   = false;
                    entry.Entity.Active    = false;
                    entry.Entity.CreatedBy = user.UserName;
                    entry.Entity.CreatedOn = DateTime.Now;
                }
                else
                {
                    entry.Entity.UpdatedOn = DateTime.Now;
                    entry.Entity.UpdatedBy = user.UserName;
                }
            }
            return(base.SaveChangesAsync(cancellationToken));
        }
Example #5
0
            public async Task <PaymentTermsRegRespObj> Handle(RefreshPPELPOCommand 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);
                    }
                    var ppeclasses = await _pperequest.GetAllPPEClassificationsAsync();

                    if (ppeclasses.AssetClassifications.Count() > 0)
                    {
                        var lpos = await _dataContext.purch_plpo.ToListAsync();

                        var typePPELpos = (from a in lpos
                                           join b in _dataContext.cor_supplier on a.WinnerSupplierId equals b.SupplierId
                                           join c in _dataContext.cor_suppliertype on b.SupplierTypeId equals c.SupplierTypeId
                                           join d in ppeclasses.AssetClassifications on c.DebitGL equals d.SubGlAddition
                                           select a).ToList();

                        var typePPELposmapped = _mapper.Map <List <UpdatePPELPO> >(typePPELpos);
                        await _pperequest.CreateUpdateLPOForAdditionAsync(typePPELposmapped);
                    }

                    response.Status.IsSuccessful            = true;
                    response.Status.Message.FriendlyMessage = "Successful";
                    return(response);
                }
                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
                }
            }
Example #6
0
        public async Task <ActionResult <LoanCustomerFSCaptionGroupRespObj> > AddUpdateLoanCustomerFSCaptionGroup([FromBody] LoanCustomerFSCaptionGroupObj model)
        {
            try
            {
                var identity = await _identityServer.UserDataAsync();

                var user = identity.UserName;

                model.CreatedBy = user;
                model.UpdatedBy = user;

                var response = _repo.AddUpdateLoanCustomerFSCaptionGroup(model);
                if (response)
                {
                    return(new LoanCustomerFSCaptionGroupRespObj
                    {
                        Status = new APIResponseStatus {
                            IsSuccessful = true, Message = new APIResponseMessage {
                                FriendlyMessage = $"Record saved successfully."
                            }
                        }
                    });
                }
                return(new LoanCustomerFSCaptionGroupRespObj
                {
                    Status = new APIResponseStatus {
                        IsSuccessful = false, Message = new APIResponseMessage {
                            FriendlyMessage = "Record not saved"
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                var errorCode = ErrorID.Generate(5);
                _logger.Error($"ErrorID : {errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}");
                return(new LoanCustomerFSCaptionGroupRespObj
                {
                    Status = new APIResponseStatus {
                        IsSuccessful = false, Message = new APIResponseMessage {
                            FriendlyMessage = "Error Occurred", TechnicalMessage = ex?.Message, MessageId = errorCode
                        }
                    }
                });
            }
        }
        public async Task <SupplierFinancialDetalRegRespObj> Handle(AddUpdateSupplierFinancialDetalCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var currentUserId        = _httpContextAccessor.HttpContext.User?.FindFirst(x => x.Type == "userId").Value;
                UserDataResponseObj user = null;

                user = await _serverRequest.UserDataAsync();

                cor_financialdetail item = new cor_financialdetail();
                item.Deleted           = false;
                item.CreatedOn         = request.SupplierId > 0 ? (DateTime?)null : DateTime.Now;
                item.CreatedBy         = user != null ? user.UserName : "";
                item.UpdatedBy         = user != null ? user.UserName : "";
                item.SupplierId        = request.SupplierId;
                item.Value             = request.Value;
                item.Year              = request.Year;
                item.FinancialdetailId = request.FinancialdetailId;
                item.BusinessSize      = request.BusinessSize;
                item.Active            = true;

                await _supRepo.AddUpdateBankFinancialDetailsAsync(item);

                return(new SupplierFinancialDetalRegRespObj
                {
                    FinancialdetailId = item.FinancialdetailId,
                    Status = new APIResponseStatus
                    {
                        IsSuccessful = true,
                        Message = new APIResponseMessage
                        {
                            FriendlyMessage = "Successful",
                        }
                    }
                });
            }
            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 SupplierFinancialDetalRegRespObj
                {
                    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
            }
        }
        public async Task <ActionResult <CollateralTypeRespObj> > GetAllCollateralType()
        {
            try
            {
                var user = await _serverRequest.UserDataAsync();

                var createdBy = user.UserName;
                var response  = _repo.GetAllCollateralType();
                return(new CollateralTypeRespObj
                {
                    CollateralTypes = response,
                });
            }
            catch (Exception ex)
            {
                var errorCode = ErrorID.Generate(5);
                _logger.Error($"ErrorID : {errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}");
                return(new CollateralTypeRespObj
                {
                    Status = new APIResponseStatus {
                        IsSuccessful = false, Message = new APIResponseMessage {
                            FriendlyMessage = "Error Occurred", TechnicalMessage = ex?.Message, MessageId = errorCode
                        }
                    }
                });
            }
        }
        public async Task <IEnumerable <cor_supplier> > SupplierInformationAwaitingApprovalAsync(string userName)
        {
            var userDetail = await _serverRequest.UserDataAsync();

            var thisUserSupplierData = await _dataContext.cor_supplier.Where(x => x.Email == userDetail.Email).ToListAsync();

            return(thisUserSupplierData.Where(x => x.ApprovalStatusId == (int)ApprovalStatus.Pending &&
                                              x.ApprovalStatusId == (int)ApprovalStatus.Processing));
        }
        public async Task <SupplierTopSupplierRegRespObj> Handle(UpdateSupplierTopSupplierCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var user = await _serverRequest.UserDataAsync();

                cor_topsupplier supTopSupplier = new cor_topsupplier();
                supTopSupplier.Deleted       = false;
                supTopSupplier.CreatedOn     = request.SupplierId > 0 ? (DateTime?)null : DateTime.Now;
                supTopSupplier.CreatedBy     = user != null ? user.UserName : "";
                supTopSupplier.UpdatedBy     = user != null ? user.UserName : "";
                supTopSupplier.SupplierId    = request.SupplierId;
                supTopSupplier.TopSupplierId = request.TopSupplierId;
                supTopSupplier.PhoneNo       = request.PhoneNo;
                supTopSupplier.Name          = request.Name;
                supTopSupplier.Address       = request.Address;
                supTopSupplier.ContactPerson = request.ContactPerson;
                supTopSupplier.Email         = request.Email;
                supTopSupplier.NoOfStaff     = request.NoOfStaff;
                supTopSupplier.CountryId     = request.CountryId;
                await _supRepo.UpdateSupplierTopSupplierAsync(supTopSupplier);

                return(new SupplierTopSupplierRegRespObj
                {
                    TopSupplierId = supTopSupplier.TopSupplierId,
                    Status = new APIResponseStatus
                    {
                        IsSuccessful = true,
                        Message = new APIResponseMessage
                        {
                            FriendlyMessage = "Successful",
                        }
                    }
                });
            }
            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 SupplierTopSupplierRegRespObj
                {
                    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
            }
        }
            public async Task <PaymentTermsRegRespObj> Handle(RequestforPaymentCommand 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);
                    }

                    var paymentProposal = await _repo.GetSinglePaymenttermAsync(request.PaymentTermId);

                    if (paymentProposal.PaymentStatus == (int)PaymentStatus.Paid)
                    {
                        response.Status.Message.FriendlyMessage = "Payment already made for this phase";
                        return(response);
                    }
                    var thisphaseLpo = await _repo.GetLPOsAsync(paymentProposal.LPOId);

                    if (thisphaseLpo == null)
                    {
                        response.Status.Message.FriendlyMessage = "Unable to Identify this Phase LPO";
                        return(response);
                    }

                    if (paymentProposal.InvoiceGenerated)
                    {
                        response.Status.Message.FriendlyMessage = "Invoice Already generated for this phase";
                        return(response);
                    }

                    await SendEmailToOfficerForPaymentAsync(paymentProposal, thisphaseLpo);

                    response.Status.IsSuccessful            = true;
                    response.Status.Message.FriendlyMessage = "Payment Request Successfully sent";
                    return(response);
                }
                catch (Exception ex)
                {
                    #region Log error to file
                    response.Status.IsSuccessful             = false;
                    response.Status.Message.FriendlyMessage  = "Error occured!! Unable to process item";
                    response.Status.Message.TechnicalMessage = $"Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}";
                    return(response);

                    #endregion
                }
            }
        public async Task <SuppliertypeRegRespObj> Handle(AddUpdateSuppliertypeCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var user = await _serverRequest.UserDataAsync();

                cor_suppliertype sup = new cor_suppliertype();
                sup.Deleted          = true;
                sup.CreatedOn        = request.SupplierTypeId > 0 ? (DateTime?)null : DateTime.Now;
                sup.CreatedBy        = user.UserName;
                sup.UpdatedBy        = user.UserName;
                sup.SupplierTypeName = request.SupplierTypeName;
                sup.TaxApplicable    = string.Join(',', request.TaxApplicable);
                sup.CreditGL         = request.CreditGL;
                sup.DebitGL          = request.DebitGL;
                sup.Deleted          = false;
                sup.SupplierTypeId   = request.SupplierTypeId > 0 ? request.SupplierTypeId : 0;
                await _supRepo.AddUpdateSupplierTypeAsync(sup);

                var actionTaken = request.SupplierTypeId < 1 ? "created" : "updated";
                return(new SuppliertypeRegRespObj
                {
                    SuppliertypeId = sup.SupplierTypeId,
                    Status = new APIResponseStatus
                    {
                        IsSuccessful = true,
                        Message = new APIResponseMessage
                        {
                            FriendlyMessage = $"Successfully  {actionTaken}",
                        }
                    }
                });
            }
            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 SuppliertypeRegRespObj
                {
                    Status = new APIResponseStatus
                    {
                        IsSuccessful = false,
                        Message = new APIResponseMessage
                        {
                            FriendlyMessage = "Error occured!! Unable to process request",
                            MessageId = errorCode,
                            TechnicalMessage = $"ErrorID : {errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}"
                        }
                    }
                });

                #endregion
            }
        }
        public async Task <ActionResult <LoanStagingRegRespObj> > AddUpDateAccountType([FromBody] LoanStagingObj model)
        {
            try
            {
                LoanStagingObj item = null;
                if (model.LoanStagingId > 0)
                {
                    item = await _repo.GetLoanStagingByIdAsync(model.LoanStagingId);

                    if (item == null)
                    {
                        return new LoanStagingRegRespObj
                               {
                                   Status = new APIResponseStatus {
                                       IsSuccessful = false, Message = new APIResponseMessage {
                                           FriendlyMessage = "Item does not Exist"
                                       }
                                   }
                               }
                    }
                    ;
                }
                var user = await _identityServer.UserDataAsync();

                var createdBy = user.UserName;

                model.CreatedBy = createdBy;
                model.UpdatedBy = createdBy;

                await _repo.AddOrUpdateLoanStagingAsync(model);

                return(new LoanStagingRegRespObj
                {
                    Status = new APIResponseStatus {
                        IsSuccessful = true, Message = new APIResponseMessage {
                            FriendlyMessage = "Successful"
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                var errorCode = ErrorID.Generate(5);
                return(new LoanStagingRegRespObj
                {
                    Status = new APIResponseStatus {
                        IsSuccessful = false, Message = new APIResponseMessage {
                            FriendlyMessage = "Error Occurred", TechnicalMessage = ex?.Message, MessageId = errorCode
                        }
                    }
                });
            }
        }
Example #14
0
        public async Task <ActionResult <IFRSRespObj> > AddUpdateIFRSSetupData([FromBody] IFRSSetupDataObj model)
        {
            try
            {
                var identity = await _identityServer.UserDataAsync();

                var user = identity.UserName;

                model.CreatedBy = user;
                model.UpdatedBy = user;

                var response = _repo.AddUpdateIFRSSetupData(model);
                return(new IFRSRespObj
                {
                    Status = new APIResponseStatus {
                        IsSuccessful = response ? true : false, Message = new APIResponseMessage {
                            FriendlyMessage = response ? "Record saved Successfully" : "Unsuccessful"
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                var errorCode = ErrorID.Generate(5);
                _logger.Error($"ErrorID : {errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}");
                return(new IFRSRespObj
                {
                    Status = new APIResponseStatus {
                        IsSuccessful = false, Message = new APIResponseMessage {
                            FriendlyMessage = "Error Occurred", TechnicalMessage = ex?.Message, MessageId = errorCode
                        }
                    }
                });
            }
        }
Example #15
0
        public async Task <ActionResult <FeeRegRespObj> > UploadFeeAsync()
        {
            try
            {
                var files = _httpContextAccessor.HttpContext.Request.Form.Files;

                var byteList = new List <byte[]>();
                foreach (var fileBit in files)
                {
                    if (fileBit.Length > 0)
                    {
                        using (var ms = new MemoryStream())
                        {
                            await fileBit.CopyToAsync(ms);

                            byteList.Add(ms.ToArray());
                        }
                    }
                }

                var user = await _identityServer.UserDataAsync();

                var createdBy = user.UserName;

                var isDone = await _repo.UploadFeeAsync(byteList, createdBy);

                return(new FeeRegRespObj
                {
                    Status = new APIResponseStatus {
                        IsSuccessful = isDone ? true : false, Message = new APIResponseMessage {
                            FriendlyMessage = isDone ? "Successful" : "Unsuccessful"
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                var errorCode = ErrorID.Generate(5);
                _logger.Error($"ErrorID : {errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}");
                return(new FeeRegRespObj
                {
                    Status = new APIResponseStatus {
                        IsSuccessful = false, Message = new APIResponseMessage {
                            FriendlyMessage = "Error Occurred", TechnicalMessage = ex?.Message, MessageId = errorCode
                        }
                    }
                });
            }
        }
        public async Task <ActionResult <LoanRespObj> > AddLoanBooking([FromBody] LoanReviewOperationObj model)
        {
            try
            {
                using (var _trans = _context.Database.BeginTransaction())
                {
                    var identity = await _identityServer.UserDataAsync();

                    var user = identity.UserName;

                    model.CreatedBy = user;
                    model.UpdatedBy = user;

                    var appicationResponse = _repo.AddOperationReview(model);

                    if (appicationResponse.loanPayment != null && appicationResponse.AnyIdentifier > 0)
                    {
                        await _schedule.AddLoanSchedule(appicationResponse.AnyIdentifier, appicationResponse.loanPayment);
                    }
                    await _context.SaveChangesAsync();

                    _trans.Commit();
                    return(new LoanRespObj
                    {
                        Status = new APIResponseStatus {
                            IsSuccessful = true, Message = new APIResponseMessage {
                                FriendlyMessage = "Successful"
                            }
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                var errorCode = ErrorID.Generate(5);
                _logger.Error($"ErrorID : {errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}");
                return(new LoanRespObj
                {
                    Status = new APIResponseStatus {
                        IsSuccessful = false, Message = new APIResponseMessage {
                            FriendlyMessage = "Error Occurred", TechnicalMessage = ex?.Message, MessageId = errorCode
                        }
                    }
                });
            }
        }
Example #17
0
        public async Task <RequisitionNoteRespObj> Handle(GetAllPRNQuery request, CancellationToken cancellationToken)
        {
            var prn = await _repo.GetAllPurchaseRequisitionNoteAsync();

            var _Department = await _serverRequest.GetAllCompanyStructureAsync();

            var user = await _serverRequest.UserDataAsync();

            return(new RequisitionNoteRespObj
            {
                RequisitionNotes = prn.Where(q => q.StaffId == user.StaffId).OrderByDescending(r => r.PurchaseReqNoteId).Select(d => new RequisitionNoteObj
                {
                    ApprovalStatusId = d.ApprovalStatusId,
                    Comment = d.Comment,
                    DeliveryLocation = d.DeliveryLocation,
                    DepartmentId = d.DepartmentId,
                    Description = d.Description,
                    DocumentNumber = d.DocumentNumber,
                    ExpectedDeliveryDate = d.ExpectedDeliveryDate,
                    IsFundAvailable = d.IsFundAvailable,
                    PurchaseReqNoteId = d.PurchaseReqNoteId,
                    RequestBy = d.RequestBy,
                    StatusName = Convert.ToString((ApprovalStatus)d.ApprovalStatusId),
                    Total = d.Total,
                    WorkflowToken = d.WorkflowToken,
                    RequestDate = d.CreatedOn,
                    PRNNumber = d.PRNNumber,
                    DepartmentName = _Department.companyStructures.FirstOrDefault(c => c.CompanyStructureId == d.DepartmentId)?.Name,
                    DetailsCount = d.purch_prndetails.Count()
                }).ToList(),
                Status = new APIResponseStatus
                {
                    IsSuccessful = true,
                    Message = new APIResponseMessage
                    {
                        FriendlyMessage = prn.Count() < 1 ? "No PRN awaiting approvals" : null
                    }
                }
            });
        }
Example #18
0
        private async Task <bool> NoDuplicateEmail(UpdateSupplierCommand request, CancellationToken cancellation)
        {
            var user = await _serverRequest.UserDataAsync();

            if (user.StaffId > 0)
            {
                if (request.SupplierId > 0)
                {
                    var otherSupplier = _dataContext.cor_supplier.FirstOrDefault(q => q.Email.Trim().ToLower() == request.Email.Trim().ToLower() && q.SupplierId != request.SupplierId) ?? null;
                    if (otherSupplier == null)
                    {
                        return(await Task.Run(() => true));
                    }
                }
                var other = _dataContext.cor_supplier.FirstOrDefault(q => q.Email.Trim().ToLower() == request.Email.Trim().ToLower()) ?? null;
                if (other == null)
                {
                    return(await Task.Run(() => true));
                }
                return(await Task.Run(() => false));
            }
            return(await Task.Run(() => true));
        }
Example #19
0
            public async Task <FileUploadRespObj> Handle(UploadSupplierTypeCommand request, CancellationToken cancellationToken)
            {
                try
                {
                    var apiResponse = new FileUploadRespObj {
                        Status = new APIResponseStatus {
                            IsSuccessful = false, Message = new APIResponseMessage()
                        }
                    };

                    var files = _accessor.HttpContext.Request.Form.Files;

                    var byteList = new List <byte[]>();
                    foreach (var fileBit in files)
                    {
                        if (fileBit.Length > 0)
                        {
                            using (var ms = new MemoryStream())
                            {
                                await fileBit.CopyToAsync(ms);

                                byteList.Add(ms.ToArray());
                            }
                        }
                    }
                    var user = await _serverRequest.UserDataAsync();

                    var uploadedRecord = new List <SupplierTypeObj>();
                    ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

                    if (byteList.Count() > 0)
                    {
                        foreach (var byteItem in byteList)
                        {
                            using (MemoryStream stream = new MemoryStream(byteItem))
                                using (ExcelPackage excelPackage = new ExcelPackage(stream))
                                {
                                    ExcelWorksheet workSheet    = excelPackage.Workbook.Worksheets[0];
                                    int            totalRows    = workSheet.Dimension.Rows;
                                    int            totalColumns = workSheet.Dimension.Columns;

                                    if (totalColumns != 2)
                                    {
                                        apiResponse.Status.Message.FriendlyMessage = "2 Columns Expected";
                                        return(apiResponse);
                                    }

                                    for (int i = 2; i <= totalRows; i++)
                                    {
                                        var item = new SupplierTypeObj
                                        {
                                            ExcelLineNumber   = i,
                                            SupplierTypeName  = workSheet.Cells[i, 1]?.Value != null ? workSheet.Cells[i, 1]?.Value.ToString() : string.Empty,
                                            TaxApplicableName = workSheet.Cells[i, 2]?.Value != null ? workSheet.Cells[i, 2]?.Value.ToString() : string.Empty,
                                        };
                                        uploadedRecord.Add(item);
                                    }
                                }
                        }
                    }


                    var ItemList = await _repo.GetAllSupplierTypeAsync();

                    var TaxList = await _repo.GetAllTaxSetupAsync();

                    if (uploadedRecord.Count > 0)
                    {
                        var listOftaxt = new List <int>();

                        foreach (var item in uploadedRecord)
                        {
                            if (string.IsNullOrEmpty(item.TaxApplicableName))
                            {
                                apiResponse.Status.Message.FriendlyMessage = $"No Tax Applicable found Detected on line {item.ExcelLineNumber}";
                                return(apiResponse);
                            }
                            else
                            {
                                var taxNames = item.TaxApplicableName.Trim().ToLower().Split(',');
                                foreach (var tx in taxNames)
                                {
                                    var taxes = TaxList.FirstOrDefault(a => taxNames.Contains(a.TaxName.Trim().ToLower()));
                                    if (taxes == null)
                                    {
                                        apiResponse.Status.Message.FriendlyMessage = $"Unidentified Tax name Detected on line {item.ExcelLineNumber}";
                                        return(apiResponse);
                                    }
                                    listOftaxt.Add(taxes.TaxSetupId);
                                }
                            }
                            if (string.IsNullOrEmpty(item.SupplierTypeName))
                            {
                                apiResponse.Status.Message.FriendlyMessage = $"Empty Supplier Type Name Detected on line {item.ExcelLineNumber}";
                                return(apiResponse);
                            }

                            var itemFrmRepo = ItemList.FirstOrDefault(c => c.SupplierTypeName.ToLower().Trim() == item.SupplierTypeName.ToLower().Trim());

                            if (itemFrmRepo != null)
                            {
                                itemFrmRepo.SupplierTypeName = item?.SupplierTypeName;
                                itemFrmRepo.TaxApplicable    = string.Join(',', listOftaxt);
                                await _repo.AddUpdateSupplierTypeAsync(itemFrmRepo);
                            }
                            else
                            {
                                var newItem = new cor_suppliertype
                                {
                                    SupplierTypeName = item?.SupplierTypeName,
                                    TaxApplicable    = string.Join(',', listOftaxt),
                                };
                                await _repo.AddUpdateSupplierTypeAsync(newItem);
                            }
                        }
                    }
                    apiResponse.Status.IsSuccessful            = true;
                    apiResponse.Status.Message.FriendlyMessage = "Successful";
                    return(apiResponse);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
Example #20
0
        public async Task <ActionResult <CategoryRegRespObj> > AddUpDateCategory([FromBody] AddUpdateCategoryObj model)
        {
            try
            {
                var user = await _identityServer.UserDataAsync();

                deposit_category item = null;
                if (model.CategoryId > 0)
                {
                    item = await _repo.GetCategoryByIdAsync(model.CategoryId);

                    if (item == null)
                    {
                        return new CategoryRegRespObj
                               {
                                   Status = new APIResponseStatus {
                                       IsSuccessful = false, Message = new APIResponseMessage {
                                           FriendlyMessage = "Item does not Exist"
                                       }
                                   }
                               }
                    }
                    ;
                }

                var domainObj = new deposit_category();

                domainObj.CategoryId  = model.CategoryId > 0 ? model.CategoryId : 0;
                domainObj.Name        = model.Name;
                domainObj.Description = model.Description;
                domainObj.Active      = true;
                domainObj.CreatedOn   = DateTime.Today;
                domainObj.CreatedBy   = user.UserName;
                domainObj.Deleted     = false;
                domainObj.UpdatedOn   = model.CategoryId > 0 ? DateTime.Today : DateTime.Today;
                domainObj.UpdatedBy   = user.UserName;


                var isDone = await _repo.AddUpdateCategoryAsync(domainObj);

                return(new CategoryRegRespObj
                {
                    CategoryId = domainObj.CategoryId,
                    Status = new APIResponseStatus {
                        IsSuccessful = isDone ? true : false, Message = new APIResponseMessage {
                            FriendlyMessage = isDone ? "successful" : "Unsuccessful"
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                var errorCode = ErrorID.Generate(5);
                _logger.Error($"ErrorID : {errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}");
                return(new CategoryRegRespObj
                {
                    Status = new APIResponseStatus {
                        IsSuccessful = false, Message = new APIResponseMessage {
                            FriendlyMessage = "Error Occurred", TechnicalMessage = ex?.Message, MessageId = errorCode
                        }
                    }
                });
            }
        }
Example #21
0
        public async Task <SupplierRegRespObj> Handle(GothroughApprovalCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var supplierInfor = await _repo.GetSupplierAsync(request.SupplierId);

                if (supplierInfor == null)
                {
                    return(new SupplierRegRespObj
                    {
                        Status = new APIResponseStatus
                        {
                            IsSuccessful = false,
                            Message = new APIResponseMessage
                            {
                                FriendlyMessage = $"Supplier Not found"
                            }
                        }
                    });
                }
                var enumName = (ApprovalStatus)supplierInfor.ApprovalStatusId;
                if (supplierInfor.ApprovalStatusId != (int)ApprovalStatus.Pending)
                {
                    return(new SupplierRegRespObj
                    {
                        Status = new APIResponseStatus
                        {
                            IsSuccessful = false,
                            Message = new APIResponseMessage
                            {
                                FriendlyMessage = $"Unable to push supplier with status '{enumName.ToString()}' for approvals"
                            }
                        }
                    });
                }
                var user = await _serverRequest.UserDataAsync();

                using (var _transaction = await _dataContext.Database.BeginTransactionAsync())
                {
                    try
                    {
                        var targetList = new List <int>();
                        targetList.Add(supplierInfor.SupplierId);
                        GoForApprovalRequest wfRequest = new GoForApprovalRequest
                        {
                            Comment                = "Supplier Registration",
                            OperationId            = (int)OperationsEnum.SupplierRegistrationApproval,
                            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)
                        {
                            new SupplierRegRespObj
                            {
                                Status = new APIResponseStatus
                                {
                                    IsSuccessful = false,
                                    Message      = new APIResponseMessage {
                                        FriendlyMessage = $"{result.ReasonPhrase} {result.StatusCode}"
                                    }
                                }
                            };
                        }
                        var stringData = await result.Content.ReadAsStringAsync();

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

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

                            await _transaction.CommitAsync();

                            return(new SupplierRegRespObj
                            {
                                SupplierId = supplierInfor.SupplierId,
                                Status = new APIResponseStatus
                                {
                                    IsSuccessful = res.Status.IsSuccessful,
                                    Message = res.Status.Message
                                }
                            });
                        }

                        if (res.EnableWorkflow || !res.HasWorkflowAccess)
                        {
                            supplierInfor.ApprovalStatusId = (int)ApprovalStatus.Processing;
                            await _repo.UpdateSupplierAsync(supplierInfor);

                            await _transaction.RollbackAsync();

                            return(new SupplierRegRespObj
                            {
                                Status = new APIResponseStatus
                                {
                                    IsSuccessful = res.Status.IsSuccessful,
                                    Message = res.Status.Message
                                }
                            });
                        }
                        if (!res.EnableWorkflow)
                        {
                            supplierInfor.ApprovalStatusId = (int)ApprovalStatus.Approved;
                            supplierInfor.SupplierNumber   = SupplierNumber.Generate(15);
                            await _repo.UpdateSupplierAsync(supplierInfor);

                            await _transaction.CommitAsync();

                            return(new SupplierRegRespObj
                            {
                                Status = new APIResponseStatus
                                {
                                    IsSuccessful = true,
                                    Message = new APIResponseMessage {
                                        FriendlyMessage = "Successful"
                                    }
                                }
                            });
                        }
                        return(new SupplierRegRespObj
                        {
                            Status = new APIResponseStatus
                            {
                                IsSuccessful = res.Status.IsSuccessful,
                                Message = res.Status.Message
                            }
                        });
                    }
                    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}");
                        return(new SupplierRegRespObj
                        {
                            Status = new APIResponseStatus
                            {
                                Message = new APIResponseMessage
                                {
                                    FriendlyMessage = "Error occured!! Please try again later",
                                    MessageId = errorCode,
                                    TechnicalMessage = $"ErrorID : {errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}"
                                }
                            }
                        });

                        #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 SupplierRegRespObj
                {
                    Status = new APIResponseStatus
                    {
                        Message = new APIResponseMessage
                        {
                            FriendlyMessage = "Error occured!! Please try again later",
                            MessageId = errorCode,
                            TechnicalMessage = $"ErrorID : {errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}"
                        }
                    }
                });

                #endregion
            }
        }
Example #22
0
        public async Task <StaffApprovalRegRespObj> Handle(SupplierStaffApprovalCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var apiResponse = new StaffApprovalRegRespObj {
                    Status = new APIResponseStatus {
                        IsSuccessful = false, Message = new APIResponseMessage()
                    }
                };

                if (request.ApprovalStatus == (int)ApprovalStatus.Revert && request.ReferredStaffId < 1)
                {
                    apiResponse.Status.Message.FriendlyMessage = "Please select staff to revert to";
                    return(apiResponse);
                }

                var currentUserId = _accessor.HttpContext.User?.FindFirst(x => x.Type == "userId").Value;
                var user          = await _serverRequest.UserDataAsync();

                var supplier = await _repo.GetSupplierAsync(request.TargetId);

                var detail = BuildApprovalDetailObject(request, supplier, user.StaffId);

                var req = new IndentityServerApprovalCommand
                {
                    ApprovalComment = request.ApprovalComment,
                    ApprovalStatus  = request.ApprovalStatus,
                    TargetId        = request.TargetId,
                    WorkflowToken   = supplier.WorkflowToken,
                    ReferredStaffId = request.ReferredStaffId
                };

                var result = await _serverRequest.StaffApprovalRequestAsync(req);

                if (!result.IsSuccessStatusCode)
                {
                    apiResponse.Status.Message.FriendlyMessage = result.ReasonPhrase;
                    return(apiResponse);
                }

                var stringData = await result.Content.ReadAsStringAsync();

                response = JsonConvert.DeserializeObject <StaffApprovalRegRespObj>(stringData);

                if (!response.Status.IsSuccessful)
                {
                    apiResponse.Status = response.Status;
                    return(apiResponse);
                }

                if (response.ResponseId == (int)ApprovalStatus.Processing)
                {
                    await _detailService.AddUpdateApprovalDetailsAsync(detail);

                    supplier.ApprovalStatusId = (int)ApprovalStatus.Processing;
                    await _repo.UpdateSupplierAsync(supplier);

                    apiResponse.ResponseId          = (int)ApprovalStatus.Processing;
                    apiResponse.Status.IsSuccessful = true;
                    apiResponse.Status.Message      = response.Status.Message;
                    return(apiResponse);
                }

                if (response.ResponseId == (int)ApprovalStatus.Revert)
                {
                    await _detailService.AddUpdateApprovalDetailsAsync(detail);

                    supplier.ApprovalStatusId = (int)ApprovalStatus.Revert;
                    await _repo.UpdateSupplierAsync(supplier);

                    apiResponse.ResponseId          = (int)ApprovalStatus.Revert;
                    apiResponse.Status.IsSuccessful = true;
                    apiResponse.Status.Message      = response.Status.Message;
                    return(apiResponse);
                }

                if (response.ResponseId == (int)ApprovalStatus.Approved)
                {
                    await _detailService.AddUpdateApprovalDetailsAsync(detail);

                    supplier.ApprovalStatusId = (int)ApprovalStatus.Approved;
                    supplier.SupplierNumber   = SupplierNumber.Generate(10);
                    await _repo.UpdateSupplierAsync(supplier);


                    apiResponse.ResponseId          = (int)ApprovalStatus.Approved;
                    apiResponse.Status.IsSuccessful = true;
                    apiResponse.Status.Message      = response.Status.Message;
                    return(apiResponse);
                }

                if (response.ResponseId == (int)ApprovalStatus.Disapproved)
                {
                    await _detailService.AddUpdateApprovalDetailsAsync(detail);

                    supplier.ApprovalStatusId = (int)ApprovalStatus.Disapproved;
                    await _repo.UpdateSupplierAsync(supplier);

                    apiResponse.ResponseId          = (int)ApprovalStatus.Disapproved;
                    apiResponse.Status.IsSuccessful = true;
                    apiResponse.Status.Message      = response.Status.Message;
                    return(apiResponse);
                }

                apiResponse.ResponseId = detail.ApprovalDetailId;
                apiResponse.Status     = response.Status;
                return(apiResponse);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
            public async Task <PaymentTermsRegRespObj> Handle(SendPaymentInvoiceToApprovalCommand request, CancellationToken cancellationToken)
            {
                var apiResponse = new PaymentTermsRegRespObj {
                    Status = new APIResponseStatus {
                        IsSuccessful = false, Message = new APIResponseMessage()
                    }
                };

                try
                {
                    var paymentprop = await _repo.GetSinglePaymenttermAsync(request.PaymentTermId);

                    if (paymentprop == null)
                    {
                        apiResponse.Status.Message.FriendlyMessage = $"Proposal Not found";
                        return(apiResponse);
                    }
                    if (paymentprop.PaymentStatus == (int)PaymentStatus.Paid)
                    {
                        apiResponse.Status.Message.FriendlyMessage = "Payment already made for this phase";
                        return(apiResponse);
                    }
                    if (paymentprop.ApprovalStatusId == (int)ApprovalStatus.Processing)
                    {
                        apiResponse.Status.Message.FriendlyMessage = "Payment In Process";
                        return(apiResponse);
                    }
                    var invoice = await _invoice.GetInvoiceByPhaseAsync(paymentprop.PaymentTermId);

                    if (invoice == null)
                    {
                        apiResponse.Status.Message.FriendlyMessage = "Invoice not found";
                        return(apiResponse);
                    }

                    if (invoice.ApprovalStatusId != (int)ApprovalStatus.Approved)
                    {
                        if (invoice.ApprovalStatusId != (int)ApprovalStatus.Pending)
                        {
                            apiResponse.Status.Message.FriendlyMessage = $"Unable to push invoice with status '{Convert.ToString((ApprovalStatus)invoice.ApprovalStatusId)}' for approval";
                            return(apiResponse);
                        }
                    }
                    var companies = await _serverRequest.GetAllCompanyStructureAsync();

                    var currentCompanyCurrency = companies.companyStructures.FirstOrDefault(q => q.CompanyStructureId == invoice.CompanyId);
                    if (currentCompanyCurrency == null)
                    {
                        apiResponse.Status.Message.FriendlyMessage = "Unable to Identify Company";
                        return(apiResponse);
                    }
                    invoice.CurrencyId = currentCompanyCurrency.ReportCurrencyId ?? 0;

                    invoice.PaymentBankId  = request.PaymentBankId;
                    invoice.SupplierBankId = request.SupplierBankId;
                    var user = await _serverRequest.UserDataAsync();

                    using (var _transaction = await _dataContext.Database.BeginTransactionAsync())
                    {
                        try
                        {
                            var targetList = new List <int>();
                            targetList.Add(invoice.InvoiceId);
                            GoForApprovalRequest wfRequest = new GoForApprovalRequest
                            {
                                Comment                = "Invoice Payment Phase",
                                OperationId            = (int)OperationsEnum.PaymentApproval,
                                TargetId               = targetList,
                                ApprovalStatus         = (int)ApprovalStatus.Pending,
                                DeferredExecution      = true,
                                StaffId                = user.StaffId,
                                CompanyId              = user.CompanyId,
                                EmailNotification      = true,
                                ExternalInitialization = false,
                                StatusId               = (int)ApprovalStatus.Processing,
                            };

                            var result = await _serverRequest.GotForApprovalAsync(wfRequest);

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

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

                            if (res.ApprovalProcessStarted)
                            {
                                invoice.ApprovalStatusId     = (int)ApprovalStatus.Processing;
                                invoice.WorkflowToken        = res.Status.CustomToken;
                                paymentprop.ApprovalStatusId = (int)ApprovalStatus.Processing;
                                await _repo.AddUpdatePaymentTermsAsync(paymentprop);

                                await _invoice.CreateUpdateInvoiceAsync(invoice);

                                await _transaction.CommitAsync();

                                apiResponse.PaymentTermId = invoice.PaymentTermId;
                                apiResponse.Status        = res.Status;
                                return(apiResponse);
                            }

                            if (res.EnableWorkflow || !res.HasWorkflowAccess)
                            {
                                await _transaction.RollbackAsync();

                                apiResponse.Status.Message = res.Status.Message;
                                return(apiResponse);
                            }

                            if (!res.EnableWorkflow)
                            {
                                invoice.ApprovalStatusId = (int)ApprovalStatus.Approved;

                                var thisInvoicePhase = await _repo.GetSinglePaymenttermAsync(invoice.PaymentTermId);

                                thisInvoicePhase.PaymentStatus    = (int)PaymentStatus.Paid;
                                thisInvoicePhase.CompletionDate   = DateTime.Now;
                                thisInvoicePhase.ApprovalStatusId = (int)ApprovalStatus.Approved;

                                var paymentResp = await _invoice.TransferPaymentAsync(invoice);

                                if (!paymentResp.Status.IsSuccessful)
                                {
                                    await _transaction.RollbackAsync();

                                    apiResponse.Status.IsSuccessful            = false;
                                    apiResponse.Status.Message.FriendlyMessage = paymentResp.Status.Message.FriendlyMessage;
                                    return(apiResponse);
                                }
                                await _repo.AddUpdatePaymentTermsAsync(thisInvoicePhase);

                                invoice.AmountPaid = invoice.Amount;
                                await _invoice.CreateUpdateInvoiceAsync(invoice);

                                var entryRequest = _invoice.BuildSupplierSecondEntryRequestObject(invoice);
                                var entry        = await _financeServer.PassEntryAsync(entryRequest);

                                if (!entry.Status.IsSuccessful)
                                {
                                    await _transaction.RollbackAsync();

                                    apiResponse.Status.IsSuccessful            = false;
                                    apiResponse.Status.Message.FriendlyMessage = $"{entry.Status.Message.FriendlyMessage}";
                                    return(apiResponse);
                                }
                                await _repo.SendEmailToSupplierDetailingPaymentAsync(invoice, thisInvoicePhase.Phase);

                                await _transaction.CommitAsync();

                                apiResponse.Status.IsSuccessful            = true;
                                apiResponse.Status.Message.FriendlyMessage = $"Payment Successful";
                                return(apiResponse);
                            }
                            apiResponse.Status = res.Status;
                            return(apiResponse);
                        }
                        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}");
                            return(new PaymentTermsRegRespObj
                            {
                                Status = new APIResponseStatus
                                {
                                    Message = new APIResponseMessage
                                    {
                                        FriendlyMessage = "Error occured!! Please try again later",
                                        MessageId = errorCode,
                                        TechnicalMessage = $"ErrorID : {errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}"
                                    }
                                }
                            });

                            #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
                        {
                            Message = new APIResponseMessage
                            {
                                FriendlyMessage = "Error occured!! Please try again later",
                                MessageId = errorCode,
                                TechnicalMessage = $"ErrorID : {errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}"
                            }
                        }
                    });

                    #endregion
                }
            }
Example #24
0
        public async Task <ActionResult <ApprovalRegRespObj> > GoForApproval([FromBody] ApprovalObj entity)
        {
            try
            {
                using (var _trans = _dataContext.Database.BeginTransaction())
                {
                    try
                    {
                        var currentUserId = _httpContextAccessor.HttpContext.User?.FindFirst(x => x.Type == "userId").Value;
                        var user          = await _serverRequest.UserDataAsync();

                        var loanApplication = _dataContext.credit_loanapplication.Find(entity.TargetId);


                        var req = new IndentityServerApprovalCommand
                        {
                            ApprovalComment = entity.Comment,
                            ApprovalStatus  = entity.ApprovalStatusId,
                            TargetId        = entity.TargetId,
                            WorkflowToken   = loanApplication.WorkflowToken,
                            ReferredStaffId = entity.ReferredStaffId
                        };

                        var previousDetails = _dataContext.cor_approvaldetail.Where(x => x.WorkflowToken.Contains(loanApplication.WorkflowToken) && x.TargetId == entity.TargetId).ToList();
                        var lastDate        = loanApplication.CreatedOn;
                        if (previousDetails.Count() > 0)
                        {
                            lastDate = previousDetails.OrderByDescending(x => x.ApprovalDetailId).FirstOrDefault().Date;
                        }
                        var details = new cor_approvaldetail
                        {
                            Comment       = entity.Comment,
                            Date          = DateTime.Now,
                            ArrivalDate   = previousDetails.Count() > 0 ? lastDate : loanApplication.CreatedOn,
                            StatusId      = entity.ApprovalStatusId,
                            TargetId      = entity.TargetId,
                            StaffId       = user.StaffId,
                            WorkflowToken = loanApplication.WorkflowToken
                        };

                        var result = await _serverRequest.StaffApprovalRequestAsync(req);

                        if (!result.IsSuccessStatusCode)
                        {
                            return(new ApprovalRegRespObj
                            {
                                Status = new APIResponseStatus
                                {
                                    Message = new APIResponseMessage {
                                        FriendlyMessage = result.ReasonPhrase
                                    }
                                }
                            });
                        }

                        var stringData = await result.Content.ReadAsStringAsync();

                        var response = JsonConvert.DeserializeObject <ApprovalRegRespObj>(stringData);

                        if (!response.Status.IsSuccessful)
                        {
                            return(new ApprovalRegRespObj
                            {
                                Status = response.Status
                            });
                        }

                        if (response.ResponseId == (int)ApprovalStatus.Processing)
                        {
                            loanApplication.ApprovalStatusId = (int)ApprovalStatus.Processing;
                            await _dataContext.cor_approvaldetail.AddAsync(details);

                            await _dataContext.SaveChangesAsync();

                            _trans.Commit();
                            return(new ApprovalRegRespObj
                            {
                                ResponseId = (int)ApprovalStatus.Processing,
                                Status = new APIResponseStatus {
                                    IsSuccessful = true, Message = response.Status.Message
                                }
                            });
                        }


                        if (response.ResponseId == (int)ApprovalStatus.Revert)
                        {
                            loanApplication.ApprovalStatusId = (int)ApprovalStatus.Revert;
                            await _dataContext.cor_approvaldetail.AddAsync(details);

                            await _dataContext.SaveChangesAsync();

                            _trans.Commit();
                            return(new ApprovalRegRespObj
                            {
                                ResponseId = (int)ApprovalStatus.Revert,
                                Status = new APIResponseStatus {
                                    IsSuccessful = true, Message = response.Status.Message
                                }
                            });
                        }

                        if (response.ResponseId == (int)ApprovalStatus.Approved)
                        {
                            loanApplication.ApprovalStatusId = (int)ApprovalStatus.Approved;
                            var appicationResponse = _repo.LoanApplicationApproval(entity.TargetId, (short)entity.ApprovalStatusId);

                            if (appicationResponse.loanPayment != null && appicationResponse.AnyIdentifier > 0)
                            {
                                await _schedule.AddTempLoanApplicationSchedule(appicationResponse.AnyIdentifier, appicationResponse.loanPayment);
                            }
                            await _dataContext.cor_approvaldetail.AddAsync(details);

                            await _dataContext.SaveChangesAsync();

                            _trans.Commit();
                            return(new ApprovalRegRespObj
                            {
                                ResponseId = (int)ApprovalStatus.Approved,
                                Status = new APIResponseStatus {
                                    IsSuccessful = true, Message = response.Status.Message
                                }
                            });
                        }

                        if (response.ResponseId == (int)ApprovalStatus.Disapproved)
                        {
                            loanApplication.ApprovalStatusId = (int)ApprovalStatus.Disapproved;
                            await _dataContext.cor_approvaldetail.AddAsync(details);

                            await _dataContext.SaveChangesAsync();

                            _trans.Commit();
                            return(new ApprovalRegRespObj
                            {
                                ResponseId = (int)ApprovalStatus.Disapproved,
                                Status = new APIResponseStatus {
                                    IsSuccessful = true, Message = response.Status.Message
                                }
                            });
                        }


                        return(new ApprovalRegRespObj
                        {
                            Status = response.Status
                        });
                    }
                    catch (SqlException ex)
                    {
                        _trans.Rollback();
                        throw;
                    }
                    finally { _trans.Dispose(); }
                }
            }
            catch (Exception ex)
            {
                var errorCode = ErrorID.Generate(5);
                _logger.Error($"ErrorID : {errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}");
                return(new ApprovalRegRespObj
                {
                    Status = new APIResponseStatus {
                        IsSuccessful = false, Message = new APIResponseMessage {
                            FriendlyMessage = "Error Occurred", TechnicalMessage = ex?.Message, MessageId = errorCode
                        }
                    }
                });
            }
        }
Example #25
0
            public async Task <PaymentTermsRegRespObj> Handle(UpdatePaymentProposalCommand 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);
                    }
                    using (var tran = await _dataContext.Database.BeginTransactionAsync())
                    {
                        try
                        {
                            var phase = await _repo.GetSinglePaymenttermAsync(request.PaymentTermId);

                            if (phase != null)
                            {
                                if (phase.Status == (int)JobProgressStatus.Executed_Successfully)
                                {
                                    response.Status.Message.FriendlyMessage = "This Phase has already been Executed succesfully";
                                    return(response);
                                }
                                if (phase.PaymentStatus == (int)PaymentStatus.Paid)
                                {
                                    response.Status.Message.FriendlyMessage = "Payment already made for this phase";
                                    return(response);
                                }
                                var file = _accessor.HttpContext.Request.Form.Files;


                                if (file.Count() > 0)
                                {
                                    if (file[0].FileName.Split('.').Length > 2)
                                    {
                                        response.Status.Message.FriendlyMessage = "Invalid Character detected in file Name";
                                        return(response);
                                    }

                                    var folderName = Path.Combine("Resources", "Images");
                                    var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);
                                    var fileName   = $"{file[0].FileName}-{DateTime.Now.Day.ToString()}-{DateTime.Now.Millisecond.ToString()}-{DateTime.Now.Year.ToString()}-{DateTime.Now.Year.ToString()}"; //ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"') + date.ToString();
                                    var type       = file[0].ContentType;                                                                                                                                     //ContentDispositionHeaderValue.Parse(file.ContentDisposition).DispositionType.Trim('"');

                                    var fullPath = _env.WebRootPath + "/Resources/" + fileName;
                                    var dbPath   = _env.WebRootPath + "/Resources/" + fileName;

                                    using (FileStream filestrem = System.IO.File.Create(fullPath))
                                    {
                                        await file[0].CopyToAsync(filestrem);
                                        await filestrem.FlushAsync();
                                    }

                                    phase.CcompletionCertificateFullPath = fullPath;
                                    phase.CcompletionCertificateName     = fileName;
                                    phase.CcompletionCertificatePath     = dbPath;
                                    phase.CcompletionCertificateType     = type;
                                }

                                phase.Status           = request.JobStatus;
                                phase.PaymentStatus    = (int)PaymentStatus.Not_Paid;
                                phase.EntryDate        = DateTime.Now;
                                phase.InvoiceGenerated = true;
                                await _repo.AddUpdatePaymentTermsAsync(phase);
                            }


                            var currentbidProposals = _dataContext.cor_paymentterms.Where(q => q.BidAndTenderId == phase.BidAndTenderId && q.ProposedBy == (int)Proposer.STAFF).ToList();
                            if (currentbidProposals.Count() > 0)
                            {
                                var thisBidLpo = _dataContext.purch_plpo.FirstOrDefault(q => q.PLPOId == phase.LPOId);
                                var completed  = currentbidProposals.All(q => q.Status == (int)JobProgressStatus.Executed_Successfully);
                                if (completed)
                                {
                                    thisBidLpo.JobStatus = (int)JobProgressStatus.Executed_Successfully;
                                }
                                else
                                {
                                    thisBidLpo.JobStatus = (int)JobProgressStatus.In_Progress;
                                }

                                var cancelled = currentbidProposals.All(q => q.Status == (int)JobProgressStatus.Cancelled);
                                if (cancelled)
                                {
                                    thisBidLpo.JobStatus = (int)JobProgressStatus.Cancelled;
                                }
                                await _repo.AddUpdateLPOAsync(thisBidLpo);
                            }

                            if (phase.Status == (int)JobProgressStatus.Executed_Successfully)
                            {
                                var thisPhaseLPO = await _repo.GetLPOsAsync(phase.LPOId);

                                if (thisPhaseLPO != null)
                                {
                                    var invoice = BuildInvoiceDomainObject(phase, thisPhaseLPO, user);

                                    var entryRequest1 = _invoice.BuildSupplierFirstEntryRequestObject(phase, invoice);
                                    var phaseEntry    = await _financeServer.PassEntryAsync(entryRequest1);

                                    if (!phaseEntry.Status.IsSuccessful)
                                    {
                                        await tran.RollbackAsync();

                                        response.Status.IsSuccessful            = true;
                                        response.Status.Message.FriendlyMessage = $"Proposal Entry Error Occurred Process Rolled Back:  <br/>{phaseEntry.Status.Message.FriendlyMessage}";
                                        return(response);
                                    }
                                    invoice.CreditGl           = entryRequest1.CreditGL;
                                    invoice.DebitGl            = entryRequest1.DebitGL;
                                    thisPhaseLPO.DateCompleted = DateTime.UtcNow;
                                    await _repo.AddUpdateLPOAsync(thisPhaseLPO);

                                    await _invoice.CreateUpdateInvoiceAsync(invoice);
                                }
                            }
                            await tran.CommitAsync();

                            response.Status.IsSuccessful            = true;
                            response.Status.Message.FriendlyMessage = "Successful";
                            return(response);
                        }
                        catch (Exception ex)
                        {
                            await tran.RollbackAsync();

                            _logger.Error($"Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}");
                            response.Status.IsSuccessful             = false;
                            response.Status.Message.FriendlyMessage  = "Could not process request";
                            response.Status.Message.TechnicalMessage = ex.Message;
                            return(response);
                        }
                        finally { await tran.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
                }
            }
        public async Task <Deposit_bankClosureSetupRegRespObj> Handle(AddUpdateBankClosureSetupCommand request, CancellationToken cancellationToken)
        {
            try
            {
                deposit_bankclosuresetup currentItem = null;
                if (request.BankClosureSetupId > 0)
                {
                    currentItem = _repo.GetBankClosureSetup(request.BankClosureSetupId);
                    if (currentItem != null)
                    {
                        if (request.ChargeType.Trim().ToLower() == currentItem.ChargeType.Trim().ToLower())
                        {
                            return(new Deposit_bankClosureSetupRegRespObj
                            {
                                Status = new APIResponseStatus
                                {
                                    IsSuccessful = false,
                                    Message = new APIResponseMessage
                                    {
                                        FriendlyMessage = "This item already exists",
                                    }
                                }
                            });
                        }
                    }
                }



                var user = await _serverRequest.UserDataAsync();

                var bankClosureSetup = new deposit_bankclosuresetup
                {
                    BankClosureSetupId      = request.BankClosureSetupId,
                    Structure               = request.Structure,
                    ProductId               = request.ProductId,
                    ClosureChargeApplicable = request.ClosureChargeApplicable,
                    SettlementBalance       = request.SettlementBalance,
                    PresetChart             = request.PresetChart,
                    Active    = true,
                    Deleted   = false,
                    CreatedBy = user.UserName,
                    CreatedOn = DateTime.Now,
                };
                if (request.BankClosureSetupId > 0)
                {
                    bankClosureSetup.UpdatedBy = user.UserName;
                    bankClosureSetup.UpdatedOn = DateTime.Now;
                    bankClosureSetup.CreatedBy = currentItem.CreatedBy;
                    bankClosureSetup.CreatedOn = currentItem.CreatedOn;
                }
                var isDone      = _repo.AddUpdateBankClosureSetup(bankClosureSetup);
                var actionTaken = request.BankClosureSetupId > 0 ? "updated" : "added";
                if (isDone)
                {
                    return(new Deposit_bankClosureSetupRegRespObj
                    {
                        Status = new APIResponseStatus
                        {
                            IsSuccessful = false,
                            Message = new APIResponseMessage
                            {
                                FriendlyMessage = $"Successfully {actionTaken}",
                            }
                        }
                    });
                }
                return(new Deposit_bankClosureSetupRegRespObj
                {
                    Status = new APIResponseStatus
                    {
                        IsSuccessful = false,
                        Message = new APIResponseMessage
                        {
                            FriendlyMessage = "Could not process request",
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                #region Log error to file
                var errorCode = ErrorID.Generate(4);
                _logger.Error($"ErrorID : AddUpdateBankClosureSetupCommandHandler{errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}");
                return(new Deposit_bankClosureSetupRegRespObj
                {
                    Status = new APIResponseStatus
                    {
                        IsSuccessful = false,
                        Message = new APIResponseMessage
                        {
                            FriendlyMessage = "Error occured!! Unable to process item",
                            MessageId = errorCode,
                            TechnicalMessage = $"ErrorID : AddUpdateBankClosureSetupCommandHandler{errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}"
                        }
                    }
                });

                #endregion ;
            }
        }
        public async Task <StaffApprovalRegRespObj> Handle(LPOStaffApprovalCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var apiResponse = new StaffApprovalRegRespObj {
                    Status = new APIResponseStatus {
                        IsSuccessful = false, Message = new APIResponseMessage()
                    }
                };
                if (request.ApprovalStatus == (int)ApprovalStatus.Revert && request.ReferredStaffId < 1)
                {
                    return(new StaffApprovalRegRespObj
                    {
                        Status = new APIResponseStatus {
                            IsSuccessful = false, Message = new APIResponseMessage {
                                FriendlyMessage = "Please select staff to revert to"
                            }
                        }
                    });
                }

                var currentUserId = _accessor.HttpContext.User?.FindFirst(x => x.Type == "userId").Value;
                var user          = await _serverRequest.UserDataAsync();

                var currentLPO = await _repo.GetLPOsAsync(request.TargetId);

                List <cor_paymentterms> paymentTerms = await _repo.GetPaymenttermsAsync();

                var detail = BuildApprovalDetailObject(request, currentLPO, user.StaffId);

                var req = new IndentityServerApprovalCommand
                {
                    ApprovalComment = request.ApprovalComment,
                    ApprovalStatus  = request.ApprovalStatus,
                    TargetId        = request.TargetId,
                    WorkflowToken   = currentLPO.WorkflowToken,
                    ReferredStaffId = request.ReferredStaffId
                };

                using (var _trans = await _dataContext.Database.BeginTransactionAsync())
                {
                    try
                    {
                        var result = await _serverRequest.StaffApprovalRequestAsync(req);

                        if (!result.IsSuccessStatusCode)
                        {
                            response.Status.Message.FriendlyMessage = result.ReasonPhrase.ToString();
                            return(apiResponse);
                        }

                        var stringData = await result.Content.ReadAsStringAsync();

                        response = JsonConvert.DeserializeObject <StaffApprovalRegRespObj>(stringData);

                        if (!response.Status.IsSuccessful)
                        {
                            apiResponse.Status = response.Status;
                            return(apiResponse);
                        }
                        if (response.ResponseId == (int)ApprovalStatus.Processing)
                        {
                            await _detailService.AddUpdateApprovalDetailsAsync(detail);

                            currentLPO.ApprovalStatusId = (int)ApprovalStatus.Processing;
                            await _repo.AddUpdateLPOAsync(currentLPO);

                            await _trans.CommitAsync();

                            apiResponse.Status = response.Status;
                            apiResponse.Status.IsSuccessful = true;
                            return(apiResponse);
                        }
                        if (response.ResponseId == (int)ApprovalStatus.Revert)
                        {
                            await _detailService.AddUpdateApprovalDetailsAsync(detail);

                            currentLPO.ApprovalStatusId = (int)ApprovalStatus.Revert;
                            await _repo.AddUpdateLPOAsync(currentLPO);

                            await _trans.CommitAsync();

                            apiResponse.Status = response.Status;
                            return(apiResponse);
                        }
                        if (response.ResponseId == (int)ApprovalStatus.Approved)
                        {
                            await _detailService.AddUpdateApprovalDetailsAsync(detail);

                            currentLPO.ApprovalStatusId = (int)ApprovalStatus.Approved;
                            await _repo.AddUpdateLPOAsync(currentLPO);

                            await _repo.ShareTaxToPhasesIthereIsAsync(currentLPO);

                            await _repo.RemoveLostBidsAndProposals(currentLPO);

                            await _trans.CommitAsync();

                            apiResponse.Status = response.Status;
                            apiResponse.Status.Message.FriendlyMessage = $"Final Approval </br> for this LPO {currentLPO.LPONumber}";
                            return(apiResponse);
                        }
                        if (response.ResponseId == (int)ApprovalStatus.Disapproved)
                        {
                            await _detailService.AddUpdateApprovalDetailsAsync(detail);

                            currentLPO.ApprovalStatusId = (int)ApprovalStatus.Disapproved;
                            await _repo.AddUpdateLPOAsync(currentLPO);

                            await _trans.CommitAsync();

                            apiResponse.Status = response.Status;
                            return(apiResponse);
                        }
                    }
                    catch (Exception ex)
                    {
                        await _trans.RollbackAsync();

                        throw ex;
                    }
                    finally { await _trans.DisposeAsync(); }
                }
                apiResponse.ResponseId = detail.ApprovalDetailId;
                apiResponse.Status     = response.Status;
                return(apiResponse);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
            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
                }
            }
            public async Task <LPORegRespObj> Handle(SendLPOToApprovalCommand request, CancellationToken cancellationToken)
            {
                var apiResponse = new LPORegRespObj {
                    Status = new APIResponseStatus {
                        IsSuccessful = false, Message = new APIResponseMessage()
                    }
                };

                try
                {
                    var LPOObj = await _repo.GetLPOsAsync(request.LPOId);

                    if (LPOObj == null)
                    {
                        apiResponse.Status.Message.FriendlyMessage = $"Bid Not found";
                        return(apiResponse);
                    }
                    var enumName = (ApprovalStatus)LPOObj.ApprovalStatusId;
                    if (LPOObj.ApprovalStatusId != (int)ApprovalStatus.Pending)
                    {
                        apiResponse.Status.Message.FriendlyMessage = $"Unable to push LPO with status '{enumName.ToString()}' for approval";
                        return(apiResponse);
                    }
                    var user = await _serverRequest.UserDataAsync();

                    using (var _transaction = await _dataContext.Database.BeginTransactionAsync())
                    {
                        try
                        {
                            var targetList = new List <int>();
                            targetList.Add(request.LPOId);
                            GoForApprovalRequest wfRequest = new GoForApprovalRequest
                            {
                                Comment                = "LPO",
                                OperationId            = (int)OperationsEnum.PurchaseLPOApproval,
                                TargetId               = targetList,
                                ApprovalStatus         = (int)ApprovalStatus.Pending,
                                DeferredExecution      = true,
                                StaffId                = user.StaffId,
                                CompanyId              = 1,
                                EmailNotification      = true,
                                ExternalInitialization = false,
                                StatusId               = (int)ApprovalStatus.Processing,
                            };

                            var result = await _serverRequest.GotForApprovalAsync(wfRequest);

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

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

                            if (res.ApprovalProcessStarted)
                            {
                                LPOObj.ApprovalStatusId = (int)ApprovalStatus.Processing;
                                LPOObj.WorkflowToken    = res.Status.CustomToken;

                                await _repo.AddUpdateLPOAsync(LPOObj);

                                await _transaction.CommitAsync();

                                apiResponse.PLPOId = LPOObj.PLPOId;
                                apiResponse.Status = res.Status;
                                return(apiResponse);
                            }

                            if (res.EnableWorkflow || !res.HasWorkflowAccess)
                            {
                                await _transaction.RollbackAsync();

                                apiResponse.Status.Message = res.Status.Message;
                                return(apiResponse);
                            }
                            if (!res.EnableWorkflow)
                            {
                                LPOObj.ApprovalStatusId = (int)ApprovalStatus.Approved;
                                await _repo.AddUpdateLPOAsync(LPOObj);

                                await _repo.ShareTaxToPhasesIthereIsAsync(LPOObj);

                                await _transaction.CommitAsync();

                                apiResponse.Status.IsSuccessful            = true;
                                apiResponse.Status.Message.FriendlyMessage = "LPO Updated";
                                return(apiResponse);
                            }
                            apiResponse.Status = res.Status;
                            return(apiResponse);
                        }
                        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}");
                            return(new LPORegRespObj
                            {
                                Status = new APIResponseStatus
                                {
                                    Message = new APIResponseMessage
                                    {
                                        FriendlyMessage = "Error occured!! Please try again later",
                                        MessageId = errorCode,
                                        TechnicalMessage = $"ErrorID : {errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}"
                                    }
                                }
                            });

                            #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 LPORegRespObj
                    {
                        Status = new APIResponseStatus
                        {
                            Message = new APIResponseMessage
                            {
                                FriendlyMessage = "Error occured!! Please try again later",
                                MessageId = errorCode,
                                TechnicalMessage = $"ErrorID : {errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}"
                            }
                        }
                    });

                    #endregion
                }
            }
        public async Task <BidAndTenderRegRespObj> Handle(SendSupplierBidAndTenderToApprovalCommand request, CancellationToken cancellationToken)
        {
            var apiResponse = new BidAndTenderRegRespObj {
                Status = new APIResponseStatus {
                    IsSuccessful = false, Message = new APIResponseMessage()
                }
            };

            try
            {
                var bidAndTenderObj = await _repo.GetBidAndTender(request.BidAndTenderId);

                // IEnumerable<cor_paymentterms> paymentTerms = await _repo.GetPaymenttermsAsync();

                if (bidAndTenderObj == null)
                {
                    apiResponse.Status.Message.FriendlyMessage = $"Bid Not found";
                    return(apiResponse);
                }
                var enumName = (ApprovalStatus)bidAndTenderObj.ApprovalStatusId;
                if (bidAndTenderObj.ApprovalStatusId != (int)ApprovalStatus.Pending)
                {
                    apiResponse.Status.Message.FriendlyMessage = $"Unable to push supplier bid with status '{enumName.ToString()}' for approval";
                    return(apiResponse);
                }

                var _ThisBidLPO = await _repo.GetLPOByNumberAsync(bidAndTenderObj.LPOnumber);

                if (_ThisBidLPO.WinnerSupplierId > 0)
                {
                    apiResponse.Status.Message.FriendlyMessage = $"Supplier already taken for the item associated to this bid";
                    return(apiResponse);
                }

                if (bidAndTenderObj.Paymentterms.Count() > 0 && bidAndTenderObj.Paymentterms.Count(q => q.ProposedBy == (int)Proposer.STAFF) == 0)
                {
                    apiResponse.Status.Message.FriendlyMessage = $"No Payment Plan Found";
                    return(apiResponse);
                }

                var user = await _serverRequest.UserDataAsync();

                IEnumerable <cor_paymentterms> paymentTerms = await _repo.GetPaymenttermsAsync();

                using (var _transaction = await _dataContext.Database.BeginTransactionAsync())
                {
                    try
                    {
                        var targetList = new List <int>();
                        targetList.Add(bidAndTenderObj.BidAndTenderId);
                        GoForApprovalRequest wfRequest = new GoForApprovalRequest
                        {
                            Comment                = "Bid and tender",
                            OperationId            = (int)OperationsEnum.BidAndTenders,
                            TargetId               = targetList,
                            ApprovalStatus         = (int)ApprovalStatus.Pending,
                            DeferredExecution      = true,
                            StaffId                = user.StaffId,
                            CompanyId              = user.CompanyId,
                            EmailNotification      = true,
                            ExternalInitialization = false,
                            StatusId               = (int)ApprovalStatus.Processing,
                        };

                        var result = await _serverRequest.GotForApprovalAsync(wfRequest);

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

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

                        if (res.ApprovalProcessStarted)
                        {
                            bidAndTenderObj.ApprovalStatusId = (int)ApprovalStatus.Processing;
                            bidAndTenderObj.WorkflowToken    = res.Status.CustomToken;
                            // var thisBidPaymentTerms = paymentTerms.Where(d => d.BidAndTenderId == bidAndTenderObj.BidAndTenderId).ToList();
                            ///bidAndTenderObj.Paymentterms = thisBidPaymentTerms;
                            await _repo.AddUpdateBidAndTender(bidAndTenderObj);

                            await _transaction.CommitAsync();

                            apiResponse.BidAndTenderId = bidAndTenderObj.BidAndTenderId;
                            apiResponse.Status         = res.Status;
                            return(apiResponse);
                        }

                        if (res.EnableWorkflow || !res.HasWorkflowAccess)
                        {
                            await _transaction.RollbackAsync();

                            apiResponse.Status.Message = res.Status.Message;
                            return(apiResponse);
                        }
                        if (!res.EnableWorkflow)
                        {
                            bidAndTenderObj.ApprovalStatusId = (int)ApprovalStatus.Approved;
                            bidAndTenderObj.DecisionResult   = (int)DecisionResult.Win;
                            bidAndTenderObj.PLPOId           = _ThisBidLPO.PLPOId;
                            var thisBidPaymentTerms = paymentTerms.Where(d => d.BidAndTenderId == bidAndTenderObj.BidAndTenderId).ToList();
                            bidAndTenderObj.Paymentterms = thisBidPaymentTerms;
                            await _repo.SendEmailToSuppliersSelectedAsync(bidAndTenderObj.SupplierId, bidAndTenderObj.DescriptionOfRequest, _ThisBidLPO.PLPOId);

                            await _repo.AddUpdateBidAndTender(bidAndTenderObj);

                            var terms = paymentTerms.Where(q => q.BidAndTenderId == bidAndTenderObj.BidAndTenderId).ToList();
                            foreach (var term in terms)
                            {
                                term.LPOId     = bidAndTenderObj.PLPOId;
                                term.CompanyId = bidAndTenderObj.CompanyId;
                                await _repo.AddUpdatePaymentTermsAsync(term);
                            }
                            var otherBids = _dataContext.cor_bid_and_tender.Where(q => q.LPOnumber.Trim().ToLower() == bidAndTenderObj.LPOnumber.Trim().ToLower() && q.BidAndTenderId != bidAndTenderObj.BidAndTenderId).ToList();
                            if (otherBids.Count() > 0)
                            {
                                foreach (var otherbid in otherBids)
                                {
                                    otherbid.ApprovalStatusId = (int)ApprovalStatus.Disapproved;
                                    otherbid.DecisionResult   = (int)DecisionResult.Lost;
                                    otherbid.Paymentterms     = _dataContext.cor_paymentterms.Where(q => q.BidAndTenderId == otherbid.BidAndTenderId).ToList();
                                    await _repo.AddUpdateBidAndTender(otherbid);
                                }
                            }
                            var thisBidLpo = _repo.BuildThisBidLPO(_ThisBidLPO, bidAndTenderObj);
                            await _repo.AddUpdateLPOAsync(thisBidLpo);

                            await _transaction.CommitAsync();
                        }
                        apiResponse.Status.IsSuccessful            = true;
                        apiResponse.Status.Message.FriendlyMessage = "LPO Generated";
                        return(apiResponse);
                    }
                    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}");
                        return(new BidAndTenderRegRespObj
                        {
                            Status = new APIResponseStatus
                            {
                                Message = new APIResponseMessage
                                {
                                    FriendlyMessage = "Error occured!! Please try again later",
                                    MessageId = errorCode,
                                    TechnicalMessage = $"ErrorID : {errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}"
                                }
                            }
                        });

                        #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 BidAndTenderRegRespObj
                {
                    Status = new APIResponseStatus
                    {
                        Message = new APIResponseMessage
                        {
                            FriendlyMessage = "Error occured!! Please try again later",
                            MessageId = errorCode,
                            TechnicalMessage = $"ErrorID : {errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}"
                        }
                    }
                });

                #endregion
            }
        }