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 <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 <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
                }
            }
예제 #4
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
            }
        }
        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
            }
        }