Debian Codegraph @

addons/point_of_sale/models/stock_picking.py

raw
1 # -*- coding: utf-8 -*-
2 # Part of Odoo. See LICENSE file for full copyright and licensing details.
3
4 from odoo import api, fields, models, _
5 from odoo.exceptions import UserError, ValidationError
6 from odoo.tools import float_is_zero
7
8 from itertools import groupby
9 from collections import defaultdict
10
11
12 class StockPicking(models.Model):
13 _inherit = 'stock.picking'
14
15 pos_session_id = fields.Many2one('pos.session', index=True)
16 pos_order_id = fields.Many2one('pos.order', index=True)
17
18 def _prepare_picking_vals(self, partner, picking_type, location_id, location_dest_id):
19 return {
20 'partner_id': partner.id if partner else False,
21 'user_id': False,
22 'picking_type_id': picking_type.id,
23 'move_type': 'direct',
24 'location_id': location_id,
25 'location_dest_id': location_dest_id,
26 'state': 'draft',
27 }
28
29
30 @api.model
31 def _create_picking_from_pos_order_lines(self, location_dest_id, lines, picking_type, partner=False):
32 """We'll create some picking based on order_lines"""
33
34 pickings = self.env['stock.picking']
35 stockable_lines = lines.filtered(lambda l: l.product_id.type == 'consu' and not l.product_id.uom_id.is_zero(l.qty))
36 if not stockable_lines:
37 return pickings
38 positive_lines = stockable_lines.filtered(lambda l: l.qty > 0)
39 negative_lines = stockable_lines - positive_lines
40
41 if positive_lines:
42 location_id = picking_type.default_location_src_id.id
43 positive_picking = self.env['stock.picking'].create(
44 self._prepare_picking_vals(partner, picking_type, location_id, location_dest_id)
45 )
46
47 positive_picking._create_move_from_pos_order_lines(positive_lines)
48 self.env.flush_all()
49 try:
50 with self.env.cr.savepoint():
51 positive_picking._action_done()
52 except (UserError, ValidationError):
53 pass
54
55 pickings |= positive_picking
56 if negative_lines:
57 if picking_type.return_picking_type_id:
58 return_picking_type = picking_type.return_picking_type_id
59 return_location_id = return_picking_type.default_location_dest_id.id
60 else:
61 return_picking_type = picking_type
62 return_location_id = picking_type.default_location_src_id.id
63
64 negative_picking = self.env['stock.picking'].create(
65 self._prepare_picking_vals(partner, return_picking_type, location_dest_id, return_location_id)
66 )
67 negative_picking._create_move_from_pos_order_lines(negative_lines)
68 self.env.flush_all()
69 try:
70 with self.env.cr.savepoint():
71 negative_picking._action_done()
72 except (UserError, ValidationError):
73 pass
74 pickings |= negative_picking
75 return pickings
76
77 def _prepare_stock_move_vals(self, first_line, order_lines):
78 return {
79 'product_uom': first_line.product_id.uom_id.id,
80 'picking_id': self.id,
81 'picking_type_id': self.picking_type_id.id,
82 'product_id': first_line.product_id.id,
83 'product_uom_qty': abs(sum(order_lines.mapped('qty'))),
84 'location_id': self.location_id.id,
85 'location_dest_id': self.location_dest_id.id,
86 'company_id': self.company_id.id,
87 'never_product_template_attribute_value_ids': first_line.attribute_value_ids.filtered(lambda a: a.attribute_id.create_variant == 'no_variant'),
88 }
89
90 def _create_move_from_pos_order_lines(self, lines):
91 self.ensure_one()
92
93 def get_grouping_key(line):
94 return (line.product_id.id, tuple(sorted(line.attribute_value_ids.ids)))
95
96 lines_by_product_and_attrs = groupby(sorted(lines, key=get_grouping_key), key=get_grouping_key)
97 move_vals = []
98 for _product, olines in lines_by_product_and_attrs:
99 order_lines = self.env['pos.order.line'].concat(*olines)
100 move_vals.append(self._prepare_stock_move_vals(order_lines[0], order_lines))
101 moves = self.env['stock.move'].create(move_vals)
102 confirmed_moves = moves._action_confirm()
103 confirmed_moves._add_mls_related_to_order(lines, are_qties_done=True)
104 confirmed_moves.picked = True
105 self._link_owner_on_return_picking(lines)
106
107 def _link_owner_on_return_picking(self, lines):
108 """This method tries to retrieve the owner of the returned product"""
109 if lines and lines[0].order_id.refunded_order_id.picking_ids:
110 returned_lines_picking = lines[0].order_id.refunded_order_id.picking_ids
111 returnable_qty_by_product = {}
112 for move_line in returned_lines_picking.move_line_ids:
113 returnable_qty_by_product[(move_line.product_id.id, move_line.owner_id.id or 0)] = move_line.quantity
114 for move in self.move_line_ids:
115 for keys in returnable_qty_by_product:
116 if move.product_id.id == keys[0] and keys[1] and returnable_qty_by_product[keys] > 0:
117 move.write({'owner_id': keys[1]})
118 returnable_qty_by_product[keys] -= move.quantity
119
120
121 def _send_confirmation_email(self):
122 # Avoid sending Mail/SMS for POS deliveries
123 pickings = self.filtered(lambda p: p.picking_type_id != p.picking_type_id.warehouse_id.pos_type_id)
124 return super(StockPicking, pickings)._send_confirmation_email()
125
126
127 class StockPickingType(models.Model):
128 _name = 'stock.picking.type'
129 _inherit = ['stock.picking.type', 'pos.load.mixin']
130
131 @api.depends('warehouse_id')
132 def _compute_hide_reservation_method(self):
133 super()._compute_hide_reservation_method()
134 for picking_type in self:
135 if picking_type == picking_type.warehouse_id.pos_type_id:
136 picking_type.hide_reservation_method = True
137
138 @api.constrains('active')
139 def _check_active(self):
140 for picking_type in self:
141 if picking_type.active:
142 continue
143 pos_config = self.env['pos.config'].sudo().search([('picking_type_id', '=', picking_type.id)], limit=1)
144 if pos_config:
145 raise ValidationError(_("You cannot archive '%(picking_type)s' as it is used by POS configuration '%(config)s'.", picking_type=picking_type.name, config=pos_config.name))
146
147 @api.model
148 def _load_pos_data_domain(self, data, config):
149 return [('id', '=', config.picking_type_id.id)]
150
151 @api.model
152 def _load_pos_data_fields(self, config):
153 return ['id', 'use_create_lots', 'use_existing_lots']
154
155
156 class StockMove(models.Model):
157 _inherit = 'stock.move'
158
159 def _get_new_picking_values(self):
160 vals = super()._get_new_picking_values()
161 orders = self.reference_ids.pos_order_ids
162 if orders:
163 order = orders.filtered(lambda o: o.is_refund and o.state == 'paid')[:1] or orders[:1]
164 vals['pos_session_id'] = order.session_id.id
165 vals['pos_order_id'] = order.id
166 return vals
167
168 def _key_assign_picking(self):
169 keys = super(StockMove, self)._key_assign_picking()
170 return keys + (self.reference_ids.pos_order_ids,)
171
172 @api.model
173 def _prepare_lines_data_dict(self, order_lines):
174 lines_data = defaultdict(dict)
175 for product_id, olines in groupby(sorted(order_lines, key=lambda l: l.product_id.id), key=lambda l: l.product_id.id):
176 lines_data[product_id].update({'order_lines': self.env['pos.order.line'].concat(*olines)})
177 return lines_data
178
179 def _create_production_lots_for_pos_order(self, lines):
180 ''' Search for existing lots and create missing ones.
181
182 :param lines: pos order lines with pack lot ids.
183 :type lines: pos.order.line recordset.
184
185 :return stock.lot recordset.
186 '''
187 valid_lots = self.env['stock.lot']
188 moves = self.filtered(lambda m: m.picking_type_id.use_existing_lots)
189 # Already called in self._action_confirm() but just to be safe when coming from _launch_stock_rule_from_pos_order_lines.
190 self._check_company()
191 if moves:
192 moves_product_ids = set(moves.mapped('product_id').ids)
193 lots = lines.pack_lot_ids.filtered(lambda l: l.lot_name and l.product_id.id in moves_product_ids)
194 lots_data = set(lots.mapped(lambda l: (l.product_id.id, l.lot_name)))
195 existing_lots = self.env['stock.lot'].search([
196 '|', ('company_id', '=', False), ('company_id', '=', moves[0].picking_type_id.company_id.id),
197 ('product_id', 'in', lines.product_id.ids),
198 ('name', 'in', lots.mapped('lot_name')),
199 ])
200 #The previous search may return (product_id.id, lot_name) combinations that have no matching in lines.pack_lot_ids.
201 for lot in existing_lots:
202 if (lot.product_id.id, lot.name) in lots_data:
203 valid_lots |= lot
204 lots_data.remove((lot.product_id.id, lot.name))
205 moves = moves.filtered(lambda m: m.picking_type_id.use_create_lots)
206 if moves:
207 moves_product_ids = set(moves.mapped('product_id').ids)
208 missing_lot_values = []
209 for lot_product_id, lot_name in filter(lambda l: l[0] in moves_product_ids, lots_data):
210 missing_lot_values.append({'company_id': self.company_id.id, 'product_id': lot_product_id, 'name': lot_name})
211 valid_lots |= self.env['stock.lot'].create(missing_lot_values)
212 return valid_lots
213
214 def _add_mls_related_to_order(self, related_order_lines, are_qties_done=True):
215 lines_data = self._prepare_lines_data_dict(related_order_lines)
216 # Moves with product_id not in related_order_lines. This can happend e.g. when product_id has a phantom-type bom.
217 moves_to_assign = self.filtered(lambda m: m.product_id.id not in lines_data or m.product_id.tracking == 'none'
218 or (not m.picking_type_id.use_existing_lots and not m.picking_type_id.use_create_lots))
219
220 # Check for any conversion issues in the moves before setting quantities
221 uoms_with_issues = set()
222 for move in moves_to_assign.filtered(lambda m: m.product_uom_qty and m.product_uom != m.product_id.uom_id):
223 converted_qty = move.product_uom._compute_quantity(
224 move.product_uom_qty,
225 move.product_id.uom_id,
226 rounding_method='HALF-UP'
227 )
228 if not converted_qty:
229 uoms_with_issues.add(
230 (move.product_uom.name, move.product_id.uom_id.name)
231 )
232
233 if uoms_with_issues:
234 error_message_lines = [
235 _("Conversion Error: The following unit of measure conversions result in a zero quantity due to rounding:")
236 ]
237 for uom_from, uom_to in uoms_with_issues:
238 error_message_lines.append(_(' - From "%(uom_from)s" to "%(uom_to)s"', uom_from=uom_from, uom_to=uom_to))
239
240 error_message_lines.append(
241 _("\nThis issue occurs because the quantity becomes zero after rounding during the conversion. "
242 "To fix this, adjust the conversion factors or rounding method to ensure that even the smallest quantity in the original unit "
243 "does not round down to zero in the target unit.")
244 )
245
246 raise UserError('\n'.join(error_message_lines))
247
248 for move in moves_to_assign:
249 move.quantity = move.product_uom_qty
250 moves_remaining = self - moves_to_assign
251 existing_lots = moves_remaining._create_production_lots_for_pos_order(related_order_lines)
252 move_lines_to_create = []
253 mls_qties = []
254 if are_qties_done:
255 for move in moves_remaining:
256 move.move_line_ids.unlink()
257 for line in lines_data[move.product_id.id]['order_lines']:
258 sum_of_lots = 0
259 for lot in line.pack_lot_ids.filtered(lambda l: l.lot_name):
260 qty = 1 if line.product_id.tracking == 'serial' else abs(line.qty)
261 ml_vals = dict(move._prepare_move_line_vals(qty))
262 if existing_lots:
263 existing_lot = existing_lots.filtered_domain([('product_id', '=', line.product_id.id), ('name', '=', lot.lot_name)])
264 quant = self.env['stock.quant']
265 if existing_lot:
266 quant = self.env['stock.quant'].search(
267 [('lot_id', '=', existing_lot.id), ('quantity', '>', '0.0'), ('location_id', 'child_of', move.location_id.id)],
268 order='id desc',
269 limit=1
270 )
271 if quant:
272 ml_vals.update({
273 'quant_id': quant.id,
274 })
275 else:
276 ml_vals.update({
277 'lot_name': existing_lot.name,
278 'lot_id': existing_lot.id,
279 })
280 else:
281 ml_vals.update({'lot_name': lot.lot_name})
282 move_lines_to_create.append(ml_vals)
283 mls_qties.append(qty)
284 sum_of_lots += qty
285 self.env['stock.move.line'].create(move_lines_to_create)
286 else:
287 for move in moves_remaining:
288 for line in lines_data[move.product_id.id]['order_lines']:
289 for lot in line.pack_lot_ids.filtered(lambda l: l.lot_name):
290 if line.product_id.tracking == 'serial':
291 qty = 1
292 else:
293 qty = abs(line.qty)
294 if existing_lots:
295 existing_lot = existing_lots.filtered_domain([('product_id', '=', line.product_id.id), ('name', '=', lot.lot_name)])
296 if existing_lot:
297 move._update_reserved_quantity(qty, move.location_id, lot_id=existing_lot)
298 continue