Beispiel #1
0
        public List <Invoice> CreateInvoicesForFrequency(DateTime date, Frequency frequency)
        {
            var dateRange = GetRange(frequency, date);

            Logging.Log($"Creating {frequency} on {date:yyyy-MM-dd} for {dateRange.Start:yyyy-MM-dd} to {dateRange.End:yyyy-MM-dd}.");
            var connectionLock = QuickBooksClient.GetConnectionForLocks();

            if (frequency == Frequency.Weekly && connectionLock.WeeklyInvoiceLock ||
                frequency == Frequency.Monthly && connectionLock.MonthlyInvoiceLock)
            {
                throw new Exception($"Can't create {frequency} invoices. {frequency} invoice lock is enabled. Invoices are being created by another process.");
            }
            QuickBooksClient.LockInvoices(frequency, true);
            try
            {
                var invoices = CreateInvoices(dateRange, frequency);
                Logging.Log($"Created {invoices.Count} {frequency} invoices for {date:O}.");
                foreach (var invoice in invoices)
                {
                    Logging.Log($"Created {frequency} invoice for {invoice.CustomerRef.Name} - {invoice.CustomerRef.Value}");
                }
                Logging.Log("Newly created invoices: " + JsonConvert.SerializeObject(invoices));
                return(invoices);
            }
            finally
            {
                QuickBooksClient.LockInvoices(frequency, false);
            }
        }
Beispiel #2
0
        private List <Invoice> CreateInvoices(DateRange dateRange, Frequency frequency)
        {
            var invoiceQuery       = $"select * from Invoice Where TxnDate >= '{dateRange.Start:yyyy-MM-dd}' and TxnDate <= '{dateRange.End:yyyy-MM-dd}'";
            var allInvoices        = QuickBooksClient.QueryAll <Invoice>(invoiceQuery);
            var allActiveCustomers = QuickBooksClient.QueryAll <Customer>("select * from customer")
                                     .ToDictionary(x => x.Id);
            var vendors     = new ActiveVendorSearch().GetActiveVendors(allActiveCustomers, VendorService, frequency);
            var newInvoices = new List <Invoice>();

            foreach (var vendor in vendors.Values)
            {
                var vendorInvoices = allInvoices.Where(x => x.CustomerRef.Value == vendor.QuickBooksOnlineId.ToString());
                if (!vendorInvoices.Any())
                {
                    var invoiceDate = frequency == Frequency.Weekly ? dateRange.End : dateRange.Start;
                    newInvoices.Add(CreateInvoice(invoiceDate, allActiveCustomers[vendor.QuickBooksOnlineId], vendor));
                }
            }
            var paymentApplicator = new PaymentApplicator(QuickBooksClient);

            foreach (var invoice in newInvoices)
            {
                paymentApplicator.ApplyUnappliedPaymentsToInvoice(invoice);
            }
            return(newInvoices);
        }
Beispiel #3
0
 private void Revert(ReceiptSaveResult result)
 {
     if (result.Invoice != null)
     {
         QuickBooksClient.Delete(result.Invoice);
         result.Invoice = null;
     }
     foreach (var payment in result.Payments ?? new List <Payment>())
     {
         QuickBooksClient.Delete(payment);
     }
     result.Payments = null;
     foreach (var reservation in result.SpotReservations ?? new List <SpotReservation>())
     {
         SpotReservationDbClient.Delete(reservation);
     }
     result.SpotReservations = null;
 }
