Compare commits

..

3 commits

Author SHA1 Message Date
GitHub Copilot
9a9139711f change order in basket assembly view 2026-06-04 13:53:16 +02:00
GitHub Copilot
d35c3383b2 [FIX] product_sale_price_from_pricelist: apply supplier discounts from supplierinfo
The sale price was computed from a gross last_purchase_price_received when
the product relied on its supplierinfo (no stock receipt), ignoring the
vendor discounts even with last_purchase_price_compute_type set.

Sync last_purchase_price_received from the main vendor's supplierinfo on
create/write, applying its discounts according to compute_type (mirrors the
stock.move receipt logic): without_discounts keeps the gross price, with_*
discounts apply 1/2/all three, manual_update is left untouched. The
theoretical price is refreshed (and last_purchase_price_updated flagged)
without overwriting lst_price until the user confirms.

Also drop the redundant _compute_price_rule call in _compute_theoritical_price
by asking the pricelist for the price directly instead of going through
_get_price (which computed the price twice).

Add purchase_triple_discount as an explicit dependency and tests covering
every discount type, manual_update, write re-sync and the main-vendor rule.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 13:51:48 +02:00
GitHub Copilot
9a7dfe02db [ADD] Claude Code ecosystem adapted from Copilot config
Port .github Copilot setup to Claude Code:
- CLAUDE.md: condensed project instructions (auto-loaded each session)
- .claude/skills: per-language guides (odoo-python, odoo-xml-views,
  odoo-qweb-html, odoo-javascript) + openspec-* workflow skills
- .claude/commands/opsx: /opsx:explore|propose|apply|archive slash commands

Original .github/ files kept untouched as extended reference.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 13:29:10 +02:00
22 changed files with 1776 additions and 240 deletions

View file

@ -0,0 +1,149 @@
---
description: Implement tasks from an OpenSpec change (Experimental)
---
Implement tasks from an OpenSpec change.
**Input**: Optionally specify a change name (e.g., `/opsx:apply add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes and use the **AskUserQuestion tool** to let the user select
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:apply <other>`).
2. **Check status to understand the schema**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand:
- `schemaName`: The workflow being used (e.g., "spec-driven")
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
3. **Get apply instructions**
```bash
openspec instructions apply --change "<name>" --json
```
This returns:
- Context file paths (varies by schema)
- Progress (total, complete, remaining)
- Task list with status
- Dynamic instruction based on current state
**Handle states:**
- If `state: "blocked"` (missing artifacts): show message, suggest using `/opsx:continue`
- If `state: "all_done"`: congratulate, suggest archive
- Otherwise: proceed to implementation
4. **Read context files**
Read the files listed in `contextFiles` from the apply instructions output.
The files depend on the schema being used:
- **spec-driven**: proposal, specs, design, tasks
- Other schemas: follow the contextFiles from CLI output
5. **Show current progress**
Display:
- Schema being used
- Progress: "N/M tasks complete"
- Remaining tasks overview
- Dynamic instruction from CLI
6. **Implement tasks (loop until done or blocked)**
For each pending task:
- Show which task is being worked on
- Make the code changes required
- Keep changes minimal and focused
- Mark task complete in the tasks file: `- [ ]``- [x]`
- Continue to next task
**Pause if:**
- Task is unclear → ask for clarification
- Implementation reveals a design issue → suggest updating artifacts
- Error or blocker encountered → report and wait for guidance
- User interrupts
7. **On completion or pause, show status**
Display:
- Tasks completed this session
- Overall progress: "N/M tasks complete"
- If all done: suggest archive
- If paused: explain why and wait for guidance
**Output During Implementation**
```
## Implementing: <change-name> (schema: <schema-name>)
Working on task 3/7: <task description>
[...implementation happening...]
✓ Task complete
Working on task 4/7: <task description>
[...implementation happening...]
✓ Task complete
```
**Output On Completion**
```
## Implementation Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 7/7 tasks complete ✓
### Completed This Session
- [x] Task 1
- [x] Task 2
...
All tasks complete! You can archive this change with `/opsx:archive`.
```
**Output On Pause (Issue Encountered)**
```
## Implementation Paused
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 4/7 tasks complete
### Issue Encountered
<description of the issue>
**Options:**
1. <option 1>
2. <option 2>
3. Other approach
What would you like to do?
```
**Guardrails**
- Keep going through tasks until done or blocked
- Always read context files before starting (from the apply instructions output)
- If task is ambiguous, pause and ask before implementing
- If implementation reveals issues, pause and suggest artifact updates
- Keep code changes minimal and scoped to each task
- Update task checkbox immediately after completing each task
- Pause on errors, blockers, or unclear requirements - don't guess
- Use contextFiles from CLI output, don't assume specific file names
**Fluid Workflow Integration**
This skill supports the "actions on a change" model:
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly

View file

