| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
from collections import defaultdict |
| 5 |
from datetime import datetime |
| 6 |
from dateutil.relativedelta import relativedelta |
| 7 |
from markupsafe import Markup |
| 8 |
from odoo.tools import float_compare |
| 9 |
|
| 10 |
from odoo import api, fields, models, SUPERUSER_ID, _, Command |
| 11 |
from odoo.addons.stock.models.stock_rule import ProcurementException |
| 12 |
from odoo.tools import groupby |
| 13 |
|
| 14 |
|
| 15 |
class StockRule(models.Model): |
| 16 |
_inherit = 'stock.rule' |
| 17 |
|
| 18 |
action = fields.Selection(selection_add=[ |
| 19 |
('buy', 'Buy') |
| 20 |
], ondelete={'buy': 'cascade'}) |
| 21 |
|
| 22 |
def _get_message_dict(self): |
| 23 |
message_dict = super(StockRule, self)._get_message_dict() |
| 24 |
__, destination, __, __ = self._get_message_values() |
| 25 |
message_dict.update({ |
| 26 |
'buy': _('When products are needed in <b>%s</b>, <br/> ' |
| 27 |
'a request for quotation is created to fulfill the need.<br/>' |
| 28 |
'Note: This rule will be used in combination with the rules<br/>' |
| 29 |
'of the reception route(s)', destination) |
| 30 |
}) |
| 31 |
return message_dict |
| 32 |
|
| 33 |
@api.depends('action') |
| 34 |
def _compute_picking_type_code_domain(self): |
| 35 |
super()._compute_picking_type_code_domain() |
| 36 |
for rule in self: |
| 37 |
if rule.action == 'buy': |
| 38 |
rule.picking_type_code_domain = rule.picking_type_code_domain or [] + ['incoming'] |
| 39 |
|
| 40 |
@api.onchange('action') |
| 41 |
def _onchange_action(self): |
| 42 |
if self.action == 'buy': |
| 43 |
self.location_src_id = False |
| 44 |
|
| 45 |
@api.model |
| 46 |
def run(self, procurements, raise_user_error=True): |
| 47 |
wh_by_comp = dict() |
| 48 |
for procurement in procurements: |
| 49 |
routes = procurement.values.get('route_ids') |
| 50 |
if routes and any(r.action == 'buy' for r in routes.rule_ids): |
| 51 |
company = procurement.company_id |
| 52 |
if company not in wh_by_comp: |
| 53 |
wh_by_comp[company] = self.env['stock.warehouse'].search([('company_id', '=', company.id)]) |
| 54 |
wh = wh_by_comp[company] |
| 55 |
procurement.values['route_ids'] |= wh.reception_route_id |
| 56 |
return super().run(procurements, raise_user_error=raise_user_error) |
| 57 |
|
| 58 |
@api.model |
| 59 |
def _run_buy(self, procurements): |
| 60 |
procurements_by_po_domain = defaultdict(list) |
| 61 |
errors = [] |
| 62 |
for procurement, rule in procurements: |
| 63 |
company_id = rule.company_id or procurement.company_id |
| 64 |
|
| 65 |
supplier = rule._get_matching_supplier( |
| 66 |
procurement.product_id, procurement.product_qty, procurement.product_uom, |
| 67 |
company_id, procurement.values |
| 68 |
) |
| 69 |
|
| 70 |
if not supplier and self.env.context.get('from_orderpoint'): |
| 71 |
msg = _('There is no matching vendor price to generate the purchase order for product %s (no vendor defined, minimum quantity not reached, dates not valid, ...). Go on the product form and complete the list of vendors.', procurement.product_id.display_name) |
| 72 |
errors.append((procurement, msg)) |
| 73 |
elif not supplier: |
| 74 |
|
| 75 |
moves = procurement.values.get('move_dest_ids') or self.env['stock.move'] |
| 76 |
if moves.propagate_cancel: |
| 77 |
moves._action_cancel() |
| 78 |
moves.procure_method = 'make_to_stock' |
| 79 |
self._notify_responsible(procurement) |
| 80 |
continue |
| 81 |
|
| 82 |
partner = supplier.partner_id |
| 83 |
|
| 84 |
procurement.values['supplier'] = supplier |
| 85 |
procurement.values['propagate_cancel'] = rule.propagate_cancel |
| 86 |
|
| 87 |
domain = rule._make_po_get_domain(company_id, procurement.values, partner) |
| 88 |
procurements_by_po_domain[domain].append((procurement, rule)) |
| 89 |
|
| 90 |
if errors: |
| 91 |
raise ProcurementException(errors) |
| 92 |
|
| 93 |
for domain, procurements_rules in procurements_by_po_domain.items(): |
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
procurements, rules = zip(*procurements_rules) |
| 98 |
|
| 99 |
|
| 100 |
origins = set([p.origin for p in procurements if p.origin]) |
| 101 |
|
| 102 |
po = self.env['purchase.order'].sudo().search([dom for dom in domain], limit=1) |
| 103 |
company_id = rules[0].company_id or procurements[0].company_id |
| 104 |
if not po: |
| 105 |
positive_values = [p.values for p in procurements if p.product_uom.compare(p.product_qty, 0.0) >= 0] |
| 106 |
if positive_values: |
| 107 |
|
| 108 |
|
| 109 |
|
| 110 |
vals = rules[0]._prepare_purchase_order(company_id, origins, positive_values) |
| 111 |
|
| 112 |
|
| 113 |
|
| 114 |
|
| 115 |
po = self.env['purchase.order'].with_company(company_id).with_user(SUPERUSER_ID).create(vals) |
| 116 |
else: |
| 117 |
reference_ids = set() |
| 118 |
for procurement in procurements: |
| 119 |
reference_ids |= set(procurement.values.get('reference_ids', self.env['stock.reference']).ids) |
| 120 |
|
| 121 |
po.reference_ids = [Command.link(ref_id) for ref_id in reference_ids] |
| 122 |
if po.origin: |
| 123 |
missing_origins = origins - set(po.origin.split(', ')) |
| 124 |
if missing_origins: |
| 125 |
po.write({'origin': po.origin + ', ' + ', '.join(missing_origins)}) |
| 126 |
else: |
| 127 |
po.write({'origin': ', '.join(origins)}) |
| 128 |
|
| 129 |
procurements_to_merge = self._get_procurements_to_merge(procurements) |
| 130 |
procurements = self._merge_procurements(procurements_to_merge) |
| 131 |
|
| 132 |
po_lines_by_product = {} |
| 133 |
grouped_po_lines = groupby(po.order_line.filtered(lambda l: not l.display_type), key=lambda l: l.product_id.id) |
| 134 |
for product, po_lines in grouped_po_lines: |
| 135 |
po_lines_by_product[product] = self.env['purchase.order.line'].concat(*po_lines) |
| 136 |
po_line_values = [] |
| 137 |
for procurement in procurements: |
| 138 |
po_lines = po_lines_by_product.get(procurement.product_id.id, self.env['purchase.order.line']) |
| 139 |
po_line = po_lines._find_candidate(*procurement) |
| 140 |
|
| 141 |
if po_line: |
| 142 |
|
| 143 |
|
| 144 |
vals = self._update_purchase_order_line(procurement.product_id, |
| 145 |
procurement.product_qty, procurement.product_uom, company_id, |
| 146 |
procurement.values, po_line) |
| 147 |
po_line.sudo().write(vals) |
| 148 |
else: |
| 149 |
if procurement.product_uom.compare(procurement.product_qty, 0) <= 0: |
| 150 |
|
| 151 |
continue |
| 152 |
|
| 153 |
|
| 154 |
|
| 155 |
partner = procurement.values['supplier'].partner_id |
| 156 |
po_line_values.append(self.env['purchase.order.line']._prepare_purchase_order_line_from_procurement( |
| 157 |
*procurement, po)) |
| 158 |
|
| 159 |
date_planned = po.date_planned or min(v['date_planned'] for v in po_line_values) |
| 160 |
order_date_planned = date_planned - relativedelta( |
| 161 |
days=procurement.values['supplier'].delay) |
| 162 |
if fields.Date.to_date(order_date_planned) < fields.Date.to_date(po.date_order): |
| 163 |
po.date_order = order_date_planned |
| 164 |
|
| 165 |
self.env['purchase.order.line'].sudo().create(po_line_values) |
| 166 |
|
| 167 |
def _filter_warehouse_routes(self, product, warehouses, route): |
| 168 |
if any(rule.action == 'buy' for rule in route.rule_ids): |
| 169 |
if product.seller_ids: |
| 170 |
return super()._filter_warehouse_routes(product, warehouses, route) |
| 171 |
return False |
| 172 |
return super()._filter_warehouse_routes(product, warehouses, route) |
| 173 |
|
| 174 |
def _get_matching_supplier(self, product_id, product_qty, product_uom, company_id, values): |
| 175 |
supplier = False |
| 176 |
|
| 177 |
if 'date_planned' in values: |
| 178 |
date = max(fields.Datetime.from_string(values['date_planned']).date(), fields.Date.today()) |
| 179 |
else: |
| 180 |
date = None |
| 181 |
|
| 182 |
if values.get('supplierinfo_id'): |
| 183 |
supplier = values['supplierinfo_id'] |
| 184 |
elif values.get('orderpoint_id') and values['orderpoint_id'].supplier_id: |
| 185 |
supplier = values['orderpoint_id'].supplier_id |
| 186 |
else: |
| 187 |
supplier = product_id.with_company(company_id.id)._select_seller( |
| 188 |
partner_id=self._get_partner_id(values, self), |
| 189 |
quantity=product_qty, |
| 190 |
date=date, |
| 191 |
uom_id=product_uom, |
| 192 |
params={'force_uom': values.get('force_uom')}, |
| 193 |
) |
| 194 |
|
| 195 |
|
| 196 |
|
| 197 |
supplier = supplier or product_id._prepare_sellers(False).filtered( |
| 198 |
lambda s: not s.company_id or s.company_id == company_id |
| 199 |
)[:1] |
| 200 |
|
| 201 |
return supplier |
| 202 |
|
| 203 |
def _post_vendor_notification(self, records_to_notify, users_to_notify, product): |
| 204 |
notification_msg = Markup(" ").join(Markup("%s") % user._get_html_link(f'@{user.name}') for user in users_to_notify) |
| 205 |
notification_msg += Markup("<br/>%s <strong>%s</strong>, %s") % (_("No supplier has been found to replenish"), product.display_name, _("this product should be manually replenished.")) |
| 206 |
records_to_notify.message_post(body=notification_msg, partner_ids=users_to_notify.ids) |
| 207 |
|
| 208 |
def _notify_responsible(self, procurement): |
| 209 |
pass |
| 210 |
|
| 211 |
def _get_lead_days(self, product, **values): |
| 212 |
"""Add the supplier delay to the cumulative delay and cumulative description. |
| 213 |
""" |
| 214 |
delays, delay_description = super()._get_lead_days(product, **values) |
| 215 |
bypass_delay_description = self.env.context.get('bypass_delay_description') |
| 216 |
buy_rule = self.filtered(lambda r: r.action == 'buy') |
| 217 |
seller = 'supplierinfo' in values and values['supplierinfo'] or product.with_company(buy_rule.company_id)._select_seller(quantity=None) |
| 218 |
if not buy_rule: |
| 219 |
return delays, delay_description |
| 220 |
if not seller: |
| 221 |
delays['total_delay'] += 365 |
| 222 |
delays['no_vendor_found_delay'] += 365 |
| 223 |
if not bypass_delay_description: |
| 224 |
delay_description.append((_('No Vendor Found'), _('+ %s day(s)', 365))) |
| 225 |
return delays, delay_description |
| 226 |
buy_rule.ensure_one() |
| 227 |
if not self.env.context.get('ignore_vendor_lead_time'): |
| 228 |
supplier_delay = seller[:1].delay |
| 229 |
delays['total_delay'] += supplier_delay |
| 230 |
delays['purchase_delay'] += supplier_delay |
| 231 |
if not bypass_delay_description: |
| 232 |
delay_description.append((_('Receipt Date'), supplier_delay)) |
| 233 |
delay_description.append((_('Vendor Lead Time'), _('+ %d day(s)', supplier_delay))) |
| 234 |
days_to_order = buy_rule.company_id.days_to_purchase |
| 235 |
delays['total_delay'] += days_to_order |
| 236 |
if not bypass_delay_description: |
| 237 |
delay_description.append((_('Order Deadline'), days_to_order)) |
| 238 |
delay_description.append((_('Days to Purchase'), _('+ %d day(s)', days_to_order))) |
| 239 |
return delays, delay_description |
| 240 |
|
| 241 |
@api.model |
| 242 |
def _get_procurements_to_merge_groupby(self, procurement): |
| 243 |
|
| 244 |
|
| 245 |
|
| 246 |
|
| 247 |
|
| 248 |
return procurement.product_id, procurement.product_uom, procurement.values['propagate_cancel'],\ |
| 249 |
procurement.values.get('product_description_variants'),\ |
| 250 |
(procurement.values.get('orderpoint_id') and not procurement.values.get('move_dest_ids')) and procurement.values['orderpoint_id'] |
| 251 |
|
| 252 |
@api.model |
| 253 |
def _get_procurements_to_merge(self, procurements): |
| 254 |
""" Get a list of procurements values and create groups of procurements |
| 255 |
that would use the same purchase order line. |
| 256 |
params procurements_list list: procurements requests (not ordered nor |
| 257 |
sorted). |
| 258 |
return list: procurements requests grouped by their product_id. |
| 259 |
""" |
| 260 |
return [pro_g for __, pro_g in groupby(procurements, key=self._get_procurements_to_merge_groupby)] |
| 261 |
|
| 262 |
@api.model |
| 263 |
def _merge_procurements(self, procurements_to_merge): |
| 264 |
""" Merge the quantity for procurements requests that could use the same |
| 265 |
order line. |
| 266 |
params similar_procurements list: list of procurements that have been |
| 267 |
marked as 'alike' from _get_procurements_to_merge method. |
| 268 |
return a list of procurements values where values of similar_procurements |
| 269 |
list have been merged. |
| 270 |
""" |
| 271 |
merged_procurements = [] |
| 272 |
for procurements in procurements_to_merge: |
| 273 |
quantity = 0 |
| 274 |
move_dest_ids = self.env['stock.move'] |
| 275 |
orderpoint_id = self.env['stock.warehouse.orderpoint'] |
| 276 |
for procurement in procurements: |
| 277 |
if procurement.values.get('move_dest_ids'): |
| 278 |
move_dest_ids |= procurement.values['move_dest_ids'] |
| 279 |
if not orderpoint_id and procurement.values.get('orderpoint_id'): |
| 280 |
orderpoint_id = procurement.values['orderpoint_id'] |
| 281 |
quantity += procurement.product_qty |
| 282 |
|
| 283 |
|
| 284 |
|
| 285 |
values = dict(procurement.values) |
| 286 |
values.update({ |
| 287 |
'move_dest_ids': move_dest_ids, |
| 288 |
'orderpoint_id': orderpoint_id, |
| 289 |
}) |
| 290 |
merged_procurement = self.env['stock.rule'].Procurement( |
| 291 |
procurement.product_id, quantity, procurement.product_uom, |
| 292 |
procurement.location_id, procurement.name, procurement.origin, |
| 293 |
procurement.company_id, values |
| 294 |
) |
| 295 |
merged_procurements.append(merged_procurement) |
| 296 |
return merged_procurements |
| 297 |
|
| 298 |
def _update_purchase_order_line(self, product_id, product_qty, product_uom, company_id, values, line): |
| 299 |
partner = values['supplier'].partner_id |
| 300 |
procurement_uom_po_qty = product_uom._compute_quantity(product_qty, line.product_uom_id, rounding_method='HALF-UP') |
| 301 |
seller = product_id.with_company(company_id)._select_seller( |
| 302 |
partner_id=partner, |
| 303 |
quantity=line.product_qty + procurement_uom_po_qty, |
| 304 |
date=line.order_id.date_order and line.order_id.date_order.date(), |
| 305 |
uom_id=line.product_uom_id, |
| 306 |
params={'force_uom': values.get('force_uom')}) |
| 307 |
|
| 308 |
price_unit = self.env['account.tax']._fix_tax_included_price_company(seller.price, line.product_id.supplier_taxes_id, line.sudo().tax_ids, company_id) if seller else 0.0 |
| 309 |
if price_unit and seller and line.order_id.currency_id and seller.currency_id != line.order_id.currency_id: |
| 310 |
price_unit = seller.currency_id._convert( |
| 311 |
price_unit, line.order_id.currency_id, line.order_id.company_id, fields.Date.today()) |
| 312 |
|
| 313 |
res = { |
| 314 |
'product_qty': line.product_qty + procurement_uom_po_qty, |
| 315 |
'price_unit': price_unit, |
| 316 |
'move_dest_ids': [(4, x.id) for x in values.get('move_dest_ids', [])] |
| 317 |
} |
| 318 |
if seller.product_uom_id != line.product_uom_id and not values.get('force_uom'): |
| 319 |
res['product_qty'] = line.product_uom_id._compute_quantity(res['product_qty'], seller.product_uom_id, rounding_method='HALF-UP') |
| 320 |
res['product_uom_id'] = seller.product_uom_id |
| 321 |
orderpoint_id = values.get('orderpoint_id') |
| 322 |
if orderpoint_id: |
| 323 |
res['orderpoint_id'] = orderpoint_id.id |
| 324 |
return res |
| 325 |
|
| 326 |
def _prepare_purchase_order(self, company_id, origins, values): |
| 327 |
""" Create a purchase order for procuremets that share the same domain |
| 328 |
returned by _make_po_get_domain. |
| 329 |
params values: values of procurements |
| 330 |
params origins: procuremets origins to write on the PO |
| 331 |
""" |
| 332 |
purchase_date = min([value.get('date_order') or fields.Datetime.from_string(value['date_planned']) - relativedelta(days=int(value['supplier'].delay)) for value in values]) |
| 333 |
|
| 334 |
|
| 335 |
|
| 336 |
|
| 337 |
|
| 338 |
values = values[0] |
| 339 |
partner = values['supplier'].partner_id |
| 340 |
currency = values['supplier'].currency_id |
| 341 |
|
| 342 |
fpos = self.env['account.fiscal.position'].with_company(company_id)._get_fiscal_position(partner) |
| 343 |
|
| 344 |
return { |
| 345 |
'partner_id': partner.id, |
| 346 |
'user_id': partner.buyer_id.id, |
| 347 |
'picking_type_id': self.picking_type_id.id, |
| 348 |
'company_id': company_id.id, |
| 349 |
'currency_id': currency.id or partner.with_company(company_id).property_purchase_currency_id.id or company_id.currency_id.id, |
| 350 |
'dest_address_id': values.get('partner_id', False), |
| 351 |
'origin': ', '.join(origins), |
| 352 |
'payment_term_id': partner.with_company(company_id).property_supplier_payment_term_id.id, |
| 353 |
'date_order': purchase_date, |
| 354 |
'fiscal_position_id': fpos.id, |
| 355 |
'reference_ids': [Command.set(values.get('reference_ids', self.env['stock.reference']).ids)], |
| 356 |
} |
| 357 |
|
| 358 |
def _make_po_get_domain(self, company_id, values, partner): |
| 359 |
currency = ('supplier' in values and values['supplier'].currency_id) or \ |
| 360 |
partner.with_company(company_id).property_purchase_currency_id or \ |
| 361 |
company_id.currency_id |
| 362 |
domain = ( |
| 363 |
('partner_id', '=', partner.id), |
| 364 |
('state', '=', 'draft'), |
| 365 |
('picking_type_id', '=', self.picking_type_id.id), |
| 366 |
('company_id', '=', company_id.id), |
| 367 |
('user_id', '=', partner.buyer_id.id), |
| 368 |
('currency_id', '=', currency.id), |
| 369 |
) |
| 370 |
if partner.group_rfq == 'default' or self.picking_type_id.code == 'dropship': |
| 371 |
if values.get('reference_ids'): |
| 372 |
domain += (('reference_ids', 'in', tuple(values['reference_ids'].ids)),) |
| 373 |
date_planned = fields.Datetime.from_string(values['date_planned']) |
| 374 |
if partner.group_rfq == 'day': |
| 375 |
start_dt = datetime.combine(date_planned, datetime.min.time()) |
| 376 |
end_dt = datetime.combine(date_planned, datetime.max.time()) |
| 377 |
domain += (('date_planned', '>=', start_dt), ('date_planned', '<=', end_dt)) |
| 378 |
if partner.group_rfq == 'week': |
| 379 |
if partner.group_on == 'default': |
| 380 |
start_dt = datetime.combine(date_planned - relativedelta(days=date_planned.isoweekday()), datetime.min.time()) |
| 381 |
end_dt = datetime.combine(date_planned + relativedelta(days=6 - date_planned.isoweekday()), datetime.max.time()) |
| 382 |
domain += (('date_planned', '>=', start_dt), ('date_planned', '<=', end_dt)) |
| 383 |
else: |
| 384 |
delta_days = (7 + int(partner.group_on) - date_planned.isoweekday()) % 7 |
| 385 |
date = date_planned + relativedelta(days=delta_days) |
| 386 |
start_dt = datetime.combine(date, datetime.min.time()) |
| 387 |
end_dt = datetime.combine(date, datetime.max.time()) |
| 388 |
domain += (('date_planned', '>=', start_dt), ('date_planned', '<=', end_dt)) |
| 389 |
|
| 390 |
return domain |
| 391 |
|
| 392 |
def _push_prepare_move_copy_values(self, move_to_copy, new_date): |
| 393 |
res = super(StockRule, self)._push_prepare_move_copy_values(move_to_copy, new_date) |
| 394 |
res['purchase_line_id'] = None |
| 395 |
if self.location_dest_id.usage == "supplier": |
| 396 |
res['purchase_line_id'], res['partner_id'] = move_to_copy._get_purchase_line_and_partner_from_chain() |
| 397 |
return res |
| 398 |
|
| 399 |
def _get_partner_id(self, values, rule): |
| 400 |
return values.get("supplierinfo_name") or (values.get("force_uom") and values.get("partner_id")) |
| 401 |
|
| 402 |
|
| 403 |
class StockRoute(models.Model): |
| 404 |
_inherit = "stock.route" |
| 405 |
|
| 406 |
def _is_valid_resupply_route_for_product(self, product): |
| 407 |
if any(rule.action == 'buy' for rule in self.rule_ids): |
| 408 |
return bool(product.seller_ids) |
| 409 |
return super()._is_valid_resupply_route_for_product(product) |