Beispiel #4
0
        private Invoice CreateInvoice(DateTime date, Customer customer, DatabaseModel.Vendor vendor)
        {
            decimal quantity      = 1;
            decimal taxableAmount = vendor.RentPrice.GetValueOrDefault() / (1 + TaxRate);
            var     invoice       = new Invoice
            {
                TxnDate     = date.ToString("yyyy-MM-dd"),
                CustomerRef = new Reference {
                    Value = customer.Id.ToString()
                },
                Line = new List <SalesLine>
                {
                    new SalesLine
                    {
                        DetailType          = "SalesItemLineDetail",
                        SalesItemLineDetail = new SalesItemLineDetail
                        {
                            ItemRef = new Reference {
                                Value = Constants.QUICKBOOKS_PRODUCT_RENT.ToString()
                            },
                            Quantity   = quantity,
                            TaxCodeRef = new Reference {
                                Value = Accounting.Constants.QUICKBOOKS_INVOICE_LINE_TAXABLE
                            },
                            UnitPrice = taxableAmount
                        },
                        Amount = quantity * taxableAmount
                    }
                },
                TxnTaxDetail = new TxnTaxDetail
                {
                    TxnTaxCodeRef = new Reference {
                        Value = Constants.QUICKBOOKS_RENTAL_TAX_RATE.ToString()
                    }
                },
                PrivateNote  = vendor.Memo,
                SalesTermRef = new Reference {
                    Value = Constants.QUICKBOOKS_TERMS_DUE_NOW.ToString()
                }
            };

            return(QuickBooksClient.Create(invoice));
        }
Beispiel #5
0
        private bool _disposedValue = false; // To detect redundant calls

        /// <summary>
        /// Initializes a new instance of the <see cref="SessionManager"/> class.
        /// </summary>
        private SessionManager()
        {
            this._log = LogManager.GetLogger(typeof(SessionManager));
            AggregateCatalog catalog = new AggregateCatalog();

            // 1. this adds the executables of the current executable folder to the catalog
            var execPath = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            catalog.Catalogs.Add(new DirectoryCatalog(execPath, "*.dll"));
            catalog.Catalogs.Add(new DirectoryCatalog(execPath, "*.exe"));

            // 2. this creates the container that is passed to map view and beyond
            this._container = new CompositionContainer(catalog);

            // Get information on the application
            this.AppName    = Assembly.GetExecutingAssembly().GetName().Name.ToString().Replace(".", " ").Replace("UI", "");
            this.AppVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString();
            var client = new QuickBooksClient(string.Empty, $"{this.AppName} v{this.AppVersion}", "US");

            this.InventoryManager = new InventoryManager(client);
        }
Beispiel #6
0
 public DepositController(QuickBooksClient client, string oAuthVersion) : base(client, oAuthVersion)
 {
 }
