summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRafi Zadanly <zadanlyr@gmail.com>2023-08-16 11:06:36 +0700
committerRafi Zadanly <zadanlyr@gmail.com>2023-08-16 11:06:36 +0700
commit3a954e59343d2d3a3df5436297f7007008ae62e8 (patch)
treebf4db37ee3fe1a745a99b5cba2d4d5d446319628
parentdd233630dce7128b6e25660db3e655b0a2e069e3 (diff)
Refactor sale order and sale order line
-rwxr-xr-xindoteknik_custom/models/__init__.py1
-rwxr-xr-xindoteknik_custom/models/sale_order.py413
-rw-r--r--indoteknik_custom/models/sale_order_line.py182
3 files changed, 246 insertions, 350 deletions
diff --git a/indoteknik_custom/models/__init__.py b/indoteknik_custom/models/__init__.py
index 843beeae..5de392ca 100755
--- a/indoteknik_custom/models/__init__.py
+++ b/indoteknik_custom/models/__init__.py
@@ -27,6 +27,7 @@ from . import res_partner_company_type
from . import res_partner
from . import res_users
from . import sale_order
+from . import sale_order_line
from . import sale_monitoring_detail
from . import sale_monitoring
from . import sales_outstanding
diff --git a/indoteknik_custom/models/sale_order.py b/indoteknik_custom/models/sale_order.py
index 0f4c5c2e..036fba1b 100755
--- a/indoteknik_custom/models/sale_order.py
+++ b/indoteknik_custom/models/sale_order.py
@@ -1,26 +1,21 @@
from odoo import fields, models, api, _
from odoo.exceptions import UserError
-import logging, random, string, requests, math, json
+import logging, random, string, requests, math, json, re
_logger = logging.getLogger(__name__)
class SaleOrder(models.Model):
_inherit = "sale.order"
- total_margin = fields.Float(
- 'Total Margin', compute='compute_total_margin',
- help="Total Margin in Sales Order Header")
- total_percent_margin = fields.Float(
- 'Total Percent Margin', compute='compute_total_margin',
- help="Total % Margin in Sales Order Header")
+ total_margin = fields.Float('Total Margin', compute='_compute_total_margin', help="Total Margin in Sales Order Header")
+ total_percent_margin = fields.Float('Total Percent Margin', compute='_compute_total_percent_margin', help="Total % Margin in Sales Order Header")
approval_status = fields.Selection([
('pengajuan1', 'Approval Manager'),
('pengajuan2', 'Approval Pimpinan'),
('approved', 'Approved'),
], string='Approval Status', readonly=True, copy=False, index=True, tracking=3)
carrier_id = fields.Many2one('delivery.carrier', string='Shipping Method')
- have_visit_service = fields.Boolean(string='Have Visit Service', help='To compute is customer get visit service',
- compute='_have_visit_service')
+ have_visit_service = fields.Boolean(string='Have Visit Service', compute='_have_visit_service', help='To compute is customer get visit service')
delivery_amt = fields.Float('Delivery Amt')
shipping_cost_covered = fields.Selection([
('indoteknik', 'Indoteknik'),
@@ -30,8 +25,7 @@ class SaleOrder(models.Model):
('indoteknik', 'Indoteknik'),
('customer', 'Customer')
], string='Shipping Paid by', help='Siapa yang talangin dulu Biaya ekspedisi-nya?', copy=False)
- sales_tax_id = fields.Many2one('account.tax', string='Tax',
- domain=['|', ('active', '=', False), ('active', '=', True)])
+ sales_tax_id = fields.Many2one('account.tax', string='Tax', domain=['|', ('active', '=', False), ('active', '=', True)])
have_outstanding_invoice = fields.Boolean('Have Outstanding Invoice', compute='_have_outstanding_invoice')
have_outstanding_picking = fields.Boolean('Have Outstanding Picking', compute='_have_outstanding_picking')
have_outstanding_po = fields.Boolean('Have Outstanding PO', compute='_have_outstanding_po')
@@ -84,15 +78,11 @@ class SaleOrder(models.Model):
source_id = fields.Many2one('utm.source', 'Source', domain="[('id', 'in', [32, 59, 60, 61])]")
def _compute_purchase_total(self):
-
for order in self:
total = 0
for line in order.order_line:
total += line.vendor_subtotal
order.purchase_total = total
- end_time = time.time()
- execution_time = end_time - start_time
- print(f"Total execution time: {execution_time} seconds")
def generate_payment_link_midtrans_sales_order(self):
# midtrans_url = 'https://app.sandbox.midtrans.com/snap/v1/transactions' # dev - sandbox
@@ -136,7 +126,6 @@ class SaleOrder(models.Model):
if line.product_id.type == 'product':
line_no += 1
line.line_no = line_no
- # _logger.info('Calculate PO Line No %s' % line.id)
def write(self, vals):
res = super(SaleOrder, self).write(vals)
@@ -154,10 +143,7 @@ class SaleOrder(models.Model):
('state', 'in', so_state),
('so_status', '!=', 'terproses'),
])
- sales = self.browse(12656)
for sale in sales:
- print(sale.check_due())
- continue
picking_states = {'draft', 'assigned', 'confirmed', 'waiting'}
have_outstanding_pick = any(x.state in picking_states for x in sale.picking_ids)
@@ -236,19 +222,25 @@ class SaleOrder(models.Model):
order.has_due = False
order.is_warning = False
+ def _validate_order(self):
+ if self.warehouse_id.id != 8: #GD Bandengan
+ raise UserError('Gudang harus Bandengan')
+ if self.state not in ['draft', 'sent']:
+ raise UserError("Status harus draft atau sent")
+ if not self._validate_npwp():
+ raise UserError("Isi NPWP Dengan Benar!")
+
+ def _validate_npwp(self):
+ pattern = r'^\d{2}\.\d{3}\.\d{3}\.\d{1}-\d{3}\.\d{3}$'
+ return re.match(pattern, self.npwp) is not None
+
def sale_order_approve(self):
self.check_due()
for order in self:
- if order.warehouse_id.id != 8: #GD Bandengan
- raise UserError('Gudang harus Bandengan')
- if order.state not in ['draft', 'sent']:
- raise UserError("Status harus draft atau sent")
- if not order.partner_invoice_id.npwp:
- raise UserError("NPWP harus diisi di master data konsumen, jika non pkp dapat diisi 00.000.000.0-000.000")
- if '-' not in order.npwp or '.' not in order.npwp:
- raise UserError("Isi NPWP Dengan Benar!")
-
+ order._validate_order()
+ order.order_line.validate_line()
+
partner = order.partner_id.parent_id or order.partner_id
if not partner.property_payment_term_id:
raise UserError("Payment Term pada Master Data Customer harus diisi")
@@ -257,19 +249,37 @@ class SaleOrder(models.Model):
if order.payment_term_id != partner.property_payment_term_id:
raise UserError("Payment Term berbeda pada Master Data Customer")
- order.order_line.validate_confirm()
-
if order.validate_partner_invoice_due():
- return self._notification_has_unapprove_due()
+ return self._create_notification_action('Notification', 'Terdapat invoice yang telah melewati batas waktu, mohon perbarui pada dokumen Due Extension')
- if order._notification_margin_leader():
+ if order._requires_approval_margin_leader():
order.approval_status = 'pengajuan2'
- return self._notification_has_margin_leader()
- elif order._notification_margin_manager():
+ return self._create_approval_notification('Pimpinan')
+ elif order._requires_approval_margin_manager():
order.approval_status = 'pengajuan1'
- return self._notification_has_margin_manager()
+ return self._create_approval_notification('Sales Manager')
raise UserError("Bisa langsung Confirm")
+
+ def action_confirm(self):
+ for order in self:
+ order._validate_order()
+ order.order_line.validate_line()
+
+ if order.validate_partner_invoice_due():
+ return self._create_notification_action('Notification', 'Terdapat invoice yang telah melewati batas waktu, mohon perbarui pada dokumen Due Extension')
+
+ if order._requires_approval_margin_leader():
+ return self._create_approval_notification('Pimpinan')
+ elif order._requires_approval_margin_manager():
+ return self._create_approval_notification('Sales Manager')
+
+ order.approval_status = 'approved'
+ order._set_sppkp_npwp_contact()
+ order.calculate_line_no()
+
+ res = super(SaleOrder, self).action_confirm()
+ return res
def action_cancel(self):
# TODO stephan prevent cancel if have invoice, do, and po
@@ -317,49 +327,22 @@ class SaleOrder(models.Model):
due_extension.unlink()
return False
- def _notification_margin_leader(self):
- if self.total_percent_margin <= 15 and not self.env.user.is_leader:
- return True
- else:
- return False
+ def _requires_approval_margin_leader(self):
+ return self.total_percent_margin <= 15 and not self.env.user.is_leader
- def _notification_margin_manager(self):
- if self.total_percent_margin <= 22 and not self.env.user.is_leader and not self.env.user.is_sales_manager:
- return True
- else:
- return False
-
- def _notification_has_unapprove_due(self):
- return {
- 'type': 'ir.actions.client',
- 'tag': 'display_notification',
- 'params': {
- 'title': 'Notification',
- 'message': 'Ada Invoice Yang Sudah Over Due, Silahkan Memperbarui Over Due di Due Extension',
- 'next': {'type': 'ir.actions.act_window_close'},
- }
- }
+ def _requires_approval_margin_manager(self):
+ return self.total_percent_margin <= 22 and not self.env.user.is_leader and not self.env.user.is_sales_manager
- def _notification_has_margin_leader(self):
- return {
- 'type': 'ir.actions.client',
- 'tag': 'display_notification',
- 'params': {
- 'title': 'Notification',
- 'message': 'SO Harus Di Approve Oleh Pimpinan',
- 'next': {'type': 'ir.actions.act_window_close'},
- }
- }
-
- def _notification_has_margin_manager(self):
+ def _create_approval_notification(self, approval_role):
+ title = 'Warning'
+ message = f'SO butuh approval {approval_role}'
+ return self._create_notification_action(title, message)
+
+ def _create_notification_action(self, title, message):
return {
'type': 'ir.actions.client',
'tag': 'display_notification',
- 'params': {
- 'title': 'Notification',
- 'message': 'SO Harus Di Approve Oleh Sales Manager',
- 'next': {'type': 'ir.actions.act_window_close'},
- }
+ 'params': { 'title': title, 'message': message }
}
def _set_sppkp_npwp_contact(self):
@@ -369,82 +352,16 @@ class SaleOrder(models.Model):
partner.npwp = self.npwp
partner.sppkp = self.sppkp
- def action_confirm(self):
+ def _compute_total_margin(self):
for order in self:
- if order.warehouse_id.id != 8: #GD Bandengan
- raise UserError('Gudang harus Bandengan')
- if '-' not in order.npwp or '.' not in order.npwp:
- raise UserError("Isi NPWP Dengan Benar!")
-
- order.order_line.validate_confirm()
-
- if order.validate_partner_invoice_due():
- return self._notification_has_unapprove_due()
-
- if order._notification_margin_leader():
- return self._notification_has_margin_leader()
- elif order._notification_margin_manager():
- return self._notification_has_margin_manager()
- else:
- order.approval_status = 'approved'
- order._set_sppkp_npwp_contact()
- order.calculate_line_no()
-
- res = super(SaleOrder, self).action_confirm()
- return res
-
- def _have_outstanding_invoices(self):
- partner_id = self.partner_id
- if self.partner_id.parent_id:
- partner_id = self.partner_id
- partners = []
- partners += partner_id.child_ids
- partners.append(partner_id)
- for partner in partners:
- query = [
- ('partner_id', '=', partner.id),
- ('state', '=', 'posted'),
- ('move_type', '=', 'out_invoice'),
- ('amount_residual_signed', '>', 0)
- ]
- invoices = self.env['account.move'].search(query)
- for invoice in invoices:
- if invoice.invoice_day_to_due < 0:
- self.notification = 'Ada %s yang sudah jatuh tempo dan belum lunas' % invoice.name
- # self.env.cr.commit()
- return True
-
-
- def compute_total_margin(self):
- for order in self:
- total_margin = total_percent_margin = 0
- for line in order.order_line:
- if not line.product_id:
- order.total_margin = 0
- order.total_percent_margin = 0
- continue
- total_margin += line.item_margin
- # sales_price = line.price_reduce_taxexcl * line.product_uom_qty
- # if line.order_id.shipping_cost_covered == 'indoteknik':
- # sales_price -= line.delivery_amt_line
- # if line.order_id.fee_third_party > 0:
- # sales_price -= line.fee_third_party_line
- # sum_sales_price += sales_price
+ total_margin = sum(line.item_margin for line in order.order_line if line.product_id)
order.total_margin = total_margin
- if order.amount_untaxed > 0:
- total_percent_margin = round((total_margin / order.amount_untaxed), 2) * 100
- order.total_percent_margin = total_percent_margin
-
- def compute_count_line_product(self):
+
+ def _compute_total_percent_margin(self):
for order in self:
- count = 0
- for line in order.order_line:
- if line.product_id.type == 'product':
- count += 1
- if count == 0:
- order.count_line_product = 1
- else:
- order.count_line_product = count
+ if order.amount_untaxed == 0:
+ continue
+ order.total_percent_margin = round((order.total_margin / order.amount_untaxed) * 100, 2)
@api.onchange('sales_tax_id')
def onchange_sales_tax_id(self):
@@ -458,207 +375,3 @@ class SaleOrder(models.Model):
else:
order.grand_total = order.amount_total
-
-class SaleOrderLine(models.Model):
- _inherit = 'sale.order.line'
- item_margin = fields.Float(
- 'Margin', compute='compute_item_margin',
- help="Total Margin in Sales Order Header")
- item_percent_margin = fields.Float(
- '%Margin', compute='compute_item_margin',
- help="Total % Margin in Sales Order Header")
- vendor_id = fields.Many2one(
- 'res.partner', string='Vendor', readonly=True,
- states={'draft': [('readonly', False)], 'sent': [('readonly', False)]},
- change_default=True, index=True, tracking=1,
- domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]",)
- purchase_price = fields.Float('Purchase', required=True, digits='Product Price', default=0.0)
- purchase_tax_id = fields.Many2one('account.tax', string='Tax',
- domain=['|', ('active', '=', False), ('active', '=', True)])
- delivery_amt_line = fields.Float('DeliveryAmtLine', compute='compute_delivery_amt_line')
- fee_third_party_line = fields.Float('FeeThirdPartyLine', compute='compute_fee_third_party_line', default=0)
- line_no = fields.Integer('No', default=0, copy=False)
- note_procurement = fields.Char(string='Note', help="Harap diisi jika ada keterangan tambahan dari Procurement, agar dapat dimonitoring")
- vendor_subtotal = fields.Float(string='Vendor Subtotal', compute="_compute_vendor_subtotal")
- amount_voucher_disc = fields.Float(string='Voucher Discount')
- program_line_id = fields.Many2one('promotion.program.line', 'Program Line')
-
- def _compute_vendor_subtotal(self):
- for line in self:
- if line.purchase_price > 0 and line.product_uom_qty > 0:
- # product = line.product_id
-
- # if product:
- # vendor_price = line.purchase_price
- # if line.purchase_tax_id.price_include:
- # vendor_price = line.purchase_price
- # else:
- # vendor_price = line.purchase_price + (line.purchase_price*11/100)
- subtotal = line.purchase_price * line.product_uom_qty
- line.vendor_subtotal = subtotal
- else:
- line.vendor_subtotal = 0
-
- def compute_item_margin(self):
- for line in self:
- if not line.product_id or line.product_id.type == 'service' \
- or line.price_unit <= 0 or line.product_uom_qty <= 0 \
- or not line.vendor_id:
- line.item_margin = 0
- line.item_percent_margin = 0
- continue
- # calculate margin without tax
- sales_price = line.price_reduce_taxexcl * line.product_uom_qty
- # minus with delivery if covered by indoteknik
- if line.order_id.shipping_cost_covered == 'indoteknik':
- sales_price -= line.delivery_amt_line
- if line.order_id.fee_third_party > 0:
- sales_price -= line.fee_third_party_line
-
- purchase_price = line.purchase_price
- if line.purchase_tax_id.price_include:
- purchase_price = line.purchase_price / 1.11
-
- purchase_price = purchase_price * line.product_uom_qty
- margin_per_item = sales_price - purchase_price
- line.item_margin = margin_per_item
-
- if sales_price > 0:
- line.item_percent_margin = round((margin_per_item / sales_price), 2) * 100
- else:
- line.item_percent_margin = 0
-
- @api.onchange('vendor_id')
- def onchange_vendor_id(self):
- if not self.product_id or self.product_id.type == 'service':
- return
- elif self.product_id.categ_id.id == 34: # finish good / manufacturing only
- # bom = self.env['mrp.bom'].search(
- # [('product_tmpl_id', '=', self.product_id.product_tmpl_id.id)]
- # , limit=1)
- # cost = 0
- # for line in bom.bom_line_ids:
- # purchase_price = self.env['purchase.pricelist'].search(
- # [('vendor_id', '=', self.vendor_id.id), ('product_id', '=', line.product_id.id)], limit=1)
- # cost += purchase_price.product_price
- cost = self.product_id.standard_price
- self.purchase_price = cost
- else:
- purchase_price = self.env['purchase.pricelist'].search(
- [('vendor_id', '=', self.vendor_id.id), ('product_id', '=', self.product_id.id)], limit=1)
- self.purchase_price = purchase_price.product_price
- self.purchase_tax_id = 22
-
- @api.onchange('product_id')
- def product_id_change(self):
- super(SaleOrderLine, self).product_id_change()
- for line in self:
- if line.product_id and line.product_id.type == 'product':
- purchase_price = self.env['purchase.pricelist'].search(
- [('product_id', '=', self.product_id.id)], limit=1, order='product_price ASC')
- line.vendor_id = purchase_price.vendor_id
- line.tax_id = line.order_id.sales_tax_id
- line.purchase_price = purchase_price.product_price
-
- def compute_delivery_amt_line(self):
- for line in self:
- try:
- contribution = round((line.price_total / line.order_id.amount_total), 2)
- except:
- contribution = 0
- delivery_amt = line.order_id.delivery_amt
- line.delivery_amt_line = delivery_amt * contribution
-
- def compute_fee_third_party_line(self):
- for line in self:
- try:
- contribution = round((line.price_total / line.order_id.amount_total), 2)
- except:
- contribution = 0
- fee = line.order_id.fee_third_party
- line.fee_third_party_line = fee * contribution
-
- @api.onchange('product_id', 'price_unit', 'product_uom', 'product_uom_qty', 'tax_id')
- def _onchange_discount(self):
- if not (self.product_id and self.product_uom and
- self.order_id.partner_id and self.order_id.pricelist_id and
- self.order_id.pricelist_id.discount_policy == 'without_discount' and
- self.env.user.has_group('product.group_discount_per_so_line')):
- return
-
- self.discount = 0.0
- product = self.product_id.with_context(
- lang=self.order_id.partner_id.lang,
- partner=self.order_id.partner_id,
- quantity=self.product_uom_qty,
- date=self.order_id.date_order,
- pricelist=self.order_id.pricelist_id.id,
- uom=self.product_uom.id,
- fiscal_position=self.env.context.get('fiscal_position')
- )
-
- product_context = dict(self.env.context, partner_id=self.order_id.partner_id.id, date=self.order_id.date_order,
- uom=self.product_uom.id)
-
- price, rule_id = self.order_id.pricelist_id.with_context(product_context).get_product_price_rule(
- self.product_id, self.product_uom_qty or 1.0, self.order_id.partner_id)
- new_list_price, currency = self.with_context(product_context)._get_real_price_currency(product, rule_id,
- self.product_uom_qty,
- self.product_uom,
- self.order_id.pricelist_id.id)
- new_list_price = product.web_price
-
- if new_list_price != 0:
- if self.order_id.pricelist_id.currency_id != currency:
- # we need new_list_price in the same currency as price, which is in the SO's pricelist's currency
- new_list_price = currency._convert(
- new_list_price, self.order_id.pricelist_id.currency_id,
- self.order_id.company_id or self.env.company, self.order_id.date_order or fields.Date.today())
- discount = (new_list_price - price) / new_list_price * 100
- if (discount > 0 and new_list_price > 0) or (discount < 0 and new_list_price < 0):
- self.discount = discount
-
- def _get_display_price(self, product):
- # TO DO: move me in master/saas-16 on sale.order
- # awa: don't know if it's still the case since we need the "product_no_variant_attribute_value_ids" field now
- # to be able to compute the full price
-
- # it is possible that a no_variant attribute is still in a variant if
- # the type of the attribute has been changed after creation.
- no_variant_attributes_price_extra = [
- ptav.price_extra for ptav in self.product_no_variant_attribute_value_ids.filtered(
- lambda ptav:
- ptav.price_extra and
- ptav not in product.product_template_attribute_value_ids
- )
- ]
- if no_variant_attributes_price_extra:
- product = product.with_context(
- no_variant_attributes_price_extra=tuple(no_variant_attributes_price_extra)
- )
-
- if self.order_id.pricelist_id.discount_policy == 'with_discount':
- return product.with_context(pricelist=self.order_id.pricelist_id.id, uom=self.product_uom.id).price
- product_context = dict(self.env.context, partner_id=self.order_id.partner_id.id, date=self.order_id.date_order, uom=self.product_uom.id)
-
- final_price, rule_id = self.order_id.pricelist_id.with_context(product_context).get_product_price_rule(product or self.product_id, self.product_uom_qty or 1.0, self.order_id.partner_id)
- base_price, currency = self.with_context(product_context)._get_real_price_currency(product, rule_id, self.product_uom_qty, self.product_uom, self.order_id.pricelist_id.id)
- base_price = product.web_price
- if currency != self.order_id.pricelist_id.currency_id:
- base_price = currency._convert(
- base_price, self.order_id.pricelist_id.currency_id,
- self.order_id.company_id or self.env.company, self.order_id.date_order or fields.Date.today())
- # negative discounts (= surcharge) are included in the display price
-
- return max(base_price, final_price)
-
- def validate_confirm(self):
- for line in self:
- if line.product_id.id in [385544, 224484]:
- raise UserError('Produk Sementara Tidak Bisa Di Confirm atau Ask Approval')
- if not line.product_id or line.product_id.type == 'service':
- continue
- if not line.product_id.product_tmpl_id.sale_ok:
- raise UserError('Product %s belum bisa dijual, harap hubungi finance' % line.product_id.display_name)
- if not line.vendor_id or not line.purchase_price:
- raise UserError(_('Isi Vendor dan Harga Beli sebelum Request Approval'))
diff --git a/indoteknik_custom/models/sale_order_line.py b/indoteknik_custom/models/sale_order_line.py
new file mode 100644
index 00000000..4e1209cb
--- /dev/null
+++ b/indoteknik_custom/models/sale_order_line.py
@@ -0,0 +1,182 @@
+from odoo import fields, models, api, _
+from odoo.exceptions import UserError
+
+
+class SaleOrderLine(models.Model):
+ _inherit = 'sale.order.line'
+ item_margin = fields.Float('Margin', compute='compute_item_margin', help="Total Margin in Sales Order Header")
+ item_percent_margin = fields.Float('%Margin', compute='compute_item_margin', help="Total % Margin in Sales Order Header")
+ vendor_id = fields.Many2one(
+ 'res.partner', string='Vendor', readonly=True,
+ change_default=True, index=True, tracking=1,
+ states={'draft': [('readonly', False)], 'sent': [('readonly', False)]},
+ domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]"
+ )
+ purchase_price = fields.Float('Purchase', required=True, digits='Product Price', default=0.0)
+ purchase_tax_id = fields.Many2one('account.tax', string='Tax', domain=['|', ('active', '=', False), ('active', '=', True)])
+ delivery_amt_line = fields.Float('DeliveryAmtLine', compute='compute_delivery_amt_line')
+ fee_third_party_line = fields.Float('FeeThirdPartyLine', compute='compute_fee_third_party_line', default=0)
+ line_no = fields.Integer('No', default=0, copy=False)
+ note_procurement = fields.Char(string='Note', help="Harap diisi jika ada keterangan tambahan dari Procurement, agar dapat dimonitoring")
+ vendor_subtotal = fields.Float(string='Vendor Subtotal', compute="_compute_vendor_subtotal")
+ amount_voucher_disc = fields.Float(string='Voucher Discount')
+ program_line_id = fields.Many2one('promotion.program.line', 'Program Line')
+
+ def _compute_vendor_subtotal(self):
+ for line in self:
+ if line.purchase_price > 0 and line.product_uom_qty > 0:
+ line.vendor_subtotal = line.purchase_price * line.product_uom_qty
+ else:
+ line.vendor_subtotal = 0
+
+ def compute_item_margin(self):
+ for line in self:
+ if not line.product_id or line.product_id.type == 'service' \
+ or line.price_unit <= 0 or line.product_uom_qty <= 0 \
+ or not line.vendor_id:
+ line.item_margin = 0
+ line.item_percent_margin = 0
+ continue
+ # calculate margin without tax
+ sales_price = line.price_reduce_taxexcl * line.product_uom_qty
+ # minus with delivery if covered by indoteknik
+ if line.order_id.shipping_cost_covered == 'indoteknik':
+ sales_price -= line.delivery_amt_line
+ if line.order_id.fee_third_party > 0:
+ sales_price -= line.fee_third_party_line
+
+ purchase_price = line.purchase_price
+ if line.purchase_tax_id.price_include:
+ purchase_price = line.purchase_price / 1.11
+
+ purchase_price = purchase_price * line.product_uom_qty
+ margin_per_item = sales_price - purchase_price
+ line.item_margin = margin_per_item
+
+ if sales_price > 0:
+ line.item_percent_margin = round((margin_per_item / sales_price), 2) * 100
+ else:
+ line.item_percent_margin = 0
+
+ @api.onchange('vendor_id')
+ def onchange_vendor_id(self):
+ if not self.product_id or self.product_id.type == 'service':
+ return
+ elif self.product_id.categ_id.id == 34: # finish good / manufacturing only
+ cost = self.product_id.standard_price
+ self.purchase_price = cost
+ else:
+ purchase_price = self.env['purchase.pricelist'].search(
+ [('vendor_id', '=', self.vendor_id.id), ('product_id', '=', self.product_id.id)], limit=1)
+ self.purchase_price = purchase_price.product_price
+ self.purchase_tax_id = 22
+
+ @api.onchange('product_id')
+ def product_id_change(self):
+ super(SaleOrderLine, self).product_id_change()
+ for line in self:
+ if line.product_id and line.product_id.type == 'product':
+ purchase_price = self.env['purchase.pricelist'].search(
+ [('product_id', '=', self.product_id.id)], limit=1, order='product_price ASC')
+ line.vendor_id = purchase_price.vendor_id
+ line.tax_id = line.order_id.sales_tax_id
+ line.purchase_price = purchase_price.product_price
+
+ def compute_delivery_amt_line(self):
+ for line in self:
+ try:
+ contribution = round((line.price_total / line.order_id.amount_total), 2)
+ except:
+ contribution = 0
+ delivery_amt = line.order_id.delivery_amt
+ line.delivery_amt_line = delivery_amt * contribution
+
+ def compute_fee_third_party_line(self):
+ for line in self:
+ try:
+ contribution = round((line.price_total / line.order_id.amount_total), 2)
+ except:
+ contribution = 0
+ fee = line.order_id.fee_third_party
+ line.fee_third_party_line = fee * contribution
+
+ @api.onchange('product_id', 'price_unit', 'product_uom', 'product_uom_qty', 'tax_id')
+ def _onchange_discount(self):
+ if not (self.product_id and self.product_uom and
+ self.order_id.partner_id and self.order_id.pricelist_id and
+ self.order_id.pricelist_id.discount_policy == 'without_discount' and
+ self.env.user.has_group('product.group_discount_per_so_line')):
+ return
+
+ self.discount = 0.0
+ product = self.product_id.with_context(
+ lang=self.order_id.partner_id.lang,
+ partner=self.order_id.partner_id,
+ quantity=self.product_uom_qty,
+ date=self.order_id.date_order,
+ pricelist=self.order_id.pricelist_id.id,
+ uom=self.product_uom.id,
+ fiscal_position=self.env.context.get('fiscal_position')
+ )
+
+ product_context = dict(self.env.context, partner_id=self.order_id.partner_id.id, date=self.order_id.date_order, uom=self.product_uom.id)
+
+ price, rule_id = self.order_id.pricelist_id.with_context(product_context).get_product_price_rule(
+ self.product_id, self.product_uom_qty or 1.0, self.order_id.partner_id)
+ new_list_price, currency = self.with_context(product_context)._get_real_price_currency(product, rule_id, self.product_uom_qty, self.product_uom, self.order_id.pricelist_id.id)
+ new_list_price = product.web_price
+
+ if new_list_price != 0:
+ if self.order_id.pricelist_id.currency_id != currency:
+ # we need new_list_price in the same currency as price, which is in the SO's pricelist's currency
+ new_list_price = currency._convert(
+ new_list_price, self.order_id.pricelist_id.currency_id,
+ self.order_id.company_id or self.env.company, self.order_id.date_order or fields.Date.today())
+ discount = (new_list_price - price) / new_list_price * 100
+ if (discount > 0 and new_list_price > 0) or (discount < 0 and new_list_price < 0):
+ self.discount = discount
+
+ def _get_display_price(self, product):
+ # TO DO: move me in master/saas-16 on sale.order
+ # awa: don't know if it's still the case since we need the "product_no_variant_attribute_value_ids" field now
+ # to be able to compute the full price
+
+ # it is possible that a no_variant attribute is still in a variant if
+ # the type of the attribute has been changed after creation.
+ no_variant_attributes_price_extra = [
+ ptav.price_extra for ptav in self.product_no_variant_attribute_value_ids.filtered(
+ lambda ptav:
+ ptav.price_extra and
+ ptav not in product.product_template_attribute_value_ids
+ )
+ ]
+ if no_variant_attributes_price_extra:
+ product = product.with_context(
+ no_variant_attributes_price_extra=tuple(no_variant_attributes_price_extra)
+ )
+
+ if self.order_id.pricelist_id.discount_policy == 'with_discount':
+ return product.with_context(pricelist=self.order_id.pricelist_id.id, uom=self.product_uom.id).price
+ product_context = dict(self.env.context, partner_id=self.order_id.partner_id.id, date=self.order_id.date_order, uom=self.product_uom.id)
+
+ final_price, rule_id = self.order_id.pricelist_id.with_context(product_context).get_product_price_rule(product or self.product_id, self.product_uom_qty or 1.0, self.order_id.partner_id)
+ base_price, currency = self.with_context(product_context)._get_real_price_currency(product, rule_id, self.product_uom_qty, self.product_uom, self.order_id.pricelist_id.id)
+ base_price = product.web_price
+ if currency != self.order_id.pricelist_id.currency_id:
+ base_price = currency._convert(
+ base_price, self.order_id.pricelist_id.currency_id,
+ self.order_id.company_id or self.env.company, self.order_id.date_order or fields.Date.today())
+ # negative discounts (= surcharge) are included in the display price
+
+ return max(base_price, final_price)
+
+ def validate_line(self):
+ for line in self:
+ if line.product_id.id in [385544, 224484]:
+ raise UserError('Produk Sementara Tidak Bisa Di Confirm atau Ask Approval')
+ if not line.product_id or line.product_id.type == 'service':
+ continue
+ if not line.product_id.product_tmpl_id.sale_ok:
+ raise UserError('Product %s belum bisa dijual, harap hubungi finance' % line.product_id.display_name)
+ if not line.vendor_id or not line.purchase_price:
+ raise UserError(_('Isi Vendor dan Harga Beli sebelum Request Approval')) \ No newline at end of file