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

            DateTime startDate;
            DateTime endDate;

            Mandate.ParameterNotNull(lastActivityDateStart, "lastActivityDateStart is a required parameter");
            Mandate.ParameterCondition(DateTime.TryParse(lastActivityDateStart.Value, out startDate), "Failed to convert lastActivityDateStart to a valid DateTime");

            endDate = lastActivityDateEnd == null
                ? DateTime.MaxValue
                : DateTime.TryParse(lastActivityDateEnd.Value, out endDate)
                    ? endDate
                    : DateTime.MaxValue;

            return
                (_merchello.Query.Customer.Search(
                     startDate,
                     endDate,
                     query.CurrentPage + 1,
                     query.ItemsPerPage,
                     query.SortBy,
                     query.SortDirection));
        }
        public QueryResultDisplay ExportByDateRange(QueryDisplay query)
        {
            var result = this.SearchByDateRange(query);

            var invoiceDateStart = query.Parameters.FirstOrDefault(x => x.FieldName == "invoiceDateStart");
            var invoiceDateEnd   = query.Parameters.FirstOrDefault(x => x.FieldName == "invoiceDateEnd");

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

            // check if the directory exists
            var exportDir = IOHelper.MapPath("~/App_Data/TEMP/Merchello/");

            if (!Directory.Exists(exportDir))
            {
                Directory.CreateDirectory(exportDir);
            }


            var dump = CsvSerializer.SerializeToCsv(result.Items);

            // write dump to export file
            var exportFileName = string.Concat("SalesByItemReport_", DateTime.Parse(invoiceDateStart.Value).ToString("_yyyyMMdd"), "_", DateTime.Parse(invoiceDateEnd.Value).ToString("_yyyyMMdd"), ".csv");
            var exportPath     = string.Concat(exportDir, exportFileName);

            File.WriteAllText(exportPath, dump);

            return(result);
        }
        public QueryResultDisplay GetByAdvancedSearch(QueryDisplay query)
        {
            var itemsPerPage     = query.ItemsPerPage;
            var currentPage      = query.CurrentPage + 1;
            var collectionKey    = query.Parameters.FirstOrDefault(x => x.FieldName == "collectionKey");
            var includedFields   = query.Parameters.FirstOrDefault(x => x.FieldName == "includedFields");
            var searchTerm       = query.Parameters.FirstOrDefault(x => x.FieldName == "term");
            var manufacturerTerm = query.Parameters.FirstOrDefault(x => x.FieldName == "manufacturer");

            var key          = collectionKey == null ? Guid.Empty : new Guid(collectionKey.Value);
            var incFields    = includedFields == null ? new[] { "name", "sku" } : includedFields.Value.Split(',');
            var term         = searchTerm == null ? string.Empty : searchTerm.Value;
            var manufacturer = manufacturerTerm == null ? string.Empty : manufacturerTerm.Value;

            var results = ((ProductService)_productService).GetByAdvancedSearch(
                key,
                incFields,
                term,
                manufacturer,
                currentPage,
                itemsPerPage,
                query.SortBy,
                query.SortDirection);

            return(results.ToQueryResultDisplay <IProduct, ProductDisplay>(MapToProductDisplay));
        }
        public QueryResultDisplay PostGetEntitiesNotInCollection(QueryDisplay query)
        {
            var collectionKey  = query.Parameters.FirstOrDefault(x => x.FieldName == "collectionKey");
            var entityTypeName = query.Parameters.FirstOrDefault(x => x.FieldName == "entityType");

            if (collectionKey == null || entityTypeName == null)
            {
                throw new NullReferenceException("collectionKey and entityType must be included as a parameter");
            }

            var key = new Guid(collectionKey.Value);

            var entityType = (EntityType)Enum.Parse(typeof(EntityType), entityTypeName.Value);

            var term = query.Parameters.FirstOrDefault(x => x.FieldName == "term");

            var cachedQuery = this.GetCachedQueryByEntityType(entityType);

            return(term != null && !string.IsNullOrEmpty(term.Value)
              ?
                   cachedQuery.GetNotInCollection(
                       key,
                       term.Value,
                       query.CurrentPage + 1,
                       query.ItemsPerPage,
                       query.SortBy,
                       query.SortDirection)
              :
                   cachedQuery.GetNotInCollection(
                       key,
                       query.CurrentPage + 1,
                       query.ItemsPerPage,
                       query.SortBy,
                       query.SortDirection));
        }
        public QueryResultDisplay GetRecentlyUpdated(QueryDisplay query)
        {
            var itemsPerPage = query.ItemsPerPage;
            var currentPage  = query.CurrentPage + 1;

            var results = _productService.GetRecentlyUpdatedProducts(currentPage, itemsPerPage);

            return(results.ToQueryResultDisplay <IProduct, ProductDisplay>(MapToProductDisplay));
        }
        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");
            }
            if (!DateTime.TryParse(invoiceDateStart.Value, out startDate))
            {
                throw new InvalidCastException("Failed to convert invoiceDateStart to a valid DateTime");
            }

            endDate = invoiceDateEnd == null
                ? DateTime.MaxValue
                : DateTime.TryParse(invoiceDateEnd.Value, out endDate)
                    ? endDate
                    : DateTime.MaxValue;

            var invoices = _merchello.Query.Invoice.Search(
                startDate,
                endDate,
                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);
        }
