Debian Codegraph @

addons/website_sale_collect/models/delivery_carrier.py

raw symbols SCIP
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2
3 from odoo import _, api, fields, models
4 from odoo.exceptions import ValidationError
5 from odoo.fields import Command
6 from odoo.http import request
7
8 from odoo.addons.website_sale_collect import utils
9
10
11 class DeliveryCarrier(models.Model):
12 _inherit = 'delivery.carrier'
13
14 delivery_type = fields.Selection(
15 selection_add=[('in_store', "Pick up in store")], ondelete={'in_store': 'set default'}
16 )
17 warehouse_ids = fields.Many2many(string="Stores", comodel_name='stock.warehouse')
18
19 @api.constrains('delivery_type', 'is_published', 'warehouse_ids')
20 def _check_in_store_dm_has_warehouses_when_published(self):
21 if any(self.filtered(
22 lambda dm: dm.delivery_type == 'in_store'
23 and dm.is_published
24 and not dm.warehouse_ids
25 )):
26 raise ValidationError(
27 _("The delivery method must have at least one warehouse to be published.")
28 )
29
30 @api.constrains('delivery_type', 'company_id', 'warehouse_ids')
31 def _check_warehouses_have_same_company(self):
32 for dm in self:
33 if dm.delivery_type == 'in_store' and dm.company_id and any(
34 wh.company_id and dm.company_id != wh.company_id for wh in dm.warehouse_ids
35 ):
36 raise ValidationError(
37 _("The delivery method and a warehouse must share the same company")
38 )
39
40 @api.model_create_multi
41 def create(self, vals_list):
42 for vals in vals_list:
43 if vals.get('delivery_type') == 'in_store':
44 vals['integration_level'] = 'rate'
45 vals['allow_cash_on_delivery'] = False
46
47 # Set the default warehouses and publish if one is found.
48 if 'company_id' in vals:
49 company_id = vals.get('company_id')
50 else:
51 company_id = (
52 self.env['product.product'].browse(vals.get('product_id')).company_id.id
53 or self.env.company.id
54 )
55 warehouses = self.env['stock.warehouse'].search(
56 [('company_id', 'in', company_id)]
57 )
58 vals.update({
59 'warehouse_ids': [Command.set(warehouses.ids)],
60 'is_published': bool(warehouses),
61 })
62 return super().create(vals_list)
63
64 def write(self, vals):
65 if vals.get('delivery_type') == 'in_store':
66 vals['integration_level'] = 'rate'
67 vals['allow_cash_on_delivery'] = False
68 return super().write(vals)
69
70 # === BUSINESS METHODS ===#
71
72 def _in_store_get_close_locations(self, partner_address, product_id=None):
73 """ Get the formatted close pickup locations sorted by distance to the partner address.
74
75 :param res.partner partner_address: The address to use to sort the pickup locations.
76 :param str product_id: The product whose product page was used to open the location
77 selector, if any, as a `product.product` id.
78 :return: The sorted and formatted close pickup locations.
79 :rtype: list[dict]
80 """
81 try:
82 product_id = product_id and int(product_id)
83 except ValueError:
84 product = self.env['product.product']
85 else:
86 product = self.env['product.product'].browse(product_id)
87
88 partner_address.geo_localize() # Calculate coordinates.
89
90 pickup_locations = []
91 order_sudo = request.cart
92 for wh in self.warehouse_ids:
93 pickup_location_values = wh._prepare_pickup_location_data()
94 if not pickup_location_values: # Ignore warehouses with badly configured addresses.
95 continue
96
97 # Prepare the stock data based on either the product or the order.
98 if product: # Called from the product page.
99 in_store_stock_data = utils.format_product_stock_values(product, wh.id)
100 else: # Called from the checkout page.
101 in_store_stock_data = {'in_stock': order_sudo._is_in_stock(wh.id)}
102
103 # Calculate the distance between the partner address and the warehouse location.
104 pickup_location_values.update({
105 'additional_data': {'in_store_stock_data': in_store_stock_data},
106 'distance': utils.calculate_partner_distance(partner_address, wh.partner_id),
107 })
108 pickup_locations.append(pickup_location_values)
109
110 return sorted(pickup_locations, key=lambda k: k['distance'])
111
112 def in_store_rate_shipment(self, *_args):
113 return {
114 'success': True,
115 'price': self.product_id.list_price,
116 'error_message': False,
117 'warning_message': False,
118 }