﻿# Kho Kiến Thức Odoo cho BMAD-METHOD-ODOO

## Mẫu cốt lõi & tham chiếu nhanh

> **Lưu ý**: Để lấy tài liệu Odoo đầy đủ và cập nhật, hãy dùng các lệnh Context7:
> - `*odoo-docs {topic}` – Lấy tài liệu Odoo theo chủ đề  
> - `*odoo-api {module}` – Lấy tham chiếu API cho module  
> - `*odoo-version {version} {topic}` – Thông tin theo phiên bản

### Các mẫu kế thừa cốt lõi

**Kế thừa lớp** (mở rộng model hiện hữu):
```python
class ResPartnerExtension(models.Model):
    _inherit = 'res.partner'
    custom_field = fields.Char('Custom Field')
```

**Kế thừa ủy quyền** (delegation):
```python
class CustomPartner(models.Model):
    _name = 'custom.partner'
    _inherits = {'res.partner': 'partner_id'}
    partner_id = fields.Many2one('res.partner', required=True, ondelete='cascade')
```

**Mở rộng tại chỗ** (in-place):
```python
class ResPartner(models.Model):
    _inherit = 'res.partner'  # Không khai báo _name để mở rộng model hiện có
    new_field = fields.Char('New Field')
```

### Các kiểu trường thiết yếu

| Type | Sử dụng | Ví dụ |
|------|---------|-------|
| `Char` | Chuỗi ngắn | `name = fields.Char('Name', required=True)` |
| `Text` | Chuỗi dài | `description = fields.Text('Description')` |
| `Integer` | Số nguyên | `quantity = fields.Integer('Quantity', default=1)` |
| `Float` | Số thập phân | `price = fields.Float('Price', digits=(16,2))` |
| `Boolean` | Đúng/Sai | `active = fields.Boolean('Active', default=True)` |
| `Date` | Ngày | `date_start = fields.Date('Start Date')` |
| `Datetime` | Ngày + Giờ | `create_date = fields.Datetime('Created')` |
| `Selection` | Dropdown | `state = fields.Selection([('draft','Draft')], 'State')` |
| `Many2one` | Khóa ngoại | `partner_id = fields.Many2one('res.partner')` |
| `One2many` | Khóa ngoại ngược | `line_ids = fields.One2many('sale.line', 'order_id')` |
| `Many2many` | Bảng liên kết | `tag_ids = fields.Many2many('product.tag')` |

### Các thao tác ORM phổ biến

**Tạo bản ghi**:
```python
# Một bản ghi
record = self.env['model.name'].create({'field1': 'value1'})

# Nhiều bản ghi
records = self.env['model.name'].create([
    {'field1': 'value1'}, {'field1': 'value2'}
])
```

**Đọc / Tìm kiếm**:
```python
# Tìm và đọc
records = self.env['model.name'].search([('field', '=', 'value')])
records = self.env['model.name'].search([('field', 'in', ['val1', 'val2'])])

# Duyệt theo ID
record = self.env['model.name'].browse(record_id)
```

**Cập nhật bản ghi**:
```python
records.write({'field1': 'new_value'})
```

### Các mixin thiết yếu

| Mixin | Mục đích | Trường chính thêm |
|-------|----------|-------------------|
| `mail.thread` | Chatter/nhắn tin | `message_ids`, tracking |
| `website.published.mixin` | Hiển thị website | `website_published`, `website_url` |
| `portal.mixin` | Truy cập cổng khách hàng | `access_url`, `access_token` |
| `rating.mixin` | Đánh giá khách hàng | Trường rating |

### Các mẫu bảo mật

**Groups** – `res.groups.xml`
```xml
<record id="group_manager" model="res.groups">
    <field name="name">Manager</field>
    <field name="category_id" ref="base.module_category"/>
</record>
```

**Access Rights** – `ir.model.access.csv`
```csv
id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink
access_model_user,model.access.user,model_model,base.group_user,1,0,0,0
```

**Record Rules** – bảo mật cấp bản ghi
```xml
<record id="rule_own_records" model="ir.rule">
    <field name="domain">[('user_id', '=', user.id)]</field>
</record>
```

## Odoo 17 Strict Rules 

