public QueryResultDisplay SearchByDateRange(QueryDisplay query)
        {
            var invoiceDateStart = query.Parameters.FirstOrDefault(x => x.FieldName == "invoiceDateStart");
            var invoiceDateEnd = query.Parameters.FirstOrDefault(x => x.FieldName == "invoiceDateEnd");

            DateTime startDate;
            DateTime endDate;
            if (invoiceDateStart == null) throw new NullReferenceException("SalesOverTimeReportApiController::SearchByDateRange: invoiceDateStart is a required parameter");

            var settings = _storeSettingService.GetAll().ToList();
            var dateFormat = settings.FirstOrDefault(s => s.Name == "dateFormat");
            if (dateFormat == null)
            {
                if (!DateTime.TryParse(invoiceDateStart.Value, out startDate)) throw new InvalidCastException("SalesOverTimeReportApiController::SearchByDateRange: Failed to convert invoiceDateStart to a valid DateTime");
            }
            else if (!DateTime.TryParseExact(invoiceDateStart.Value, dateFormat.Value, CultureInfo.InvariantCulture, DateTimeStyles.None, out startDate))
            {
                throw new InvalidCastException("SalesOverTimeReportApiController::SearchByDateRange: Failed to convert invoiceDateStart to a valid DateTime");
            }

            endDate = invoiceDateEnd == null || dateFormat == null
                ? DateTime.MaxValue
                : DateTime.TryParseExact(invoiceDateEnd.Value, dateFormat.Value, CultureInfo.InvariantCulture, DateTimeStyles.None, out endDate)
                    ? endDate
                    : DateTime.MaxValue;

            var invoices = _merchello.Query.Invoice.Search(
                startDate,
                endDate.AddDays(1), // through end of day
                1,
                long.MaxValue,
                query.SortBy,
                query.SortDirection);


            var result = new QueryResultDisplay();

            if (!invoices.Items.Any())
            {
                return result;
            }

            ////build list of items grouped by date. each item has "date", "salestotal", "salescount"
            var source = (from invoiceItem in invoices.Items.ToList().Cast<InvoiceDisplay>()
                         where invoiceItem.InvoiceStatus.Alias == "paid"
                         group invoiceItem by invoiceItem.InvoiceDate.Date
                         into g
                         orderby g.Key descending
                         select
                             new SalesOverTimeResult
                                 {
                                     Date = g.Key.ToString("MMMM dd, yyyy"),
                                     SalesTotal = g.Sum(item => item.Total),
                                     SalesCount = g.Count()
                                 }).ToArray();

            result.Items = source;
            result.TotalItems = source.Count();
            result.ItemsPerPage = 10;
            result.CurrentPage = 0;
            result.TotalPages = result.TotalItems / result.ItemsPerPage;

            return result;
        }
        public QueryResultDisplay SearchByDateRange(QueryDisplay query)
        {
            var invoiceDateStart = query.Parameters.FirstOrDefault(x => x.FieldName == "invoiceDateStart");
            var invoiceDateEnd = query.Parameters.FirstOrDefault(x => x.FieldName == "invoiceDateEnd");

            DateTime startDate;
            DateTime endDate;
            if (invoiceDateStart == null) throw new NullReferenceException("invoiceDateStart is a required parameter");

            var settings = _storeSettingService.GetAll().ToList();
            var dateFormat = settings.FirstOrDefault(s => s.Name == "dateFormat");
            if (dateFormat == null)
            {
                if (!DateTime.TryParse(invoiceDateStart.Value, out startDate)) throw new InvalidCastException("Failed to convert invoiceDateStart to a valid DateTime");
            }
            else if (!DateTime.TryParseExact(invoiceDateStart.Value, dateFormat.Value, CultureInfo.InvariantCulture, DateTimeStyles.None, out startDate))
            {
                throw new InvalidCastException("Failed to convert invoiceDateStart to a valid DateTime");
            }

            endDate = invoiceDateEnd == null || dateFormat == null
                ? DateTime.MaxValue
                : DateTime.TryParseExact(invoiceDateEnd.Value, dateFormat.Value, CultureInfo.InvariantCulture, DateTimeStyles.None, out endDate)
                    ? endDate
                    : DateTime.MaxValue;

            var invoices = _merchello.Query.Invoice.Search(
                startDate,
                endDate.AddDays(1), // through end of day
                1,
                long.MaxValue,
                query.SortBy,
                query.SortDirection);


            var result = new QueryResultDisplay();

            if (!invoices.Items.Any()) return result;

            // Use a visitor to build the collection of report data
            var vistor = new SalesByItemVisitor(_merchello);

            foreach (var invoice in invoices.Items)
            {
                ((InvoiceDisplay)invoice).Accept(vistor);
            }

            result.TotalItems = vistor.Results.Count();
            result.ItemsPerPage = vistor.Results.Count();
            result.CurrentPage = 0;
            result.TotalPages = 1;
            result.Items = vistor.Results;

            return result;
        }
        public override QueryResultDisplay GetDefaultReportData()
        {
            var anonymousBasketCount = _itemCacheService.Count(this._itemCacheType, CustomerType.Anonymous, _startDate, _endDate);
            var anonymousCheckoutCount = _invoiceService.CountInvoices(_startDate, _endDate, CustomerType.Anonymous);
            var customerBasketCount = _itemCacheService.Count(this._itemCacheType, CustomerType.Customer, _startDate, _endDate);
            var customerCheckoutCount = _invoiceService.CountInvoices(_startDate, _endDate, CustomerType.Customer);

            var result = new QueryResultDisplay()
                             {
                                 TotalItems = 1,
                                 TotalPages = 1,
                                 CurrentPage = 1,
                                 ItemsPerPage = 1,
                                 Items = new[]
                                    {
                                        new AbandonedBasketResult()
                                            {
                                                ConfiguredDays = _maxDays,
                                                StartDate = _startDate,
                                                EndDate = _endDate,
                                                AnonymousBasketCount = anonymousBasketCount,
                                                AnonymousCheckoutCount = anonymousCheckoutCount,
                                                AnonymousCheckoutPercent = GetCheckoutPercent(anonymousBasketCount, anonymousCheckoutCount),
                                                CustomerBasketCount = customerBasketCount,
                                                CustomerCheckoutCount = customerCheckoutCount,
                                                CustomerCheckoutPercent = GetCheckoutPercent(customerBasketCount, customerCheckoutCount)
                                            }
                                    }
                             };

            return result;
        }
        /// <summary>
        /// The get default report data.
        /// 
        /// GET /umbraco/Merchello/ExportOrdersReportApi/GetOrderReportData/
        /// 
        /// </summary>
        /// <returns>
        /// The <see cref="QueryResultDisplay"/>.
        /// </returns>
        public QueryResultDisplay GetOrderReportData()
        {
            var dtStart = new DateTime(2014,1,1);
            var dtEnd = new DateTime(2014,12,31);
            var invoices = _invoiceService.GetInvoicesByDateRange(dtStart,dtEnd).ToArray();
            var queryResultDisplay = new QueryResultDisplay();

            try
            {
                var csvExport = new CvsExport();
                foreach (var invoice in invoices)
                {
                    csvExport.AddRow();

                    csvExport["Number"] = invoice.InvoiceNumber;
                    csvExport["Date"] = invoice.InvoiceDate;
                    csvExport["Bill To Name"] = invoice.BillToName;
                    csvExport["Bill To Company"] = invoice.BillToCompany;
                    csvExport["Bill To Address"] = invoice.BillToAddress1;
                    csvExport["Bill To Address2"] = invoice.BillToAddress2;
                    csvExport["Email"] = invoice.BillToEmail;
                    csvExport["Phone"] = invoice.BillToPhone;
                    csvExport["City"] = invoice.BillToLocality;
                    csvExport["State"] = invoice.BillToRegion;
                    csvExport["Postal Code"] = invoice.BillToPostalCode;
                    csvExport["Total"] = invoice.Total;
                    csvExport["Status"] = invoice.InvoiceStatus.Name;

                    foreach (var invoiceItems in invoice.Items)
                    {

                        foreach (var invoiceItem in invoice.Items)
                        {
                            if (invoiceItem.LineItemType == LineItemType.Product)
                            {
                                csvExport["Name"] = invoiceItem.Name;
                                csvExport["Sku"] = invoiceItem.Sku;
                                csvExport["Quantity"] = invoiceItem.Quantity;
                                csvExport["Price"] = invoiceItem.Price;
                            }
                            else if (invoiceItem.LineItemType == LineItemType.Shipping)
                            {
                                csvExport["Ship Method"] = invoiceItem.Name;
                                csvExport["Ship Quantity"] = invoiceItem.Quantity;
                                csvExport["Ship Price"] = invoiceItem.Price;

                                var origin =invoiceItem.ExtendedData.GetAddress(Constants.ExtendedDataKeys.ShippingOriginAddress);
                                var destination =invoiceItem.ExtendedData.GetAddress(Constants.ExtendedDataKeys.ShippingDestinationAddress);

                                csvExport["Ship Origin"] = FormatAddress(origin);
                                csvExport["Ship Destination"] = FormatAddress(destination);
                            }
                            else if (invoiceItem.LineItemType == LineItemType.Tax)
                            {
                                csvExport["Tax"] = invoiceItem.Name;
                                csvExport["Tax Quantity"] = invoiceItem.Quantity;
                                csvExport["Tax Price"] = invoiceItem.Price;
                            }
                            else if (invoiceItem.LineItemType == LineItemType.Discount)
                            {
                                csvExport["Coupon"] = invoiceItem.Name;
                                csvExport["Coupon Quantity"] = invoiceItem.Quantity;
                                csvExport["Coupon Price"] = invoiceItem.Price;
                            }
                        }
                    }
                }

                string path = HttpContext.Current.Server.MapPath("/orders.csv");

                csvExport.ExportToFile(path);

                queryResultDisplay = new QueryResultDisplay { Items = invoices, TotalItems = invoices.Count() };
            }
            catch (SystemException e)
            {
                string ex = e.Message;
            }

            return queryResultDisplay;
        }