示例#7
0
        public QueryResultDisplay SearchOffers(QueryDisplay query)
        {
            var term = query.Parameters.FirstOrDefault(x => x.FieldName == "term");

            var hasSearchTerm = term != null && !string.IsNullOrEmpty(term.Value);

            var page = hasSearchTerm ?
                       _offerSettingsService.GetPage(term.Value, query.CurrentPage + 1, query.ItemsPerPage, query.SortBy, query.SortDirection) :
                       _offerSettingsService.GetPage(query.CurrentPage + 1, query.ItemsPerPage, query.SortBy, query.SortDirection);

            return(this.GetQueryResultDisplay(page));
        }
        public QueryResultDisplay SearchOptions(QueryDisplay query)
        {
            var termParam = query.Parameters.FirstOrDefault(x => x.FieldName == "term");
            var term      = termParam == null ? string.Empty : termParam.Value;

            var sharedOnlyParam = query.Parameters.FirstOrDefault(x => x.FieldName == "sharedOnly");

            var sharedOnly = sharedOnlyParam == null;

            var page = _productOptionService.GetPage(term, query.CurrentPage + 1, query.ItemsPerPage, query.SortBy, query.SortDirection, sharedOnly);

            return(page.ToQueryResultDisplay(MapToProductOptionDisplayForEditor));
        }
        public QueryResultDisplay GetWeeklyResult(QueryDisplay query)
        {
            var invoiceDateEnd = query.Parameters.FirstOrDefault(x => x.FieldName == "invoiceDateEnd");
            var isDateSearch   = invoiceDateEnd != null && !string.IsNullOrEmpty(invoiceDateEnd.Value);

            DateTime weekEnding;

            if (!isDateSearch)
            {
                weekEnding = DateTime.Today;
            }
            else
            {
                if (!DateTime.TryParse(invoiceDateEnd.Value, out weekEnding))
                {
                    weekEnding = DateTime.Today;
                }
            }

            var weekStarting = weekEnding.StartOfWeek();

            weekEnding = weekStarting.AddDays(6);


            var count       = 0;
            var results     = new List <SalesOverTimeResult>();
            var currentDate = weekStarting;

            while (currentDate <= weekEnding)
            {
                // special case where the end date is today - so add a day to make sure that the BETWEEN query reflects
                // the intended report result.
                var endDate = currentDate < DateTime.Today ? currentDate : currentDate.AddDays(1);

                count++;
                results.Add(GetResults(currentDate, endDate));
                currentDate = currentDate.AddDays(1);
            }

            return(new QueryResultDisplay()
            {
                Items = results,
                CurrentPage = 1,
                ItemsPerPage = count,
                TotalItems = count,
                TotalPages = 1
            });
        }
        public QueryResultDisplay GetWeeklyResult(QueryDisplay query)
        {
            var invoiceDateEnd  = query.Parameters.FirstOrDefault(x => x.FieldName == "invoiceDateEnd");
            var isDateSearch    = invoiceDateEnd != null && !string.IsNullOrEmpty(invoiceDateEnd.Value);
            var invoiceStatuses = GetInvoiceStatusesFromParameters(query);

            DateTime weekEnding;

            if (!isDateSearch)
            {
                weekEnding = DateTime.Today;
            }
            else
            {
                if (!DateTime.TryParse(invoiceDateEnd.Value, out weekEnding))
                {
                    weekEnding = DateTime.Today;
                }
            }

            var weekStarting = weekEnding.StartOfWeek();

            weekEnding = weekStarting.AddDays(6);


            var count       = 0;
            var results     = new List <SalesOverTimeResult>();
            var currentDate = weekStarting;

            while (currentDate <= weekEnding)
            {
                var endDate = currentDate.AddDays(1).AddMilliseconds(-1);

                count++;
                results.Add(GetResults(currentDate, endDate, invoiceStatuses));
                currentDate = currentDate.AddDays(1);
            }

            return(new QueryResultDisplay()
            {
                Items = results,
                CurrentPage = 1,
                ItemsPerPage = count,
                TotalItems = count,
                TotalPages = 1,
                InvoiceStatuses = invoiceStatuses
            });
        }