Beispiel #7
0
        private void SaveReceiptCore(
            Receipt receipt,
            string customerId,
            string firstName,
            string lastName,
            string email,
            Vendor vendor,
            string userIp,
            out ReceiptSaveResult result)
        {
            var existing = ReceiptDbClient.Get(new ReceiptSaveResult {
                Id = receipt.Id
            }, true).Result;

            if (existing != null)
            {
                throw new Exception($"A receipt with id {receipt.Id} has already been sent for processing.");
            }
            var receiptCopyToSave = JsonConvert.DeserializeObject <Receipt>(JsonConvert.SerializeObject(receipt));

            receiptCopyToSave.CardPayment = null;
            result = new ReceiptSaveResult
            {
                Id        = receipt.Id,
                Timestamp = DateTime.UtcNow.ToString("O"),
                Receipt   = receiptCopyToSave,
                Vendor    = vendor,
                CreatedBy = new ReceiptSaveResultUser
                {
                    FirstName = firstName,
                    LastName  = lastName,
                    Email     = email,
                    Ip        = userIp
                }
            };
            ReceiptDbClient.Create(result);
            var memo = receipt.Memo;

            if (receipt.MakeCardPayment.GetValueOrDefault())
            {
                var last4 = receipt.CardPayment.CardNumber.Substring(receipt.CardPayment.CardNumber.Length - 4);
                Logger.Log($"{firstName} {lastName} {email} is charging card ending in {last4} ${receipt.ThisPayment:C} on {DateTime.UtcNow:O} for receipt {result.Id}.");
                var chargeResult = CardPayment.Authorize(
                    receipt.ThisPayment * 100,
                    receipt.CardPayment.CardNumber,
                    receipt.CardPayment.ExpirationMonth,
                    receipt.CardPayment.ExpirationYear,
                    receipt.CardPayment.Cvv,
                    receipt.IsCardPresent);
                result.CardAuthorizationResult = chargeResult;
                ReceiptDbClient.Create(result);
                if (chargeResult["error"] != null)
                {
                    return;
                }
            }

            if (receipt.Spots != null && receipt.Spots.Any())
            {
                memo += Environment.NewLine + "Spots: " + string.Join(", ", receipt.Spots.Select(x => $"{x.Section?.Name} - {x.Name}"));
            }

            if (receipt.RentalAmount > 0)
            {
                result.Invoice = QuickBooksClient.Create(CreateInvoice(customerId, receipt.RentalAmount, receipt.RentalDate, memo));
                ReceiptDbClient.Create(result);
            }

            result.Payments = new List <Payment>();
            if (receipt.ThisPayment > 0)
            {
                ZonedClock easternClock = SystemClock.Instance.InZone(DateTimeZoneProviders.Tzdb["America/New_York"]);
                var        paymentMemo  = $"True Payment Date: {easternClock.GetCurrentDate():yyyy-MM-dd}. " +
                                          $"Payment entered by {firstName} {lastName} from IP {userIp}." +
                                          Environment.NewLine + Environment.NewLine + memo;
                var     unpaidInvoices    = QuickBooksClient.QueryAll <Invoice>($"select * from Invoice where Balance != '0' and CustomerRef = '{customerId}' ORDERBY TxnDate");
                decimal payment           = receipt.ThisPayment.GetValueOrDefault();
                var     paymentApplicator = new PaymentApplicator(QuickBooksClient);
                foreach (var unpaidInvoice in unpaidInvoices)
                {
                    var paymentAppliedToInvoice = paymentApplicator.CreatePayment(
                        unpaidInvoice,
                        customerId,
                        payment,
                        $"{easternClock.GetCurrentDate():yyyy-MM-dd}",
                        paymentMemo);
                    result.Payments.Add(paymentAppliedToInvoice);
                    payment -= paymentAppliedToInvoice.TotalAmount.GetValueOrDefault();
                    if (payment <= 0)
                    {
                        break;
                    }
                }
                if (payment > 0)
                {
                    var unappliedPayment = paymentApplicator.CreatePayment(
                        null,
                        customerId,
                        payment,
                        $"{easternClock.GetCurrentDate():yyyy-MM-dd}",
                        paymentMemo
                        );
                    result.Payments.Add(unappliedPayment);
                }
            }
            ReceiptDbClient.Create(result);

            if (receipt.Spots != null)
            {
                result.SpotReservations = new List <SpotReservation>();
                foreach (var spot in receipt.Spots)
                {
                    var spotReservation = new SpotReservation
                    {
                        SpotId             = spot.Id,
                        RentalDate         = receipt.RentalDate,
                        QuickBooksOnlineId = int.Parse(customerId),
                        VendorId           = vendor.Id
                    };
                    SpotReservationDbClient.Create(spotReservation);
                    result.SpotReservations.Add(spotReservation);
                }
            }

            if (receipt.MakeCardPayment.GetValueOrDefault())
            {
                result.CardCaptureResult = CardPayment.Capture(result.CardAuthorizationResult["id"].Value <string>());
                for (var ct = 0; ct < result.Payments.Count; ct++)
                {
                    result.Payments[ct].PrivateNote += Environment.NewLine + Environment.NewLine + $"Card payment confirmation {result.CardAuthorizationResult.ToString(Formatting.Indented)}";
                    result.Payments[ct]              = QuickBooksClient.SparseUpdate(result.Payments[ct]);
                }
            }
            ReceiptDbClient.Create(result);
        }
 public CompanyInfoController(QuickBooksClient client, string oAuthVersion) : base(client, oAuthVersion)
 {
 }
Beispiel #9
0
 protected BaseController(QuickBooksClient client, string oAuthVersion)
 {
     Client        = client;
     _oAuthVersion = oAuthVersion;
 }
 public SalesReceiptController(QuickBooksClient client, string oAuthVersion) : base(client, oAuthVersion)
 {
 }
 public CustomerController(QuickBooksClient client, string oAuthVersion) : base(client, oAuthVersion)
 {
 }
Beispiel #12
0
 public InvoiceController(QuickBooksClient client, string oAuthVersion) : base(client, oAuthVersion)
 {
 }