Пример #1
0
        /// <summary>
        /// Process starts here.
        /// </summary>
        /// <param name="args">The arguments.</param>
        private static void Main(string[] args)
        {
            try
            {
                //set the culture
                CultureInfo cultureInfo = new CultureInfo("en-AU");
                Thread.CurrentThread.CurrentCulture   = cultureInfo;
                Thread.CurrentThread.CurrentUICulture = cultureInfo;

                bool   ownsMutex = true;
                string MutexName = "StageBitzAgent";

                #region Check mutex and run the agent activities

                using (Mutex mutex = new Mutex(true, MutexName, out ownsMutex))
                {
                    if (!ownsMutex)
                    {
                        AgentErrorLog.WriteToErrorLog("StageBitz Agent could not run as previous instance is already running.");
                    }
                    else
                    {
                        try
                        {
                            RunAgent();
                        }
                        catch (Exception ex)
                        {
                            AgentErrorLog.HandleException(ex);
                        }
                        finally
                        {
                            mutex.ReleaseMutex();
                        }
                    }
                }

                #endregion Check mutex and run the agent activities
            }
            catch (Exception ex)
            {
                AgentErrorLog.HandleException(ex);
            }
        }
Пример #2
0
        /// <summary>
        /// Processes the invoice.
        /// </summary>
        /// <param name="invoice">The invoice.</param>
        /// <param name="company">The company.</param>
        /// <param name="dataContext">The data context.</param>
        /// <returns></returns>
        private static bool ProcessInvoice(Invoice invoice, Data.Company company, StageBitzDB dataContext)
        {
            bool isSuccess = true;

            try
            {
                //Get the Payment History record which has not sent to the payment gateway.
                PaymentLog paymentLog = dataContext.PaymentLogs.Where(pl => pl.RelatedTableName == "Invoice" && pl.RelatedId == invoice.InvoiceID && pl.IsSentToPaymentGateway == false).FirstOrDefault();

                //Get the TokenID of the Company to pass over to Payment gateway.
                CreditCardToken creditCardToken = (from ct in dataContext.CreditCardTokens
                                                   where ct.RelatedTableName == "Company" && ct.RelatedId == company.CompanyId &&
                                                   ct.IsActive == true
                                                   select ct).FirstOrDefault();

                bool isPaymentSuccess = false;

                if (creditCardToken != null)
                {
                    paymentLog.ReferenceNumber = Utils.GetSystemValue("ReferenceNumberPrefix") + paymentLog.PaymentLogId;

                    //Make the payment via the payment gateway.
                    //Multuply by 100 to send over to FatZebra.
                    //Utils.DecryptStringAES(creditCardToken.Token)
                    var response = Purchase.Create((int)(invoice.Amount * 100), Utils.DecryptStringAES(creditCardToken.Token), null, paymentLog.ReferenceNumber, Utils.GetSystemValue("SBServerIPAddress"));
                    isPaymentSuccess = response.Successful && response.Result != null && response.Result.Successful;

                    if (isPaymentSuccess)
                    {
                        //Update Invoice as Processed.
                        invoice.InvoiceStatusCodeId = Utils.GetCodeByValue("InvoiceStatus", "PROCESSED").CodeId;

                        //Create Receipt for the Invoice
                        FinanceSupport.CreateReceipt(company.CompanyId, "Company", string.Format("Payment for Company {0}", company.CompanyName), invoice.Amount, invoice.Transaction.TransactionID, dataContext);
                    }
                    else
                    {
                        //Update Invoice as Failed.
                        invoice.InvoiceStatusCodeId = Utils.GetCodeByValue("InvoiceStatus", "FAILED").CodeId;
                    }

                    //Update the Payment History record as Sent to payment gateway.
                    paymentLog.IsSentToPaymentGateway = true;
                    paymentLog.IsPaymentSuccess       = isPaymentSuccess;
                    if (response.Result != null)
                    {
                        paymentLog.ResponseId = response.Result.ID;
                    }
                    paymentLog.Description       = GetPaymentGatewayLogDescription(response);
                    paymentLog.CreditCardTokenId = creditCardToken.CreditCardTokenID;
                }
                else
                {
                    paymentLog.Description = "Credit card details not provided.";
                    //Update Invoice as Failed.
                    invoice.InvoiceStatusCodeId = Utils.GetCodeByValue("InvoiceStatus", "FAILED").CodeId;
                }

                invoice.LastUpdateDate = Utils.Now;
                invoice.LastUpdatedBy  = 0;

                paymentLog.LastUpdatedDate     = Utils.Now;
                paymentLog.LastUpdatedByUserId = 0;

                isSuccess = isPaymentSuccess;
            }
            catch (Exception ex)
            {
                AgentErrorLog.WriteToErrorLog("Failed to Process the Invoice for CompanyId " + invoice.RelatedID);
                AgentErrorLog.HandleException(ex);
                isSuccess = false;
            }
            return(isSuccess);
        }
