Skip to content

Add query rule search #148

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: feature/rule-based-filtering
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions lib/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,27 @@ const version = fs.existsSync(versionFile)
? fs.readFileSync(versionFile, "utf8")
: "0";
const axios = require("axios");
const ini = require("ini");

// Load query rules from queryrules.ini at startup
const queryRulesPath = path.join(__dirname, "queryrules.ini");
let queryRules = {};
if (fs.existsSync(queryRulesPath)) {
const parsed = ini.parse(fs.readFileSync(queryRulesPath, "utf8"));
for (const [name, rule] of Object.entries(parsed)) {
try {
queryRules[name] = {
chip: rule.Chip,
keywords: String(rule.Keywords || "")
.split(/,\s*/)
.filter(Boolean),
query: JSON.parse(rule.Query),
};
} catch (e) {
console.error(`Failed to parse query rule ${name}:`, e);
}
}
}

// Disabled for now because it causes confusion when we update the data
// const cache = {};
Expand Down Expand Up @@ -59,11 +80,31 @@ module.exports = async function ({ plants, nurseries }) {
});
return res.send(response.data);
});

// Provide query rules to the frontend
app.get("/api/v1/queryrules", (req, res) => {
res.json(queryRules);
});
app.get("/api/v1/plants", async (req, res) => {
try {
const fetchResults = req.query.results !== "0";
const fetchTotal = req.query.total !== "0";
const query = {};
const ruleChips = [];
const rulesParam = req.query.rules;
if (rulesParam) {
const names = Array.isArray(rulesParam)
? rulesParam
: String(rulesParam).split(/,/);
for (const name of names) {
const rule = queryRules[name];
if (rule) {
if (!query.$and) query.$and = [];
query.$and.push(rule.query);
ruleChips.push({ name, chip: rule.chip });
}
}
}
const sorts = {
"Sort by Common Name (A-Z)": {
"Common Name": 1,
Expand Down Expand Up @@ -437,6 +478,9 @@ module.exports = async function ({ plants, nurseries }) {
);
}
}
if (ruleChips.length) {
response.ruleChips = ruleChips;
}
// setCache(req, response);
return res.send(response);
} catch (e) {
Expand Down
78 changes: 67 additions & 11 deletions src/components/Explorer.vue
Original file line number Diff line number Diff line change
Expand Up @@ -862,6 +862,9 @@ export default {
total: 0,
q: "",
activeSearch: "",
queryRules: {},
appliedRules: [],
ruleChips: [],
sort: "Sort by Recommendation Score",
filters,
componentKey: 0, // Add a key for forcing re-renders
Expand Down Expand Up @@ -913,7 +916,18 @@ export default {
return extras;
},
chips() {
return this.getChips(true);
const chips = this.getChips(true);
if (this.ruleChips.length) {
for (const rc of this.ruleChips) {
chips.push({
name: rc.name,
label: rc.chip,
key: `rule:${rc.name}`,
svg: 'Search',
});
}
}
return chips;
},
flags() {
return this.getChips(false);
Expand Down Expand Up @@ -1024,6 +1038,15 @@ export default {
// Pick a random hero image after hydration to avoid SSR hydration mismatch
this.twoUpIndex = Math.floor(Math.random() * twoUpImageCredits.length);

// Fetch query rules used for keyword searches
try {
const resp = await fetch('/api/v1/queryrules');
this.queryRules = await resp.json();
} catch (e) {
console.error('Failed to fetch query rules', e);
this.queryRules = {};
}

this.displayLocation = localStorage.getItem("displayLocation") || "";
this.zipCode = localStorage.getItem("zipCode") || "";
this.manualZip = localStorage.getItem("manualZip") === "true";
Expand Down Expand Up @@ -1176,6 +1199,21 @@ export default {
this.manualZip = true;
localStorage.setItem("manualZip", "true")
},

detectRules() {
const matches = [];
if (!this.q || !this.queryRules) return matches;
const qLower = this.q.toLowerCase();
for (const [name, rule] of Object.entries(this.queryRules)) {
for (const kw of rule.keywords) {
if (qLower.includes(kw.toLowerCase())) {
matches.push(name);
break;
}
}
}
return matches;
},
async getVendors() {
if (!this.selected) return [];
const data = {
Expand Down Expand Up @@ -1330,6 +1368,12 @@ export default {
clearTimeout(this.submitTimeout);
this.submitTimeout = null;
}
const detected = this.detectRules();
if (detected.length) {
this.appliedRules = detected;
} else {
this.appliedRules = [];
}
this.submitTimeout = setTimeout(submit.bind(this), 50); // Reduced timeout for faster response

function submit() {
Expand Down Expand Up @@ -1370,19 +1414,23 @@ export default {
this.updatingCounts = true;
const doUpdate = async () => {
try {
const params = {
...this.filterValues,
q: this.q,
sort: this.sort,
};
const params = {
...this.filterValues,
...(this.appliedRules.length ? {} : { q: this.q }),
sort: this.sort,
};
if (this.initializing) {
resolve();
return;
}
if (this.appliedRules.length) {
params.rules = this.appliedRules;
}
const response = await fetch("/api/v1/plants?" + qs.stringify(params));
const data = await response.json();
this.filterCounts = data.counts;
this.activeSearch = this.q;
this.activeSearch = this.appliedRules.length ? "" : this.q;
this.ruleChips = data.ruleChips || [];
} finally {
this.updatingCounts = false;
resolve();
Expand Down Expand Up @@ -1412,17 +1460,21 @@ export default {
}
: {
...this.filterValues,
q: this.q,
...(this.appliedRules.length ? {} : { q: this.q }),
sort: this.sort,
page: this.page,
};
this.activeSearch = this.q;
if (this.appliedRules.length) {
params.rules = this.appliedRules;
}
this.activeSearch = this.appliedRules.length ? "" : this.q;
if (this.initializing) {
// Don't send a bogus query for min 0 max 0
delete params["Height (feet)"];
}
const response = await fetch("/api/v1/plants?" + qs.stringify(params));
const data = await response.json();
this.ruleChips = data.ruleChips || [];
if (!this.favorites) {
this.filterCounts = data.counts;
for (const filter of this.filters) {
Expand Down Expand Up @@ -1476,12 +1528,15 @@ export default {
if (chip.name === "Search") {
this.q = "";
} else {
if (chip.key && chip.key.startsWith('rule:')) {
this.appliedRules = this.appliedRules.filter((n) => n !== chip.name);
}
const filter = this.filters.find((filter) => filter.name === chip.name);
if (filter.array) {
if (filter && filter.array) {
this.filterValues[chip.name] = this.filterValues[chip.name].filter(
(value) => value !== chip.label
);
} else {
} else if (filter) {
this.filterValues[chip.name] = filter.default;
}
}
Expand All @@ -1492,6 +1547,7 @@ export default {
this.filterValues[filter.name] = filter.default;
}
this.q = "";
this.appliedRules = [];
this.submit();
},
toggleSort() {
Expand Down