### Backend/Python & ORM
- Dùng `@api.model_create_multi` khi override `create`, luôn gọi `super()`.  
- Với `write/unlink/...`, đảm bảo gọi `super()` và xử lý recordset an toàn (`for record in self`).  
- Quan hệ O2m/M2m: ưu tiên `odoo.fields.Command` (`Command.create/link/clear/set`).  
- Compute: bắt buộc `@api.depends`; dùng `read_group`, `mapped`, `filtered` để tránh N+1.  
- Dịch chuỗi hiển thị bằng `_()`. SQL chỉ dùng khi bất khả kháng, phải parametrized.  
- Tránh `getattr/hasattr` mù trên field; dùng `self._fields` để kiểm tra động.  
- Ưu tiên `_sql_constraints` cho uniqueness/non-negative; hạn chế `sudo()` không kiểm soát.  
- `@api.depends_context` cho compute phụ thuộc context (lang/company/tz).  
- Raise `ValidationError/UserError` trong `create/write` chỉ khi cần và đã có thông điệp rõ ràng.

### UI/View Odoo 17
- Cấm `attrs`/`states`; dùng biểu thức Python trực tiếp: `invisible="state != 'draft'"`, `readonly="qty_done > 0"`, `required="is_manager"`.  
- Tree/List: không ẩn cột bằng `invisible`; dùng `column_invisible="True"`.  
- Search view: ưu tiên `search_panel`.  
- Required: đặt trong view (`required="1"`), hạn chế `required=True` ở field Python.

### Đóng gói & bảo mật module
- Manifest phải rõ `license/depends/data/assets`, không khai báo thừa.  
- Mỗi model mới phải có `security/ir.model.access.csv` và record rule phù hợp; tránh cấp write/unlink rộng.  
- Đặt tên XML ID theo pattern `view_[model]_[type]_[suffix]`.  
- Cron: cấu hình chuẩn `interval_number/interval_type/numbercall`; tránh job dày đặc.  
- Controller: thiết lập `auth`, `csrf` chuẩn và kiểm tra quyền trong handler.

### Wizard & Transient Model
- File Python/XML chứa wizard phải nằm trong thư mục `wizard/`.  
- Wizard phải kế thừa `models.TransientModel` (trừ khi có lý do được Architect duyệt).  
- Không trùng tên hàm trong cùng class/file; dùng `compute` cho dữ liệu realtime.

### Deployment readiness
- Đồng bộ dịch `.po`; đảm bảo mọi chuỗi trong view/report/controller được dịch.  
- Rà soát `depends`/`assets`, loại bỏ thừa; tách bạch `demo` vs `data`.  
- Chuẩn bị rollback và kiểm soát dữ liệu tải ở production.

## Mẫu phản hồi ngắn gọn (tham chiếu)
### 🛠️ Implementation Details
- `__manifest__.py`: depends, data, license.  
- `models/*.py`: import `Command`, `_()`, `@api.model_create_multi`.  
- `views/*.xml`: dùng smart modifiers Odoo 17, không `attrs/states`.

## Tích hợp BMAD-METHOD

### Các pha quy trình
1. **Business Analysis** (*odoo-analyst): Requirements → Functional Specs → User Stories  
2. **Architecture** (*odoo-architect): Technical Design → Module Planning → Integration Strategy  
3. **Story Creation** (*odoo-analyst với vai trò SM): Architecture → Development Stories  
4. **Development** (*odoo-developer): Stories → Implementation → Testing → Deployment

### Phát triển dẫn dắt bởi story
- **Cấu trúc Epic**: Tính năng nghiệp vụ → Thành phần kỹ thuật → Development stories  
- **Định dạng Story**: Chuẩn BMAD với tiêu chí chấp nhận chuyên biệt Odoo  
- **Triển khai**: Lệnh `*develop-story` tuân theo workflow BMAD

### Checklist tuân thủ OCA
- [ ] Tuân theo tiêu chuẩn và quy ước mã hóa OCA  
- [ ] Dùng cấu trúc & đặt tên module chuẩn  
- [ ] Bao gồm kiểm thử và tài liệu đầy đủ  
- [ ] Triển khai bảo mật & kiểm soát truy cập đúng  
- [ ] Ưu tiên kế thừa, tránh sửa trực tiếp code gốc  
- [ ] Ưu tiên mẫu chuẩn Odoo, tránh tùy biến không cần thiết