@ -0,0 +1,154 @@
---
description: Archive a completed change in the experimental workflow
---
Archive a completed change in the experimental workflow.
**Input**: Optionally specify a change name after `/opsx:archive` (e.g., `/opsx:archive add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **If no change name provided, prompt for selection**
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
Show only active changes (not already archived).
Include the schema used for each change if available.
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
2. **Check artifact completion status**
Run `openspec status --change "<name>" --json` to check artifact completion.
Parse the JSON to understand:
- `schemaName`: The workflow being used
- `artifacts`: List of artifacts with their status (`done` or other)
**If any artifacts are not `done`:**
- Display warning listing incomplete artifacts
- Prompt user for confirmation to continue
- Proceed if user confirms
3. **Check task completion status**
Read the tasks file (typically `tasks.md`) to check for incomplete tasks.
Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).
**If incomplete tasks found:**
- Display warning showing count of incomplete tasks
- Prompt user for confirmation to continue
- Proceed if user confirms
**If no tasks file exists:** Proceed without task-related warning.
4. **Assess delta spec sync state**
Check for delta specs at `openspec/changes/<name>/specs/`. If none exist, proceed without sync prompt.
**If delta specs exist:**
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
- Determine what changes would be applied (adds, modifications, removals, renames)
- Show a combined summary before prompting
**Prompt options:**
- If changes needed: "Sync now (recommended)", "Archive without syncing"
- If already synced: "Archive now", "Sync anyway", "Cancel"
If user chooses sync, use Task tool (subagent_type: "general-purpose", prompt: "Use Skill tool to invoke openspec-sync-specs for change '<name>'. Delta spec analysis: <include the analyzed delta spec summary>"). Proceed to archive regardless of choice.
5. **Perform the archive**
Create the archive directory if it doesn't exist:
```bash
mkdir -p openspec/changes/archive
```
Generate target name using current date: `YYYY-MM-DD-<change-name>`
**Check if target already exists:**
- If yes: Fail with error, suggest renaming existing archive or using different date
- If no: Move the change directory to archive
```bash
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>
```
6. **Display summary**
Show archive completion summary including:
- Change name
- Schema that was used
- Archive location
- Spec sync status (synced / sync skipped / no delta specs)
- Note about any warnings (incomplete artifacts/tasks)
**Output On Success**
```
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** ✓ Synced to main specs
All artifacts complete. All tasks complete.
```
**Output On Success (No Delta Specs)**
```
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** No delta specs
All artifacts complete. All tasks complete.
```
**Output On Success With Warnings**
```
## Archive Complete (with warnings)
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** Sync skipped (user chose to skip)
**Warnings:**
- Archived with 2 incomplete artifacts
- Archived with 3 incomplete tasks
- Delta spec sync was skipped (user chose to skip)
Review the archive if this was not intentional.
```
**Output On Error (Archive Exists)**
```
## Archive Failed
**Change:** <change-name>
**Target:** openspec/changes/archive/YYYY-MM-DD-<name>/
Target archive directory already exists.
**Options:**
1. Rename the existing archive
2. Delete the existing archive if it's a duplicate
3. Wait until a different date to archive
```
**Guardrails**
- Always prompt for change selection if not provided
- Use artifact graph (openspec status --json) for completion checking
- Don't block archive on warnings - just inform and confirm
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
- Show clear summary of what happened
- If sync is requested, use the Skill tool to invoke `openspec-sync-specs` (agent-driven)
- If delta specs exist, always run the sync assessment and show the combined summary before prompting

View file

@ -0,0 +1,170 @@
---
description: Enter explore mode - think through ideas, investigate problems, clarify requirements
---
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing.
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
**Input**: The argument after `/opsx:explore` is whatever the user wants to think about. Could be:
- A vague idea: "real-time collaboration"
- A specific problem: "the auth system is getting unwieldy"
- A change name: "add-dark-mode" (to explore in context of that change)
- A comparison: "postgres vs sqlite for this"
- Nothing (just enter explore mode)
---
## The Stance
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
- **Adaptive** - Follow interesting threads, pivot when new information emerges
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
---
## What You Might Do
Depending on what the user brings, you might:
**Explore the problem space**
- Ask clarifying questions that emerge from what they said
- Challenge assumptions
- Reframe the problem
- Find analogies
**Investigate the codebase**
- Map existing architecture relevant to the discussion
- Find integration points
- Identify patterns already in use
- Surface hidden complexity
**Compare options**
- Brainstorm multiple approaches
- Build comparison tables
- Sketch tradeoffs
- Recommend a path (if asked)
**Visualize**
```
┌─────────────────────────────────────────┐
│ Use ASCII diagrams liberally │
├─────────────────────────────────────────┤
│ │
│ ┌────────┐ ┌────────┐ │
│ │ State │────────▶│ State │ │
│ │ A │ │ B │ │
│ └────────┘ └────────┘ │
│ │
│ System diagrams, state machines, │
│ data flows, architecture sketches, │
│ dependency graphs, comparison tables │
│ │
└─────────────────────────────────────────┘
```
**Surface risks and unknowns**
- Identify what could go wrong
- Find gaps in understanding
- Suggest spikes or investigations
---
## OpenSpec Awareness
You have full context of the OpenSpec system. Use it naturally, don't force it.
### Check for context
At the start, quickly check what exists:
```bash
openspec list --json
```
This tells you:
- If there are active changes
- Their names, schemas, and status
- What the user might be working on
If the user mentioned a specific change name, read its artifacts for context.
### When no change exists
Think freely. When insights crystallize, you might offer:
- "This feels solid enough to start a change. Want me to create a proposal?"
- Or keep exploring - no pressure to formalize
### When a change exists
If the user mentions a change or you detect one is relevant:
1. **Read existing artifacts for context**
- `openspec/changes/<name>/proposal.md`
- `openspec/changes/<name>/design.md`
- `openspec/changes/<name>/tasks.md`
- etc.
2. **Reference them naturally in conversation**
- "Your design mentions using Redis, but we just realized SQLite fits better..."
- "The proposal scopes this to premium users, but we're now thinking everyone..."
3. **Offer to capture when decisions are made**
| Insight Type | Where to Capture |
|--------------|------------------|
| New requirement discovered | `specs/<capability>/spec.md` |
| Requirement changed | `specs/<capability>/spec.md` |
| Design decision made | `design.md` |
| Scope changed | `proposal.md` |
| New work identified | `tasks.md` |
| Assumption invalidated | Relevant artifact |
Example offers:
- "That's a design decision. Capture it in design.md?"
- "This is a new requirement. Add it to specs?"
- "This changes scope. Update the proposal?"
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
---
## What You Don't Have To Do
- Follow a script
- Ask the same questions every time
- Produce a specific artifact
- Reach a conclusion
- Stay on topic if a tangent is valuable
- Be brief (this is thinking time)
---
## Ending Discovery
There's no required ending. Discovery might:
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
- **Result in artifact updates**: "Updated design.md with these decisions"
- **Just provide clarity**: User has what they need, moves on
- **Continue later**: "We can pick this up anytime"
When things crystallize, you might offer a summary - but it's optional. Sometimes the thinking IS the value.
---
## Guardrails
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
- **Don't fake understanding** - If something is unclear, dig deeper
- **Don't rush** - Discovery is thinking time, not task time
- **Don't force structure** - Let patterns emerge naturally
- **Don't auto-capture** - Offer to save insights, don't just do it
- **Do visualize** - A good diagram is worth many paragraphs
- **Do explore the codebase** - Ground discussions in reality
- **Do question assumptions** - Including the user's and your own

View file

@ -0,0 +1,103 @@
---
description: Propose a new change - create it and generate all artifacts in one step
---
Propose a new change - create the change and generate all artifacts in one step.
I'll create a change with artifacts:
- proposal.md (what & why)
- design.md (how)
- tasks.md (implementation steps)
When ready to implement, run /opsx:apply
---
**Input**: The argument after `/opsx:propose` is the change name (kebab-case), OR a description of what the user wants to build.
**Steps**
1. **If no input provided, ask what they want to build**
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
> "What change do you want to work on? Describe what you want to build or fix."
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
2. **Create the change directory**
```bash
openspec new change "<name>"
```
This creates a scaffolded change at `openspec/changes/<name>/` with `.openspec.yaml`.
3. **Get the artifact build order**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to get:
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
- `artifacts`: list of all artifacts with their status and dependencies
4. **Create artifacts in sequence until apply-ready**
Use the **TodoWrite tool** to track progress through the artifacts.
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
a. **For each artifact that is `ready` (dependencies satisfied)**:
- Get instructions:
```bash
openspec instructions <artifact-id> --change "<name>" --json
```
- The instructions JSON includes:
- `context`: Project background (constraints for you - do NOT include in output)
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
- `template`: The structure to use for your output file
- `instruction`: Schema-specific guidance for this artifact type
- `outputPath`: Where to write the artifact
- `dependencies`: Completed artifacts to read for context
- Read any completed dependency files for context
- Create the artifact file using `template` as the structure
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
- Show brief progress: "Created <artifact-id>"
b. **Continue until all `applyRequires` artifacts are complete**
- After creating each artifact, re-run `openspec status --change "<name>" --json`
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
- Stop when all `applyRequires` artifacts are done
c. **If an artifact requires user input** (unclear context):
- Use **AskUserQuestion tool** to clarify
- Then continue with creation
5. **Show final status**
```bash
openspec status --change "<name>"
```
**Output**
After completing all artifacts, summarize:
- Change name and location
- List of artifacts created with brief descriptions
- What's ready: "All artifacts created! Ready for implementation."
- Prompt: "Run `/opsx:apply` to start implementing."
**Artifact Creation Guidelines**
- Follow the `instruction` field from `openspec instructions` for each artifact type
- The schema defines what each artifact should contain - follow it
- Read dependency artifacts for context before creating new ones
- Use `template` as the structure for your output file - fill in its sections
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
- These guide what you write, but should never appear in the output
**Guardrails**
- Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
- Always read dependency artifacts before creating a new one
- If context is critically unclear, ask the user - but prefer making reasonable decisions to keep momentum
- If a change with that name already exists, ask if user wants to continue it or create a new one
- Verify each artifact file exists after writing before proceeding to next

8
.claude/settings.json Normal file
View file

@ -0,0 +1,8 @@
{
"permissions": {
"allow": [
"Edit(/.claude/skills/odoo-javascript/**)",
"Bash(git -C /home/snt/Documentos/lab/odoo/addons-cm commit -m ' *)"
]
}
}

View file

@ -0,0 +1,24 @@
---
name: odoo-javascript
description: JavaScript/Odoo frontend conventions for this repo (modules, tours, events, lazy loading). Use when editing JS in static/src/js/ of Odoo addons.
metadata:
type: reference
---
# JavaScript (Odoo Web/Frontend)
## Style and conventions
- ES6+ (`let`/`const`, arrow functions). Linting with ESLint (`.eslintrc.js` at root).
- Odoo pattern: AMD modules (`odoo.define`).
- **No business logic in JS, only UI and events.** Business logic lives in Python.
- Comments to explain hacks or workarounds.
## Key patterns
- Scripts in `static/src/js/`.
- UI tours registered with `web_tour.tour` (test: true, url, steps).
- **Delegated** events for dynamic elements (lazy loading, infinite scroll in `website_sale_aplicoop`).
- AJAX via Odoo helpers (`ajax.jsonRpc`).
## Common mistakes
- Business logic in JS → move it to Python.
- Listeners lost after DOM manipulation → reattach via event delegation.

View file

@ -0,0 +1,37 @@
---
name: odoo-python
description: Python/Odoo ORM conventions for this repo (models, fields, computed, tests, OCA). Use when writing or modifying Python code in Odoo addons (.py, models/, wizards/, tests/).
metadata:
type: reference
---
# Python (Odoo ORM)
## Style and conventions
- Follow the **OCA guidelines** strictly.
- `black` (line length 88) for formatting, `isort` (black profile) for imports.
- Mandatory linting: `flake8` and `pylint-odoo`.
- Docstrings on classes and public methods; inline comments only for complex logic.
- **Do NOT use `_()` in field definitions** (import-time warning). Only in executable methods.
## Key patterns
- Models inherit from `models.Model` or `models.TransientModel` (wizards).
- **Business fields ALWAYS on `product.product`**, not on `product.template` (use `related` on the template).
Avoids issues with pricelists and reports that operate at the variant level.
- `@api.depends(...)` for computed fields.
- Notifications: `ir.actions.client` with `display_notification` (`type`: success/warning/danger/info).
- Detailed price/discount logging: `_logger.info("[PRICE] Product %s [%s]: ...", code, id, ...)`.
- Bulk updates: prefer `search().write()` over loops; `create([vals, ...])` for bulk create.
- Pricing: use `product_get_price_helper` (`product._get_price(qty=1, pricelist=pricelist)`).
Validate `product.taxes_id` before computing (raise `UserError` if missing).
## Testing
- Tests in each addon's `tests/`, named `test_*.py`, inheriting from `odoo.tests.common.TransactionCase`.
- Run (use `run`, not `exec`, for a clean container):
```bash
docker-compose run odoo odoo -d odoo --test-enable --stop-after-init -u <addon>
```
## Common mistakes
- `_()` in module-level field definitions → warning. Remove it; translation goes through `.po`.
- Computed fields failing in pricelists/reports → move logic to `product.product`.

View file

@ -0,0 +1,35 @@
---
name: odoo-qweb-html
description: HTML/CSS/QWeb conventions for this repo (web templates, moving logic to the controller, styling). Use when editing QWeb templates, web views, or CSS in Odoo addons (website_sale_aplicoop).
metadata:
type: reference
---
# HTML & CSS (Odoo/QWeb)
## Golden rule
**QWeb has strict limitations with complex logic.** Prepare ALL data in the Python controller
and use only simple attribute access in the template. This avoids errors like
`TypeError: 'NoneType' object is not callable`.
```python
# ❌ BAD — QWeb does not reliably parse this
# <t t-set="price" t-value="info.get('price') or product.list_price or 0"/>
# ✅ GOOD — pre-process in the controller
def _prepare_product_display_info(self, product, price_info):
price = price_info.get(product.id, {}).get('price') or product.list_price or 0.0
return {'display_price': float(price), 'safe_uom': product.uom_id.category_id.name or ''}
```
```xml
<!-- In template: simple access, no conditionals -->
<span t-esc="product_display['display_price']"/>
```
## Style and conventions
- Valid HTML5. 4-space indentation.
- CSS: BEM or utility classes / Bootstrap when available. **No inline styles** except in well-justified cases.
- Templates in `views/*.xml` or `static/src/xml/`. Styles in `static/src/css/` (load in manifest if needed).
## Reference
- `docs/QWEB_BEST_PRACTICES.md` for full logic/template separation patterns.

View file

@ -0,0 +1,28 @@
---
name: odoo-xml-views
description: XML/Odoo views conventions for this repo (XPath, inheritance, IDs, security, manifest data). Use when editing .xml views, security/, or XML data in Odoo addons.
metadata:
type: reference
---
# XML (Odoo Views)
## Style and conventions
- Indentation: **4 spaces** (no tabs).
- XPath with explicit `position`: `before`, `after`, `inside`, `replace`, `attributes`.
- Reference groups via `module.xml_id` (e.g. `sales_team.group_sale_manager`).
- `sequence` to order fields in views.
- IDs: `module.descriptive_name` pattern.
- **No conditional logic in QWeb**, only access to attributes prepared in the controller.
- Translate strings in XML, never with `_()` in Python field definitions.
## Key patterns
- Views in `views/*.xml`. Typical manifest `data` order:
`security/ir.model.access.csv`, `views/actions.xml`, `views/menu.xml`, `views/<model>_views.xml`.
- Security: `id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink`.
- Common groups: `base.group_user`, `base.group_system`,
`sales_team.group_sale_manager`, `purchase.group_purchase_manager`.
## Common mistakes
- *XPath not found* → check inheritance chain and correct XML IDs.
- Complex logic in QWeb → move it to the controller (see `docs/QWEB_BEST_PRACTICES.md`).

View file

@ -0,0 +1,156 @@
---
name: openspec-apply-change
description: Implement tasks from an OpenSpec change. Use when the user wants to start implementing, continue implementation, or work through tasks.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.2.0"
---
Implement tasks from an OpenSpec change.
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes and use the **AskUserQuestion tool** to let the user select
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:apply <other>`).
2. **Check status to understand the schema**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand:
- `schemaName`: The workflow being used (e.g., "spec-driven")
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
3. **Get apply instructions**
```bash
openspec instructions apply --change "<name>" --json
```
This returns:
- Context file paths (varies by schema - could be proposal/specs/design/tasks or spec/tests/implementation/docs)
- Progress (total, complete, remaining)
- Task list with status
- Dynamic instruction based on current state
**Handle states:**
- If `state: "blocked"` (missing artifacts): show message, suggest using openspec-continue-change
- If `state: "all_done"`: congratulate, suggest archive
- Otherwise: proceed to implementation
4. **Read context files**
Read the files listed in `contextFiles` from the apply instructions output.
The files depend on the schema being used:
- **spec-driven**: proposal, specs, design, tasks
- Other schemas: follow the contextFiles from CLI output
5. **Show current progress**
Display:
- Schema being used
- Progress: "N/M tasks complete"
- Remaining tasks overview
- Dynamic instruction from CLI
6. **Implement tasks (loop until done or blocked)**
For each pending task:
- Show which task is being worked on
- Make the code changes required
- Keep changes minimal and focused
- Mark task complete in the tasks file: `- [ ]``- [x]`
- Continue to next task
**Pause if:**
- Task is unclear → ask for clarification
- Implementation reveals a design issue → suggest updating artifacts
- Error or blocker encountered → report and wait for guidance
- User interrupts
7. **On completion or pause, show status**
Display:
- Tasks completed this session
- Overall progress: "N/M tasks complete"
- If all done: suggest archive
- If paused: explain why and wait for guidance
**Output During Implementation**
```
## Implementing: <change-name> (schema: <schema-name>)
Working on task 3/7: <task description>
[...implementation happening...]
✓ Task complete
Working on task 4/7: <task description>
[...implementation happening...]
✓ Task complete
```
**Output On Completion**
```
## Implementation Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 7/7 tasks complete ✓
### Completed This Session
- [x] Task 1
- [x] Task 2
...
All tasks complete! Ready to archive this change.
```
**Output On Pause (Issue Encountered)**
```
## Implementation Paused
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 4/7 tasks complete
### Issue Encountered
<description of the issue>
**Options:**
1. <option 1>
2. <option 2>
3. Other approach
What would you like to do?
```
**Guardrails**
- Keep going through tasks until done or blocked
- Always read context files before starting (from the apply instructions output)
- If task is ambiguous, pause and ask before implementing
- If implementation reveals issues, pause and suggest artifact updates
- Keep code changes minimal and scoped to each task
- Update task checkbox immediately after completing each task
- Pause on errors, blockers, or unclear requirements - don't guess
- Use contextFiles from CLI output, don't assume specific file names
**Fluid Workflow Integration**
This skill supports the "actions on a change" model:
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly

View file

@ -0,0 +1,114 @@
---
name: openspec-archive-change
description: Archive a completed change in the experimental workflow. Use when the user wants to finalize and archive a change after implementation is complete.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.2.0"
---
Archive a completed change in the experimental workflow.
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **If no change name provided, prompt for selection**
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
Show only active changes (not already archived).
Include the schema used for each change if available.
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
2. **Check artifact completion status**
Run `openspec status --change "<name>" --json` to check artifact completion.
Parse the JSON to understand:
- `schemaName`: The workflow being used
- `artifacts`: List of artifacts with their status (`done` or other)
**If any artifacts are not `done`:**
- Display warning listing incomplete artifacts
- Use **AskUserQuestion tool** to confirm user wants to proceed
- Proceed if user confirms
3. **Check task completion status**
Read the tasks file (typically `tasks.md`) to check for incomplete tasks.
Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).
**If incomplete tasks found:**
- Display warning showing count of incomplete tasks
- Use **AskUserQuestion tool** to confirm user wants to proceed
- Proceed if user confirms
**If no tasks file exists:** Proceed without task-related warning.
4. **Assess delta spec sync state**
Check for delta specs at `openspec/changes/<name>/specs/`. If none exist, proceed without sync prompt.
**If delta specs exist:**
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
- Determine what changes would be applied (adds, modifications, removals, renames)
- Show a combined summary before prompting
**Prompt options:**
- If changes needed: "Sync now (recommended)", "Archive without syncing"
- If already synced: "Archive now", "Sync anyway", "Cancel"
If user chooses sync, use Task tool (subagent_type: "general-purpose", prompt: "Use Skill tool to invoke openspec-sync-specs for change '<name>'. Delta spec analysis: <include the analyzed delta spec summary>"). Proceed to archive regardless of choice.
5. **Perform the archive**
Create the archive directory if it doesn't exist:
```bash
mkdir -p openspec/changes/archive
```
Generate target name using current date: `YYYY-MM-DD-<change-name>`
**Check if target already exists:**
- If yes: Fail with error, suggest renaming existing archive or using different date
- If no: Move the change directory to archive
```bash
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>
```
6. **Display summary**
Show archive completion summary including:
- Change name
- Schema that was used
- Archive location
- Whether specs were synced (if applicable)
- Note about any warnings (incomplete artifacts/tasks)
**Output On Success**
```
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** ✓ Synced to main specs (or "No delta specs" or "Sync skipped")
All artifacts complete. All tasks complete.
```
**Guardrails**
- Always prompt for change selection if not provided
- Use artifact graph (openspec status --json) for completion checking
- Don't block archive on warnings - just inform and confirm
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
- Show clear summary of what happened
- If sync is requested, use openspec-sync-specs approach (agent-driven)
- If delta specs exist, always run the sync assessment and show the combined summary before prompting

View file

@ -0,0 +1,288 @@
---
name: openspec-explore
description: Enter explore mode - a thinking partner for exploring ideas, investigating problems, and clarifying requirements. Use when the user wants to think through something before or during a change.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.2.0"
---
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing.
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
---
## The Stance
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
- **Adaptive** - Follow interesting threads, pivot when new information emerges
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
---
## What You Might Do
Depending on what the user brings, you might:
**Explore the problem space**
- Ask clarifying questions that emerge from what they said
- Challenge assumptions
- Reframe the problem
- Find analogies
**Investigate the codebase**
- Map existing architecture relevant to the discussion
- Find integration points
- Identify patterns already in use
- Surface hidden complexity
**Compare options**
- Brainstorm multiple approaches
- Build comparison tables
- Sketch tradeoffs
- Recommend a path (if asked)
**Visualize**
```
┌─────────────────────────────────────────┐
│ Use ASCII diagrams liberally │
├─────────────────────────────────────────┤
│ │
│ ┌────────┐ ┌────────┐ │
│ │ State │────────▶│ State │ │
│ │ A │ │ B │ │
│ └────────┘ └────────┘ │
│ │
│ System diagrams, state machines, │
│ data flows, architecture sketches, │
│ dependency graphs, comparison tables │
│ │
└─────────────────────────────────────────┘
```
**Surface risks and unknowns**
- Identify what could go wrong
- Find gaps in understanding
- Suggest spikes or investigations
---
## OpenSpec Awareness
You have full context of the OpenSpec system. Use it naturally, don't force it.
### Check for context
At the start, quickly check what exists:
```bash
openspec list --json
```
This tells you:
- If there are active changes
- Their names, schemas, and status
- What the user might be working on
### When no change exists
Think freely. When insights crystallize, you might offer:
- "This feels solid enough to start a change. Want me to create a proposal?"
- Or keep exploring - no pressure to formalize
### When a change exists
If the user mentions a change or you detect one is relevant:
1. **Read existing artifacts for context**
- `openspec/changes/<name>/proposal.md`
- `openspec/changes/<name>/design.md`
- `openspec/changes/<name>/tasks.md`
- etc.
2. **Reference them naturally in conversation**
- "Your design mentions using Redis, but we just realized SQLite fits better..."
- "The proposal scopes this to premium users, but we're now thinking everyone..."
3. **Offer to capture when decisions are made**
| Insight Type | Where to Capture |
|--------------|------------------|
| New requirement discovered | `specs/<capability>/spec.md` |
| Requirement changed | `specs/<capability>/spec.md` |
| Design decision made | `design.md` |
| Scope changed | `proposal.md` |
| New work identified | `tasks.md` |
| Assumption invalidated | Relevant artifact |
Example offers:
- "That's a design decision. Capture it in design.md?"
- "This is a new requirement. Add it to specs?"
- "This changes scope. Update the proposal?"
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
---
## What You Don't Have To Do
- Follow a script
- Ask the same questions every time
- Produce a specific artifact
- Reach a conclusion
- Stay on topic if a tangent is valuable
- Be brief (this is thinking time)
---
## Handling Different Entry Points
**User brings a vague idea:**
```
User: I'm thinking about adding real-time collaboration
You: Real-time collab is a big space. Let me think about this...
COLLABORATION SPECTRUM
════════════════════════════════════════════
Awareness Coordination Sync
│ │ │
▼ ▼ ▼
┌────────┐ ┌────────┐ ┌────────┐
│Presence│ │Cursors │ │ CRDT │
│ "3 │ │ Multi │ │Conflict│
│online" │ │ select │ │ free │
└────────┘ └────────┘ └────────┘
│ │ │
trivial moderate complex
Where's your head at?
```
**User brings a specific problem:**
```
User: The auth system is a mess
You: [reads codebase]
┌─────────────────────────────────────────────┐
│ CURRENT AUTH FLOW │
└─────────────────────────────────────────────┘
┌─────────────┼─────────────┐
▼ ▼ ▼
┌─────────┐ ┌─────────┐ ┌─────────┐
│ Google │ │ GitHub │ │ Email │
│ OAuth │ │ OAuth │ │ Magic │
└────┬────┘ └────┬────┘ └────┬────┘
│ │ │
└─────────────┼─────────────┘
┌───────────┐
│ Session │
└─────┬─────┘
┌───────────┐
│ Perms │
└───────────┘
I see three tangles. Which one's burning?
```
**User is stuck mid-implementation:**
```
User: /opsx:explore add-auth-system
The OAuth integration is more complex than expected
You: [reads change artifacts]
You're on task 4: "Implement OAuth flow"
Let me trace what's involved...
[draws diagram, explores options, suggests paths]
Want to update the design to reflect this?
Or add a spike task to investigate?
```
**User wants to compare options:**
```
User: Should we use Postgres or SQLite?
You: Generic answer is boring. What's the context?
User: A CLI tool that tracks local dev environments
You: That changes everything.
┌─────────────────────────────────────────────────┐
│ CLI TOOL DATA STORAGE │
└─────────────────────────────────────────────────┘
Key constraints:
• No daemon running
• Must work offline
• Single user
SQLite Postgres
Deployment embedded ✓ needs server ✗
Offline yes ✓ no ✗
Single file yes ✓ no ✗
SQLite. Not even close.
Unless... is there a sync component?
```
---
## Ending Discovery
There's no required ending. Discovery might:
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
- **Result in artifact updates**: "Updated design.md with these decisions"
- **Just provide clarity**: User has what they need, moves on
- **Continue later**: "We can pick this up anytime"
When it feels like things are crystallizing, you might summarize:
```
## What We Figured Out
**The problem**: [crystallized understanding]
**The approach**: [if one emerged]
**Open questions**: [if any remain]
**Next steps** (if ready):
- Create a change proposal
- Keep exploring: just keep talking
```
But this summary is optional. Sometimes the thinking IS the value.
---
## Guardrails
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
- **Don't fake understanding** - If something is unclear, dig deeper
- **Don't rush** - Discovery is thinking time, not task time
- **Don't force structure** - Let patterns emerge naturally
- **Don't auto-capture** - Offer to save insights, don't just do it
- **Do visualize** - A good diagram is worth many paragraphs
- **Do explore the codebase** - Ground discussions in reality
- **Do question assumptions** - Including the user's and your own

View file

@ -0,0 +1,110 @@
---
name: openspec-propose
description: Propose a new change with all artifacts generated in one step. Use when the user wants to quickly describe what they want to build and get a complete proposal with design, specs, and tasks ready for implementation.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.2.0"
---
Propose a new change - create the change and generate all artifacts in one step.
I'll create a change with artifacts:
- proposal.md (what & why)
- design.md (how)
- tasks.md (implementation steps)
When ready to implement, run /opsx:apply
---
**Input**: The user's request should include a change name (kebab-case) OR a description of what they want to build.
**Steps**
1. **If no clear input provided, ask what they want to build**
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
> "What change do you want to work on? Describe what you want to build or fix."
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
2. **Create the change directory**
```bash
openspec new change "<name>"
```
This creates a scaffolded change at `openspec/changes/<name>/` with `.openspec.yaml`.
3. **Get the artifact build order**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to get:
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
- `artifacts`: list of all artifacts with their status and dependencies
4. **Create artifacts in sequence until apply-ready**
Use the **TodoWrite tool** to track progress through the artifacts.
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
a. **For each artifact that is `ready` (dependencies satisfied)**:
- Get instructions:
```bash
openspec instructions <artifact-id> --change "<name>" --json
```
- The instructions JSON includes:
- `context`: Project background (constraints for you - do NOT include in output)
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
- `template`: The structure to use for your output file
- `instruction`: Schema-specific guidance for this artifact type
- `outputPath`: Where to write the artifact
- `dependencies`: Completed artifacts to read for context
- Read any completed dependency files for context
- Create the artifact file using `template` as the structure
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
- Show brief progress: "Created <artifact-id>"
b. **Continue until all `applyRequires` artifacts are complete**
- After creating each artifact, re-run `openspec status --change "<name>" --json`
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
- Stop when all `applyRequires` artifacts are done
c. **If an artifact requires user input** (unclear context):
- Use **AskUserQuestion tool** to clarify
- Then continue with creation
5. **Show final status**
```bash
openspec status --change "<name>"
```
**Output**
After completing all artifacts, summarize:
- Change name and location
- List of artifacts created with brief descriptions
- What's ready: "All artifacts created! Ready for implementation."
- Prompt: "Run `/opsx:apply` or ask me to implement to start working on the tasks."
**Artifact Creation Guidelines**
- Follow the `instruction` field from `openspec instructions` for each artifact type
- The schema defines what each artifact should contain - follow it
- Read dependency artifacts for context before creating new ones
- Use `template` as the structure for your output file - fill in its sections
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
- These guide what you write, but should never appear in the output
**Guardrails**
- Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
- Always read dependency artifacts before creating a new one
- If context is critically unclear, ask the user - but prefer making reasonable decisions to keep momentum
- If a change with that name already exists, ask if user wants to continue it or create a new one
- Verify each artifact file exists after writing before proceeding to next

70
CLAUDE.md Normal file
View file

@ -0,0 +1,70 @@
# Kidekoop — Odoo 18.0 Custom Addons
Odoo 18.0 (OCB community) addons repo. Code in **English**, UI in **Basque/Spanish**.
Combines OCB (`ocb/`), inherited OCA addons, and our own custom addons.
## ⚠️ Critical rules (non-negotiable)
- **DO NOT modify** the OCB core (`ocb/`) nor these original OCA addons (reference/inheritance only):
`product_main_seller`, `product_origin`, `account_invoice_triple_discount`,
`product_get_price_helper`, `product_price_category`, `purchase_triple_discount`.
All changes go in our own custom addons.
- **Do NOT use `_()` in field definitions** (triggers import-time warnings). Only in methods/executable code.
- **Business logic ALWAYS on `product.product`** (variants), never on `product.template` (use `related` there).
Avoids issues with pricelists and reports that operate at the variant level.
- **No logic in QWeb**: prepare all data in the Python controller; templates only do simple attribute access.
- **No business logic in JavaScript**: UI/events only.
- Translations: edit `.po` files with `polib` (append). **`msgmerge` corrupts the files** — do not use it.
## Stack
Odoo 18.0 · Python 3.10+ · PostgreSQL · Docker Compose · XML/QWeb/JS.
Formatting: `black` (line 88) + `isort` (black profile) + `flake8` + `pylint-odoo`. Pre-commit active.
## Commands
```bash
docker-compose up -d # env (8070=web, 8073=longpolling)
docker-compose run odoo odoo -d odoo --test-enable --stop-after-init -u <addon> # tests (run, NOT exec: avoids cache)
docker-compose exec odoo odoo -d odoo -u <addon> --stop-after-init # update addon
docker-compose logs -f odoo # logs
docker-compose exec db psql -U odoo -d odoo # postgres
make lint | make format | make check-format | make flake8 | make pylint-required
pre-commit run --all-files
```
## Odoo conventions
- Models `snake.case` · classes `PascalCase` · files `snake_case.py` · XML IDs `module.name`.
- Manifest always `__manifest__.py`, version `18.0.X.Y.Z`, `depends` alphabetically ordered.
- Views: 4 spaces, explicit `position` in XPath, groups via `module.xml_id`, `sequence` for ordering.
- Bulk: prefer `search().write()` over loops; `create([vals, ...])` for bulk create.
- Notifications: `ir.actions.client` + `display_notification`.
- Detailed logging in price/discount computations: `_logger.info("[PRICE] ...", ...)`.
- i18n: each addon ships `i18n/{es,eu}.po` (mandatory) + `.pot`. UTF-8 charset.
## Custom addons
- `product_sale_price_from_pricelist` — auto-computes sale price from last purchase price + pricelist.
Requires taxes on the product and `last_purchase_price_compute_type != "manual_update"`.
- `website_sale_aplicoop` — Eskaera: collaborative purchasing for consumer co-ops (group orders,
per-member carts, cutoff/pickup dates, lazy loading, multi-language).
- `account_invoice_triple_discount_readonly` — fix for triple-discount accumulation bug (always use it).
- `product_price_category_supplier` — price categories per supplier.
## Documentation
- Per-addon details: its `README.rst` (OCA) or `README_DEV.md` (technical).
- Global patterns: `.github/copilot-instructions.md` (extended version of this file).
- Guides: `docs/QWEB_BEST_PRACTICES.md`, `docs/OCA_DOCUMENTATION.md`, `docs/LAZY_LOADING.md`.
- OCA `readme/` structure (DESCRIPTION, INSTALL, CONFIGURE, USAGE, CONTRIBUTORS, CREDITS).
Credits: Criptomart (author) + Elika Bilbo (funder).
## Commits
`[TAG] module: description` — tags: `[ADD] [FIX] [IMP] [REF] [REM] [I18N] [DOC]`.
## Available skills
Per-language skills (`odoo-python`, `odoo-xml-views`, `odoo-qweb-html`, `odoo-javascript`) and the
OpenSpec workflow (`openspec-explore/propose/apply-change/archive-change`, `/opsx:*` commands) live in `.claude/`.

View file

@ -2,7 +2,7 @@
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{ # noqa: B018 { # noqa: B018
"name": "Product Sale Price from Pricelist", "name": "Product Sale Price from Pricelist",
"version": "18.0.2.7.0", "version": "18.0.2.8.0",
"category": "product", "category": "product",
"summary": "Set sale price from pricelist based on last purchase price", "summary": "Set sale price from pricelist based on last purchase price",
"author": "Odoo Community Association (OCA), Criptomart", "author": "Odoo Community Association (OCA), Criptomart",
@ -12,6 +12,7 @@
"depends": [ "depends": [
"product_get_price_helper", "product_get_price_helper",
"account_invoice_triple_discount_readonly", "account_invoice_triple_discount_readonly",
"purchase_triple_discount",
"sale_management", "sale_management",
"purchase", "purchase",
"account", "account",

View file

@ -1,6 +1,7 @@
from . import product_pricelist # noqa: F401 from . import product_pricelist # noqa: F401
from . import product_pricelist_item # noqa: F401 from . import product_pricelist_item # noqa: F401
from . import product_product # noqa: F401 from . import product_product # noqa: F401
from . import product_supplierinfo # noqa: F401
from . import product_template # noqa: F401 from . import product_template # noqa: F401
from . import res_config # noqa: F401 from . import res_config # noqa: F401
from . import stock_move # noqa: F401 from . import stock_move # noqa: F401

View file

@ -3,6 +3,7 @@ import logging
from odoo import fields from odoo import fields
from odoo import models from odoo import models
from odoo.exceptions import UserError from odoo.exceptions import UserError
from odoo.tools import float_round
_logger = logging.getLogger(__name__) _logger = logging.getLogger(__name__)
@ -73,15 +74,6 @@ class ProductProduct(models.Model):
and product.id and product.id
and product.last_purchase_price_compute_type != "manual_update" and product.last_purchase_price_compute_type != "manual_update"
): ):
partial_price = product._get_price(qty=1, pricelist=pricelist)
_logger.info(
"[PRICE DEBUG] Product %s [%s]: partial_price result = %s",
product.default_code or product.name,
product.id,
partial_price,
)
# Compute taxes to add # Compute taxes to add
if not product.taxes_id: if not product.taxes_id:
raise UserError( raise UserError(
@ -91,7 +83,11 @@ class ProductProduct(models.Model):
) )
) )
base_price = partial_price.get("value", 0.0) or 0.0 # Ask the pricelist for the price directly. Going through
# _get_price would compute the price twice (once for the
# value and once more to resolve the discount rule, which we
# don't use here), triggering a redundant _compute_price_rule.
base_price = pricelist._get_product_price(product, 1.0) or 0.0
_logger.info( _logger.info(
"[PRICE DEBUG] Product %s [%s]: base_price from pricelist = %.2f, last_purchase_price = %.2f", "[PRICE DEBUG] Product %s [%s]: base_price from pricelist = %.2f, last_purchase_price = %.2f",
product.default_code or product.name, product.default_code or product.name,
@ -127,6 +123,43 @@ class ProductProduct(models.Model):
) )
) )
def _recompute_theoritical_price_safe(self):
"""Recompute the theoretical price without raising when the automatic
pricelist is not configured yet (e.g. while editing supplierinfo lines
during data imports)."""
pricelist_id = (
self.env["ir.config_parameter"]
.sudo()
.get_param("product_sale_price_from_pricelist.product_pricelist_automatic")
)
if not pricelist_id:
return
self._compute_theoritical_price()
def _get_main_supplierinfo(self):
"""Return the main vendor supplierinfo line for this variant (first
active vendor by sequence, same selection Odoo uses for purchasing)."""
self.ensure_one()
return fields.first(self._prepare_sellers())
def _compute_supplierinfo_net_price(self, seller):
"""Net purchase price from a supplierinfo line, applying its discounts
according to last_purchase_price_compute_type. Mirrors the receipt
logic in stock.move so both paths produce the same cost basis."""
self.ensure_one()
price = seller.price or 0.0
compute_type = self.last_purchase_price_compute_type
if compute_type == "with_discount":
price *= 1 - (seller.discount1 or 0.0) / 100
elif compute_type == "with_two_discounts":
price *= (1 - (seller.discount1 or 0.0) / 100) * (
1 - (seller.discount2 or 0.0) / 100
)
elif compute_type == "with_three_discounts":
# seller.discount aggregates the three discounts (triple discount).
price *= 1 - (seller.discount or 0.0) / 100
return float_round(price, precision_digits=2)
def action_update_list_price(self): def action_update_list_price(self):
updated_products = [] updated_products = []
skipped_products = [] skipped_products = []

View file

@ -0,0 +1,83 @@
# Copyright (C) 2020: Criptomart (https://criptomart.net)
# @author Santi Noreña (<santi@criptomart.net>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import logging
from odoo import api
from odoo import models
from odoo.tools import float_compare
_logger = logging.getLogger(__name__)
# Fields whose change can alter the net purchase price of the main vendor.
PRICE_FIELDS = {
"price",
"discount",
"discount1",
"discount2",
"discount3",
"sequence",
"partner_id",
"product_id",
"product_tmpl_id",
"company_id",
}
class ProductSupplierInfo(models.Model):
_inherit = "product.supplierinfo"
@api.model_create_multi
def create(self, vals_list):
records = super().create(vals_list)
records._sync_last_purchase_price_received()
return records
def write(self, vals):
res = super().write(vals)
if PRICE_FIELDS & set(vals):
self._sync_last_purchase_price_received()
return res
def _sync_last_purchase_price_received(self):
"""Keep last_purchase_price_received in sync with the main vendor's
supplierinfo price, applying its discounts according to each variant's
last_purchase_price_compute_type. The actual sale price is only refreshed
in last_purchase_price_updated/list_price_theoritical; lst_price is left
untouched until the user confirms with the update button (same behaviour
as a stock receipt)."""
if self.env.context.get("skip_last_purchase_price_sync"):
return
products = self.env["product.product"]
for seller in self:
if seller.product_id:
products |= seller.product_id
elif seller.product_tmpl_id:
products |= seller.product_tmpl_id.product_variant_ids
for product in products.exists():
if product.last_purchase_price_compute_type == "manual_update":
continue
seller = product._get_main_supplierinfo()
if not seller:
continue
net_price = product._compute_supplierinfo_net_price(seller)
if (
float_compare(
product.last_purchase_price_received,
net_price,
precision_digits=2,
)
!= 0
):
_logger.info(
"[PRICE] Product %s [%s]: last_purchase_price_received synced "
"from supplierinfo %.2f -> %.2f (compute_type: %s)",
product.default_code or product.name,
product.id,
product.last_purchase_price_received,
net_price,
product.last_purchase_price_compute_type,
)
product.write({"last_purchase_price_received": net_price})
product._recompute_theoritical_price_safe()

View file

@ -5,3 +5,4 @@ from . import test_stock_move
from . import test_pricelist from . import test_pricelist
from . import test_res_config from . import test_res_config
from . import test_theoretical_price from . import test_theoretical_price
from . import test_supplierinfo_sync

View file

@ -0,0 +1,199 @@
# Copyright (C) 2020: Criptomart (https://criptomart.net)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo.tests import tagged
from odoo.tests.common import TransactionCase
@tagged("post_install", "-at_install")
class TestSupplierinfoSync(TransactionCase):
"""Cover the supplierinfo -> last_purchase_price_received sync, which applies
the vendor discounts according to last_purchase_price_compute_type."""
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.tax = cls.env["account.tax"].create(
{
"name": "Test Tax 21%",
"amount": 21.0,
"amount_type": "percent",
"type_tax_use": "sale",
}
)
# Pricelist applies a 50% markup on the last purchase price, so the
# theoretical price is always net_cost * 1.5 (same setup as stock tests).
cls.pricelist = cls.env["product.pricelist"].create(
{
"name": "Test Pricelist",
"currency_id": cls.env.company.currency_id.id,
}
)
cls.env["product.pricelist.item"].create(
{
"pricelist_id": cls.pricelist.id,
"compute_price": "formula",
"base": "last_purchase_price",
"price_markup": 50.0,
"applied_on": "3_global",
}
)
cls.env["ir.config_parameter"].sudo().set_param(
"product_sale_price_from_pricelist.product_pricelist_automatic",
str(cls.pricelist.id),
)
cls.supplier = cls.env["res.partner"].create(
{"name": "Test Supplier", "supplier_rank": 1}
)
cls.supplier2 = cls.env["res.partner"].create(
{"name": "Test Supplier 2", "supplier_rank": 1}
)
cls.uom_unit = cls.env.ref("uom.product_uom_unit")
cls.product = cls.env["product.product"].create(
{
"name": "Test Product Supplierinfo",
"uom_id": cls.uom_unit.id,
"uom_po_id": cls.uom_unit.id,
"list_price": 10.0,
"standard_price": 5.0,
"taxes_id": [(6, 0, [cls.tax.id])],
"last_purchase_price_received": 0.0,
"last_purchase_price_compute_type": "without_discounts",
}
)
cls.has_discounts = hasattr(cls.env["product.supplierinfo"], "discount1")
def setUp(self):
super().setUp()
if not self.has_discounts:
self.skipTest("purchase_triple_discount module not installed")
def _create_supplierinfo(
self,
product,
price,
discount1=0.0,
discount2=0.0,
discount3=0.0,
sequence=1,
partner=None,
):
return self.env["product.supplierinfo"].create(
{
"partner_id": (partner or self.supplier).id,
"product_tmpl_id": product.product_tmpl_id.id,
"price": price,
"discount1": discount1,
"discount2": discount2,
"discount3": discount3,
"sequence": sequence,
}
)
def test_sync_without_discounts(self):
"""without_discounts: vendor discounts are ignored, gross price is kept."""
self.product.last_purchase_price_compute_type = "without_discounts"
self._create_supplierinfo(self.product, price=1.53, discount1=15.0)
self.assertAlmostEqual(
self.product.last_purchase_price_received, 1.53, places=2
)
def test_sync_with_first_discount(self):
"""with_discount: only discount1 is applied."""
self.product.last_purchase_price_compute_type = "with_discount"
self._create_supplierinfo(
self.product, price=10.0, discount1=20.0, discount2=10.0, discount3=5.0
)
# 10 * (1 - 0.20) = 8.0
self.assertAlmostEqual(self.product.last_purchase_price_received, 8.0, places=2)
def test_sync_with_two_discounts(self):
"""with_two_discounts: discount1 and discount2 are applied, discount3 ignored."""
self.product.last_purchase_price_compute_type = "with_two_discounts"
self._create_supplierinfo(
self.product, price=10.0, discount1=20.0, discount2=10.0, discount3=5.0
)
# 10 * 0.80 * 0.90 = 7.2
self.assertAlmostEqual(self.product.last_purchase_price_received, 7.2, places=2)
def test_sync_with_three_discounts(self):
"""with_three_discounts: all three discounts are applied (aggregated)."""
self.product.last_purchase_price_compute_type = "with_three_discounts"
self._create_supplierinfo(
self.product, price=10.0, discount1=20.0, discount2=10.0, discount3=5.0
)
# 10 * 0.80 * 0.90 * 0.95 = 6.84
self.assertAlmostEqual(
self.product.last_purchase_price_received, 6.84, places=2
)
def test_sync_with_three_discounts_reported_case(self):
"""Reproduces the reported DIS0002 case: 1.53 with a single 15% discount."""
self.product.last_purchase_price_compute_type = "with_three_discounts"
self._create_supplierinfo(self.product, price=1.53, discount1=15.0)
# 1.53 * 0.85 = 1.3005 -> 1.30
self.assertAlmostEqual(
self.product.last_purchase_price_received, 1.30, places=2
)
def test_sync_updates_theoretical_price(self):
"""The sync also refreshes the theoretical price and the update flag."""
self.product.last_purchase_price_compute_type = "with_three_discounts"
self._create_supplierinfo(self.product, price=1.53, discount1=15.0)
# net 1.30 * 1.5 markup = 1.95
self.assertAlmostEqual(self.product.list_price_theoritical, 1.95, places=2)
self.assertTrue(
self.product.last_purchase_price_updated,
"last_purchase_price_updated should flag a pending sale price change",
)
def test_manual_update_is_not_synced(self):
"""manual_update: the cost is never touched by the supplierinfo sync."""
self.product.write(
{
"last_purchase_price_compute_type": "manual_update",
"last_purchase_price_received": 99.0,
}
)
self._create_supplierinfo(self.product, price=10.0, discount1=20.0)
self.assertAlmostEqual(
self.product.last_purchase_price_received, 99.0, places=2
)
def test_write_resyncs(self):
"""Editing the discount on an existing supplierinfo re-syncs the cost."""
self.product.last_purchase_price_compute_type = "with_three_discounts"
seller = self._create_supplierinfo(self.product, price=1.53, discount1=15.0)
self.assertAlmostEqual(
self.product.last_purchase_price_received, 1.30, places=2
)
seller.discount1 = 0.0
self.assertAlmostEqual(
self.product.last_purchase_price_received, 1.53, places=2
)
def test_secondary_seller_does_not_override(self):
"""Only the main vendor (lowest sequence) drives the cost basis."""
self.product.last_purchase_price_compute_type = "with_three_discounts"
self._create_supplierinfo(
self.product, price=10.0, sequence=1, partner=self.supplier
)
self.assertAlmostEqual(
self.product.last_purchase_price_received, 10.0, places=2
)
# A cheaper, heavily discounted secondary vendor must not change the cost.
self._create_supplierinfo(
self.product,
price=5.0,
discount1=50.0,
sequence=5,
partner=self.supplier2,
)
self.assertAlmostEqual(
self.product.last_purchase_price_received, 10.0, places=2
)

View file

@ -1,228 +0,0 @@
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * stock_picking_batch_custom
#
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 18.0\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-05-21 13:17+0000\n"
"PO-Revision-Date: 2026-05-21 13:17+0000\n"
"Last-Translator: \n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Plural-Forms: \n"
#. module: stock_picking_batch_custom
#: model:ir.model.fields.selection,name:stock_picking_batch_custom.selection__res_company__batch_detailed_restriction_scope__all
msgid "All detailed lines"
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model.fields.selection,name:stock_picking_batch_custom.selection__res_company__batch_summary_restriction_scope__all
msgid "All summary products"
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model,name:stock_picking_batch_custom.model_stock_backorder_confirmation
msgid "Backorder Confirmation"
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model.fields,field_description:stock_picking_batch_custom.field_stock_picking_batch_summary_line__batch_id
msgid "Batch"
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model.fields,field_description:stock_picking_batch_custom.field_stock_picking__batch_consumer_group_id
msgid "Batch Consumer Group"
msgstr ""
#. module: stock_picking_batch_custom
#: model_terms:ir.ui.view,arch_db:stock_picking_batch_custom.res_config_settings_view_form_inherit_batch_custom
msgid "Batch Detailed Operations Restriction"
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model,name:stock_picking_batch_custom.model_stock_picking_batch_summary_line
msgid "Batch Product Summary Line"
msgstr ""
#. module: stock_picking_batch_custom
#: model_terms:ir.ui.view,arch_db:stock_picking_batch_custom.res_config_settings_view_form_inherit_batch_custom
msgid "Batch Product Summary Restriction"
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model,name:stock_picking_batch_custom.model_stock_picking_batch
msgid "Batch Transfer"
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model.fields,field_description:stock_picking_batch_custom.field_stock_move_line__is_collected
#: model:ir.model.fields,field_description:stock_picking_batch_custom.field_stock_picking_batch_summary_line__is_collected
msgid "Collected"
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model,name:stock_picking_batch_custom.model_res_company
msgid "Companies"
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model,name:stock_picking_batch_custom.model_res_config_settings
msgid "Config Settings"
msgstr ""
#. module: stock_picking_batch_custom
#: model_terms:ir.ui.view,arch_db:stock_picking_batch_custom.res_config_settings_view_form_inherit_batch_custom
msgid "Configuración de restricciones para la pestaña Operaciones Detalladas."
msgstr ""
#. module: stock_picking_batch_custom
#: model_terms:ir.ui.view,arch_db:stock_picking_batch_custom.res_config_settings_view_form_inherit_batch_custom
msgid "Configuración de restricciones para la pestaña Product Summary."
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model.fields,field_description:stock_picking_batch_custom.field_stock_move_line__consumer_group_id
msgid "Consumer Group"
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model.fields,field_description:stock_picking_batch_custom.field_stock_picking_batch_summary_line__create_uid
msgid "Created by"
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model.fields,field_description:stock_picking_batch_custom.field_stock_picking_batch_summary_line__create_date
msgid "Created on"
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model.fields,field_description:stock_picking_batch_custom.field_stock_picking_batch_summary_line__qty_demanded
msgid "Demanded Quantity"
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model.fields,field_description:stock_picking_batch_custom.field_res_company__batch_detailed_restriction_scope
#: model:ir.model.fields,field_description:stock_picking_batch_custom.field_res_config_settings__batch_detailed_restriction_scope
msgid "Detailed Operations Restriction Scope"
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model.fields,field_description:stock_picking_batch_custom.field_stock_picking_batch_summary_line__display_name
msgid "Display Name"
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model.fields,field_description:stock_picking_batch_custom.field_stock_picking_batch_summary_line__qty_done
msgid "Done Quantity"
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model.fields,field_description:stock_picking_batch_custom.field_res_company__batch_detailed_restriction_enabled
#: model:ir.model.fields,field_description:stock_picking_batch_custom.field_res_config_settings__batch_detailed_restriction_enabled
msgid "Enforce Detailed Operations Restriction"
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model.fields,field_description:stock_picking_batch_custom.field_res_company__batch_summary_restriction_enabled
#: model:ir.model.fields,field_description:stock_picking_batch_custom.field_res_config_settings__batch_summary_restriction_enabled
msgid "Enforce Product Summary Restriction"
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model.fields,field_description:stock_picking_batch_custom.field_stock_move_line__home_delivery
msgid "Home Delivery"
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model.fields,field_description:stock_picking_batch_custom.field_stock_picking_batch_summary_line__id
msgid "ID"
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model.fields,field_description:stock_picking_batch_custom.field_stock_picking_batch_summary_line__write_uid
msgid "Last Updated by"
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model.fields,field_description:stock_picking_batch_custom.field_stock_picking_batch_summary_line__write_date
msgid "Last Updated on"
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model.fields.selection,name:stock_picking_batch_custom.selection__res_company__batch_detailed_restriction_scope__processed
msgid "Only processed lines"
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model.fields.selection,name:stock_picking_batch_custom.selection__res_company__batch_summary_restriction_scope__processed
msgid "Only processed products"
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model.fields,field_description:stock_picking_batch_custom.field_stock_picking_batch_summary_line__qty_pending
msgid "Pending Quantity"
msgstr ""
#. module: stock_picking_batch_custom
#. odoo-python
#: code:addons/stock_picking_batch_custom/models/stock_picking_batch.py:0
msgid "Pending products: %(products)s"
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model.fields,field_description:stock_picking_batch_custom.field_stock_picking_batch_summary_line__product_id
msgid "Product"
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model.fields,field_description:stock_picking_batch_custom.field_stock_picking_batch_summary_line__product_categ_id
msgid "Product Category"
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model.fields,field_description:stock_picking_batch_custom.field_stock_move_line__product_categ_id
msgid "Product Category (Batch)"
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model,name:stock_picking_batch_custom.model_stock_move_line
msgid "Product Moves (Stock Move Line)"
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model.fields,field_description:stock_picking_batch_custom.field_stock_picking_batch__summary_line_ids
#: model_terms:ir.ui.view,arch_db:stock_picking_batch_custom.view_stock_picking_batch_form_inherit_summary
msgid "Product Summary"
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model.fields,field_description:stock_picking_batch_custom.field_res_company__batch_summary_restriction_scope
#: model:ir.model.fields,field_description:stock_picking_batch_custom.field_res_config_settings__batch_summary_restriction_scope
msgid "Product Summary Restriction Scope"
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model.constraint,message:stock_picking_batch_custom.constraint_stock_picking_batch_summary_line_product_required
msgid "Product is required for summary lines."
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model,name:stock_picking_batch_custom.model_stock_picking
msgid "Transfer"
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model.fields,field_description:stock_picking_batch_custom.field_stock_picking_batch_summary_line__product_uom_id
msgid "Unit of Measure"
msgstr ""
#. module: stock_picking_batch_custom
#: model:ir.model.fields,help:stock_picking_batch_custom.field_stock_move_line__home_delivery
msgid "Whether this picking includes home delivery (from sale order)"
msgstr ""

View file

@ -31,8 +31,8 @@
<field name="picking_partner_id" readonly="1" optional="show"/> <field name="picking_partner_id" readonly="1" optional="show"/>
<field name="home_delivery" readonly="1" widget="boolean_toggle" optional="show"/> <field name="home_delivery" readonly="1" widget="boolean_toggle" optional="show"/>
<field name="consumer_group_id" readonly="1" optional="show"/> <field name="consumer_group_id" readonly="1" optional="show"/>
<field name="is_collected" widget="boolean_toggle"/>
<field name="quantity" string="Cant."/> <field name="quantity" string="Cant."/>
<field name="is_collected" widget="boolean_toggle"/>
</list> </list>
</field> </field>
</record> </record>