示例#11
0
        /// <summary>
        /// Get invocie statuses from query parameters
        /// </summary>
        /// <param name="query">The query</param>
        /// <returns>A list of invoice statuses</returns>
        protected IEnumerable <InvStatus> GetInvoiceStatusesFromParameters(QueryDisplay query)
        {
            var allStatuses          = AllInvoiceStatuses();
            var invoiceStatusesParam = query.Parameters.FirstOrDefault(x => x.FieldName == "invoiceStatuses");

            if (invoiceStatusesParam != null && !string.IsNullOrWhiteSpace(invoiceStatusesParam.Value))
            {
                var statuses = JsonConvert.DeserializeObject <List <InvStatus> >(invoiceStatusesParam.Value);
                if (statuses.Any())
                {
                    return(statuses);
                }
            }

            return(allStatuses);
        }
示例#12
0
        public QueryResultDisplay SearchByCustomer(QueryDisplay query)
        {
            Guid key;

            var customerKey = query.Parameters.FirstOrDefault(x => x.FieldName == "customerKey");

            Mandate.ParameterNotNull(customerKey, "customerKey was null");
            Mandate.ParameterCondition(Guid.TryParse(customerKey.Value, out key), "customerKey was not a valid GUID");

            return(_merchello.Query.Invoice.SearchByCustomer(
                       key,
                       query.CurrentPage + 1,
                       query.ItemsPerPage,
                       query.SortBy,
                       query.SortDirection));
        }
示例#13
0
        public QueryResultDisplay SearchProducts(QueryDisplay query)
        {
            var term = query.Parameters.FirstOrDefault(x => x.FieldName == "term");

            return(term != null && !string.IsNullOrEmpty(term.Value)
              ?
                   _merchello.Query.Product.Search(
                       term.Value,
                       query.CurrentPage + 1,
                       query.ItemsPerPage,
                       query.SortBy,
                       query.SortDirection)
              :
                   _merchello.Query.Product.Search(
                       query.CurrentPage + 1,
                       query.ItemsPerPage,
                       query.SortBy,
                       query.SortDirection));
        }
