[ADD] website_sale_stock_variant_preselect: preselect variant with stock - #482
Open
ALopez-Adhoc wants to merge 1 commit into
Open
[ADD] website_sale_stock_variant_preselect: preselect variant with stock#482ALopez-Adhoc wants to merge 1 commit into
ALopez-Adhoc wants to merge 1 commit into
Conversation
- Add product.template._get_first_available_combination, walking _get_possible_combinations in the configured attribute order and matching it against the set of variants that have stock - Override _get_combination_info to use it when the caller passed no combination, product_id nor only_template, guarded by the website_sale_preselect_available_variant context key - Override WebsiteSale._prepare_product_values to set that key on the product record only, so the shop grid and the website product blocks keep core behaviour - Resolve availability through website._get_product_available_qty, batched over product_variant_ids, to honour the website warehouse and the website_sale_collect session branch - Fall back to core when the template is not storable, allows out-of-stock orders, has a single variant, or when no variant has stock - Add the website_sale_stock_variant_preselect.enabled system parameter as an internal kill switch, enabled by default - Add tests for preselection, configured order, every fallback, the kill switch and both controller paths Change note: En la ficha de un producto con variantes, la tienda ahora abre mostrando una variante que tenga stock en lugar de la primera configurada. Antes, si la primera variante estaba agotada, la ficha se veía como sin stock y muchos visitantes creian que todo el producto lo estaba, aunque hubiera otros talles o colores disponibles. Si el visitante elige atributos, se respeta siempre su eleccion, y el listado de la tienda no cambia.
Contributor
There was a problem hiding this comment.
🟡 Changes recommended
Hay ajustes menores pero concretos por resolver (robustez del helper de tests y consistencia de metadatos en el manifest) antes de aprobar.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Pull request overview
Este PR agrega el módulo website_sale_stock_variant_preselect para mejorar la UX en la ficha de producto con variantes: cuando el visitante entra sin seleccionar atributos, se preselecciona la primera combinación con stock respetando el orden configurado de atributos, y si ninguna tiene stock se mantiene el comportamiento estándar.
Changes:
- Override de
product.template._get_combination_info()para usar una combinación “stock-aware” solo cuando el controller lo solicita por contexto. - Implementación de
_get_first_available_combination()para elegir la primera variante disponible según el orden de atributos. - Suite de tests (9 casos) que valida preselección, fallback a core, kill-switch y respeto de
attribute_values.
File summaries
| File | Description |
|---|---|
| website_sale_stock_variant_preselect/models/product_template.py | Lógica principal de preselección por stock y kill-switch vía ir.config_parameter. |
| website_sale_stock_variant_preselect/controllers/main.py | Inyecta el contexto para limitar el comportamiento a la ficha de producto. |
| website_sale_stock_variant_preselect/tests/test_variant_preselect.py | Casos de prueba para validar preselección, fallback y control por parámetro/contexto. |
| website_sale_stock_variant_preselect/tests/init.py | Registro del módulo de tests. |
| website_sale_stock_variant_preselect/models/init.py | Registro de modelos. |
| website_sale_stock_variant_preselect/controllers/init.py | Registro de controllers. |
| website_sale_stock_variant_preselect/manifest.py | Manifest del nuevo módulo y dependencia con website_sale_stock. |
| website_sale_stock_variant_preselect/init.py | Carga de controllers y models del módulo. |
Review details
- Files reviewed: 8/8 changed files
- Comments generated: 2
- Review effort level: Lite
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
Comment on lines
+21
to
+25
| "name": "Website Sale Stock Variant Preselect", | ||
| "version": "19.0.1.0.0", | ||
| "author": "ADHOC SA", | ||
| "website": "www.adhoc.com.ar", | ||
| "license": "AGPL-3", |
Comment on lines
+62
to
+66
| @classmethod | ||
| def _variant_for(cls, attribute_value): | ||
| return cls.product.product_variant_ids.filtered( | ||
| lambda variant: attribute_value in variant.product_template_attribute_value_ids.product_attribute_value_id | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.

Nuevo módulo
website_sale_stock_variant_preselect.Problema
En la ficha de un producto con variantes, cuando el visitante entra sin elegir atributos, Odoo preselecciona siempre la primera combinación en el orden de configuración (
_get_first_possible_combination), sin mirar stock. Si esa primera variante está agotada, la ficha se renderiza como sin stock y el visitante puede creer que todo el producto lo está, aunque haya otros talles o colores disponibles.Solución
Cuando la ficha resuelve la combinación por defecto, se prefiere la primera variante con stock siguiendo el mismo orden configurado de atributos. Si ninguna tiene stock, se mantiene el comportamiento actual.
Diseño
product.template._get_first_available_combination()recorre_get_possible_combinations()—que respeta el orden deattribute_line_idsy sus valores, el mismo que ve el visitante en el selector— y lo cruza contra el conjunto de variantes con stock. No se usa el orden deproduct_variant_ids, cuyo_order(default_code, name, id) no tiene relación con el orden configurado.website._get_product_available_qty(), no leyendofree_qtydirecto: así se respetan el almacén del sitio y la sucursal de sesión dewebsite_sale_collect. El cálculo se batchea sobreproduct_variant_idsaprovechando el prefetch del recordset, de modo que_compute_quantities_dictse resuelve en un_read_groupy no en una query por variante._get_combination_info, pero acotado por contexto: el controller marcawebsite_sale_preselect_available_variantsobre el registro del producto, no sobre el request. Así llega solo al_get_combination_info()de la ficha y no al del listado ni al de los bloques de producto del sitio, que quedan con el comportamiento de core. Es el mismo patrón que usawebsite_sale_stockconwebsite_sale_stock_get_quantity.allow_out_of_stock_orderactivo (que es el default), una sola variante, o ninguna variante con stock.website_sale_ux, que hoy depende solo dewebsite_sale: sumarlewebsite_sale_stockle impondría stock a todos los que ya lo usan.website_sale_stock_variant_preselect.enabled, encendido por default, como interruptor interno para apagarlo en una base puntual sin esperar un release. No se expone en ninguna pantalla de configuración: no es una opción del cliente.Test plan
tests/test_variant_preselect.py, 9 casos sobreWebsiteSaleStockCommon(producto de tres talles, stock solo en el segundo):allow_out_of_stock_ordery con templates no almacenablesFalserestaura el comportamiento de coreattribute_valuesexplícitoProbado además contra una base local: la ficha renderiza el radio de la variante con stock ya marcado en el primer response HTML, sin round-trip JS.
Tarea: https://www.adhoc.inc/odoo/project.task/72834