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
                }
            }
예제 #2
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 <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 <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
            }
        }
        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 <StaffApprovalRegRespObj> Handle(PRNStaffApprovalCommand request, CancellationToken cancellationToken)
        {
            try
            {
                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 allSuppliers = await _dataContext.cor_supplier.ToListAsync();

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

                var prn = await _repo.GetPurchaseRequisitionNoteAsync(request.TargetId);

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

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

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

                        if (!result.IsSuccessStatusCode)
                        {
                            var stringData2 = await result.Content.ReadAsStringAsync();

                            response = JsonConvert.DeserializeObject <StaffApprovalRegRespObj>(stringData2);
                            return(new StaffApprovalRegRespObj
                            {
                                Status = response.Status
                            });
                        }

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

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

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

                            prn.ApprovalStatusId = (int)ApprovalStatus.Processing;
                            await _repo.AddUpdatePurchaseRequisitionNoteAsync(prn);

                            await _trans.CommitAsync();

                            return(new StaffApprovalRegRespObj
                            {
                                ResponseId = (int)ApprovalStatus.Processing,
                                Status = new APIResponseStatus {
                                    IsSuccessful = true, Message = response.Status.Message
                                }
                            });
                        }
                        if (response.ResponseId == (int)ApprovalStatus.Revert)
                        {
                            await _detailService.AddUpdateApprovalDetailsAsync(detail);

                            prn.ApprovalStatusId = (int)ApprovalStatus.Revert;
                            await _repo.AddUpdatePurchaseRequisitionNoteAsync(prn);

                            await _trans.CommitAsync();

                            return(new StaffApprovalRegRespObj
                            {
                                ResponseId = (int)ApprovalStatus.Revert,
                                Status = new APIResponseStatus {
                                    IsSuccessful = true, Message = response.Status.Message
                                }
                            });
                        }
                        if (response.ResponseId == (int)ApprovalStatus.Approved)
                        {
                            await _detailService.AddUpdateApprovalDetailsAsync(detail);

                            prn.ApprovalStatusId = (int)ApprovalStatus.Approved;
                            var prnDetails = await _repo.GetPrnDetailsByPrnId(prn.PurchaseReqNoteId);

                            EmailMessageObj email = new EmailMessageObj {
                                ToAddresses = new List <EmailAddressObj>()
                            };

                            foreach (var item in prnDetails)
                            {
                                item.LPONumber = _repo.LpoNubmer(prn.PurchaseReqNoteId + item.PRNDetailsId);

                                if (await _repo.AddUpdatePrnDetailsAsync(item))
                                {
                                    var lpoObject = _repo.BuildLPODomianObject(item, prn.DeliveryLocation, prn.ExpectedDeliveryDate ?? DateTime.Today);
                                    item.PurchaseReqNoteId = prn.PurchaseReqNoteId;
                                    if (await _repo.AddUpdateLPOAsync(lpoObject))
                                    {
                                        var SuggestedSupplierList = lpoObject.SupplierIds.Split(',').Select(int.Parse);
                                        foreach (var supplierId in SuggestedSupplierList)
                                        {
                                            var supplier = await _supRepo.GetSupplierAsync(supplierId);

                                            if (supplier != null)
                                            {
                                                var bidAndTenderObject = _repo.BuildBidAndTenderDomianObject(supplier, lpoObject, prn.DepartmentId, item);
                                                bidAndTenderObject.CompanyId         = prn.CompanyId;
                                                bidAndTenderObject.PurchaseReqNoteId = prn.PurchaseReqNoteId;
                                                if (await _repo.AddUpdateBidAndTender(bidAndTenderObject))
                                                {
                                                    email.ToAddresses.Add(new EmailAddressObj {
                                                        Address = supplier.Email, Name = supplier.Name
                                                    });
                                                }
                                            }
                                        }
                                        var otherSupplierbid = _repo.BuildBidAndTenderDomianObjectForNonSelectedSuppliers(lpoObject, prn.DepartmentId, item);
                                        await _repo.AddUpdateBidAndTender(otherSupplierbid);
                                    }
                                }
                            }
                            email.ToAddresses.Distinct();
                            await _repo.SendEmailToSuppliersAsync(email, prn.Description);

                            await _repo.AddUpdatePurchaseRequisitionNoteAsync(prn);

                            await _repo.SendEmailToInitiatingStaffAsync(prn);

                            await _trans.CommitAsync();

                            return(new StaffApprovalRegRespObj
                            {
                                ResponseId = (int)ApprovalStatus.Approved,
                                Status = new APIResponseStatus {
                                    IsSuccessful = true, Message = new APIResponseMessage {
                                        FriendlyMessage = "Final Approval </br> Successfully created Supplier Bids"
                                    }
                                }
                            });
                        }
                        if (response.ResponseId == (int)ApprovalStatus.Disapproved)
                        {
                            await _detailService.AddUpdateApprovalDetailsAsync(detail);

                            prn.ApprovalStatusId = (int)ApprovalStatus.Disapproved;
                            await _repo.AddUpdatePurchaseRequisitionNoteAsync(prn);

                            await _trans.CommitAsync();

                            return(new StaffApprovalRegRespObj
                            {
                                ResponseId = (int)ApprovalStatus.Disapproved,
                                Status = new APIResponseStatus {
                                    IsSuccessful = true, Message = response.Status.Message
                                }
                            });
                        }
                    }
                    catch (Exception ex)
                    {
                        await _trans.RollbackAsync();

                        throw ex;
                    }
                    finally { await _trans.DisposeAsync(); }
                }

                return(new StaffApprovalRegRespObj
                {
                    ResponseId = detail.ApprovalDetailId,
                    Status = response.Status
                });
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public async Task <RequisitionNoteRegRespObj> Handle(AddUpdateRequisitionNoteCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var apiResponse = new RequisitionNoteRegRespObj {
                    Status = new APIResponseStatus {
                        IsSuccessful = false, Message = new APIResponseMessage()
                    }
                };
                var user = await _serverRequest.UserDataAsync();

                if (user == null)
                {
                    return(new RequisitionNoteRegRespObj
                    {
                        Status = new APIResponseStatus {
                            IsSuccessful = false, Message = new APIResponseMessage {
                                FriendlyMessage = " Unable To Process This User"
                            }
                        }
                    });
                }

                List <purch_prndetails> prnDetails = new List <purch_prndetails>();
                using (var _trans = await _dataContext.Database.BeginTransactionAsync())
                {
                    try
                    {
                        var prn = _repo.BuildPurchRequisionNoteObject(request, user.StaffId, user.CompanyId);
                        await _repo.AddUpdatePurchaseRequisitionNoteAsync(prn);

                        if (request.PRNDetails.Count() > 0)
                        {
                            prnDetails = _repo.BuildListOfPrnDetails(request.PRNDetails, prn.CompanyId);
                        }
                        var targetList = new List <int>();
                        targetList.Add(prn.PurchaseReqNoteId);
                        GoForApprovalRequest wfRequest = new GoForApprovalRequest
                        {
                            Comment                = "Purchase PRN",
                            OperationId            = (int)OperationsEnum.PurchasePRNApproval,
                            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();

                        var res = JsonConvert.DeserializeObject <GoForApprovalRespObj>(stringData);
                        if (res.ApprovalProcessStarted)
                        {
                            prn.ApprovalStatusId = (int)ApprovalStatus.Processing;
                            prn.WorkflowToken    = res.Status.CustomToken;

                            await _repo.AddUpdatePurchaseRequisitionNoteAsync(prn);

                            foreach (var item in prnDetails)
                            {
                                item.PurchaseReqNoteId = prn.PurchaseReqNoteId;
                                await _repo.AddUpdatePrnDetailsAsync(item);
                            }
                            await _trans.CommitAsync();

                            apiResponse.PurchaseReqNoteId   = prn.PurchaseReqNoteId;
                            apiResponse.Status.IsSuccessful = res.Status.IsSuccessful;
                            apiResponse.Status.Message      = res.Status.Message;
                            return(apiResponse);
                        }

                        if (res.EnableWorkflow || !res.HasWorkflowAccess)
                        {
                            await _trans.CommitAsync();

                            apiResponse.PurchaseReqNoteId              = prn.PurchaseReqNoteId;
                            apiResponse.Status.IsSuccessful            = true;
                            apiResponse.Status.Message.FriendlyMessage = "Successful";
                            return(apiResponse);
                        }
                        if (!res.EnableWorkflow)
                        {
                            prn.ApprovalStatusId = (int)ApprovalStatus.Approved;
                            EmailMessageObj email = new EmailMessageObj {
                                ToAddresses = new List <EmailAddressObj>()
                            };
                            var lponum = 0;
                            foreach (var item in prnDetails)
                            {
                                if (await _repo.AddUpdatePrnDetailsAsync(item))
                                {
                                    item.LPONumber         = _repo.LpoNubmer(prn.PurchaseReqNoteId + item.PRNDetailsId);
                                    item.PurchaseReqNoteId = prn.PurchaseReqNoteId;
                                    await _repo.AddUpdatePrnDetailsAsync(item);

                                    var lpoObject = _repo.BuildLPODomianObject(item, prn.DeliveryLocation, prn.ExpectedDeliveryDate ?? DateTime.Today);
                                    if (await _repo.AddUpdateLPOAsync(lpoObject))
                                    {
                                        var SuggestedSupplierList = lpoObject.SupplierIds.Split(',').Select(int.Parse);
                                        foreach (var supplierId in SuggestedSupplierList)
                                        {
                                            var supplier = await _suprepo.GetSupplierAsync(supplierId);

                                            if (supplier != null)
                                            {
                                                var bidAndTenderObject = _repo.BuildBidAndTenderDomianObject(supplier, lpoObject, prn.DepartmentId, item);
                                                bidAndTenderObject.CompanyId         = prn.CompanyId;
                                                bidAndTenderObject.PurchaseReqNoteId = prn.PurchaseReqNoteId;
                                                if (await _repo.AddUpdateBidAndTender(bidAndTenderObject))
                                                {
                                                    email.ToAddresses.Add(new EmailAddressObj {
                                                        Address = supplier.Email, Name = supplier.Name
                                                    });
                                                }
                                            }
                                        }
                                        var otherSupplierbid = _repo.BuildBidAndTenderDomianObjectForNonSelectedSuppliers(lpoObject, prn.DepartmentId, item);
                                        otherSupplierbid.PurchaseReqNoteId = prn.PurchaseReqNoteId;
                                        otherSupplierbid.CompanyId         = prn.CompanyId;
                                        await _repo.AddUpdateBidAndTender(otherSupplierbid);
                                    }
                                }
                            }
                            email.ToAddresses.Distinct();
                            await _repo.SendEmailToSuppliersAsync(email, prn.Description);

                            await _repo.AddUpdatePurchaseRequisitionNoteAsync(prn);

                            await _trans.CommitAsync();

                            apiResponse.Status.IsSuccessful            = true;
                            apiResponse.Status.Message.FriendlyMessage = "Successful";
                            return(apiResponse);
                        }
                    }
                    catch (SqlException ex)
                    {
                        await _trans.RollbackAsync();

                        var errorCode = ErrorID.Generate(4);
                        _logger.Error($"ErrorID : {errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}");
                        throw ex;
                    }
                    finally { await _trans.DisposeAsync(); }
                }
                return(new RequisitionNoteRegRespObj
                {
                    Status = new APIResponseStatus
                    {
                        IsSuccessful = true,
                        Message = new APIResponseMessage
                        {
                            FriendlyMessage = "Success"
                        }
                    }
                });
            }
            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 RequisitionNoteRegRespObj
                {
                    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(UpdateProposalBySupplierCommand 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);
                    }

                    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()}";
                        var type       = file[0].ContentType;

                        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();
                        }

                        paymentProposal.CcompletionCertificateFullPath = fullPath;
                        paymentProposal.CcompletionCertificateName     = fileName;
                        paymentProposal.CcompletionCertificatePath     = dbPath;
                        paymentProposal.CcompletionCertificateType     = file[0].FileName.Split('.')[1];;
                    }

                    paymentProposal.Status = request.Status;
                    thisphaseLpo.JobStatus = (int)JobProgressStatus.In_Progress;
                    await _repo.AddUpdateLPOAsync(thisphaseLpo);

                    await _repo.AddUpdatePaymentTermsAsync(paymentProposal);

                    await SendEmailToOfficerForPaymentAsync(paymentProposal, thisphaseLpo, request.Status);

                    response.Status.IsSuccessful            = true;
                    response.Status.Message.FriendlyMessage = $"Successfully Updated phase {paymentProposal.Phase}";
                    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
                }
            }