示例#14
0
        public QueryResultDisplay GetCustomerSavedBaskets(QueryDisplay query)
        {
            var page = _itemCacheService.GetCustomerItemCachePage(
                _itemCacheType,
                _startDate,
                _endDate.AddDays(2),
                query.CurrentPage + 1,
                query.ItemsPerPage,
                query.SortBy,
                query.SortDirection);

            return(new QueryResultDisplay
            {
                Items = page.Items.Select(x => x.ToCustomerItemCacheDisplay()),
                CurrentPage = page.CurrentPage - 1,
                ItemsPerPage = page.ItemsPerPage,
                TotalPages = page.TotalPages,
                TotalItems = page.TotalItems
            });
        }
        public override QueryResultDisplay GetCustomDateRange(QueryDisplay query)
        {
            var invoiceDateStart = query.Parameters.FirstOrDefault(x => x.FieldName == "invoiceDateStart");
            var invoiceDateEnd   = query.Parameters.FirstOrDefault(x => x.FieldName == "invoiceDateEnd");
            var invoiceStatuses  = GetInvoiceStatusesFromParameters(query);

            var isDateSearch = invoiceDateStart != null && !string.IsNullOrEmpty(invoiceDateStart.Value) &&
                               invoiceDateEnd != null && !string.IsNullOrEmpty(invoiceDateEnd.Value);

            if (!isDateSearch)
            {
                return(GetDefaultReportData());
            }

            DateTime startDate;

            //// Assert the start date
            if (DateTime.TryParse(invoiceDateStart.Value, out startDate))
            {
                DateTime endDate;
                //// Assert the end date
                if (DateTime.TryParse(invoiceDateEnd.Value, out endDate))
                {
                    //// Return the default report if startDate >= endDate
                    if (startDate >= endDate)
                    {
                        return(GetDefaultReportData());
                    }

                    var endOfMonth  = GetEndOfMonth(endDate);
                    var startOfYear = GetFirstOfMonth(startDate);

                    return(BuildResult(startOfYear, endOfMonth, invoiceStatuses));
                }

                return(GetDefaultReportData());
            }

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

            var isDateSearch = invoiceDateStart != null && !string.IsNullOrEmpty(invoiceDateStart.Value) &&
                               invoiceDateEnd != null && !string.IsNullOrEmpty(invoiceDateEnd.Value);

            if (!isDateSearch)
            {
                return(GetDefaultReportData());
            }

            DateTime startDate;

            //// Assert the start date
            if (DateTime.TryParse(invoiceDateStart.Value, out startDate))
            {
                DateTime endDate;
                //// Assert the end date
                if (DateTime.TryParse(invoiceDateEnd.Value, out endDate))
                {
                    //// Return the default report if startDate >= endDate
                    if (startDate >= endDate)
                    {
                        return(GetDefaultReportData());
                    }

                    var day = endDate.Day;

                    return(BuildResult(startDate, endDate));
                }

                return(GetDefaultReportData());
            }

            return(GetDefaultReportData());
        }
        public override QueryResultDisplay GetDefaultReportData()
        {
            var settings   = _storeSettingService.GetAll().ToList();
            var dateFormat = settings.FirstOrDefault(s => s.Name == "dateFormat");

            var query = new QueryDisplay()
            {
                CurrentPage  = 0,
                ItemsPerPage = int.MaxValue,
                Parameters   = new List <QueryDisplayParameter>()
                {
                    new QueryDisplayParameter()
                    {
                        FieldName = "invoiceDateStart",
                        Value     = dateFormat != null?DateTime.Now.AddMonths(-1).ToString(dateFormat.Value) : DateTime.Now.AddMonths(-1).ToShortDateString()
                    },
                    new QueryDisplayParameter()
                    {
                        FieldName = "invoiceDateEnd",
                        Value     = dateFormat != null?DateTime.Now.ToString(dateFormat.Value) : DateTime.Now.ToShortDateString()
                    }
                },
                SortBy = "invoiceDate"
            };

            try
            {
                var results = SearchByDateRange(query);
                return(results);
            }
            catch (Exception ex)
            {
                LogHelper.Error <SalesByItemReportApiController>("The system was unable to determine the default report data for the SalesOverTime report", ex);
            }

            return(new QueryResultDisplay());
        }
        public override QueryResultDisplay GetDefaultReportData()
        {
            var query = new QueryDisplay()
            {
                CurrentPage  = 0,
                ItemsPerPage = int.MaxValue,
                Parameters   = new List <QueryDisplayParameter>()
                {
                    new QueryDisplayParameter()
                    {
                        FieldName = "invoiceDateStart",
                        Value     = DateTime.Now.AddMonths(-1).ToShortDateString()
                    },
                    new QueryDisplayParameter()
                    {
                        FieldName = "invoiceDateEnd",
                        Value     = DateTime.Now.ToShortDateString()
                    }
                },
                SortBy = "invoiceDate"
            };

            return(SearchByDateRange(query));
        }
