Debian Codegraph @

addons/sale_purchase/models/sale_order_line.py

raw symbols SCIP
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2
3 from dateutil.relativedelta import relativedelta
4
5 from odoo import api, fields, models, _
6 from odoo.fields import Domain
7 from odoo.exceptions import UserError
8 from odoo.tools import float_compare
9 from odoo.tools.misc import get_lang
10
11
12 class SaleOrderLine(models.Model):
13 _inherit = 'sale.order.line'
14
15 purchase_line_ids = fields.One2many('purchase.order.line', 'sale_line_id', string="Generated Purchase Lines", readonly=True, help="Purchase line generated by this Sales item on order confirmation, or when the quantity was increased.")
16 purchase_line_count = fields.Integer("Number of generated purchase items", compute='_compute_purchase_count')
17
18 @api.depends('purchase_line_ids')
19 def _compute_purchase_count(self):
20 database_data = self.env['purchase.order.line'].sudo()._read_group([('sale_line_id', 'in', self.ids)], ['sale_line_id'], ['__count'])
21 mapped_data = {sale_line.id: count for sale_line, count in database_data}
22 for line in self:
23 line.purchase_line_count = mapped_data.get(line.id, 0)
24
25 @api.onchange('product_uom_qty')
26 def _onchange_service_product_uom_qty(self):
27 if self.state == 'sale' and self.product_id.type == 'service' and self.product_id.with_company(self._purchase_service_get_company()).service_to_purchase:
28 if self.product_uom_qty < self._origin.product_uom_qty:
29 if self.product_uom_qty < self.qty_delivered:
30 return {}
31 warning_mess = {
32 'title': _('Ordered quantity decreased!'),
33 'message': _('You are decreasing the ordered quantity! Do not forget to manually update the purchase order if needed.'),
34 }
35 return {'warning': warning_mess}
36 return {}
37
38 # --------------------------
39 # CRUD
40 # --------------------------
41
42 @api.model_create_multi
43 def create(self, vals_list):
44 lines = super().create(vals_list)
45 # Do not generate purchase when expense SO line since the product is already delivered
46 lines.filtered(
47 lambda line: line.state == 'sale' and not line.is_expense
48 )._purchase_service_generation()
49 return lines
50
51 def write(self, vals):
52 increased_lines = None
53 decreased_lines = None
54 increased_values = {}
55 decreased_values = {}
56 if 'product_uom_qty' in vals:
57 precision = self.env['decimal.precision'].precision_get('Product Unit')
58 increased_lines = self.sudo().filtered(lambda r: r.product_id.with_company(r._purchase_service_get_company()).service_to_purchase and r.purchase_line_count and float_compare(r.product_uom_qty, vals['product_uom_qty'], precision_digits=precision) == -1)
59 decreased_lines = self.sudo().filtered(lambda r: r.product_id.with_company(r._purchase_service_get_company()).service_to_purchase and r.purchase_line_count and float_compare(r.product_uom_qty, vals['product_uom_qty'], precision_digits=precision) == 1)
60 increased_values = {line.id: line.product_uom_qty for line in increased_lines}
61 decreased_values = {line.id: line.product_uom_qty for line in decreased_lines}
62
63 result = super().write(vals)
64
65 if increased_lines:
66 increased_lines._purchase_increase_ordered_qty(vals['product_uom_qty'], increased_values)
67 if decreased_lines:
68 decreased_lines._purchase_decrease_ordered_qty(vals['product_uom_qty'], decreased_values)
69 return result
70
71 # --------------------------
72 # Business Methods
73 # --------------------------
74
75 def _purchase_decrease_ordered_qty(self, new_qty, origin_values):
76 """ Decrease the quantity from SO line will add a next acitivities on the related purchase order
77 :param new_qty: new quantity (lower than the current one on SO line), expressed
78 in UoM of SO line.
79 :param origin_values: map from sale line id to old value for the ordered quantity (dict)
80 """
81 purchase_to_notify_map = {} # map PO -> set(SOL)
82 last_purchase_lines = self.env['purchase.order.line'].search([('sale_line_id', 'in', self.ids)])
83 for purchase_line in last_purchase_lines:
84 purchase_to_notify_map.setdefault(purchase_line.order_id, self.env['sale.order.line'])
85 purchase_to_notify_map[purchase_line.order_id] |= purchase_line.sale_line_id
86
87 # create next activity
88 for purchase_order, sale_lines in purchase_to_notify_map.items():
89 render_context = {
90 'sale_lines': sale_lines,
91 'sale_orders': sale_lines.mapped('order_id'),
92 'origin_values': origin_values,
93 }
94 purchase_order._activity_schedule_with_view('mail.mail_activity_data_warning',
95 user_id=purchase_order.user_id.id or self.env.uid,
96 views_or_xmlid='sale_purchase.exception_purchase_on_sale_quantity_decreased',
97 render_context=render_context)
98
99 def _purchase_increase_ordered_qty(self, new_qty, origin_values):
100 """ Increase the quantity on the related purchase lines
101 :param new_qty: new quantity (higher than the current one on SO line), expressed
102 in UoM of SO line.
103 :param origin_values: map from sale line id to old value for the ordered quantity (dict)
104 """
105 for line in self:
106 last_purchase_line = self.env['purchase.order.line'].search([('sale_line_id', '=', line.id)], order='create_date DESC', limit=1)
107 if last_purchase_line.state in ['draft', 'sent', 'to approve']: # update qty for draft PO lines
108 quantity = line.product_uom_id._compute_quantity(new_qty, last_purchase_line.product_uom_id)
109 last_purchase_line.write({'product_qty': quantity})
110 elif last_purchase_line.state in ['purchase', 'cancel']: # create new PO, by forcing the quantity as the difference from SO line
111 quantity = line.product_uom_id._compute_quantity(new_qty - origin_values.get(line.id, 0.0), last_purchase_line.product_uom_id)
112 line._purchase_service_create(quantity=quantity)
113
114 def _purchase_get_date_order(self, supplierinfo):
115 """ return the ordered date for the purchase order, computed as : SO commitment date - supplier delay """
116 commitment_date = fields.Datetime.from_string(self.order_id.commitment_date or fields.Datetime.now())
117 return commitment_date - relativedelta(days=int(supplierinfo.delay))
118
119 def _purchase_service_get_company(self):
120 return self.company_id
121
122 def _purchase_service_prepare_order_values(self, supplierinfo):
123 """ Returns the values to create the purchase order from the current SO line.
124 :param supplierinfo: record of product.supplierinfo
125 :rtype: dict
126 """
127 self.ensure_one()
128 partner_supplier = supplierinfo.partner_id
129 fpos = self.env['account.fiscal.position'].sudo()._get_fiscal_position(partner_supplier)
130 date_order = self._purchase_get_date_order(supplierinfo)
131 return {
132 'partner_id': partner_supplier.id,
133 'partner_ref': partner_supplier.ref,
134 'company_id': self._purchase_service_get_company().id,
135 'currency_id': partner_supplier.property_purchase_currency_id.id or self.env.company.currency_id.id,
136 'dest_address_id': False, # False since only supported in stock
137 'origin': self.order_id.name,
138 'payment_term_id': partner_supplier.property_supplier_payment_term_id.id,
139 'date_order': date_order,
140 'fiscal_position_id': fpos.id,
141 }
142
143 def _purchase_service_get_price_unit_and_taxes(self, supplierinfo, purchase_order):
144 supplier_taxes = self.product_id.supplier_taxes_id.filtered(lambda t: t.company_id in purchase_order.company_id.parent_ids)
145 taxes = purchase_order.fiscal_position_id.map_tax(supplier_taxes)
146 if supplierinfo:
147 price_unit = self.env['account.tax'].sudo()._fix_tax_included_price_company(supplierinfo.price, supplier_taxes, taxes, purchase_order.company_id)
148 if purchase_order.currency_id and supplierinfo.currency_id != purchase_order.currency_id:
149 price_unit = supplierinfo.currency_id._convert(
150 price_unit,
151 purchase_order.currency_id,
152 purchase_order.company_id,
153 fields.Date.context_today(self)
154 )
155 else:
156 price_unit = 0.0
157 return price_unit, taxes
158
159 def _purchase_service_get_product_name(self, supplierinfo, purchase_order, quantity):
160 product_ctx = {
161 'lang': get_lang(self.env, purchase_order.partner_id.lang).code,
162 'company_id': purchase_order.company_id.id,
163 }
164 if supplierinfo:
165 product_ctx.update({'seller_id': supplierinfo.id})
166 else:
167 product_ctx.update({'partner_id': purchase_order.partner_id.id})
168 product = self.product_id.with_context(**product_ctx)
169 name = product.display_name
170 if product.description_purchase:
171 name += '\n' + product.description_purchase
172 return name
173
174 def _purchase_service_prepare_line_values(self, purchase_order, quantity=False):
175 """ Returns the values to create the purchase order line from the current SO line.
176 :param purchase_order: record of purchase.order
177 :rtype: dict
178 :param quantity: the quantity to force on the PO line, expressed in SO line UoM
179 """
180 self.ensure_one()
181 # compute quantity from SO line UoM
182 product_quantity = self.product_uom_qty
183 if quantity:
184 product_quantity = quantity
185
186 purchase_qty_uom = self.product_uom_id._compute_quantity(product_quantity, self.product_id.uom_id)
187
188 # determine vendor (real supplier, sharing the same partner as the one from the PO, but with more accurate informations like validity, quantity, ...)
189 # Note: one partner can have multiple supplier info for the same product
190 supplierinfo = self.product_id._select_seller(
191 partner_id=purchase_order.partner_id,
192 quantity=purchase_qty_uom,
193 date=purchase_order.date_order and purchase_order.date_order.date(), # and purchase_order.date_order[:10],
194 uom_id=self.product_id.uom_id
195 )
196 if supplierinfo and supplierinfo.product_uom_id != self.product_id.uom_id:
197 purchase_qty_uom = self.product_id.uom_id._compute_quantity(purchase_qty_uom, supplierinfo.product_uom_id)
198
199 price_unit, taxes = self._purchase_service_get_price_unit_and_taxes(supplierinfo, purchase_order)
200 name = self._purchase_service_get_product_name(supplierinfo, purchase_order, quantity)
201
202 line_description = self.with_context(lang=self.order_id.partner_id.lang)._get_sale_order_line_multiline_description_variants()
203 if line_description:
204 name += line_description
205
206 purchase_line_vals = {
207 'name': name,
208 'product_qty': purchase_qty_uom,
209 'product_id': self.product_id.id,
210 'product_uom_id': supplierinfo.product_uom_id.id or self.product_id.uom_id.id,
211 'price_unit': price_unit,
212 'date_planned': purchase_order.date_order + relativedelta(days=int(supplierinfo.delay)),
213 'tax_ids': [(6, 0, taxes.ids)],
214 'order_id': purchase_order.id,
215 'sale_line_id': self.id,
216 'discount': supplierinfo.discount,
217 }
218 if self.analytic_distribution:
219 purchase_line_vals['analytic_distribution'] = self.analytic_distribution
220 return purchase_line_vals
221
222 def _purchase_service_match_supplier(self, warning=True):
223 # determine vendor of the order (take the first matching company and product)
224 suppliers = self.product_id._select_seller(partner_id=self._retrieve_purchase_partner(), quantity=self.product_uom_qty, uom_id=self.product_uom_id)
225 if warning and not suppliers:
226 raise UserError(_("There is no vendor associated to the product %s. Please define a vendor for this product.", self.product_id.display_name))
227 return suppliers[0]
228
229 def _get_additional_domain_for_purchase_order_line(self):
230 return [('sale_order_id', '=', self.order_id.id)]
231
232 def _purchase_service_match_purchase_order(self, partner, company=False):
233 return self.env['purchase.order.line'].search(
234 Domain.AND([
235 [
236 ('partner_id', '=', partner.id),
237 ('state', '=', 'draft'),
238 ('company_id', '=', (company and company or self.env.company).id),
239 ],
240 self._get_additional_domain_for_purchase_order_line(),
241 ]),
242 order='order_id',
243 limit=1,
244 ).order_id
245
246 def _create_purchase_order(self, supplierinfo):
247 values = self._purchase_service_prepare_order_values(supplierinfo)
248 return self.env['purchase.order'].with_context(mail_create_nosubscribe=True).create(values)
249
250 def _match_or_create_purchase_order(self, supplierinfo):
251 purchase_order = self._purchase_service_match_purchase_order(supplierinfo.partner_id)[:1]
252 if not purchase_order:
253 purchase_order = self._create_purchase_order(supplierinfo)
254 return purchase_order
255
256 def _retrieve_purchase_partner(self):
257 """ In case we want to explicitely name a partner from whom we want to buy or receive products
258 """
259 self.ensure_one()
260 return False
261
262 def _purchase_service_create(self, quantity=False):
263 """ On Sales Order confirmation, some lines (services ones) can create a purchase order line and maybe a purchase order.
264 If a line should create a RFQ, it will check for existing PO. If no one is find, the SO line will create one, then adds
265 a new PO line. The created purchase order line will be linked to the SO line.
266 :param quantity: the quantity to force on the PO line, expressed in SO line UoM
267 """
268 supplier_po_map = {}
269 sale_line_purchase_map = {}
270
271 for line in self:
272 line = line.with_company(line._purchase_service_get_company())
273 supplierinfo = line._purchase_service_match_supplier()
274 partner_supplier = supplierinfo.partner_id
275
276 # determine (or create) PO
277 purchase_order = supplier_po_map.get(partner_supplier.id)
278 if not purchase_order:
279 purchase_order = line._match_or_create_purchase_order(supplierinfo)
280 so_name = line.order_id.name
281 origins = (purchase_order.origin or '').split(', ')
282 if so_name not in origins:
283 purchase_order.write({'origin': ', '.join(origins + [so_name])})
284 supplier_po_map[partner_supplier.id] = purchase_order
285
286 # add a PO line to the PO
287 values = line._purchase_service_prepare_line_values(purchase_order, quantity=quantity)
288 purchase_line = line.env['purchase.order.line'].create(values)
289
290 # link the generated purchase to the SO line
291 sale_line_purchase_map.setdefault(line, line.env['purchase.order.line'])
292 sale_line_purchase_map[line] |= purchase_line
293 return sale_line_purchase_map
294
295 def _purchase_service_generation(self):
296 """ Create a Purchase for the first time from the sale line. If the SO line already created a PO, it
297 will not create a second one.
298 """
299 sale_line_purchase_map = {}
300 for line in self:
301 line = line.with_company(line._purchase_service_get_company())
302 # Do not regenerate PO line if the SO line has already created one in the past (SO cancel/reconfirmation case)
303 if line.product_id.service_to_purchase and not line.purchase_line_count:
304 result = line._purchase_service_create()
305 sale_line_purchase_map.update(result)
306 return sale_line_purchase_map