## Tham chiếu nhanh xử lý sự cố

### Các vấn đề thường gặp
- **Import Errors**: Kiểm tra `__init__.py` và vòng lặp import  
- **Field Errors**: Xác minh định nghĩa trường và schema DB  
- **Access Errors**: Kiểm tra groups và record rules  
- **View Errors**: Kiểm tra cú pháp XML và tham chiếu trường  
- **ORM Errors**: Cẩn trọng với `self.env.cr.commit()` trong giao dịch

### Lệnh debug
```python
# Bật chế độ developer
import logging
logger = logging.getLogger(__name__)
logger.info("Debug message")

# SQL debugging
self.env.cr.execute("SELECT * FROM table WHERE condition")
results = self.env.cr.fetchall()
```

---

> **Để có tài liệu đầy đủ**: Dùng các lệnh Context7 trong mọi tác nhân  
> **Cho workflow BMAD**: Tuân theo các mẫu phát triển dẫn dắt bởi story

**Pha Lập Kế Hoạch (Web UI)**  
- Odoo Functional Consultant: phân tích quy trình nghiệp vụ  
- Odoo Technical Architect: thiết kế hệ thống  
- Tạo PRD với template Odoo  
- Tạo kiến trúc kỹ thuật theo template Odoo

**Pha Phát Triển (IDE)**  
- Dùng BMAD story sharding cho tasks Odoo  
- Theo hướng dẫn của tác nhân Odoo Developer  
- Triển khai theo tiêu chuẩn & mẫu OCA  
- Kiểm thử với framework kiểm thử chuyên Odoo

**Pha Triển Khai**  
- Lập kế hoạch triển khai Odoo  
- Theo các mẫu triển khai Odoo  
- Tích hợp hạ tầng Odoo hiện có

### Tích hợp luồng tài liệu
**PRD → Architecture → Stories → Implementation**  
1. Thu thập yêu cầu trong PRD Odoo  
2. Thiết kế kỹ thuật trong template Kiến trúc Odoo  
3. Sinh stories với ngữ cảnh Odoo đầy đủ  
4. Triển khai theo các mẫu phát triển Odoo

## Tiêu chuẩn OCA (Odoo Community Association)

### Tiêu chuẩn chất lượng mã
**Python**  
- Tuân theo PEP 8  
- Dùng pylint-odoo cho phân tích chuyên Odoo  
- Xử lý lỗi & logging chuẩn hóa  
- Viết docstring đầy đủ

**Cấu trúc module**
```
module_name/
├── __init__.py
├── __manifest__.py          # Metadata module
├── models/                  # Logic nghiệp vụ
│   ├── __init__.py
│   └── *.py
├── views/                   # Giao diện người dùng
│   └── *.xml
├── security/                # Kiểm soát truy cập
│   ├── ir.model.access.csv
│   └── *.xml
├── data/                    # Dữ liệu chủ
│   └── *.xml
├── demo/                    # Dữ liệu demo
│   └── *.xml
├── static/                  # Tài sản web
│   └── description/
│       ├── icon.png
│       └── index.html
├── tests/                   # Mã kiểm thử
│   ├── __init__.py
│   └── test_*.py
└── README.rst               # Tài liệu module
```

**Quy ước đặt tên**  
- Module: `category_subcategory_feature`  
- Model: `module.model_name`  
- Field: `descriptive_field_name`  
- Method: `action_verb_object`

### Thực hành phát triển tốt
- Chọn loại field phù hợp dữ liệu  
- Triển khai ràng buộc & validation đúng  
- Tuân thủ lifecycle Odoo (create, write, unlink)  
- Dùng computed fields với dependencies đầy đủ  
- Tuân theo hướng dẫn UI/UX Odoo cho views  
- Thiết lập bảo mật: groups, access rights, record rules, validation input

## Kịch bản phát triển Odoo phổ biến

### Tạo module mới
**Phân tích yêu cầu**  
1) Xác định khoảng trống nghiệp vụ  
2) Ánh xạ vào khả năng Odoo  
3) Lập kế hoạch tùy chỉnh & tích hợp  
4) Thiết kế điểm tích hợp và dữ liệu