示例#19
0
        public QueryResultDisplay SearchByDateRange(QueryDisplay query)
        {
            var invoiceDateStart = query.Parameters.FirstOrDefault(x => x.FieldName == "invoiceDateStart");
            var invoiceDateEnd   = query.Parameters.FirstOrDefault(x => x.FieldName == "invoiceDateEnd");
            var invoiceStatusKey = query.Parameters.FirstOrDefault(x => x.FieldName == "invoiceStatusKey");

            DateTime startDate;
            DateTime endDate;

            Mandate.ParameterNotNull(invoiceDateStart, "invoiceDateStart is a required parameter");
            Mandate.ParameterCondition(DateTime.TryParse(invoiceDateStart.Value, out startDate), "Failed to convert invoiceDateStart to a valid DateTime");

            endDate = invoiceDateEnd == null
                ? DateTime.MaxValue
                : DateTime.TryParse(invoiceDateEnd.Value, out endDate)
                    ? endDate
                    : DateTime.MaxValue;

            return(invoiceStatusKey == null
                ? _merchello.Query.Invoice.Search(
                       startDate,
                       endDate,
                       query.CurrentPage + 1,
                       query.ItemsPerPage,
                       query.SortBy,
                       query.SortDirection) :

                   _merchello.Query.Invoice.Search(
                       startDate,
                       endDate,
                       invoiceStatusKey.Value.EncodeAsGuid(),
                       query.CurrentPage + 1,
                       query.ItemsPerPage,
                       query.SortBy,
                       query.SortDirection));
        }
示例#20
0
        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");
            }
            if (!DateTime.TryParse(invoiceDateStart.Value, out startDate))
            {
                throw new InvalidCastException("SalesOverTimeReportApiController::SearchByDateRange: Failed to convert invoiceDateStart to a valid DateTime");
            }

            endDate = invoiceDateEnd == null
                ? DateTime.MaxValue
                : DateTime.TryParse(invoiceDateEnd.Value, out endDate)
                    ? endDate
                    : DateTime.MaxValue;

            var invoices = _merchello.Query.Invoice.Search(
                startDate,
                endDate,
                1,
                long.MaxValue,
                query.SortBy,
                query.SortDirection);


            var result = new QueryResultDisplay();

            if (!invoices.Items.Any())
            {
                return(result);
            }
            else
            {
                //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.Name == "Paid"
                             group invoiceItem by invoiceItem.InvoiceDate.Date
                             into g
                             orderby g.Key descending
                             select
                             new
                {
                    date       = g.Key.ToString("MMMM dd, yyyy"),
                    salestotal = g.Sum <InvoiceDisplay>((Func <InvoiceDisplay, decimal>)(item => item.Total)),
                    salescount = g.Count <InvoiceDisplay>()
                };

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

                return(result);
            }
        }
        public HttpResponseMessage GetOrderReportData(QueryDisplay query)
        {
            HttpResponseMessage result = null;

            var invoiceDateStart = query.Parameters.FirstOrDefault(x => x.FieldName == "invoiceDateStart");
            var invoiceDateEnd   = query.Parameters.FirstOrDefault(x => x.FieldName == "invoiceDateEnd");

            DateTime dtStart;
            DateTime dtEnd;

            if (invoiceDateStart == null)
            {
                result = Request.CreateErrorResponse(HttpStatusCode.BadRequest, "invoiceDateStart is a required parameter");
                return(result);
            }

            var settings   = _storeSettingService.GetAll().ToList();
            var dateFormat = settings.FirstOrDefault(s => s.Name == "dateFormat");

            if (dateFormat == null)
            {
                if (!DateTime.TryParse(invoiceDateStart.Value, out dtStart))
                {
                    result = Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Failed to convert invoiceDateStart to a valid DateTime");
                    return(result);
                }
            }
            else if (!DateTime.TryParseExact(invoiceDateStart.Value, dateFormat.Value, CultureInfo.InvariantCulture, DateTimeStyles.None, out dtStart))
            {
                result = Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Failed to convert invoiceDateStart to a valid DateTime");
                return(result);
            }

            dtEnd = invoiceDateEnd == null || dateFormat == null
                ? DateTime.MaxValue
                : DateTime.TryParseExact(invoiceDateEnd.Value, dateFormat.Value, CultureInfo.InvariantCulture, DateTimeStyles.None, out dtEnd)
                    ? dtEnd.AddDays(1) // through end of day
                    : DateTime.MaxValue;

            var invoices = _invoiceService.GetInvoicesByDateRange(dtStart, dtEnd).ToArray();

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

                    csvExport["Invoice Number"]   = invoice.InvoiceNumber;
                    csvExport["PO Number"]        = invoice.PoNumber;
                    csvExport["Order 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;
                            }
                        }
                    }
                }

                result         = Request.CreateResponse(HttpStatusCode.OK);
                result.Content = new StreamContent(csvExport.ExportToStream());
                result.Content.Headers.ContentType        = new MediaTypeHeaderValue("text/csv");
                result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = "Orders.csv"
                };
            }
            catch (SystemException ex)
            {
                result = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
                return(result);
            }

            return(result);
        }