예제 #9
0
        public async Task <StaffApprovalRegRespObj> Handle(BidandTenderStaffApprovalCommand request, CancellationToken cancellationToken)
        {
            try
            {
                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 currentBid = await _repo.GetBidAndTender(request.TargetId);

                if (!Validation(currentBid).Status.IsSuccessful)
                {
                    return(Validation(currentBid));
                }


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

                if (_ThisBidLPO.WinnerSupplierId > 0 && request.ApprovalStatus != (int)ApprovalStatus.Approved)
                {
                    return(new StaffApprovalRegRespObj
                    {
                        Status = new APIResponseStatus {
                            IsSuccessful = false, Message = new APIResponseMessage {
                                FriendlyMessage = $"Supplier already selected for this LPO {currentBid.LPOnumber}"
                            }
                        }
                    });
                }

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

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

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

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

                        if (!result.IsSuccessStatusCode)
                        {
                            return(new StaffApprovalRegRespObj
                            {
                                Status = new APIResponseStatus
                                {
                                    IsSuccessful = false,
                                    Message = new APIResponseMessage {
                                        FriendlyMessage = result.ReasonPhrase
                                    }
                                }
                            });
                        }

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

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

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

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

                            currentBid.ApprovalStatusId = (int)ApprovalStatus.Processing;
                            currentBid.DecisionResult   = (int)DecisionResult.Non_Applicable;

                            var thisBidPaymentTerms = paymentTerms.Where(d => d.BidAndTenderId == currentBid.BidAndTenderId).ToList();
                            currentBid.Paymentterms = thisBidPaymentTerms;

                            await _repo.AddUpdateBidAndTender(currentBid);

                            await _trans.CommitAsync();

                            return(new StaffApprovalRegRespObj
                            {
                                ResponseId = (int)ApprovalStatus.Processing,
                                Status = new APIResponseStatus {
                                    IsSuccessful = true, Message = response.Status.Message
                                }
                            });
                        }
                        if (response.ResponseId == (int)ApprovalStatus.Revert)
                        {
                            await _detailService.AddUpdateApprovalDetailsAsync(detail);

                            currentBid.ApprovalStatusId = (int)ApprovalStatus.Revert;
                            currentBid.DecisionResult   = (int)DecisionResult.Non_Applicable;



                            await _repo.AddUpdateBidAndTender(currentBid);

                            await _trans.CommitAsync();

                            return(new StaffApprovalRegRespObj
                            {
                                ResponseId = (int)ApprovalStatus.Revert,
                                Status = new APIResponseStatus {
                                    IsSuccessful = true, Message = response.Status.Message
                                }
                            });
                        }
                        if (response.ResponseId == (int)ApprovalStatus.Approved)
                        {
                            await _detailService.AddUpdateApprovalDetailsAsync(detail);

                            currentBid.ApprovalStatusId = (int)ApprovalStatus.Approved;
                            currentBid.DecisionResult   = (int)DecisionResult.Win;
                            currentBid.PLPOId           = _ThisBidLPO.PLPOId;
                            var thisBidPaymentTerms = paymentTerms.Where(d => d.BidAndTenderId == currentBid.BidAndTenderId).ToList();
                            currentBid.Paymentterms = thisBidPaymentTerms;
                            await _repo.SendEmailToSuppliersSelectedAsync(currentBid.SupplierId, currentBid.DescriptionOfRequest, _ThisBidLPO.PLPOId);

                            await _repo.AddUpdateBidAndTender(currentBid);

                            var terms = paymentTerms.Where(q => q.BidAndTenderId == currentBid.BidAndTenderId).ToList();
                            foreach (var term in terms)
                            {
                                term.LPOId     = currentBid.PLPOId;
                                term.CompanyId = currentBid.CompanyId;
                                await _repo.AddUpdatePaymentTermsAsync(term);
                            }
                            var otherBids = _dataContext.cor_bid_and_tender.Where(q => q.LPOnumber.Trim().ToLower() == currentBid.LPOnumber.Trim().ToLower() && q.BidAndTenderId != currentBid.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, currentBid);
                            await _repo.AddUpdateLPOAsync(thisBidLpo);

                            await _trans.CommitAsync();

                            return(new StaffApprovalRegRespObj
                            {
                                ResponseId = (int)ApprovalStatus.Approved,
                                Status = new APIResponseStatus {
                                    IsSuccessful = true, Message = new APIResponseMessage {
                                        FriendlyMessage = $"Final Approval </br> Successfully selected Supplier for  {currentBid.LPOnumber}"
                                    }
                                }
                            });
                        }
                        if (response.ResponseId == (int)ApprovalStatus.Disapproved)
                        {
                            await _detailService.AddUpdateApprovalDetailsAsync(detail);

                            _ThisBidLPO.JobStatus       = _ThisBidLPO.JobStatus;
                            currentBid.ApprovalStatusId = (int)ApprovalStatus.Disapproved;
                            currentBid.DecisionResult   = (int)DecisionResult.Lost;
                            await _repo.AddUpdateBidAndTender(currentBid);

                            await _trans.CommitAsync();

                            return(new StaffApprovalRegRespObj
                            {
                                ResponseId = (int)ApprovalStatus.Disapproved,
                                Status = new APIResponseStatus {
                                    IsSuccessful = true, Message = response.Status.Message
                                }
                            });
                        }
                    }
                    catch (Exception ex)
                    {
                        await _trans.RollbackAsync();

                        throw new Exception("Error Occurerd", new Exception($"{ex.Message}"));
                    }
                    finally { await _trans.DisposeAsync(); }
                }

                return(new StaffApprovalRegRespObj
                {
                    ResponseId = detail.ApprovalDetailId,
                    Status = response.Status
                });
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #10
0
            public async Task <LPORegRespObj> Handle(RespondToLPOCommand request, CancellationToken cancellationToken)
            {
                var response = new LPORegRespObj {
                    Status = new APIResponseStatus {
                        IsSuccessful = false, Message = new APIResponseMessage()
                    }
                };

                try
                {
                    var rejectedlpo = _dataContext.purch_plpo.Find(request.LPOId);
                    if (rejectedlpo == null)
                    {
                        response.Status.Message.FriendlyMessage = "Unable to identify this LPO";
                        return(response);
                    }
                    var rejectedLpoBid = await _purchaseService.GetBidAndTender(rejectedlpo.BidAndTenderId);

                    if (rejectedLpoBid == null)
                    {
                        response.Status.Message.FriendlyMessage = "Error Occurred";
                        return(response);
                    }

                    if (request.IsRejected)
                    {
                        using (var _trans = await _dataContext.Database.BeginTransactionAsync())
                        {
                            try
                            {
                                await _purchaseService.SendEmailToSuppliersWhenBidIsRejectedAsync(rejectedlpo.WinnerSupplierId, rejectedlpo.Description);

                                rejectedlpo.ApprovalStatusId = (int)ApprovalStatus.Disapproved;
                                rejectedlpo.WinnerSupplierId = 0;
                                rejectedlpo.Name             = string.Empty;
                                rejectedlpo.BidAndTenderId   = 0;
                                await _purchaseService.AddUpdateLPOAsync(rejectedlpo);


                                if (rejectedLpoBid.Paymentterms.Count() > 0)
                                {
                                    foreach (var term in rejectedLpoBid.Paymentterms)
                                    {
                                        var item = await _dataContext.cor_paymentterms.FindAsync(term.PaymentTermId);

                                        if (item != null)
                                        {
                                            item.LPOId            = 0;
                                            item.ApprovalStatusId = (int)ApprovalStatus.Disapproved;
                                        }
                                        await _purchaseService.AddUpdatePaymentTermsAsync(item);
                                    }
                                }
                                rejectedLpoBid.IsRejected       = true;
                                rejectedLpoBid.PLPOId           = 0;
                                rejectedLpoBid.ApprovalStatusId = (int)ApprovalStatus.Disapproved;
                                await _purchaseService.AddUpdateBidAndTender(rejectedLpoBid);

                                var lostBids = await _dataContext.cor_bid_and_tender.Where(q => q.PLPOId == request.LPOId && q.BidAndTenderId != rejectedLpoBid.BidAndTenderId).ToListAsync();

                                if (lostBids.Count() > 0)
                                {
                                    foreach (var otherbid in lostBids)
                                    {
                                        var item = await _purchaseService.GetBidAndTender(otherbid.BidAndTenderId);

                                        if (item != null)
                                        {
                                            item.ApprovalStatusId = (int)ApprovalStatus.Pending;
                                            item.DecisionResult   = (int)DecisionResult.Non_Applicable;
                                            var terms = await _dataContext.cor_paymentterms.Where(q => q.BidAndTenderId == item.BidAndTenderId).ToListAsync();

                                            item.Paymentterms = terms;
                                        }
                                        await _purchaseService.AddUpdateBidAndTender(item);
                                    }
                                }
                                await _trans.CommitAsync();

                                response.Status.IsSuccessful            = true;
                                response.Status.Message.FriendlyMessage = "Successfully rejected LPO";
                                return(response);
                            }
                            catch (Exception ex)
                            {
                                await _trans.RollbackAsync();
                            }
                            finally { await _trans.DisposeAsync(); }
                        }
                    }
                    return(response);
                }
                catch (Exception ex)
                {
                    response.Status.Message.FriendlyMessage = ex.Message;
                    return(response);
                }
            }