Beispiel #1
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(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
                }
            }
        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 <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
                }
            }
Beispiel #5
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;
            }
        }
        public async Task <StaffApprovalRegRespObj> Handle(PaymentRequestStaffApprovalCommand 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 currentInvoice = await _invoice.GetInvoiceAsync(request.TargetId);

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

                var req = new IndentityServerApprovalCommand
                {
                    ApprovalComment = request.ApprovalComment,
                    ApprovalStatus  = request.ApprovalStatus,
                    TargetId        = request.TargetId,
                    WorkflowToken   = currentInvoice.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)
                        {
                            apiResponse.Status = response.Status;
                            return(apiResponse);
                        }
                        if (response.ResponseId == (int)ApprovalStatus.Processing)
                        {
                            await _detailService.AddUpdateApprovalDetailsAsync(detail);

                            currentInvoice.ApprovalStatusId = (int)ApprovalStatus.Processing;
                            await _invoice.CreateUpdateInvoiceAsync(currentInvoice);

                            await _trans.CommitAsync();

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

                            currentInvoice.ApprovalStatusId = (int)ApprovalStatus.Revert;
                            await _invoice.CreateUpdateInvoiceAsync(currentInvoice);

                            await _trans.CommitAsync();

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

                            currentInvoice.ApprovalStatusId = (int)ApprovalStatus.Approved;

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

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

                            currentInvoice.AmountPaid       = currentInvoice.Amount;
                            currentInvoice.ApprovalStatusId = (int)ApprovalStatus.Approved;
                            await _invoice.CreateUpdateInvoiceAsync(currentInvoice);

                            var paymentResp = await _invoice.TransferPaymentAsync(currentInvoice);

                            if (!paymentResp.Status.IsSuccessful)
                            {
                                await _trans.CommitAsync();

                                apiResponse.Status.Message.FriendlyMessage = $"Final Approval Successful <br/>But payment not made 'Reason (s): {paymentResp.Status.Message.FriendlyMessage}";
                                return(apiResponse);
                            }
                            await _repo.SendEmailToSupplierDetailingPaymentAsync(currentInvoice, thisInvoicePhase.Phase);

                            await _trans.CommitAsync();

                            apiResponse.Status = response.Status;
                            apiResponse.Status.Message.FriendlyMessage = $"Final Approval Successful";
                            return(apiResponse);
                        }
                        if (response.ResponseId == (int)ApprovalStatus.Disapproved)
                        {
                            await _detailService.AddUpdateApprovalDetailsAsync(detail);

                            currentInvoice.ApprovalStatusId = (int)ApprovalStatus.Disapproved;

                            await _invoice.CreateUpdateInvoiceAsync(currentInvoice);

                            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;
            }
        }
Beispiel #7
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);
                }
            }