示例#22
0
        public QueryResultDisplay SearchInvoices(QueryDisplay query)
        {
            var term             = query.Parameters.FirstOrDefault(x => x.FieldName == "term");
            var invoiceDateStart = query.Parameters.FirstOrDefault(x => x.FieldName == "invoiceDateStart");
            var invoiceDateEnd   = query.Parameters.FirstOrDefault(x => x.FieldName == "invoiceDateEnd");

            var isTermSearch = term != null && !string.IsNullOrEmpty(term.Value);

            var isDateSearch = invoiceDateStart != null && !string.IsNullOrEmpty(invoiceDateStart.Value);

            var startDate = DateTime.MinValue;
            var endDate   = DateTime.MaxValue;

            if (isDateSearch)
            {
                var settings   = _storeSettingService.GetAll().ToList();
                var dateFormat = settings.FirstOrDefault(s => s.Name == "dateFormat");

                if (dateFormat == null)
                {
                    if (!DateTime.TryParse(invoiceDateStart.Value, out startDate))
                    {
                        MultiLogHelper.Warn <InvoiceApiController>(string.Format("Was unable to parse startDate: {0}", invoiceDateStart.Value));
                        startDate = DateTime.MinValue;
                    }
                }
                else if (!DateTime.TryParseExact(invoiceDateStart.Value, dateFormat.Value, CultureInfo.InvariantCulture, DateTimeStyles.None, out startDate))
                {
                    MultiLogHelper.Warn <InvoiceApiController>(string.Format("Was unable to parse startDate: {0}", invoiceDateStart.Value));
                    startDate = DateTime.MinValue;
                }

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


            if (isTermSearch && isDateSearch)
            {
                return(_merchello.Query.Invoice.Search(
                           term.Value,
                           startDate,
                           endDate,
                           query.CurrentPage + 1,
                           query.ItemsPerPage,
                           query.SortBy,
                           query.SortDirection));
            }

            if (isTermSearch)
            {
                return(this._merchello.Query.Invoice.Search(
                           term.Value,
                           query.CurrentPage + 1,
                           query.ItemsPerPage,
                           query.SortBy,
                           query.SortDirection));
            }

            if (isDateSearch)
            {
                return(this._merchello.Query.Invoice.Search(
                           startDate,
                           endDate,
                           query.CurrentPage + 1,
                           query.ItemsPerPage,
                           query.SortBy,
                           query.SortDirection));
            }

            return(this._merchello.Query.Invoice.Search(
                       query.CurrentPage + 1,
                       query.ItemsPerPage,
                       query.SortBy,
                       query.SortDirection));
        }
        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);
        }