summaryrefslogtreecommitdiff
path: root/indoteknik_custom/models/automatic_purchase.py
blob: 438d365f2648fac813ca777bb463b83e31aa3db9 (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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
from odoo import models, api, fields
from odoo.exceptions import UserError
from datetime import datetime
import logging

_logger = logging.getLogger(__name__)


class AutomaticPurchase(models.Model):
    _name = 'automatic.purchase'
    _order = 'id desc'
    _inherit = ['mail.thread']
    _rec_name = 'number'

    number = fields.Char(string='Document No', index=True, copy=False, readonly=True)
    date_doc = fields.Date(string='Date', required=True, help='Isi tanggal hari ini')
    description = fields.Char(string='Description', help='bebas isi nya apa')
    purchase_lines = fields.One2many('automatic.purchase.line', 'automatic_purchase_id', string='Lines', auto_join=True)
    notification = fields.Char(string='Notification')
    is_po = fields.Boolean(string='Is PO')
    purchase_match = fields.One2many('automatic.purchase.match', 'automatic_purchase_id', string='PO Matches', auto_join=True)
    vendor_id = fields.Many2one('res.partner', string='Vendor', help='boleh kosong, jika diisi, maka hanya keluar data untuk vendor tersebut')
    responsible_id = fields.Many2one('res.users', string='Responsible', required=True)
    apo_type = fields.Selection([
        ('regular', 'Regular Fulfill SO'),
        ('reordering', 'Reordering Rule'),
    ], string='Type', tracking=3)
    sales_match = fields.One2many('automatic.purchase.sales.match', 'automatic_purchase_id', string='SO Matches', auto_join=True)

    @api.model
    def create(self, vals):
        vals['number'] = self.env['ir.sequence'].next_by_code('automatic.purchase') or '0'
        result = super(AutomaticPurchase, self).create(vals)
        return result

    def create_po_from_automatic_purchase(self):
        if not self.purchase_lines:
            raise UserError('Tidak ada Lines, belum bisa create PO')
        if self.is_po:
            raise UserError('Sudah pernah di create PO')
        current_time = datetime.now()
        vendor_ids = self.env['automatic.purchase.line'].read_group([('automatic_purchase_id', '=', self.id), ('partner_id', '!=', False)], fields=['partner_id'], groupby=['partner_id'])
        
        counter_po_number = 0
        for vendor in vendor_ids:
            param_header = {
                'partner_id': vendor['partner_id'][0],
                # 'partner_ref': 'Automatic PO',
                'currency_id': 12,
                'user_id': self.env.user.id,
                'company_id': 1, # indoteknik dotcom gemilang
                'picking_type_id': 28, # indoteknik bandengan receipts
                'date_order': current_time,
                'note_description': 'Automatic PO'
            }
            # new_po = self.env['purchase.order'].create([param_header])
            products_vendors = self.env['automatic.purchase.line'].search([
                ('automatic_purchase_id', '=', self.id), 
                ('partner_id', '=', vendor['partner_id'][0]),
                ('qty_purchase', '>', 0)
            ], order='brand_id')
            count = brand_id = 0
            for product in products_vendors:
                if count == 200 or brand_id != product.brand_id.id:
                    count = 0
                    counter_po_number += 1
                    new_po = self.env['purchase.order'].create([param_header])
                    new_po.name = new_po.name + "/A/"+str(counter_po_number)
                    self.env['automatic.purchase.match'].create([{
                        'automatic_purchase_id': self.id,
                        'order_id': new_po.id
                    }])
                    self.env.cr.commit()
                # else:
                #     new_po = self.env['purchase.order'].create([param_header])
                brand_id = product.brand_id.id
                count += 10
                
                qty_available = product.product_id.qty_onhand_bandengan + product.product_id.qty_incoming_bandengan - product.product_id.outgoing_qty
                suggest = 'harus beli'
                if qty_available > product.qty_purchase:
                    suggest = 'masih cukup'
                param_line = {
                    'order_id': new_po.id,
                    'sequence': count,
                    'product_id': product.product_id.id,
                    'product_qty': product.qty_purchase,
                    'qty_available_store': qty_available,
                    'suggest': suggest,
                    'product_uom_qty': product.qty_purchase,
                    'price_unit': product.last_price,
                }
                new_line = self.env['purchase.order.line'].create([param_line])
                product.current_po_id = new_po.id
                product.current_po_line_id = new_line.id
                _logger.info('Automatic Create PO Line %s' % product.product_id.name)
            self.notification = self.notification + ' %s' % new_po.name
        self.is_po = True

    def generate_regular_purchase(self):
        if self.apo_type == 'reordering':
            raise UserError('Tombol ini hanya untuk Regular Fulfill SO')
        if self.vendor_id:
            raise UserError('Vendor tidak dapat diisi jika Regular Fulfill SO')
        if self.purchase_lines:
            raise UserError('Sudah digenerate sebelumnya, hapus line terlebih dahulu')
        #TODO must add order by for fifo mechanism
        #change the view of v.purchasing.job and use order by in query
        query = [
            ('action', '=', 'kurang beli')
        ]
        jobs = self.env['v.purchasing.job'].search(query)
        count = 0
        for job in jobs:
            qty_purchase = job.outgoing - job.onhand + job.incoming
            qty_available = job.onhand + job.incoming - job.outgoing

            domain = [
                ('product_id.id', '=', job.product_id.id),
            ]
            orderby = 'count_trx_po desc, count_trx_po_vendor desc'
            purchase_pricelist = self.env['purchase.pricelist'].search(domain, order=orderby, limit=1)

            vendor_id = purchase_pricelist.vendor_id
            price = self._get_valid_purchase_price(purchase_pricelist)
            last_po_line = self.env['purchase.order.line'].search([('product_id', '=', job.product_id.id), ('order_id.state', '=', 'done')], order='id desc', limit=1)

            self.env['automatic.purchase.line'].create([{
                'automatic_purchase_id': self.id,
                'product_id': job.product_id.id,
                'qty_purchase': qty_purchase,
                'qty_available': qty_available,
                'partner_id': vendor_id.id,
                'last_price': price,
                'subtotal': qty_purchase * price,
                'last_order_id': last_po_line.order_id.id,
                'last_orderline_id': last_po_line.id,
                'brand_id': job.product_id.product_tmpl_id.x_manufacture.id
            }])
            count += 1
            _logger.info('Create Automatic Purchase Line %s' % job.product_id.name)
        self.notification = "Automatic PO Created %s Lines" % count
        print(1)

    def generate_automatic_purchase(self):
        # for reordering rule only
        if self.apo_type == 'regular':
            raise UserError('Tombol ini hanya untuk Reordering Rule')
        if self.purchase_lines:
            raise UserError('Sudah digenerate sebelumnya, hapus line terlebih dahulu')
        
        query = [
            ('product_min_qty', '>', 0),
            ('product_id.x_manufacture.user_id.id', '=', self.responsible_id.id)
        ]
        orderpoints = self.env['stock.warehouse.orderpoint'].search(query)
        count = 0
        for point in orderpoints:
            # _logger.info('test %s' % point.product_id.name)
            if point.product_id.virtual_available > point.product_min_qty:
                continue
            qty_purchase = point.product_max_qty - point.product_id.virtual_available
            po_line = self.env['purchase.order.line'].search([('product_id', '=', point.product_id.id), ('order_id.state', '=', 'done')], order='id desc', limit=1)
            
            if self.vendor_id:
                purchase_price = self.env['purchase.pricelist'].search([
                    ('product_id', '=', point.product_id.id),
                    # ('product_id.x_manufacture.user_id.id', '=', self.responsible_id.id),
                    ('vendor_id', '=', self.vendor_id.id)
                ], order='count_trx_po desc, count_trx_po_vendor desc', limit=1)
            else:
                purchase_price = self.env['purchase.pricelist'].search([
                    ('product_id', '=', point.product_id.id),
                    # ('product_id.x_manufacture.user_id.id', '=', self.responsible_id.id),
                ], order='count_trx_po desc, count_trx_po_vendor desc', limit=1)

            vendor_id = purchase_price.vendor_id.id
            price = self._get_valid_purchase_price(purchase_price)

            if self.vendor_id and self.vendor_id.id != vendor_id:
                continue

            self.env['automatic.purchase.line'].create([{
                'automatic_purchase_id': self.id,
                'product_id': point.product_id.id,
                'qty_purchase': qty_purchase,
                'qty_min': point.product_min_qty,
                'qty_max': point.product_max_qty,
                'qty_available': point.product_id.virtual_available,
                # 'partner_id': po_line.order_id.partner_id.id,
                # 'last_price': po_line.price_unit,
                'partner_id': vendor_id,
                'last_price': price,
                'subtotal': qty_purchase * price,
                'last_order_id': po_line.order_id.id,
                'last_orderline_id': po_line.id,
                'brand_id': point.product_id.product_tmpl_id.x_manufacture.id
            }])
            count += 1
            _logger.info('Create Automatic Purchase Line %s' % point.product_id.name)
        self.notification = "Automatic PO Created %s Lines" % count

    def _get_valid_purchase_price(self, purchase_price):
        p_price = 0
        if purchase_price.system_price > 0 and purchase_price.product_price > 0:
            if purchase_price.human_last_update > purchase_price.system_last_update:
                p_price = purchase_price.product_price
            else:
                p_price = purchase_price.system_price
        elif purchase_price.system_price > 0 and purchase_price.product_price == 0:
            p_price = purchase_price.system_price
        elif purchase_price.system_price == 0 and purchase_price.product_price > 0:
            p_price = purchase_price.product_price
        return p_price


class AutomaticPurchaseLine(models.Model):
    _name = 'automatic.purchase.line'
    _description = 'Automatic Purchase Line'
    _order = 'automatic_purchase_id, id'

    automatic_purchase_id = fields.Many2one('automatic.purchase', string='Ref', required=True, ondelete='cascade', index=True, copy=False)
    product_id = fields.Many2one('product.product', string='Product')
    qty_purchase = fields.Float(string='Qty Purchase')
    qty_min = fields.Float(string='Qty Min')
    qty_max = fields.Float(string='Qty Max')
    qty_available = fields.Float(string='Qty Available')
    partner_id = fields.Many2one('res.partner', string='Vendor')
    last_price = fields.Float(string='Last Price')
    subtotal = fields.Float(string='Subtotal')
    last_order_id = fields.Many2one('purchase.order', string='Last Order')
    last_orderline_id = fields.Many2one('purchase.order.line', string='Last Order Line')
    is_po = fields.Boolean(String='Is PO')
    current_po_id = fields.Many2one('purchase.order', string='Current')
    current_po_line_id = fields.Many2one('purchase.order.line', string='Current Line')
    brand_id = fields.Many2one('x_manufactures', string='Brand')

    @api.onchange('last_price', 'qty_purchase')
    def _calculate_subtotal(self):
        for line in self:
            line.subtotal = line.qty_purchase * line.last_price


class AutomaticPurchaseMatch(models.Model):
    _name = 'automatic.purchase.match'
    _order = 'automatic_purchase_id, id'

    automatic_purchase_id = fields.Many2one('automatic.purchase', string='Ref', required=True, ondelete='cascade', index=True, copy=False)
    order_id = fields.Many2one('purchase.order', string='Purchase Order')
    vendor = fields.Char(string='Vendor', compute='_compute_info_po')
    total = fields.Float(string='Total', compute='_compute_info_po')

    def _compute_info_po(self):
        for match in self:
            match.vendor = match.order_id.partner_id.name
            match.total = match.order_id.amount_total


class AutomaticPurchaseSalesMatch(models.Model):
    _name = 'automatic.purchase.sales.match'
    _order = 'automatic_purchase_id, id'

    automatic_purchase_id = fields.Many2one('automatic.purchase', string='Ref', required=True, ondelete='cascade', index=True, copy=False)
    sale_id = fields.Many2one('sale.order', string='SO')
    partner_id = fields.Many2one('res.partner', string='Customer')
    salesperson_id = fields.Many2one('res.user', string='Sales')
    product_id = fields.Many2one('product.product', string='Product')
    qty_so = fields.Float(string='Qty')