1# -*- coding: utf-8 -*-
2# Part of Odoo. See LICENSE file for full copyright and licensing details.
3
4from odoo import _, api, fields, models
5from odoo.exceptions import UserError
6from odoo.tools import float_compare
7
8
9class StockScrap(models.Model):
10    _name = 'stock.scrap'
11    _inherit = ['mail.thread']
12    _order = 'id desc'
13    _description = 'Scrap'
14
15    def _get_default_scrap_location_id(self):
16        company_id = self.env.context.get('default_company_id') or self.env.company.id
17        return self.env['stock.location'].search([('scrap_location', '=', True), ('company_id', 'in', [company_id, False])], limit=1).id
18
19    def _get_default_location_id(self):
20        company_id = self.env.context.get('default_company_id') or self.env.company.id
21        warehouse = self.env['stock.warehouse'].search([('company_id', '=', company_id)], limit=1)
22        if warehouse:
23            return warehouse.lot_stock_id.id
24        return None
25
26    name = fields.Char(
27        'Reference',  default=lambda self: _('New'),
28        copy=False, readonly=True, required=True,
29        states={'done': [('readonly', True)]})
30    company_id = fields.Many2one('res.company', string='Company', default=lambda self: self.env.company, required=True, states={'done': [('readonly', True)]})
31    origin = fields.Char(string='Source Document')
32    product_id = fields.Many2one(
33        'product.product', 'Product', domain="[('type', 'in', ['product', 'consu']), '|', ('company_id', '=', False), ('company_id', '=', company_id)]",
34        required=True, states={'done': [('readonly', True)]}, check_company=True)
35    product_uom_id = fields.Many2one(
36        'uom.uom', 'Unit of Measure',
37        required=True, states={'done': [('readonly', True)]}, domain="[('category_id', '=', product_uom_category_id)]")
38    product_uom_category_id = fields.Many2one(related='product_id.uom_id.category_id')
39    tracking = fields.Selection(string='Product Tracking', readonly=True, related="product_id.tracking")
40    lot_id = fields.Many2one(
41        'stock.production.lot', 'Lot/Serial',
42        states={'done': [('readonly', True)]}, domain="[('product_id', '=', product_id), ('company_id', '=', company_id)]", check_company=True)
43    package_id = fields.Many2one(
44        'stock.quant.package', 'Package',
45        states={'done': [('readonly', True)]}, check_company=True)
46    owner_id = fields.Many2one('res.partner', 'Owner', states={'done': [('readonly', True)]}, check_company=True)
47    move_id = fields.Many2one('stock.move', 'Scrap Move', readonly=True, check_company=True, copy=False)
48    picking_id = fields.Many2one('stock.picking', 'Picking', states={'done': [('readonly', True)]}, check_company=True)
49    location_id = fields.Many2one(
50        'stock.location', 'Source Location', domain="[('usage', '=', 'internal'), ('company_id', 'in', [company_id, False])]",
51        required=True, states={'done': [('readonly', True)]}, default=_get_default_location_id, check_company=True)
52    scrap_location_id = fields.Many2one(
53        'stock.location', 'Scrap Location', default=_get_default_scrap_location_id,
54        domain="[('scrap_location', '=', True), ('company_id', 'in', [company_id, False])]", required=True, states={'done': [('readonly', True)]}, check_company=True)
55    scrap_qty = fields.Float('Quantity', default=1.0, required=True, states={'done': [('readonly', True)]})
56    state = fields.Selection([
57        ('draft', 'Draft'),
58        ('done', 'Done')],
59        string='Status', default="draft", readonly=True, tracking=True)
60    date_done = fields.Datetime('Date', readonly=True)
61
62    @api.onchange('picking_id')
63    def _onchange_picking_id(self):
64        if self.picking_id:
65            self.location_id = (self.picking_id.state == 'done') and self.picking_id.location_dest_id.id or self.picking_id.location_id.id
66
67    @api.onchange('product_id')
68    def _onchange_product_id(self):
69        if self.product_id:
70            if self.tracking == 'serial':
71                self.scrap_qty = 1
72            self.product_uom_id = self.product_id.uom_id.id
73            # Check if we can get a more precise location instead of
74            # the default location (a location corresponding to where the
75            # reserved product is stored)
76            if self.picking_id:
77                for move_line in self.picking_id.move_line_ids:
78                    if move_line.product_id == self.product_id:
79                        self.location_id = move_line.location_id if move_line.state != 'done' else move_line.location_dest_id
80                        break
81
82    @api.onchange('company_id')
83    def _onchange_company_id(self):
84        if self.company_id:
85            warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.company_id.id)], limit=1)
86            # Change the locations only if their company doesn't match the company set, otherwise
87            # user defaults are overridden.
88            if self.location_id.company_id != self.company_id:
89                self.location_id = warehouse.lot_stock_id
90            if self.scrap_location_id.company_id != self.company_id:
91                self.scrap_location_id = self.env['stock.location'].search([
92                    ('scrap_location', '=', True),
93                    ('company_id', 'in', [self.company_id.id, False]),
94                ], limit=1)
95        else:
96            self.location_id = False
97            self.scrap_location_id = False
98
99    def unlink(self):
100        if 'done' in self.mapped('state'):
101            raise UserError(_('You cannot delete a scrap which is done.'))
102        return super(StockScrap, self).unlink()
103
104    def _prepare_move_values(self):
105        self.ensure_one()
106        return {
107            'name': self.name,
108            'origin': self.origin or self.picking_id.name or self.name,
109            'company_id': self.company_id.id,
110            'product_id': self.product_id.id,
111            'product_uom': self.product_uom_id.id,
112            'state': 'draft',
113            'product_uom_qty': self.scrap_qty,
114            'location_id': self.location_id.id,
115            'scrapped': True,
116            'location_dest_id': self.scrap_location_id.id,
117            'move_line_ids': [(0, 0, {'product_id': self.product_id.id,
118                                           'product_uom_id': self.product_uom_id.id,
119                                           'qty_done': self.scrap_qty,
120                                           'location_id': self.location_id.id,
121                                           'location_dest_id': self.scrap_location_id.id,
122                                           'package_id': self.package_id.id,
123                                           'owner_id': self.owner_id.id,
124                                           'lot_id': self.lot_id.id, })],
125#             'restrict_partner_id': self.owner_id.id,
126            'picking_id': self.picking_id.id
127        }
128
129    def do_scrap(self):
130        self._check_company()
131        for scrap in self:
132            scrap.name = self.env['ir.sequence'].next_by_code('stock.scrap') or _('New')
133            move = self.env['stock.move'].create(scrap._prepare_move_values())
134            # master: replace context by cancel_backorder
135            move.with_context(is_scrap=True)._action_done()
136            scrap.write({'move_id': move.id, 'state': 'done'})
137            scrap.date_done = fields.Datetime.now()
138        return True
139
140    def action_get_stock_picking(self):
141        action = self.env['ir.actions.act_window']._for_xml_id('stock.action_picking_tree_all')
142        action['domain'] = [('id', '=', self.picking_id.id)]
143        return action
144
145    def action_get_stock_move_lines(self):
146        action = self.env['ir.actions.act_window']._for_xml_id('stock.stock_move_line_action')
147        action['domain'] = [('move_id', '=', self.move_id.id)]
148        return action
149
150    def action_validate(self):
151        self.ensure_one()
152        if self.product_id.type != 'product':
153            return self.do_scrap()
154        precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')
155        available_qty = sum(self.env['stock.quant']._gather(self.product_id,
156                                                            self.location_id,
157                                                            self.lot_id,
158                                                            self.package_id,
159                                                            self.owner_id,
160                                                            strict=True).mapped('quantity'))
161        scrap_qty = self.product_uom_id._compute_quantity(self.scrap_qty, self.product_id.uom_id)
162        if float_compare(available_qty, scrap_qty, precision_digits=precision) >= 0:
163            return self.do_scrap()
164        else:
165            ctx = dict(self.env.context)
166            ctx.update({
167                'default_product_id': self.product_id.id,
168                'default_location_id': self.location_id.id,
169                'default_scrap_id': self.id,
170                'default_quantity': scrap_qty,
171                'default_product_uom_name': self.product_id.uom_name
172            })
173            return {
174                'name': self.product_id.display_name + _(': Insufficient Quantity To Scrap'),
175                'view_mode': 'form',
176                'res_model': 'stock.warn.insufficient.qty.scrap',
177                'view_id': self.env.ref('stock.stock_warn_insufficient_qty_scrap_form_view').id,
178                'type': 'ir.actions.act_window',
179                'context': ctx,
180                'target': 'new'
181            }
182