summaryrefslogtreecommitdiff
path: root/indoteknik_custom/models/sale_order_line.py
blob: 39366028bd52771ef3f06b326e58115a292bdb8d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
from odoo import fields, models, api, _
from odoo.exceptions import UserError
from datetime import datetime


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")
    initial_discount = fields.Float('Initial Discount')
    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 = fields.Selection([
        ('eta', 'ETA'),
        ('info_sales', 'Info Sales'),
        ('info_vendor', 'Info Vendor'),
        ('penggabungan', 'Penggabungan'),
    ], string='Note', help="Harap diisi jika ada keterangan tambahan dari Procurement, agar dapat dimonitoring")
    note_procurement = fields.Char(string='Note Detail', 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')
    qty_reserved = fields.Float(string='Qty Reserved', compute='_compute_qty_reserved')
    reserved_from = fields.Char(string='Reserved From', copy=False)

    # def get_reserved_from(self):
    #     for line in self:
    #         current_stock = self.env['stock.quant'].search([
    #             ('product_id', '=', line.product_id.id),
    #             ('location_id', '=', line.order_id.warehouse_id.lot_stock_id.id)
    #         ])

    #         po_stock = self.env['purchase.order.line'].search([
    #             ('product_id', '=', line.product_id.id),
    #             ('order_id.sale_order_id', '=', line.order_id.id),
    #             ('state', '=', 'done')
    #         ])

    #         available_quantity = current_stock.available_quantity if current_stock else 0
    #         product_qty = po_stock.product_qty if po_stock else 0

    #         if available_quantity >= line.product_uom_qty:
    #             line.reserved_from = 'From Stock'
    #         elif product_qty >= line.product_uom_qty:
    #             line.reserved_from = 'From PO'
    #         elif (available_quantity + product_qty) >= line.product_uom_qty:
    #             line.reserved_from = 'From Stock and PO'
    #         else:
    #             line.reserved_from = None

    def _compute_qty_reserved(self):
        for line in self:
            stock_moves = self.env['stock.move.line'].search([
                ('product_id', '=', line.product_id.id),
                ('picking_id.sale_id', '=', line.order_id.id),
                ('picking_id.state', 'not in', ['cancel', 'done']),
            ])

            reserved_qty = sum(move.product_uom_qty for move in stock_moves)
            line.qty_reserved = reserved_qty

    def _compute_reserved_from(self):
            for line in self:
                report_stock_forecasted = self.env['report.stock.report_product_product_replenishment']
                report_stock_forecasted._get_report_data(False, [line.product_id.id])

    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)
            purchase_price = self.env['purchase.pricelist'].search(
                [('vendor_id', '=', self.vendor_id.id), ('product_id', '=', self.product_id.id)], 
                limit=1, order='count_trx_po desc, count_trx_po_vendor desc')
            self.purchase_price = self._get_valid_purchase_price(purchase_price)
        self.purchase_tax_id = 22

    def _get_valid_purchase_price(self, purchase_price):
        price = 0
        human_last_update = purchase_price.human_last_update or datetime.min
        system_last_update = purchase_price.system_last_update or datetime.min

        if system_last_update > human_last_update:
            price = purchase_price.system_price
        else:
            price = purchase_price.product_price
        
        return price or 0

    @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='count_trx_po desc, count_trx_po_vendor desc')
                line.vendor_id = purchase_price.vendor_id
                line.tax_id = line.order_id.sales_tax_id
                line.purchase_price = self._get_valid_purchase_price(purchase_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'))