fix search and filtering for /busqueda

This commit is contained in:
2025-10-10 15:00:36 +02:00
parent 987c388bff
commit 894546a901
2 changed files with 77 additions and 180 deletions

View File

@@ -38,9 +38,9 @@
<ClientOnly> <ClientOnly>
<v-range-slider <v-range-slider
v-model="priceRange" v-model="priceRange"
:min="0" :min="minPrice"
:max="500" :max="maxPrice"
step="10" step="5"
thumb-label="always" thumb-label="always"
color="#143E8C" color="#143E8C"
track-color="#d6d5d5" track-color="#d6d5d5"
@@ -120,15 +120,17 @@
</template> </template>
<script> <script>
export default { export default {
props: { props: {
filters: { maxPrice: {
type: Object, type: Number,
default: () => ({}), default: 500,
}, },
prices: { minPrice: {
type: Object, type: Number,
default: () => ({}), default: 0,
}, },
currentFilters: { currentFilters: {
type: Object, type: Object,
@@ -144,10 +146,6 @@ export default {
data() { data() {
return { return {
// filterForm: {
// shipping_cost: false,
// discount: false,
// },
screenSize: null, screenSize: null,
visible: true, visible: true,
checkedCategories: [], checkedCategories: [],
@@ -167,7 +165,7 @@ export default {
"Finanzas Éticas y Seguros", "Finanzas Éticas y Seguros",
"Servicios Profesionales", "Servicios Profesionales",
], ],
priceRange: [0, 500], priceRange: [this.minPrice, this.maxPrice],
priceRangeFilter: {}, priceRangeFilter: {},
place: null, place: null,
coordinates: null, coordinates: null,
@@ -188,24 +186,25 @@ export default {
} else { } else {
this.checkedCategories = []; this.checkedCategories = [];
} }
// if (Object.keys(newCurrentFilters).includes("shipping_cost")) { if (newCurrentFilters["price_min"] && newCurrentFilters["price_max"]) {
// this.filterForm.shipping_cost = true; this.priceRange = [newCurrentFilters["price_min"], newCurrentFilters["price_max"]];
// } else { }
// this.filterForm.shipping_cost = false; else if (newCurrentFilters["price_min"] && !newCurrentFilters["price_max"]) {
// } this.priceRange = [newCurrentFilters["price_min"], this.maxPrice];
}
else if (!newCurrentFilters["price_min"] && newCurrentFilters["price_max"]) {
this.priceRange = [this.minPrice, newCurrentFilters["price_max"]];
}
else {
this.priceRange = [this.minPrice, this.maxPrice];
} }
//this.filterForm.discount = this.$route.query.hasOwnProperty("discount");
},
prices(newPrices) {
if (newPrices.min && newPrices.max) {
this.priceRange = [newPrices.min, newPrices.max];
} }
}, },
}, },
mounted() { mounted() {
if (this.prices.min && this.prices.max) { if (this.currentFilters?.price_min && this.currentFilters?.price_max) {
this.priceRange = [this.prices.min, this.prices.max]; this.priceRange = [this.currentFilters.price_min, this.currentFilters.prices_max];
} }
this.screenSize = window.innerWidth; this.screenSize = window.innerWidth;
window.addEventListener("resize", () => { window.addEventListener("resize", () => {
@@ -224,17 +223,7 @@ export default {
}, },
applyFilters() { applyFilters() {
const filters = {}; this.$emit("applyFilters", { category: [...this.checkedCategories], price_min: this.priceRange[0], price_max: this.priceRange[1] });
filters.price_min = this.priceRange[0];
filters.price_max = this.priceRange[1];
//if (this.filterForm.shipping_cost) filters.shipping_cost = false;
//if (this.filterForm.discount) filters.discount = true;
filters.category = this.checkedCategories;
if (this.place) {
filters.latitude = this.place.geo.latitude;
filters.longitude = this.place.geo.longitude;
}
this.$emit("applyFilters", filters);
}, },
}, },
}; };
@@ -361,7 +350,6 @@ export default {
gap: 1rem; gap: 1rem;
} }
.form-check-input { .form-check-input {
&:checked { &:checked {
background-color: $color-button; background-color: $color-button;
} }

View File

@@ -17,14 +17,14 @@
type="text" type="text"
autocomplete="off" autocomplete="off"
placeholder="Encuentra productos o servicios" placeholder="Encuentra productos o servicios"
/> >
<div class="search-link"> <div class="search-link">
<img <img
class="search-icon" class="search-icon"
src="@/assets/img/latienda-search.svg" src="@/assets/img/latienda-search.svg"
alt="consumo-cuidado-search" alt="consumo-cuidado-search"
@click="search" @click="search"
/> >
</div> </div>
</form> </form>
</div> </div>
@@ -34,9 +34,9 @@
<div class="c-container"> <div class="c-container">
<div class="col-md-3"> <div class="col-md-3">
<ProductFilter <ProductFilter
:filters="filters"
:current-filters="currentFilters" :current-filters="currentFilters"
:prices="prices" :max_price="MAX_PRICE"
:min_price="MIN_PRICE"
:geo="coordinates" :geo="coordinates"
@apply-filters="updateData" @apply-filters="updateData"
/> />
@@ -62,7 +62,7 @@
<div v-if="count > 0" class="carousel"> <div v-if="count > 0" class="carousel">
<div class="title-container"> <div class="title-container">
<h5 class="items-title">Últimos productos y servicios</h5> <h5 class="items-title">Últimos productos y servicios</h5>
<div class="title-lines"></div> <div class="title-lines"/>
</div> </div>
<ItemsRow class="items" :type="`product`" :items="carouselProducts.results" :items-to-show="3" /> <ItemsRow class="items" :type="`product`" :items="carouselProducts.results" :items-to-show="3" />
</div> </div>
@@ -104,7 +104,7 @@
<div class="results"> <div class="results">
<div class="title-container"> <div class="title-container">
<h5 class="items-title">Catálogo</h5> <h5 class="items-title">Catálogo</h5>
<div class="title-lines"></div> <div class="title-lines"/>
</div> </div>
<p class="count">Resultados de búsqueda: {{ count }} resultados</p> <p class="count">Resultados de búsqueda: {{ count }} resultados</p>
<div v-if="products.length !== 0"> <div v-if="products.length !== 0">
@@ -128,23 +128,11 @@
Prueba un término más general, revisa la ortografía o Prueba un término más general, revisa la ortografía o
<span class="link" @click="clearFilters">limpia los filtros</span>. <span class="link" @click="clearFilters">limpia los filtros</span>.
</p> </p>
<!-- <div v-for="product in defaultProducts" :key="product.id">
<ProductCard :key="product.key" :product="product" />
</div> -->
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<!-- appliedFilters: {{appliedFilters}} <br>
filters: {{filters}} <br>
prices: {{prices}} <br>
coordinates: {{coordinates}} <br>
products: {{products}} <br>
defaultProducts: {{defaultProducts}} <br>
carouselProducts: {{carouselProducts}} <br>
count: {{count}} -->
</template> </template>
<script> <script>
@@ -174,46 +162,35 @@ export default {
previousParams: null, previousParams: null,
currentFilters: null, currentFilters: null,
mountedProducts: [], mountedProducts: [],
appliedFilters: {},
filters: {}, filters: {},
prices: { min: null, max: null }, MAX_PRICE: 500,
MIN_PRICE: 0,
coordinates: null, coordinates: null,
products: [], products: [],
defaultProducts: [],
carouselProducts: [], carouselProducts: [],
count: 0, count: 0,
loadingProducts: true, loadingProducts: true,
} }
}, },
computed: { // watch: {
hasFilterTags() { // '$route.query'(newValue) {
if (!this.appliedFilters) return false // console.log('New Value:', newValue)
return ( // //console.log('Route changed:', this.$route.fullPath)
Object.keys(this.appliedFilters).includes('shipping_cost') || // //console.log('Current params:', this.$route.query)
Object.keys(this.appliedFilters).includes('discount') || // this.queryText = newValue.q
(Array.isArray(this.appliedFilters.category) && // console.log('Updated queryText:', this.queryText)
this.appliedFilters.category.length > 0) // this.updateData(newValue)
) // //Object.assign(this.$data, this.$options.data())
} // }
}, // },
watch: {
'$route.query'(newValue) {
console.log('New Value:', newValue)
//console.log('Route changed:', this.$route.fullPath)
//console.log('Current params:', this.$route.query)
this.queryText = newValue.q
console.log('Updated queryText:', this.queryText)
this.updateData(newValue)
//Object.assign(this.$data, this.$options.data())
}
},
async beforeCreate() { async beforeCreate() {
const config = useRuntimeConfig() const config = useRuntimeConfig()
const params = import.meta.client ? clientSearch(this.$route.query) : serverSearch(this.$route.query) const params = import.meta.client ? clientSearch(this.$route.query) : serverSearch(this.$route.query)
console.log('Initial params:', params);
const data = await $fetch(`/search_products/?`, { const data = await $fetch(`/search_products/?`, {
baseURL: config.public.baseURL, baseURL: config.public.baseURL,
method: 'GET', method: 'GET',
@@ -222,28 +199,9 @@ export default {
Authorization: '/', Authorization: '/',
}, },
}) })
//console.log('data', data)
const products = data.products const products = data.products
//console.log('products', products)
let defaultProducts = []
if (products.length === 0) {
//console.log('no products, fetching default')
const data = await $fetch(`/search_products/?q=${params.q}`, {
baseURL: config.public.baseURL,
method: 'GET',
params: {
order: 'newest',
limit: 10,
offset: 0
},
headers: {
Authorization: '/',
},
})
defaultProducts = data.products
}
// Productos para el carrusel
const carouselProducts = await $fetch(`/products/`, { const carouselProducts = await $fetch(`/products/`, {
baseURL: config.public.baseURL, baseURL: config.public.baseURL,
method: 'GET', method: 'GET',
@@ -255,8 +213,8 @@ export default {
Authorization: '/', Authorization: '/',
}, },
}) })
//console.log('carouselProducts', carouselProducts)
// Pasar filtros aplicados a las variables de estado que usan los componentes de filtros
let coordinates let coordinates
if (params.latitude && params.longitude) { if (params.latitude && params.longitude) {
coordinates = { coordinates = {
@@ -264,33 +222,25 @@ export default {
lng: Number(params.longitude), lng: Number(params.longitude),
} }
} }
// let prices
let prices // if (params.price_min || params.price_max) {
if (params.price_min || params.price_max) { // prices = { max: params.price_max, min: params.price_min }
prices = { max: params.price_max, min: params.price_min } // } else if (data.prices.min || data.prices.max) {
} else if (data.prices.min || data.prices.max) { // prices = data.prices
prices = data.prices // } else {
} else { // prices = { max: null, min: null }
prices = { max: null, min: null } // }
} this.searchText = params.q
this.currentFilters = { category: params.category, q: params.q, price_min: params.price_min, price_max: params.price_max }
this.appliedFilters = params.q
console.log('Initial appliedFilters:', this.appliedFilters)
this.filters = data.filters this.filters = data.filters
this.prices = prices
this.coordinates = coordinates this.coordinates = coordinates
this.products = products this.products = products
this.defaultProducts = defaultProducts
this.carouselProducts = carouselProducts this.carouselProducts = carouselProducts
this.count = data.count this.count = data.count
this.loadingProducts = false this.loadingProducts = false
}, },
mounted() {
this.currentFilters = this.appliedFilters
},
methods: { methods: {
async handlePageChange(value) { async handlePageChange(value) {
const offset = (value - 1) * this.perPage const offset = (value - 1) * this.perPage
@@ -303,7 +253,7 @@ export default {
baseURL: config.public.baseURL, baseURL: config.public.baseURL,
method: 'GET', method: 'GET',
params: { params: {
...this.appliedFilters, ...this.currentFilters,
limit: 10, limit: 10,
offset: offset offset: offset
}, },
@@ -315,11 +265,16 @@ export default {
}, },
async updateData(value) { async updateData(value) {
//console.log('updateData called with:', value) this.loadingProducts = true
const filters = { q: this.appliedFilters.q }
const query = Object.keys(value).length === 0 ? { ...filters } : { ...value, ...filters } // Actualizar filtros aplicados
const query = {};
if (this.searchText) query['q'] = this.searchText;
if (value.q) query['q'] = value.q;
if (value.category) query['category'] = value.category;
if (value.price_min > this.MIN_PRICE) query['price_min'] = value.price_min;
if (value.price_max < this.MAX_PRICE) query['price_max'] = value.price_max;
//console.log('Navigating to busqueda with query:', query)
this.$router.push({ name: 'busqueda', query }) this.$router.push({ name: 'busqueda', query })
const config = useRuntimeConfig() const config = useRuntimeConfig()
@@ -334,65 +289,19 @@ export default {
this.loadingProducts = false this.loadingProducts = false
}, },
removeCategory(cat) {
this.currentFilters = this.appliedFilters
const categoryArray = this.currentFilters.category
const newCats = []
categoryArray.forEach((element) => {
if (element !== cat) {
newCats.push(element)
}
})
this.currentFilters.category = newCats
const noCategory = {}
Object.entries(this.currentFilters).forEach(([key, value]) => {
if (key !== 'category') {
noCategory[key] = value
}
})
if (newCats.length === 0) {
return this.$router.push({
path: this.$route.path,
query: { ...noCategory },
})
} else {
return this.$router.push({
path: this.$route.path,
query: { category: newCats, ...noCategory },
})
}
},
removeFilter(filter) {
this.currentFilters = { ...this.appliedFilters }
this.currentFilters = Object.fromEntries(
Object.entries(this.currentFilters).filter(([key]) => key !== filter)
)
return this.$router.push({
name: 'busqueda',
query: { ...this.currentFilters },
})
},
async search() { async search() {
this.currentFilters = { ...this.appliedFilters } this.currentFilters = {}
console.log('Searching for:', this.searchText) await this.updateData({ q: this.searchText })
if (this.searchText) {
this.appliedFilters = this.searchText
this.products = await this.updateData({ q: this.searchText })
}
}, },
clearFilters() { clearFilters() {
this.currentFilters = null this.currentFilters = {}
this.appliedFilters = null this.searchText = ''
this.queryText = '' this.queryText = ''
this.$router.push({ this.$router.push({
name: 'busqueda' name: 'busqueda', query: {}
}) })
this.updateData({})
}, },
}, },
} }