Compare commits

..

8 Commits

24 changed files with 593 additions and 28 deletions

View File

@@ -114,7 +114,20 @@ Tabel inti Odoo 19 yang digunakan dalam alur di atas:
---
## 6. Perintah Manajemen Docker
## 6. Master Data Import
Kami menyediakan file template Excel untuk mempercepat input data:
* **Lokasi Template:** `/templates/`
* **File tersedia:**
* `import-products.xlsx`: Template produk.
* `import-product-categories.xlsx`: Template kategori.
* `README-IMPORT.md`: Panduan lengkap import master data.
* **Catatan:** Jangan isi kolom `Item Code` saat import — sistem akan meng-generate-nya otomatis (format: `parent+child+id+name_slug`, koma → titik).
---
## 7. Perintah Manajemen Docker
* **Menjalankan stack:**
```bash

View File

@@ -9,6 +9,7 @@
'security/ir.model.access.csv',
'data/ir_sequence.xml',
'data/stock_picking_type.xml',
'views/product_views.xml',
],
'installable': True,
'application': False,

View File

@@ -2,3 +2,4 @@ from . import sale_order
from . import stock_picking
from . import product_category
from . import product_template
from . import product_product

View File

@@ -0,0 +1,13 @@
from odoo import models, fields, api
class ProductProduct(models.Model):
_inherit = 'product.product'
item_code = fields.Char(
string='Item Code',
related='product_tmpl_id.item_code',
store=True,
readonly=True,
help='Item Code dari template produk (variant menampilkan kode template).',
)

View File

@@ -9,10 +9,24 @@ class ProductTemplate(models.Model):
item_code = fields.Char(
string='Item Code',
index=True,
help='Kombinasi: parent_kode + kategori_kode + id_produk(4digit) + nama_produk_tanpa_spasi(lower)',
store=True,
readonly=False, # biar view bisa pakai; kita atur readonly di XML
help='Kombinasi: parent_kode + kategori_kode + id(+4 digit) + nama_tanpa_spasi(lower). '
'Read-only, dipakai sbg stock keeping unit code.',
)
@api.onchange('categ_id')
def _onchange_categ_preview(self):
"""Saat create belum simpan id -> tampilkan pratinjau gabungan kode kategori."""
if self.categ_id and not self.env.context.get('default_product_tmpl_id') \
and not self.id and not self.item_code:
cat = self.categ_id
if cat and not cat.code:
cat.code = f'{cat.id:02d}'
parent = cat.parent_id.code if cat.parent_id else ''
own = cat.code or ''
self.item_code = f'{parent}{own}'
@api.constrains('item_code')
def _check_item_code_unique(self):
for rec in self:
@@ -25,32 +39,36 @@ class ProductTemplate(models.Model):
f'({dup.name}). Item Code harus unik.'
)
def _generate_item_code(self):
"""Generate item_code: parent_code + cat_code + id:04d + name_slug"""
for p in self:
cat = p.categ_id
parent_code = ''
cat_code = '00'
def _category_prefix(self, cat):
"""Return gabungan kode kategori (parent+own), 4 digit atau 00."""
if not cat:
return '00'
if not cat.code:
cat.code = f'{cat.id:02d}'
parent_code = cat.parent_id.code if cat.parent_id else ''
own_code = cat.code or ''
return f'{parent_code}{own_code}'
if cat:
# Pastikan kategori punya code (calculate jika belum ada)
if not cat.code:
cat.code = f'{cat.id:02d}'
parent_code = cat.parent_id.code if cat.parent_id else ''
cat_code = cat.code
def _name_slug(self, name):
slug = (name or '').lower().replace(',', '.')
return re.sub(r'\s+', '', slug)
# slug: lowercase, remove semua spasi
name_slug = re.sub(r'\s+', '', (p.name or '').lower())
p.item_code = f'{parent_code}{cat_code}{p.id:04d}{name_slug}'
def _full_item_code(self, obj):
"""Compute full item_code: prefix kategori + id:04d + name_slug."""
prefix = self._category_prefix(obj.categ_id)
oid = obj.id or 0
return f'{prefix}{oid:04d}{self._name_slug(obj.name)}'
@api.model_create_multi
def create(self, vals_list):
records = super().create(vals_list)
records._generate_item_code()
for r in records:
r.item_code = r._full_item_code(r)
return records
def write(self, vals):
res = super().write(vals)
if 'name' in vals or 'categ_id' in vals:
self._generate_item_code()
return res
for r in self:
r.item_code = r._full_item_code(r)
return res

View File

@@ -20,10 +20,13 @@ class SaleOrder(models.Model):
order.name = seq.with_date(order.date_order or fields.Date.context_today(self)).next_by_code()
return super().action_confirm()
@api.model
def create(self, vals):
"""When creating a quotation (draft), use SQ sequence."""
if vals.get('state') == 'draft' and not vals.get('name'):
seq = self._get_quotation_sequence_id()
vals['name'] = seq.with_date(vals.get('date_order') or fields.Date.context_today(self)).next_by_code()
return super().create(vals)
@api.model_create_multi
def create(self, vals_list):
"""When creating quotations (draft), use the SQ sequence."""
for vals in vals_list:
if vals.get('state') == 'draft' and not vals.get('name'):
seq = self._get_quotation_sequence_id()
vals['name'] = seq.with_date(
vals.get('date_order') or fields.Date.context_today(self)
).next_by_code()
return super().create(vals_list)

View File

@@ -0,0 +1,118 @@
# Custom Product Code & Item Code Automation
## Overview
Odoo 17/19 Community tidak punya field `code` standar untuk product category. Untuk kebutuhan stock keeping unit (SKU) yang unik, kita buat field `item_code` yang di‑generate otomatis dari:
```
item_code = parent_category_code (2 digit) + category_code (2 digit) + product_id (4 digit) + name_slug (lowercase, no space)
```
Contoh:
- Kategori anak: id=06, parent=01 → prefix = `0106`
- Produk: id=3, nama="Backup BRT 30 x 36 x 1,25 mm"
- Hasil: `01060003backupbrt30x36x1,25mm`
## Implementation Steps
### 1. Extend `product.category` → field `code`
```python
class ProductCategory(models.Model):
_inherit = 'product.category'
code = fields.Char(string='Category Code', compute='_compute_code', store=True, size=4)
@api.model_create_multi
def create(self, vals_list):
records = super().create(vals_list)
for r in records:
r.code = f'{r.id:02d}'
return records
```
### 2. Extend `product.template` → field `item_code`
Field `item_code`:
- **Stored** (`store=True`) — dipakai untuk pencarian & unique index.
- **Read‑only di view** — tidak boleh ditulis manual.
- **On‑change preview** → tampilkan prefix kategori saat buat produk baru.
```python
class ProductTemplate(models.Model):
_inherit = 'product.template'
item_code = fields.Char(string='Item Code', store=True, readonly=False)
_sql_constraints = [
('item_code_unique', 'UNIQUE(item_code)', 'Item Code harus unik.'),
]
@api.model_create_multi
def create(self, vals_list):
records = super().create(vals_list)
for r in records:
r.item_code = r._full_item_code(r)
return records
def write(self, vals):
res = super().write(vals)
if 'name' in vals or 'categ_id' in vals:
for r in self:
r.item_code = r._full_item_code(r)
return res
```
### 3. Extend `product.product` (varian)
Untuk produk ber‑varian, `item_code` diturunkan via related field ke template:
```python
class ProductProduct(models.Model):
_inherit = 'product.product'
item_code = fields.Char(
string='Item Code',
related='product_tmpl_id.item_code',
store=True,
readonly=True,
)
```
### 4. XML View — field read‑only
```xml
<!-- product_template_form_view inheritance -->
<field name="default_code" position="after">
<field name="item_code" readonly="1" placeholder="Terisi otomatis"/>
</field>
```
### 5. PostgreSQL — Unique Index (optional, backup)
Constraint `__sql_constraints` sudah menambah unique index via Odoo ORM. Untuk kecepatan lebih cepat di PostgreSQL level, dapat manual:
```sql
CREATE UNIQUE INDEX IF NOT EXISTS product_template_item_code_uniq
ON product_template (item_code) WHERE item_code IS NOT NULL;
```
### 6. Migration — isi data existing
```python
env.cr.execute("""
CREATE UNIQUE INDEX IF NOT EXISTS product_template_item_code_uniq
ON product_template (item_code) WHERE item_code IS NOT NULL
""")
cats = env['product.category'].search([])
for c in cats:
if not c.code:
c.code = f'{c.id:02d}'
prods = env['product.template'].search([])
for p in prods:
p.item_code = p._full_item_code(p)
```
## Pitfalls
- `@api.depends('id')` **not allowed** di Odoo 19. Namun `id` tersedia di `create()` setelah super() selesai.
- Field `code` di kategori **harus `size` ditentukan** ( Odoo 17+ lint error tanpa `size`)
- Product dengan `categ_id = False` → gunakan fallback `00`.
- **Item Code read‑only di view**: bila pakai `store=True`, field tetap dapat ditulis via ORM (API). Untuk mencegah manual edit, gunakan `readonly=True` + `@api.constrains` untuk validasi.
## References
- `models/product_template.py` — contoh implementasi lengkap (sudah ada di addon `kosbar_erp_ext`)
- `views/product_views.xml` — XML view inheritance

View File

@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8"?>
<odoo>
<!-- Product Template form: Item Code read_only -->
<record id="view_product_template_item_code" model="ir.ui.view">
<field name="name">product.template.form.item.code</field>
<field name="model">product.template</field>
<field name="inherit_id" ref="product.product_template_form_view"/>
<field name="arch" type="xml">
<xpath expr="//field[@name='categ_id']" position="after">
<field name="item_code" readonly="1"
placeholder="Terisi otomatis setelah simpan"/>
</xpath>
</field>
</record>
<!-- Product Variant/Master form: Item Code read_only -->
<record id="view_product_product_item_code" model="ir.ui.view">
<field name="name">product.product.form.item.code</field>
<field name="model">product.product</field>
<field name="inherit_id" ref="product.product_normal_form_view"/>
<field name="arch" type="xml">
<xpath expr="//field[@name='categ_id']" position="after">
<field name="item_code" readonly="1"/>
</xpath>
</field>
</record>
</odoo>

View File

@@ -0,0 +1 @@
from . import models

View File

@@ -0,0 +1,18 @@
{
'name': 'Kos Barokah Purchase Finance',
'version': '1.0',
'category': 'Purchases',
'summary': 'Permintaan barang gudang + approval PO oleh Finance',
'author': 'Kos Barokah',
'license': 'LGPL-3',
'depends': ['purchase', 'stock', 'product', 'kosbar_erp_ext'],
'data': [
'security/res_groups.xml',
'security/ir.model.access.csv',
'data/ir_sequence.xml',
'views/purchase_request_views.xml',
'views/purchase_order_views.xml',
],
'installable': True,
'application': False,
}

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<odoo>
<data noupdate="1">
<record id="seq_purchase_request" model="ir.sequence">
<field name="name">Purchase Request Kos Barokah</field>
<field name="code">kosbar.purchase.request</field>
<field name="padding">5</field>
<field name="prefix">PR/%(year)s/</field>
</record>
</data>
</odoo>

View File

@@ -0,0 +1,2 @@
from . import purchase_request
from . import purchase_order

View File

@@ -0,0 +1,24 @@
from odoo import models, fields, api
class PurchaseOrder(models.Model):
_inherit = 'purchase.order'
finance_state = fields.Selection([
('pending', 'Pending Approval'),
('approved', 'Finance Approved'),
('rejected', 'Rejected'),
], string='Status Finance', default='pending', tracking=True)
def action_finance_approve(self):
"""Finance mengklik ini setelah review PO."""
return self.write({'finance_state': 'approved'})
def action_finance_reject(self):
"""Finance menolak PO — ada catatan di notes."""
return self.write({'finance_state': 'rejected'})
@api.model
def _get_state_color(self):
# optional: styling di kanban view
return {'pending': 'warning', 'approved': 'success', 'rejected': 'danger'}

View File

@@ -0,0 +1,79 @@
from odoo import models, fields, api
class PurchaseRequest(models.Model):
_name = 'kosbar.purchase.request'
_description = 'Purchase Request dari Gudang'
_order = 'id desc'
name = fields.Char(
string='Nomor Request',
required=True,
copy=False,
readonly=True,
default='New',
)
user_id = fields.Many2one(
'res.users',
string='Diminta Oleh',
default=lambda self: self.env.user,
required=True,
)
date_required = fields.Date(string='Tanggal Dibutuhkan', default=fields.Date.today())
state = fields.Selection([
('draft', 'Draft'),
('submitted', 'Submitted'),
('approved', 'Approved / In Progress'),
('done', 'Done'),
('rejected', 'Rejected'),
], string='Status', default='draft', tracking=True)
line_ids = fields.One2many(
'kosbar.purchase.request.line',
'request_id',
string='Daftar Barang',
)
notes = fields.Text(string='Catatan / Keperluan')
@api.model_create_multi
def create(self, vals_list):
for vals in vals_list:
if vals.get('name', 'New') == 'New':
seq = self.env['ir.sequence'].next_by_code('kosbar.purchase.request')
vals['name'] = seq if seq else 'PR/2026/00001'
return super().create(vals_list)
def action_submit(self):
self.write({'state': 'submitted'})
def action_approve(self):
self.write({'state': 'approved'})
def action_done(self):
self.write({'state': 'done'})
def action_reject(self):
self.write({'state': 'rejected'})
def action_draft(self):
self.write({'state': 'draft'})
class PurchaseRequestLine(models.Model):
_name = 'kosbar.purchase.request.line'
_description = 'Detail Item Purchase Request'
request_id = fields.Many2one('kosbar.purchase.request', string='Request Reference', ondelete='cascade')
# Bisa pilih barang existing ATAU buat barang baru langsung
is_new_product = fields.Boolean(string='Barang Baru?', default=False)
product_id = fields.Many2one('product.product', string='Produk (Existing)')
# Jika barang baru
new_product_name = fields.Char(string='Nama Barang Baru')
categ_id = fields.Many2one('product.category', string='Kategori Barang')
product_qty = fields.Float(string='Jumlah', default=1.0, required=True)
product_uom = fields.Many2one('uom.uom', string='Satuan', default=lambda self: self.env.ref('uom.product_uom_unit', raise_if_not_found=False))
price_unit = fields.Float(string='Estimasi Harga Satuan')
notes = fields.Char(string='Keterangan')

View File

@@ -0,0 +1,4 @@
id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink
access_purchase_request,access_purchase_request,model_kosbar_purchase_request,base.group_user,1,1,1,0
access_purchase_request_line,access_purchase_request_line,model_kosbar_purchase_request_line,base.group_user,1,1,1,0
access_purchase_order_finance,access_purchase_order_finance,model_purchase_order,kosbar_purchase_finance.group_finance,1,1,0,0
1 id name model_id:id group_id:id perm_read perm_write perm_create perm_unlink
2 access_purchase_request access_purchase_request model_kosbar_purchase_request base.group_user 1 1 1 0
3 access_purchase_request_line access_purchase_request_line model_kosbar_purchase_request_line base.group_user 1 1 1 0
4 access_purchase_order_finance access_purchase_order_finance model_purchase_order kosbar_purchase_finance.group_finance 1 1 0 0

View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<odoo>
<data noupdate="1">
<!-- Group Finance khusus -->
<record id="group_finance" model="res.groups">
<field name="name">Finance / Accounting Approval</field>
<field name="implied_ids" eval="[(4, ref('base.group_user'))]"/>
</record>
</data>
</odoo>

View File

@@ -0,0 +1,42 @@
<?xml version="1.0" encoding="utf-8"?>
<odoo>
<!-- Purchase Order : inherit form utk approval finance -->
<record id="view_purchase_order_finance" model="ir.ui.view">
<field name="name">purchase.order.form.finance</field>
<field name="model">purchase.order</field>
<field name="inherit_id" ref="purchase.purchase_order_form"/>
<field name="arch" type="xml">
<!-- Tombol approve/reject di header PO -->
<xpath expr="//header" position="inside">
<button name="action_finance_approve" string="Finance Approve"
type="object" class="btn-success"
groups="kosbar_purchase_finance.group_finance"
invisible="finance_state in ['approved','rejected']"/>
<button name="action_finance_reject" string="Finance Reject"
type="object" class="btn-danger"
groups="kosbar_purchase_finance.group_finance"
invisible="finance_state == 'rejected'"/>
</xpath>
<!-- Field status finance di sheet -->
<xpath expr="//sheet/div[hasclass('oe_button_box')]" position="inside">
<field name="finance_state" readonly="1"
class="oe_stat_button" icon="fa-money"/>
</xpath>
</field>
</record>
<!-- Status finance di list view PO -->
<record id="view_purchase_order_finance_tree" model="ir.ui.view">
<field name="name">purchase.order.tree.finance</field>
<field name="model">purchase.order</field>
<field name="inherit_id" ref="purchase.purchase_order_tree"/>
<field name="arch" type="xml">
<field name="state" position="after">
<field name="finance_state" readonly="1"/>
</field>
</field>
</record>
</odoo>

View File

@@ -0,0 +1,85 @@
<?xml version="1.0" encoding="utf-8"?>
<odoo>
<!-- Purchase Request : List view -->
<record id="view_purchase_request_tree" model="ir.ui.view">
<field name="name">kosbar.purchase.request.tree</field>
<field name="model">kosbar.purchase.request</field>
<field name="arch" type="xml">
<list string="Permintaan Barang" editable="bottom">
<field name="name"/>
<field name="user_id"/>
<field name="date_required"/>
<field name="state"/>
</list>
</field>
</record>
<!-- Purchase Request : Form view -->
<record id="view_purchase_request_form" model="ir.ui.view">
<field name="name">kosbar.purchase.request.form</field>
<field name="model">kosbar.purchase.request</field>
<field name="arch" type="xml">
<form string="Permintaan Barang">
<header>
<button name="action_submit" string="Submit" type="object"
class="btn-primary" invisible="state != 'draft'"/>
<button name="action_approve" string="Approved" type="object"
class="btn-success" invisible="state != 'submitted'"/>
<button name="action_done" string="Mark Done" type="object"
class="btn-secondary" invisible="state != 'approved'"/>
<button name="action_reject" string="Reject" type="object"
class="btn-danger" invisible="state != 'submitted'"/>
<button name="action_draft" string="Reset to Draft" type="object"
invisible="state != 'rejected'"/>
<field name="state" widget="statusbar" statusbar_visible="draft,submitted,approved,done"/>
</header>
<sheet>
<div class="oe_title">
<h1><field name="name" readonly="1"/></h1>
</div>
<group>
<group>
<field name="user_id"/>
<field name="date_required"/>
</group>
<group>
<field name="state" readonly="1"/>
</group>
</group>
<notebook>
<page string="Barang">
<field name="line_ids">
<list editable="bottom">
<field name="is_new_product"/>
<field name="product_id" invisible="is_new_product"/>
<field name="new_product_name" invisible="not is_new_product"/>
<field name="categ_id" invisible="not is_new_product"/>
<field name="product_qty"/>
<field name="product_uom"/>
<field name="price_unit"/>
<field name="notes" optional="show"/>
</list>
</field>
</page>
<page string="Keterangan">
<field name="notes" placeholder="Keperluan / alasan pembelian"/>
</page>
</notebook>
</sheet>
</form>
</field>
</record>
<!-- Action & Menu -->
<record id="action_purchase_request" model="ir.actions.act_window">
<field name="name">Permintaan Barang</field>
<field name="res_model">kosbar.purchase.request</field>
<field name="view_mode">list,form</field>
</record>
<menuitem id="menu_purchase_request"
name="Permintaan Barang"
parent="purchase.menu_purchase_root"
action="action_purchase_request"
sequence="70"/>
</odoo>

View File

@@ -0,0 +1,28 @@
# Template Import Odoo
Folder ini berisi contoh file template untuk import master data ke Odoo ERP.
## Isi Folder
| File | Kegunaan |
|---|---|
| `import-products.xlsx` | Template import produk (Product Name, Category, Price, Cost, Barcode) |
| `import-product-categories.xlsx` | Template import kategori produk (Name + Parent Category) |
| `import-product-categories.csv` | Versi CSV kategori (untuk referensi/format cepat) |
## Cara Pakai
1. **Kategori dulu, baru Produk** (Produk butuh kategori yang sudah ada).
2. Buka Odoo → **Inventory/Sales → Configuration → Product Categories** → tombol **Import**.
- Petakan: `Nama Kategori` → `Name`, `Parent Category` → `Parent Category`.
3. Setelah kategori masuk, `code` 2-digit otomatis terisi oleh addon.
4. Buka **Inventory/Sales → Products → Products** → tombol **Import**.
- Petakan: `Product Name` → `Name`, `Product Category` → `Product Category`, dll.
5. **Jangan isi** kolom `Item Code`/`Internal Reference` — otomatis di-generate addon.
- Format: `parent_code + child_code + product_id(4) + nama_lowercase_tanpa_spasi (koma → titik)`.
## Contoh hasil otomatis
- Kategori `Elektronik` (code `01`), kategori `Laptop` (code `04`, parent `Elektronik`), produk `MacBook Air M2` (id `0001`):
- `item_code = 01040001macbookairm2`
## Opsi cli
```bash
python3 -m venv /tmp/xlsxenv && /tmp/...
```

View File

@@ -0,0 +1,60 @@
#!/usr/bin/env python3
"""Generate template Excel untuk import produk & kategori Odoo."""
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment
HEADER_FILL = PatternFill('solid', fgColor='0B6E4F')
HEADER_FONT = Font(bold=True, color='FFFFFF')
def styled_header(ws, headers):
ws.append(headers)
for cell in ws[1]:
cell.fill = HEADER_FILL
cell.font = HEADER_FONT
cell.alignment = Alignment(horizontal='center')
# ---------- 1. Template Produk ----------
wb = Workbook()
ws = wb.active
ws.title = 'Products'
styled_header(ws, ['Product Name', 'Product Category', 'Sales Price', 'Cost', 'Barcode'])
rows = [
['iPhone 15 128GB', 'Smartphone', 15000000, 12000000, 1234567890123],
['Samsung Galaxy S24', 'Smartphone', 14000000, 11000000, 1234567890124],
['MacBook Air M2', 'Laptop', 25000000, 20000000, 1234567890125],
['Wireless Mouse', 'Mouse', 500000, 350000, 1234567890126],
['Mechanical Keyboard', 'Keyboard', 750000, 500000, 1234567890127],
]
for r in rows:
ws.append(r)
widths = [22, 18, 13, 13, 16]
for i, w in enumerate(widths, 1):
ws.column_dimensions[chr(64 + i)].width = w
wb.save('/home/ardhi/Application/odoo-erp/templates/import-products.xlsx')
print('OK: import-products.xlsx')
# ---------- 2. Template Kategori ----------
wb2 = Workbook()
ws2 = wb2.active
ws2.title = 'Categories'
styled_header(ws2, ['Nama Kategori', 'Parent Category'])
cat_rows = [
['Elektronik', ''],
['Smartphone', 'Elektronik'],
['Laptop', 'Elektronik'],
['Aksesoris', ''],
['Mouse', 'Aksesoris'],
['Keyboard', 'Aksesoris'],
]
for r in cat_rows:
ws2.append(r)
ws2.column_dimensions['A'].width = 22
ws2.column_dimensions['B'].width = 22
wb2.save('/home/ardhi/Application/odoo-erp/templates/import-product-categories.xlsx')
print('OK: import-product-categories.xlsx')

View File

@@ -0,0 +1,7 @@
Nama Kategori,Parent Category
Elektronik,
Smartphone,Electronics
Laptop,Electronics
Aksesoris,
Mouse,Aksesoris
Keyboard,Aksesoris
1 Nama Kategori Parent Category
2 Elektronik
3 Smartphone Electronics
4 Laptop Electronics
5 Aksesoris
6 Mouse Aksesoris
7 Keyboard Aksesoris

Binary file not shown.

Binary file not shown.