import React from 'react'; import superagent from 'superagent'; import cookie, { load } from 'react-cookies'; import constants, { DEFAULT_TIMEZONE } from '../CloudApi/Constants.js'; import { Segment, Form, Button, Icon, Pagination, Label, FormField, Grid, List, Header } from 'semantic-ui-react'; import { DateInput } from 'semantic-ui-calendar-react'; import * as ApiUtils from '../CloudApi/ApiUtils.js'; const RECENTS_STORAGE_KEY = "bigorders_query_full_recents"; const MAX_RECENTS = 5; export default class BigOrdersQuery extends React.Component { constructor(props) { super(props); this.state = { query: { origin: "Shopify" }, limit: props.limit || 50, offset: 0, loading: true, recents: [] }; } loadRecentsFromStorage() { try { const stored = localStorage.getItem(RECENTS_STORAGE_KEY); if (stored) { return JSON.parse(stored); } } catch (e) { console.log("Error loading recents from storage:", e); } return []; } saveRecentsToStorage(recents) { try { localStorage.setItem(RECENTS_STORAGE_KEY, JSON.stringify(recents)); } catch (e) { console.log("Error saving recents to storage:", e); } } generateRecentName(query, shopifySchemas) { const parts = []; // Add date range if present if (query.shopifyMinCreatedAt || query.shopifyMaxCreatedAt) { const formatDate = (dateStr) => { if (!dateStr) return null; const date = new Date(dateStr); return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }); }; const minDate = formatDate(query.shopifyMinCreatedAt); const maxDate = formatDate(query.shopifyMaxCreatedAt); if (minDate && maxDate) { parts.push(`${minDate} - ${maxDate}`); } else if (minDate) { parts.push(`After ${minDate}`); } else if (maxDate) { parts.push(`Before ${maxDate}`); } } // Add state if present if (query.state) { parts.push(query.state); } // Add country if present if (query.countryCode) { const country = constants.CountryOptions2.find(c => c.value === query.countryCode.toUpperCase()); parts.push(country ? country.text : query.countryCode); } // Add origin if not default if (query.origin && query.origin !== "Shopify") { parts.push(query.origin); } // Add IPD if present if (query.ipd) { parts.push(`IPD: ${query.ipd}`); } // Add product variants if present if (query.shopifyVariantIds && query.shopifyVariantIds.length > 0 && shopifySchemas) { const variantNames = query.shopifyVariantIds.map(id => { const variant = shopifySchemas.productVariants.find(v => v.value === id); return variant ? variant.text : id; }); if (variantNames.length === 1) { parts.push(variantNames[0]); } else { parts.push(`${variantNames.length} variants`); } } // Add email if present if (query.shopifyCustomerEmail) { parts.push(query.shopifyCustomerEmail); } // Add order number if present if (query.shopifyOrderName) { parts.push(`#${query.shopifyOrderName}`); } if (parts.length === 0) { return "All orders"; } return parts.slice(0, 3).join(" · ") + (parts.length > 3 ? " ..." : ""); } generateRecentDescription(query) { const details = []; if (query.minPriority) { details.push(`Priority ≥${query.minPriority}`); } if (query.shopifyVariantIds && query.shopifyVariantIds.length > 1) { details.push(`${query.shopifyVariantIds.length} product variants`); } return details.join(", "); } addToRecents(query) { // Don't save empty queries const hasFilters = Object.keys(query).some(key => key !== "origin" && query[key] && (Array.isArray(query[key]) ? query[key].length > 0 : true) ); if (!hasFilters) return; const name = this.generateRecentName(query, this.state.shopifySchemas); const description = this.generateRecentDescription(query); const newRecent = { id: Date.now(), name, description, query: { ...query }, timestamp: new Date().toISOString() }; // Remove duplicates (same query params) const queryKey = JSON.stringify(Object.keys(query).sort().reduce((obj, key) => { obj[key] = query[key]; return obj; }, {})); let recents = this.state.recents.filter(r => { const rKey = JSON.stringify(Object.keys(r.query).sort().reduce((obj, key) => { obj[key] = r.query[key]; return obj; }, {})); return rKey !== queryKey; }); recents.unshift(newRecent); recents = recents.slice(0, MAX_RECENTS); this.setState({ recents }); this.saveRecentsToStorage(recents); } removeFromRecents(recentId) { const recents = this.state.recents.filter(r => r.id !== recentId); this.setState({ recents }); this.saveRecentsToStorage(recents); } loadRecentQuery(recent) { const query = { ...recent.query }; this.setState({ query }, async () => { const params = this.getUrlSearchParams(); const newPathQuery = `${window.location.pathname}?${params.toString()}`; window.history.pushState(null, '', newPathQuery); await this.props.onQueryUpdated(params); }); } async componentDidMount() { try { const shopifySchemas = await ApiUtils.getShopifySchemas(); const recents = this.loadRecentsFromStorage(); const params = new URLSearchParams(window.location.search); const query = {}; for (const [key, value] of params.entries()) { if (key === "limit") { this.setState({ limit: value }); } else if (key === "offset") { this.setState({ offset: value }); } else if (key === "shopifyProductIds") { query[key] = value.split(","); } else { query[key] = value; } } console.log(query); this.setState({ query, shopifySchemas, recents, loading: false }); params.append("limit", this.state.limit); await this.props.onQueryUpdated(params); // Don't add to recents on initial page load - only when user makes changes } catch (e) { console.log(e); } } getUrlSearchParams() { const queryString = new URLSearchParams(); if (this.state.query) { for (const [key, value] of Object.entries(this.state.query)) { if (value === "" || value === null) continue; queryString.append(key, value); } } queryString.append("limit", this.state.limit); if (this.props.offset) { queryString.append("offset", this.props.offset); } return queryString; } onChange(e, { name, value }) { const query = this.state.query; if (value === "" || value === null) { console.log("delete", name, value); delete query[name]; } else { if (name === "state" && value === ApiUtils.ANY_VALUE) { delete query["state"]; } else if (name === "shopifyMinCreatedAt") { console.log(ApiUtils.CovertDateTimeToShopify(value)); query["shopifyMinCreatedAt"] = ApiUtils.CovertDateTimeToShopify(value); } else if (name === "shopifyMaxCreatedAt") { console.log(ApiUtils.CovertDateTimeToShopify(value)); query["shopifyMaxCreatedAt"] = ApiUtils.CovertDateTimeToShopify(value); } else if (name === "shopifyProductIds") { const currentProductIds = query["shopifyProductIds"] || []; if (currentProductIds.includes(value)) { currentProductIds.splice(currentProductIds.indexOf(value), 1); } else { currentProductIds.push(value); } query["shopifyProductIds"] = currentProductIds; } else { query[name] = value; } } this.setState({ query }, async () => { const params = this.getUrlSearchParams(); console.log(params.toString()); const newPathQuery = `${window.location.pathname}?${params.toString()}`; window.history.pushState(null, '', newPathQuery); await this.props.onQueryUpdated(params); // Save to recents after query executes this.addToRecents(this.state.query); }); } onClearValue(e, { name, value }) { const query = this.state.query; query[name] = ""; this.setState({ query }, this.onChange(e, {})); } render() { if (!this.props.schemas) return null; if (this.state.loading) { return false; } return ( {/* Main Query Form */}
} value={this.state.query.shopifyOrderName} onChange={this.onChange.bind(this)} /> } value={this.state.query.shopifyCustomerEmail} onChange={this.onChange.bind(this)} /> } value={this.state.query.minPriority} onChange={this.onChange.bind(this)} />
{/* Recents Sidebar */}
Recent Queries
{this.state.recents.length === 0 ? (

No recent queries

) : ( {this.state.recents.map(recent => ( this.removeFromRecents(recent.id)} title="Remove" /> this.loadRecentQuery(recent)} style={{ fontSize: '0.9em' }} > {recent.name} {recent.description && ( {recent.description} )} ))} )}
); } }