Пример #3
0
        /// <summary>
        /// This is to be called by monthly agent and manual payment.
        /// </summary>
        public static bool ProcessInvoicesAndPayments(int companyId, DateTime dateToConsider, bool shouldCreateInvoices, int userId)
        {
            using (StageBitzDB dataContext = new StageBitzDB())
            {
                FinanceSupport.InitializePaymentSettings();
                bool           isPaymentSuccess = false;
                bool           isManualPayment  = (companyId == 0) ? false : true;
                List <Invoice> invoiceList      = new List <Invoice>();

                if (shouldCreateInvoices)
                {
                    List <CompanyPaymentSummary> unProcessedPaymentSummaries = GetUnProcessedCompanyPaymentSummaries(0, dataContext, dateToConsider);

                    //Only consider companies which has payment packages
                    List <Data.Company> companies = (from c in dataContext.Companies
                                                     join cpp in dataContext.CompanyPaymentPackages on c.CompanyId equals cpp.CompanyId
                                                     select c).Distinct().ToList();

                    if (unProcessedPaymentSummaries.Count > 0)
                    {
                        CompanyBL companyBL = new CompanyBL(dataContext);

                        foreach (Data.Company company in companies)
                        {
                            try
                            {
                                List <CompanyPaymentSummary> unProcessedCompanyPaymentSummaries = unProcessedCompanyPaymentSummaries = unProcessedPaymentSummaries.Where(upcs => upcs.CompanyId == company.CompanyId).OrderBy(ups => ups.CompanyPaymentSummaryId).ToList();

                                //*******Consider payment summaries for the company*********
                                if (unProcessedCompanyPaymentSummaries != null && unProcessedCompanyPaymentSummaries.Count() > 0)
                                {
                                    if (!companyBL.IsFreeTrialCompany(company.CompanyId, dateToConsider))
                                    {
                                        decimal  totalAmount = unProcessedCompanyPaymentSummaries.Sum(ups => ups.Amount);
                                        DateTime fromDate    = unProcessedCompanyPaymentSummaries.First().FromDate;
                                        DateTime toDate      = unProcessedCompanyPaymentSummaries.Last().ToDate;

                                        Invoice invoice = null;
                                        if (totalAmount > 0) //generate the invoice only if there is a due amount to pay
                                        {
                                            invoice = FinanceSupport.CreateInvoice(company.CompanyId, "Company", "PACKAGEFEE", string.Format("Payment for Company {0}", company.CompanyName), decimal.Round(totalAmount, 2), fromDate, toDate, dataContext);
                                        }

                                        foreach (CompanyPaymentSummary companyPackagePaymentSummary in unProcessedCompanyPaymentSummaries)
                                        {
                                            companyPackagePaymentSummary.IsMonthlyAgentProcessed = true;
                                            if (invoice != null)
                                            {
                                                companyPackagePaymentSummary.Invoice = invoice;
                                            }

                                            companyPackagePaymentSummary.LastUpdatedDate = Utils.Today;
                                            companyPackagePaymentSummary.LastUpdatedBy   = 0;
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                AgentErrorLog.WriteToErrorLog("Failed to create Invoice for projectId" + company.CompanyId);
                                AgentErrorLog.HandleException(ex);
                                isPaymentSuccess = false;
                            }
                        }
                        //Complete upto now.
                        dataContext.SaveChanges();
                    }
                    //Get all the Unprocessed Invoices to send to the payment gateway.
                    invoiceList = FinanceSupport.GetUnProcessedInvoicesByRelatedTable("Company", companyId, "PACKAGEFEE", dataContext);
                }
                else
                {
                    int companyStatusCodeID = 0;
                    if (!isManualPayment)
                    {
                        //Not Manual means, Payment Retry.
                        companyStatusCodeID = Utils.GetCodeByValue("CompanyStatus", "GRACEPERIOD").CodeId;
                    }

                    //Get all the Unprocessed Invoices to send to the payment gateway.
                    //For Grace period payment Retry process projectId is 0.
                    invoiceList = FinanceSupport.GetPaymentFailedInvoices("PACKAGEFEE", companyStatusCodeID, companyId, "Company", dataContext);
                }

                //Because we need Payment Log records before process Invoices.
                foreach (Invoice invoice in invoiceList)
                {
                    FinanceSupport.CreatePaymentLog(invoice.InvoiceID, dataContext);
                }
                dataContext.SaveChanges();

                //Get distinct company Ids within the unprocessed invoice list
                var companyIds = invoiceList.Select(inv => inv.RelatedID).Distinct();

                foreach (int distinctCompanyId in companyIds)
                {
                    isPaymentSuccess = ProcessInvoicesByCompany(invoiceList, distinctCompanyId, isManualPayment, dataContext);
                    if (isPaymentSuccess)
                    {
                        CompanyBL companyBL = new CompanyBL(dataContext);
                        companyBL.ActivateUnProcessedSummaries(distinctCompanyId, userId);
                    }
                }

                dataContext.SaveChanges();
                //For the Monthly Agent Runner the return value is not important but for the manual payment.
                return(isPaymentSuccess);
            }
        }