**Triển khai kỹ thuật**  
1) Tạo cấu trúc module  
2) Định nghĩa model & ràng buộc  
3) Triển khai logic nghiệp vụ  
4) Tạo views/UI  
5) Thiết lập bảo mật  
6) Viết kiểm thử & tài liệu

### Nâng cấp hệ thống hiện có (brownfield)
- Phân tích dependencies hiện hữu  
- Ưu tiên kế thừa, tránh chỉnh sửa trực tiếp  
- Đảm bảo khả năng nâng cấp và rollback  
- Kiểm thử kỹ với dữ liệu thật

### Phát triển tích hợp
- REST API, scheduled jobs, webhooks, import/export  
- Bảo mật API: xác thực, phân quyền, rate limiting, audit log  
- Kiểm thử tích hợp end-to-end

## Quản lý phiên bản & tương thích

### Chiến lược phiên bản Odoo
- Ưu tiên LTS cho production  
- Đánh giá tương thích module (OCA/custom)  
- Lập kế hoạch di chuyển dữ liệu & rollback  
- Kiểm thử nâng cấp theo kịch bản

### Quản lý module OCA
- Chọn module phù hợp yêu cầu & maturity  
- Quản lý dependencies, xung đột, hiệu suất  
- Đánh giá nhu cầu tùy chỉnh

## Tối ưu hiệu suất

### Cơ sở dữ liệu
- Dùng chỉ mục phù hợp, tối ưu domain & search  
- Phân trang, tránh N+1 queries  
- Lưu trữ/archiving dữ liệu cũ hợp lý  
- Batch processing cho khối lượng lớn

### Ứng dụng
- Tối ưu computed fields, caching hợp lý  
- Giảm số request và tối ưu render view  
- Chọn kích thước server phù hợp, cân bằng tải  
- Giám sát CPU/Mem/IO, cấu hình worker hợp lý

## Thực hành bảo mật

### Kiểm soát truy cập
- RBAC, nguyên tắc đặc quyền tối thiểu  
- MFA khi có thể, giám sát mẫu truy cập

### Bảo vệ dữ liệu
- Mã hóa dữ liệu nhạy cảm và backup  
- Giao thức truyền thông an toàn, tuân thủ quy định

### Bảo mật mã nguồn & API
- Xác thực/làm sạch mọi input  
- Chống SQL injection, XSS  
- Rate limiting cho API, audit log

## Chiến lược kiểm thử

### Kiểm thử đơn vị
- Bao phủ logic nghiệp vụ, ràng buộc, lỗi & biên  
- Đặt tên rõ ràng, dữ liệu kiểm thử chuẩn, kiểm thử độc lập

### Kiểm thử tích hợp
- Tương tác module, render view, bảo mật, tích hợp ngoài  
- Kiểm thử hiệu suất với dữ liệu thực tế

## Xử lý sự cố thường gặp

### Vấn đề phát triển
- Lỗi cài đặt: kiểm tra dependencies, manifest, quyền file  
- Hiệu suất: truy vấn chậm, dependencies của computed fields, search kém

### Vấn đề triển khai
- Kiểm tra cấu hình Docker, kết nối DB, biến môi trường, quyền file  
- Tích hợp: kiểm thử endpoint, xác thực/ủy quyền, định dạng dữ liệu, logs

## Nguồn tham khảo hữu ích

### Tài liệu chính thức
- Odoo Developer Docs: https://www.odoo.com/documentation/  
- OCA Guidelines: https://github.com/OCA/odoo-community.org  

### Công cụ phát triển
- VSCode/PyCharm extensions cho Odoo  
- Database tools: pgAdmin, DBeaver  
- API testing: Postman, Insomnia

### Nguồn cộng đồng
- OCA GitHub repos  
- Odoo Community Forums  
- Stack Overflow  
- YouTube tutorials

---

Kho kiến thức này là tài liệu tham khảo nhanh cho các tác nhân AI làm việc trên dự án phát triển Odoo theo workflow BMAD-METHOD. Nó cung cấp ngữ cảnh cần thiết để ra quyết định về mẫu phát triển Odoo, thực hành tốt nhất, và chiến lược tích hợp.***
