size
int64 0
304k
| ext
stringclasses 1
value | lang
stringclasses 1
value | branch
stringclasses 1
value | content
stringlengths 0
304k
| avg_line_length
float64 0
238
| max_line_length
int64 0
304k
|
|---|---|---|---|---|---|---|
584
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class FleetVehicleAssignationLog(models.Model):
_name = "fleet.vehicle.assignation.log"
_description = "Drivers history on a vehicle"
_order = "create_date desc, date_start desc"
vehicle_id = fields.Many2one('fleet.vehicle', string="Vehicle", required=True)
driver_id = fields.Many2one('res.partner', string="Driver", required=True)
date_start = fields.Date(string="Start Date")
date_end = fields.Date(string="End Date")
| 38.933333
| 584
|
20,940
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models, _
from odoo.osv import expression
from odoo.addons.fleet.models.fleet_vehicle_model import FUEL_TYPES
#Some fields don't have the exact same name
MODEL_FIELDS_TO_VEHICLE = {
'transmission': 'transmission', 'model_year': 'model_year', 'electric_assistance': 'electric_assistance',
'color': 'color', 'seats': 'seats', 'doors': 'doors', 'trailer_hook': 'trailer_hook',
'default_co2': 'co2', 'co2_standard': 'co2_standard', 'default_fuel_type': 'fuel_type',
'power': 'power', 'horsepower': 'horsepower', 'horsepower_tax': 'horsepower_tax',
}
class FleetVehicle(models.Model):
_inherit = ['mail.thread', 'mail.activity.mixin']
_name = 'fleet.vehicle'
_description = 'Vehicle'
_order = 'license_plate asc, acquisition_date asc'
def _get_default_state(self):
state = self.env.ref('fleet.fleet_vehicle_state_registered', raise_if_not_found=False)
return state if state and state.id else False
name = fields.Char(compute="_compute_vehicle_name", store=True)
description = fields.Html("Vehicle Description", help="Add a note about this vehicle")
active = fields.Boolean('Active', default=True, tracking=True)
manager_id = fields.Many2one(
'res.users', 'Fleet Manager',
domain=lambda self: [('groups_id', 'in', self.env.ref('fleet.fleet_group_manager').id)],
)
company_id = fields.Many2one(
'res.company', 'Company',
default=lambda self: self.env.company,
)
currency_id = fields.Many2one('res.currency', related='company_id.currency_id')
country_id = fields.Many2one('res.country', related='company_id.country_id')
country_code = fields.Char(related='country_id.code')
license_plate = fields.Char(tracking=True,
help='License plate number of the vehicle (i = plate number for a car)')
vin_sn = fields.Char('Chassis Number', help='Unique number written on the vehicle motor (VIN/SN number)', copy=False)
trailer_hook = fields.Boolean(default=False, string='Trailer Hitch', compute='_compute_model_fields', store=True, readonly=False)
driver_id = fields.Many2one('res.partner', 'Driver', tracking=True, help='Driver address of the vehicle', copy=False)
future_driver_id = fields.Many2one('res.partner', 'Future Driver', tracking=True, help='Next Driver Address of the vehicle', copy=False, domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]")
model_id = fields.Many2one('fleet.vehicle.model', 'Model',
tracking=True, required=True, help='Model of the vehicle')
brand_id = fields.Many2one('fleet.vehicle.model.brand', 'Brand', related="model_id.brand_id", store=True, readonly=False)
log_drivers = fields.One2many('fleet.vehicle.assignation.log', 'vehicle_id', string='Assignment Logs')
log_services = fields.One2many('fleet.vehicle.log.services', 'vehicle_id', 'Services Logs')
log_contracts = fields.One2many('fleet.vehicle.log.contract', 'vehicle_id', 'Contracts')
contract_count = fields.Integer(compute="_compute_count_all", string='Contract Count')
service_count = fields.Integer(compute="_compute_count_all", string='Services')
odometer_count = fields.Integer(compute="_compute_count_all", string='Odometer')
history_count = fields.Integer(compute="_compute_count_all", string="Drivers History Count")
next_assignation_date = fields.Date('Assignment Date', help='This is the date at which the car will be available, if not set it means available instantly')
acquisition_date = fields.Date('Immatriculation Date', required=False,
default=fields.Date.today, help='Date when the vehicle has been immatriculated')
first_contract_date = fields.Date(string="First Contract Date", default=fields.Date.today)
color = fields.Char(help='Color of the vehicle', compute='_compute_model_fields', store=True, readonly=False)
state_id = fields.Many2one('fleet.vehicle.state', 'State',
default=_get_default_state, group_expand='_read_group_stage_ids',
tracking=True,
help='Current state of the vehicle', ondelete="set null")
location = fields.Char(help='Location of the vehicle (garage, ...)')
seats = fields.Integer('Seats Number', help='Number of seats of the vehicle', compute='_compute_model_fields', store=True, readonly=False)
model_year = fields.Char('Model Year', help='Year of the model', compute='_compute_model_fields', store=True, readonly=False)
doors = fields.Integer('Doors Number', help='Number of doors of the vehicle', compute='_compute_model_fields', store=True, readonly=False)
tag_ids = fields.Many2many('fleet.vehicle.tag', 'fleet_vehicle_vehicle_tag_rel', 'vehicle_tag_id', 'tag_id', 'Tags', copy=False)
odometer = fields.Float(compute='_get_odometer', inverse='_set_odometer', string='Last Odometer',
help='Odometer measure of the vehicle at the moment of this log')
odometer_unit = fields.Selection([
('kilometers', 'km'),
('miles', 'mi')
], 'Odometer Unit', default='kilometers', help='Unit of the odometer ', required=True)
transmission = fields.Selection(
[('manual', 'Manual'), ('automatic', 'Automatic')], 'Transmission', help='Transmission Used by the vehicle',
compute='_compute_model_fields', store=True, readonly=False)
fuel_type = fields.Selection(FUEL_TYPES, 'Fuel Type', help='Fuel Used by the vehicle', compute='_compute_model_fields', store=True, readonly=False)
horsepower = fields.Integer(compute='_compute_model_fields', store=True, readonly=False)
horsepower_tax = fields.Float('Horsepower Taxation', compute='_compute_model_fields', store=True, readonly=False)
power = fields.Integer('Power', help='Power in kW of the vehicle', compute='_compute_model_fields', store=True, readonly=False)
co2 = fields.Float('CO2 Emissions', help='CO2 emissions of the vehicle', compute='_compute_model_fields', store=True, readonly=False)
co2_standard = fields.Char(compute='_compute_model_fields', store=True, readonly=False)
image_128 = fields.Image(related='model_id.image_128', readonly=True)
contract_renewal_due_soon = fields.Boolean(compute='_compute_contract_reminder', search='_search_contract_renewal_due_soon',
string='Has Contracts to renew')
contract_renewal_overdue = fields.Boolean(compute='_compute_contract_reminder', search='_search_get_overdue_contract_reminder',
string='Has Contracts Overdue')
contract_renewal_name = fields.Text(compute='_compute_contract_reminder', string='Name of contract to renew soon')
contract_renewal_total = fields.Text(compute='_compute_contract_reminder', string='Total of contracts due or overdue minus one')
contract_state = fields.Selection(
[('futur', 'Incoming'),
('open', 'In Progress'),
('expired', 'Expired'),
('closed', 'Closed')
], string='Last Contract State', compute='_compute_contract_reminder', required=False)
car_value = fields.Float(string="Catalog Value (VAT Incl.)", help='Value of the bought vehicle')
net_car_value = fields.Float(string="Purchase Value", help="Purchase value of the vehicle")
residual_value = fields.Float()
plan_to_change_car = fields.Boolean(related='driver_id.plan_to_change_car', store=True, readonly=False)
plan_to_change_bike = fields.Boolean(related='driver_id.plan_to_change_bike', store=True, readonly=False)
vehicle_type = fields.Selection(related='model_id.vehicle_type')
frame_type = fields.Selection([('diamant', 'Diamant'), ('trapez', 'Trapez'), ('wave', 'Wave')], help="Frame type of the bike")
electric_assistance = fields.Boolean(compute='_compute_model_fields', store=True, readonly=False)
frame_size = fields.Float()
@api.depends('model_id')
def _compute_model_fields(self):
'''
Copies all the related fields from the model to the vehicle
'''
model_values = dict()
for vehicle in self.filtered('model_id'):
if vehicle.model_id.id in model_values:
write_vals = model_values[vehicle.model_id.id]
else:
# copy if value is truthy
write_vals = {MODEL_FIELDS_TO_VEHICLE[key]: vehicle.model_id[key] for key in MODEL_FIELDS_TO_VEHICLE\
if vehicle.model_id[key]}
model_values[vehicle.model_id.id] = write_vals
vehicle.write(write_vals)
@api.depends('model_id.brand_id.name', 'model_id.name', 'license_plate')
def _compute_vehicle_name(self):
for record in self:
record.name = (record.model_id.brand_id.name or '') + '/' + (record.model_id.name or '') + '/' + (record.license_plate or _('No Plate'))
def _get_odometer(self):
FleetVehicalOdometer = self.env['fleet.vehicle.odometer']
for record in self:
vehicle_odometer = FleetVehicalOdometer.search([('vehicle_id', '=', record.id)], limit=1, order='value desc')
if vehicle_odometer:
record.odometer = vehicle_odometer.value
else:
record.odometer = 0
def _set_odometer(self):
for record in self:
if record.odometer:
date = fields.Date.context_today(record)
data = {'value': record.odometer, 'date': date, 'vehicle_id': record.id}
self.env['fleet.vehicle.odometer'].create(data)
def _compute_count_all(self):
Odometer = self.env['fleet.vehicle.odometer']
LogService = self.env['fleet.vehicle.log.services']
LogContract = self.env['fleet.vehicle.log.contract']
for record in self:
record.odometer_count = Odometer.search_count([('vehicle_id', '=', record.id)])
record.service_count = LogService.search_count([('vehicle_id', '=', record.id), ('active', '=', record.active)])
record.contract_count = LogContract.search_count([('vehicle_id', '=', record.id), ('state', '!=', 'closed'), ('active', '=', record.active)])
record.history_count = self.env['fleet.vehicle.assignation.log'].search_count([('vehicle_id', '=', record.id)])
@api.depends('log_contracts')
def _compute_contract_reminder(self):
params = self.env['ir.config_parameter'].sudo()
delay_alert_contract = int(params.get_param('hr_fleet.delay_alert_contract', default=30))
for record in self:
overdue = False
due_soon = False
total = 0
name = ''
state = ''
for element in record.log_contracts:
if element.state in ('open', 'expired') and element.expiration_date:
current_date_str = fields.Date.context_today(record)
due_time_str = element.expiration_date
current_date = fields.Date.from_string(current_date_str)
due_time = fields.Date.from_string(due_time_str)
diff_time = (due_time - current_date).days
if diff_time < 0:
overdue = True
total += 1
if diff_time < delay_alert_contract:
due_soon = True
total += 1
if overdue or due_soon:
log_contract = self.env['fleet.vehicle.log.contract'].search([
('vehicle_id', '=', record.id),
('state', 'in', ('open', 'expired'))
], limit=1, order='expiration_date asc')
if log_contract:
# we display only the name of the oldest overdue/due soon contract
name = log_contract.name
state = log_contract.state
record.contract_renewal_overdue = overdue
record.contract_renewal_due_soon = due_soon
record.contract_renewal_total = total - 1 # we remove 1 from the real total for display purposes
record.contract_renewal_name = name
record.contract_state = state
def _get_analytic_name(self):
# This function is used in fleet_account and is overrided in l10n_be_hr_payroll_fleet
return self.license_plate or _('No plate')
def _search_contract_renewal_due_soon(self, operator, value):
params = self.env['ir.config_parameter'].sudo()
delay_alert_contract = int(params.get_param('hr_fleet.delay_alert_contract', default=30))
res = []
assert operator in ('=', '!=', '<>') and value in (True, False), 'Operation not supported'
if (operator == '=' and value is True) or (operator in ('<>', '!=') and value is False):
search_operator = 'in'
else:
search_operator = 'not in'
today = fields.Date.context_today(self)
datetime_today = fields.Datetime.from_string(today)
limit_date = fields.Datetime.to_string(datetime_today + relativedelta(days=+delay_alert_contract))
res_ids = self.env['fleet.vehicle.log.contract'].search([
('expiration_date', '>', today),
('expiration_date', '<', limit_date),
('state', 'in', ['open', 'expired'])
]).mapped('vehicle_id').ids
res.append(('id', search_operator, res_ids))
return res
def _search_get_overdue_contract_reminder(self, operator, value):
res = []
assert operator in ('=', '!=', '<>') and value in (True, False), 'Operation not supported'
if (operator == '=' and value is True) or (operator in ('<>', '!=') and value is False):
search_operator = 'in'
else:
search_operator = 'not in'
today = fields.Date.context_today(self)
res_ids = self.env['fleet.vehicle.log.contract'].search([
('expiration_date', '!=', False),
('expiration_date', '<', today),
('state', 'in', ['open', 'expired'])
]).mapped('vehicle_id').ids
res.append(('id', search_operator, res_ids))
return res
@api.model
def create(self, vals):
# Fleet administrator may not have rights to create the plan_to_change_car value when the driver_id is a res.user
# This trick is used to prevent access right error.
ptc_value = 'plan_to_change_car' in vals.keys() and {'plan_to_change_car': vals.pop('plan_to_change_car')}
res = super(FleetVehicle, self).create(vals)
if ptc_value:
res.sudo().write(ptc_value)
if 'driver_id' in vals and vals['driver_id']:
res.create_driver_history(vals)
if 'future_driver_id' in vals and vals['future_driver_id']:
state_waiting_list = self.env.ref('fleet.fleet_vehicle_state_waiting_list', raise_if_not_found=False)
states = res.mapped('state_id').ids
if not state_waiting_list or state_waiting_list.id not in states:
future_driver = self.env['res.partner'].browse(vals['future_driver_id'])
if self.vehicle_type == 'bike':
future_driver.sudo().write({'plan_to_change_bike': True})
if self.vehicle_type == 'car':
future_driver.sudo().write({'plan_to_change_car': True})
return res
def write(self, vals):
if 'driver_id' in vals and vals['driver_id']:
driver_id = vals['driver_id']
for vehicle in self.filtered(lambda v: v.driver_id.id != driver_id):
vehicle.create_driver_history(vals)
if vehicle.driver_id:
vehicle.activity_schedule(
'mail.mail_activity_data_todo',
user_id=vehicle.manager_id.id or self.env.user.id,
note=_('Specify the End date of %s') % vehicle.driver_id.name)
if 'future_driver_id' in vals and vals['future_driver_id']:
state_waiting_list = self.env.ref('fleet.fleet_vehicle_state_waiting_list', raise_if_not_found=False)
states = self.mapped('state_id').ids if 'state_id' not in vals else [vals['state_id']]
if not state_waiting_list or state_waiting_list.id not in states:
future_driver = self.env['res.partner'].browse(vals['future_driver_id'])
if self.vehicle_type == 'bike':
future_driver.sudo().write({'plan_to_change_bike': True})
if self.vehicle_type == 'car':
future_driver.sudo().write({'plan_to_change_car': True})
if 'active' in vals and not vals['active']:
self.env['fleet.vehicle.log.contract'].search([('vehicle_id', 'in', self.ids)]).active = False
self.env['fleet.vehicle.log.services'].search([('vehicle_id', 'in', self.ids)]).active = False
res = super(FleetVehicle, self).write(vals)
return res
def _get_driver_history_data(self, vals):
self.ensure_one()
return {
'vehicle_id': self.id,
'driver_id': vals['driver_id'],
'date_start': fields.Date.today(),
}
def create_driver_history(self, vals):
for vehicle in self:
self.env['fleet.vehicle.assignation.log'].create(
vehicle._get_driver_history_data(vals),
)
def action_accept_driver_change(self):
# Find all the vehicles for which the driver is the future_driver_id
# remove their driver_id and close their history using current date
vehicles = self.search([('driver_id', 'in', self.mapped('future_driver_id').ids)])
vehicles.write({'driver_id': False})
for vehicle in self:
if vehicle.vehicle_type == 'bike':
vehicle.future_driver_id.sudo().write({'plan_to_change_bike': False})
if vehicle.vehicle_type == 'car':
vehicle.future_driver_id.sudo().write({'plan_to_change_car': False})
vehicle.driver_id = vehicle.future_driver_id
vehicle.future_driver_id = False
@api.model
def _read_group_stage_ids(self, stages, domain, order):
return self.env['fleet.vehicle.state'].search([], order=order)
@api.model
def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True):
if 'co2' in fields:
fields.remove('co2')
return super(FleetVehicle, self).read_group(domain, fields, groupby, offset, limit, orderby, lazy)
@api.model
def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None):
args = args or []
if operator == 'ilike' and not (name or '').strip():
domain = []
else:
domain = ['|', ('name', operator, name), ('driver_id.name', operator, name)]
return self._search(expression.AND([domain, args]), limit=limit, access_rights_uid=name_get_uid)
def return_action_to_open(self):
""" This opens the xml view specified in xml_id for the current vehicle """
self.ensure_one()
xml_id = self.env.context.get('xml_id')
if xml_id:
res = self.env['ir.actions.act_window']._for_xml_id('fleet.%s' % xml_id)
res.update(
context=dict(self.env.context, default_vehicle_id=self.id, group_by=False),
domain=[('vehicle_id', '=', self.id)]
)
return res
return False
def act_show_log_cost(self):
""" This opens log view to view and add new log for this vehicle, groupby default to only show effective costs
@return: the costs log view
"""
self.ensure_one()
copy_context = dict(self.env.context)
copy_context.pop('group_by', None)
res = self.env['ir.actions.act_window']._for_xml_id('fleet.fleet_vehicle_costs_action')
res.update(
context=dict(copy_context, default_vehicle_id=self.id, search_default_parent_false=True),
domain=[('vehicle_id', '=', self.id)]
)
return res
def _track_subtype(self, init_values):
self.ensure_one()
if 'driver_id' in init_values or 'future_driver_id' in init_values:
return self.env.ref('fleet.mt_fleet_driver_updated')
return super(FleetVehicle, self)._track_subtype(init_values)
def open_assignation_logs(self):
self.ensure_one()
return {
'type': 'ir.actions.act_window',
'name': 'Assignment Logs',
'view_mode': 'tree',
'res_model': 'fleet.vehicle.assignation.log',
'domain': [('vehicle_id', '=', self.id)],
'context': {'default_driver_id': self.driver_id.id, 'default_vehicle_id': self.id}
}
| 55.543767
| 20,940
|
431
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class FleetVehicleTag(models.Model):
_name = 'fleet.vehicle.tag'
_description = 'Vehicle Tag'
name = fields.Char('Tag Name', required=True, translate=True)
color = fields.Integer('Color Index')
_sql_constraints = [('name_uniq', 'unique (name)', "Tag name already exists !")]
| 30.785714
| 431
|
366
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class ResConfigSettings(models.TransientModel):
_inherit = ['res.config.settings']
delay_alert_contract = fields.Integer(string='Delay alert contract outdated', default=30, config_parameter='hr_fleet.delay_alert_contract')
| 36.6
| 366
|
352
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class ResPartner(models.Model):
_inherit = 'res.partner'
plan_to_change_car = fields.Boolean('Plan To Change Car', default=False)
plan_to_change_bike = fields.Boolean('Plan To Change Bike', default=False)
| 32
| 352
|
7,365
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models
class FleetVehicleLogContract(models.Model):
_inherit = ['mail.thread', 'mail.activity.mixin']
_name = 'fleet.vehicle.log.contract'
_description = 'Vehicle Contract'
_order = 'state desc,expiration_date'
def compute_next_year_date(self, strdate):
oneyear = relativedelta(years=1)
start_date = fields.Date.from_string(strdate)
return fields.Date.to_string(start_date + oneyear)
vehicle_id = fields.Many2one('fleet.vehicle', 'Vehicle', required=True, help='Vehicle concerned by this log', check_company=True)
cost_subtype_id = fields.Many2one('fleet.service.type', 'Type', help='Cost type purchased with this cost', domain=[('category', '=', 'contract')])
amount = fields.Monetary('Cost')
date = fields.Date(help='Date when the cost has been executed')
company_id = fields.Many2one('res.company', 'Company', default=lambda self: self.env.company)
currency_id = fields.Many2one('res.currency', related='company_id.currency_id')
name = fields.Char(string='Name', compute='_compute_contract_name', store=True)
active = fields.Boolean(default=True)
user_id = fields.Many2one('res.users', 'Responsible', default=lambda self: self.env.user, index=True)
start_date = fields.Date(
'Contract Start Date', default=fields.Date.context_today,
help='Date when the coverage of the contract begins')
expiration_date = fields.Date(
'Contract Expiration Date', default=lambda self:
self.compute_next_year_date(fields.Date.context_today(self)),
help='Date when the coverage of the contract expirates (by default, one year after begin date)')
days_left = fields.Integer(compute='_compute_days_left', string='Warning Date')
insurer_id = fields.Many2one('res.partner', 'Vendor')
purchaser_id = fields.Many2one(related='vehicle_id.driver_id', string='Driver')
ins_ref = fields.Char('Reference', size=64, copy=False)
state = fields.Selection(
[('futur', 'Incoming'),
('open', 'In Progress'),
('expired', 'Expired'),
('closed', 'Closed')
], 'Status', default='open', readonly=True,
help='Choose whether the contract is still valid or not',
tracking=True,
copy=False)
notes = fields.Html('Terms and Conditions', help='Write here all supplementary information relative to this contract', copy=False)
cost_generated = fields.Monetary('Recurring Cost')
cost_frequency = fields.Selection([
('no', 'No'),
('daily', 'Daily'),
('weekly', 'Weekly'),
('monthly', 'Monthly'),
('yearly', 'Yearly')
], 'Recurring Cost Frequency', default='monthly', help='Frequency of the recuring cost', required=True)
service_ids = fields.Many2many('fleet.service.type', string="Included Services")
@api.depends('vehicle_id.name', 'cost_subtype_id')
def _compute_contract_name(self):
for record in self:
name = record.vehicle_id.name
if name and record.cost_subtype_id.name:
name = record.cost_subtype_id.name + ' ' + name
record.name = name
@api.depends('expiration_date', 'state')
def _compute_days_left(self):
"""return a dict with as value for each contract an integer
if contract is in an open state and is overdue, return 0
if contract is in a closed state, return -1
otherwise return the number of days before the contract expires
"""
for record in self:
if record.expiration_date and record.state in ['open', 'expired']:
today = fields.Date.from_string(fields.Date.today())
renew_date = fields.Date.from_string(record.expiration_date)
diff_time = (renew_date - today).days
record.days_left = diff_time if diff_time > 0 else 0
else:
record.days_left = -1
def write(self, vals):
res = super(FleetVehicleLogContract, self).write(vals)
if 'start_date' in vals or 'expiration_date' in vals:
date_today = fields.Date.today()
future_contracts, running_contracts, expired_contracts = self.env[self._name], self.env[self._name], self.env[self._name]
for contract in self.filtered(lambda c: c.start_date and c.state != 'closed'):
if date_today < contract.start_date:
future_contracts |= contract
elif not contract.expiration_date or contract.start_date <= date_today < contract.expiration_date:
running_contracts |= contract
else:
expired_contracts |= contract
future_contracts.action_draft()
running_contracts.action_open()
expired_contracts.action_expire()
if vals.get('expiration_date') or vals.get('user_id'):
self.activity_reschedule(['fleet.mail_act_fleet_contract_to_renew'], date_deadline=vals.get('expiration_date'), new_user_id=vals.get('user_id'))
return res
def action_close(self):
self.write({'state': 'closed'})
def action_draft(self):
self.write({'state': 'futur'})
def action_open(self):
self.write({'state': 'open'})
def action_expire(self):
self.write({'state': 'expired'})
@api.model
def scheduler_manage_contract_expiration(self):
# This method is called by a cron task
# It manages the state of a contract, possibly by posting a message on the vehicle concerned and updating its status
params = self.env['ir.config_parameter'].sudo()
delay_alert_contract = int(params.get_param('hr_fleet.delay_alert_contract', default=30))
date_today = fields.Date.from_string(fields.Date.today())
outdated_days = fields.Date.to_string(date_today + relativedelta(days=+delay_alert_contract))
reminder_activity_type = self.env.ref('fleet.mail_act_fleet_contract_to_renew', raise_if_not_found=False) or self.env['mail.activity.type']
nearly_expired_contracts = self.search([
('state', '=', 'open'),
('expiration_date', '<', outdated_days),
('user_id', '!=', False)
]
).filtered(
lambda nec: reminder_activity_type not in nec.activity_ids.activity_type_id
)
for contract in nearly_expired_contracts:
contract.activity_schedule(
'fleet.mail_act_fleet_contract_to_renew', contract.expiration_date,
user_id=contract.user_id.id)
expired_contracts = self.search([('state', 'not in', ['expired', 'closed']), ('expiration_date', '<',fields.Date.today() )])
expired_contracts.write({'state': 'expired'})
futur_contracts = self.search([('state', 'not in', ['futur', 'closed']), ('start_date', '>', fields.Date.today())])
futur_contracts.write({'state': 'futur'})
now_running_contracts = self.search([('state', '=', 'futur'), ('start_date', '<=', fields.Date.today())])
now_running_contracts.write({'state': 'open'})
def run_scheduler(self):
self.scheduler_manage_contract_expiration()
| 49.763514
| 7,365
|
1,228
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class FleetVehicleOdometer(models.Model):
_name = 'fleet.vehicle.odometer'
_description = 'Odometer log for a vehicle'
_order = 'date desc'
name = fields.Char(compute='_compute_vehicle_log_name', store=True)
date = fields.Date(default=fields.Date.context_today)
value = fields.Float('Odometer Value', group_operator="max")
vehicle_id = fields.Many2one('fleet.vehicle', 'Vehicle', required=True)
unit = fields.Selection(related='vehicle_id.odometer_unit', string="Unit", readonly=True)
driver_id = fields.Many2one(related="vehicle_id.driver_id", string="Driver", readonly=False)
@api.depends('vehicle_id', 'date')
def _compute_vehicle_log_name(self):
for record in self:
name = record.vehicle_id.name
if not name:
name = str(record.date)
elif record.date:
name += ' / ' + str(record.date)
record.name = name
@api.onchange('vehicle_id')
def _onchange_vehicle(self):
if self.vehicle_id:
self.unit = self.vehicle_id.odometer_unit
| 38.375
| 1,228
|
477
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class FleetVehicleModelCategory(models.Model):
_name = 'fleet.vehicle.model.category'
_description = 'Category of the model'
_order = 'sequence asc, id asc'
_sql_constraints = [
('name_uniq', 'UNIQUE (name)', 'Category name must be unique')
]
name = fields.Char(required=True)
sequence = fields.Integer()
| 28.058824
| 477
|
5,199
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from psycopg2 import sql
from odoo import tools
from odoo import api, fields, models
class FleetReport(models.Model):
_name = "fleet.vehicle.cost.report"
_description = "Fleet Analysis Report"
_auto = False
_order = 'date_start desc'
company_id = fields.Many2one('res.company', 'Company', readonly=True)
vehicle_id = fields.Many2one('fleet.vehicle', 'Vehicle', readonly=True)
name = fields.Char('Vehicle Name', readonly=True)
driver_id = fields.Many2one('res.partner', 'Driver', readonly=True)
fuel_type = fields.Char('Fuel', readonly=True)
date_start = fields.Date('Date', readonly=True)
vehicle_type = fields.Selection([('car', 'Car'), ('bike', 'Bike')], readonly=True)
cost = fields.Float('Cost', readonly=True)
cost_type = fields.Selection(string='Cost Type', selection=[
('contract', 'Contract'),
('service', 'Service')
], readonly=True)
def init(self):
query = """
WITH service_costs AS (
SELECT
ve.id AS vehicle_id,
ve.company_id AS company_id,
ve.name AS name,
ve.driver_id AS driver_id,
ve.fuel_type AS fuel_type,
date(date_trunc('month', d)) AS date_start,
vem.vehicle_type as vehicle_type,
COALESCE(sum(se.amount), 0) AS
COST,
'service' AS cost_type
FROM
fleet_vehicle ve
JOIN
fleet_vehicle_model vem ON vem.id = ve.model_id
CROSS JOIN generate_series((
SELECT
min(date)
FROM fleet_vehicle_log_services), CURRENT_DATE + '1 month'::interval, '1 month') d
LEFT JOIN fleet_vehicle_log_services se ON se.vehicle_id = ve.id
AND date_trunc('month', se.date) = date_trunc('month', d)
WHERE
ve.active AND se.active AND se.state != 'cancelled'
GROUP BY
ve.id,
ve.company_id,
vem.vehicle_type,
ve.name,
date_start,
d
ORDER BY
ve.id,
date_start
),
contract_costs AS (
SELECT
ve.id AS vehicle_id,
ve.company_id AS company_id,
ve.name AS name,
ve.driver_id AS driver_id,
ve.fuel_type AS fuel_type,
date(date_trunc('month', d)) AS date_start,
vem.vehicle_type as vehicle_type,
(COALESCE(sum(co.amount), 0) + COALESCE(sum(cod.cost_generated * extract(day FROM least (date_trunc('month', d) + interval '1 month', cod.expiration_date) - greatest (date_trunc('month', d), cod.start_date))), 0) + COALESCE(sum(com.cost_generated), 0) + COALESCE(sum(coy.cost_generated), 0)) AS
COST,
'contract' AS cost_type
FROM
fleet_vehicle ve
JOIN
fleet_vehicle_model vem ON vem.id = ve.model_id
CROSS JOIN generate_series((
SELECT
min(acquisition_date)
FROM fleet_vehicle), CURRENT_DATE + '1 month'::interval, '1 month') d
LEFT JOIN fleet_vehicle_log_contract co ON co.vehicle_id = ve.id
AND date_trunc('month', co.date) = date_trunc('month', d)
LEFT JOIN fleet_vehicle_log_contract cod ON cod.vehicle_id = ve.id
AND date_trunc('month', cod.start_date) <= date_trunc('month', d)
AND date_trunc('month', cod.expiration_date) >= date_trunc('month', d)
AND cod.cost_frequency = 'daily'
LEFT JOIN fleet_vehicle_log_contract com ON com.vehicle_id = ve.id
AND date_trunc('month', com.start_date) <= date_trunc('month', d)
AND date_trunc('month', com.expiration_date) >= date_trunc('month', d)
AND com.cost_frequency = 'monthly'
LEFT JOIN fleet_vehicle_log_contract coy ON coy.vehicle_id = ve.id
AND date_trunc('month', coy.date) = date_trunc('month', d)
AND date_trunc('month', coy.start_date) <= date_trunc('month', d)
AND date_trunc('month', coy.expiration_date) >= date_trunc('month', d)
AND coy.cost_frequency = 'yearly'
WHERE
ve.active
GROUP BY
ve.id,
ve.company_id,
vem.vehicle_type,
ve.name,
date_start,
d
ORDER BY
ve.id,
date_start
)
SELECT row_number() OVER (ORDER BY vehicle_id ASC) as id,
company_id,
vehicle_id,
name,
driver_id,
fuel_type,
date_start,
vehicle_type,
COST,
cost_type
FROM (
SELECT
company_id,
vehicle_id,
name,
driver_id,
fuel_type,
date_start,
vehicle_type,
COST,
'service' as cost_type
FROM
service_costs sc
UNION ALL (
SELECT
company_id,
vehicle_id,
name,
driver_id,
fuel_type,
date_start,
vehicle_type,
COST,
'contract' as cost_type
FROM
contract_costs cc)
) c
"""
tools.drop_view_if_exists(self.env.cr, self._table)
self.env.cr.execute(
sql.SQL("""CREATE or REPLACE VIEW {} as ({})""").format(
sql.Identifier(self._table),
sql.SQL(query)
))
| 33.11465
| 5,199
|
557
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Mass mailing on lead / opportunities',
'category': 'Hidden',
'version': '1.0',
'summary': 'Add lead / opportunities UTM info on mass mailing',
'description': """UTM and mass mailing on lead / opportunities""",
'depends': ['crm', 'mass_mailing'],
'data': [
'views/mailing_mailing_views.xml',
],
'demo': [
'data/mass_mailing_demo.xml',
],
'auto_install': True,
'license': 'LGPL-3',
}
| 29.315789
| 557
|
294
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class UtmCampaign(models.Model):
_inherit = 'utm.campaign'
ab_testing_winner_selection = fields.Selection(selection_add=[('crm_lead_count', 'Leads')])
| 29.4
| 294
|
209
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class CrmLead(models.Model):
_inherit = 'crm.lead'
_mailing_enabled = True
| 23.222222
| 209
|
2,019
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, _, tools
class MassMailing(models.Model):
_name = 'mailing.mailing'
_inherit = 'mailing.mailing'
use_leads = fields.Boolean('Use Leads', compute='_compute_use_leads')
crm_lead_count = fields.Integer('Leads/Opportunities Count', groups='sales_team.group_sale_salesman', compute='_compute_crm_lead_count')
def _compute_use_leads(self):
self.use_leads = self.env.user.has_group('crm.group_use_lead')
def _compute_crm_lead_count(self):
lead_data = self.env['crm.lead'].with_context(active_test=False).read_group(
[('source_id', 'in', self.source_id.ids)],
['source_id'], ['source_id']
)
mapped_data = {datum['source_id'][0]: datum['source_id_count'] for datum in lead_data}
for mass_mailing in self:
mass_mailing.crm_lead_count = mapped_data.get(mass_mailing.source_id.id, 0)
def action_redirect_to_leads_and_opportunities(self):
view = 'crm.crm_lead_all_leads' if self.use_leads else 'crm.crm_lead_opportunities'
action = self.env.ref(view).sudo().read()[0]
action['view_mode'] = 'tree,kanban,graph,pivot,form,calendar'
action['domain'] = [('source_id', 'in', self.source_id.ids)]
action['context'] = {'active_test': False, 'create': False}
return action
def _prepare_statistics_email_values(self):
self.ensure_one()
values = super(MassMailing, self)._prepare_statistics_email_values()
if not self.user_id:
return values
if not self.env['crm.lead'].check_access_rights('read', raise_exception=False):
return values
values['kpi_data'][1]['kpi_col1'] = {
'value': tools.format_decimalized_number(self.crm_lead_count, decimal=0),
'col_subtitle': _('LEADS'),
}
values['kpi_data'][1]['kpi_name'] = 'lead'
return values
| 43.891304
| 2,019
|
695
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Colombian - Point of Sale',
'icon': '/l10n_co/static/description/icon.png',
'version': '1.0',
'description': """Colombian - Point of Sale""",
'category': 'Accounting/Localizations/Point of Sale',
'auto_install': True,
'depends': [
'l10n_co',
'point_of_sale'
],
'data': [
'views/views.xml'
],
'assets': {
'point_of_sale.assets': [
'l10n_co_pos/static/src/js/**/*',
],
'web.assets_qweb': [
'l10n_co_pos/static/src/xml/**/*',
],
},
'license': 'LGPL-3',
}
| 25.740741
| 695
|
391
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Google Users',
'category': 'Hidden/Tools',
'description': """
The module adds google user in res user.
========================================
""",
'depends': ['base_setup'],
'data': [
'data/google_account_data.xml',
],
'license': 'LGPL-3',
}
| 24.4375
| 391
|
8,704
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime
import json
import logging
import requests
from werkzeug import urls
from odoo import api, fields, models, _
from odoo.exceptions import UserError
_logger = logging.getLogger(__name__)
TIMEOUT = 20
GOOGLE_AUTH_ENDPOINT = 'https://accounts.google.com/o/oauth2/auth'
GOOGLE_TOKEN_ENDPOINT = 'https://accounts.google.com/o/oauth2/token'
GOOGLE_API_BASE_URL = 'https://www.googleapis.com'
class GoogleService(models.AbstractModel):
_name = 'google.service'
_description = 'Google Service'
@api.model
def generate_refresh_token(self, service, authorization_code):
""" Call Google API to refresh the token, with the given authorization code
:param service : the name of the google service to actualize
:param authorization_code : the code to exchange against the new refresh token
:returns the new refresh token
"""
Parameters = self.env['ir.config_parameter'].sudo()
client_id = Parameters.get_param('google_%s_client_id' % service)
client_secret = Parameters.get_param('google_%s_client_secret' % service)
redirect_uri = Parameters.get_param('google_redirect_uri')
# Get the Refresh Token From Google And store it in ir.config_parameter
headers = {"Content-type": "application/x-www-form-urlencoded"}
data = {
'code': authorization_code,
'client_id': client_id,
'client_secret': client_secret,
'redirect_uri': redirect_uri,
'grant_type': "authorization_code"
}
try:
req = requests.post(GOOGLE_TOKEN_ENDPOINT, data=data, headers=headers, timeout=TIMEOUT)
req.raise_for_status()
content = req.json()
except IOError:
error_msg = _("Something went wrong during your token generation. Maybe your Authorization Code is invalid or already expired")
raise self.env['res.config.settings'].get_config_warning(error_msg)
return content.get('refresh_token')
@api.model
def _get_google_token_uri(self, service, scope):
get_param = self.env['ir.config_parameter'].sudo().get_param
encoded_params = urls.url_encode({
'scope': scope,
'redirect_uri': get_param('google_redirect_uri'),
'client_id': get_param('google_%s_client_id' % service),
'response_type': 'code',
})
return '%s?%s' % (GOOGLE_AUTH_ENDPOINT, encoded_params)
@api.model
def _get_authorize_uri(self, from_url, service, scope=False):
""" This method return the url needed to allow this instance of Odoo to access to the scope
of gmail specified as parameters
"""
state = {
'd': self.env.cr.dbname,
's': service,
'f': from_url
}
get_param = self.env['ir.config_parameter'].sudo().get_param
base_url = self._context.get('base_url') or self.env.user.get_base_url()
client_id = get_param('google_%s_client_id' % (service,), default=False)
encoded_params = urls.url_encode({
'response_type': 'code',
'client_id': client_id,
'state': json.dumps(state),
'scope': scope or '%s/auth/%s' % (GOOGLE_API_BASE_URL, service), # If no scope is passed, we use service by default to get a default scope
'redirect_uri': base_url + '/google_account/authentication',
'approval_prompt': 'force',
'access_type': 'offline'
})
return "%s?%s" % (GOOGLE_AUTH_ENDPOINT, encoded_params)
@api.model
def _get_google_tokens(self, authorize_code, service):
""" Call Google API to exchange authorization code against token, with POST request, to
not be redirected.
"""
get_param = self.env['ir.config_parameter'].sudo().get_param
base_url = self._context.get('base_url') or self.env.user.get_base_url()
client_id = get_param('google_%s_client_id' % (service,), default=False)
client_secret = get_param('google_%s_client_secret' % (service,), default=False)
headers = {"content-type": "application/x-www-form-urlencoded"}
data = {
'code': authorize_code,
'client_id': client_id,
'client_secret': client_secret,
'grant_type': 'authorization_code',
'redirect_uri': base_url + '/google_account/authentication'
}
try:
dummy, response, dummy = self._do_request(GOOGLE_TOKEN_ENDPOINT, params=data, headers=headers, method='POST', preuri='')
access_token = response.get('access_token')
refresh_token = response.get('refresh_token')
ttl = response.get('expires_in')
return access_token, refresh_token, ttl
except requests.HTTPError:
error_msg = _("Something went wrong during your token generation. Maybe your Authorization Code is invalid")
raise self.env['res.config.settings'].get_config_warning(error_msg)
@api.model
def _get_access_token(self, refresh_token, service, scope):
"""Fetch the access token thanks to the refresh token."""
get_param = self.env['ir.config_parameter'].sudo().get_param
client_id = get_param('google_%s_client_id' % service, default=False)
client_secret = get_param('google_%s_client_secret' % service, default=False)
if not client_id or not client_secret:
raise UserError(_('Google %s is not yet configured.', service.title()))
if not refresh_token:
raise UserError(_('The refresh token for authentication is not set.'))
try:
result = requests.post(
GOOGLE_TOKEN_ENDPOINT,
data={
'client_id': client_id,
'client_secret': client_secret,
'refresh_token': refresh_token,
'grant_type': 'refresh_token',
'scope': scope,
},
headers={'Content-type': 'application/x-www-form-urlencoded'},
timeout=TIMEOUT,
)
result.raise_for_status()
except requests.HTTPError:
raise UserError(
_('Something went wrong during the token generation. Please request again an authorization code.')
)
json_result = result.json()
return json_result.get('access_token'), json_result.get('expires_in')
@api.model
def _do_request(self, uri, params=None, headers=None, method='POST', preuri="https://www.googleapis.com", timeout=TIMEOUT):
""" Execute the request to Google API. Return a tuple ('HTTP_CODE', 'HTTP_RESPONSE')
:param uri : the url to contact
:param params : dict or already encoded parameters for the request to make
:param headers : headers of request
:param method : the method to use to make the request
:param preuri : pre url to prepend to param uri.
"""
if params is None:
params = {}
if headers is None:
headers = {}
_logger.debug("Uri: %s - Type : %s - Headers: %s - Params : %s !", uri, method, headers, params)
ask_time = fields.Datetime.now()
try:
if method.upper() in ('GET', 'DELETE'):
res = requests.request(method.lower(), preuri + uri, params=params, timeout=timeout)
elif method.upper() in ('POST', 'PATCH', 'PUT'):
res = requests.request(method.lower(), preuri + uri, data=params, headers=headers, timeout=timeout)
else:
raise Exception(_('Method not supported [%s] not in [GET, POST, PUT, PATCH or DELETE]!') % (method))
res.raise_for_status()
status = res.status_code
if int(status) == 204: # Page not found, no response
response = False
else:
response = res.json()
try:
ask_time = datetime.strptime(res.headers.get('date', ''), "%a, %d %b %Y %H:%M:%S %Z")
except ValueError:
pass
except requests.HTTPError as error:
if error.response.status_code in (204, 404):
status = error.response.status_code
response = ""
else:
_logger.exception("Bad google request : %s !", error.response.content)
raise error
return (status, response, ask_time)
| 43.089109
| 8,704
|
1,376
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import json
from werkzeug.exceptions import BadRequest
from odoo import http
from odoo.http import request
class GoogleAuth(http.Controller):
@http.route('/google_account/authentication', type='http', auth="public")
def oauth2callback(self, **kw):
""" This route/function is called by Google when user Accept/Refuse the consent of Google """
state = json.loads(kw.get('state', '{}'))
dbname = state.get('d')
service = state.get('s')
url_return = state.get('f')
base_url = request.httprequest.url_root.strip('/')
if (not dbname or not service or (kw.get('code') and not url_return)):
raise BadRequest()
if kw.get('code'):
access_token, refresh_token, ttl = request.env['google.service'].with_context(base_url=base_url)._get_google_tokens(kw['code'], service)
# LUL TODO only defined in google_calendar
request.env.user.google_cal_account_id._set_auth_tokens(access_token, refresh_token, ttl)
return request.redirect(url_return)
elif kw.get('error'):
return request.redirect("%s%s%s" % (url_return, "?error=", kw['error']))
else:
return request.redirect("%s%s" % (url_return, "?error=Unknown_error"))
| 43
| 1,376
|
6,485
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Inventory',
'version': '1.1',
'summary': 'Manage your stock and logistics activities',
'description': "",
'website': 'https://www.odoo.com/app/inventory',
'depends': ['product', 'barcodes', 'digest'],
'category': 'Inventory/Inventory',
'sequence': 25,
'demo': [
'data/stock_demo_pre.xml',
'data/stock_demo.xml',
'data/stock_demo2.xml',
'data/stock_orderpoint_demo.xml',
'data/stock_storage_category_demo.xml',
],
'data': [
'security/stock_security.xml',
'security/ir.model.access.csv',
'data/digest_data.xml',
'data/mail_templates.xml',
'data/default_barcode_patterns.xml',
'data/stock_data.xml',
'data/stock_sequence_data.xml',
'data/stock_traceability_report_data.xml',
'report/report_stock_forecasted.xml',
'report/report_stock_quantity.xml',
'report/report_stock_reception.xml',
'report/stock_report_views.xml',
'report/report_package_barcode.xml',
'report/report_lot_barcode.xml',
'report/report_location_barcode.xml',
'report/report_stockpicking_operations.xml',
'report/report_deliveryslip.xml',
'report/report_stockinventory.xml',
'report/report_stock_rule.xml',
'report/package_templates.xml',
'report/picking_templates.xml',
'report/product_templates.xml',
'report/product_packaging.xml',
'data/mail_template_data.xml',
'views/stock_menu_views.xml',
'wizard/stock_assign_serial_views.xml',
'wizard/stock_change_product_qty_views.xml',
'wizard/stock_picking_return_views.xml',
'wizard/stock_scheduler_compute_views.xml',
'wizard/stock_immediate_transfer_views.xml',
'wizard/stock_inventory_conflict.xml',
'wizard/stock_backorder_confirmation_views.xml',
'wizard/stock_quantity_history.xml',
'wizard/stock_request_count.xml',
'wizard/stock_replenishment_info.xml',
'wizard/stock_rules_report_views.xml',
'wizard/stock_warn_insufficient_qty_views.xml',
'wizard/product_replenish_views.xml',
'wizard/product_label_layout_views.xml',
'wizard/stock_track_confirmation_views.xml',
'wizard/stock_orderpoint_snooze_views.xml',
'wizard/stock_package_destination_views.xml',
'wizard/stock_inventory_adjustment_name.xml',
'wizard/stock_inventory_warning.xml',
'views/res_partner_views.xml',
'views/product_strategy_views.xml',
'views/product_views.xml',
'views/stock_production_lot_views.xml',
'views/stock_scrap_views.xml',
'views/stock_quant_views.xml',
'views/stock_location_views.xml',
'views/stock_warehouse_views.xml',
'views/stock_move_line_views.xml',
'views/stock_picking_views.xml',
'views/stock_move_views.xml',
'views/stock_orderpoint_views.xml',
'views/stock_storage_category_views.xml',
'views/res_config_settings_views.xml',
'views/report_stock_traceability.xml',
'views/stock_template.xml',
'views/stock_rule_views.xml',
'views/stock_package_level_views.xml',
'views/stock_package_type_view.xml',
],
'installable': True,
'application': True,
'auto_install': False,
'pre_init_hook': 'pre_init_hook',
'post_init_hook': '_assign_default_mail_template_picking_id',
'assets': {
'web.report_assets_common': [
'web/static/src/legacy/scss/views.scss',
'web/static/src/legacy/scss/graph_view.scss',
'stock/static/src/scss/report_stock_forecasted.scss',
'stock/static/src/scss/report_stock_reception.scss',
'stock/static/src/scss/report_stock_rule.scss',
],
'web.assets_common': [
'stock/static/src/scss/stock_traceability_report.scss',
],
'web.assets_backend': [
'stock/static/src/js/inventory_report_list_controller.js',
'stock/static/src/js/inventory_report_list_view.js',
'stock/static/src/js/inventory_singleton_list_renderer.js',
'stock/static/src/js/inventory_singleton_list_controller.js',
'stock/static/src/js/inventory_singleton_list_view.js',
'stock/static/src/js/report_stock_forecasted.js',
'stock/static/src/js/report_stock_reception.js',
'stock/static/src/js/lazy_column_list.js',
'stock/static/src/js/stock_orderpoint_list_controller.js',
'stock/static/src/js/stock_orderpoint_list_model.js',
'stock/static/src/js/stock_orderpoint_list_view.js',
'stock/static/src/js/stock_traceability_report_backend.js',
'stock/static/src/js/stock_traceability_report_widgets.js',
'stock/static/src/js/popover_widget.js',
'stock/static/src/js/forecast_widget.js',
'stock/static/src/js/counted_quantity_widget.js',
'stock/static/src/js/basic_model.js',
'stock/static/src/js/stock_rescheduling_popover.js',
'stock/static/src/scss/forecast_widget.scss',
'stock/static/src/scss/stock_traceability_report.scss',
'stock/static/src/scss/stock_empty_screen.scss',
],
'web.assets_tests': [
'stock/static/tests/tours/stock_report_tests.js',
],
'web.qunit_suite_tests': [
'stock/static/tests/singleton_list_tests.js',
'stock/static/tests/popover_widget_tests.js',
'stock/static/tests/lazy_column_list_tests.js',
'stock/static/tests/stock_traceability_report_backend_tests.js',
'stock/static/tests/stock_orderpoint_tests.js',
],
'web.assets_qweb': [
'stock/static/src/xml/inventory_report.xml',
'stock/static/src/xml/inventory_lines.xml',
'stock/static/src/xml/popover_widget.xml',
'stock/static/src/xml/forecast_widget.xml',
'stock/static/src/xml/report_stock_forecasted.xml',
'stock/static/src/xml/report_stock_reception.xml',
'stock/static/src/xml/stock_orderpoint.xml',
'stock/static/src/xml/stock_traceability_report_backend.xml',
],
},
'license': 'LGPL-3',
}
| 43.233333
| 6,485
|
30,335
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
import math
from datetime import datetime, timedelta
from itertools import product as cartesian_product
from collections import defaultdict
from odoo import models, api
from odoo.tools import populate, groupby
_logger = logging.getLogger(__name__)
# Take X first company to put some stock on it data (it is to focus data on these companies)
COMPANY_NB_WITH_STOCK = 3 # Need to be smaller than 5 (_populate_sizes['small'] of company)
class Warehouse(models.Model):
_inherit = 'stock.warehouse'
_populate_sizes = {'small': 6, 'medium': 12, 'large': 24}
_populate_dependencies = ['res.company']
def _populate(self, size):
# Activate options used in the stock populate to have a ready Database
_logger.info("Activate settings for stock populate")
self.env['res.config.settings'].create({
'group_stock_production_lot': True, # Activate lot
'group_stock_tracking_lot': True, # Activate package
'group_stock_multi_locations': True, # Activate multi-locations
'group_stock_tracking_owner': True, # Activate owner_id
}).execute()
return super()._populate(size)
def _populate_factories(self):
company_ids = self.env.registry.populated_models['res.company'][:COMPANY_NB_WITH_STOCK]
def get_name(values, counter, random):
return "WH-%d-%d" % (values['company_id'], counter)
return [
('company_id', populate.iterate(company_ids)),
('name', populate.compute(get_name)),
('code', populate.constant("W{counter}")),
('reception_steps', populate.iterate(['one_step', 'two_steps', 'three_steps'], [0.6, 0.2, 0.2])),
('delivery_steps', populate.iterate(['ship_only', 'pick_ship', 'pick_pack_ship'], [0.6, 0.2, 0.2])),
]
class StorageCategory(models.Model):
_inherit = 'stock.storage.category'
_populate_sizes = {'small': 10, 'medium': 20, 'large': 50}
def _populate(self, size):
# Activate options used in the stock populate to have a ready Database
self.env['res.config.settings'].create({
'group_stock_storage_categories': True, # Activate storage categories
}).execute()
return super()._populate(size)
def _populate_factories(self):
return [
('name', populate.constant("SC-{counter}")),
('max_weight', populate.iterate([10, 100, 500, 1000])),
('allow_new_product', populate.randomize(['empty', 'same', 'mixed'], [0.1, 0.1, 0.8])),
]
class Location(models.Model):
_inherit = 'stock.location'
_populate_sizes = {'small': 50, 'medium': 2_000, 'large': 50_000}
_populate_dependencies = ['stock.warehouse', 'stock.storage.category']
def _populate(self, size):
locations = super()._populate(size)
random = populate.Random('stock_location_sample')
locations_sample = self.browse(random.sample(locations.ids, len(locations.ids)))
company_ids = self.env.registry.populated_models['res.company'][:COMPANY_NB_WITH_STOCK]
warehouses = self.env['stock.warehouse'].browse(self.env.registry.populated_models['stock.warehouse'])
warehouse_by_company = dict(groupby(warehouses, lambda ware: ware.company_id.id))
loc_ids_by_company = dict(groupby(locations_sample, lambda loc: loc.company_id.id))
scenario_index = 0
for company_id in company_ids:
loc_ids_by_company[company_id] = loc_ids_by_company[company_id][::-1] # Inverse the order to use pop()
warehouses = warehouse_by_company[company_id]
nb_loc_by_warehouse = math.ceil(len(loc_ids_by_company[company_id]) / len(warehouses))
for warehouse in warehouses:
# Manage the ceil, the last warehouse can have less locations than others.
nb_loc_to_take = min(nb_loc_by_warehouse, len(loc_ids_by_company[company_id]))
if scenario_index % 3 == 0:
# Scenario 1 : remain companies with "normal" level depth keep 4 levels max
depth = 3 # Force the number of level to 3 (root doesn't count)
elif scenario_index % 3 == 1:
# Scenario 2 : one company with very low level depth location tree (all child of root)
depth = 1
else:
# Scenario 3 : one company with high depth location tree
depth = 10
nb_by_level = int(math.log(nb_loc_to_take, depth)) + 1 if depth > 1 else nb_loc_to_take # number of loc to put by level
_logger.info("Create locations (%d) tree for a warehouse (%s) - depth : %d, width : %d" % (nb_loc_to_take, warehouse.code, depth, nb_by_level))
# Root is the lot_stock_id of warehouse
root = warehouse.lot_stock_id
def link_next_locations(parent, level):
if level < depth:
children = []
nonlocal nb_loc_to_take
nb_loc = min(nb_by_level, nb_loc_to_take)
nb_loc_to_take -= nb_loc
for i in range(nb_loc):
children.append(loc_ids_by_company[company_id].pop())
child_locations = self.env['stock.location'].concat(*children)
child_locations.location_id = parent # Quite slow, because the ORM flush each time
for child in child_locations:
link_next_locations(child, level + 1)
link_next_locations(root, 0)
scenario_index += 1
# Change 20 % the usage of some no-leaf location into 'view' (instead of 'internal')
to_views = locations_sample.filtered_domain([('child_ids', '!=', [])]).ids
random = populate.Random('stock_location_views')
view_locations = self.browse(random.sample(to_views, int(len(to_views) * 0.1)))
view_locations.write({
'usage': 'view',
'storage_category_id': False,
})
return locations
def _populate_factories(self):
company_ids = self.env.registry.populated_models['res.company'][:COMPANY_NB_WITH_STOCK]
removal_strategies = self.env['product.removal'].search([])
storage_category_ids = self.env.registry.populated_models['stock.storage.category']
def get_storage_category_id(values, counter, random):
if random.random() > 0.5:
return random.choice(storage_category_ids)
return False
return [
('name', populate.constant("Loc-{counter}")),
('usage', populate.constant('internal')),
('removal_strategy_id', populate.randomize(removal_strategies.ids + [False])),
('company_id', populate.iterate(company_ids)),
('storage_category_id', populate.compute(get_storage_category_id)),
]
class StockPutawayRule(models.Model):
_inherit = 'stock.putaway.rule'
_populate_sizes = {'small': 10, 'medium': 20, 'large': 50}
_populate_dependencies = ['stock.location', 'product.product']
def _populate_factories(self):
company_ids = self.env.registry.populated_models['res.company'][:COMPANY_NB_WITH_STOCK]
product_ids = self.env['product.product'].browse(self.env.registry.populated_models['product.product']).filtered(lambda p: p.type == 'product').ids
product_categ_ids = self.env.registry.populated_models['product.category']
storage_categ_ids = self.env.registry.populated_models['stock.storage.category']
location_ids = self.env['stock.location'].browse(self.env.registry.populated_models['stock.location']).filtered(lambda loc: loc.usage == 'internal')
def get_product_id(values, counter, random):
if random.random() > 0.5:
return random.choice(product_ids)
return False
def get_category_id(values, counter, random):
if not values['product_id']:
return random.choice(product_categ_ids)
return False
def get_location_in_id(values, counter, random):
locations = location_ids.filtered(lambda loc: loc.company_id.id == values['company_id'])
return random.choice(locations.ids)
def get_location_out_id(values, counter, random):
child_locs = self.env['stock.location'].search([
('id', 'child_of', values['location_in_id']),
('usage', '=', 'internal')
]) + self.env['stock.location'].browse(values['location_in_id'])
return random.choice(child_locs.ids)
return [
('company_id', populate.randomize(company_ids)),
('product_id', populate.compute(get_product_id)),
('category_id', populate.compute(get_category_id)),
('location_in_id', populate.compute(get_location_in_id)),
('location_out_id', populate.compute(get_location_out_id)),
('sequence', populate.randint(1, 1000)),
('storage_category_id', populate.randomize(storage_categ_ids)),
]
class StockWarehouseOrderpoint(models.Model):
_inherit = 'stock.warehouse.orderpoint'
_populate_sizes = {'small': 150, 'medium': 5_000, 'large': 60_000}
_populate_dependencies = ['product.product', 'product.supplierinfo', 'stock.location']
def _populate_factories(self):
warehouse_ids = self.env.registry.populated_models['stock.warehouse']
warehouses = self.env['stock.warehouse'].browse(warehouse_ids)
location_by_warehouse = {
warehouse.id: self.env['stock.location'].search([('id', 'child_of', warehouse.lot_stock_id.id)]).ids
for warehouse in warehouses
}
all_product_ids = set(self.env.registry.populated_models['product.product'])
supplierinfos = self.env['product.supplierinfo'].browse(self.env.registry.populated_models['product.supplierinfo'])
# Valid product by company (a supplier info exist for this product+company_id)
valid_product = defaultdict(set)
for suplierinfo in supplierinfos:
products = suplierinfo.product_id or suplierinfo.product_tmpl_id.product_variant_ids
# Reordering rule is only on the storable product
if products and products[0].type == 'product':
valid_product[suplierinfo.company_id.id] |= set(products.ids)
valid_product = {company_id: product_ids | valid_product[False] for company_id, product_ids in valid_product.items() if company_id}
invalid_product = {company_id: list(all_product_ids - product_ids) for company_id, product_ids in valid_product.items() if company_id}
valid_product = {company_id: list(product_ids) for company_id, product_ids in valid_product.items()}
def get_company_id(values, counter, random):
warehouse = self.env['stock.warehouse'].browse(values['warehouse_id'])
return warehouse.company_id.id
def get_location_product(iterator, field_name, model_name):
random = populate.Random('get_location_product')
# To avoid raise product_location_check : product/location/company (company is ensure because warehouse doesn't share location for now)
# Use generator to avoid cartisian product in memory
generator_valid_product_loc_dict = {}
generator_invalid_product_loc_dict = {}
for warehouse in warehouses:
# TODO: randomize cartesian product
generator_valid_product_loc_dict[warehouse.id] = cartesian_product(
# Force to begin by the main location of the warehouse
[warehouse.lot_stock_id.id] + random.sample(location_by_warehouse[warehouse.id], len(location_by_warehouse[warehouse.id])),
random.sample(valid_product[warehouse.company_id.id], len(valid_product[warehouse.company_id.id]))
)
generator_invalid_product_loc_dict[warehouse.id] = cartesian_product(
[warehouse.lot_stock_id.id] + random.sample(location_by_warehouse[warehouse.id], len(location_by_warehouse[warehouse.id])),
random.sample(invalid_product[warehouse.company_id.id], len(invalid_product[warehouse.company_id.id]))
)
for values in iterator:
# 95 % of the orderpoint will be valid (a supplier info exist for this product + company_id)
if random.random() < 0.95:
loc_id, product_id = next(generator_valid_product_loc_dict[values['warehouse_id']])
else:
loc_id, product_id = next(generator_invalid_product_loc_dict[values['warehouse_id']])
values['product_id'] = product_id
values['location_id'] = loc_id
yield values
return [
('active', populate.iterate([True, False], [0.95, 0.05])),
('warehouse_id', populate.iterate(warehouse_ids)),
('company_id', populate.compute(get_company_id)),
('_get_location_product', get_location_product),
('product_min_qty', populate.iterate([0.0, 2.0, 10.0], [0.6, 0.2, 0.2])),
('product_max_qty', populate.iterate([10.0, 20.0, 100.0], [0.6, 0.2, 0.2])),
('qty_multiple', populate.iterate([0.0, 1.0, 2.0, 10.0], [0.4, 0.2, 0.2, 0.2])),
]
class StockQuant(models.Model):
_inherit = 'stock.quant'
_populate_sizes = {'small': 100, 'medium': 5000, 'large': 20000}
_populate_dependencies = ['stock.location', 'product.product']
def _populate_factories(self):
product_ids = self.env['product.product'].search([
('id', 'in', self.env.registry.populated_models['product.product']),
('type', '=', 'product'),
('tracking', '=', 'none')
]).ids
locations = self.env['stock.location'].search([
('id', 'in', self.env.registry.populated_models['stock.location']),
('usage', '=', 'internal'),
])
return [
('location_id', populate.randomize(locations.ids)),
('product_id', populate.randomize(product_ids)),
('inventory_quantity', populate.randint(0, 100)),
]
def _populate(self, size):
res = super(StockQuant, self.with_context(inventory_move=True))._populate(size)
_logger.info("Apply %d inventories line", len(res))
res.action_apply_inventory()
return res
class PickingType(models.Model):
_inherit = 'stock.picking.type'
_populate_sizes = {'small': 9, 'medium': 30, 'large': 200}
_populate_dependencies = ['stock.location']
def _populate_factories(self):
company_ids = self.env.registry.populated_models['res.company'][:COMPANY_NB_WITH_STOCK]
warehouses = self.env['stock.warehouse'].browse(self.env.registry.populated_models['stock.warehouse'])
internal_locations = self.env['stock.location'].search([('company_id', 'in', company_ids), ('usage', '=', 'internal')])
in_warehouse_locations = self.env['stock.location'].search([('id', 'child_of', warehouses.lot_stock_id.ids)])
internal_locations &= in_warehouse_locations
def get_name(values, counter, random):
return "%d-%s-%d" % (values['company_id'], values['code'], counter)
def _compute_default_locations(iterator, field_name, model_name):
random = populate.Random('_compute_default_locations')
locations_by_company = dict(groupby(internal_locations, key=lambda loc: loc.company_id.id))
locations_by_company = {company_id: self.env['stock.location'].concat(*locations) for company_id, locations in locations_by_company.items()}
for values in iterator:
locations_company = locations_by_company[values['company_id']]
inter_location = random.choice(locations_company)
values['warehouse_id'] = inter_location.warehouse_id.id
if values['code'] == 'internal':
values['default_location_src_id'] = inter_location.id
values['default_location_dest_id'] = random.choice(locations_company - inter_location).id
elif values['code'] == 'incoming':
values['default_location_dest_id'] = inter_location.id
elif values['code'] == 'outgoing':
values['default_location_src_id'] = inter_location.id
yield values
def get_show_operations(values, counter, random):
return values['code'] != 'incoming' # Simulate onchange of form
def get_show_reserved(values, counter, random):
return values['show_operations'] and values['code'] != 'incoming' # Simulate onchange of form
return [
('company_id', populate.iterate(company_ids)),
('code', populate.iterate(['incoming', 'outgoing', 'internal'], [0.3, 0.3, 0.4])),
('name', populate.compute(get_name)),
('sequence_code', populate.constant("PT{counter}")),
('_compute_default_locations', _compute_default_locations),
('show_operations', populate.compute(get_show_operations)),
('show_reserved', populate.compute(get_show_reserved)),
]
class Picking(models.Model):
_inherit = 'stock.picking'
_populate_sizes = {'small': 100, 'medium': 2_000, 'large': 50_000}
_populate_dependencies = ['stock.location', 'stock.picking.type', 'res.partner']
def _populate_factories(self):
company_ids = self.env.registry.populated_models['res.company'][:COMPANY_NB_WITH_STOCK]
picking_types_ids = self.env['stock.picking.type'].browse(self.env.registry.populated_models['stock.picking.type']).ids
now = datetime.now()
cross_company_locations = self.env['stock.location'].search([('company_id', '=', False)])
locations_companies = self.env['stock.location'].search([('company_id', 'in', company_ids)])
all_partners = self.env['res.partner'].browse(self.env.registry.populated_models['res.partner'])
partners_by_company = dict(groupby(all_partners, key=lambda par: par.company_id.id))
partners_inter_company = self.env['res.partner'].concat(*partners_by_company.get(False, []))
partners_by_company = {com: self.env['res.partner'].concat(*partners) | partners_inter_company for com, partners in partners_by_company.items() if com}
def get_until_date(values, counter, random):
# 95.45 % of picking scheduled between (-10, 30) days and follow a gauss distribution (only +-15% picking is late)
delta = random.gauss(10, 10)
return now + timedelta(days=delta)
def get_partner_id(values, counter, random):
picking_type = self.env['stock.picking.type'].browse(values['picking_type_id'])
company = picking_type.company_id
return partners_by_company.get(company.id) and random.choice(partners_by_company[company.id]).id or False
def get_owner_id(values, counter, random):
picking_type = self.env['stock.picking.type'].browse(values['picking_type_id'])
company = picking_type.company_id
if company.id not in partners_by_company:
return False
if random.random() < 0.10: # For 10 % of picking, force owner_id
random.choice(partners_by_company[company.id]).id
def _compute_locations(iterator, field_name, model_name):
locations_out = cross_company_locations.filtered_domain([('usage', '=', 'customer')])
locations_in = cross_company_locations.filtered_domain([('usage', '=', 'supplier')])
locations_internal = locations_companies.filtered_domain([('usage', '=', 'internal')])
locations_by_company = dict(groupby(locations_companies, key=lambda loc: loc.company_id.id))
locations_by_company = {com: self.env['stock.location'].concat(*locs) for com, locs in locations_by_company.items()}
random = populate.Random('_compute_locations')
for values in iterator:
picking_type = self.env['stock.picking.type'].browse(values['picking_type_id'])
source_loc = picking_type.default_location_src_id
dest_loc = picking_type.default_location_dest_id
locations_company = locations_by_company[picking_type.company_id.id]
if not source_loc or random.random() > 0.8:
if picking_type.code == 'incoming':
source_loc = random.choice(locations_in)
elif picking_type.code == 'outgoing':
source_loc = random.choice(locations_internal & locations_company)
elif picking_type.code == 'internal':
source_loc = random.choice(locations_internal & locations_company)
if not dest_loc or random.random() > 0.8:
if picking_type.code == 'incoming':
dest_loc = random.choice(locations_internal & locations_company)
elif picking_type.code == 'outgoing':
dest_loc = random.choice(locations_out)
elif picking_type.code == 'internal':
# Need at most 2 internal locations
dest_loc = random.choice((locations_internal & locations_company) - source_loc)
values['location_id'] = source_loc.id
values['location_dest_id'] = dest_loc.id
yield values
return [
('priority', populate.randomize(['1', '0'], [0.05, 0.95])),
('scheduled_date', populate.compute(get_until_date)),
('picking_type_id', populate.iterate(picking_types_ids)),
('partner_id', populate.compute(get_partner_id)),
('owner_id', populate.compute(get_owner_id)),
('_compute_locations', _compute_locations),
]
class StockMove(models.Model):
_inherit = 'stock.move'
_populate_sizes = {'small': 1_000, 'medium': 20_000, 'large': 1_000_000}
_populate_dependencies = ['stock.picking', 'product.product']
def _populate(self, size):
moves = super()._populate(size)
def confirm_pickings(sample_ratio):
# Confirm sample_ratio * 100 % of picking
random = populate.Random('confirm_pickings')
picking_ids = moves.picking_id.ids
picking_to_confirm = self.env['stock.picking'].browse(random.sample(picking_ids, int(len(picking_ids) * sample_ratio)))
_logger.info("Confirm %d pickings" % len(picking_to_confirm))
picking_to_confirm.action_confirm()
return picking_to_confirm
def assign_picking(pickings):
_logger.info("Assign %d pickings" % len(pickings))
pickings.action_assign()
def validate_pickings(pickings, sample_ratio):
# Fill picking and validate it
random = populate.Random('validate_pickings')
picking_ids = pickings.ids
picking_to_validate = self.env['stock.picking'].browse(random.sample(picking_ids, int(len(picking_ids) * sample_ratio)))
_logger.info("Fill %d pickings with sml" % len(picking_to_validate))
sml_values = []
lot_values = []
package_values = []
for picking in picking_to_validate:
package_for_picking = None
if random.random() < 0.20: # 20 % of chance to use package
package_for_picking = {'name': picking.name}
for move in picking.move_lines:
# For assigned moves
for move_line in move._get_move_lines():
move_line.qty_done = move_line.product_uom_qty
# Create move line for remaining qty
missing_to_do = move.product_qty - move.quantity_done
missing_to_do = move.product_uom._compute_quantity(missing_to_do, move.product_uom, rounding_method='HALF-UP')
if move.product_id.tracking == 'serial':
for i in range(int(missing_to_do)):
lot_values.append({
'name': "ValPick-%d-%d--%d" % (move.id, move.product_id.id, i),
'product_id': move.product_id.id,
'company_id': move.company_id.id
})
sml_values.append(dict(
**move._prepare_move_line_vals(),
qty_done=1,
lot_id=len(lot_values) - 1,
package_id=package_for_picking and len(package_values) - 1 or False
))
elif move.product_id.tracking == 'lot':
lot_values.append({
'name': "ValPick-%d-%d" % (move.id, move.product_id.id),
'product_id': move.product_id.id,
'company_id': move.company_id.id
})
sml_values.append(dict(
**move._prepare_move_line_vals(),
qty_done=missing_to_do,
lot_id=len(lot_values) - 1,
package_id=package_for_picking and len(package_values) - 1 or False
))
else:
sml_values.append(dict(
**move._prepare_move_line_vals(),
qty_done=missing_to_do,
package_id=package_for_picking and len(package_values) - 1 or False
))
if package_for_picking:
package_values.append(package_for_picking)
_logger.info("Create lots (%d) for pickings to validate" % len(lot_values))
lots = self.env["stock.production.lot"].create(lot_values)
_logger.info("Create packages (%d) for pickings to validate" % len(package_values))
packages = self.env["stock.quant.package"].create(package_values)
_logger.info("Create sml (%d) for pickings to validate" % len(sml_values))
for vals in sml_values:
if vals.get('package_id') is not None:
vals['package_id'] = packages[vals['package_id']].id
if 'lot_id' in vals:
vals['lot_id'] = lots[vals['lot_id']].id
self.env['stock.move.line'].create(sml_values)
_logger.info("Validate %d of pickings" % len(picking_to_validate))
picking_to_validate.with_context(skip_backorder=True, skip_sms=True).button_validate()
# (Un)comment to test a DB with a lot of outgoing/incoming/internal confirmed moves, e.g. for testing of forecasted report
# pickings = confirm_pickings(0.8)
# (Un)comment to test a DB with a lot of outgoing/incoming/internal finished moves
# assign_picking(pickings)
# validate_pickings(pickings, 1)
return moves.exists() # Confirm picking can unlink some moves
@api.model
def _populate_attach_record_weight(self):
return ['picking_id'], [1]
@api.model
def _populate_attach_record_generator(self):
picking_ids = self.env['stock.picking'].browse(self.env.registry.populated_models['stock.picking'])
def next_picking_generator():
while picking_ids:
yield from picking_ids.ids
return {'picking_id': next_picking_generator()}
def _populate_factories(self):
product_ids = self.env['product.product'].browse(self.env.registry.populated_models['product.product']).filtered(lambda p: p.type in ('product', 'consu')).ids
random_products = populate.Random("move_product_sample")
product_ids = random_products.sample(product_ids, int(len(product_ids) * 0.8))
def get_product_uom(values, counter, random):
return self.env['product.product'].browse(values['product_id']).uom_id.id
def _attach_to_record(iterator, field_name, model_name):
random = populate.Random('_attach_to_record')
fields, weights = self._populate_attach_record_weight()
fields_generator = self._populate_attach_record_generator()
for values in iterator:
field = random.choices(fields, weights)[0]
values[field] = next(fields_generator[field])
yield values
def _compute_picking_values(iterator, field_name, model_name):
random = populate.Random('_compute_picking_values')
for values in iterator:
if values.get('picking_id'):
picking = self.env['stock.picking'].browse(values['picking_id'])
values['picking_id'] = picking.id
values['location_id'] = picking.location_id.id
values['location_dest_id'] = picking.location_dest_id.id
values['name'] = picking.name
values['date'] = picking.scheduled_date
values['company_id'] = picking.company_id.id
if picking.picking_type_id.code == 'incoming':
values['price_unit'] = random.randint(1, 100)
yield values
return [
('product_id', populate.randomize(product_ids)),
('product_uom', populate.compute(get_product_uom)),
('product_uom_qty', populate.randint(1, 10)),
('sequence', populate.randint(1, 1000)),
('_attach_to_record', _attach_to_record),
('_compute_picking_values', _compute_picking_values),
]
| 49.325203
| 30,335
|
772
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
from odoo.tools import populate
class ProductProduct(models.Model):
_inherit = 'product.product'
def _populate_get_types(self):
types, types_distribution = super()._populate_get_types()
return types + ["product"], types_distribution + [3]
def _populate_factories(self):
def get_tracking(values, counter, random):
if values['type'] == 'product':
return random.choices(['none', 'lot', 'serial'], [0.7, 0.2, 0.1])[0]
else:
return 'none'
return super()._populate_factories() + [
('tracking', populate.compute(get_tracking))
]
| 30.88
| 772
|
12,151
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.mail.tests.common import mail_new_test_user
from odoo.tests.common import Form, TransactionCase
from odoo.exceptions import AccessError, UserError
class TestEditableQuant(TransactionCase):
@classmethod
def setUpClass(cls):
super(TestEditableQuant, cls).setUpClass()
# Shortcut to call `stock.quant` with `inventory mode` set in the context
cls.Quant = cls.env['stock.quant'].with_context(inventory_mode=True)
Product = cls.env['product.product']
Location = cls.env['stock.location']
cls.product = Product.create({
'name': 'Product A',
'type': 'product',
'categ_id': cls.env.ref('product.product_category_all').id,
})
cls.product2 = Product.create({
'name': 'Product B',
'type': 'product',
'categ_id': cls.env.ref('product.product_category_all').id,
})
cls.product_tracked_sn = Product.create({
'name': 'Product tracked by SN',
'type': 'product',
'tracking': 'serial',
'categ_id': cls.env.ref('product.product_category_all').id,
})
cls.warehouse = Location.create({
'name': 'Warehouse',
'usage': 'internal',
})
cls.stock = Location.create({
'name': 'Stock',
'usage': 'internal',
'location_id': cls.warehouse.id,
})
cls.room1 = Location.create({
'name': 'Room A',
'usage': 'internal',
'location_id': cls.stock.id,
})
cls.room2 = Location.create({
'name': 'Room B',
'usage': 'internal',
'location_id': cls.stock.id,
})
cls.inventory_loss = cls.product.property_stock_inventory
def test_create_quant_1(self):
""" Create a new quant who don't exist yet.
"""
# Checks we don't have any quant for this product.
quants = self.env['stock.quant'].search([('product_id', '=', self.product.id)])
self.assertEqual(len(quants), 0)
self.Quant.create({
'product_id': self.product.id,
'location_id': self.stock.id,
'inventory_quantity': 24
}).action_apply_inventory()
quants = self.env['stock.quant'].search([
('product_id', '=', self.product.id),
('quantity', '>', 0),
])
# Checks we have now a quant, and also checks the quantity is equals to
# what we set in `inventory_quantity` field.
self.assertEqual(len(quants), 1)
self.assertEqual(quants.quantity, 24)
stock_move = self.env['stock.move'].search([
('product_id', '=', self.product.id),
])
self.assertEqual(stock_move.location_id.id, self.inventory_loss.id)
self.assertEqual(stock_move.location_dest_id.id, self.stock.id)
def test_create_quant_2(self):
""" Try to create a quant who already exist.
Must update the existing quant instead of creating a new one.
"""
# Creates a quants...
first_quant = self.Quant.create({
'product_id': self.product.id,
'location_id': self.room1.id,
'quantity': 12,
})
quants = self.env['stock.quant'].search([
('product_id', '=', self.product.id),
('quantity', '>', 0),
])
self.assertEqual(len(quants), 1)
# ... then try to create an another quant for the same product/location.
second_quant = self.Quant.create({
'product_id': self.product.id,
'location_id': self.room1.id,
'inventory_quantity': 24,
})
second_quant.action_apply_inventory()
quants = self.env['stock.quant'].search([
('product_id', '=', self.product.id),
('quantity', '>', 0),
])
# Checks we still have only one quant, and first quant quantity was
# updated, and second quant had the same ID than the first quant.
self.assertEqual(len(quants), 1)
self.assertEqual(first_quant.quantity, 24)
self.assertEqual(first_quant.id, second_quant.id)
stock_move = self.env['stock.move'].search([
('product_id', '=', self.product.id),
])
self.assertEqual(len(stock_move), 1)
def test_create_quant_3(self):
""" Try to create a quant with `inventory_quantity` but without applying it.
Creates two quants:
- One with `quantity` (this one must be OK)
- One with `inventory_quantity` (this one will have null quantity)
"""
valid_quant = self.env['stock.quant'].create({
'product_id': self.product.id,
'location_id': self.room1.id,
'quantity': 10,
})
invalid_quant = self.env['stock.quant'].create({
'product_id': self.product2.id,
'location_id': self.room1.id,
'inventory_quantity': 20,
})
self.assertEqual(valid_quant.quantity, 10)
self.assertEqual(invalid_quant.quantity, 0)
def test_create_quant_4(self):
""" Try to create tree quants in inventory mode with `quantity` and/or `inventory_quantity`.
Creates two quants not in inventory mode:
- One with `quantity` (this one must be OK, but `inventory_mode` is useless here as it
doesn't enter in the inventory mode case and create quant as usual)
- One with `inventory_quantity` (this one must be OK)
- One with the two values (this one must raises an error as it enters in the inventory
mode but user can't edit directly `quantity` in inventory mode)
"""
valid_quant = self.env['stock.quant'].with_context(inventory_mode=True).create({
'product_id': self.product.id,
'location_id': self.room1.id,
'quantity': 10,
})
inventoried_quant = self.env['stock.quant'].with_context(inventory_mode=True).create({
'product_id': self.product2.id,
'location_id': self.room1.id,
'inventory_quantity': 20,
})
inventoried_quant.action_apply_inventory()
with self.assertRaises(UserError):
invalid_quant = self.env['stock.quant'].with_context(inventory_mode=True).create({
'product_id': self.product.id,
'location_id': self.room2.id,
'quantity': 10,
'inventory_quantity': 20,
})
self.assertEqual(valid_quant.quantity, 10)
self.assertEqual(inventoried_quant.quantity, 20)
def test_edit_quant_1(self):
""" Increases manually quantity of a quant.
"""
quant = self.Quant.create({
'product_id': self.product.id,
'location_id': self.room1.id,
'quantity': 12,
})
quant.inventory_quantity = 24
quant.action_apply_inventory()
self.assertEqual(quant.quantity, 24)
stock_move = self.env['stock.move'].search([
('product_id', '=', self.product.id),
])
self.assertEqual(stock_move.location_id.id, self.inventory_loss.id)
self.assertEqual(stock_move.location_dest_id.id, self.room1.id)
def test_edit_quant_2(self):
""" Decreases manually quantity of a quant.
"""
quant = self.Quant.create({
'product_id': self.product.id,
'location_id': self.room1.id,
'quantity': 12,
})
quant.inventory_quantity = 8
quant.action_apply_inventory()
self.assertEqual(quant.quantity, 8)
stock_move = self.env['stock.move'].search([
('product_id', '=', self.product.id),
])
self.assertEqual(stock_move.location_id.id, self.room1.id)
self.assertEqual(stock_move.location_dest_id.id, self.inventory_loss.id)
def test_edit_quant_3(self):
""" Try to edit a record without the inventory mode.
Must raise an error.
"""
self.demo_user = mail_new_test_user(
self.env,
name='Pauline Poivraisselle',
login='pauline',
email='p.p@example.com',
groups='base.group_user',
)
user_admin = self.env.ref('base.user_admin')
quant = self.Quant.create({
'product_id': self.product.id,
'location_id': self.room1.id,
'quantity': 12
})
self.assertEqual(quant.quantity, 12)
# Try to write on quant without permission
with self.assertRaises(AccessError):
quant.with_user(self.demo_user).write({'inventory_quantity': 8})
self.assertEqual(quant.quantity, 12)
# Try to write on quant with permission
quant.with_user(user_admin).write({'inventory_quantity': 8})
quant.action_apply_inventory()
self.assertEqual(quant.quantity, 8)
def test_edit_quant_4(self):
""" Update the quantity with the inventory report mode """
default_wh = self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1)
default_stock_location = default_wh.lot_stock_id
quant = self.Quant.create({
'product_id': self.product.id,
'location_id': default_stock_location.id,
'inventory_quantity': 100,
})
quant.action_apply_inventory()
self.assertEqual(self.product.qty_available, 100)
quant.with_context(inventory_report_mode=True).inventory_quantity_auto_apply = 75
self.assertEqual(self.product.qty_available, 75)
quant.with_context(inventory_report_mode=True).inventory_quantity_auto_apply = 75
self.assertEqual(self.product.qty_available, 75)
smls = self.env['stock.move.line'].search([('product_id', '=', self.product.id)])
self.assertRecordValues(smls, [
{'qty_done': 100},
{'qty_done': 25},
{'qty_done': 0},
])
def test_edit_quant_5(self):
""" Create a quant with inventory mode and check that the inventory adjustment reason
is used as a reference in the `stock.move` """
default_wh = self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1)
default_stock_location = default_wh.lot_stock_id
quant = self.Quant.create({
'product_id': self.product.id,
'location_id': default_stock_location.id,
'inventory_quantity': 1,
})
form_wizard = Form(self.env['stock.inventory.adjustment.name'].with_context(
default_quant_ids=quant.ids
))
form_wizard.inventory_adjustment_name = "Inventory Adjustment - Test"
form_wizard.save().action_apply()
self.assertTrue(self.env['stock.move'].search([('reference', '=', 'Inventory Adjustment - Test')], limit=1))
def test_sn_warning(self):
""" Checks that a warning is given when reusing an existing SN
in inventory mode.
"""
sn1 = self.env['stock.production.lot'].create({
'name': 'serial1',
'product_id': self.product_tracked_sn.id,
'company_id': self.env.company.id,
})
self.Quant.create({
'product_id': self.product_tracked_sn.id,
'location_id': self.room1.id,
'inventory_quantity': 1,
'lot_id': sn1.id
}).action_apply_inventory()
dupe_sn = self.Quant.create({
'product_id': self.product_tracked_sn.id,
'location_id': self.room2.id,
'inventory_quantity': 1,
'lot_id': sn1.id
})
dupe_sn.action_apply_inventory()
warning = False
warning = dupe_sn._onchange_serial_number()
self.assertTrue(warning, 'Reuse of existing serial number not detected')
self.assertEqual(list(warning.keys())[0], 'warning', 'Warning message was not returned')
| 41.050676
| 12,151
|
8,700
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests.common import TransactionCase
class TestWiseOperator(TransactionCase):
def test_wise_operator(self):
# Create a new storable product
product_wise = self.env['product.product'].create({
'name': 'Wise Unit',
'type': 'product',
'categ_id': self.ref('product.product_category_1'),
'uom_id': self.ref('uom.product_uom_unit'),
'uom_po_id': self.ref('uom.product_uom_unit'),
})
self.partner = self.env['res.partner'].create({'name': 'Deco Addict'})
warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1)
self.shelf2 = self.env['stock.location'].create({
'name': 'Shelf 2',
'barcode': 1231985,
'location_id': warehouse.lot_stock_id.id
})
self.shelf1 = self.env['stock.location'].create({
'name': 'Shelf 1',
'barcode': 1231892,
'location_id': warehouse.lot_stock_id.id
})
self.partner2 = self.env['res.partner'].create({'name': 'Ready Mat'})
# Create an incoming picking for this product of 10 PCE from suppliers to stock
vals = {
'name': 'Incoming picking (wise unit)',
'partner_id': self.partner.id,
'picking_type_id': self.ref('stock.picking_type_in'),
'location_id': self.ref('stock.stock_location_suppliers'),
'location_dest_id': self.ref('stock.stock_location_stock'),
'move_lines': [(0, 0, {
'name': '/',
'product_id': product_wise.id,
'product_uom': product_wise.uom_id.id,
'product_uom_qty': 10.00,
'location_id': self.ref('stock.stock_location_suppliers'),
'location_dest_id': self.ref('stock.stock_location_stock'),
})],
}
pick1_wise = self.env['stock.picking'].create(vals)
pick1_wise._onchange_picking_type()
pick1_wise.move_lines._onchange_product_id()
# Confirm and assign picking and prepare partial
pick1_wise.action_confirm()
pick1_wise.action_assign()
# Put 4 pieces in shelf1 and 6 pieces in shelf2
package1 = self.env['stock.quant.package'].create({'name': 'Pack 1'})
pick1_wise.move_line_ids[0].write({
'result_package_id': package1.id,
'qty_done': 4,
'location_dest_id': self.shelf1.id
})
new_pack1 = self.env['stock.move.line'].create({
'product_id': product_wise.id,
'product_uom_id': self.ref('uom.product_uom_unit'),
'picking_id': pick1_wise.id,
'qty_done': 6.0,
'location_id': self.ref('stock.stock_location_suppliers'),
'location_dest_id': self.shelf2.id
})
# Transfer the receipt
pick1_wise._action_done()
# Check the system created 3 quants
records = self.env['stock.quant'].search([('product_id', '=', product_wise.id)])
self.assertEqual(len(records.ids), 3, "The number of quants created is not correct")
# Make a delivery order of 5 pieces to the customer
vals = {
'name': 'outgoing picking 1 (wise unit)',
'partner_id': self.partner2.id,
'picking_type_id': self.ref('stock.picking_type_out'),
'location_id': self.ref('stock.stock_location_stock'),
'location_dest_id': self.ref('stock.stock_location_customers'),
'move_lines': [(0, 0, {
'name': '/',
'product_id': product_wise.id,
'product_uom': product_wise.uom_id.id,
'product_uom_qty': 5.0,
'location_id': self.ref('stock.stock_location_stock'),
'location_dest_id': self.ref('stock.stock_location_customers'),
})],
}
delivery_order_wise1 = self.env['stock.picking'].create(vals)
delivery_order_wise1._onchange_picking_type()
delivery_order_wise1.move_lines._onchange_product_id()
# Assign and confirm
delivery_order_wise1.action_confirm()
delivery_order_wise1.action_assign()
self.assertEqual(delivery_order_wise1.state, 'assigned')
# Make a delivery order of 5 pieces to the customer
vals = {
'name': 'outgoing picking 2 (wise unit)',
'partner_id': self.partner2.id,
'picking_type_id': self.ref('stock.picking_type_out'),
'location_id': self.ref('stock.stock_location_stock'),
'location_dest_id': self.ref('stock.stock_location_customers'),
'move_lines': [(0, 0, {
'name': '/',
'product_id': product_wise.id,
'product_uom': product_wise.uom_id.id,
'product_uom_qty': 5.0,
'location_id': self.ref('stock.stock_location_stock'),
'location_dest_id': self.ref('stock.stock_location_customers'),
})],
}
delivery_order_wise2 = self.env['stock.picking'].create(vals)
delivery_order_wise2._onchange_picking_type()
delivery_order_wise2.move_lines._onchange_product_id()
# Assign and confirm
delivery_order_wise2.action_confirm()
delivery_order_wise2.action_assign()
self.assertEqual(delivery_order_wise2.state, 'assigned')
# The operator is a wise guy and decides to do the opposite of what Odoo proposes.
# He uses the products reserved on picking 1 on picking 2 and vice versa
move1 = delivery_order_wise1.move_lines[0]
move2 = delivery_order_wise2.move_lines[0]
pack_ids1 = delivery_order_wise1.move_line_ids
pack_ids2 = delivery_order_wise2.move_line_ids
self.assertEqual(pack_ids1.location_id.id, self.shelf2.id)
self.assertEqual(set(pack_ids2.mapped('location_id.id')), set([
self.shelf1.id,
self.shelf2.id]))
# put the move lines from delivery_order_wise2 into delivery_order_wise1
for pack_id2 in pack_ids2:
new_pack_id1 = pack_id2.copy(default={'picking_id': delivery_order_wise1.id, 'move_id': move1.id})
new_pack_id1.qty_done = pack_id2.product_qty
new_move_lines = delivery_order_wise1.move_line_ids.filtered(lambda p: p.qty_done)
self.assertEqual(sum(new_move_lines.mapped('product_qty')), 0)
self.assertEqual(sum(new_move_lines.mapped('qty_done')), 5)
self.assertEqual(set(new_move_lines.mapped('location_id.id')), set([
self.shelf1.id,
self.shelf2.id]))
# put the move line from delivery_order_wise1 into delivery_order_wise2
new_pack_id2 = pack_ids1.copy(default={'picking_id': delivery_order_wise2.id, 'move_id': move2.id})
new_pack_id2.qty_done = pack_ids1.product_qty
new_move_lines = delivery_order_wise2.move_line_ids.filtered(lambda p: p.qty_done)
self.assertEqual(len(new_move_lines), 1)
self.assertEqual(sum(new_move_lines.mapped('product_qty')), 0)
self.assertEqual(sum(new_move_lines.mapped('qty_done')), 5)
self.assertEqual(new_move_lines.location_id.id, self.shelf2.id)
# Process this picking
delivery_order_wise1._action_done()
# Check there was no negative quant created by this picking
records = self.env['stock.quant'].search([
('product_id', '=', product_wise.id),
('quantity', '<', 0.0),
('location_id.id', '=', self.ref('stock.stock_location_stock'))])
self.assertEqual(len(records.ids), 0, 'This should not have created a negative quant')
# Check the other delivery order has changed its state back to ready
self.assertEqual(delivery_order_wise2.state, 'assigned', "Delivery order 2 should be back in ready state")
# Process the second picking
delivery_order_wise2._action_done()
# Check all quants are in Customers and there are no negative quants anymore
records = self.env['stock.quant'].search([
('product_id', '=', product_wise.id),
('location_id', '!=', self.ref('stock.stock_location_suppliers'))])
self.assertTrue(all([x.location_id.id == self.ref('stock.stock_location_customers') and x.quantity > 0.0 or
x.location_id.id != self.ref('stock.stock_location_customers') and x.quantity == 0.0 for x in records]),
"Negative quant or wrong location detected")
| 45.789474
| 8,700
|
604
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import odoo
from odoo.tests import Form, HttpCase, tagged
@tagged('-at_install', 'post_install')
class TestStockReportTour(HttpCase):
def setUp(self):
super().setUp()
def _get_report_url(self):
return '/web#&model=product.template&action=stock.product_template_action_product'
def test_stock_route_diagram_report(self):
""" Open the route diagram report."""
url = self._get_report_url()
self.start_tour(url, 'test_stock_route_diagram_report', login='admin', timeout=180)
| 31.789474
| 604
|
9,728
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.exceptions import UserError, ValidationError
from odoo.tests.common import TransactionCase
class TestRobustness(TransactionCase):
@classmethod
def setUpClass(cls):
super(TestRobustness, cls).setUpClass()
cls.stock_location = cls.env.ref('stock.stock_location_stock')
cls.customer_location = cls.env.ref('stock.stock_location_customers')
cls.uom_unit = cls.env.ref('uom.product_uom_unit')
cls.uom_dozen = cls.env.ref('uom.product_uom_dozen')
cls.product1 = cls.env['product.product'].create({
'name': 'Product A',
'type': 'product',
'categ_id': cls.env.ref('product.product_category_all').id,
})
def test_uom_factor(self):
""" Changing the factor of a unit of measure shouldn't be allowed while
quantities are reserved, else the existing move lines won't be consistent
with the `reserved_quantity` on quants.
"""
# make some stock
self.env['stock.quant']._update_available_quantity(
self.product1,
self.stock_location,
12,
)
# reserve a dozen
move1 = self.env['stock.move'].create({
'name': 'test_uom_rounding',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_dozen.id,
'product_uom_qty': 1,
})
move1._action_confirm()
move1._action_assign()
self.assertEqual(move1.state, 'assigned')
quant = self.env['stock.quant']._gather(
self.product1,
self.stock_location,
)
# assert the reservation
self.assertEqual(quant.reserved_quantity, 12)
self.assertEqual(move1.product_qty, 12)
# change the factor
with self.assertRaises(UserError):
with self.cr.savepoint():
move1.product_uom.factor = 0.05
# assert the reservation
self.assertEqual(quant.reserved_quantity, 12)
self.assertEqual(move1.state, 'assigned')
self.assertEqual(move1.product_qty, 12)
# unreserve
move1._do_unreserve()
def test_location_usage(self):
""" Changing the usage of a location shouldn't be allowed while
quantities are reserved, else the existing move lines won't be
consistent with the `reserved_quantity` on the quants.
"""
# change stock usage
test_stock_location = self.env['stock.location'].create({
'name': "Test Location",
'location_id': self.stock_location.id,
})
test_stock_location.scrap_location = True
# make some stock
self.env['stock.quant']._update_available_quantity(
self.product1,
test_stock_location,
1,
)
# reserve a unit
move1 = self.env['stock.move'].create({
'name': 'test_location_archive',
'location_id': test_stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1,
})
move1._action_confirm()
move1._action_assign()
self.assertEqual(move1.state, 'assigned')
quant = self.env['stock.quant']._gather(
self.product1,
test_stock_location,
)
# assert the reservation
self.assertEqual(quant.reserved_quantity, 0) # reservation is bypassed in scrap location
self.assertEqual(move1.product_qty, 1)
# change the stock usage
with self.assertRaises(UserError):
with self.cr.savepoint():
test_stock_location.scrap_location = False
# unreserve
move1._do_unreserve()
def test_package_unpack(self):
""" Unpack a package that contains quants with a reservation
should also remove the package on the reserved move lines.
"""
package = self.env['stock.quant.package'].create({
'name': 'Shell Helix HX7 10W30',
})
self.env['stock.quant']._update_available_quantity(
self.product1,
self.stock_location,
10,
package_id=package
)
# reserve a dozen
move1 = self.env['stock.move'].create({
'name': 'test_uom_rounding',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10,
})
move1._action_confirm()
move1._action_assign()
self.assertEqual(move1.move_line_ids.package_id, package)
package.unpack()
self.assertEqual(move1.move_line_ids.package_id, self.env['stock.quant.package'])
# unreserve
move1._do_unreserve()
self.assertEqual(len(self.env['stock.quant']._gather(self.product1, self.stock_location)), 1)
self.assertEqual(len(self.env['stock.quant']._gather(self.product1, self.stock_location, package_id=package)), 0)
self.assertEqual(self.env['stock.quant']._gather(self.product1, self.stock_location).reserved_quantity, 0)
def test_lot_id_product_id_mix(self):
""" Make sure it isn't possible to create a move line with a lot incompatible with its
product.
"""
product1 = self.env['product.product'].create({
'name': 'Product 1',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
'tracking': 'lot',
})
product2 = self.env['product.product'].create({
'name': 'Product 2',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
'tracking': 'lot',
})
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': product1.id,
'company_id': self.env.company.id,
})
lot2 = self.env['stock.production.lot'].create({
'name': 'lot2',
'product_id': product2.id,
'company_id': self.env.company.id,
})
self.env['stock.quant']._update_available_quantity(product1, self.stock_location, 1, lot_id=lot1)
self.env['stock.quant']._update_available_quantity(product2, self.stock_location, 1, lot_id=lot2)
move1 = self.env['stock.move'].create({
'name': 'test_lot_id_product_id_mix_move_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move2 = self.env['stock.move'].create({
'name': 'test_lot_id_product_id_mix_move_2',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': product2.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
(move1 + move2)._action_confirm()
with self.assertRaises(ValidationError):
move1.write({'move_line_ids': [(0, 0, {
'product_id': product1.id,
'product_uom_id': self.uom_unit.id,
'qty_done': 1,
'lot_id': lot2.id,
'location_id': move1.location_id.id,
'location_dest_id': move1.location_dest_id.id,
})]})
with self.assertRaises(ValidationError):
move2.write({'move_line_ids': [(0, 0, {
'product_id': product2.id,
'product_uom_id': self.uom_unit.id,
'qty_done': 1,
'lot_id': lot1.id,
'location_id': move2.location_id.id,
'location_dest_id': move2.location_dest_id.id,
})]})
def test_lot_quantity_remains_unchanged_after_done(self):
""" Make sure the method _set_lot_ids does not change the quantities of lots to 1 once they are done.
"""
productA = self.env['product.product'].create({
'name': 'ProductA',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
'tracking': 'lot',
})
lotA = self.env['stock.production.lot'].create({
'name': 'lotA',
'product_id': productA.id,
'company_id': self.env.company.id,
})
self.env['stock.quant']._update_available_quantity(productA, self.stock_location, 5, lot_id=lotA)
moveA = self.env['stock.move'].create({
'name': 'TEST_A',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': productA.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 5.0,
})
moveA._action_confirm()
moveA.write({'move_line_ids': [(0, 0, {
'product_id': productA.id,
'product_uom_id': self.uom_unit.id,
'qty_done': 5,
'lot_id': lotA.id,
'location_id': moveA.location_id.id,
'location_dest_id': moveA.location_dest_id.id,
})]})
moveA._action_done()
moveA._set_lot_ids()
self.assertEqual(moveA.quantity_done, 5)
| 37.272031
| 9,728
|
24,607
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import date, datetime, timedelta
from dateutil.relativedelta import relativedelta
from odoo.exceptions import ValidationError
from odoo.tests.common import Form, TransactionCase
class TestInventory(TransactionCase):
@classmethod
def setUpClass(cls):
super(TestInventory, cls).setUpClass()
cls.stock_location = cls.env.ref('stock.stock_location_stock')
cls.pack_location = cls.env.ref('stock.location_pack_zone')
cls.pack_location.active = True
cls.customer_location = cls.env.ref('stock.stock_location_customers')
cls.uom_unit = cls.env.ref('uom.product_uom_unit')
cls.product1 = cls.env['product.product'].create({
'name': 'Product A',
'type': 'product',
'categ_id': cls.env.ref('product.product_category_all').id,
})
cls.product2 = cls.env['product.product'].create({
'name': 'Product A',
'type': 'product',
'tracking': 'serial',
'categ_id': cls.env.ref('product.product_category_all').id,
})
def test_inventory_1(self):
""" Check that making an inventory adjustment to remove all products from stock is working
as expected.
"""
# make some stock
self.env['stock.quant']._update_available_quantity(self.product1, self.stock_location, 100)
self.assertEqual(len(self.env['stock.quant']._gather(self.product1, self.stock_location)), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product1, self.stock_location), 100.0)
# remove them with an inventory adjustment
inventory_quant = self.env['stock.quant'].search([
('location_id', '=', self.stock_location.id),
('product_id', '=', self.product1.id),
])
self.assertEqual(len(inventory_quant), 1)
self.assertEqual(inventory_quant.quantity, 100)
self.assertEqual(inventory_quant.inventory_quantity, 0)
inventory_quant.action_apply_inventory()
# check
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product1, self.stock_location), 0.0)
self.assertEqual(sum(self.env['stock.quant']._gather(self.product1, self.stock_location).mapped('quantity')), 0.0)
def test_inventory_2(self):
""" Check that adding a tracked product through an inventory adjustment works as expected.
"""
inventory_quant = self.env['stock.quant'].search([
('location_id', '=', self.stock_location.id),
('product_id', '=', self.product2.id)
])
self.assertEqual(len(inventory_quant), 0)
lot1 = self.env['stock.production.lot'].create({
'name': 'sn2',
'product_id': self.product2.id,
'company_id': self.env.company.id,
})
inventory_quant = self.env['stock.quant'].create({
'location_id': self.stock_location.id,
'product_id': self.product2.id,
'lot_id': lot1.id,
'inventory_quantity': 1
})
self.assertEqual(inventory_quant.quantity, 0)
self.assertEqual(inventory_quant.inventory_diff_quantity, 1)
inventory_quant.action_apply_inventory()
# check
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product2, self.stock_location, lot_id=lot1), 1.0)
self.assertEqual(len(self.env['stock.quant']._gather(self.product2, self.stock_location, lot_id=lot1)), 1.0)
self.assertEqual(lot1.product_qty, 1.0)
def test_inventory_3(self):
""" Check that it's not possible to have multiple products with the same serial number through an
inventory adjustment
"""
inventory_quant = self.env['stock.quant'].search([
('location_id', '=', self.stock_location.id),
('product_id', '=', self.product2.id)
])
self.assertEqual(len(inventory_quant), 0)
lot1 = self.env['stock.production.lot'].create({
'name': 'sn2',
'product_id': self.product2.id,
'company_id': self.env.company.id,
})
inventory_quant = self.env['stock.quant'].create({
'location_id': self.stock_location.id,
'product_id': self.product2.id,
'lot_id': lot1.id,
'inventory_quantity': 2
})
self.assertEqual(len(inventory_quant), 1)
self.assertEqual(inventory_quant.quantity, 0)
with self.assertRaises(ValidationError):
inventory_quant.action_apply_inventory()
def test_inventory_4(self):
""" Check that even if a product is tracked by serial number, it's possible to add an
untracked one in an inventory adjustment.
"""
quant_domain = [
('location_id', '=', self.stock_location.id),
('product_id', '=', self.product2.id)
]
inventory_quants = self.env['stock.quant'].search(quant_domain)
self.assertEqual(len(inventory_quants), 0)
lot1 = self.env['stock.production.lot'].create({
'name': 'sn2',
'product_id': self.product2.id,
'company_id': self.env.company.id,
})
self.env['stock.quant'].create({
'location_id': self.stock_location.id,
'product_id': self.product2.id,
'lot_id': lot1.id,
'inventory_quantity': 1
})
inventory_quants = self.env['stock.quant'].search(quant_domain)
self.assertEqual(len(inventory_quants), 1)
self.assertEqual(inventory_quants.quantity, 0)
self.env['stock.quant'].create({
'location_id': self.stock_location.id,
'product_id': self.product2.id,
'inventory_quantity': 10
})
inventory_quants = self.env['stock.quant'].search(quant_domain)
self.assertEqual(len(inventory_quants), 2)
stock_confirmation_action = inventory_quants.action_apply_inventory()
stock_confirmation_wizard_form = Form(
self.env['stock.track.confirmation'].with_context(
**stock_confirmation_action['context'])
)
stock_confirmation_wizard = stock_confirmation_wizard_form.save()
stock_confirmation_wizard.action_confirm()
# check
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product2, self.stock_location, lot_id=lot1, strict=True), 11.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product2, self.stock_location, strict=True), 10.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product2, self.stock_location), 11.0)
self.assertEqual(len(self.env['stock.quant']._gather(self.product2, self.stock_location, lot_id=lot1, strict=True).filtered(lambda q: q.lot_id)), 1.0)
self.assertEqual(len(self.env['stock.quant']._gather(self.product2, self.stock_location, strict=True)), 1.0)
self.assertEqual(len(self.env['stock.quant']._gather(self.product2, self.stock_location)), 2.0)
def test_inventory_5(self):
""" Check that assigning an owner works.
"""
owner1 = self.env['res.partner'].create({'name': 'test_inventory_5'})
inventory_quant = self.env['stock.quant'].create({
'location_id': self.stock_location.id,
'product_id': self.product1.id,
'inventory_quantity': 5,
'owner_id': owner1.id,
})
self.assertEqual(inventory_quant.quantity, 0)
inventory_quant.action_apply_inventory()
quant = self.env['stock.quant']._gather(self.product1, self.stock_location)
self.assertEqual(len(quant), 1)
self.assertEqual(quant.quantity, 5)
self.assertEqual(quant.owner_id.id, owner1.id)
def test_inventory_6(self):
""" Test that for chained moves, making an inventory adjustment to reduce a quantity that
has been reserved correctly frees the reservation. After that, add products to stock and check
that they're used if the user encodes more than what's available through the chain
"""
# add 10 products to stock
inventory_quant = self.env['stock.quant'].create({
'location_id': self.stock_location.id,
'product_id': self.product1.id,
'inventory_quantity': 10,
})
inventory_quant.action_apply_inventory()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product1, self.stock_location), 10.0)
# Make a chain of two moves, validate the first and check that 10 products are reserved
# in the second one.
move_stock_pack = self.env['stock.move'].create({
'name': 'test_link_2_1',
'location_id': self.stock_location.id,
'location_dest_id': self.pack_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
})
move_pack_cust = self.env['stock.move'].create({
'name': 'test_link_2_2',
'location_id': self.pack_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
})
move_stock_pack.write({'move_dest_ids': [(4, move_pack_cust.id, 0)]})
move_pack_cust.write({'move_orig_ids': [(4, move_stock_pack.id, 0)]})
(move_stock_pack + move_pack_cust)._action_confirm()
move_stock_pack._action_assign()
self.assertEqual(move_stock_pack.state, 'assigned')
move_stock_pack.move_line_ids.qty_done = 10
move_stock_pack._action_done()
self.assertEqual(move_stock_pack.state, 'done')
self.assertEqual(move_pack_cust.state, 'assigned')
self.assertEqual(self.env['stock.quant']._gather(self.product1, self.pack_location).quantity, 10.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product1, self.pack_location), 0.0)
# Make an inventory adjustment and remove two products from the pack location. This should
# free the reservation of the second move.
inventory_quant = self.env['stock.quant'].search([
('location_id', '=', self.pack_location.id),
('product_id', '=', self.product1.id)
])
inventory_quant.inventory_quantity = 8
inventory_quant.action_apply_inventory()
self.assertEqual(self.env['stock.quant']._gather(self.product1, self.pack_location).quantity, 8.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product1, self.pack_location), 0)
self.assertEqual(move_pack_cust.state, 'partially_available')
self.assertEqual(move_pack_cust.reserved_availability, 8)
# If the user tries to assign again, only 8 products are available and thus the reservation
# state should not change.
move_pack_cust._action_assign()
self.assertEqual(move_pack_cust.state, 'partially_available')
self.assertEqual(move_pack_cust.reserved_availability, 8)
# Make a new inventory adjustment and add two new products.
inventory_quant = self.env['stock.quant'].search([
('location_id', '=', self.pack_location.id),
('product_id', '=', self.product1.id)
])
inventory_quant.inventory_quantity = 10
inventory_quant.action_apply_inventory()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product1, self.pack_location), 2)
# Nothing should have changed for our pack move
self.assertEqual(move_pack_cust.state, 'partially_available')
self.assertEqual(move_pack_cust.reserved_availability, 8)
# Running _action_assign will now find the new available quantity. Since the products
# are not differentiated (no lot/pack/owner), even if the new available quantity is not directly
# brought by the chain, the system will take them into account.
move_pack_cust._action_assign()
self.assertEqual(move_pack_cust.state, 'assigned')
# move all the things
move_pack_cust.move_line_ids.qty_done = 10
move_stock_pack._action_done()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product1, self.pack_location), 0)
def test_inventory_7(self):
""" Check that duplicated quants create a single inventory line.
"""
owner1 = self.env['res.partner'].create({'name': 'test_inventory_7'})
vals = {
'product_id': self.product1.id,
'product_uom_id': self.uom_unit.id,
'owner_id': owner1.id,
'location_id': self.stock_location.id,
'quantity': 1,
}
self.env['stock.quant'].create(vals)
self.env['stock.quant'].create(dict(**vals, inventory_quantity=1))
self.assertEqual(len(self.env['stock.quant']._gather(self.product1, self.stock_location)), 2.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product1, self.stock_location), 2.0)
self.env['stock.quant']._quant_tasks()
inventory_quant = self.env['stock.quant'].search([
('location_id', '=', self.stock_location.id),
('product_id', '=', self.product1.id)
])
self.assertEqual(len(inventory_quant), 1)
self.assertEqual(inventory_quant.inventory_quantity, 1)
self.assertEqual(inventory_quant.quantity, 2)
def test_inventory_counted_quantity(self):
""" Checks that inventory quants have a `inventory quantity` set to zero
after an adjustment.
"""
# Set product quantity to 42.
inventory_quant = self.env['stock.quant'].create(vals={
'product_id': self.product1.id,
'location_id': self.stock_location.id,
'inventory_quantity': 42,
})
# Applies the change, the quant must have a quantity of 42 and a inventory quantity to 0.
inventory_quant.action_apply_inventory()
self.assertEqual(len(inventory_quant), 1)
self.assertEqual(inventory_quant.inventory_quantity, 0)
self.assertEqual(inventory_quant.quantity, 42)
# Checks we can write on `inventory_quantity_set` even if we write on
# `inventory_quantity` at the same time.
self.assertEqual(inventory_quant.inventory_quantity_set, False)
inventory_quant.write({'inventory_quantity': 5})
self.assertEqual(inventory_quant.inventory_quantity_set, True)
inventory_quant.write({
'inventory_quantity': 12,
'inventory_quantity_set': False,
})
self.assertEqual(inventory_quant.inventory_quantity_set, False)
def test_inventory_outdate_1(self):
""" Checks that applying an inventory adjustment that is outdated due to
its corresponding quant being modified after its inventory quantity is set
opens a wizard. The wizard should warn about the conflict and its value should be
corrected after user confirms the inventory quantity.
"""
# Set initial quantity to 7
self.env['stock.quant']._update_available_quantity(self.product1, self.stock_location, 7)
inventory_quant = self.env['stock.quant'].search([
('location_id', '=', self.stock_location.id),
('product_id', '=', self.product1.id)
])
# When a quant is created, it must not be marked as outdated
# and its `inventory_quantity` must be equal to zero.
self.assertEqual(inventory_quant.inventory_quantity, 0)
inventory_quant.inventory_quantity = 5
self.assertEqual(inventory_quant.inventory_diff_quantity, -2)
# Deliver 3 units
move_out = self.env['stock.move'].create({
'name': 'Outgoing move of 3 units',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 3.0,
})
move_out._action_confirm()
move_out._action_assign()
move_out.move_line_ids.qty_done = 3
move_out._action_done()
# Ensure that diff didn't change.
self.assertEqual(inventory_quant.inventory_diff_quantity, -2)
self.assertEqual(inventory_quant.inventory_quantity, 5)
self.assertEqual(inventory_quant.quantity, 4)
conflict_wizard_values = inventory_quant.action_apply_inventory()
conflict_wizard_form = Form(self.env['stock.inventory.conflict'].with_context(conflict_wizard_values['context']))
conflict_wizard = conflict_wizard_form.save()
conflict_wizard.quant_to_fix_ids.inventory_quantity = 5
conflict_wizard.action_keep_counted_quantity()
self.assertEqual(inventory_quant.inventory_diff_quantity, 0)
self.assertEqual(inventory_quant.inventory_quantity, 0)
self.assertEqual(inventory_quant.quantity, 5)
def test_inventory_outdate_2(self):
""" Checks that an outdated inventory adjustment auto-corrects when
changing its inventory quantity after its corresponding quant has been modified.
"""
# Set initial quantity to 7
vals = {
'product_id': self.product1.id,
'product_uom_id': self.uom_unit.id,
'location_id': self.stock_location.id,
'quantity': 7,
'inventory_quantity': 7
}
quant = self.env['stock.quant'].create(vals)
# Decrease quant to 3 and inventory line is now outdated
move_out = self.env['stock.move'].create({
'name': 'Outgoing move of 3 units',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 4.0,
})
move_out._action_confirm()
move_out._action_assign()
move_out.move_line_ids.qty_done = 4
move_out._action_done()
self.assertEqual(quant.inventory_quantity, 7)
self.assertEqual(quant.inventory_diff_quantity, 0)
# Refresh inventory line and quantity will recompute to 3
quant.inventory_quantity = 3
self.assertEqual(quant.inventory_quantity, 3)
self.assertEqual(quant.inventory_diff_quantity, 0)
def test_inventory_outdate_3(self):
""" Checks that an inventory adjustment line without a difference
doesn't change quant when validated.
"""
# Set initial quantity to 10
vals = {
'product_id': self.product1.id,
'product_uom_id': self.uom_unit.id,
'location_id': self.stock_location.id,
'quantity': 10,
}
quant = self.env['stock.quant'].create(vals)
quant.inventory_quantity = 10
quant.action_apply_inventory()
self.assertEqual(quant.quantity, 10)
self.assertEqual(quant.inventory_quantity, 0)
def test_inventory_dont_outdate_1(self):
""" Checks that inventory adjustment line isn't marked as outdated when
a non-corresponding quant is created.
"""
# Set initial quantity to 7 and create inventory adjustment for product1
inventory_quant = self.env['stock.quant'].create({
'product_id': self.product1.id,
'product_uom_id': self.uom_unit.id,
'location_id': self.stock_location.id,
'quantity': 7,
'inventory_quantity': 5
})
# Create quant for product3
product3 = self.env['product.product'].create({
'name': 'Product C',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
})
self.env['stock.quant'].create({
'product_id': product3.id,
'product_uom_id': self.uom_unit.id,
'location_id': self.stock_location.id,
'inventory_quantity': 22,
'reserved_quantity': 0,
})
inventory_quant.action_apply_inventory()
# Expect action apply do not return a wizard
self.assertEqual(inventory_quant.quantity, 5)
def test_cyclic_inventory(self):
""" Check that locations with and without cyclic inventory set has its inventory
dates auto-generate and apply relevant dates.
"""
grp_multi_loc = self.env.ref('stock.group_stock_multi_locations')
self.env.user.write({'groups_id': [(4, grp_multi_loc.id)]})
now = datetime.now()
today = now.date()
new_loc = self.env['stock.location'].create({
'name': 'New Cyclic Inv Location',
'usage': 'internal',
'location_id': self.stock_location.id,
})
existing_loc2 = self.env['stock.location'].create({
'name': 'Pre-existing Cyclic Inv Location',
'usage': 'internal',
'location_id': self.stock_location.id,
'last_inventory_date': now - timedelta(days=5),
})
no_cyclic_loc = self.env['stock.location'].create({
'name': 'No Cyclic Inv Location',
'usage': 'internal',
'location_id': self.stock_location.id,
})
no_cyclic_loc.company_id.write({'annual_inventory_day': str(today.day), 'annual_inventory_month': str(today.month)})
new_loc_form = Form(new_loc)
new_loc_form.cyclic_inventory_frequency = 2
new_loc = new_loc_form.save()
# check next_inventory_date is correctly calculated
existing_loc2_form = Form(existing_loc2)
existing_loc2_form.cyclic_inventory_frequency = 2
existing_loc2 = existing_loc2_form.save()
# next_inventory_date = today + cyclic_inventory_frequency
self.assertEqual(new_loc.next_inventory_date, today + timedelta(days=2))
# previous inventory done + cyclic_inventory_frequency < today => next_inventory_date = tomorrow
self.assertEqual(existing_loc2.next_inventory_date, today + timedelta(days=1))
# check that cyclic inventories are correctly autogenerated
self.env['stock.quant']._update_available_quantity(self.product1, new_loc, 5)
self.env['stock.quant']._update_available_quantity(self.product1, existing_loc2, 5)
self.env['stock.quant']._update_available_quantity(self.product1, no_cyclic_loc, 5)
# cyclic inventory locations should auto-assign their next inventory date to their quants
quant_new_loc = self.env['stock.quant'].search([('location_id', '=', new_loc.id)])
quant_existing_loc = self.env['stock.quant'].search([('location_id', '=', existing_loc2.id)])
self.assertEqual(quant_new_loc.inventory_date, new_loc.next_inventory_date)
self.assertEqual(quant_existing_loc.inventory_date, existing_loc2.next_inventory_date)
# quant without a cyclic inventory location should default to the company's annual inventory date
quant_non_cyclic_loc = self.env['stock.quant'].search([('location_id', '=', no_cyclic_loc.id)])
self.assertEqual(quant_non_cyclic_loc.inventory_date.month, int(no_cyclic_loc.company_id.annual_inventory_month))
self.assertEqual(quant_non_cyclic_loc.inventory_date.day, no_cyclic_loc.company_id.annual_inventory_day)
quant_new_loc.inventory_quantity = 10
(quant_new_loc | quant_existing_loc | quant_non_cyclic_loc).action_apply_inventory()
# check location's last inventory dates + their quants next inventory dates
self.assertEqual(new_loc.last_inventory_date, date.today())
self.assertEqual(existing_loc2.last_inventory_date, date.today())
self.assertEqual(no_cyclic_loc.last_inventory_date, date.today())
self.assertEqual(new_loc.next_inventory_date, date.today() + timedelta(days=2))
self.assertEqual(existing_loc2.next_inventory_date, date.today() + timedelta(days=2))
self.assertEqual(quant_new_loc.inventory_date, date.today() + timedelta(days=2))
self.assertEqual(quant_existing_loc.inventory_date, date.today() + timedelta(days=2))
self.assertEqual(quant_non_cyclic_loc.inventory_date, date.today() + relativedelta(years=1))
| 47.230326
| 24,607
|
41,457
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from contextlib import closing
from datetime import datetime, timedelta
from unittest.mock import patch
from odoo import fields
from odoo.addons.mail.tests.common import mail_new_test_user
from odoo.exceptions import ValidationError
from odoo.tests.common import TransactionCase
from odoo.exceptions import AccessError, UserError
class StockQuant(TransactionCase):
@classmethod
def setUpClass(cls):
super(StockQuant, cls).setUpClass()
cls.demo_user = mail_new_test_user(
cls.env,
name='Pauline Poivraisselle',
login='pauline',
email='p.p@example.com',
notification_type='inbox',
groups='base.group_user',
)
cls.stock_user = mail_new_test_user(
cls.env,
name='Pauline Poivraisselle',
login='pauline2',
email='p.p@example.com',
notification_type='inbox',
groups='stock.group_stock_user',
)
cls.product = cls.env['product.product'].create({
'name': 'Product A',
'type': 'product',
})
cls.product_lot = cls.env['product.product'].create({
'name': 'Product A',
'type': 'product',
'tracking': 'lot',
})
cls.product_consu = cls.env['product.product'].create({
'name': 'Product A',
'type': 'consu',
})
cls.product_serial = cls.env['product.product'].create({
'name': 'Product A',
'type': 'product',
'tracking': 'serial',
})
cls.stock_location = cls.env['stock.location'].create({
'name': 'stock_location',
'usage': 'internal',
})
cls.stock_subloc3 = cls.env['stock.location'].create({
'name': 'subloc3',
'usage': 'internal',
'location_id': cls.stock_location.id
})
cls.stock_subloc2 = cls.env['stock.location'].create({
'name': 'subloc2',
'usage': 'internal',
'location_id': cls.stock_location.id,
})
def gather_relevant(self, product_id, location_id, lot_id=None, package_id=None, owner_id=None, strict=False):
quants = self.env['stock.quant']._gather(product_id, location_id, lot_id=lot_id, package_id=package_id, owner_id=owner_id, strict=strict)
return quants.filtered(lambda q: not (q.quantity == 0 and q.reserved_quantity == 0))
def test_get_available_quantity_1(self):
""" Quantity availability with only one quant in a location.
"""
self.env['stock.quant'].create({
'product_id': self.product.id,
'location_id': self.stock_location.id,
'quantity': 1.0,
})
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 1.0)
def test_get_available_quantity_2(self):
""" Quantity availability with multiple quants in a location.
"""
for i in range(3):
self.env['stock.quant'].create({
'product_id': self.product.id,
'location_id': self.stock_location.id,
'quantity': 1.0,
})
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 3.0)
def test_get_available_quantity_3(self):
""" Quantity availability with multiple quants (including negatives ones) in a location.
"""
for i in range(3):
self.env['stock.quant'].create({
'product_id': self.product.id,
'location_id': self.stock_location.id,
'quantity': 1.0,
})
self.env['stock.quant'].create({
'product_id': self.product.id,
'location_id': self.stock_location.id,
'quantity': -3.0,
})
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0.0)
def test_get_available_quantity_4(self):
""" Quantity availability with no quants in a location.
"""
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0.0)
def test_get_available_quantity_5(self):
""" Quantity availability with multiple partially reserved quants in a location.
"""
self.env['stock.quant'].create({
'product_id': self.product.id,
'location_id': self.stock_location.id,
'quantity': 10.0,
'reserved_quantity': 9.0,
})
self.env['stock.quant'].create({
'product_id': self.product.id,
'location_id': self.stock_location.id,
'quantity': 1.0,
'reserved_quantity': 1.0,
})
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 1.0)
def test_get_available_quantity_6(self):
""" Quantity availability with multiple partially reserved quants in a location.
"""
self.env['stock.quant'].create({
'product_id': self.product.id,
'location_id': self.stock_location.id,
'quantity': 10.0,
'reserved_quantity': 20.0,
})
self.env['stock.quant'].create({
'product_id': self.product.id,
'location_id': self.stock_location.id,
'quantity': 5.0,
'reserved_quantity': 0.0,
})
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, allow_negative=True), -5.0)
def test_get_available_quantity_7(self):
""" Quantity availability with only one tracked quant in a location.
"""
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.product_lot.id,
'company_id': self.env.company.id,
})
self.env['stock.quant'].create({
'product_id': self.product_lot.id,
'location_id': self.stock_location.id,
'quantity': 10.0,
'reserved_quantity': 20.0,
'lot_id': lot1.id,
})
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_lot, self.stock_location, lot_id=lot1), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_lot, self.stock_location, lot_id=lot1, allow_negative=True), -10.0)
def test_get_available_quantity_8(self):
""" Quantity availability with a consumable product.
"""
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_consu, self.stock_location), 0.0)
self.assertEqual(len(self.gather_relevant(self.product_consu, self.stock_location)), 0)
with self.assertRaises(ValidationError):
self.env['stock.quant']._update_available_quantity(self.product_consu, self.stock_location, 1.0)
def test_get_available_quantity_9(self):
""" Quantity availability by a demo user with access rights/rules.
"""
self.env['stock.quant'].create({
'product_id': self.product.id,
'location_id': self.stock_location.id,
'quantity': 1.0,
})
self.env = self.env(user=self.demo_user)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 1.0)
def test_increase_available_quantity_1(self):
""" Increase the available quantity when no quants are already in a location.
"""
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 1.0)
def test_increase_available_quantity_2(self):
""" Increase the available quantity when multiple quants are already in a location.
"""
for i in range(2):
self.env['stock.quant'].create({
'product_id': self.product.id,
'location_id': self.stock_location.id,
'quantity': 1.0,
})
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 2.0)
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 3.0)
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location)), 2)
def test_increase_available_quantity_3(self):
""" Increase the available quantity when a concurrent transaction is already increasing
the reserved quanntity for the same product.
"""
quant = self.env['stock.quant'].search([('location_id', '=', self.stock_location.id)], limit=1)
if not quant:
self.skipTest('Cannot test concurrent transactions without demo data.')
product = quant.product_id
available_quantity = self.env['stock.quant']._get_available_quantity(product, self.stock_location, allow_negative=True)
# opens a new cursor and SELECT FOR UPDATE the quant, to simulate another concurrent reserved
# quantity increase
with closing(self.registry.cursor()) as cr:
cr.execute("SELECT id FROM stock_quant WHERE product_id=%s AND location_id=%s", (product.id, self.stock_location.id))
quant_id = cr.fetchone()
cr.execute("SELECT 1 FROM stock_quant WHERE id=%s FOR UPDATE", quant_id)
self.env['stock.quant']._update_available_quantity(product, self.stock_location, 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(product, self.stock_location, allow_negative=True), available_quantity + 1)
self.assertEqual(len(self.gather_relevant(product, self.stock_location, strict=True)), 2)
def test_increase_available_quantity_4(self):
""" Increase the available quantity when no quants are already in a location with a user without access right.
"""
self.env = self.env(user=self.demo_user)
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1.0)
def test_increase_available_quantity_5(self):
""" Increase the available quantity when no quants are already in stock.
Increase a subLocation and check that quants are in this location. Also test inverse.
"""
stock_sub_location = self.stock_location.child_ids[0]
product2 = self.env['product.product'].create({
'name': 'Product B',
'type': 'product',
})
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1.0)
self.env['stock.quant']._update_available_quantity(self.product, stock_sub_location, 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 2.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, stock_sub_location), 1.0)
self.env['stock.quant']._update_available_quantity(product2, stock_sub_location, 1.0)
self.env['stock.quant']._update_available_quantity(product2, self.stock_location, 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(product2, self.stock_location), 2.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(product2, stock_sub_location), 1.0)
def test_increase_available_quantity_6(self):
""" Increasing the available quantity in a view location should be forbidden.
"""
location1 = self.env['stock.location'].create({
'name': 'viewloc1',
'usage': 'view',
'location_id': self.stock_location.id,
})
with self.assertRaises(ValidationError):
self.env['stock.quant']._update_available_quantity(self.product, location1, 1.0)
def test_increase_available_quantity_7(self):
""" Setting a location's usage as "view" should be forbidden if it already
contains quant.
"""
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1.0)
self.assertTrue(len(self.stock_location.quant_ids.ids) > 0)
with self.assertRaises(UserError):
self.stock_location.usage = 'view'
def test_decrease_available_quantity_1(self):
""" Decrease the available quantity when no quants are already in a location.
"""
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, -1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, allow_negative=True), -1.0)
def test_decrease_available_quantity_2(self):
""" Decrease the available quantity when multiple quants are already in a location.
"""
for i in range(2):
self.env['stock.quant'].create({
'product_id': self.product.id,
'location_id': self.stock_location.id,
'quantity': 1.0,
})
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 2.0)
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location)), 2)
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, -1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 1.0)
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location)), 1)
def test_decrease_available_quantity_3(self):
""" Decrease the available quantity when a concurrent transaction is already increasing
the reserved quanntity for the same product.
"""
quant = self.env['stock.quant'].search([('location_id', '=', self.stock_location.id)], limit=1)
if not quant:
self.skipTest('Cannot test concurrent transactions without demo data.')
product = quant.product_id
available_quantity = self.env['stock.quant']._get_available_quantity(product, self.stock_location, allow_negative=True)
# opens a new cursor and SELECT FOR UPDATE the quant, to simulate another concurrent reserved
# quantity increase
with closing(self.registry.cursor()) as cr:
cr.execute("SELECT 1 FROM stock_quant WHERE id = %s FOR UPDATE", quant.ids)
self.env['stock.quant']._update_available_quantity(product, self.stock_location, -1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(product, self.stock_location, allow_negative=True), available_quantity - 1)
self.assertEqual(len(self.gather_relevant(product, self.stock_location, strict=True)), 2)
def test_decrease_available_quantity_4(self):
""" Decrease the available quantity that delete the quant. The active user should have
read,write and unlink rights
"""
self.env['stock.quant'].create({
'product_id': self.product.id,
'location_id': self.stock_location.id,
'quantity': 1.0,
})
self.env = self.env(user=self.demo_user)
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, -1.0)
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location)), 0)
def test_increase_reserved_quantity_1(self):
""" Increase the reserved quantity of quantity x when there's a single quant in a given
location which has an available quantity of x.
"""
self.env['stock.quant'].create({
'product_id': self.product.id,
'location_id': self.stock_location.id,
'quantity': 10.0,
})
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 10.0)
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location)), 1)
self.env['stock.quant']._update_reserved_quantity(self.product, self.stock_location, 10.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0.0)
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location)), 1)
def test_increase_reserved_quantity_2(self):
""" Increase the reserved quantity of quantity x when there's two quants in a given
location which have an available quantity of x together.
"""
for i in range(2):
self.env['stock.quant'].create({
'product_id': self.product.id,
'location_id': self.stock_location.id,
'quantity': 5.0,
})
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 10.0)
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location)), 2)
self.env['stock.quant']._update_reserved_quantity(self.product, self.stock_location, 10.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0.0)
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location)), 2)
def test_increase_reserved_quantity_3(self):
""" Increase the reserved quantity of quantity x when there's multiple quants in a given
location which have an available quantity of x together.
"""
self.env['stock.quant'].create({
'product_id': self.product.id,
'location_id': self.stock_location.id,
'quantity': 5.0,
'reserved_quantity': 2.0,
})
self.env['stock.quant'].create({
'product_id': self.product.id,
'location_id': self.stock_location.id,
'quantity': 10.0,
'reserved_quantity': 12.0,
})
self.env['stock.quant'].create({
'product_id': self.product.id,
'location_id': self.stock_location.id,
'quantity': 8.0,
'reserved_quantity': 3.0,
})
self.env['stock.quant'].create({
'product_id': self.product.id,
'location_id': self.stock_location.id,
'quantity': 35.0,
'reserved_quantity': 12.0,
})
# total quantity: 58
# total reserved quantity: 29
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 29.0)
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location)), 4)
self.env['stock.quant']._update_reserved_quantity(self.product, self.stock_location, 10.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 19.0)
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location)), 4)
def test_increase_reserved_quantity_4(self):
""" Increase the reserved quantity of quantity x when there's multiple quants in a given
location which have an available quantity of x together.
"""
self.env['stock.quant'].create({
'product_id': self.product.id,
'location_id': self.stock_location.id,
'quantity': 5.0,
'reserved_quantity': 7.0,
})
self.env['stock.quant'].create({
'product_id': self.product.id,
'location_id': self.stock_location.id,
'quantity': 12.0,
'reserved_quantity': 10.0,
})
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0.0)
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location)), 2)
with self.assertRaises(UserError):
self.env['stock.quant']._update_reserved_quantity(self.product, self.stock_location, 10.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0.0)
def test_increase_reserved_quantity_5(self):
""" Decrease the available quantity when no quant are in a location.
"""
with self.assertRaises(UserError):
self.env['stock.quant']._update_reserved_quantity(self.product, self.stock_location, 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0.0)
def test_decrease_reserved_quantity_1(self):
self.env['stock.quant'].create({
'product_id': self.product.id,
'location_id': self.stock_location.id,
'quantity': 10.0,
'reserved_quantity': 10.0,
})
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0.0)
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location)), 1)
self.env['stock.quant']._update_reserved_quantity(self.product, self.stock_location, -10.0, strict=True)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 10.0)
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location)), 1)
def test_increase_decrease_reserved_quantity_1(self):
""" Decrease then increase reserved quantity when no quant are in a location.
"""
with self.assertRaises(UserError):
self.env['stock.quant']._update_reserved_quantity(self.product, self.stock_location, 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0.0)
with self.assertRaises(UserError):
self.env['stock.quant']._update_reserved_quantity(self.product, self.stock_location, -1.0, strict=True)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0.0)
def test_action_done_1(self):
pack_location = self.env.ref('stock.location_pack_zone')
pack_location.active = True
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 2.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 2.0)
self.env['stock.quant']._update_reserved_quantity(self.product, self.stock_location, 2.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0.0)
self.env['stock.quant']._update_reserved_quantity(self.product, self.stock_location, -2.0, strict=True)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 2.0)
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, -2.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0.0)
self.env['stock.quant']._update_available_quantity(self.product, pack_location, 2.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, pack_location), 2.0)
def test_mix_tracked_untracked_1(self):
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
# add one tracked, one untracked
self.env['stock.quant']._update_available_quantity(self.product_serial, self.stock_location, 1.0)
self.env['stock.quant']._update_available_quantity(self.product_serial, self.stock_location, 1.0, lot_id=lot1)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location), 2.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location, strict=True), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location, lot_id=lot1), 2.0)
self.env['stock.quant']._update_reserved_quantity(self.product_serial, self.stock_location, 1.0, lot_id=lot1, strict=True)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location, strict=True), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location, lot_id=lot1), 1.0)
self.env['stock.quant']._update_reserved_quantity(self.product_serial, self.stock_location, -1.0, lot_id=lot1, strict=True)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location), 2.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location, strict=True), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location, lot_id=lot1), 2.0)
with self.assertRaises(UserError):
self.env['stock.quant']._update_reserved_quantity(self.product_serial, self.stock_location, -1.0, strict=True)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location), 2.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location, strict=True), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location, lot_id=lot1), 2.0)
def test_access_rights_1(self):
""" Directly update the quant with a user with or without stock access rights should not raise
an AccessError only deletion will.
"""
quant = self.env['stock.quant'].create({
'product_id': self.product.id,
'location_id': self.stock_location.id,
'quantity': 1.0,
})
self.env = self.env(user=self.demo_user)
with self.assertRaises(AccessError):
self.env['stock.quant'].create({
'product_id': self.product.id,
'location_id': self.stock_location.id,
'quantity': 1.0,
})
with self.assertRaises(AccessError):
quant.with_user(self.demo_user).write({'quantity': 2.0})
with self.assertRaises(UserError):
quant.with_user(self.demo_user).unlink()
self.env = self.env(user=self.stock_user)
self.env['stock.quant'].create({
'product_id': self.product.id,
'location_id': self.stock_location.id,
'quantity': 1.0,
})
quant.with_user(self.stock_user).with_context(inventory_mode=True).write({'quantity': 3.0})
with self.assertRaises(AccessError):
quant.with_user(self.stock_user).unlink()
def test_in_date_1(self):
""" Check that no incoming date is set when updating the quantity of an untracked quant.
"""
quantity, in_date = self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1.0)
self.assertEqual(quantity, 1)
self.assertNotEqual(in_date, None)
def test_in_date_1b(self):
self.env['stock.quant'].create({
'product_id': self.product.id,
'location_id': self.stock_location.id,
'quantity': 1.0,
})
quantity, in_date = self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 2.0)
self.assertEqual(quantity, 3)
self.assertNotEqual(in_date, None)
def test_in_date_2(self):
""" Check that an incoming date is correctly set when updating the quantity of a tracked
quant.
"""
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
quantity, in_date = self.env['stock.quant']._update_available_quantity(self.product_serial, self.stock_location, 1.0, lot_id=lot1)
self.assertEqual(quantity, 1)
self.assertNotEqual(in_date, None)
def test_in_date_3(self):
""" Check that the FIFO strategies correctly applies when you have multiple lot received
at different times for a tracked product.
"""
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
lot2 = self.env['stock.production.lot'].create({
'name': 'lot2',
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
in_date_lot1 = datetime.now()
in_date_lot2 = datetime.now() - timedelta(days=5)
self.env['stock.quant']._update_available_quantity(self.product_serial, self.stock_location, 1.0, lot_id=lot1, in_date=in_date_lot1)
self.env['stock.quant']._update_available_quantity(self.product_serial, self.stock_location, 1.0, lot_id=lot2, in_date=in_date_lot2)
quants = self.env['stock.quant']._update_reserved_quantity(self.product_serial, self.stock_location, 1)
# Default removal strategy is FIFO, so lot2 should be received as it was received earlier.
self.assertEqual(quants[0][0].lot_id.id, lot2.id)
def test_in_date_4(self):
""" Check that the LIFO strategies correctly applies when you have multiple lot received
at different times for a tracked product.
"""
lifo_strategy = self.env['product.removal'].search([('method', '=', 'lifo')])
self.stock_location.removal_strategy_id = lifo_strategy
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
lot2 = self.env['stock.production.lot'].create({
'name': 'lot2',
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
in_date_lot1 = datetime.now()
in_date_lot2 = datetime.now() - timedelta(days=5)
self.env['stock.quant']._update_available_quantity(self.product_serial, self.stock_location, 1.0, lot_id=lot1, in_date=in_date_lot1)
self.env['stock.quant']._update_available_quantity(self.product_serial, self.stock_location, 1.0, lot_id=lot2, in_date=in_date_lot2)
quants = self.env['stock.quant']._update_reserved_quantity(self.product_serial, self.stock_location, 1)
# Removal strategy is LIFO, so lot1 should be received as it was received later.
self.assertEqual(quants[0][0].lot_id.id, lot1.id)
def test_in_date_5(self):
""" Receive the same lot at different times, once they're in the same location, the quants
are merged and only the earliest incoming date is kept.
"""
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.product_lot.id,
'company_id': self.env.company.id,
})
from odoo.fields import Datetime
in_date1 = Datetime.now()
self.env['stock.quant']._update_available_quantity(self.product_lot, self.stock_location, 1.0, lot_id=lot1, in_date=in_date1)
quant = self.env['stock.quant'].search([
('product_id', '=', self.product_lot.id),
('location_id', '=', self.stock_location.id),
])
self.assertEqual(len(quant), 1)
self.assertEqual(quant.quantity, 1)
self.assertEqual(quant.lot_id.id, lot1.id)
self.assertEqual(quant.in_date, in_date1)
in_date2 = Datetime.now() - timedelta(days=5)
self.env['stock.quant']._update_available_quantity(self.product_lot, self.stock_location, 1.0, lot_id=lot1, in_date=in_date2)
quant = self.env['stock.quant'].search([
('product_id', '=', self.product_lot.id),
('location_id', '=', self.stock_location.id),
])
self.assertEqual(len(quant), 1)
self.assertEqual(quant.quantity, 2)
self.assertEqual(quant.lot_id.id, lot1.id)
self.assertEqual(quant.in_date, in_date2)
def test_closest_removal_strategy_tracked(self):
""" Check that the Closest location strategy correctly applies when you have multiple lot received
at different locations for a tracked product.
"""
closest_strategy = self.env['product.removal'].search([('method', '=', 'closest')])
self.stock_location.removal_strategy_id = closest_strategy
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
lot2 = self.env['stock.production.lot'].create({
'name': 'lot2',
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
in_date = datetime.now()
# Add a product from lot1 in stock_location/subloc2
self.env['stock.quant']._update_available_quantity(self.product_serial, self.stock_subloc2, 1.0, lot_id=lot1, in_date=in_date)
# Add a product from lot2 in stock_location/subloc3
self.env['stock.quant']._update_available_quantity(self.product_serial, self.stock_subloc3, 1.0, lot_id=lot2, in_date=in_date)
# Require one unit of the product
quants = self.env['stock.quant']._update_reserved_quantity(self.product_serial, self.stock_location, 1)
# Default removal strategy is 'Closest location', so lot1 should be received as it was put in a closer location. (stock_location/subloc2 < stock_location/subloc3)
self.assertEqual(quants[0][0].lot_id.id, lot1.id)
def test_closest_removal_strategy_untracked(self):
""" Check that the Closest location strategy correctly applies when you have multiple products received
at different locations for untracked products."""
closest_strategy = self.env['product.removal'].search([('method', '=', 'closest')])
self.stock_location.removal_strategy_id = closest_strategy
# Add 2 units of product into stock_location/subloc2
self.env['stock.quant'].create({
'product_id': self.product.id,
'location_id': self.stock_subloc2.id,
'quantity': 2.0,
})
# Add 3 units of product into stock_location/subloc3
self.env['stock.quant'].create({
'product_id': self.product.id,
'location_id': self.stock_subloc3.id,
'quantity': 3.0
})
# Request 3 units of product, with 'Closest location' as removal strategy
quants = self.env['stock.quant']._update_reserved_quantity(self.product, self.stock_location, 3)
# The 2 in stock_location/subloc2 should be taken first, as the location name is smaller alphabetically
self.assertEqual(quants[0][0].reserved_quantity, 2)
# The last one should then be taken in stock_location/subloc3 since the first location doesn't have enough products
self.assertEqual(quants[1][0].reserved_quantity, 1)
def test_in_date_6(self):
"""
One P in stock, P is delivered. Later on, a stock adjustement adds one P. This test checks
the date value of the related quant
"""
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1.0)
move = self.env['stock.move'].create({
'name': 'OUT 1 product',
'product_id': self.product.id,
'product_uom_qty': 1,
'product_uom': self.product.uom_id.id,
'location_id': self.stock_location.id,
'location_dest_id': self.ref('stock.stock_location_customers'),
})
move._action_confirm()
move._action_assign()
move.quantity_done = 1
move._action_done()
tomorrow = fields.Datetime.now() + timedelta(days=1)
with patch.object(fields.Datetime, 'now', lambda: tomorrow):
move = self.env['stock.move'].create({
'name': 'IN 1 product',
'product_id': self.product.id,
'product_uom_qty': 1,
'product_uom': self.product.uom_id.id,
'location_id': self.ref('stock.stock_location_suppliers'),
'location_dest_id': self.stock_location.id,
})
move._action_confirm()
move._action_assign()
move.quantity_done = 1
move._action_done()
quant = self.env['stock.quant'].search([('product_id', '=', self.product.id), ('location_id', '=', self.stock_location.id), ('quantity', '>', 0)])
self.assertEqual(quant.in_date, tomorrow)
def test_quant_creation(self):
"""
This test ensures that, after an internal transfer, the values of the created quand are correct
"""
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 10.0)
move = self.env['stock.move'].create({
'name': 'Move 1 product',
'product_id': self.product.id,
'product_uom_qty': 1,
'product_uom': self.product.uom_id.id,
'location_id': self.stock_location.id,
'location_dest_id': self.stock_subloc2.id,
})
move._action_confirm()
move._action_assign()
move.quantity_done = 1
move._action_done()
quant = self.gather_relevant(self.product, self.stock_subloc2)
self.assertFalse(quant.inventory_quantity_set)
def test_unpack_and_quants_merging(self):
"""
When unpacking a package, if there are already some quantities of the
packed product in the stock, the quant of the on hand quantity and the
one of the package should be merged
"""
stock_location = self.env['stock.warehouse'].search([], limit=1).lot_stock_id
supplier_location = self.env.ref('stock.stock_location_suppliers')
picking_type_in = self.env.ref('stock.picking_type_in')
self.env['stock.quant']._update_available_quantity(self.product, stock_location, 1.0)
picking = self.env['stock.picking'].create({
'picking_type_id': picking_type_in.id,
'location_id': supplier_location.id,
'location_dest_id': stock_location.id,
'move_lines': [(0, 0, {
'name': 'In 10 x %s' % self.product.name,
'product_id': self.product.id,
'location_id': supplier_location.id,
'location_dest_id': stock_location.id,
'product_uom_qty': 10,
'product_uom': self.product.uom_id.id,
})],
})
picking.action_confirm()
package = self.env['stock.quant.package'].create({
'name': 'Super Package',
})
picking.move_lines.move_line_ids.write({
'qty_done': 10,
'result_package_id': package.id,
})
picking.button_validate()
package.unpack()
quant = self.env['stock.quant'].search([('product_id', '=', self.product.id), ('on_hand', '=', True)])
self.assertEqual(len(quant), 1)
# The quants merging is processed thanks to a SQL query (see StockQuant._merge_quants).
# At that point, the ORM is not aware of the new value. So we need to invalidate the
# cache to ensure that the value will be the newest
quant.invalidate_cache(fnames=['quantity'], ids=quant.ids)
self.assertEqual(quant.quantity, 11)
def test_clean_quant_after_package_move(self):
"""
A product is at WH/Stock in a package PK. We deliver PK. The user should
not find any quant at WH/Stock with PK anymore.
"""
package = self.env['stock.quant.package'].create({})
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1.0, package_id=package)
move = self.env['stock.move'].create({
'name': 'OUT 1 product',
'product_id': self.product.id,
'product_uom_qty': 1,
'product_uom': self.product.uom_id.id,
'location_id': self.stock_location.id,
'location_dest_id': self.ref('stock.stock_location_customers'),
})
move._action_confirm()
move._action_assign()
move.move_line_ids.write({
'result_package_id': package.id,
'qty_done': 1,
})
move._action_done()
self.assertFalse(self.env['stock.quant'].search_count([
('product_id', '=', self.product.id),
('package_id', '=', package.id),
('location_id', '=', self.stock_location.id),
]))
| 50.068841
| 41,457
|
10,603
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime, timedelta
from odoo import fields, tests
from odoo.tests.common import Form
class TestReportStockQuantity(tests.TransactionCase):
def setUp(self):
super().setUp()
self.product1 = self.env['product.product'].create({
'name': 'Mellohi',
'default_code': 'C418',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
'tracking': 'lot',
'barcode': 'scan_me'
})
self.wh = self.env['stock.warehouse'].create({
'name': 'Base Warehouse',
'code': 'TESTWH'
})
self.categ_unit = self.env.ref('uom.product_uom_categ_unit')
self.uom_unit = self.env['uom.uom'].search([('category_id', '=', self.categ_unit.id), ('uom_type', '=', 'reference')], limit=1)
self.customer_location = self.env.ref('stock.stock_location_customers')
self.supplier_location = self.env.ref('stock.stock_location_suppliers')
# replenish
self.move1 = self.env['stock.move'].create({
'name': 'test_in_1',
'location_id': self.supplier_location.id,
'location_dest_id': self.wh.lot_stock_id.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 100.0,
'state': 'done',
'date': fields.Datetime.now(),
})
self.quant1 = self.env['stock.quant'].create({
'product_id': self.product1.id,
'location_id': self.wh.lot_stock_id.id,
'quantity': 100.0,
})
# ship
self.move2 = self.env['stock.move'].create({
'name': 'test_out_1',
'location_id': self.wh.lot_stock_id.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 120.0,
'state': 'partially_available',
'date': fields.Datetime.add(fields.Datetime.now(), days=3),
'date_deadline': fields.Datetime.add(fields.Datetime.now(), days=3),
})
self.env['base'].flush()
def test_report_stock_quantity(self):
from_date = fields.Date.to_string(fields.Date.add(fields.Date.today(), days=-1))
to_date = fields.Date.to_string(fields.Date.add(fields.Date.today(), days=4))
report = self.env['report.stock.quantity'].read_group(
[('date', '>=', from_date), ('date', '<=', to_date), ('product_id', '=', self.product1.id)],
['product_qty', 'date', 'product_id', 'state'],
['date:day', 'product_id', 'state'],
lazy=False)
forecast_report = [x['product_qty'] for x in report if x['state'] == 'forecast']
self.assertEqual(forecast_report, [0, 100, 100, 100, -20, -20])
def test_report_stock_quantity_stansit(self):
wh2 = self.env['stock.warehouse'].create({'name': 'WH2', 'code': 'WH2'})
transit_loc = self.wh.company_id.internal_transit_location_id
self.move_transit_out = self.env['stock.move'].create({
'name': 'test_transit_out_1',
'location_id': self.wh.lot_stock_id.id,
'location_dest_id': transit_loc.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 25.0,
'state': 'assigned',
'date': fields.Datetime.now(),
'date_deadline': fields.Datetime.now(),
})
self.move_transit_in = self.env['stock.move'].create({
'name': 'test_transit_in_1',
'location_id': transit_loc.id,
'location_dest_id': wh2.lot_stock_id.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 25.0,
'state': 'waiting',
'date': fields.Datetime.now(),
'date_deadline': fields.Datetime.now(),
})
self.env['base'].flush()
report = self.env['report.stock.quantity'].read_group(
[('date', '>=', fields.Date.today()), ('date', '<=', fields.Date.today()), ('product_id', '=', self.product1.id)],
['product_qty', 'date', 'product_id', 'state'],
['date:day', 'product_id', 'state'],
lazy=False)
forecast_in_report = [x['product_qty'] for x in report if x['state'] == 'in']
self.assertEqual(forecast_in_report, [25])
forecast_out_report = [x['product_qty'] for x in report if x['state'] == 'out']
self.assertEqual(forecast_out_report, [-25])
def test_report_stock_quantity_with_product_qty_filter(self):
from_date = fields.Date.to_string(fields.Date.add(fields.Date.today(), days=-1))
to_date = fields.Date.to_string(fields.Date.add(fields.Date.today(), days=4))
report = self.env['report.stock.quantity'].read_group(
[('product_qty', '<', 0), ('date', '>=', from_date), ('date', '<=', to_date), ('product_id', '=', self.product1.id)],
['product_qty', 'date', 'product_id', 'state'],
['date:day', 'product_id', 'state'],
lazy=False)
forecast_report = [x['product_qty'] for x in report if x['state'] == 'forecast']
self.assertEqual(forecast_report, [-20, -20])
def test_replenishment_report_1(self):
self.product_replenished = self.env['product.product'].create({
'name': 'Security razor',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
})
# get auto-created pull rule from when warehouse is created
self.wh.reception_route_id.rule_ids.unlink()
self.env['stock.rule'].create({
'name': 'Rule Supplier',
'route_id': self.wh.reception_route_id.id,
'location_id': self.wh.lot_stock_id.id,
'location_src_id': self.env.ref('stock.stock_location_suppliers').id,
'action': 'pull',
'delay': 1.0,
'procure_method': 'make_to_stock',
'picking_type_id': self.wh.in_type_id.id,
})
delivery_picking = self.env['stock.picking'].create({
'location_id': self.wh.lot_stock_id.id,
'location_dest_id': self.ref('stock.stock_location_customers'),
'picking_type_id': self.ref('stock.picking_type_out'),
})
self.env['stock.move'].create({
'name': 'Delivery',
'product_id': self.product_replenished.id,
'product_uom_qty': 500.0,
'product_uom': self.uom_unit.id,
'location_id': self.wh.lot_stock_id.id,
'location_dest_id': self.ref('stock.stock_location_customers'),
'picking_id': delivery_picking.id,
})
delivery_picking.action_confirm()
# Trigger the manual orderpoint creation for missing product
self.env['stock.move'].flush()
self.env['stock.warehouse.orderpoint'].action_open_orderpoints()
orderpoint = self.env['stock.warehouse.orderpoint'].search([
('product_id', '=', self.product_replenished.id)
])
self.assertTrue(orderpoint)
self.assertEqual(orderpoint.location_id, self.wh.lot_stock_id)
self.assertEqual(orderpoint.qty_to_order, 500.0)
orderpoint.action_replenish()
self.env['stock.warehouse.orderpoint'].action_open_orderpoints()
move = self.env['stock.move'].search([
('product_id', '=', self.product_replenished.id),
('location_dest_id', '=', self.wh.lot_stock_id.id)
])
# Simulate a supplier delay
move.date = fields.datetime.now() + timedelta(days=1)
orderpoint = self.env['stock.warehouse.orderpoint'].search([
('product_id', '=', self.product_replenished.id)
])
self.assertFalse(orderpoint)
orderpoint_form = Form(self.env['stock.warehouse.orderpoint'])
orderpoint_form.product_id = self.product_replenished
orderpoint_form.location_id = self.wh.lot_stock_id
orderpoint = orderpoint_form.save()
self.assertEqual(orderpoint.qty_to_order, 0.0)
self.env['stock.warehouse.orderpoint'].action_open_orderpoints()
self.assertEqual(orderpoint.qty_to_order, 0.0)
def test_inter_warehouse_transfer(self):
"""
Ensure that the report correctly processes the inter-warehouses SM
"""
product = self.env['product.product'].create({
'name': 'SuperProduct',
'type': 'product',
})
today = datetime.now()
two_days_ago = today - timedelta(days=2)
in_two_days = today + timedelta(days=2)
wh01, wh02 = self.env['stock.warehouse'].create([{
'name': 'Warehouse 01',
'code': 'WH01',
}, {
'name': 'Warehouse 02',
'code': 'WH02',
}])
self.env['stock.quant']._update_available_quantity(product, wh01.lot_stock_id, 3, in_date=two_days_ago)
# Let's have 2 inter-warehouses stock moves (one for today and one for two days from now)
move01, move02 = self.env['stock.move'].create([{
'name': 'Inter WH Move',
'location_id': wh01.lot_stock_id.id,
'location_dest_id': wh02.lot_stock_id.id,
'product_id': product.id,
'product_uom': product.uom_id.id,
'product_uom_qty': 1,
'date': date,
} for date in (today, in_two_days)])
(move01 + move02)._action_confirm()
move01.quantity_done = 1
move01._action_done()
self.env['stock.move'].flush()
data = self.env['report.stock.quantity'].read_group(
[('state', '=', 'forecast'), ('product_id', '=', product.id), ('date', '>=', two_days_ago), ('date', '<=', in_two_days)],
['product_qty', 'date', 'warehouse_id'],
['date:day', 'warehouse_id'],
orderby='date, warehouse_id',
lazy=False,
)
for row, qty in zip(data, [
# wh01_qty, wh02_qty
3.0, 0.0, # two days ago
3.0, 0.0,
2.0, 1.0, # today
2.0, 1.0,
1.0, 2.0, # in two days
]):
self.assertEqual(row['product_qty'], qty, "Incorrect qty for Date '%s' Warehouse '%s'" % (row['date:day'], row['warehouse_id'][1]))
| 43.633745
| 10,603
|
86,515
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import date, datetime, timedelta
from odoo.tests.common import Form, TransactionCase
class TestReportsCommon(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.partner = cls.env['res.partner'].create({'name': 'Partner'})
cls.ModelDataObj = cls.env['ir.model.data']
cls.picking_type_in = cls.env['stock.picking.type'].browse(cls.ModelDataObj._xmlid_to_res_id('stock.picking_type_in'))
cls.picking_type_out = cls.env['stock.picking.type'].browse(cls.ModelDataObj._xmlid_to_res_id('stock.picking_type_out'))
cls.supplier_location = cls.env['stock.location'].browse(cls.ModelDataObj._xmlid_to_res_id('stock.stock_location_suppliers'))
cls.stock_location = cls.env['stock.location'].browse(cls.ModelDataObj._xmlid_to_res_id('stock.stock_location_stock'))
product_form = Form(cls.env['product.product'])
product_form.detailed_type = 'product'
product_form.name = 'Product'
cls.product = product_form.save()
cls.product_template = cls.product.product_tmpl_id
def get_report_forecast(self, product_template_ids=False, product_variant_ids=False, context=False):
if product_template_ids:
report = self.env['report.stock.report_product_template_replenishment']
product_ids = product_template_ids
elif product_variant_ids:
report = self.env['report.stock.report_product_product_replenishment']
product_ids = product_template_ids
if context:
report = report.with_context(context)
report_values = report._get_report_values(docids=product_ids)
docs = report_values['docs']
lines = docs['lines']
return report_values, docs, lines
class TestReports(TestReportsCommon):
def test_reports(self):
product1 = self.env['product.product'].create({
'name': 'Mellohi',
'default_code': 'C418',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
'tracking': 'lot',
'barcode': 'scan_me'
})
lot1 = self.env['stock.production.lot'].create({
'name': 'Volume-Beta',
'product_id': product1.id,
'company_id': self.env.company.id,
})
report = self.env.ref('stock.label_lot_template')
target = b'\n\n\n^XA\n^FO100,50\n^A0N,44,33^FD[C418]Mellohi^FS\n^FO100,100\n^A0N,44,33^FDLN/SN:Volume-Beta^FS\n^FO100,150^BY3\n^BCN,100,Y,N,N\n^FDVolume-Beta^FS\n^XZ\n\n\n'
rendering, qweb_type = report._render_qweb_text(lot1.id)
self.assertEqual(target, rendering.replace(b' ', b''), 'The rendering is not good')
self.assertEqual(qweb_type, 'text', 'the report type is not good')
def test_report_quantity_1(self):
product_form = Form(self.env['product.product'])
product_form.detailed_type = 'product'
product_form.name = 'Product'
product = product_form.save()
warehouse = self.env['stock.warehouse'].search([], limit=1)
stock = self.env['stock.location'].create({
'name': 'New Stock',
'usage': 'internal',
'location_id': warehouse.view_location_id.id,
})
# Inventory Adjustement of 50.0 today.
self.env['stock.quant'].with_context(inventory_mode=True).create({
'product_id': product.id,
'location_id': stock.id,
'inventory_quantity': 50
}).action_apply_inventory()
self.env['stock.move'].flush()
report_records_today = self.env['report.stock.quantity'].read_group(
[('product_id', '=', product.id), ('date', '=', date.today())],
['product_qty'], [], lazy=False)
report_records_tomorrow = self.env['report.stock.quantity'].read_group(
[('product_id', '=', product.id), ('date', '=', date.today() + timedelta(days=1))],
['product_qty'], [])
report_records_yesterday = self.env['report.stock.quantity'].read_group(
[('product_id', '=', product.id), ('date', '=', date.today() - timedelta(days=1))],
['product_qty'], [])
self.assertEqual(sum([r['product_qty'] for r in report_records_today]), 50.0)
self.assertEqual(sum([r['product_qty'] for r in report_records_tomorrow]), 50.0)
self.assertEqual(sum([r['product_qty'] for r in report_records_yesterday]), 0.0)
# Delivery of 20.0 units tomorrow
move_out = self.env['stock.move'].create({
'name': 'Move Out 20',
'date': datetime.now() + timedelta(days=1),
'location_id': stock.id,
'location_dest_id': self.env.ref('stock.stock_location_customers').id,
'product_id': product.id,
'product_uom': product.uom_id.id,
'product_uom_qty': 20.0,
})
self.env['stock.move'].flush()
report_records_tomorrow = self.env['report.stock.quantity'].read_group(
[('product_id', '=', product.id), ('date', '=', date.today() + timedelta(days=1))],
['product_qty'], [])
self.assertEqual(sum([r['product_qty'] for r in report_records_tomorrow]), 50.0)
move_out._action_confirm()
self.env['stock.move'].flush()
report_records_tomorrow = self.env['report.stock.quantity'].read_group(
[('product_id', '=', product.id), ('date', '=', date.today() + timedelta(days=1))],
['product_qty', 'state'], ['state'], lazy=False)
self.assertEqual(sum([r['product_qty'] for r in report_records_tomorrow if r['state'] == 'forecast']), 30.0)
self.assertEqual(sum([r['product_qty'] for r in report_records_tomorrow if r['state'] == 'out']), -20.0)
report_records_today = self.env['report.stock.quantity'].read_group(
[('product_id', '=', product.id), ('date', '=', date.today())],
['product_qty', 'state'], ['state'], lazy=False)
self.assertEqual(sum([r['product_qty'] for r in report_records_today if r['state'] == 'forecast']), 50.0)
# Receipt of 10.0 units tomorrow
move_in = self.env['stock.move'].create({
'name': 'Move In 10',
'date': datetime.now() + timedelta(days=1),
'location_id': self.env.ref('stock.stock_location_suppliers').id,
'location_dest_id': stock.id,
'product_id': product.id,
'product_uom': product.uom_id.id,
'product_uom_qty': 10.0,
})
move_in._action_confirm()
self.env['stock.move'].flush()
report_records_tomorrow = self.env['report.stock.quantity'].read_group(
[('product_id', '=', product.id), ('date', '=', date.today() + timedelta(days=1))],
['product_qty', 'state'], ['state'], lazy=False)
self.assertEqual(sum([r['product_qty'] for r in report_records_tomorrow if r['state'] == 'forecast']), 40.0)
self.assertEqual(sum([r['product_qty'] for r in report_records_tomorrow if r['state'] == 'out']), -20.0)
self.assertEqual(sum([r['product_qty'] for r in report_records_tomorrow if r['state'] == 'in']), 10.0)
report_records_today = self.env['report.stock.quantity'].read_group(
[('product_id', '=', product.id), ('date', '=', date.today())],
['product_qty', 'state'], ['state'], lazy=False)
self.assertEqual(sum([r['product_qty'] for r in report_records_today if r['state'] == 'forecast']), 50.0)
# Delivery of 20.0 units tomorrow
move_out = self.env['stock.move'].create({
'name': 'Move Out 30 - Day-1',
'date': datetime.now() - timedelta(days=1),
'location_id': stock.id,
'location_dest_id': self.env.ref('stock.stock_location_customers').id,
'product_id': product.id,
'product_uom': product.uom_id.id,
'product_uom_qty': 30.0,
})
move_out._action_confirm()
self.env['stock.move'].flush()
report_records_today = self.env['report.stock.quantity'].read_group(
[('product_id', '=', product.id), ('date', '=', date.today())],
['product_qty', 'state'], ['state'], lazy=False)
report_records_tomorrow = self.env['report.stock.quantity'].read_group(
[('product_id', '=', product.id), ('date', '=', date.today() + timedelta(days=1))],
['product_qty', 'state'], ['state'], lazy=False)
report_records_yesterday = self.env['report.stock.quantity'].read_group(
[('product_id', '=', product.id), ('date', '=', date.today() - timedelta(days=1))],
['product_qty', 'state'], ['state'], lazy=False)
self.assertEqual(sum([r['product_qty'] for r in report_records_yesterday if r['state'] == 'forecast']), -30.0)
self.assertEqual(sum([r['product_qty'] for r in report_records_yesterday if r['state'] == 'out']), -30.0)
self.assertEqual(sum([r['product_qty'] for r in report_records_yesterday if r['state'] == 'in']), 0.0)
self.assertEqual(sum([r['product_qty'] for r in report_records_today if r['state'] == 'forecast']), 20.0)
self.assertEqual(sum([r['product_qty'] for r in report_records_today if r['state'] == 'out']), 0.0)
self.assertEqual(sum([r['product_qty'] for r in report_records_today if r['state'] == 'in']), 0.0)
self.assertEqual(sum([r['product_qty'] for r in report_records_tomorrow if r['state'] == 'forecast']), 10.0)
self.assertEqual(sum([r['product_qty'] for r in report_records_tomorrow if r['state'] == 'out']), -20.0)
self.assertEqual(sum([r['product_qty'] for r in report_records_tomorrow if r['state'] == 'in']), 10.0)
def test_report_quantity_2(self):
""" Not supported case.
"""
product_form = Form(self.env['product.product'])
product_form.detailed_type = 'product'
product_form.name = 'Product'
product = product_form.save()
warehouse = self.env['stock.warehouse'].search([], limit=1)
stock = self.env['stock.location'].create({
'name': 'Stock Under Warehouse',
'usage': 'internal',
'location_id': warehouse.view_location_id.id,
})
stock_without_wh = self.env['stock.location'].create({
'name': 'Stock Outside Warehouse',
'usage': 'internal',
'location_id': self.env.ref('stock.stock_location_locations').id,
})
self.env['stock.quant'].with_context(inventory_mode=True).create({
'product_id': product.id,
'location_id': stock.id,
'inventory_quantity': 50
}).action_apply_inventory()
self.env['stock.quant'].with_context(inventory_mode=True).create({
'product_id': product.id,
'location_id': stock_without_wh.id,
'inventory_quantity': 50
}).action_apply_inventory()
move = self.env['stock.move'].create({
'name': 'Move outside warehouse',
'location_id': stock.id,
'location_dest_id': stock_without_wh.id,
'product_id': product.id,
'product_uom': product.uom_id.id,
'product_uom_qty': 10.0,
})
move._action_confirm()
self.env['stock.move'].flush()
report_records = self.env['report.stock.quantity'].read_group(
[('product_id', '=', product.id), ('date', '=', date.today()), ('warehouse_id', '!=', False)],
['product_qty', 'state'], ['state'], lazy=False)
self.assertEqual(sum([r['product_qty'] for r in report_records if r['state'] == 'forecast']), 40.0)
report_records = self.env['report.stock.quantity'].read_group(
[('product_id', '=', product.id), ('date', '=', date.today())],
['product_qty', 'state'], ['state'], lazy=False)
self.assertEqual(sum([r['product_qty'] for r in report_records if r['state'] == 'forecast']), 40.0)
move = self.env['stock.move'].create({
'name': 'Move outside warehouse',
'location_id': stock_without_wh.id,
'location_dest_id': self.env.ref('stock.stock_location_customers').id,
'product_id': product.id,
'product_uom': product.uom_id.id,
'product_uom_qty': 10.0,
})
move._action_confirm()
self.env['stock.move'].flush()
report_records = self.env['report.stock.quantity'].read_group(
[('product_id', '=', product.id), ('date', '=', date.today())],
['product_qty', 'state'], ['state'], lazy=False)
self.assertEqual(sum([r['product_qty'] for r in report_records if r['state'] == 'forecast']), 40.0)
def test_report_quantity_3(self):
product_form = Form(self.env['product.product'])
product_form.detailed_type = 'product'
product_form.name = 'Product'
product = product_form.save()
warehouse = self.env['stock.warehouse'].search([], limit=1)
stock = self.env['stock.location'].create({
'name': 'Rack',
'usage': 'view',
'location_id': warehouse.view_location_id.id,
})
stock_real_loc = self.env['stock.location'].create({
'name': 'Drawer',
'usage': 'internal',
'location_id': stock.id,
})
self.env['stock.move'].flush()
report_records = self.env['report.stock.quantity'].read_group(
[('product_id', '=', product.id), ('date', '=', date.today())],
['product_qty'], [], lazy=False)
self.assertEqual(sum([r['product_qty'] for r in report_records if r['product_qty']]), 0.0)
# Receipt of 20.0 units tomorrow
move_in = self.env['stock.move'].create({
'name': 'Move In 20',
'location_id': self.env.ref('stock.stock_location_suppliers').id,
'location_dest_id': stock.id,
'product_id': product.id,
'product_uom': product.uom_id.id,
'product_uom_qty': 20.0,
})
move_in._action_confirm()
move_in.move_line_ids.location_dest_id = stock_real_loc.id
move_in.move_line_ids.qty_done = 20.0
move_in._action_done()
self.env['stock.move'].flush()
report_records = self.env['report.stock.quantity'].read_group(
[('product_id', '=', product.id), ('date', '=', date.today())],
['product_qty'], [], lazy=False)
self.assertEqual(sum([r['product_qty'] for r in report_records]), 20.0)
# Delivery of 10.0 units tomorrow
move_out = self.env['stock.move'].create({
'name': 'Move Out 10',
'location_id': stock.id,
'location_dest_id': self.env.ref('stock.stock_location_customers').id,
'product_id': product.id,
'product_uom': product.uom_id.id,
'product_uom_qty': 10.0,
})
move_out._action_confirm()
move_out._action_assign()
move_out.move_line_ids.qty_done = 10.0
move_out._action_done()
self.env['stock.move'].flush()
report_records = self.env['report.stock.quantity'].read_group(
[('product_id', '=', product.id), ('date', '=', date.today())],
['product_qty'], [], lazy=False)
self.assertEqual(sum([r['product_qty'] for r in report_records]), 10.0)
def test_report_forecast_1(self):
""" Checks report data for product is empty. Then creates and process
some operations and checks the report data accords rigthly these operations.
"""
report_values, docs, lines = self.get_report_forecast(product_template_ids=self.product_template.ids)
draft_picking_qty = docs['draft_picking_qty']
self.assertEqual(len(lines), 0, "Must have 0 line.")
self.assertEqual(draft_picking_qty['in'], 0)
self.assertEqual(draft_picking_qty['out'], 0)
# Creates a receipt then checks draft picking quantities.
receipt_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
receipt_form.partner_id = self.partner
receipt_form.picking_type_id = self.picking_type_in
receipt = receipt_form.save()
with receipt_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 2
receipt = receipt_form.save()
report_values, docs, lines = self.get_report_forecast(product_template_ids=self.product_template.ids)
draft_picking_qty = docs['draft_picking_qty']
self.assertEqual(len(lines), 0, "Must have 0 line.")
self.assertEqual(draft_picking_qty['in'], 2)
self.assertEqual(draft_picking_qty['out'], 0)
# Creates a delivery then checks draft picking quantities.
delivery_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
delivery_form.partner_id = self.partner
delivery_form.picking_type_id = self.picking_type_out
delivery = delivery_form.save()
with delivery_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 5
delivery = delivery_form.save()
report_values, docs, lines = self.get_report_forecast(product_template_ids=self.product_template.ids)
draft_picking_qty = docs['draft_picking_qty']
self.assertEqual(len(lines), 0, "Must have 0 line.")
self.assertEqual(draft_picking_qty['in'], 2)
self.assertEqual(draft_picking_qty['out'], 5)
# Confirms the delivery: must have one report line and no more pending qty out now.
delivery.action_confirm()
report_values, docs, lines = self.get_report_forecast(product_template_ids=self.product_template.ids)
draft_picking_qty = docs['draft_picking_qty']
self.assertEqual(len(lines), 1, "Must have 1 line.")
self.assertEqual(draft_picking_qty['in'], 2)
self.assertEqual(draft_picking_qty['out'], 0)
delivery_line = lines[0]
self.assertEqual(delivery_line['quantity'], 5)
self.assertEqual(delivery_line['replenishment_filled'], False)
self.assertEqual(delivery_line['document_out'].id, delivery.id)
# Confirms the receipt, must have two report lines now:
# - line with 2 qty (from the receipt to the delivery)
# - line with 3 qty (delivery, unavailable)
receipt.action_confirm()
report_values, docs, lines = self.get_report_forecast(product_template_ids=self.product_template.ids)
draft_picking_qty = docs['draft_picking_qty']
self.assertEqual(len(lines), 2, "Must have 2 line.")
self.assertEqual(draft_picking_qty['in'], 0)
self.assertEqual(draft_picking_qty['out'], 0)
fulfilled_line = lines[0]
unavailable_line = lines[1]
self.assertEqual(fulfilled_line['replenishment_filled'], True)
self.assertEqual(fulfilled_line['quantity'], 2)
self.assertEqual(fulfilled_line['document_in'].id, receipt.id)
self.assertEqual(fulfilled_line['document_out'].id, delivery.id)
self.assertEqual(unavailable_line['replenishment_filled'], False)
self.assertEqual(unavailable_line['quantity'], 3)
self.assertEqual(unavailable_line['document_out'].id, delivery.id)
# Creates a new receipt for the remaining quantity, confirm it...
receipt_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
receipt_form.partner_id = self.partner
receipt_form.picking_type_id = self.picking_type_in
with receipt_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 3
receipt2 = receipt_form.save()
receipt2.action_confirm()
# ... and valid the first one.
receipt_form = Form(receipt)
with receipt_form.move_ids_without_package.edit(0) as move_line:
move_line.quantity_done = 2
receipt = receipt_form.save()
receipt.button_validate()
report_values, docs, lines = self.get_report_forecast(product_template_ids=self.product_template.ids)
draft_picking_qty = docs['draft_picking_qty']
self.assertEqual(len(lines), 2, "Still must have 2 line.")
self.assertEqual(draft_picking_qty['in'], 0)
self.assertEqual(draft_picking_qty['out'], 0)
line1 = lines[0]
line2 = lines[1]
# First line must be fulfilled thanks to the stock on hand.
self.assertEqual(line1['quantity'], 2)
self.assertEqual(line1['replenishment_filled'], True)
self.assertEqual(line1['document_in'], False)
self.assertEqual(line1['document_out'].id, delivery.id)
# Second line must be linked to the second receipt.
self.assertEqual(line2['quantity'], 3)
self.assertEqual(line2['replenishment_filled'], True)
self.assertEqual(line2['document_in'].id, receipt2.id)
self.assertEqual(line2['document_out'].id, delivery.id)
def test_report_forecast_2_replenishments_order(self):
""" Creates a receipt then creates a delivery using half of the receipt quantity.
Checks replenishment lines are correctly sorted (assigned first, unassigned at the end).
"""
# Creates a receipt then checks draft picking quantities.
receipt_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
receipt_form.partner_id = self.partner
receipt_form.picking_type_id = self.picking_type_in
with receipt_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 6
receipt = receipt_form.save()
receipt.action_confirm()
# Creates a delivery then checks draft picking quantities.
delivery_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
delivery_form.partner_id = self.partner
delivery_form.picking_type_id = self.picking_type_out
with delivery_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 3
delivery = delivery_form.save()
delivery.action_confirm()
report_values, docs, lines = self.get_report_forecast(product_template_ids=self.product_template.ids)
self.assertEqual(len(lines), 2, "Must have 2 line.")
line_1 = lines[0]
line_2 = lines[1]
self.assertEqual(line_1['document_in'].id, receipt.id)
self.assertEqual(line_1['document_out'].id, delivery.id)
self.assertEqual(line_2['document_in'].id, receipt.id)
self.assertEqual(line_2['document_out'], False)
def test_report_forecast_3_sort_by_date(self):
""" Creates some deliveries with different dates and checks the report
lines are correctly sorted by date. Then, creates some receipts and
check their are correctly linked according to their date.
"""
today = datetime.today()
one_hours = timedelta(hours=1)
one_day = timedelta(days=1)
one_month = timedelta(days=30)
# Creates a bunch of deliveries with different date.
delivery_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
delivery_form.partner_id = self.partner
delivery_form.picking_type_id = self.picking_type_out
delivery_form.scheduled_date = today
with delivery_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 5
delivery_1 = delivery_form.save()
delivery_1.action_confirm()
delivery_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
delivery_form.partner_id = self.partner
delivery_form.picking_type_id = self.picking_type_out
delivery_form.scheduled_date = today + one_hours
with delivery_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 5
delivery_2 = delivery_form.save()
delivery_2.action_confirm()
delivery_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
delivery_form.partner_id = self.partner
delivery_form.picking_type_id = self.picking_type_out
delivery_form.scheduled_date = today - one_hours
with delivery_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 5
delivery_3 = delivery_form.save()
delivery_3.action_confirm()
delivery_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
delivery_form.partner_id = self.partner
delivery_form.picking_type_id = self.picking_type_out
delivery_form.scheduled_date = today + one_day
with delivery_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 5
delivery_4 = delivery_form.save()
delivery_4.action_confirm()
delivery_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
delivery_form.partner_id = self.partner
delivery_form.picking_type_id = self.picking_type_out
delivery_form.scheduled_date = today - one_day
with delivery_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 5
delivery_5 = delivery_form.save()
delivery_5.action_confirm()
delivery_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
delivery_form.partner_id = self.partner
delivery_form.picking_type_id = self.picking_type_out
delivery_form.scheduled_date = today + one_month
with delivery_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 5
delivery_6 = delivery_form.save()
delivery_6.action_confirm()
delivery_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
delivery_form.partner_id = self.partner
delivery_form.picking_type_id = self.picking_type_out
delivery_form.scheduled_date = today - one_month
with delivery_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 5
delivery_7 = delivery_form.save()
delivery_7.action_confirm()
# Order must be: 7, 5, 3, 1, 2, 4, 6
report_values, docs, lines = self.get_report_forecast(product_template_ids=self.product_template.ids)
draft_picking_qty = docs['draft_picking_qty']
self.assertEqual(len(lines), 7, "The report must have 7 line.")
self.assertEqual(draft_picking_qty['in'], 0)
self.assertEqual(draft_picking_qty['out'], 0)
self.assertEqual(lines[0]['document_out'].id, delivery_7.id)
self.assertEqual(lines[1]['document_out'].id, delivery_5.id)
self.assertEqual(lines[2]['document_out'].id, delivery_3.id)
self.assertEqual(lines[3]['document_out'].id, delivery_1.id)
self.assertEqual(lines[4]['document_out'].id, delivery_2.id)
self.assertEqual(lines[5]['document_out'].id, delivery_4.id)
self.assertEqual(lines[6]['document_out'].id, delivery_6.id)
# Creates 3 receipts for 20 units.
receipt_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
receipt_form.partner_id = self.partner
receipt_form.picking_type_id = self.picking_type_in
receipt_form.scheduled_date = today + one_month
with receipt_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 5
receipt_1 = receipt_form.save()
receipt_1.action_confirm()
receipt_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
receipt_form.partner_id = self.partner
receipt_form.picking_type_id = self.picking_type_in
receipt_form.scheduled_date = today - one_month
with receipt_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 5
receipt_2 = receipt_form.save()
receipt_2.action_confirm()
receipt_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
receipt_form.partner_id = self.partner
receipt_form.picking_type_id = self.picking_type_in
receipt_form.scheduled_date = today - one_hours
with receipt_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 10
receipt_3 = receipt_form.save()
receipt_3.action_confirm()
# Check report lines (link and order).
report_values, docs, lines = self.get_report_forecast(product_template_ids=self.product_template.ids)
draft_picking_qty = docs['draft_picking_qty']
self.assertEqual(len(lines), 7, "The report must have 7 line.")
self.assertEqual(draft_picking_qty['in'], 0)
self.assertEqual(draft_picking_qty['out'], 0)
self.assertEqual(lines[0]['document_out'].id, delivery_7.id)
self.assertEqual(lines[0]['document_in'].id, receipt_2.id)
self.assertEqual(lines[0]['is_late'], False)
self.assertEqual(lines[1]['document_out'].id, delivery_5.id)
self.assertEqual(lines[1]['document_in'].id, receipt_3.id)
self.assertEqual(lines[1]['is_late'], True)
self.assertEqual(lines[2]['document_out'].id, delivery_3.id)
self.assertEqual(lines[2]['document_in'].id, receipt_3.id)
self.assertEqual(lines[2]['is_late'], False)
self.assertEqual(lines[3]['document_out'].id, delivery_1.id)
self.assertEqual(lines[3]['document_in'].id, receipt_1.id)
self.assertEqual(lines[3]['is_late'], True)
self.assertEqual(lines[4]['document_out'].id, delivery_2.id)
self.assertEqual(lines[4]['document_in'], False)
self.assertEqual(lines[5]['document_out'].id, delivery_4.id)
self.assertEqual(lines[5]['document_in'], False)
self.assertEqual(lines[6]['document_out'].id, delivery_6.id)
self.assertEqual(lines[6]['document_in'], False)
def test_report_forecast_4_intermediate_transfers(self):
""" Create a receipt in 3 steps and check the report line.
"""
grp_multi_loc = self.env.ref('stock.group_stock_multi_locations')
grp_multi_routes = self.env.ref('stock.group_adv_location')
self.env.user.write({'groups_id': [(4, grp_multi_loc.id)]})
self.env.user.write({'groups_id': [(4, grp_multi_routes.id)]})
# Warehouse config.
warehouse = self.env.ref('stock.warehouse0')
warehouse.reception_steps = 'three_steps'
# Product config.
self.product.write({'route_ids': [(4, self.env.ref('stock.route_warehouse0_mto').id)]})
# Create a RR
pg1 = self.env['procurement.group'].create({})
reordering_rule = self.env['stock.warehouse.orderpoint'].create({
'name': 'Product RR',
'location_id': warehouse.lot_stock_id.id,
'product_id': self.product.id,
'product_min_qty': 5,
'product_max_qty': 10,
'group_id': pg1.id,
})
reordering_rule.action_replenish()
report_values, docs, lines = self.get_report_forecast(product_template_ids=self.product_template.ids)
pickings = self.env['stock.picking'].search([('product_id', '=', self.product.id)])
receipt = pickings.filtered(lambda p: p.picking_type_id.id == self.picking_type_in.id)
# The Forecasted Report don't show intermediate moves, it must display only ingoing/outgoing documents.
self.assertEqual(len(lines), 1, "The report must have only 1 line.")
self.assertEqual(lines[0]['document_in'].id, receipt.id, "The report must only show the receipt.")
self.assertEqual(lines[0]['document_out'], False)
self.assertEqual(lines[0]['quantity'], reordering_rule.product_max_qty)
def test_report_forecast_5_multi_warehouse(self):
""" Create some transfer for two different warehouses and check the
report display the good moves according to the selected warehouse.
"""
# Warehouse config.
wh_2 = self.env['stock.warehouse'].create({
'name': 'Evil Twin Warehouse',
'code': 'ETWH',
})
picking_type_out_2 = self.env['stock.picking.type'].search([
('code', '=', 'outgoing'),
('warehouse_id', '=', wh_2.id),
])
# Creates a delivery then checks draft picking quantities.
delivery_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
delivery_form.partner_id = self.partner
delivery_form.picking_type_id = self.picking_type_out
delivery = delivery_form.save()
with delivery_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 5
delivery = delivery_form.save()
report_values, docs, lines = self.get_report_forecast(product_template_ids=self.product_template.ids)
draft_picking_qty = docs['draft_picking_qty']
self.assertEqual(len(lines), 0, "Must have 0 line.")
self.assertEqual(draft_picking_qty['out'], 5)
report_values, docs, lines = self.get_report_forecast(
product_template_ids=self.product_template.ids,
context={'warehouse': wh_2.id},
)
draft_picking_qty = docs['draft_picking_qty']
self.assertEqual(len(lines), 0)
self.assertEqual(draft_picking_qty['out'], 0)
# Confirm the delivery -> The report must now have 1 line.
delivery.action_confirm()
report_values, docs, lines = self.get_report_forecast(product_template_ids=self.product_template.ids)
draft_picking_qty = docs['draft_picking_qty']
self.assertEqual(len(lines), 1)
self.assertEqual(draft_picking_qty['out'], 0)
self.assertEqual(lines[0]['document_out'].id, delivery.id)
self.assertEqual(lines[0]['quantity'], 5)
report_values, docs, lines = self.get_report_forecast(
product_template_ids=self.product_template.ids,
context={'warehouse': wh_2.id},
)
draft_picking_qty = docs['draft_picking_qty']
self.assertEqual(len(lines), 0)
self.assertEqual(draft_picking_qty['out'], 0)
# Creates a delivery for the second warehouse.
delivery_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
delivery_form.partner_id = self.partner
delivery_form.picking_type_id = picking_type_out_2
delivery_2 = delivery_form.save()
with delivery_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 8
delivery_2 = delivery_form.save()
report_values, docs, lines = self.get_report_forecast(product_template_ids=self.product_template.ids)
draft_picking_qty = docs['draft_picking_qty']
self.assertEqual(len(lines), 1)
self.assertEqual(draft_picking_qty['out'], 0)
self.assertEqual(lines[0]['document_out'].id, delivery.id)
self.assertEqual(lines[0]['quantity'], 5)
report_values, docs, lines = self.get_report_forecast(
product_template_ids=self.product_template.ids,
context={'warehouse': wh_2.id},
)
draft_picking_qty = docs['draft_picking_qty']
self.assertEqual(len(lines), 0)
self.assertEqual(draft_picking_qty['out'], 8)
# Confirm the second delivery -> The report must now have 1 line.
delivery_2.action_confirm()
report_values, docs, lines = self.get_report_forecast(product_template_ids=self.product_template.ids)
draft_picking_qty = docs['draft_picking_qty']
self.assertEqual(len(lines), 1)
self.assertEqual(draft_picking_qty['out'], 0)
self.assertEqual(lines[0]['document_out'].id, delivery.id)
self.assertEqual(lines[0]['quantity'], 5)
report_values, docs, lines = self.get_report_forecast(
product_template_ids=self.product_template.ids,
context={'warehouse': wh_2.id},
)
draft_picking_qty = docs['draft_picking_qty']
self.assertEqual(len(lines), 1)
self.assertEqual(draft_picking_qty['out'], 0)
self.assertEqual(lines[0]['document_out'].id, delivery_2.id)
self.assertEqual(lines[0]['quantity'], 8)
def test_report_forecast_6_multi_company(self):
""" Create transfers for two different companies and check report
display the right transfers.
"""
# Configure second warehouse.
company_2 = self.env['res.company'].create({'name': 'Aperture Science'})
wh_2 = self.env['stock.warehouse'].search([('company_id', '=', company_2.id)])
wh_2_picking_type_in = wh_2.in_type_id
# Creates a receipt then checks draft picking quantities.
receipt_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
receipt_form.partner_id = self.partner
receipt_form.picking_type_id = self.picking_type_in
wh_1_receipt = receipt_form.save()
with receipt_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 2
wh_1_receipt = receipt_form.save()
# Creates a receipt then checks draft picking quantities.
receipt_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
receipt_form.partner_id = self.partner
receipt_form.picking_type_id = wh_2_picking_type_in
wh_2_receipt = receipt_form.save()
with receipt_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 5
wh_2_receipt = receipt_form.save()
report_values, docs, lines = self.get_report_forecast(product_template_ids=self.product_template.ids)
draft_picking_qty = docs['draft_picking_qty']
self.assertEqual(len(lines), 0, "Must have 0 line.")
self.assertEqual(draft_picking_qty['in'], 2)
self.assertEqual(draft_picking_qty['out'], 0)
report_values, docs, lines = self.get_report_forecast(
product_template_ids=self.product_template.ids,
context={'warehouse': wh_2.id},
)
draft_picking_qty = docs['draft_picking_qty']
self.assertEqual(len(lines), 0, "Must have 0 line.")
self.assertEqual(draft_picking_qty['in'], 5)
self.assertEqual(draft_picking_qty['out'], 0)
# Confirm the receipts -> The report must now have one line for each company.
wh_1_receipt.action_confirm()
wh_2_receipt.action_confirm()
report_values, docs, lines = self.get_report_forecast(product_template_ids=self.product_template.ids)
self.assertEqual(len(lines), 1, "Must have 1 line.")
self.assertEqual(lines[0]['document_in'].id, wh_1_receipt.id)
self.assertEqual(lines[0]['quantity'], 2)
report_values, docs, lines = self.get_report_forecast(
product_template_ids=self.product_template.ids,
context={'warehouse': wh_2.id},
)
self.assertEqual(len(lines), 1, "Must have 1 line.")
self.assertEqual(lines[0]['document_in'].id, wh_2_receipt.id)
self.assertEqual(lines[0]['quantity'], 5)
def test_report_forecast_7_multiple_variants(self):
""" Create receipts for different variant products and check the report
work well with them.Also, check the receipt/delivery lines are correctly
linked depending of their product variant.
"""
# Create some variant's attributes.
product_attr_color = self.env['product.attribute'].create({'name': 'Color'})
color_gray = self.env['product.attribute.value'].create({
'name': 'Old Fashioned Gray',
'attribute_id': product_attr_color.id,
})
color_blue = self.env['product.attribute.value'].create({
'name': 'Electric Blue',
'attribute_id': product_attr_color.id,
})
product_attr_size = self.env['product.attribute'].create({'name': 'size'})
size_pocket = self.env['product.attribute.value'].create({
'name': 'Pocket',
'attribute_id': product_attr_size.id,
})
size_xl = self.env['product.attribute.value'].create({
'name': 'XL',
'attribute_id': product_attr_size.id,
})
# Create a new product and set some variants on the product.
product_template = self.env['product.template'].create({
'name': 'Game Joy',
'type': 'product',
'attribute_line_ids': [
(0, 0, {
'attribute_id': product_attr_color.id,
'value_ids': [(6, 0, [color_gray.id, color_blue.id])]
}),
(0, 0, {
'attribute_id': product_attr_size.id,
'value_ids': [(6, 0, [size_pocket.id, size_xl.id])]
}),
],
})
gamejoy_pocket_gray = product_template.product_variant_ids[0]
gamejoy_xl_gray = product_template.product_variant_ids[1]
gamejoy_pocket_blue = product_template.product_variant_ids[2]
gamejoy_xl_blue = product_template.product_variant_ids[3]
# Create two receipts.
receipt_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
receipt_form.partner_id = self.partner
receipt_form.picking_type_id = self.picking_type_in
with receipt_form.move_ids_without_package.new() as move_line:
move_line.product_id = gamejoy_pocket_gray
move_line.product_uom_qty = 8
with receipt_form.move_ids_without_package.new() as move_line:
move_line.product_id = gamejoy_pocket_blue
move_line.product_uom_qty = 4
receipt_1 = receipt_form.save()
receipt_1.action_confirm()
receipt_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
receipt_form.partner_id = self.partner
receipt_form.picking_type_id = self.picking_type_in
with receipt_form.move_ids_without_package.new() as move_line:
move_line.product_id = gamejoy_pocket_gray
move_line.product_uom_qty = 2
with receipt_form.move_ids_without_package.new() as move_line:
move_line.product_id = gamejoy_xl_gray
move_line.product_uom_qty = 10
with receipt_form.move_ids_without_package.new() as move_line:
move_line.product_id = gamejoy_xl_blue
move_line.product_uom_qty = 12
receipt_2 = receipt_form.save()
receipt_2.action_confirm()
report_values, docs, lines = self.get_report_forecast(product_template_ids=product_template.ids)
self.assertEqual(len(lines), 5, "Must have 5 lines.")
self.assertEqual(docs['product_variants'].ids, product_template.product_variant_ids.ids)
# Create a delivery for one of these products and check the report lines
# are correctly linked to the good receipts.
delivery_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
delivery_form.partner_id = self.partner
delivery_form.picking_type_id = self.picking_type_out
with delivery_form.move_ids_without_package.new() as move_line:
move_line.product_id = gamejoy_pocket_gray
move_line.product_uom_qty = 10
delivery = delivery_form.save()
delivery.action_confirm()
report_values, docs, lines = self.get_report_forecast(product_template_ids=product_template.ids)
self.assertEqual(len(lines), 5, "Still must have 5 lines.")
self.assertEqual(docs['product_variants'].ids, product_template.product_variant_ids.ids)
# First and second lines should be about the "Game Joy Pocket (gray)"
# and must link the delivery with the two receipt lines.
line_1 = lines[0]
line_2 = lines[1]
self.assertEqual(line_1['product']['id'], gamejoy_pocket_gray.id)
self.assertEqual(line_1['quantity'], 8)
self.assertTrue(line_1['replenishment_filled'])
self.assertEqual(line_1['document_in'].id, receipt_1.id)
self.assertEqual(line_1['document_out'].id, delivery.id)
self.assertEqual(line_2['product']['id'], gamejoy_pocket_gray.id)
self.assertEqual(line_2['quantity'], 2)
self.assertTrue(line_2['replenishment_filled'])
self.assertEqual(line_2['document_in'].id, receipt_2.id)
self.assertEqual(line_2['document_out'].id, delivery.id)
def test_report_forecast_8_delivery_to_receipt_link(self):
"""
Create 2 deliveries, and 1 receipt tied to the second delivery.
The report should show the source document as the 2nd delivery, and show the first
delivery completely unfilled.
"""
delivery_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
delivery_form.partner_id = self.partner
delivery_form.picking_type_id = self.picking_type_out
with delivery_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 100
delivery = delivery_form.save()
delivery.action_confirm()
delivery_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
delivery_form.partner_id = self.partner
delivery_form.picking_type_id = self.picking_type_out
with delivery_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 200
delivery2 = delivery_form.save()
delivery2.action_confirm()
receipt_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
receipt_form.partner_id = self.partner
receipt_form.picking_type_id = self.picking_type_in
receipt = receipt_form.save()
with receipt_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 200
receipt = receipt_form.save()
receipt.move_lines[0].write({
'move_dest_ids': [(4, delivery2.move_lines[0].id)],
})
receipt.action_confirm()
# Test compute _compute_forecast_information
self.assertEqual(delivery.move_lines.forecast_availability, -100.0)
self.assertEqual(delivery2.move_lines.forecast_availability, 200)
self.assertFalse(delivery.move_lines.forecast_expected_date)
self.assertEqual(delivery2.move_lines.forecast_expected_date, receipt.move_lines.date)
_, _, lines = self.get_report_forecast(product_template_ids=self.product_template.ids)
self.assertEqual(len(lines), 2, 'Only 2 lines')
delivery_line = [l for l in lines if l['document_out'].id == delivery.id][0]
self.assertTrue(delivery_line, 'No line for delivery 1')
self.assertFalse(delivery_line['replenishment_filled'])
delivery2_line = [l for l in lines if l['document_out'].id == delivery2.id][0]
self.assertTrue(delivery2_line, 'No line for delivery 2')
self.assertTrue(delivery2_line['replenishment_filled'])
def test_report_forecast_9_delivery_to_receipt_link_over_received(self):
"""
Create 2 deliveries, and 1 receipt tied to the second delivery.
Set the quantity on the receipt to be enough for BOTH deliveries.
For example, this can happen if they have manually increased the quantity on the generated PO.
The report should show both deliveries fulfilled.
"""
delivery_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
delivery_form.partner_id = self.partner
delivery_form.picking_type_id = self.picking_type_out
with delivery_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 100
delivery = delivery_form.save()
delivery.action_confirm()
delivery_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
delivery_form.partner_id = self.partner
delivery_form.picking_type_id = self.picking_type_out
with delivery_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 200
delivery2 = delivery_form.save()
delivery2.action_confirm()
receipt_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
receipt_form.partner_id = self.partner
receipt_form.picking_type_id = self.picking_type_in
receipt = receipt_form.save()
with receipt_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 300
receipt = receipt_form.save()
receipt.move_lines[0].write({
'move_dest_ids': [(4, delivery2.move_lines[0].id)],
})
receipt.action_confirm()
# Test compute _compute_forecast_information
self.assertEqual(delivery.move_lines.forecast_availability, 100)
self.assertEqual(delivery2.move_lines.forecast_availability, 200)
self.assertEqual(delivery.move_lines.forecast_expected_date, receipt.move_lines.date)
self.assertEqual(delivery2.move_lines.forecast_expected_date, receipt.move_lines.date)
_, _, lines = self.get_report_forecast(product_template_ids=self.product_template.ids)
self.assertEqual(len(lines), 2, 'Only 2 lines')
delivery_line = [l for l in lines if l['document_out'].id == delivery.id][0]
self.assertTrue(delivery_line, 'No line for delivery 1')
self.assertTrue(delivery_line['replenishment_filled'])
delivery2_line = [l for l in lines if l['document_out'].id == delivery2.id][0]
self.assertTrue(delivery2_line, 'No line for delivery 2')
self.assertTrue(delivery2_line['replenishment_filled'])
def test_report_forecast_10_report_line_corresponding_to_picking_highlighted(self):
""" When accessing the report from a stock move, checks if the correct picking is highlighted in the report
and if the forecasted availability for incoming and outcoming moves is correct
"""
# Creation of one delivery with date 'today'
delivery_form = Form(self.env['stock.picking'])
delivery_form.partner_id = self.partner
delivery_form.picking_type_id = self.picking_type_out
delivery_form.scheduled_date = date.today()
with delivery_form.move_ids_without_package.new() as move:
move.product_id = self.product
move.product_uom_qty = 200
delivery1 = delivery_form.save()
delivery1.action_confirm()
# Creation of one receipt with date 'today + 1' and smaller qty than the delivery
scheduled_date1 = datetime.now() + timedelta(days=1)
receipt_form = Form(self.env['stock.picking'])
receipt_form.partner_id = self.partner
receipt_form.picking_type_id = self.picking_type_in
receipt_form.scheduled_date = scheduled_date1
with receipt_form.move_ids_without_package.new() as move:
move.product_id = self.product
move.product_uom_qty = 150
receipt1 = receipt_form.save()
receipt1.action_confirm()
self.assertEqual(receipt1.move_lines.forecast_availability, -50.0)
self.assertEqual(delivery1.move_lines.forecast_availability, 150)
self.assertEqual(delivery1.move_lines.forecast_expected_date, scheduled_date1)
# Creation of an identical receipt which should lead to a positive forecast availability
scheduled_date2 = datetime.now() + timedelta(days=3)
receipt_form = Form(self.env['stock.picking'])
receipt_form.partner_id = self.partner
receipt_form.picking_type_id = self.picking_type_in
receipt_form.scheduled_date = scheduled_date2
with receipt_form.move_ids_without_package.new() as move:
move.product_id = self.product
move.product_uom_qty = 150
receipt2 = receipt_form.save()
receipt2.action_confirm()
for move in receipt2.move_lines:
move.quantity_done = 150
# Check forecast_information of delivery1
delivery1.move_lines._compute_forecast_information() # Because depends not "complete"
self.assertEqual(delivery1.move_lines.forecast_availability, 200)
self.assertEqual(delivery1.move_lines.forecast_expected_date, scheduled_date2)
receipt2.button_validate()
self.assertEqual(receipt1.move_lines.forecast_availability, 100.0)
# Check forecast_information of delivery1, because the receipt2 as been validate the forecast_expected_date == receipt1.scheduled_date
delivery1.move_lines._compute_forecast_information()
self.assertEqual(delivery1.move_lines.forecast_availability, 200)
self.assertEqual(delivery1.move_lines.forecast_expected_date, scheduled_date1)
delivery2 = delivery1.copy()
delivery2_form = Form(delivery2)
delivery2_form.scheduled_date = datetime.now() + timedelta(days=1)
delivery2 = delivery2_form.save()
delivery2.action_confirm()
self.assertEqual(delivery2.move_lines.forecast_availability, 100)
# Check for both deliveries and receipts if the highlight (is_matched) corresponds to the correct picking
for picking in [delivery1, delivery2, receipt1, receipt2]:
context = picking.move_lines[0].action_product_forecast_report()['context']
_, _, lines = self.get_report_forecast(product_template_ids=self.product_template.ids, context=context)
for line in lines:
if picking in [line['document_in'], line['document_out']]:
self.assertTrue(line['is_matched'], "The corresponding picking should be matched in the forecast report.")
else:
self.assertFalse(line['is_matched'], "A line of the forecast report not linked to the picking shoud not be matched.")
def test_report_forecast_11_non_reserved_order(self):
""" Creates deliveries with different operation type reservation methods.
Checks replenishment lines are correctly sorted by reservation_date:
'manual': always last (no reservation_date)
'at_confirm': reservation_date = time of creation
'by_date': reservation_date = scheduled_date - reservation_days_before(_priority)
"""
picking_type_manual = self.picking_type_out.copy()
picking_type_by_date = picking_type_manual.copy()
picking_type_at_confirm = picking_type_manual.copy()
picking_type_manual.reservation_method = 'manual'
picking_type_manual.sequence_code = 'manual'
picking_type_by_date.reservation_method = 'by_date'
picking_type_by_date.sequence_code = 'by'
# artificially make non-priority moves reserve before priority moves to
# check order doesn't prioritize priority
picking_type_by_date.reservation_days_before = '6'
picking_type_by_date.reservation_days_before_priority = '4'
picking_type_at_confirm.reservation_method = 'at_confirm'
picking_type_at_confirm.sequence_code = 'confirm'
# 'manual' reservation => no reservation_date
delivery_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
delivery_form.partner_id = self.partner
delivery_form.picking_type_id = picking_type_manual
delivery_form.scheduled_date = datetime.now() - timedelta(days=10)
with delivery_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 3
delivery_manual = delivery_form.save()
delivery_manual.action_confirm()
# 'by_date' reservation => reservation_date = 1 day before today
delivery_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
delivery_form.partner_id = self.partner
delivery_form.picking_type_id = picking_type_by_date
delivery_form.scheduled_date = datetime.now() + timedelta(days=5)
with delivery_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 3
delivery_by_date = delivery_form.save()
delivery_by_date.action_confirm()
# 'by_date' reservation (priority) => reservation_date = 1 day after today
delivery_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
delivery_form.partner_id = self.partner
delivery_form.picking_type_id = picking_type_by_date
delivery_form.scheduled_date = datetime.now() + timedelta(days=5)
delivery_form.priority = '1'
with delivery_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 3
delivery_by_date_priority = delivery_form.save()
delivery_by_date_priority.action_confirm()
# 'at_confirm' reservation => reservation_date = today
delivery_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
delivery_form.partner_id = self.partner
delivery_form.picking_type_id = picking_type_at_confirm
with delivery_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 3
delivery_at_confirm = delivery_form.save()
delivery_at_confirm.action_confirm()
# Order should be: delivery_by_date, delivery_at_confirm, delivery_by_date_priority, delivery_manual
_, _, lines = self.get_report_forecast(product_template_ids=self.product_template.ids)
self.assertEqual(len(lines), 4, "The report must have 4 lines.")
self.assertEqual(lines[0]['document_out'].id, delivery_by_date.id)
self.assertEqual(lines[1]['document_out'].id, delivery_at_confirm.id)
self.assertEqual(lines[2]['document_out'].id, delivery_by_date_priority.id)
self.assertEqual(lines[3]['document_out'].id, delivery_manual.id)
all_delivery = delivery_by_date | delivery_at_confirm | delivery_by_date_priority | delivery_manual
self.assertEqual(all_delivery.move_lines.mapped("forecast_availability"), [-3.0, -3.0, -3.0, -3.0])
# Creation of one receipt to fulfill the 2 first deliveries delivery_by_date and delivery_at_confirm
receipt_form = Form(self.env['stock.picking'])
receipt_form.partner_id = self.partner
receipt_form.picking_type_id = self.picking_type_in
receipt_form.scheduled_date = date.today() + timedelta(days=1)
with receipt_form.move_ids_without_package.new() as move:
move.product_id = self.product
move.product_uom_qty = 6
receipt1 = receipt_form.save()
receipt1.action_confirm()
self.assertEqual(all_delivery.move_lines.mapped("forecast_availability"), [3, 3, -3.0, -3.0])
def test_report_reception_1_one_receipt(self):
""" Create 2 deliveries and 1 receipt where some of the products being received
can be reserved for the deliveries. Check that the reception report correctly
shows these corresponding potential allocations + correctly reserves incoming moves
when reserve button is pushed.
"""
product2 = self.env['product.product'].create({
'name': 'Extra Product',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
})
product3 = self.env['product.product'].create({
'name': 'Unpopular Product',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
})
# Creates some deliveries for reception report to match against
delivery_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
delivery_form.partner_id = self.partner
delivery_form.picking_type_id = self.picking_type_out
with delivery_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 5
with delivery_form.move_ids_without_package.new() as move_line:
move_line.product_id = product2
move_line.product_uom_qty = 10
delivery1 = delivery_form.save()
delivery1.action_confirm()
delivery_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
delivery_form.partner_id = self.partner
delivery_form.picking_type_id = self.picking_type_out
with delivery_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 2
delivery2 = delivery_form.save()
delivery2.action_confirm()
# Create a receipt
receipt_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
receipt_form.partner_id = self.partner
receipt_form.picking_type_id = self.picking_type_in
with receipt_form.move_ids_without_package.new() as move_line:
# incoming qty greater than total (2 moves) outgoing amount => 2 report lines, each = outgoing qty
move_line.product_id = self.product
move_line.product_uom_qty = 15
with receipt_form.move_ids_without_package.new() as move_line:
# outgoing qty greater than incoming amount => report line = incoming qty
move_line.product_id = product2
move_line.product_uom_qty = 5
with receipt_form.move_ids_without_package.new() as move_line:
# not outgoing => shouldn't appear in report
move_line.product_id = product3
move_line.product_uom_qty = 5
receipt = receipt_form.save()
# check that reception report has correct number of deliveries/outgoing moves
# but the quantities aren't available for assignment yet (i.e. can link as chained moves)
report = self.env['report.stock.report_reception']
report_values = report._get_report_values(docids=[receipt.id])
sources_to_lines = report_values['sources_to_lines']
self.assertEqual(len(sources_to_lines), 2, "The report has wrong number of outgoing pickings.")
all_lines = []
for dummy, lines in sources_to_lines.items():
for line in lines:
self.assertFalse(line['is_qty_assignable'], "The receipt IS DRAFT => its move quantities ARE NOT available to assign.")
all_lines.append(line)
self.assertEqual(len(all_lines), 3, "The report has wrong number of outgoing moves.")
# we expect this order based on move creation
self.assertEqual(all_lines[0]['quantity'], 5, "The first move has wrong incoming qty.")
self.assertEqual(all_lines[0]['product']['id'], self.product.id, "The first move has wrong incoming product to assign.")
self.assertEqual(all_lines[1]['quantity'], 5, "The second move has wrong incoming qty.")
self.assertEqual(all_lines[1]['product']['id'], product2.id, "The second move has wrong incoming product to assign.")
self.assertEqual(all_lines[2]['quantity'], 2, "The last move has wrong incoming qty.")
self.assertEqual(all_lines[2]['product']['id'], self.product.id, "The third move has wrong incoming product to assign.")
# check that report correctly realizes outgoing moves can be linked when receipt is done
receipt.action_confirm()
for move in receipt.move_lines:
move.quantity_done = move.product_uom_qty
receipt.button_validate()
report_values = report._get_report_values(docids=[receipt.id])
sources_to_lines = report_values['sources_to_lines']
all_lines = []
move_ids = []
qtys = []
in_ids = []
for dummy, lines in sources_to_lines.items():
for line in lines:
self.assertTrue(line['is_qty_assignable'], "The receipt IS DONE => all of its move quantities ARE assignable")
all_lines.append(line)
move_ids.append(line['move_out'].id)
qtys.append(line['quantity'])
in_ids += line['move_ins']
# line quantities should be the same when receipt is done compared to when it was draft
self.assertEqual(len(all_lines), 3, "The report has wrong number of outgoing moves.")
self.assertEqual(all_lines[0]['quantity'], 5, "The first move has wrong incoming qty to reserve.")
self.assertEqual(all_lines[0]['product']['id'], self.product.id, "The first move has wrong product to reserve.")
self.assertEqual(all_lines[1]['quantity'], 5, "The second move has wrong incoming qty to reserve.")
self.assertEqual(all_lines[1]['product']['id'], product2.id, "The second move has wrong product to reserve.")
self.assertEqual(all_lines[2]['quantity'], 2, "The last move has wrong incoming qty to reserve.")
self.assertEqual(all_lines[2]['product']['id'], self.product.id, "The third move has wrong product to reserve.")
# check that report assign button works correctly
report.action_assign(move_ids, qtys, in_ids)
self.assertEqual(len(receipt.move_lines[0].move_dest_ids.ids), 2, "Demand qty of first and last moves should now be linked to incoming.")
self.assertEqual(len(receipt.move_lines[1].move_dest_ids.ids), 1, "Demand qty of second move should now be linked to incoming.")
self.assertEqual(len(receipt.move_lines[2].move_dest_ids.ids), 0, "product3 should have no moves linked to it.")
self.assertEqual(len(delivery1.move_lines.filtered(lambda m: m.product_id == product2)), 2, "product2 outgoing move should be split between linked and non-linked quantities.")
def test_report_reception_2_two_receipts(self):
""" Create 1 delivery and 2 receipts where the products being received
can be reserved for the delivery. Check that the reception report correctly
shows corresponding potential allocations when receipts have differing states.
"""
# Creates delivery for reception report to match against
delivery_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
delivery_form.partner_id = self.partner
delivery_form.picking_type_id = self.picking_type_out
with delivery_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 100
delivery = delivery_form.save()
delivery.action_confirm()
# Create 2 receipts and check its reception report values
receipt_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
receipt_form.partner_id = self.partner
receipt_form.picking_type_id = self.picking_type_in
with receipt_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 5
receipt1 = receipt_form.save()
receipt_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
receipt_form.partner_id = self.partner
receipt_form.picking_type_id = self.picking_type_in
with receipt_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 3
receipt2 = receipt_form.save()
# check that report correctly merges not draft incoming quantities
report = self.env['report.stock.report_reception']
report_values = report._get_report_values(docids=[receipt1.id, receipt2.id])
self.assertEqual(len(report_values['pickings']), 2, "There should be 2 receipts to assign from in this report")
sources_to_lines = report_values['sources_to_lines']
self.assertEqual(len(sources_to_lines), 1, "The report has wrong number of outgoing pickings.")
all_lines = list(sources_to_lines.values())[0]
self.assertEqual(len(all_lines), 1, "The report has wrong number of outgoing move lines.")
self.assertFalse(all_lines[0]['is_qty_assignable'], "The receipt IS NOT done => its move quantities ARE NOT available to reserve (i.e. done).")
self.assertEqual(all_lines[0]['quantity'], 8, "The move has wrong incoming qty.")
# check that report splits assignable and non-assignable quantities when 1 receipt is draft and other is confirmed
receipt1.action_confirm()
for move in receipt1.move_lines:
move.quantity_done = move.product_uom_qty
report_values = report._get_report_values(docids=[receipt1.id, receipt2.id])
sources_to_lines = report_values['sources_to_lines']
all_lines = list(sources_to_lines.values())[0]
# line quantities depends on done vs not done incoming quantities => should be 2 lines now
self.assertEqual(len(all_lines), 2, "The report has wrong number of lines (1 assignable + 1 not).")
self.assertEqual(all_lines[0]['quantity'], 5, "The first move has wrong incoming qty to assign.")
self.assertTrue(all_lines[0]['is_qty_assignable'], "1 receipt is done => should have 1 reservable move.")
self.assertEqual(all_lines[1]['quantity'], 3, "The second move has wrong (expected) incoming qty.")
self.assertFalse(all_lines[1]['is_qty_assignable'], "1 receipt is draft => should have 1 non-assignable move.")
# check that report doesn't allow done and non-done moves at same time
receipt1.button_validate()
reason = report._get_report_values(docids=[receipt1.id, receipt2.id])['reason']
self.assertEqual(reason, "This report cannot be used for done and not done transfers at the same time", "empty report reason not shown")
def test_report_reception_3_multiwarehouse(self):
""" Check that reception report respects same warehouse for
receipts and deliveries.
"""
# Warehouse config.
wh_2 = self.env['stock.warehouse'].create({
'name': 'Other Warehouse',
'code': 'OTHER',
})
picking_type_out_2 = self.env['stock.picking.type'].search([
('code', '=', 'outgoing'),
('warehouse_id', '=', wh_2.id),
])
# Creates delivery in warehouse2
delivery_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
delivery_form.partner_id = self.partner
delivery_form.picking_type_id = picking_type_out_2
with delivery_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 100
delivery = delivery_form.save()
delivery.action_confirm()
# Create a receipt in warehouse1
receipt_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
receipt_form.partner_id = self.partner
receipt_form.picking_type_id = self.picking_type_in
with receipt_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 15
receipt = receipt_form.save()
report = self.env['report.stock.report_reception']
report_values = report._get_report_values(docids=[receipt.id])
self.assertEqual(len(report_values['sources_to_lines']), 0, "The receipt and delivery are in different warehouses => no moves to link to should be found.")
def test_report_reception_4_pick_pack(self):
""" Check that reception report ignores outgoing moves that are not beginning of chain
"""
warehouse = self.env['stock.warehouse'].search([('lot_stock_id', '=', self.stock_location.id)], limit=1)
warehouse.write({'delivery_steps': 'pick_pack_ship'})
ship_move = self.env['stock.move'].create({
'name': 'The ship move',
'product_id': self.product.id,
'product_uom_qty': 5.0,
'product_uom': self.product.uom_id.id,
'location_id': warehouse.wh_output_stock_loc_id.id,
'location_dest_id': self.env.ref('stock.stock_location_customers').id,
'warehouse_id': warehouse.id,
'picking_type_id': warehouse.out_type_id.id,
'procure_method': 'make_to_order',
'state': 'draft',
})
# create chained pick/pack moves to test with
ship_move._assign_picking()
ship_move._action_confirm()
pack_move = ship_move.move_orig_ids[0]
pick_move = pack_move.move_orig_ids[0]
self.assertEqual(pack_move.state, 'waiting', "Pack move wasn't created...")
self.assertEqual(pick_move.state, 'confirmed', "Pick move wasn't created...")
receipt_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
receipt_form.partner_id = self.partner
receipt_form.picking_type_id = self.picking_type_in
with receipt_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 15
receipt = receipt_form.save()
report = self.env['report.stock.report_reception']
report_values = report._get_report_values(docids=[receipt.id])
self.assertEqual(len(report_values['sources_to_lines']), 1, "There should only be 1 line (pick move)")
def test_report_reception_5_move_splitting(self):
""" Check the complicated use cases of correct move splitting when assigning/unassigning when:
1. Qty to assign is less than delivery qty demand
2. Delivery already has some reserved quants
"""
incoming_qty = 4
outgoing_qty = 10
qty_in_stock = outgoing_qty - incoming_qty
self.env['stock.quant'].with_context(inventory_mode=True).create({
'product_id': self.product.id,
'location_id': self.stock_location.id,
'inventory_quantity': qty_in_stock
}).action_apply_inventory()
# create delivery + receipt
delivery_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
delivery_form.picking_type_id = self.picking_type_out
with delivery_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = outgoing_qty
delivery = delivery_form.save()
delivery.action_confirm()
receipt_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
receipt_form.partner_id = self.partner
receipt_form.picking_type_id = self.picking_type_in
with receipt_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = incoming_qty
receipt = receipt_form.save()
receipt.action_confirm()
self.assertEqual(len(delivery.move_ids_without_package), 1)
report = self.env['report.stock.report_reception']
# -------------------
# check report assign
# -------------------
report.action_assign(delivery.move_ids_without_package.ids, [incoming_qty], receipt.move_ids_without_package.ids)
mto_move = delivery.move_ids_without_package.filtered(lambda m: m.procure_method == 'make_to_order')
non_mto_move = delivery.move_ids_without_package - mto_move
# check that delivery move splits correctly when receipt move is assigned to it
self.assertEqual(len(delivery.move_ids_without_package), 2, "Delivery moves should have split into assigned + not assigned")
self.assertEqual(len(delivery.move_ids_without_package.mapped('move_orig_ids')), 1, "Only 1 delivery + 1 receipt move should be assigned")
self.assertEqual(len(receipt.move_ids_without_package.mapped('move_dest_ids')), 1, "Receipt move should remain unsplit")
# check that assigned (MTO) move is correctly created
self.assertEqual(len(mto_move), 1, "Only 1 delivery move should be MTO")
self.assertEqual(mto_move.product_uom_qty, incoming_qty, "Incorrect quantity split for MTO move")
self.assertEqual(mto_move.reserved_availability, 0, "Receipt is not done => assigned move can't have a reserved qty")
self.assertEqual(mto_move.state, 'waiting', "MTO move state not correctly set")
# check that non-assigned move has correct values
self.assertEqual(non_mto_move.product_uom_qty, outgoing_qty - incoming_qty, "Incorrect quantity split for non-MTO move")
self.assertEqual(non_mto_move.reserved_availability, qty_in_stock, "Reserved qty not correctly linked to non-MTO move")
self.assertEqual(non_mto_move.state, 'assigned', "Fully reserved move has not correctly set state")
# ---------------------
# check report unassign
# ---------------------
report.action_unassign([mto_move.id], incoming_qty, receipt.move_ids_without_package.ids)
self.assertEqual(mto_move.product_uom_qty, incoming_qty, "Move quantities should be unchanged")
self.assertEqual(mto_move.procure_method, 'make_to_stock', "Procure method not correctly reset")
self.assertEqual(mto_move.state, 'confirmed', "Move state not correctly reset (to non-MTO state)")
def test_report_reception_6_backorders(self):
""" Check the complicated use case with backorder when:
1. Incoming qty is greater than outgoing qty needed to be assigned + total outgoing qty is assigned
2. Smaller qty is completed + backorder is made for rest
3. Backorder qty (which is still assigned) is unassigned + re-assigned
"""
incoming_qty = 10
outgoing_qty = 8
orig_incoming_qty_done = 4
delivery_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
delivery_form.partner_id = self.partner
delivery_form.picking_type_id = self.picking_type_out
with delivery_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = outgoing_qty
delivery = delivery_form.save()
delivery.action_confirm()
# Create receipt w/greater qty than needed delivery qty
receipt_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
receipt_form.partner_id = self.partner
receipt_form.picking_type_id = self.picking_type_in
with receipt_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = incoming_qty
receipt = receipt_form.save()
receipt.action_confirm()
report = self.env['report.stock.report_reception']
report.action_assign(delivery.move_ids_without_package.ids, [outgoing_qty], receipt.move_ids_without_package.ids)
self.assertEqual(receipt.move_ids_without_package.move_dest_ids.ids, delivery.move_ids_without_package.ids, "Link between receipt and delivery moves should have been made")
for move in receipt.move_lines:
move.quantity_done = orig_incoming_qty_done
res_dict = receipt.button_validate()
backorder_wizard = Form(self.env[res_dict['res_model']].with_context(res_dict['context'])).save()
backorder_wizard.process()
backorder = self.env['stock.picking'].search([('backorder_id', '=', receipt.id)])
# Check backorder assigned quantities
self.assertEqual(receipt.move_ids_without_package.move_dest_ids, backorder.move_ids_without_package.move_dest_ids, "Backorder should have copied link to delivery move")
report_values = report._get_report_values(docids=[backorder.id])
sources_to_lines = report_values['sources_to_lines']
all_lines = list(sources_to_lines.values())[0]
self.assertEqual(len(all_lines), 1, "The report has wrong number of outgoing moves.")
# we expect that the report won't know about original receipt done amount, so it will show outgoing_qty as assigned
# (rather than the remaining amount that isn't reserved). This can change if the report becomes more sophisticated
self.assertEqual(all_lines[0]['quantity'], incoming_qty - orig_incoming_qty_done, "The report doesn't have the correct qty assigned.")
# Unassign the amount we expect to see in the report + check split correctly happens
report.action_unassign(delivery.move_ids_without_package.ids, outgoing_qty, backorder.move_ids_without_package.ids)
self.assertEqual(len(delivery.move_ids_without_package), 2, "The delivery should have split its reserved qty from the original move")
reserved_move = receipt.move_ids_without_package.move_dest_ids
self.assertEqual(len(reserved_move), 1, "Move w/reserved qty should have full demand reserved")
self.assertEqual(reserved_move.state, 'assigned', "Move w/reserved qty should have full demand reserved")
self.assertEqual(reserved_move.product_uom_qty, orig_incoming_qty_done, "Done amount in original receipt should be amount demanded/reserved in delivery still with a link")
report_values = report._get_report_values(docids=[backorder.id])
sources_to_lines = report_values['sources_to_lines']
all_lines = list(sources_to_lines.values())[0]
self.assertEqual(len(all_lines), 1, "The report should only contain the remaining non-reserved move")
self.assertEqual(all_lines[0]['quantity'], outgoing_qty - orig_incoming_qty_done, "The report doesn't have the correct qty to assign")
# Re-assign the remaining delivery amount and check that everything reserves correctly in the end
report.action_assign((delivery.move_ids_without_package - reserved_move).ids, [outgoing_qty - orig_incoming_qty_done], backorder.move_ids_without_package.ids)
for move in backorder.move_lines:
move.quantity_done = incoming_qty - orig_incoming_qty_done
backorder.button_validate()
for move in delivery.move_ids_without_package:
self.assertEqual(move.state, 'assigned', "All delivery moves should be fully reserved now")
| 52.688794
| 86,515
|
280,852
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.exceptions import UserError
from odoo.tests import Form
from odoo.tests.common import TransactionCase
class StockMove(TransactionCase):
@classmethod
def setUpClass(cls):
super(StockMove, cls).setUpClass()
group_stock_multi_locations = cls.env.ref('stock.group_stock_multi_locations')
cls.env.user.write({'groups_id': [(4, group_stock_multi_locations.id, 0)]})
cls.stock_location = cls.env.ref('stock.stock_location_stock')
cls.customer_location = cls.env.ref('stock.stock_location_customers')
cls.supplier_location = cls.env.ref('stock.stock_location_suppliers')
cls.pack_location = cls.env.ref('stock.location_pack_zone')
cls.pack_location.active = True
cls.transit_location = cls.env['stock.location'].search([
('company_id', '=', cls.env.company.id),
('usage', '=', 'transit'),
('active', '=', False)
], limit=1)
cls.transit_location.active = True
cls.uom_unit = cls.env.ref('uom.product_uom_unit')
cls.uom_dozen = cls.env.ref('uom.product_uom_dozen')
cls.product = cls.env['product.product'].create({
'name': 'Product A',
'type': 'product',
'categ_id': cls.env.ref('product.product_category_all').id,
})
cls.product_serial = cls.env['product.product'].create({
'name': 'Product A',
'type': 'product',
'tracking': 'serial',
'categ_id': cls.env.ref('product.product_category_all').id,
})
cls.product_lot = cls.env['product.product'].create({
'name': 'Product A',
'type': 'product',
'tracking': 'lot',
'categ_id': cls.env.ref('product.product_category_all').id,
})
cls.product_consu = cls.env['product.product'].create({
'name': 'Product A',
'type': 'consu',
'categ_id': cls.env.ref('product.product_category_all').id,
})
def gather_relevant(self, product_id, location_id, lot_id=None, package_id=None, owner_id=None, strict=False):
quants = self.env['stock.quant']._gather(product_id, location_id, lot_id=lot_id, package_id=package_id, owner_id=owner_id, strict=strict)
return quants.filtered(lambda q: not (q.quantity == 0 and q.reserved_quantity == 0))
def test_in_1(self):
""" Receive products from a supplier. Check that a move line is created and that the
reception correctly increase a single quant in stock.
"""
# creation
move1 = self.env['stock.move'].create({
'name': 'test_in_1',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 100.0,
})
self.assertEqual(move1.state, 'draft')
# confirmation
move1._action_confirm()
self.assertEqual(move1.state, 'assigned')
self.assertEqual(len(move1.move_line_ids), 1)
# fill the move line
move_line = move1.move_line_ids[0]
self.assertEqual(move_line.product_qty, 100.0)
self.assertEqual(move_line.qty_done, 0.0)
move_line.qty_done = 100.0
# validation
move1._action_done()
self.assertEqual(move1.state, 'done')
# no quants are created in the supplier location
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.supplier_location), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.supplier_location, allow_negative=True), -100.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 100.0)
self.assertEqual(len(self.gather_relevant(self.product, self.supplier_location)), 1.0)
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location)), 1.0)
def test_in_2(self):
""" Receive 5 tracked products from a supplier. The create move line should have 5
reserved. If i assign the 5 items to lot1, the reservation should not change. Once
i validate, the reception correctly increase a single quant in stock.
"""
# creation
move1 = self.env['stock.move'].create({
'name': 'test_in_1',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product_lot.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 5.0,
'picking_type_id': self.env.ref('stock.picking_type_in').id,
})
self.assertEqual(move1.state, 'draft')
# confirmation
move1._action_confirm()
self.assertEqual(move1.state, 'assigned')
self.assertEqual(len(move1.move_line_ids), 1)
move_line = move1.move_line_ids[0]
self.assertEqual(move_line.product_qty, 5)
move_line.lot_name = 'lot1'
move_line.qty_done = 5.0
self.assertEqual(move_line.product_qty, 5) # don't change reservation
move1._action_done()
self.assertEqual(move_line.product_qty, 0) # change reservation to 0 for done move
self.assertEqual(move1.state, 'done')
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_lot, self.supplier_location), 0.0)
supplier_quants = self.gather_relevant(self.product_lot, self.supplier_location)
self.assertEqual(sum(supplier_quants.mapped('quantity')), -5.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_lot, self.stock_location), 5.0)
self.assertEqual(len(self.gather_relevant(self.product_lot, self.supplier_location)), 1.0)
quants = self.gather_relevant(self.product_lot, self.stock_location)
self.assertEqual(len(quants), 1.0)
for quant in quants:
self.assertNotEqual(quant.in_date, False)
def test_in_3(self):
""" Receive 5 serial-tracked products from a supplier. The system should create 5 different
move line.
"""
# creation
move1 = self.env['stock.move'].create({
'name': 'test_in_1',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product_serial.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 5.0,
'picking_type_id': self.env.ref('stock.picking_type_in').id,
})
self.assertEqual(move1.state, 'draft')
# confirmation
move1._action_confirm()
self.assertEqual(move1.state, 'assigned')
self.assertEqual(len(move1.move_line_ids), 5)
move_line = move1.move_line_ids[0]
self.assertEqual(move1.reserved_availability, 5)
i = 0
for move_line in move1.move_line_ids:
move_line.lot_name = 'sn%s' % i
move_line.qty_done = 1
i += 1
self.assertEqual(move1.quantity_done, 5.0)
self.assertEqual(move1.product_qty, 5) # don't change reservation
move1._action_done()
self.assertEqual(move1.quantity_done, 5.0)
self.assertEqual(move1.product_qty, 5) # don't change reservation
self.assertEqual(move1.state, 'done')
# Quant balance should result with 5 quant in supplier and stock
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.supplier_location), 0.0)
supplier_quants = self.gather_relevant(self.product_serial, self.supplier_location)
self.assertEqual(sum(supplier_quants.mapped('quantity')), -5.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location), 5.0)
self.assertEqual(len(self.gather_relevant(self.product_serial, self.supplier_location)), 5.0)
quants = self.gather_relevant(self.product_serial, self.stock_location)
self.assertEqual(len(quants), 5.0)
for quant in quants:
self.assertNotEqual(quant.in_date, False)
def test_out_1(self):
""" Send products to a client. Check that a move line is created reserving products in
stock and that the delivery correctly remove the single quant in stock.
"""
# make some stock
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 100)
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location)), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 100.0)
# creation
move1 = self.env['stock.move'].create({
'name': 'test_out_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 100.0,
})
self.assertEqual(move1.state, 'draft')
# confirmation
move1._action_confirm()
self.assertEqual(move1.state, 'confirmed')
# assignment
move1._action_assign()
self.assertEqual(move1.state, 'assigned')
self.assertEqual(len(move1.move_line_ids), 1)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0.0)
# Should be a reserved quantity and thus a quant.
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location)), 1.0)
# fill the move line
move_line = move1.move_line_ids[0]
self.assertEqual(move_line.product_qty, 100.0)
self.assertEqual(move_line.qty_done, 0.0)
move_line.qty_done = 100.0
# validation
move1._action_done()
self.assertEqual(move1.state, 'done')
# Check there is one quant in customer location
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.customer_location), 100.0)
self.assertEqual(len(self.gather_relevant(self.product, self.customer_location)), 1.0)
# there should be no quant amymore in the stock location
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0.0)
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location)), 0.0)
def test_out_2(self):
""" Send a consumable product to a client. Check that a move line is created but
quants are not impacted.
"""
# make some stock
self.product.type = 'consu'
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location)), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0.0)
# creation
move1 = self.env['stock.move'].create({
'name': 'test_out_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 100.0,
})
self.assertEqual(move1.state, 'draft')
# confirmation
move1._action_confirm()
self.assertEqual(move1.state, 'assigned')
self.assertEqual(len(move1.move_line_ids), 1)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0.0)
# Should be a reserved quantity and thus a quant.
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location)), 0.0)
# fill the move line
move_line = move1.move_line_ids[0]
self.assertEqual(move_line.product_qty, 100.0)
self.assertEqual(move_line.qty_done, 0.0)
move_line.qty_done = 100.0
# validation
move1._action_done()
self.assertEqual(move1.state, 'done')
# no quants are created in the customer location since it's a consumable
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.customer_location), 0.0)
self.assertEqual(len(self.gather_relevant(self.product, self.customer_location)), 0.0)
# there should be no quant amymore in the stock location
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0.0)
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location)), 0.0)
def test_mixed_tracking_reservation_1(self):
""" Send products tracked by lot to a customer. In your stock, there are tracked and
untracked quants. Two moves lines should be created: one for the tracked ones, another
for the untracked ones.
"""
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.product_lot.id,
'company_id': self.env.company.id,
})
self.env['stock.quant']._update_available_quantity(self.product_lot, self.stock_location, 2)
self.env['stock.quant']._update_available_quantity(self.product_lot, self.stock_location, 3, lot_id=lot1)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_lot, self.stock_location), 5.0)
# creation
move1 = self.env['stock.move'].create({
'name': 'test_in_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product_lot.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 5.0,
})
move1._action_confirm()
move1._action_assign()
self.assertEqual(len(move1.move_line_ids), 2)
def test_mixed_tracking_reservation_2(self):
""" Send products tracked by lot to a customer. In your stock, there are two tracked and
mulitple untracked quants. There should be as many move lines as there are quants
reserved. Edit the reserve move lines to set them to new serial numbers, the reservation
should stay. Validate and the final quantity in stock should be 0, not negative.
"""
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
lot2 = self.env['stock.production.lot'].create({
'name': 'lot2',
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
self.env['stock.quant']._update_available_quantity(self.product_serial, self.stock_location, 2)
self.env['stock.quant']._update_available_quantity(self.product_serial, self.stock_location, 1, lot_id=lot1)
self.env['stock.quant']._update_available_quantity(self.product_serial, self.stock_location, 1, lot_id=lot2)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location), 4.0)
# creation
move1 = self.env['stock.move'].create({
'name': 'test_in_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product_serial.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 4.0,
})
move1._action_confirm()
move1._action_assign()
self.assertEqual(len(move1.move_line_ids), 4)
for ml in move1.move_line_ids:
self.assertEqual(ml.product_qty, 1.0)
# assign lot3 and lot 4 to both untracked move lines
lot3 = self.env['stock.production.lot'].create({
'name': 'lot3',
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
lot4 = self.env['stock.production.lot'].create({
'name': 'lot4',
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
untracked_move_line = move1.move_line_ids.filtered(lambda ml: not ml.lot_id)
untracked_move_line[0].lot_id = lot3
untracked_move_line[1].lot_id = lot4
for ml in move1.move_line_ids:
self.assertEqual(ml.product_qty, 1.0)
# no changes on quants, even if i made some move lines with a lot id whom reserved on untracked quants
self.assertEqual(len(self.gather_relevant(self.product_serial, self.stock_location, strict=True)), 1.0) # with a qty of 2
self.assertEqual(len(self.gather_relevant(self.product_serial, self.stock_location, lot_id=lot1, strict=True).filtered(lambda q: q.lot_id)), 1.0)
self.assertEqual(len(self.gather_relevant(self.product_serial, self.stock_location, lot_id=lot2, strict=True).filtered(lambda q: q.lot_id)), 1.0)
self.assertEqual(len(self.gather_relevant(self.product_serial, self.stock_location, lot_id=lot3, strict=True).filtered(lambda q: q.lot_id)), 0)
self.assertEqual(len(self.gather_relevant(self.product_serial, self.stock_location, lot_id=lot4, strict=True).filtered(lambda q: q.lot_id)), 0)
move1.move_line_ids.write({'qty_done': 1.0})
move1._action_done()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location, lot_id=lot1, strict=True), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location, lot_id=lot2, strict=True), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location, lot_id=lot3, strict=True), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location, lot_id=lot4, strict=True), 0.0)
def test_mixed_tracking_reservation_3(self):
""" Send two products tracked by lot to a customer. In your stock, there two tracked quants
and two untracked. Once the move is validated, add move lines to also move the two untracked
ones and assign them serial numbers on the fly. The final quantity in stock should be 0, not
negative.
"""
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
lot2 = self.env['stock.production.lot'].create({
'name': 'lot2',
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
self.env['stock.quant']._update_available_quantity(self.product_serial, self.stock_location, 1, lot_id=lot1)
self.env['stock.quant']._update_available_quantity(self.product_serial, self.stock_location, 1, lot_id=lot2)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location), 2.0)
# creation
move1 = self.env['stock.move'].create({
'name': 'test_in_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product_serial.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 2.0,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.write({'qty_done': 1.0})
move1._action_done()
self.env['stock.quant']._update_available_quantity(self.product_serial, self.stock_location, 2)
lot3 = self.env['stock.production.lot'].create({
'name': 'lot3',
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
lot4 = self.env['stock.production.lot'].create({
'name': 'lot4',
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
self.env['stock.move.line'].create({
'move_id': move1.id,
'product_id': move1.product_id.id,
'qty_done': 1,
'product_uom_id': move1.product_uom.id,
'location_id': move1.location_id.id,
'location_dest_id': move1.location_dest_id.id,
'lot_id': lot3.id,
})
self.env['stock.move.line'].create({
'move_id': move1.id,
'product_id': move1.product_id.id,
'qty_done': 1,
'product_uom_id': move1.product_uom.id,
'location_id': move1.location_id.id,
'location_dest_id': move1.location_dest_id.id,
'lot_id': lot4.id
})
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location, lot_id=lot1, strict=True), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location, lot_id=lot2, strict=True), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location, lot_id=lot3, strict=True), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location, lot_id=lot4, strict=True), 0.0)
def test_mixed_tracking_reservation_4(self):
""" Send two products tracked by lot to a customer. In your stock, there two tracked quants
and on untracked. Once the move is validated, edit one of the done move line to change the
serial number to one that is not in stock. The original serial should go back to stock and
the untracked quant should be tracked on the fly and sent instead.
"""
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
lot2 = self.env['stock.production.lot'].create({
'name': 'lot2',
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
self.env['stock.quant']._update_available_quantity(self.product_serial, self.stock_location, 1, lot_id=lot1)
self.env['stock.quant']._update_available_quantity(self.product_serial, self.stock_location, 1, lot_id=lot2)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location), 2.0)
# creation
move1 = self.env['stock.move'].create({
'name': 'test_in_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product_serial.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 2.0,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.write({'qty_done': 1.0})
move1._action_done()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location, lot_id=lot1, strict=True), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location, lot_id=lot2, strict=True), 0.0)
self.env['stock.quant']._update_available_quantity(self.product_serial, self.stock_location, 1)
lot3 = self.env['stock.production.lot'].create({
'name': 'lot3',
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
move1.move_line_ids[1].lot_id = lot3
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location, lot_id=lot1, strict=True), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location, lot_id=lot2, strict=True), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location, lot_id=lot3, strict=True), 0.0)
def test_mixed_tracking_reservation_5(self):
move1 = self.env['stock.move'].create({
'name': 'test_jenaimarre_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product_serial.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move1._action_confirm()
move1._action_assign()
self.assertEqual(move1.state, 'confirmed')
# create an untracked quant
self.env['stock.quant']._update_available_quantity(self.product_serial, self.stock_location, 1.0)
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
# create a new move line with a lot not assigned to any quant
self.env['stock.move.line'].create({
'move_id': move1.id,
'product_id': move1.product_id.id,
'qty_done': 1,
'product_uom_id': move1.product_uom.id,
'location_id': move1.location_id.id,
'location_dest_id': move1.location_dest_id.id,
'lot_id': lot1.id
})
self.assertEqual(len(move1.move_line_ids), 1)
self.assertEqual(move1.reserved_availability, 0)
# validating the move line should move the lot, not create a negative quant in stock
move1._action_done()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location), 0.0)
self.assertEqual(len(self.gather_relevant(self.product_serial, self.stock_location)), 0.0)
def test_mixed_tracking_reservation_6(self):
# create an untracked quant
self.env['stock.quant']._update_available_quantity(self.product_serial, self.stock_location, 1.0)
move1 = self.env['stock.move'].create({
'name': 'test_jenaimarre_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product_serial.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move1._action_confirm()
move1._action_assign()
self.assertEqual(move1.state, 'assigned')
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
lot2 = self.env['stock.production.lot'].create({
'name': 'lot2',
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
move_line = move1.move_line_ids
move_line.lot_id = lot1
self.assertEqual(move_line.product_qty, 1.0)
move_line.lot_id = lot2
self.assertEqual(move_line.product_qty, 1.0)
move_line.qty_done = 1
# validating the move line should move the lot, not create a negative quant in stock
move1._action_done()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location), 0.0)
self.assertEqual(len(self.gather_relevant(self.product_serial, self.stock_location)), 0.0)
def test_mixed_tracking_reservation_7(self):
""" Similar test_mixed_tracking_reservation_2 but creates first the tracked quant, then the
untracked ones. When adding a lot to the untracked move line, it should not decrease the
untracked quant then increase a non-existing tracked one that will fallback on the
untracked quant.
"""
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
lot2 = self.env['stock.production.lot'].create({
'name': 'lot2',
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
self.env['stock.quant']._update_available_quantity(self.product_serial, self.stock_location, 1, lot_id=lot1)
self.env['stock.quant']._update_available_quantity(self.product_serial, self.stock_location, 1)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location), 2.0)
# creation
move1 = self.env['stock.move'].create({
'name': 'test_in_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product_serial.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 2.0,
})
move1._action_confirm()
move1._action_assign()
self.assertEqual(len(move1.move_line_ids), 2)
for ml in move1.move_line_ids:
self.assertEqual(ml.product_qty, 1.0)
untracked_move_line = move1.move_line_ids.filtered(lambda ml: not ml.lot_id).lot_id = lot2
for ml in move1.move_line_ids:
self.assertEqual(ml.product_qty, 1.0)
move1.move_line_ids.write({'qty_done': 1.0})
move1._action_done()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location, lot_id=lot1, strict=True), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location, lot_id=lot2, strict=True), 0.0)
quants = self.gather_relevant(self.product_serial, self.stock_location)
self.assertEqual(len(quants), 0)
def test_mixed_tracking_reservation_8(self):
""" Send one product tracked by lot to a customer. In your stock, there are one tracked and
one untracked quant. Reserve the move, then edit the lot to one not present in stock. The
system will update the reservation and use the untracked quant. Now unreserve, no error
should happen
"""
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
# at first, we only make the tracked quant available in stock to make sure this one is selected
self.env['stock.quant']._update_available_quantity(self.product_serial, self.stock_location, 1, lot_id=lot1)
# creation
move1 = self.env['stock.move'].create({
'name': 'test_mixed_tracking_reservation_7',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product_serial.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move1._action_confirm()
move1._action_assign()
self.assertEqual(move1.reserved_availability, 1.0)
self.assertEqual(move1.move_line_ids.lot_id.id, lot1.id)
# change the lot_id to one not available in stock while an untracked quant is available
self.env['stock.quant']._update_available_quantity(self.product_serial, self.stock_location, 1)
lot2 = self.env['stock.production.lot'].create({
'name': 'lot2',
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
move1.move_line_ids.lot_id = lot2
self.assertEqual(move1.reserved_availability, 1.0)
self.assertEqual(move1.move_line_ids.lot_id.id, lot2.id)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location, strict=True), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location, lot_id=lot1, strict=True), 1.0)
# unreserve
move1._do_unreserve()
self.assertEqual(move1.reserved_availability, 0.0)
self.assertEqual(len(move1.move_line_ids), 0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location, strict=True), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.stock_location, lot_id=lot1, strict=True), 2.0)
def test_putaway_1(self):
""" Receive products from a supplier. Check that putaway rules are rightly applied on
the receipt move line.
"""
# This test will apply a putaway strategy on the stock location to put everything
# incoming in the sublocation shelf1.
shelf1_location = self.env['stock.location'].create({
'name': 'shelf1',
'usage': 'internal',
'location_id': self.stock_location.id,
})
# putaway from stock to shelf1
putaway = self.env['stock.putaway.rule'].create({
'category_id': self.env.ref('product.product_category_all').id,
'location_in_id': self.stock_location.id,
'location_out_id': shelf1_location.id,
})
self.stock_location.write({
'putaway_rule_ids': [(4, putaway.id, 0)]
})
# creation
move1 = self.env['stock.move'].create({
'name': 'test_putaway_1',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 100.0,
})
move1._action_confirm()
self.assertEqual(move1.state, 'assigned')
self.assertEqual(len(move1.move_line_ids), 1)
# check if the putaway was rightly applied
self.assertEqual(move1.move_line_ids.location_dest_id.id, shelf1_location.id)
def test_putaway_2(self):
""" Receive products from a supplier. Check that putaway rules are rightly applied on
the receipt move line.
"""
# This test will apply a putaway strategy by product on the stock location to put everything
# incoming in the sublocation shelf1.
shelf1_location = self.env['stock.location'].create({
'name': 'shelf1',
'usage': 'internal',
'location_id': self.stock_location.id,
})
# putaway from stock to shelf1
putaway = self.env['stock.putaway.rule'].create({
'product_id': self.product.id,
'location_in_id': self.stock_location.id,
'location_out_id': shelf1_location.id,
})
self.stock_location.write({
'putaway_rule_ids': [(4, putaway.id, 0)],
})
# creation
move1 = self.env['stock.move'].create({
'name': 'test_putaway_2',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 100.0,
})
move1._action_confirm()
self.assertEqual(move1.state, 'assigned')
self.assertEqual(len(move1.move_line_ids), 1)
# check if the putaway was rightly applied
self.assertEqual(move1.move_line_ids.location_dest_id.id, shelf1_location.id)
def test_putaway_3(self):
""" Receive products from a supplier. Check that putaway rules are rightly applied on
the receipt move line.
"""
# This test will apply both the putaway strategy by product and category. We check here
# that the putaway by product takes precedence.
shelf1_location = self.env['stock.location'].create({
'name': 'shelf1',
'usage': 'internal',
'location_id': self.stock_location.id,
})
shelf2_location = self.env['stock.location'].create({
'name': 'shelf2',
'usage': 'internal',
'location_id': self.stock_location.id,
})
putaway_category = self.env['stock.putaway.rule'].create({
'category_id': self.env.ref('product.product_category_all').id,
'location_in_id': self.supplier_location.id,
'location_out_id': shelf1_location.id,
})
putaway_product = self.env['stock.putaway.rule'].create({
'product_id': self.product.id,
'location_in_id': self.supplier_location.id,
'location_out_id': shelf2_location.id,
})
self.stock_location.write({
'putaway_rule_ids': [(6, 0, [
putaway_category.id,
putaway_product.id
])],
})
# creation
move1 = self.env['stock.move'].create({
'name': 'test_putaway_3',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 100.0,
})
move1._action_confirm()
self.assertEqual(move1.state, 'assigned')
self.assertEqual(len(move1.move_line_ids), 1)
# check if the putaway was rightly applied
self.assertEqual(move1.move_line_ids.location_dest_id.id, shelf2_location.id)
def test_putaway_4(self):
""" Receive products from a supplier. Check that putaway rules are rightly applied on
the receipt move line.
"""
# This test will apply both the putaway strategy by product and category. We check here
# that if a putaway by product is not matched, the fallback to the category is correctly
# done.
shelf1_location = self.env['stock.location'].create({
'name': 'shelf1',
'usage': 'internal',
'location_id': self.stock_location.id,
})
shelf2_location = self.env['stock.location'].create({
'name': 'shelf2',
'usage': 'internal',
'location_id': self.stock_location.id,
})
# putaway from stock to shelf1
putaway_category = self.env['stock.putaway.rule'].create({
'category_id': self.env.ref('product.product_category_all').id,
'location_in_id': self.stock_location.id,
'location_out_id': shelf1_location.id,
})
putaway_product = self.env['stock.putaway.rule'].create({
'product_id': self.product_consu.id,
'location_in_id': self.stock_location.id,
'location_out_id': shelf2_location.id,
})
self.stock_location.write({
'putaway_rule_ids': [(6, 0, [
putaway_category.id,
putaway_product.id,
])],
})
# creation
move1 = self.env['stock.move'].create({
'name': 'test_putaway_4',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 100.0,
})
move1._action_confirm()
self.assertEqual(move1.state, 'assigned')
self.assertEqual(len(move1.move_line_ids), 1)
# check if the putaway was rightly applied
self.assertEqual(move1.move_line_ids.location_dest_id.id, shelf1_location.id)
def test_putaway_5(self):
""" Receive products from a supplier. Check that putaway rules are rightly applied on
the receipt move line.
"""
# This test will apply putaway strategy by category.
# We check here that the putaway by category works when the category is
# set on parent category of the product.
shelf_location = self.env['stock.location'].create({
'name': 'shelf',
'usage': 'internal',
'location_id': self.stock_location.id,
})
putaway = self.env['stock.putaway.rule'].create({
'category_id': self.env.ref('product.product_category_all').id,
'location_in_id': self.supplier_location.id,
'location_out_id': shelf_location.id,
})
self.stock_location.write({
'putaway_rule_ids': [(6, 0, [
putaway.id,
])],
})
# creation
move1 = self.env['stock.move'].create({
'name': 'test_putaway_5',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 100.0,
})
move1._action_confirm()
self.assertEqual(move1.state, 'assigned')
self.assertEqual(len(move1.move_line_ids), 1)
# check if the putaway was rightly applied
self.assertEqual(move1.move_line_ids.location_dest_id.id, shelf_location.id)
def test_putaway_6(self):
""" Receive products from a supplier. Check that putaway rules are rightly applied on
the receipt move line.
"""
# This test will apply two putaway strategies by category. We check here
# that the most specific putaway takes precedence.
child_category = self.env['product.category'].create({
'name': 'child_category',
'parent_id': self.ref('product.product_category_all'),
})
shelf1_location = self.env['stock.location'].create({
'name': 'shelf1',
'usage': 'internal',
'location_id': self.stock_location.id,
})
shelf2_location = self.env['stock.location'].create({
'name': 'shelf2',
'usage': 'internal',
'location_id': self.stock_location.id,
})
putaway_category_all = self.env['stock.putaway.rule'].create({
'category_id': self.env.ref('product.product_category_all').id,
'location_in_id': self.supplier_location.id,
'location_out_id': shelf1_location.id,
})
putaway_category_office_furn = self.env['stock.putaway.rule'].create({
'category_id': child_category.id,
'location_in_id': self.supplier_location.id,
'location_out_id': shelf2_location.id,
})
self.stock_location.write({
'putaway_rule_ids': [(6, 0, [
putaway_category_all.id,
putaway_category_office_furn.id,
])],
})
self.product.categ_id = child_category
# creation
move1 = self.env['stock.move'].create({
'name': 'test_putaway_6',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 100.0,
})
move1._action_confirm()
self.assertEqual(move1.state, 'assigned')
self.assertEqual(len(move1.move_line_ids), 1)
# check if the putaway was rightly applied
self.assertEqual(move1.move_line_ids.location_dest_id.id, shelf2_location.id)
def test_putaway_7(self):
"""
Putaway with one package type and one product
"""
warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1)
warehouse.reception_steps = 'two_steps'
child_loc = self.stock_location.child_ids[0]
package_type = self.env['stock.package.type'].create({
'name': 'Super Package Type',
})
package = self.env['stock.quant.package'].create({'package_type_id': package_type.id})
self.env['stock.putaway.rule'].create({
'product_id': self.product.id,
'package_type_ids': [(6, 0, package_type.ids)],
'location_in_id': self.stock_location.id,
'location_out_id': child_loc.id,
})
move_input = self.env['stock.move'].create({
'name': self.product.name,
'location_id': self.supplier_location.id,
'location_dest_id': warehouse.wh_input_stock_loc_id.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
'warehouse_id': warehouse.id,
})
move_input._action_confirm()
move_input.move_line_ids.qty_done = 1
move_input.move_line_ids.result_package_id = package
move_input._action_done()
move_stock = move_input.move_dest_ids
self.assertEqual(move_stock.move_line_ids.location_dest_id, child_loc)
def test_putaway_8(self):
"""
Putaway with product P
Receive 1 x P in a package with a specific type
"""
warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1)
warehouse.reception_steps = 'two_steps'
child_loc = self.stock_location.child_ids[0]
package_type = self.env['stock.package.type'].create({
'name': 'Super Package Type',
})
package = self.env['stock.quant.package'].create({'package_type_id': package_type.id})
self.env['stock.putaway.rule'].create({
'product_id': self.product.id,
'location_in_id': self.stock_location.id,
'location_out_id': child_loc.id,
})
move_input = self.env['stock.move'].create({
'name': self.product.name,
'location_id': self.supplier_location.id,
'location_dest_id': warehouse.wh_input_stock_loc_id.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
'warehouse_id': warehouse.id,
})
move_input._action_confirm()
move_input.move_line_ids.qty_done = 1
move_input.move_line_ids.result_package_id = package
move_input._action_done()
move_stock = move_input.move_dest_ids
self.assertEqual(move_stock.move_line_ids.location_dest_id, child_loc)
def test_putaway_9(self):
"""
Putaway with one category C
2 steps receive
Receive one C-type product in a package with a specific type
The putaway should be selected
"""
warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1)
warehouse.reception_steps = 'two_steps'
basic_category = self.env.ref('product.product_category_all')
child_locations = self.env['stock.location']
categs = self.env['product.category']
for i in range(3):
loc = self.env['stock.location'].create({
'name': 'shelf %s' % i,
'usage': 'internal',
'location_id': self.stock_location.id,
})
child_locations |= loc
categ = self.env['product.category'].create({
'name': 'Category %s' % i,
'parent_id': basic_category.id
})
categs |= categ
self.env['stock.putaway.rule'].create({
'category_id': categ.id,
'location_in_id': self.stock_location.id,
'location_out_id': loc.id,
})
second_child_location = child_locations[1]
second_categ = categs[1]
self.product.categ_id = second_categ
package_type = self.env['stock.package.type'].create({
'name': 'Super Package Type',
})
package = self.env['stock.quant.package'].create({
'package_type_id': package_type.id,
})
move_input = self.env['stock.move'].create({
'name': self.product.name,
'location_id': self.supplier_location.id,
'location_dest_id': warehouse.wh_input_stock_loc_id.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
'warehouse_id': warehouse.id,
})
move_input._action_confirm()
move_input.move_line_ids.qty_done = 1
move_input.move_line_ids.result_package_id = package
move_input._action_done()
move_stock = move_input.move_dest_ids
self.assertEqual(move_stock.move_line_ids.location_dest_id, second_child_location)
def test_putaway_with_storage_category_1(self):
"""Receive a product. Test the product will be move to a child location
with correct storage category.
"""
# storage category
storage_category = self.env['stock.storage.category'].create({
'name': "storage category"
})
self.env['stock.location'].create({
'name': 'shelf1',
'usage': 'internal',
'location_id': self.stock_location.id,
})
shelf2_location = self.env['stock.location'].create({
'name': 'shelf2',
'usage': 'internal',
'location_id': self.stock_location.id,
'storage_category_id': storage_category.id,
})
# putaway from stock to child location with storage_category
putaway = self.env['stock.putaway.rule'].create({
'product_id': self.product.id,
'location_in_id': self.stock_location.id,
'location_out_id': self.stock_location.id,
'storage_category_id': storage_category.id,
})
self.stock_location.write({
'putaway_rule_ids': [(4, putaway.id, 0)],
})
move1 = self.env['stock.move'].create({
'name': 'test_move_1',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 100.0,
})
move1._action_confirm()
self.assertEqual(move1.state, 'assigned')
self.assertEqual(len(move1.move_line_ids), 1)
# check if the putaway was rightly applied
self.assertEqual(move1.move_line_ids.location_dest_id.id, shelf2_location.id)
def test_putaway_with_storage_category_2(self):
"""Receive a product twice. Test first time the putaway applied since we
have enough space, and second time it is not since the location is full.
"""
storage_category = self.env['stock.storage.category'].create({
'name': "storage category"
})
# set the capacity for the product in this storage category to be 100
storage_category_form = Form(storage_category, view='stock.stock_storage_category_form')
with storage_category_form.product_capacity_ids.new() as line:
line.product_id = self.product
line.quantity = 100
storage_category = storage_category_form.save()
shelf1_location = self.env['stock.location'].create({
'name': 'shelf1',
'usage': 'internal',
'location_id': self.stock_location.id,
'storage_category_id': storage_category.id,
})
# putaway from stock to child location with storage_category
putaway = self.env['stock.putaway.rule'].create({
'product_id': self.product.id,
'location_in_id': self.stock_location.id,
'location_out_id': self.stock_location.id,
'storage_category_id': storage_category.id,
})
self.stock_location.write({
'putaway_rule_ids': [(4, putaway.id, 0)],
})
# first move
move1 = self.env['stock.move'].create({
'name': 'test_move_1',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 100.0,
})
move1._action_confirm()
self.assertEqual(move1.state, 'assigned')
self.assertEqual(len(move1.move_line_ids), 1)
# check if the putaway was rightly applied
self.assertEqual(move1.move_line_ids.location_dest_id.id, shelf1_location.id)
# second move
move2 = self.env['stock.move'].create({
'name': 'test_move_2',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 100.0,
})
move2._action_confirm()
self.assertEqual(move1.state, 'assigned')
self.assertEqual(len(move2.move_line_ids), 1)
# check if the putaway wasn't applied
self.assertEqual(move2.move_line_ids.location_dest_id.id, self.stock_location.id)
def test_putaway_with_storage_category_3(self):
"""Received products twice, set storage category to only accept new
product when empty. Check the first time putaway rule applied and second
time not.
"""
storage_category = self.env['stock.storage.category'].create({
'name': "storage category",
'allow_new_product': "empty",
})
shelf1_location = self.env['stock.location'].create({
'name': 'shelf1',
'usage': 'internal',
'location_id': self.stock_location.id,
'storage_category_id': storage_category.id,
})
# putaway from stock to child location with storage_category
putaway = self.env['stock.putaway.rule'].create({
'product_id': self.product.id,
'location_in_id': self.stock_location.id,
'location_out_id': self.stock_location.id,
'storage_category_id': storage_category.id,
})
self.stock_location.write({
'putaway_rule_ids': [(4, putaway.id, 0)],
})
# first move
move1 = self.env['stock.move'].create({
'name': 'test_move_1',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 100.0,
})
move1._action_confirm()
self.assertEqual(move1.state, 'assigned')
self.assertEqual(len(move1.move_line_ids), 1)
move_line = move1.move_line_ids[0]
move_line.qty_done = 100
move1._action_done()
self.assertEqual(move1.state, 'done')
# check if the putaway was rightly applied
self.assertEqual(move1.move_line_ids.location_dest_id.id, shelf1_location.id)
# second move
move2 = self.env['stock.move'].create({
'name': 'test_move_2',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 100.0,
})
move2._action_confirm()
self.assertEqual(move2.state, 'assigned')
self.assertEqual(len(move2.move_line_ids), 1)
# check if the putaway wasn't applied
self.assertEqual(move2.move_line_ids.location_dest_id.id, self.stock_location.id)
def test_putaway_with_storage_category_4(self):
"""Received products, set storage category to only accept same product.
Check the putaway rule can't be applied when the location has different
products.
"""
storage_category = self.env['stock.storage.category'].create({
'name': "storage category",
'allow_new_product': "same",
})
shelf1_location = self.env['stock.location'].create({
'name': 'shelf1',
'usage': 'internal',
'location_id': self.stock_location.id,
'storage_category_id': storage_category.id,
})
# putaway from stock to child location with storage_category
putaway = self.env['stock.putaway.rule'].create({
'product_id': self.product.id,
'location_in_id': self.stock_location.id,
'location_out_id': self.stock_location.id,
'storage_category_id': storage_category.id,
})
self.stock_location.write({
'putaway_rule_ids': [(4, putaway.id, 0)],
})
# create a different product and its quant
product2 = self.env['product.product'].create({
'name': 'Product 2',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
})
self.env['stock.quant'].create({
'product_id': product2.id,
'product_uom_id': self.uom_unit.id,
'location_id': shelf1_location.id,
'quantity': 1,
'reserved_quantity': 0,
})
move1 = self.env['stock.move'].create({
'name': 'test_move_1',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 100.0,
})
move1._action_confirm()
self.assertEqual(move1.state, 'assigned')
self.assertEqual(len(move1.move_line_ids), 1)
move_line = move1.move_line_ids[0]
move_line.qty_done = 100
move1._action_done()
self.assertEqual(move1.state, 'done')
# check if the putaway can't be applied
self.assertEqual(move1.move_line_ids.location_dest_id.id, self.stock_location.id)
def test_putaway_with_storage_category_5(self):
"""Receive a package. Test the package will be move to a child location
with correct storage category.
"""
# storage category
storage_category = self.env['stock.storage.category'].create({
'name': "storage category"
})
package_type = self.env['stock.package.type'].create({
'name': "package type",
})
self.env['stock.location'].create({
'name': 'shelf1',
'usage': 'internal',
'location_id': self.stock_location.id,
})
shelf2_location = self.env['stock.location'].create({
'name': 'shelf2',
'usage': 'internal',
'location_id': self.stock_location.id,
'storage_category_id': storage_category.id,
})
# putaway from stock to child location with storage_category
putaway = self.env['stock.putaway.rule'].create({
'product_id': self.product.id,
'location_in_id': self.stock_location.id,
'location_out_id': self.stock_location.id,
'storage_category_id': storage_category.id,
'package_type_ids': [(4, package_type.id, 0)],
})
self.stock_location.write({
'putaway_rule_ids': [(4, putaway.id, 0)],
})
package = self.env['stock.quant.package'].create({
'name': 'package',
'package_type_id': package_type.id,
})
move1 = self.env['stock.move'].create({
'name': 'test_move_1',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 100.0,
})
move1._action_confirm()
self.assertEqual(move1.state, 'assigned')
self.assertEqual(len(move1.move_line_ids), 1)
move_form = Form(move1, view='stock.view_stock_move_nosuggest_operations')
with move_form.move_line_nosuggest_ids.new() as line:
line.result_package_id = package
line.qty_done = 100
move1 = move_form.save()
move1._action_done()
# check if the putaway was rightly applied
self.assertEqual(package.location_id.id, shelf2_location.id)
def test_putaway_with_storage_category_6(self):
"""Receive package with same package type twice. Check putaway rule can
be applied on the first one but not the second one due to no space.
"""
# storage category
storage_category = self.env['stock.storage.category'].create({
'name': "storage category"
})
package_type = self.env['stock.package.type'].create({
'name': "package type",
})
# set the capacity for the package type in this storage category to be 1
storage_category_form = Form(storage_category, view='stock.stock_storage_category_form')
with storage_category_form.package_capacity_ids.new() as line:
line.package_type_id = package_type
line.quantity = 1
storage_category = storage_category_form.save()
self.env['stock.location'].create({
'name': 'shelf1',
'usage': 'internal',
'location_id': self.stock_location.id,
})
shelf2_location = self.env['stock.location'].create({
'name': 'shelf2',
'usage': 'internal',
'location_id': self.stock_location.id,
'storage_category_id': storage_category.id,
})
# putaway from stock to child location with storage_category
putaway = self.env['stock.putaway.rule'].create({
'product_id': self.product.id,
'location_in_id': self.stock_location.id,
'location_out_id': self.stock_location.id,
'storage_category_id': storage_category.id,
'package_type_ids': [(4, package_type.id, 0)],
})
self.stock_location.write({
'putaway_rule_ids': [(4, putaway.id, 0)],
})
# first package
package1 = self.env['stock.quant.package'].create({
'name': 'package 1',
'package_type_id': package_type.id,
})
move1 = self.env['stock.move'].create({
'name': 'test_move_1',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 100.0,
})
move1._action_confirm()
self.assertEqual(move1.state, 'assigned')
self.assertEqual(len(move1.move_line_ids), 1)
move_form = Form(move1, view='stock.view_stock_move_nosuggest_operations')
with move_form.move_line_nosuggest_ids.new() as line:
line.result_package_id = package1
line.qty_done = 100
move1 = move_form.save()
move1._action_done()
# check if the putaway was rightly applied
self.assertEqual(package1.location_id.id, shelf2_location.id)
# second package
package2 = self.env['stock.quant.package'].create({
'name': 'package 2',
'package_type_id': package_type.id,
})
move2 = self.env['stock.move'].create({
'name': 'test_move_2',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 100.0,
})
move2._action_confirm()
self.assertEqual(move2.state, 'assigned')
self.assertEqual(len(move2.move_line_ids), 1)
move_form = Form(move2, view='stock.view_stock_move_nosuggest_operations')
with move_form.move_line_nosuggest_ids.new() as line:
line.result_package_id = package2
line.qty_done = 100
move2 = move_form.save()
move2._action_done()
# check if the putaway wasn't applied
self.assertEqual(package2.location_id.id, self.stock_location.id)
def test_putaway_with_storage_category_7(self):
"""Receive package with same package type twice, set storage category to
only accept new product when empty. Check putaway rule can be applied on
the first one but not the second one.
"""
# storage category
storage_category = self.env['stock.storage.category'].create({
'name': "storage category",
'allow_new_product': "empty",
})
package_type = self.env['stock.package.type'].create({
'name': "package type",
})
# set the capacity for the package type in this storage category to be 100
storage_category_form = Form(storage_category, view='stock.stock_storage_category_form')
with storage_category_form.package_capacity_ids.new() as line:
line.package_type_id = package_type
line.quantity = 100
storage_category = storage_category_form.save()
self.env['stock.location'].create({
'name': 'shelf1',
'usage': 'internal',
'location_id': self.stock_location.id,
})
shelf2_location = self.env['stock.location'].create({
'name': 'shelf2',
'usage': 'internal',
'location_id': self.stock_location.id,
'storage_category_id': storage_category.id,
})
# putaway from stock to child location with storage_category
putaway = self.env['stock.putaway.rule'].create({
'product_id': self.product.id,
'location_in_id': self.stock_location.id,
'location_out_id': self.stock_location.id,
'storage_category_id': storage_category.id,
'package_type_ids': [(4, package_type.id, 0)],
})
self.stock_location.write({
'putaway_rule_ids': [(4, putaway.id, 0)],
})
# first package
package1 = self.env['stock.quant.package'].create({
'name': 'package 1',
'package_type_id': package_type.id,
})
move1 = self.env['stock.move'].create({
'name': 'test_move_1',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 100.0,
})
move1._action_confirm()
self.assertEqual(move1.state, 'assigned')
self.assertEqual(len(move1.move_line_ids), 1)
move_form = Form(move1, view='stock.view_stock_move_nosuggest_operations')
with move_form.move_line_nosuggest_ids.new() as line:
line.result_package_id = package1
line.qty_done = 100
move1 = move_form.save()
move1._action_done()
# check if the putaway was rightly applied
self.assertEqual(package1.location_id.id, shelf2_location.id)
# second package
package2 = self.env['stock.quant.package'].create({
'name': 'package 2',
'package_type_id': package_type.id,
})
move2 = self.env['stock.move'].create({
'name': 'test_move_2',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 100.0,
})
move2._action_confirm()
self.assertEqual(move2.state, 'assigned')
self.assertEqual(len(move2.move_line_ids), 1)
move_form = Form(move2, view='stock.view_stock_move_nosuggest_operations')
with move_form.move_line_nosuggest_ids.new() as line:
line.result_package_id = package2
line.qty_done = 100
move2 = move_form.save()
move2._action_done()
# check if the putaway wasn't applied
self.assertEqual(package2.location_id.id, self.stock_location.id)
def test_putaway_with_storage_category_8(self):
"""Receive package withs different products, set storage category to only
accept same product. Check putaway rule can be applied on the first one
but not the second one.
"""
# storage category
storage_category = self.env['stock.storage.category'].create({
'name': "storage category",
'allow_new_product': "same",
})
package_type = self.env['stock.package.type'].create({
'name': "package type",
})
# set the capacity for the package type in this storage category to be 100
storage_category_form = Form(storage_category, view='stock.stock_storage_category_form')
with storage_category_form.package_capacity_ids.new() as line:
line.package_type_id = package_type
line.quantity = 100
storage_category = storage_category_form.save()
self.env['stock.location'].create({
'name': 'shelf1',
'usage': 'internal',
'location_id': self.stock_location.id,
})
shelf2_location = self.env['stock.location'].create({
'name': 'shelf2',
'usage': 'internal',
'location_id': self.stock_location.id,
'storage_category_id': storage_category.id,
})
# putaway from stock to child location for package type
putaway = self.env['stock.putaway.rule'].create({
'location_in_id': self.stock_location.id,
'location_out_id': self.stock_location.id,
'storage_category_id': storage_category.id,
'package_type_ids': [(4, package_type.id, 0)],
})
self.stock_location.write({
'putaway_rule_ids': [(4, putaway.id, 0)],
})
# first package
package1 = self.env['stock.quant.package'].create({
'name': 'package 1',
'package_type_id': package_type.id,
})
move1 = self.env['stock.move'].create({
'name': 'test_move_1',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 100.0,
})
move1._action_confirm()
self.assertEqual(move1.state, 'assigned')
self.assertEqual(len(move1.move_line_ids), 1)
move_form = Form(move1, view='stock.view_stock_move_nosuggest_operations')
with move_form.move_line_nosuggest_ids.new() as line:
line.result_package_id = package1
line.qty_done = 100
move1 = move_form.save()
move1._action_done()
# check if the putaway was rightly applied
self.assertEqual(package1.location_id.id, shelf2_location.id)
# second package
package2 = self.env['stock.quant.package'].create({
'name': 'package 2',
'package_type_id': package_type.id,
})
product2 = self.env['product.product'].create({
'name': 'Product 2',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
})
move2 = self.env['stock.move'].create({
'name': 'test_move_2',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': product2.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 100.0,
})
move2._action_confirm()
self.assertEqual(move2.state, 'assigned')
self.assertEqual(len(move2.move_line_ids), 1)
move_form = Form(move2, view='stock.view_stock_move_nosuggest_operations')
with move_form.move_line_nosuggest_ids.new() as line:
line.result_package_id = package2
line.qty_done = 100
move2 = move_form.save()
move2._action_done()
# check if the putaway wasn't applied
self.assertEqual(package2.location_id.id, self.stock_location.id)
def test_putaway_with_storage_category_9(self):
"""Receive a product twice. Test first time the putaway applied, and second
time it is not since the products violate the max_weight limitaion.
"""
self.product.weight = 1
storage_category = self.env['stock.storage.category'].create({
'name': "storage category",
'max_weight': 100,
})
shelf1_location = self.env['stock.location'].create({
'name': 'shelf1',
'usage': 'internal',
'location_id': self.stock_location.id,
'storage_category_id': storage_category.id,
})
# putaway from stock to child location with storage_category
putaway = self.env['stock.putaway.rule'].create({
'product_id': self.product.id,
'location_in_id': self.stock_location.id,
'location_out_id': self.stock_location.id,
'storage_category_id': storage_category.id,
})
self.stock_location.write({
'putaway_rule_ids': [(4, putaway.id, 0)],
})
# first move
move1 = self.env['stock.move'].create({
'name': 'test_move_1',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 100.0,
})
move1._action_confirm()
self.assertEqual(move1.state, 'assigned')
self.assertEqual(len(move1.move_line_ids), 1)
# check if the putaway was rightly applied
self.assertEqual(move1.move_line_ids.location_dest_id.id, shelf1_location.id)
# second move
move2 = self.env['stock.move'].create({
'name': 'test_move_2',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 100.0,
})
move2._action_confirm()
self.assertEqual(move1.state, 'assigned')
self.assertEqual(len(move2.move_line_ids), 1)
# check if the putaway wasn't applied since there are already 100kg products in the location
self.assertEqual(move2.move_line_ids.location_dest_id.id, self.stock_location.id)
def test_availability_1(self):
""" Check that the `availability` field on a move is correctly computed when there is
more than enough products in stock.
"""
# make some stock
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 150.0)
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location)), 1.0)
move1 = self.env['stock.move'].create({
'name': 'test_putaway_1',
'location_id': self.stock_location.id,
'location_dest_id': self.supplier_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 100.0,
})
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 150.0)
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location)), 1.0)
self.assertEqual(move1.availability, 100.0)
def test_availability_2(self):
""" Check that the `availability` field on a move is correctly computed when there is
not enough products in stock.
"""
# make some stock
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 50.0)
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location)), 1.0)
move1 = self.env['stock.move'].create({
'name': 'test_putaway_1',
'location_id': self.stock_location.id,
'location_dest_id': self.supplier_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 100.0,
})
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 50.0)
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location)), 1.0)
self.assertEqual(move1.availability, 50.0)
def test_availability_3(self):
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
lot2 = self.env['stock.production.lot'].create({
'name': 'lot2',
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
self.env['stock.quant']._update_available_quantity(self.product_serial, self.stock_location, -1.0, lot_id=lot1)
self.env['stock.quant']._update_available_quantity(self.product_serial, self.stock_location, 1.0, lot_id=lot2)
move1 = self.env['stock.move'].create({
'name': 'test_availability_3',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product_serial.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move1._action_confirm()
move1._action_assign()
self.assertEqual(move1.state, 'assigned')
self.assertEqual(move1.reserved_availability, 1.0)
def test_availability_4(self):
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 30.0)
move1 = self.env['stock.move'].create({
'name': 'test_availability_4',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 15.0,
})
move1._action_confirm()
move1._action_assign()
self.assertEqual(move1.state, 'assigned')
move2 = self.env['stock.move'].create({
'name': 'test_availability_4',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 15.0,
})
move2._action_confirm()
move2._action_assign()
# set 15 as quantity done for the first and 30 as the second
move1.move_line_ids.qty_done = 15
move2.move_line_ids.qty_done = 30
# validate the second, the first should be unreserved
move2._action_done()
self.assertEqual(move1.state, 'confirmed')
self.assertEqual(move1.move_line_ids.qty_done, 15)
self.assertEqual(move2.state, 'done')
stock_quants = self.gather_relevant(self.product, self.stock_location)
self.assertEqual(len(stock_quants), 0)
customer_quants = self.gather_relevant(self.product, self.customer_location)
self.assertEqual(customer_quants.quantity, 30)
self.assertEqual(customer_quants.reserved_quantity, 0)
def test_availability_5(self):
""" Check that rerun action assign only create new stock move
lines instead of adding quantity in existing one.
"""
self.env['stock.quant']._update_available_quantity(self.product_serial, self.stock_location, 2.0)
# move from shelf1
move = self.env['stock.move'].create({
'name': 'test_edit_moveline_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product_serial.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 4.0,
})
move._action_confirm()
move._action_assign()
self.env['stock.quant']._update_available_quantity(self.product_serial, self.stock_location, 4.0)
move._action_assign()
self.assertEqual(len(move.move_line_ids), 4.0)
def test_availability_6(self):
""" Check that, in the scenario where a move is in a bigger uom than the uom of the quants
and this uom only allows entire numbers, we don't make a partial reservation when the
quantity available is not enough to reserve the move. Check also that it is not possible
to set `quantity_done` with a value not honouring the UOM's rounding.
"""
# on the dozen uom, set the rounding set 1.0
self.uom_dozen.rounding = 1
# 6 units are available in stock
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 6.0)
# the move should not be reserved
move = self.env['stock.move'].create({
'name': 'test_availability_6',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_dozen.id,
'product_uom_qty': 1,
})
move._action_confirm()
move._action_assign()
self.assertEqual(move.state, 'confirmed')
# the quants should be left untouched
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 6.0)
# make 8 units available, the move should again not be reservabale
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 2.0)
move._action_assign()
self.assertEqual(move.state, 'confirmed')
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 8.0)
# make 12 units available, this time the move should be reservable
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 4.0)
move._action_assign()
self.assertEqual(move.state, 'assigned')
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0.0)
# Check it isn't possible to set any value to quantity_done
with self.assertRaises(UserError):
move.quantity_done = 0.1
move._action_done()
with self.assertRaises(UserError):
move.quantity_done = 1.1
move._action_done()
with self.assertRaises(UserError):
move.quantity_done = 0.9
move._action_done()
move.quantity_done = 1
move._action_done()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.customer_location), 12.0)
def test_availability_7(self):
""" Check that, in the scenario where a move is in a bigger uom than the uom of the quants
and this uom only allows entire numbers, we only reserve quantity honouring the uom's
rounding even if the quantity is set across multiple quants.
"""
# on the dozen uom, set the rounding set 1.0
self.uom_dozen.rounding = 1
# make 12 quants of 1
for i in range(1, 13):
lot_id = self.env['stock.production.lot'].create({
'name': 'lot%s' % str(i),
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
self.env['stock.quant']._update_available_quantity(self.product_serial, self.stock_location, 1.0, lot_id=lot_id)
# the move should be reserved
move = self.env['stock.move'].create({
'name': 'test_availability_7',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product_serial.id,
'product_uom': self.uom_dozen.id,
'product_uom_qty': 1,
})
move._action_confirm()
move._action_assign()
self.assertEqual(move.state, 'assigned')
self.assertEqual(len(move.move_line_ids.mapped('product_uom_id')), 1)
self.assertEqual(move.move_line_ids.mapped('product_uom_id'), self.uom_unit)
for move_line in move.move_line_ids:
move_line.qty_done = 1
move._action_done()
self.assertEqual(move.product_uom_qty, 1)
self.assertEqual(move.product_uom.id, self.uom_dozen.id)
self.assertEqual(move.state, 'done')
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.customer_location), 12.0)
self.assertEqual(len(self.gather_relevant(self.product_serial, self.customer_location)), 12)
def test_availability_8(self):
""" Test the assignment mechanism when the product quantity is decreased on a partially
reserved stock move.
"""
# make some stock
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 3.0)
self.assertAlmostEqual(self.product.qty_available, 3.0)
move_partial = self.env['stock.move'].create({
'name': 'test_partial',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 5.0,
})
move_partial._action_confirm()
move_partial._action_assign()
self.assertAlmostEqual(self.product.virtual_available, -2.0)
self.assertEqual(move_partial.state, 'partially_available')
move_partial.product_uom_qty = 3.0
move_partial._action_assign()
self.assertEqual(move_partial.state, 'assigned')
def test_availability_9(self):
""" Test the assignment mechanism when the product quantity is increase
on a receipt move.
"""
move_receipt = self.env['stock.move'].create({
'name': 'test_receipt_edit',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_dozen.id,
'product_uom_qty': 1.0,
})
move_receipt._action_confirm()
move_receipt._action_assign()
self.assertEqual(move_receipt.state, 'assigned')
move_receipt.product_uom_qty = 3.0
move_receipt._action_assign()
self.assertEqual(move_receipt.state, 'assigned')
self.assertEqual(move_receipt.move_line_ids.product_uom_qty, 3)
def test_unreserve_1(self):
""" Check that unreserving a stock move sets the products reserved as available and
set the state back to confirmed.
"""
# make some stock
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 150.0)
# creation
move1 = self.env['stock.move'].create({
'name': 'test_putaway_1',
'location_id': self.stock_location.id,
'location_dest_id': self.supplier_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 100.0,
})
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 150.0)
self.assertEqual(move1.availability, 100.0)
# confirmation
move1._action_confirm()
self.assertEqual(move1.state, 'confirmed')
# assignment
move1._action_assign()
self.assertEqual(move1.state, 'assigned')
self.assertEqual(len(move1.move_line_ids), 1)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 50.0)
# unreserve
move1._do_unreserve()
self.assertEqual(len(move1.move_line_ids), 0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 150.0)
self.assertEqual(move1.state, 'confirmed')
def test_unreserve_2(self):
""" Check that unreserving a stock move sets the products reserved as available and
set the state back to confirmed even if they are in a pack.
"""
package1 = self.env['stock.quant.package'].create({'name': 'test_unreserve_2_pack'})
# make some stock
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 150.0, package_id=package1)
# creation
move1 = self.env['stock.move'].create({
'name': 'test_putaway_1',
'location_id': self.stock_location.id,
'location_dest_id': self.supplier_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 100.0,
})
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, package_id=package1), 150.0)
self.assertEqual(move1.availability, 100.0)
# confirmation
move1._action_confirm()
self.assertEqual(move1.state, 'confirmed')
# assignment
move1._action_assign()
self.assertEqual(move1.state, 'assigned')
self.assertEqual(len(move1.move_line_ids), 1)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, package_id=package1), 50.0)
# unreserve
move1._do_unreserve()
self.assertEqual(len(move1.move_line_ids), 0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, package_id=package1), 150.0)
self.assertEqual(move1.state, 'confirmed')
def test_unreserve_3(self):
""" Similar to `test_unreserve_1` but checking the quants more in details.
"""
# make some stock
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 2)
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location)), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 2)
# creation
move1 = self.env['stock.move'].create({
'name': 'test_out_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 2.0,
})
self.assertEqual(move1.state, 'draft')
# confirmation
move1._action_confirm()
self.assertEqual(move1.state, 'confirmed')
# assignment
move1._action_assign()
self.assertEqual(move1.state, 'assigned')
self.assertEqual(len(move1.move_line_ids), 1)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0.0)
quants = self.gather_relevant(self.product, self.stock_location)
self.assertEqual(len(quants), 1.0)
self.assertEqual(quants.quantity, 2.0)
self.assertEqual(quants.reserved_quantity, 2.0)
move1._do_unreserve()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 2.0)
self.assertEqual(len(quants), 1.0)
self.assertEqual(quants.quantity, 2.0)
self.assertEqual(quants.reserved_quantity, 0.0)
self.assertEqual(len(move1.move_line_ids), 0.0)
def test_unreserve_4(self):
""" Check the unreservation of a partially available stock move.
"""
# make some stock
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 2)
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location)), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 2)
# creation
move1 = self.env['stock.move'].create({
'name': 'test_out_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 3.0,
})
self.assertEqual(move1.state, 'draft')
# confirmation
move1._action_confirm()
self.assertEqual(move1.state, 'confirmed')
# assignment
move1._action_assign()
self.assertEqual(move1.state, 'partially_available')
self.assertEqual(len(move1.move_line_ids), 1)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0.0)
quants = self.gather_relevant(self.product, self.stock_location)
self.assertEqual(len(quants), 1.0)
self.assertEqual(quants.quantity, 2.0)
self.assertEqual(quants.reserved_quantity, 2.0)
move1._do_unreserve()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 2.0)
self.assertEqual(len(quants), 1.0)
self.assertEqual(quants.quantity, 2.0)
self.assertEqual(quants.reserved_quantity, 0.0)
self.assertEqual(len(move1.move_line_ids), 0.0)
def test_unreserve_5(self):
""" Check the unreservation of a stock move reserved on multiple quants.
"""
# make some stock
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 3)
self.env['stock.quant'].create({
'product_id': self.product.id,
'location_id': self.stock_location.id,
'quantity': 2,
})
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location)), 2)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 5)
# creation
move1 = self.env['stock.move'].create({
'name': 'test_unreserve_5',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 5.0,
})
self.assertEqual(move1.state, 'draft')
# confirmation
move1._action_confirm()
self.assertEqual(move1.state, 'confirmed')
# assignment
move1._action_assign()
self.assertEqual(move1.state, 'assigned')
self.assertEqual(len(move1.move_line_ids), 1)
move1._do_unreserve()
quants = self.gather_relevant(self.product, self.stock_location)
self.assertEqual(len(quants), 2.0)
for quant in quants:
self.assertEqual(quant.reserved_quantity, 0)
def test_unreserve_6(self):
""" In a situation with a negative and a positive quant, reserve and unreserve.
"""
q1 = self.env['stock.quant'].create({
'product_id': self.product.id,
'location_id': self.stock_location.id,
'quantity': -10,
'reserved_quantity': 0,
})
q2 = self.env['stock.quant'].create({
'product_id': self.product.id,
'location_id': self.stock_location.id,
'quantity': 30.0,
'reserved_quantity': 10.0,
})
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 10.0)
move1 = self.env['stock.move'].create({
'name': 'test_unreserve_6',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
})
move1._action_confirm()
move1._action_assign()
self.assertEqual(move1.state, 'assigned')
self.assertEqual(len(move1.move_line_ids), 1)
self.assertEqual(move1.move_line_ids.product_qty, 10)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0.0)
self.assertEqual(q2.reserved_quantity, 20)
move1._do_unreserve()
self.assertEqual(move1.state, 'confirmed')
self.assertEqual(len(move1.move_line_ids), 0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 10.0)
self.assertEqual(q2.reserved_quantity, 10)
def test_unreserve_7(self):
""" Check the unreservation of a stock move delete only stock move lines
without quantity done.
"""
product = self.env['product.product'].create({
'name': 'product',
'tracking': 'serial',
'type': 'product',
})
serial_numbers = self.env['stock.production.lot'].create([{
'name': str(x),
'product_id': product.id,
'company_id': self.env.company.id,
} for x in range(5)])
for serial in serial_numbers:
self.env['stock.quant'].create({
'product_id': product.id,
'location_id': self.stock_location.id,
'quantity': 1.0,
'lot_id': serial.id,
'reserved_quantity': 0.0,
})
move1 = self.env['stock.move'].create({
'name': 'test_unreserve_7',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': product.id,
'product_uom': product.uom_id.id,
'product_uom_qty': 5.0,
})
move1._action_confirm()
move1._action_assign()
self.assertEqual(move1.state, 'assigned')
self.assertEqual(len(move1.move_line_ids), 5)
self.assertEqual(self.env['stock.quant']._get_available_quantity(product, self.stock_location), 0.0)
# Check state is changed even with 0 move lines unlinked
move1.move_line_ids.write({'qty_done': 1})
move1._do_unreserve()
self.assertEqual(len(move1.move_line_ids), 5)
self.assertEqual(move1.state, 'confirmed')
move1._action_assign()
# set a quantity done on the two first move lines
move1.move_line_ids.write({'qty_done': 0})
move1.move_line_ids[0].qty_done = 1
move1.move_line_ids[1].qty_done = 1
move1._do_unreserve()
self.assertEqual(move1.state, 'confirmed')
self.assertEqual(len(move1.move_line_ids), 2)
self.assertEqual(move1.move_line_ids.mapped('qty_done'), [1, 1])
self.assertEqual(move1.move_line_ids.mapped('product_uom_qty'), [0, 0])
def test_link_assign_1(self):
""" Test the assignment mechanism when two chained stock moves try to move one unit of an
untracked product.
"""
# make some stock
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1.0)
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location)), 1.0)
move_stock_pack = self.env['stock.move'].create({
'name': 'test_link_assign_1_1',
'location_id': self.stock_location.id,
'location_dest_id': self.pack_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move_pack_cust = self.env['stock.move'].create({
'name': 'test_link_assign_1_2',
'location_id': self.pack_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move_stock_pack.write({'move_dest_ids': [(4, move_pack_cust.id, 0)]})
move_pack_cust.write({'move_orig_ids': [(4, move_stock_pack.id, 0)]})
(move_stock_pack + move_pack_cust)._action_confirm()
move_stock_pack._action_assign()
move_stock_pack.move_line_ids[0].qty_done = 1.0
move_stock_pack._action_done()
self.assertEqual(len(move_pack_cust.move_line_ids), 1)
move_line = move_pack_cust.move_line_ids[0]
self.assertEqual(move_line.location_id.id, self.pack_location.id)
self.assertEqual(move_line.location_dest_id.id, self.customer_location.id)
self.assertEqual(move_pack_cust.state, 'assigned')
def test_link_assign_2(self):
""" Test the assignment mechanism when two chained stock moves try to move one unit of a
tracked product.
"""
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.product.id,
'company_id': self.env.company.id,
})
# make some stock
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1.0, lot_id=lot1)
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location, lot1)), 1.0)
move_stock_pack = self.env['stock.move'].create({
'name': 'test_link_2_1',
'location_id': self.stock_location.id,
'location_dest_id': self.pack_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move_pack_cust = self.env['stock.move'].create({
'name': 'test_link_2_2',
'location_id': self.pack_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move_stock_pack.write({'move_dest_ids': [(4, move_pack_cust.id, 0)]})
move_pack_cust.write({'move_orig_ids': [(4, move_stock_pack.id, 0)]})
(move_stock_pack + move_pack_cust)._action_confirm()
move_stock_pack._action_assign()
move_line_stock_pack = move_stock_pack.move_line_ids[0]
self.assertEqual(move_line_stock_pack.lot_id.id, lot1.id)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, lot_id=lot1), 0.0)
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location, lot1)), 1.0)
self.assertEqual(len(self.gather_relevant(self.product, self.pack_location, lot1)), 0.0)
move_line_stock_pack.qty_done = 1.0
move_stock_pack._action_done()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, lot_id=lot1), 0.0)
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location, lot1)), 0.0)
move_line_pack_cust = move_pack_cust.move_line_ids[0]
self.assertEqual(move_line_pack_cust.lot_id.id, lot1.id)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.pack_location, lot_id=lot1), 0.0)
self.assertEqual(len(self.gather_relevant(self.product, self.pack_location, lot1)), 1.0)
def test_link_assign_3(self):
""" Test the assignment mechanism when three chained stock moves (2 sources, 1 dest) try to
move multiple units of an untracked product.
"""
# make some stock
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 2.0)
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location)), 1.0)
move_stock_pack_1 = self.env['stock.move'].create({
'name': 'test_link_assign_1_1',
'location_id': self.stock_location.id,
'location_dest_id': self.pack_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move_stock_pack_2 = self.env['stock.move'].create({
'name': 'test_link_assign_1_1',
'location_id': self.stock_location.id,
'location_dest_id': self.pack_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move_pack_cust = self.env['stock.move'].create({
'name': 'test_link_assign_1_2',
'location_id': self.pack_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 2.0,
})
move_stock_pack_1.write({'move_dest_ids': [(4, move_pack_cust.id, 0)]})
move_stock_pack_2.write({'move_dest_ids': [(4, move_pack_cust.id, 0)]})
move_pack_cust.write({'move_orig_ids': [(4, move_stock_pack_1.id, 0), (4, move_stock_pack_2.id, 0)]})
(move_stock_pack_1 + move_stock_pack_2 + move_pack_cust)._action_confirm()
# assign and fulfill the first move
move_stock_pack_1._action_assign()
self.assertEqual(move_stock_pack_1.state, 'assigned')
self.assertEqual(len(move_stock_pack_1.move_line_ids), 1)
move_stock_pack_1.move_line_ids[0].qty_done = 1.0
move_stock_pack_1._action_done()
self.assertEqual(move_stock_pack_1.state, 'done')
# the destination move should be partially available and have one move line
self.assertEqual(move_pack_cust.state, 'partially_available')
self.assertEqual(len(move_pack_cust.move_line_ids), 1)
# Should have 1 quant in stock_location and another in pack_location
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location)), 1.0)
self.assertEqual(len(self.gather_relevant(self.product, self.pack_location)), 1.0)
move_stock_pack_2._action_assign()
self.assertEqual(move_stock_pack_2.state, 'assigned')
self.assertEqual(len(move_stock_pack_2.move_line_ids), 1)
move_stock_pack_2.move_line_ids[0].qty_done = 1.0
move_stock_pack_2._action_done()
self.assertEqual(move_stock_pack_2.state, 'done')
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location)), 0.0)
self.assertEqual(len(self.gather_relevant(self.product, self.pack_location)), 1.0)
self.assertEqual(move_pack_cust.state, 'assigned')
self.assertEqual(len(move_pack_cust.move_line_ids), 1)
move_line_1 = move_pack_cust.move_line_ids[0]
self.assertEqual(move_line_1.location_id.id, self.pack_location.id)
self.assertEqual(move_line_1.location_dest_id.id, self.customer_location.id)
self.assertEqual(move_line_1.product_qty, 2.0)
self.assertEqual(move_pack_cust.state, 'assigned')
def test_link_assign_4(self):
""" Test the assignment mechanism when three chained stock moves (2 sources, 1 dest) try to
move multiple units of a tracked by lot product.
"""
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.product.id,
'company_id': self.env.company.id,
})
# make some stock
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 2.0, lot_id=lot1)
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location, lot1)), 1.0)
move_stock_pack_1 = self.env['stock.move'].create({
'name': 'test_link_assign_1_1',
'location_id': self.stock_location.id,
'location_dest_id': self.pack_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move_stock_pack_2 = self.env['stock.move'].create({
'name': 'test_link_assign_1_1',
'location_id': self.stock_location.id,
'location_dest_id': self.pack_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move_pack_cust = self.env['stock.move'].create({
'name': 'test_link_assign_1_2',
'location_id': self.pack_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 2.0,
})
move_stock_pack_1.write({'move_dest_ids': [(4, move_pack_cust.id, 0)]})
move_stock_pack_2.write({'move_dest_ids': [(4, move_pack_cust.id, 0)]})
move_pack_cust.write({'move_orig_ids': [(4, move_stock_pack_1.id, 0), (4, move_stock_pack_2.id, 0)]})
(move_stock_pack_1 + move_stock_pack_2 + move_pack_cust)._action_confirm()
# assign and fulfill the first move
move_stock_pack_1._action_assign()
self.assertEqual(len(move_stock_pack_1.move_line_ids), 1)
self.assertEqual(move_stock_pack_1.move_line_ids[0].lot_id.id, lot1.id)
move_stock_pack_1.move_line_ids[0].qty_done = 1.0
move_stock_pack_1._action_done()
# the destination move should be partially available and have one move line
self.assertEqual(len(move_pack_cust.move_line_ids), 1)
move_stock_pack_2._action_assign()
self.assertEqual(len(move_stock_pack_2.move_line_ids), 1)
self.assertEqual(move_stock_pack_2.move_line_ids[0].lot_id.id, lot1.id)
move_stock_pack_2.move_line_ids[0].qty_done = 1.0
move_stock_pack_2._action_done()
self.assertEqual(len(move_pack_cust.move_line_ids), 1)
move_line_1 = move_pack_cust.move_line_ids[0]
self.assertEqual(move_line_1.location_id.id, self.pack_location.id)
self.assertEqual(move_line_1.location_dest_id.id, self.customer_location.id)
self.assertEqual(move_line_1.product_qty, 2.0)
self.assertEqual(move_line_1.lot_id.id, lot1.id)
self.assertEqual(move_pack_cust.state, 'assigned')
def test_link_assign_5(self):
""" Test the assignment mechanism when three chained stock moves (1 sources, 2 dest) try to
move multiple units of an untracked product.
"""
# make some stock
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 2.0)
move_stock_pack = self.env['stock.move'].create({
'name': 'test_link_assign_1_1',
'location_id': self.stock_location.id,
'location_dest_id': self.pack_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 2.0,
})
move_pack_cust_1 = self.env['stock.move'].create({
'name': 'test_link_assign_1_1',
'location_id': self.pack_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move_pack_cust_2 = self.env['stock.move'].create({
'name': 'test_link_assign_1_2',
'location_id': self.pack_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move_stock_pack.write({'move_dest_ids': [(4, move_pack_cust_1.id, 0), (4, move_pack_cust_2.id, 0)]})
move_pack_cust_1.write({'move_orig_ids': [(4, move_stock_pack.id, 0)]})
move_pack_cust_2.write({'move_orig_ids': [(4, move_stock_pack.id, 0)]})
(move_stock_pack + move_pack_cust_1 + move_pack_cust_2)._action_confirm()
# assign and fulfill the first move
move_stock_pack._action_assign()
self.assertEqual(len(move_stock_pack.move_line_ids), 1)
move_stock_pack.move_line_ids[0].qty_done = 2.0
move_stock_pack._action_done()
# the destination moves should be available and have one move line
self.assertEqual(len(move_pack_cust_1.move_line_ids), 1)
self.assertEqual(len(move_pack_cust_2.move_line_ids), 1)
move_pack_cust_1.move_line_ids[0].qty_done = 1.0
move_pack_cust_2.move_line_ids[0].qty_done = 1.0
(move_pack_cust_1 + move_pack_cust_2)._action_done()
def test_link_assign_6(self):
""" Test the assignment mechanism when four chained stock moves (2 sources, 2 dest) try to
move multiple units of an untracked by lot product. This particular test case simulates a two
step receipts with backorder.
"""
move_supp_stock_1 = self.env['stock.move'].create({
'name': 'test_link_assign_6_1',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 3.0,
})
move_supp_stock_2 = self.env['stock.move'].create({
'name': 'test_link_assign_6_1',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 2.0,
})
move_stock_stock_1 = self.env['stock.move'].create({
'name': 'test_link_assign_6_1',
'location_id': self.stock_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 3.0,
})
move_stock_stock_1.write({'move_orig_ids': [(4, move_supp_stock_1.id, 0), (4, move_supp_stock_2.id, 0)]})
move_stock_stock_2 = self.env['stock.move'].create({
'name': 'test_link_assign_6_1',
'location_id': self.stock_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 3.0,
})
move_stock_stock_2.write({'move_orig_ids': [(4, move_supp_stock_1.id, 0), (4, move_supp_stock_2.id, 0)]})
(move_supp_stock_1 + move_supp_stock_2 + move_stock_stock_1 + move_stock_stock_2)._action_confirm()
move_supp_stock_1._action_assign()
self.assertEqual(move_supp_stock_1.state, 'assigned')
self.assertEqual(move_supp_stock_2.state, 'assigned')
self.assertEqual(move_stock_stock_1.state, 'waiting')
self.assertEqual(move_stock_stock_2.state, 'waiting')
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0.0)
# do the fist move, it'll bring 3 units in stock location so only `move_stock_stock_1`
# should be assigned
move_supp_stock_1.move_line_ids.qty_done = 3.0
move_supp_stock_1._action_done()
self.assertEqual(move_supp_stock_1.state, 'done')
self.assertEqual(move_supp_stock_2.state, 'assigned')
self.assertEqual(move_stock_stock_1.state, 'assigned')
self.assertEqual(move_stock_stock_2.state, 'waiting')
def test_link_assign_7(self):
# on the dozen uom, set the rounding set 1.0
self.uom_dozen.rounding = 1
# 6 units are available in stock
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 6.0)
# create pickings and moves for a pick -> pack mto scenario
picking_stock_pack = self.env['stock.picking'].create({
'location_id': self.stock_location.id,
'location_dest_id': self.pack_location.id,
'picking_type_id': self.env.ref('stock.picking_type_internal').id,
})
move_stock_pack = self.env['stock.move'].create({
'name': 'test_link_assign_7',
'location_id': self.stock_location.id,
'location_dest_id': self.pack_location.id,
'product_id': self.product.id,
'product_uom': self.uom_dozen.id,
'product_uom_qty': 1.0,
'picking_id': picking_stock_pack.id,
})
picking_pack_cust = self.env['stock.picking'].create({
'location_id': self.pack_location.id,
'location_dest_id': self.customer_location.id,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
})
move_pack_cust = self.env['stock.move'].create({
'name': 'test_link_assign_7',
'location_id': self.pack_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_dozen.id,
'product_uom_qty': 1.0,
'picking_id': picking_pack_cust.id,
})
move_stock_pack.write({'move_dest_ids': [(4, move_pack_cust.id, 0)]})
move_pack_cust.write({'move_orig_ids': [(4, move_stock_pack.id, 0)]})
(move_stock_pack + move_pack_cust)._action_confirm()
# the pick should not be reservable because of the rounding of the dozen
move_stock_pack._action_assign()
self.assertEqual(move_stock_pack.state, 'confirmed')
move_pack_cust._action_assign()
self.assertEqual(move_pack_cust.state, 'waiting')
# move the 6 units by adding an unreserved move line
move_stock_pack.write({'move_line_ids': [(0, 0, {
'product_id': self.product.id,
'product_uom_id': self.uom_unit.id,
'qty_done': 6,
'product_uom_qty': 0,
'lot_id': False,
'package_id': False,
'result_package_id': False,
'location_id': move_stock_pack.location_id.id,
'location_dest_id': move_stock_pack.location_dest_id.id,
'picking_id': picking_stock_pack.id,
})]})
# the quantity done on the move should not respect the rounding of the move line
self.assertEqual(move_stock_pack.quantity_done, 0.5)
# create the backorder in the uom of the quants
backorder_wizard_dict = picking_stock_pack.button_validate()
backorder_wizard = Form(self.env[backorder_wizard_dict['res_model']].with_context(backorder_wizard_dict['context'])).save()
backorder_wizard.process()
self.assertEqual(move_stock_pack.state, 'done')
self.assertEqual(move_stock_pack.quantity_done, 0.5)
self.assertEqual(move_stock_pack.product_uom_qty, 0.5)
# the second move should not be reservable because of the rounding on the dozen
move_pack_cust._action_assign()
self.assertEqual(move_pack_cust.state, 'partially_available')
move_line_pack_cust = move_pack_cust.move_line_ids
self.assertEqual(move_line_pack_cust.product_uom_qty, 6)
self.assertEqual(move_line_pack_cust.product_uom_id.id, self.uom_unit.id)
# move a dozen on the backorder to see how we handle the extra move
backorder = self.env['stock.picking'].search([('backorder_id', '=', picking_stock_pack.id)])
backorder.move_lines.write({'move_line_ids': [(0, 0, {
'product_id': self.product.id,
'product_uom_id': self.uom_dozen.id,
'qty_done': 1,
'product_uom_qty': 0,
'lot_id': False,
'package_id': False,
'result_package_id': False,
'location_id': backorder.location_id.id,
'location_dest_id': backorder.location_dest_id.id,
'picking_id': backorder.id,
})]})
backorder.button_validate()
backorder_move = backorder.move_lines
self.assertEqual(backorder_move.state, 'done')
self.assertEqual(backorder_move.quantity_done, 12.0)
self.assertEqual(backorder_move.product_uom_qty, 12.0)
self.assertEqual(backorder_move.product_uom, self.uom_unit)
# the second move should now be reservable
move_pack_cust._action_assign()
self.assertEqual(move_pack_cust.state, 'assigned')
self.assertEqual(move_line_pack_cust.product_uom_qty, 12)
self.assertEqual(move_line_pack_cust.product_uom_id.id, self.uom_unit.id)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, move_stock_pack.location_dest_id), 6)
def test_link_assign_8(self):
""" Set the rounding of the dozen to 1.0, create a chain of two move for a dozen, the product
concerned is tracked by serial number. Check that the flow is ok.
"""
# on the dozen uom, set the rounding set 1.0
self.uom_dozen.rounding = 1
# 6 units are available in stock
for i in range(1, 13):
lot_id = self.env['stock.production.lot'].create({
'name': 'lot%s' % str(i),
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
self.env['stock.quant']._update_available_quantity(self.product_serial, self.stock_location, 1.0, lot_id=lot_id)
# create pickings and moves for a pick -> pack mto scenario
picking_stock_pack = self.env['stock.picking'].create({
'location_id': self.stock_location.id,
'location_dest_id': self.pack_location.id,
'picking_type_id': self.env.ref('stock.picking_type_internal').id,
})
move_stock_pack = self.env['stock.move'].create({
'name': 'test_link_assign_7',
'location_id': self.stock_location.id,
'location_dest_id': self.pack_location.id,
'product_id': self.product_serial.id,
'product_uom': self.uom_dozen.id,
'product_uom_qty': 1.0,
'picking_id': picking_stock_pack.id,
})
picking_pack_cust = self.env['stock.picking'].create({
'location_id': self.pack_location.id,
'location_dest_id': self.customer_location.id,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
})
move_pack_cust = self.env['stock.move'].create({
'name': 'test_link_assign_7',
'location_id': self.pack_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product_serial.id,
'product_uom': self.uom_dozen.id,
'product_uom_qty': 1.0,
'picking_id': picking_pack_cust.id,
})
move_stock_pack.write({'move_dest_ids': [(4, move_pack_cust.id, 0)]})
move_pack_cust.write({'move_orig_ids': [(4, move_stock_pack.id, 0)]})
(move_stock_pack + move_pack_cust)._action_confirm()
move_stock_pack._action_assign()
self.assertEqual(move_stock_pack.state, 'assigned')
move_pack_cust._action_assign()
self.assertEqual(move_pack_cust.state, 'waiting')
for ml in move_stock_pack.move_line_ids:
ml.qty_done = 1
picking_stock_pack.button_validate()
self.assertEqual(move_pack_cust.state, 'assigned')
for ml in move_pack_cust.move_line_ids:
self.assertEqual(ml.product_uom_qty, 1)
self.assertEqual(ml.product_uom_id.id, self.uom_unit.id)
self.assertTrue(bool(ml.lot_id.id))
def test_link_assign_9(self):
""" Create an uom "3 units" which is 3 times the units but without rounding. Create 3
quants in stock and two chained moves. The first move will bring the 3 quants but the
second only validate 2 and create a backorder for the last one. Check that the reservation
is correctly cleared up for the last one.
"""
uom_3units = self.env['uom.uom'].create({
'name': '3 units',
'category_id': self.uom_unit.category_id.id,
'factor_inv': 3,
'rounding': 1,
'uom_type': 'bigger',
})
for i in range(1, 4):
lot_id = self.env['stock.production.lot'].create({
'name': 'lot%s' % str(i),
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
self.env['stock.quant']._update_available_quantity(self.product_serial, self.stock_location, 1.0, lot_id=lot_id)
picking_stock_pack = self.env['stock.picking'].create({
'location_id': self.stock_location.id,
'location_dest_id': self.pack_location.id,
'picking_type_id': self.env.ref('stock.picking_type_internal').id,
})
move_stock_pack = self.env['stock.move'].create({
'name': 'test_link_assign_9',
'location_id': self.stock_location.id,
'location_dest_id': self.pack_location.id,
'product_id': self.product_serial.id,
'product_uom': uom_3units.id,
'product_uom_qty': 1.0,
'picking_id': picking_stock_pack.id,
})
picking_pack_cust = self.env['stock.picking'].create({
'location_id': self.pack_location.id,
'location_dest_id': self.customer_location.id,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
})
move_pack_cust = self.env['stock.move'].create({
'name': 'test_link_assign_0',
'location_id': self.pack_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product_serial.id,
'product_uom': uom_3units.id,
'product_uom_qty': 1.0,
'picking_id': picking_pack_cust.id,
})
move_stock_pack.write({'move_dest_ids': [(4, move_pack_cust.id, 0)]})
move_pack_cust.write({'move_orig_ids': [(4, move_stock_pack.id, 0)]})
(move_stock_pack + move_pack_cust)._action_confirm()
picking_stock_pack.action_assign()
for ml in picking_stock_pack.move_lines.move_line_ids:
ml.qty_done = 1
picking_stock_pack.button_validate()
self.assertEqual(picking_pack_cust.state, 'assigned')
for ml in picking_pack_cust.move_lines.move_line_ids:
if ml.lot_id.name != 'lot3':
ml.qty_done = 1
res_dict_for_back_order = picking_pack_cust.button_validate()
backorder_wizard = self.env[(res_dict_for_back_order.get('res_model'))].browse(res_dict_for_back_order.get('res_id')).with_context(res_dict_for_back_order['context'])
backorder_wizard.process()
backorder = self.env['stock.picking'].search([('backorder_id', '=', picking_pack_cust.id)])
backordered_move = backorder.move_lines
# due to the rounding, the backordered quantity is 0.999 ; we shoudln't be able to reserve
# 0.999 on a tracked by serial number quant
backordered_move._action_assign()
self.assertEqual(backordered_move.reserved_availability, 0)
# force the serial number and validate
lot3 = self.env['stock.production.lot'].search([('name', '=', "lot3")])
backorder.write({'move_line_ids': [(0, 0, {
'product_id': self.product_serial.id,
'product_uom_id': self.uom_unit.id,
'qty_done': 1,
'product_uom_qty': 0,
'lot_id': lot3.id,
'package_id': False,
'result_package_id': False,
'location_id': backordered_move.location_id.id,
'location_dest_id': backordered_move.location_dest_id.id,
'move_id': backordered_move.id,
})]})
backorder.button_validate()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.customer_location), 3)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_serial, self.pack_location), 0)
def test_link_assign_10(self):
""" Test the assignment mechanism with partial availability.
"""
# make some stock:
# stock location: 2.0
# pack location: -1.0
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 2.0)
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location)), 1.0)
move_out = self.env['stock.move'].create({
'name': 'test_link_assign_out',
'location_id': self.pack_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move_out._action_confirm()
move_out._action_assign()
move_out.quantity_done = 1.0
move_out._action_done()
self.assertEqual(len(self.gather_relevant(self.product, self.pack_location)), 1.0)
move_stock_pack = self.env['stock.move'].create({
'name': 'test_link_assign_1_1',
'location_id': self.stock_location.id,
'location_dest_id': self.pack_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 2.0,
})
move_pack_cust = self.env['stock.move'].create({
'name': 'test_link_assign_1_2',
'location_id': self.pack_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 2.0,
})
move_stock_pack.write({'move_dest_ids': [(4, move_pack_cust.id, 0)]})
move_pack_cust.write({'move_orig_ids': [(4, move_stock_pack.id, 0)]})
(move_stock_pack + move_pack_cust)._action_confirm()
move_stock_pack._action_assign()
move_stock_pack.quantity_done = 2.0
move_stock_pack._action_done()
self.assertEqual(len(move_pack_cust.move_line_ids), 1)
self.assertAlmostEqual(move_pack_cust.reserved_availability, 1.0)
self.assertEqual(move_pack_cust.state, 'partially_available')
def test_use_reserved_move_line_1(self):
""" Test that _free_reservation work when quantity is only available on
reserved move lines.
"""
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 10.0)
move1 = self.env['stock.move'].create({
'name': 'test_use_unreserved_move_line_1_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 5.0,
})
move2 = self.env['stock.move'].create({
'name': 'test_use_unreserved_move_line_1_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 5.0,
})
move1._action_confirm()
move1._action_assign()
move2._action_confirm()
move2._action_assign()
move3 = self.env['stock.move'].create({
'name': 'test_use_unreserved_move_line_1_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 0.0,
'quantity_done': 1.0,
})
move3._action_confirm()
move3._action_assign()
move3._action_done()
self.assertEqual(move3.state, 'done')
quant = self.env['stock.quant']._gather(self.product, self.stock_location)
self.assertEqual(quant.quantity, 9.0)
self.assertEqual(quant.reserved_quantity, 9.0)
def test_use_reserved_move_line_2(self):
# make 12 units available in stock
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 12.0)
# reserve 12 units
move1 = self.env['stock.move'].create({
'name': 'test_use_reserved_move_line_2_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 12,
})
move1._action_confirm()
move1._action_assign()
self.assertEqual(move1.state, 'assigned')
quant = self.env['stock.quant']._gather(self.product, self.stock_location)
self.assertEqual(quant.quantity, 12)
self.assertEqual(quant.reserved_quantity, 12)
# force a move of 1 dozen
move2 = self.env['stock.move'].create({
'name': 'test_use_reserved_move_line_2_2',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_dozen.id,
'product_uom_qty': 1,
})
move2._action_confirm()
move2._action_assign()
self.assertEqual(move2.state, 'confirmed')
move2._set_quantity_done(1)
move2._action_done()
# mov1 should be unreserved and the quant should be unlinked
self.assertEqual(move1.state, 'confirmed')
quant = self.env['stock.quant']._gather(self.product, self.stock_location)
self.assertEqual(quant.quantity, 0)
self.assertEqual(quant.reserved_quantity, 0)
def test_use_unreserved_move_line_1(self):
""" Test that validating a stock move linked to an untracked product reserved by another one
correctly unreserves the other one.
"""
# make some stock
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1.0)
# prepare the conflicting move
move1 = self.env['stock.move'].create({
'name': 'test_use_unreserved_move_line_1_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move2 = self.env['stock.move'].create({
'name': 'test_use_unreserved_move_line_1_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
# reserve those move
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 1.0)
move1._action_confirm()
move1._action_assign()
self.assertEqual(move1.state, 'assigned')
move2._action_confirm()
move2._action_assign()
self.assertEqual(move2.state, 'confirmed')
# use the product from the first one
move2.write({'move_line_ids': [(0, 0, {
'product_id': self.product.id,
'product_uom_id': self.uom_unit.id,
'qty_done': 1,
'product_uom_qty': 0,
'lot_id': False,
'package_id': False,
'result_package_id': False,
'location_id': move2.location_id.id,
'location_dest_id': move2.location_dest_id.id,
})]})
move2._action_done()
# the first move should go back to confirmed
self.assertEqual(move1.state, 'confirmed')
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0.0)
def test_use_unreserved_move_line_2(self):
""" Test that validating a stock move linked to a tracked product reserved by another one
correctly unreserves the other one.
"""
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.product.id,
'company_id': self.env.company.id,
})
# make some stock
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1.0, lot_id=lot1)
# prepare the conflicting move
move1 = self.env['stock.move'].create({
'name': 'test_use_unreserved_move_line_1_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move2 = self.env['stock.move'].create({
'name': 'test_use_unreserved_move_line_1_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
# reserve those move
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, lot_id=lot1), 1.0)
move1._action_confirm()
move1._action_assign()
self.assertEqual(move1.state, 'assigned')
move2._action_confirm()
move2._action_assign()
self.assertEqual(move2.state, 'confirmed')
# use the product from the first one
move2.write({'move_line_ids': [(0, 0, {
'product_id': self.product.id,
'product_uom_id': self.uom_unit.id,
'qty_done': 1,
'product_uom_qty': 0,
'lot_id': lot1.id,
'package_id': False,
'result_package_id': False,
'location_id': move2.location_id.id,
'location_dest_id': move2.location_dest_id.id,
})]})
move2._action_done()
# the first move should go back to confirmed
self.assertEqual(move1.state, 'confirmed')
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, lot_id=lot1), 0.0)
def test_use_unreserved_move_line_3(self):
""" Test the behavior of `_free_reservation` when ran on a recordset of move lines where
some are assigned and some are force assigned. `_free_reservation` should not use an
already processed move line when looking for a move line candidate to unreserve.
"""
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1.0)
move1 = self.env['stock.move'].create({
'name': 'test_use_unreserved_move_line_3',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 3.0,
})
move1._action_confirm()
move1._action_assign()
move1.quantity_done = 1
# add a forced move line in `move1`
move1.write({'move_line_ids': [(0, 0, {
'product_id': self.product.id,
'product_uom_id': self.uom_unit.id,
'qty_done': 2,
'product_uom_qty': 0,
'lot_id': False,
'package_id': False,
'result_package_id': False,
'location_id': move1.location_id.id,
'location_dest_id': move1.location_dest_id.id,
})]})
move1._action_done()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.customer_location), 3.0)
def test_use_unreserved_move_line_4(self):
product_01 = self.env['product.product'].create({
'name': 'Product 01',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
})
product_02 = self.env['product.product'].create({
'name': 'Product 02',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
})
self.env['stock.quant']._update_available_quantity(product_01, self.stock_location, 1)
self.env['stock.quant']._update_available_quantity(product_02, self.stock_location, 1)
customer = self.env['res.partner'].create({'name': 'SuperPartner'})
picking = self.env['stock.picking'].create({
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'partner_id': customer.id,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
})
p01_move = self.env['stock.move'].create({
'name': 'SuperMove01',
'location_id': picking.location_id.id,
'location_dest_id': picking.location_dest_id.id,
'picking_id': picking.id,
'product_id': product_01.id,
'product_uom_qty': 1,
'product_uom': product_01.uom_id.id,
})
self.env['stock.move'].create({
'name': 'SuperMove02',
'location_id': picking.location_id.id,
'location_dest_id': picking.location_dest_id.id,
'picking_id': picking.id,
'product_id': product_02.id,
'product_uom_qty': 1,
'product_uom': product_02.uom_id.id,
})
picking.action_confirm()
picking.action_assign()
p01_move.product_uom_qty = 0
picking.do_unreserve()
picking.action_assign()
p01_move.product_uom_qty = 1
self.assertEqual(p01_move.state, 'confirmed')
def test_edit_reserved_move_line_1(self):
""" Test that editing a stock move line linked to an untracked product correctly and
directly adapts the reservation. In this case, we edit the sublocation where we take the
product to another sublocation where a product is available.
"""
shelf1_location = self.env['stock.location'].create({
'name': 'shelf1',
'usage': 'internal',
'location_id': self.stock_location.id,
})
shelf2_location = self.env['stock.location'].create({
'name': 'shelf1',
'usage': 'internal',
'location_id': self.stock_location.id,
})
self.env['stock.quant']._update_available_quantity(self.product, shelf1_location, 1.0)
self.env['stock.quant']._update_available_quantity(self.product, shelf2_location, 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf1_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf2_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 2.0)
move1 = self.env['stock.move'].create({
'name': 'test_edit_moveline_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move1._action_confirm()
move1._action_assign()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf1_location), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf2_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 1.0)
move1.move_line_ids.location_id = shelf2_location.id
self.assertEqual(move1.reserved_availability, 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf1_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf2_location), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 1.0)
def test_edit_reserved_move_line_2(self):
""" Test that editing a stock move line linked to a tracked product correctly and directly
adapts the reservation. In this case, we edit the lot to another available one.
"""
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.product.id,
'company_id': self.env.company.id,
})
lot2 = self.env['stock.production.lot'].create({
'name': 'lot2',
'product_id': self.product.id,
'company_id': self.env.company.id,
})
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1.0, lot_id=lot1)
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1.0, lot_id=lot2)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 2.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, lot_id=lot1), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, lot_id=lot2), 1.0)
move1 = self.env['stock.move'].create({
'name': 'test_edit_moveline_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move1._action_confirm()
move1._action_assign()
self.assertEqual(move1.reserved_availability, 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, lot_id=lot1), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, lot_id=lot2), 1.0)
move1.move_line_ids.lot_id = lot2.id
self.assertEqual(move1.reserved_availability, 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, lot_id=lot1), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, lot_id=lot2), 0.0)
def test_edit_reserved_move_line_3(self):
""" Test that editing a stock move line linked to a packed product correctly and directly
adapts the reservation. In this case, we edit the package to another available one.
"""
package1 = self.env['stock.quant.package'].create({'name': 'test_edit_reserved_move_line_3'})
package2 = self.env['stock.quant.package'].create({'name': 'test_edit_reserved_move_line_3'})
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1.0, package_id=package1)
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1.0, package_id=package2)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 2.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, package_id=package1), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, package_id=package2), 1.0)
move1 = self.env['stock.move'].create({
'name': 'test_edit_moveline_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move1._action_confirm()
move1._action_assign()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, package_id=package1), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, package_id=package2), 1.0)
move1.move_line_ids.package_id = package2.id
self.assertEqual(move1.reserved_availability, 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, package_id=package1), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, package_id=package2), 0.0)
def test_edit_reserved_move_line_4(self):
""" Test that editing a stock move line linked to an owned product correctly and directly
adapts the reservation. In this case, we edit the owner to another available one.
"""
owner1 = self.env['res.partner'].create({'name': 'test_edit_reserved_move_line_4_1'})
owner2 = self.env['res.partner'].create({'name': 'test_edit_reserved_move_line_4_2'})
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1.0, owner_id=owner1)
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1.0, owner_id=owner2)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 2.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, owner_id=owner1), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, owner_id=owner2), 1.0)
move1 = self.env['stock.move'].create({
'name': 'test_edit_moveline_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move1._action_confirm()
move1._action_assign()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, owner_id=owner1), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, owner_id=owner2), 1.0)
move1.move_line_ids.owner_id = owner2.id
self.assertEqual(move1.reserved_availability, 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, owner_id=owner1), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, owner_id=owner2), 0.0)
def test_edit_reserved_move_line_5(self):
""" Test that editing a stock move line linked to a packed and tracked product correctly
and directly adapts the reservation. In this case, we edit the lot to another available one
that is not in a pack.
"""
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.product.id,
'company_id': self.env.company.id,
})
lot2 = self.env['stock.production.lot'].create({
'name': 'lot2',
'product_id': self.product.id,
'company_id': self.env.company.id,
})
package1 = self.env['stock.quant.package'].create({'name': 'test_edit_reserved_move_line_5'})
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1.0, lot_id=lot1, package_id=package1)
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1.0, lot_id=lot2)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 2.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, lot_id=lot1, package_id=package1), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, lot_id=lot2), 1.0)
move1 = self.env['stock.move'].create({
'name': 'test_edit_moveline_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move1._action_confirm()
move1._action_assign()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, lot_id=lot1, package_id=package1), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, lot_id=lot2), 1.0)
move_line = move1.move_line_ids[0]
move_line.write({'package_id': False, 'lot_id': lot2.id})
self.assertEqual(move1.reserved_availability, 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, lot_id=lot1, package_id=package1), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, lot_id=lot2), 0.0)
def test_edit_reserved_move_line_6(self):
""" Test that editing a stock move line linked to an untracked product correctly and
directly adapts the reservation. In this case, we edit the sublocation where we take the
product to another sublocation where a product is NOT available.
"""
shelf1_location = self.env['stock.location'].create({
'name': 'shelf1',
'usage': 'internal',
'location_id': self.stock_location.id,
})
shelf2_location = self.env['stock.location'].create({
'name': 'shelf1',
'usage': 'internal',
'location_id': self.stock_location.id,
})
self.env['stock.quant']._update_available_quantity(self.product, shelf1_location, 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf1_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf2_location), 0.0)
move1 = self.env['stock.move'].create({
'name': 'test_edit_moveline_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move1._action_confirm()
move1._action_assign()
self.assertEqual(move1.move_line_ids.state, 'assigned')
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf1_location), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf2_location), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0.0)
move1.move_line_ids.location_id = shelf2_location.id
self.assertEqual(move1.move_line_ids.state, 'confirmed')
self.assertEqual(move1.reserved_availability, 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf1_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf2_location), 0.0)
def test_edit_reserved_move_line_7(self):
""" Send 5 tracked products to a client, but these products do not have any lot set in our
inventory yet: we only set them at delivery time. The created move line should have 5 items
without any lot set, if we edit to set them to lot1, the reservation should not change.
Validating the stock move should should not create a negative quant for this lot in stock
location.
# """
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.product_lot.id,
'company_id': self.env.company.id,
})
# make some stock without assigning a lot id
self.env['stock.quant']._update_available_quantity(self.product_lot, self.stock_location, 5)
# creation
move1 = self.env['stock.move'].create({
'name': 'test_in_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product_lot.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 5.0,
})
self.assertEqual(move1.state, 'draft')
# confirmation
move1._action_confirm()
self.assertEqual(move1.state, 'confirmed')
# assignment
move1._action_assign()
self.assertEqual(move1.state, 'assigned')
self.assertEqual(len(move1.move_line_ids), 1)
move_line = move1.move_line_ids[0]
self.assertEqual(move_line.product_qty, 5)
move_line.qty_done = 5.0
self.assertEqual(move_line.product_qty, 5) # don't change reservation
move_line.lot_id = lot1
self.assertEqual(move_line.product_qty, 5) # don't change reservation when assgning a lot now
move1._action_done()
self.assertEqual(move_line.product_qty, 0) # change reservation to 0 for done move
self.assertEqual(move1.state, 'done')
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_lot, self.stock_location), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_lot, self.stock_location, lot_id=lot1, strict=True), 0.0)
self.assertEqual(len(self.gather_relevant(self.product_lot, self.stock_location)), 0.0)
self.assertEqual(len(self.gather_relevant(self.product_lot, self.stock_location, lot_id=lot1, strict=True)), 0.0)
def test_edit_reserved_move_line_8(self):
""" Send 5 tracked products to a client, but some of these products do not have any lot set
in our inventory yet: we only set them at delivery time. Adding a lot_id on the move line
that does not have any should not change its reservation, and validating should not create
a negative quant for this lot in stock.
"""
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.product_lot.id,
'company_id': self.env.company.id,
})
lot2 = self.env['stock.production.lot'].create({
'name': 'lot2',
'product_id': self.product_lot.id,
'company_id': self.env.company.id,
})
# make some stock without assigning a lot id
self.env['stock.quant']._update_available_quantity(self.product_lot, self.stock_location, 3)
self.env['stock.quant']._update_available_quantity(self.product_lot, self.stock_location, 2, lot_id=lot1)
# creation
move1 = self.env['stock.move'].create({
'name': 'test_in_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product_lot.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 5.0,
})
self.assertEqual(move1.state, 'draft')
# confirmation
move1._action_confirm()
self.assertEqual(move1.state, 'confirmed')
# assignment
move1._action_assign()
self.assertEqual(move1.state, 'assigned')
self.assertEqual(len(move1.move_line_ids), 2)
tracked_move_line = None
untracked_move_line = None
for move_line in move1.move_line_ids:
if move_line.lot_id:
tracked_move_line = move_line
else:
untracked_move_line = move_line
self.assertEqual(tracked_move_line.product_qty, 2)
tracked_move_line.qty_done = 2
self.assertEqual(untracked_move_line.product_qty, 3)
untracked_move_line.lot_id = lot2
self.assertEqual(untracked_move_line.product_qty, 3) # don't change reservation
untracked_move_line.qty_done = 3
self.assertEqual(untracked_move_line.product_qty, 3) # don't change reservation
move1._action_done()
self.assertEqual(untracked_move_line.product_qty, 0) # change reservation to 0 for done move
self.assertEqual(tracked_move_line.product_qty, 0) # change reservation to 0 for done move
self.assertEqual(move1.state, 'done')
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_lot, self.stock_location), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_lot, self.stock_location, lot_id=lot1, strict=True), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_lot, self.stock_location, lot_id=lot2, strict=True), 0.0)
self.assertEqual(len(self.gather_relevant(self.product_lot, self.stock_location)), 0.0)
self.assertEqual(len(self.gather_relevant(self.product_lot, self.stock_location, lot_id=lot1, strict=True)), 0.0)
self.assertEqual(len(self.gather_relevant(self.product_lot, self.stock_location, lot_id=lot2, strict=True)), 0.0)
def test_edit_reserved_move_line_9(self):
"""
When writing on the reserved quantity on the SML, a process tries to
reserve the quants with that new quantity. If it fails (for instance
because the written quantity is more than actually available), this
quantity should be reset to 0.
"""
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1.0)
out_move = self.env['stock.move'].create({
'name': self.product.name,
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom_qty': 1,
'product_uom': self.product.uom_id.id,
})
out_move._action_confirm()
out_move._action_assign()
# try to manually assign more than available
out_move.move_line_ids.product_uom_qty = 2
self.assertTrue(out_move.move_line_ids)
self.assertEqual(out_move.move_line_ids.product_uom_qty, 0, "The reserved quantity should be cancelled")
def test_edit_done_move_line_1(self):
""" Test that editing a done stock move line linked to an untracked product correctly and
directly adapts the transfer. In this case, we edit the sublocation where we take the
product to another sublocation where a product is available.
"""
shelf1_location = self.env['stock.location'].create({
'name': 'shelf1',
'usage': 'internal',
'location_id': self.stock_location.id,
})
shelf2_location = self.env['stock.location'].create({
'name': 'shelf1',
'usage': 'internal',
'location_id': self.stock_location.id,
})
self.env['stock.quant']._update_available_quantity(self.product, shelf1_location, 1.0)
self.env['stock.quant']._update_available_quantity(self.product, shelf2_location, 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf1_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf2_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 2.0)
# move from shelf1
move1 = self.env['stock.move'].create({
'name': 'test_edit_moveline_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 1
move1._action_done()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf1_location), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf2_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 1.0)
# edit once done, we actually moved from shelf2
move1.move_line_ids.location_id = shelf2_location.id
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf1_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf2_location), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 1.0)
def test_edit_done_move_line_2(self):
""" Test that editing a done stock move line linked to a tracked product correctly and directly
adapts the transfer. In this case, we edit the lot to another available one.
"""
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.product.id,
'company_id': self.env.company.id,
})
lot2 = self.env['stock.production.lot'].create({
'name': 'lot2',
'product_id': self.product.id,
'company_id': self.env.company.id,
})
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1.0, lot_id=lot1)
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1.0, lot_id=lot2)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 2.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, lot_id=lot1), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, lot_id=lot2), 1.0)
move1 = self.env['stock.move'].create({
'name': 'test_edit_moveline_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 1
move1._action_done()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, lot_id=lot1), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, lot_id=lot2), 1.0)
move1.move_line_ids.lot_id = lot2.id
# reserved_availability should always been 0 for done move.
self.assertEqual(move1.reserved_availability, 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, lot_id=lot1), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, lot_id=lot2), 0.0)
def test_edit_done_move_line_3(self):
""" Test that editing a done stock move line linked to a packed product correctly and directly
adapts the transfer. In this case, we edit the package to another available one.
"""
package1 = self.env['stock.quant.package'].create({'name': 'test_edit_reserved_move_line_3'})
package2 = self.env['stock.quant.package'].create({'name': 'test_edit_reserved_move_line_3'})
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1.0, package_id=package1)
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1.0, package_id=package2)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 2.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, package_id=package1), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, package_id=package2), 1.0)
move1 = self.env['stock.move'].create({
'name': 'test_edit_moveline_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 1
move1._action_done()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, package_id=package1), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, package_id=package2), 1.0)
move1.move_line_ids.package_id = package2.id
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, package_id=package1), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, package_id=package2), 0.0)
def test_edit_done_move_line_4(self):
""" Test that editing a done stock move line linked to an owned product correctly and directly
adapts the transfer. In this case, we edit the owner to another available one.
"""
owner1 = self.env['res.partner'].create({'name': 'test_edit_reserved_move_line_4_1'})
owner2 = self.env['res.partner'].create({'name': 'test_edit_reserved_move_line_4_2'})
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1.0, owner_id=owner1)
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1.0, owner_id=owner2)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 2.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, owner_id=owner1), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, owner_id=owner2), 1.0)
move1 = self.env['stock.move'].create({
'name': 'test_edit_moveline_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 1
move1._action_done()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, owner_id=owner1), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, owner_id=owner2), 1.0)
move1.move_line_ids.owner_id = owner2.id
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, owner_id=owner1), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, owner_id=owner2), 0.0)
def test_edit_done_move_line_5(self):
""" Test that editing a done stock move line linked to a packed and tracked product correctly
and directly adapts the transfer. In this case, we edit the lot to another available one
that is not in a pack.
"""
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.product.id,
'company_id': self.env.company.id,
})
lot2 = self.env['stock.production.lot'].create({
'name': 'lot2',
'product_id': self.product.id,
'company_id': self.env.company.id,
})
package1 = self.env['stock.quant.package'].create({'name': 'test_edit_reserved_move_line_5'})
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1.0, lot_id=lot1, package_id=package1)
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1.0, lot_id=lot2)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 2.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, lot_id=lot1, package_id=package1), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, lot_id=lot2), 1.0)
move1 = self.env['stock.move'].create({
'name': 'test_edit_moveline_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 1
move1._action_done()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, lot_id=lot1, package_id=package1), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, lot_id=lot2), 1.0)
move_line = move1.move_line_ids[0]
move_line.write({'package_id': False, 'lot_id': lot2.id})
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, lot_id=lot1, package_id=package1), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, lot_id=lot2), 0.0)
def test_edit_done_move_line_6(self):
""" Test that editing a done stock move line linked to an untracked product correctly and
directly adapts the transfer. In this case, we edit the sublocation where we take the
product to another sublocation where a product is NOT available.
"""
shelf1_location = self.env['stock.location'].create({
'name': 'shelf1',
'usage': 'internal',
'location_id': self.stock_location.id,
})
shelf2_location = self.env['stock.location'].create({
'name': 'shelf1',
'usage': 'internal',
'location_id': self.stock_location.id,
})
self.env['stock.quant']._update_available_quantity(self.product, shelf1_location, 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf1_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf2_location), 0.0)
move1 = self.env['stock.move'].create({
'name': 'test_edit_moveline_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 1
move1._action_done()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf1_location), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf2_location), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0.0)
move1.move_line_ids.location_id = shelf2_location.id
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf1_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf2_location), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf2_location, allow_negative=True), -1.0)
def test_edit_done_move_line_7(self):
""" Test that editing a done stock move line linked to an untracked product correctly and
directly adapts the transfer. In this case, we edit the sublocation where we take the
product to another sublocation where a product is NOT available because it has been reserved
by another move.
"""
shelf1_location = self.env['stock.location'].create({
'name': 'shelf1',
'usage': 'internal',
'location_id': self.stock_location.id,
})
shelf2_location = self.env['stock.location'].create({
'name': 'shelf1',
'usage': 'internal',
'location_id': self.stock_location.id,
})
self.env['stock.quant']._update_available_quantity(self.product, shelf1_location, 1.0)
self.env['stock.quant']._update_available_quantity(self.product, shelf2_location, 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 2.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf1_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf2_location), 1.0)
move1 = self.env['stock.move'].create({
'name': 'test_edit_moveline_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 1
move1._action_done()
move2 = self.env['stock.move'].create({
'name': 'test_edit_moveline_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move2._action_confirm()
move2._action_assign()
self.assertEqual(move2.state, 'assigned')
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf1_location), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf2_location), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0.0)
move1.move_line_ids.location_id = shelf2_location.id
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf1_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf2_location), 0.0)
self.assertEqual(move2.state, 'confirmed')
def test_edit_done_move_line_8(self):
""" Test that editing a done stock move line linked to an untracked product correctly and
directly adapts the transfer. In this case, we increment the quantity done (and we do not
have more in stock.
"""
shelf1_location = self.env['stock.location'].create({
'name': 'shelf1',
'usage': 'internal',
'location_id': self.stock_location.id,
})
self.env['stock.quant']._update_available_quantity(self.product, shelf1_location, 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf1_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 1.0)
# move from shelf1
move1 = self.env['stock.move'].create({
'name': 'test_edit_moveline_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 1
move1._action_done()
self.assertEqual(move1.product_uom_qty, 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf1_location), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0.0)
# edit once done, we actually moved 2 products
move1.move_line_ids.qty_done = 2
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf1_location), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf1_location, allow_negative=True), -1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location, allow_negative=True), -1.0)
self.assertEqual(move1.product_uom_qty, 2.0)
def test_edit_done_move_line_9(self):
""" Test that editing a done stock move line linked to an untracked product correctly and
directly adapts the transfer. In this case, we "cancel" the move by zeroing the qty done.
"""
shelf1_location = self.env['stock.location'].create({
'name': 'shelf1',
'usage': 'internal',
'location_id': self.stock_location.id,
})
self.env['stock.quant']._update_available_quantity(self.product, shelf1_location, 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf1_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 1.0)
# move from shelf1
move1 = self.env['stock.move'].create({
'name': 'test_edit_moveline_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 1
move1._action_done()
self.assertEqual(move1.product_uom_qty, 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf1_location), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0.0)
# edit once done, we actually moved 2 products
move1.move_line_ids.qty_done = 0
self.assertEqual(move1.product_uom_qty, 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, shelf1_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 1.0)
def test_edit_done_move_line_10(self):
""" Edit the quantity done for an incoming move shoudld also remove the quant if there
are no product in stock.
"""
# move from shelf1
move1 = self.env['stock.move'].create({
'name': 'test_edit_moveline_1',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 10
move1._action_done()
quant = self.gather_relevant(self.product, self.stock_location)
self.assertEqual(len(quant), 1.0)
# edit once done, we actually moved 2 products
move1.move_line_ids.qty_done = 0
quant = self.gather_relevant(self.product, self.stock_location)
self.assertEqual(len(quant), 0.0)
self.assertEqual(move1.product_uom_qty, 0.0)
def test_edit_done_move_line_11(self):
""" Add a move line and check if the quant is updated
"""
owner = self.env['res.partner'].create({'name': 'Jean'})
picking = self.env['stock.picking'].create({
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'partner_id': owner.id,
'picking_type_id': self.env.ref('stock.picking_type_in').id,
})
# move from shelf1
move1 = self.env['stock.move'].create({
'name': 'test_edit_moveline_1',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'picking_id': picking.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
})
picking.action_confirm()
picking.action_assign()
move1.move_line_ids.qty_done = 10
picking._action_done()
self.assertEqual(move1.product_uom_qty, 10.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 10.0)
self.env['stock.move.line'].create({
'picking_id': move1.move_line_ids.picking_id.id,
'move_id': move1.move_line_ids.move_id.id,
'product_id': move1.move_line_ids.product_id.id,
'qty_done': move1.move_line_ids.qty_done,
'product_uom_id': move1.product_uom.id,
'location_id': move1.move_line_ids.location_id.id,
'location_dest_id': move1.move_line_ids.location_dest_id.id,
})
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 20.0)
move1.move_line_ids[1].qty_done = 5
self.assertEqual(move1.product_uom_qty, 15.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 15.0)
def test_edit_done_move_line_12(self):
""" Test that editing a done stock move line linked a tracked product correctly and directly
adapts the transfer. In this case, we edit the lot to another one, but the original move line
is not in the default product's UOM.
"""
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.product_lot.id,
'company_id': self.env.company.id,
})
lot2 = self.env['stock.production.lot'].create({
'name': 'lot2',
'product_id': self.product_lot.id,
'company_id': self.env.company.id,
})
package1 = self.env['stock.quant.package'].create({'name': 'test_edit_done_move_line_12'})
move1 = self.env['stock.move'].create({
'name': 'test_edit_moveline_1',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product_lot.id,
'product_uom': self.uom_dozen.id,
'product_uom_qty': 1.0,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 1
move1.move_line_ids.lot_id = lot1.id
move1._action_done()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_lot, self.stock_location, lot_id=lot1), 12.0)
# Change the done quantity from 1 dozen to two dozen
move1.move_line_ids.qty_done = 2
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_lot, self.stock_location, lot_id=lot1), 24.0)
def test_edit_done_move_line_13(self):
""" Test that editing a done stock move line linked to a packed and tracked product correctly
and directly adapts the transfer. In this case, we edit the lot to another available one
that we put in the same pack.
"""
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.product_lot.id,
'company_id': self.env.company.id,
})
lot2 = self.env['stock.production.lot'].create({
'name': 'lot2',
'product_id': self.product_lot.id,
'company_id': self.env.company.id,
})
package1 = self.env['stock.quant.package'].create({'name': 'test_edit_reserved_move_line_5'})
move1 = self.env['stock.move'].create({
'name': 'test_edit_moveline_1',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product_lot.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.qty_done = 1
move1.move_line_ids.lot_id = lot1.id
move1.move_line_ids.result_package_id = package1.id
move1._action_done()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_lot, self.stock_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_lot, self.stock_location, lot_id=lot1, package_id=package1), 1.0)
move1.move_line_ids.write({'lot_id': lot2.id})
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_lot, self.stock_location), 1.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_lot, self.stock_location, lot_id=lot1), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_lot, self.stock_location, lot_id=lot1, package_id=package1), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_lot, self.stock_location, lot_id=lot2, package_id=package1), 1.0)
def test_edit_done_move_line_14(self):
""" Test that editing a done stock move line with a different UoM from its stock move correctly
updates the quant when its qty and/or its UoM is edited. Also check that we don't allow editing
a done stock move's UoM.
"""
move1 = self.env['stock.move'].create({
'name': 'test_edit_moveline',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 12.0,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.product_uom_id = self.uom_dozen
move1.move_line_ids.qty_done = 1
move1._action_done()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 12.0)
move1.move_line_ids.qty_done = 2
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 24.0)
self.assertEqual(move1.product_uom_qty, 24.0)
self.assertEqual(move1.product_qty, 24.0)
move1.move_line_ids.product_uom_id = self.uom_unit
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 2.0)
self.assertEqual(move1.product_uom_qty, 2.0)
self.assertEqual(move1.product_qty, 2.0)
with self.assertRaises(UserError):
move1.product_uom = self.uom_dozen
def test_immediate_validate_1(self):
""" In a picking with a single available move, clicking on validate without filling any
quantities should open a wizard asking to process all the reservation (so, the whole move).
"""
partner = self.env['res.partner'].create({'name': 'Jean'})
picking = self.env['stock.picking'].create({
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'partner_id': partner.id,
'picking_type_id': self.env.ref('stock.picking_type_in').id,
})
self.env['stock.move'].create({
'name': 'test_immediate_validate_1',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'picking_id': picking.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
})
picking.action_confirm()
picking.action_assign()
res_dict = picking.button_validate()
self.assertEqual(res_dict.get('res_model'), 'stock.immediate.transfer')
wizard = Form(self.env[res_dict['res_model']].with_context(res_dict['context'])).save()
wizard.process()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 10.0)
def test_immediate_validate_2(self):
""" In a picking with a single partially available move, clicking on validate without
filling any quantities should open a wizard asking to process all the reservation (so, only
a part of the initial demand). Validating this wizard should open another one asking for
the creation of a backorder. If the backorder is created, it should contain the quantities
not processed.
"""
partner = self.env['res.partner'].create({'name': 'Jean'})
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 5.0)
picking = self.env['stock.picking'].create({
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'partner_id': partner.id,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
})
self.env['stock.move'].create({
'name': 'test_immediate_validate_2',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'picking_id': picking.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
})
picking.action_confirm()
picking.action_assign()
# Only 5 products are reserved on the move of 10, click on `button_validate`.
res_dict = picking.button_validate()
self.assertEqual(res_dict.get('res_model'), 'stock.immediate.transfer')
wizard = Form(self.env[res_dict['res_model']].with_context(res_dict['context'])).save()
res_dict_for_back_order = wizard.process()
self.assertEqual(res_dict_for_back_order.get('res_model'), 'stock.backorder.confirmation')
backorder_wizard = self.env[(res_dict_for_back_order.get('res_model'))].browse(res_dict_for_back_order.get('res_id')).with_context(res_dict_for_back_order['context'])
# Chose to create a backorder.
backorder_wizard.process()
# Only 5 products should be processed on the initial move.
self.assertEqual(picking.move_lines.state, 'done')
self.assertEqual(picking.move_lines.quantity_done, 5.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0.0)
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location)), 0.0)
# The backoder should contain a move for the other 5 produts.
backorder = self.env['stock.picking'].search([('backorder_id', '=', picking.id)])
self.assertEqual(len(backorder), 1.0)
self.assertEqual(backorder.move_lines.product_uom_qty, 5.0)
def test_immediate_validate_3(self):
""" In a picking with two moves, one partially available and one unavailable, clicking
on validate without filling any quantities should open a wizard asking to process all the
reservation (so, only a part of one of the moves). Validating this wizard should open
another one asking for the creation of a backorder. If the backorder is created, it should
contain the quantities not processed.
"""
product5 = self.env['product.product'].create({
'name': 'Product 5',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
})
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1)
picking = self.env['stock.picking'].create({
'location_id': self.stock_location.id,
'location_dest_id': self.pack_location.id,
'picking_type_id': self.env.ref('stock.picking_type_internal').id,
})
product1_move = self.env['stock.move'].create({
'name': 'product1_move',
'location_id': self.stock_location.id,
'location_dest_id': self.pack_location.id,
'picking_id': picking.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 100,
})
product5_move = self.env['stock.move'].create({
'name': 'product3_move',
'location_id': self.stock_location.id,
'location_dest_id': self.pack_location.id,
'picking_id': picking.id,
'product_id': product5.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 100,
})
picking.action_confirm()
picking.action_assign()
# product1_move should be partially available (1/100), product5_move should be totally
# unavailable (0/100)
self.assertEqual(product1_move.state, 'partially_available')
self.assertEqual(product5_move.state, 'confirmed')
action = picking.button_validate()
self.assertEqual(action.get('res_model'), 'stock.immediate.transfer')
wizard = Form(self.env[action['res_model']].with_context(action['context'])).save()
action = wizard.process()
self.assertTrue(isinstance(action, dict), 'Should open backorder wizard')
self.assertEqual(action.get('res_model'), 'stock.backorder.confirmation')
wizard = self.env[(action.get('res_model'))].browse(action.get('res_id')).with_context(action.get('context'))
wizard.process()
backorder = self.env['stock.picking'].search([('backorder_id', '=', picking.id)])
self.assertEqual(len(backorder), 1.0)
# The backorder should contain 99 product1 and 100 product5.
for backorder_move in backorder.move_lines:
if backorder_move.product_id.id == self.product.id:
self.assertEqual(backorder_move.product_qty, 99)
elif backorder_move.product_id.id == product5.id:
self.assertEqual(backorder_move.product_qty, 100)
def test_immediate_validate_4(self):
""" In a picking with a single available tracked by lot move, clicking on validate without
filling any quantities should pop up the immediate transfer wizard.
"""
partner = self.env['res.partner'].create({'name': 'Jean'})
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.product_lot.id,
'company_id': self.env.company.id,
})
self.env['stock.quant']._update_available_quantity(self.product_lot, self.stock_location, 5.0, lot_id=lot1)
picking = self.env['stock.picking'].create({
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'partner_id': partner.id,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
})
# move from shelf1
self.env['stock.move'].create({
'name': 'test_immediate_validate_4',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'picking_id': picking.id,
'product_id': self.product_lot.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 5.0,
})
picking.action_confirm()
picking.action_assign()
# No quantities filled, immediate transfer wizard should pop up.
immediate_trans_wiz_dict = picking.button_validate()
self.assertEqual(immediate_trans_wiz_dict.get('res_model'), 'stock.immediate.transfer')
immediate_trans_wiz = Form(self.env[immediate_trans_wiz_dict['res_model']].with_context(immediate_trans_wiz_dict['context'])).save()
immediate_trans_wiz.process()
self.assertEqual(picking.move_lines.quantity_done, 5.0)
# Check move_lines data
self.assertEqual(len(picking.move_lines.move_line_ids), 1)
self.assertEqual(picking.move_lines.move_line_ids.lot_id, lot1)
self.assertEqual(picking.move_lines.move_line_ids.qty_done, 5.0)
# Check quants data
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0.0)
self.assertEqual(len(self.gather_relevant(self.product, self.stock_location)), 0.0)
def _create_picking_test_immediate_validate_5(self, picking_type_id, product_id):
picking = self.env['stock.picking'].create({
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'picking_type_id': picking_type_id.id,
})
self.env['stock.move'].create({
'name': 'move1',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'picking_id': picking.id,
'picking_type_id': picking_type_id.id,
'product_id': product_id.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 5.0,
})
picking.action_confirm()
for line in picking.move_line_ids:
line.qty_done = line.product_uom_qty
return picking
def test_immediate_validate_5(self):
""" In a receipt with a single tracked by serial numbers move, clicking on validate without
filling any quantities nor lot should open an UserError except if the picking type is
configured to allow otherwise.
"""
picking_type_id = self.env.ref('stock.picking_type_in')
product_id = self.product_serial
self.assertTrue(picking_type_id.use_create_lots or picking_type_id.use_existing_lots)
self.assertEqual(product_id.tracking, 'serial')
picking = self._create_picking_test_immediate_validate_5(picking_type_id, product_id)
# should raise because no serial numbers were specified
self.assertRaises(UserError, picking.button_validate)
picking_type_id.use_create_lots = False
picking_type_id.use_existing_lots = False
picking = self._create_picking_test_immediate_validate_5(picking_type_id, product_id)
picking.button_validate()
self.assertEqual(picking.state, 'done')
def test_immediate_validate_6(self):
""" In a receipt picking with two moves, one tracked and one untracked, clicking on
validate without filling any quantities should displays an UserError as long as no quantity
done and lot_name is set on the tracked move. Now if the user validates the picking, the
wizard telling the user all reserved quantities will be processed will NOT be opened. This
wizard is only opene if no quantities were filled. So validating the picking at this state
will open another wizard asking for the creation of a backorder. Now, if the user processed
on the second move more than the reservation, a wizard will ask him to confirm.
"""
picking_type = self.env.ref('stock.picking_type_in')
picking_type.use_create_lots = True
picking_type.use_existing_lots = False
picking = self.env['stock.picking'].create({
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'picking_type_id': picking_type.id,
})
self.env['stock.move'].create({
'name': 'product1_move',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'picking_id': picking.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1,
})
product3_move = self.env['stock.move'].create({
'name': 'product3_move',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'picking_id': picking.id,
'product_id': self.product_lot.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1,
})
picking.action_confirm()
picking.action_assign()
with self.assertRaises(UserError):
picking.button_validate()
product3_move.move_line_ids[0].qty_done = 1
with self.assertRaises(UserError):
picking.button_validate()
product3_move.move_line_ids[0].lot_name = '271828'
action = picking.button_validate() # should open backorder wizard
self.assertTrue(isinstance(action, dict), 'Should open backorder wizard')
self.assertEqual(action.get('res_model'), 'stock.backorder.confirmation')
def test_immediate_validate_7(self):
""" In a picking with a single unavailable move, clicking on validate without filling any
quantities should display an UserError telling the user he cannot process a picking without
any processed quantity.
"""
partner = self.env['res.partner'].create({'name': 'Jean'})
picking = self.env['stock.picking'].create({
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'partner_id': partner.id,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
})
self.env['stock.move'].create({
'name': 'test_immediate_validate_2',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'picking_id': picking.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
})
picking.action_confirm()
picking.action_assign()
scrap = self.env['stock.scrap'].create({
'picking_id': picking.id,
'product_id': self.product.id,
'product_uom_id': self.uom_unit.id,
'scrap_qty': 5.0,
})
scrap.do_scrap()
# No products are reserved on the move of 10, click on `button_validate`.
with self.assertRaises(UserError):
picking.button_validate()
def test_immediate_validate_8(self):
"""Validate three receipts at once."""
partner = self.env['res.partner'].create({'name': 'Pierre'})
receipt1 = self.env['stock.picking'].create({
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'partner_id': partner.id,
'picking_type_id': self.env.ref('stock.picking_type_in').id,
})
self.env['stock.move'].create({
'name': 'test_immediate_validate_8_1',
'location_id': receipt1.location_id.id,
'location_dest_id': receipt1.location_dest_id.id,
'picking_id': receipt1.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
})
receipt1.action_confirm()
receipt2 = self.env['stock.picking'].create({
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'partner_id': partner.id,
'picking_type_id': self.env.ref('stock.picking_type_in').id,
})
self.env['stock.move'].create({
'name': 'test_immediate_validate_8_2',
'location_id': receipt2.location_id.id,
'location_dest_id': receipt2.location_dest_id.id,
'picking_id': receipt2.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
})
receipt2.action_confirm()
receipt3 = self.env['stock.picking'].create({
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'partner_id': partner.id,
'picking_type_id': self.env.ref('stock.picking_type_in').id,
})
self.env['stock.move'].create({
'name': 'test_immediate_validate_8_3',
'location_id': receipt3.location_id.id,
'location_dest_id': receipt3.location_dest_id.id,
'picking_id': receipt3.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
})
receipt3.action_confirm()
immediate_trans_wiz_dict = (receipt1 + receipt2).button_validate()
immediate_trans_wiz = Form(self.env[immediate_trans_wiz_dict['res_model']].with_context(immediate_trans_wiz_dict['context'])).save()
# The different transfers are displayed to the users.
self.assertTrue(immediate_trans_wiz.show_transfers)
# All transfers are processed by default
self.assertEqual(immediate_trans_wiz.immediate_transfer_line_ids.mapped('to_immediate'), [True, True])
# Only transfer receipt1
immediate_trans_wiz.immediate_transfer_line_ids.filtered(lambda line: line.picking_id == receipt2).to_immediate = False
immediate_trans_wiz.process()
self.assertEqual(receipt1.state, 'done')
self.assertEqual(receipt2.state, 'assigned')
# Transfer receipt2 and receipt3.
immediate_trans_wiz_dict = (receipt3 + receipt2).button_validate()
immediate_trans_wiz = Form(self.env[immediate_trans_wiz_dict['res_model']].with_context(immediate_trans_wiz_dict['context'])).save()
immediate_trans_wiz.process()
self.assertEqual(receipt2.state, 'done')
self.assertEqual(receipt3.state, 'done')
def test_immediate_validate_9_tracked_move_with_0_qty_done(self):
"""When trying to validate a picking as an immediate transfer, the done
quantity of tracked move should be automatically fulfilled if the
picking type doesn't use new or existing LN/SN."""
picking_type_receipt = self.env.ref('stock.picking_type_in')
picking_type_receipt.use_create_lots = False
picking_type_receipt.use_existing_lots = False
picking_form = Form(self.env['stock.picking'])
picking_form.picking_type_id = picking_type_receipt
with picking_form.move_ids_without_package.new() as move:
move.product_id = self.product_serial
move.product_uom_qty = 4
with picking_form.move_ids_without_package.new() as move:
move.product_id = self.product_lot
move.product_uom_qty = 20
receipt = picking_form.save()
receipt.action_confirm()
immediate_wizard = receipt.button_validate()
immediate_wizard_form = Form(
self.env[immediate_wizard['res_model']].with_context(immediate_wizard['context'])
).save()
immediate_wizard_form.process()
self.assertEqual(receipt.state, 'done')
def test_immediate_validate_10_tracked_move_without_backorder(self):
"""
Create a picking for a tracked product, validate it as an
immediate transfer, and ensure that the backorder wizard is
not triggered when the qty is reserved.
"""
picking_type_internal = self.env.ref('stock.picking_type_internal')
picking_type_internal.use_create_lots = True
picking_type_internal.use_existing_lots = True
lot = self.env['stock.production.lot'].create({
'name': 'Lot 1',
'product_id': self.product_lot.id,
'company_id': self.env.company.id,
})
self.env['stock.quant']._update_available_quantity(self.product_lot, self.stock_location, 10, lot_id=lot)
picking_form = Form(self.env['stock.picking'])
picking_form.picking_type_id = picking_type_internal
with picking_form.move_ids_without_package.new() as move:
move.product_id = self.product_lot
move.product_uom_qty = 4
internal_transfer = picking_form.save()
internal_transfer.action_confirm()
immediate_wizard = internal_transfer.button_validate()
immediate_wizard_form = Form(
self.env[immediate_wizard['res_model']].with_context(immediate_wizard['context'])
).save()
immediate_wizard_form.process()
self.assertEqual(internal_transfer.state, 'done')
def test_set_quantity_done_1(self):
move1 = self.env['stock.move'].create({
'name': 'test_set_quantity_done_1',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 2.0,
})
move2 = self.env['stock.move'].create({
'name': 'test_set_quantity_done_2',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 2.0,
})
(move1 + move2)._action_confirm()
(move1 + move2).write({'quantity_done': 1})
self.assertEqual(move1.quantity_done, 1)
self.assertEqual(move2.quantity_done, 1)
def test_initial_demand_1(self):
""" Check that the initial demand is set to 0 when creating a move by hand, and
that changing the product on the move do not reset the initial demand.
"""
move1 = self.env['stock.move'].create({
'name': 'test_in_1',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
})
self.assertEqual(move1.state, 'draft')
self.assertEqual(move1.product_uom_qty, 1)
move1.product_uom_qty = 100
move1.product_id = self.product_serial
move1._onchange_product_id()
self.assertEqual(move1.product_uom_qty, 100)
def test_scrap_1(self):
""" Check the created stock move and the impact on quants when we scrap a
storable product.
"""
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1)
scrap = self.env['stock.scrap'].create({
'product_id': self.product.id,
'product_uom_id':self.product.uom_id.id,
'scrap_qty': 1,
})
scrap.do_scrap()
self.assertEqual(scrap.state, 'done')
move = scrap.move_id
self.assertEqual(move.state, 'done')
self.assertEqual(move.quantity_done, 1)
self.assertEqual(move.scrapped, True)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0)
def test_scrap_2(self):
""" Check the created stock move and the impact on quants when we scrap a
consumable product.
"""
scrap = self.env['stock.scrap'].create({
'product_id': self.product_consu.id,
'product_uom_id':self.product_consu.uom_id.id,
'scrap_qty': 1,
})
self.assertEqual(scrap.name, 'New', 'Name should be New in draft state')
scrap.do_scrap()
self.assertTrue(scrap.name.startswith('SP/'), 'Sequence should be Changed after do_scrap')
self.assertEqual(scrap.state, 'done')
move = scrap.move_id
self.assertEqual(move.state, 'done')
self.assertEqual(move.quantity_done, 1)
self.assertEqual(move.scrapped, True)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product_consu, self.stock_location), 0)
def test_scrap_3(self):
""" Scrap the product of a reserved move line. Check that the move line is
correctly deleted and that the associated stock move is not assigned anymore.
"""
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1)
move1 = self.env['stock.move'].create({
'name': 'test_scrap_3',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move1._action_confirm()
move1._action_assign()
self.assertEqual(move1.state, 'assigned')
self.assertEqual(len(move1.move_line_ids), 1)
scrap = self.env['stock.scrap'].create({
'product_id': self.product.id,
'product_uom_id':self.product.uom_id.id,
'scrap_qty': 1,
})
scrap.do_scrap()
self.assertEqual(move1.state, 'confirmed')
self.assertEqual(len(move1.move_line_ids), 0)
def test_scrap_4(self):
""" Scrap the product of a picking. Then modify the
done linked stock move and ensure the scrap quantity is also
updated.
"""
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 10)
partner = self.env['res.partner'].create({'name': 'Kimberley'})
picking = self.env['stock.picking'].create({
'name': 'A single picking with one move to scrap',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'partner_id': partner.id,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
})
move1 = self.env['stock.move'].create({
'name': 'A move to confirm and scrap its product',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
'picking_id': picking.id,
})
move1._action_confirm()
self.assertEqual(move1.state, 'assigned')
scrap = self.env['stock.scrap'].create({
'product_id': self.product.id,
'product_uom_id': self.product.uom_id.id,
'scrap_qty': 5,
'picking_id': picking.id,
})
scrap.action_validate()
self.assertEqual(len(picking.move_lines), 2)
scrapped_move = picking.move_lines.filtered(lambda m: m.state == 'done')
self.assertTrue(scrapped_move, 'No scrapped move created.')
self.assertEqual(scrapped_move.scrap_ids.ids, [scrap.id], 'Wrong scrap linked to the move.')
self.assertEqual(scrap.scrap_qty, 5, 'Scrap quantity has been modified and is not correct anymore.')
scrapped_move.quantity_done = 8
self.assertEqual(scrap.scrap_qty, 8, 'Scrap quantity is not updated.')
def test_scrap_5(self):
""" Scrap the product of a reserved move line where the product is reserved in another
unit of measure. Check that the move line is correctly updated after the scrap.
"""
# 4 units are available in stock
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 4)
# try to reserve a dozen
partner = self.env['res.partner'].create({'name': 'Kimberley'})
picking = self.env['stock.picking'].create({
'name': 'A single picking with one move to scrap',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'partner_id': partner.id,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
})
move1 = self.env['stock.move'].create({
'name': 'A move to confirm and scrap its product',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_dozen.id,
'product_uom_qty': 1.0,
'picking_id': picking.id,
})
move1._action_confirm()
move1._action_assign()
self.assertEqual(move1.reserved_availability, 0.33)
# scrap a unit
scrap = self.env['stock.scrap'].create({
'product_id': self.product.id,
'product_uom_id': self.product.uom_id.id,
'scrap_qty': 1,
'picking_id': picking.id,
})
scrap.action_validate()
self.assertEqual(scrap.state, 'done')
self.assertEqual(move1.reserved_availability, 0.25)
def test_scrap_6(self):
""" Check that scrap correctly handle UoM. """
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1)
scrap = self.env['stock.scrap'].create({
'product_id': self.product.id,
'product_uom_id': self.uom_dozen.id,
'scrap_qty': 1,
})
warning_message = scrap.action_validate()
self.assertEqual(warning_message.get('res_model', 'Wrong Model'), 'stock.warn.insufficient.qty.scrap')
insufficient_qty_wizard = self.env['stock.warn.insufficient.qty.scrap'].create({
'product_id': self.product.id,
'location_id': self.stock_location.id,
'scrap_id': scrap.id,
'quantity': 1,
'product_uom_name': self.product.uom_id.name
})
insufficient_qty_wizard.action_done()
self.assertEqual(self.env['stock.quant']._gather(self.product, self.stock_location).quantity, -11)
def test_scrap_7_sn_warning(self):
""" Check serial numbers are correctly double checked """
child_loc1 = self.env['stock.location'].create({
'name': "child_location1",
'usage': 'internal',
'location_id': self.stock_location.id
})
child_loc2 = self.env['stock.location'].create({
'name': "child_location2",
'usage': 'internal',
'location_id': self.stock_location.id
})
lot1 = self.env['stock.production.lot'].create({
'name': 'serial1',
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
self.env['stock.quant']._update_available_quantity(self.product_serial, child_loc1, 1, lot1)
scrap = self.env['stock.scrap'].create({
'product_id': self.product_serial.id,
'product_uom_id': self.uom_unit.id,
'location_id': child_loc2.id,
'lot_id': lot1.id
})
warning = False
warning = scrap._onchange_serial_number()
self.assertTrue(warning, 'Use of wrong serial number location not detected')
self.assertEqual(list(warning.keys())[0], 'warning', 'Warning message was not returned')
self.assertEqual(scrap.location_id, child_loc1, 'Location was not auto-corrected')
def test_scrap_8(self):
"""
Suppose a user wants to scrap some products thanks to internal moves.
This test checks the state of the picking based on few cases
"""
scrap_location = self.env['stock.location'].search([('company_id', '=', self.env.company.id), ('scrap_location', '=', True)], limit=1)
internal_operation = self.env['stock.picking.type'].with_context(active_test=False).search([('code', '=', 'internal'), ('company_id', '=', self.env.company.id)], limit=1)
internal_operation.active = True
product01 = self.product
product02 = self.env['product.product'].create({
'name': 'SuperProduct',
'type': 'product',
})
self.env['stock.quant']._update_available_quantity(product01, self.stock_location, 3)
self.env['stock.quant']._update_available_quantity(product02, self.stock_location, 1)
scrap_picking01, scrap_picking02, scrap_picking03 = self.env['stock.picking'].create([{
'location_id': self.stock_location.id,
'location_dest_id': scrap_location.id,
'picking_type_id': internal_operation.id,
'move_lines': [(0, 0, {
'name': 'Scrap %s' % product.display_name,
'location_id': self.stock_location.id,
'location_dest_id': scrap_location.id,
'product_id': product.id,
'product_uom': product.uom_id.id,
'product_uom_qty': 1.0,
'picking_type_id': internal_operation.id,
}) for product in products],
} for products in [(product01,), (product01,), (product01, product02)]])
(scrap_picking01 + scrap_picking02 + scrap_picking03).action_confirm()
# All SM are processed
scrap_picking01.move_lines.quantity_done = 1
scrap_picking01.button_validate()
# All SM are cancelled
scrap_picking02.action_cancel()
# Process one SM and cancel the other one
pick03_prod01_move = scrap_picking03.move_lines.filtered(lambda sm: sm.product_id == product01)
pick03_prod02_move = scrap_picking03.move_lines - pick03_prod01_move
pick03_prod01_move.quantity_done = 1
pick03_prod02_move._action_cancel()
scrap_picking03.button_validate()
self.assertEqual(scrap_picking01.move_lines.state, 'done')
self.assertEqual(scrap_picking01.state, 'done')
self.assertEqual(scrap_picking02.move_lines.state, 'cancel')
self.assertEqual(scrap_picking02.state, 'cancel')
self.assertEqual(pick03_prod01_move.state, 'done')
self.assertEqual(pick03_prod02_move.state, 'cancel')
self.assertEqual(scrap_picking03.state, 'done')
self.assertEqual(self.env['stock.quant']._get_available_quantity(product01, self.stock_location), 1)
self.assertEqual(self.env['stock.quant']._get_available_quantity(product02, self.stock_location), 1)
def test_in_date_1(self):
""" Check that moving a tracked quant keeps the incoming date.
"""
move1 = self.env['stock.move'].create({
'name': 'test_in_date_1',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product_lot.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
'picking_type_id': self.env.ref('stock.picking_type_in').id,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.lot_name = 'lot1'
move1.move_line_ids.qty_done = 1
move1._action_done()
quant = self.gather_relevant(self.product_lot, self.stock_location)
self.assertEqual(len(quant), 1.0)
self.assertNotEqual(quant.in_date, False)
# Keep a reference to the initial incoming date in order to compare it later.
initial_incoming_date = quant.in_date
move2 = self.env['stock.move'].create({
'name': 'test_in_date_1',
'location_id': self.stock_location.id,
'location_dest_id': self.pack_location.id,
'product_id': self.product_lot.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move2._action_confirm()
move2._action_assign()
move2.move_line_ids.qty_done = 1
move2._action_done()
quant = self.gather_relevant(self.product_lot, self.pack_location)
self.assertEqual(len(quant), 1.0)
self.assertEqual(quant.in_date, initial_incoming_date)
def test_in_date_2(self):
""" Check that editing a done move line for a tracked product and changing its lot
correctly restores the original lot with its incoming date and remove the new lot
with its incoming date.
"""
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.product_lot.id,
'company_id': self.env.company.id,
})
lot2 = self.env['stock.production.lot'].create({
'name': 'lot2',
'product_id': self.product_lot.id,
'company_id': self.env.company.id,
})
# receive lot1
move1 = self.env['stock.move'].create({
'name': 'test_in_date_1',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product_lot.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
'picking_type_id': self.env.ref('stock.picking_type_in').id,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.lot_id = lot1
move1.move_line_ids.qty_done = 1
move1._action_done()
# receive lot2
move2 = self.env['stock.move'].create({
'name': 'test_in_date_1',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product_lot.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
'picking_type_id': self.env.ref('stock.picking_type_in').id,
})
move2._action_confirm()
move2._action_assign()
move2.move_line_ids.lot_id = lot2
move2.move_line_ids.qty_done = 1
move2._action_done()
initial_in_date_lot2 = self.env['stock.quant'].search([
('location_id', '=', self.stock_location.id),
('product_id', '=', self.product_lot.id),
('lot_id', '=', lot2.id),
]).in_date
# Edit lot1's incoming date.
quant_lot1 = self.env['stock.quant'].search([
('location_id', '=', self.stock_location.id),
('product_id', '=', self.product_lot.id),
('lot_id', '=', lot1.id),
])
from odoo.fields import Datetime
from datetime import timedelta
initial_in_date_lot1 = Datetime.now() - timedelta(days=5)
quant_lot1.in_date = initial_in_date_lot1
# Move one quant to pack location
move3 = self.env['stock.move'].create({
'name': 'test_in_date_1',
'location_id': self.stock_location.id,
'location_dest_id': self.pack_location.id,
'product_id': self.product_lot.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move3._action_confirm()
move3._action_assign()
move3.move_line_ids.qty_done = 1
move3._action_done()
quant_in_pack = self.env['stock.quant'].search([
('product_id', '=', self.product_lot.id),
('location_id', '=', self.pack_location.id),
])
# As lot1 has an older date and FIFO is set by default, it's the one that should be
# in pack.
self.assertEqual(len(quant_in_pack), 1)
self.assertAlmostEqual(quant_in_pack.in_date, initial_in_date_lot1, delta=timedelta(seconds=1))
self.assertEqual(quant_in_pack.lot_id, lot1)
# Now, edit the move line and actually move the other lot
move3.move_line_ids.lot_id = lot2
# Check that lot1 correctly is back to stock with its right in_date
quant_lot1 = self.env['stock.quant'].search([
('location_id.usage', '=', 'internal'),
('product_id', '=', self.product_lot.id),
('lot_id', '=', lot1.id),
('quantity', '!=', 0),
])
self.assertEqual(quant_lot1.location_id, self.stock_location)
self.assertAlmostEqual(quant_lot1.in_date, initial_in_date_lot1, delta=timedelta(seconds=1))
# Check that lo2 is in pack with is right in_date
quant_lot2 = self.env['stock.quant'].search([
('location_id.usage', '=', 'internal'),
('product_id', '=', self.product_lot.id),
('lot_id', '=', lot2.id),
('quantity', '!=', 0),
])
self.assertEqual(quant_lot2.location_id, self.pack_location)
self.assertAlmostEqual(quant_lot2.in_date, initial_in_date_lot2, delta=timedelta(seconds=1))
def test_in_date_3(self):
""" Check that, when creating a move line on a done stock move, the lot and its incoming
date are correctly moved to the destination location.
"""
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.product_lot.id,
'company_id': self.env.company.id,
})
lot2 = self.env['stock.production.lot'].create({
'name': 'lot2',
'product_id': self.product_lot.id,
'company_id': self.env.company.id,
})
# receive lot1
move1 = self.env['stock.move'].create({
'name': 'test_in_date_1',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product_lot.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
'picking_type_id': self.env.ref('stock.picking_type_in').id,
})
move1._action_confirm()
move1._action_assign()
move1.move_line_ids.lot_id = lot1
move1.move_line_ids.qty_done = 1
move1._action_done()
# receive lot2
move2 = self.env['stock.move'].create({
'name': 'test_in_date_1',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product_lot.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
'picking_type_id': self.env.ref('stock.picking_type_in').id,
})
move2._action_confirm()
move2._action_assign()
move2.move_line_ids.lot_id = lot2
move2.move_line_ids.qty_done = 1
move2._action_done()
initial_in_date_lot2 = self.env['stock.quant'].search([
('location_id', '=', self.stock_location.id),
('product_id', '=', self.product_lot.id),
('lot_id', '=', lot2.id),
('quantity', '!=', 0),
]).in_date
# Edit lot1's incoming date.
quant_lot1 = self.env['stock.quant'].search([
('location_id.usage', '=', 'internal'),
('product_id', '=', self.product_lot.id),
('lot_id', '=', lot1.id),
('quantity', '!=', 0),
])
from odoo.fields import Datetime
from datetime import timedelta
initial_in_date_lot1 = Datetime.now() - timedelta(days=5)
quant_lot1.in_date = initial_in_date_lot1
# Move one quant to pack location
move3 = self.env['stock.move'].create({
'name': 'test_in_date_1',
'location_id': self.stock_location.id,
'location_dest_id': self.pack_location.id,
'product_id': self.product_lot.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move3._action_confirm()
move3._action_assign()
move3.move_line_ids.qty_done = 1
move3._action_done()
# Now, also move lot2
self.env['stock.move.line'].create({
'move_id': move3.id,
'product_id': move3.product_id.id,
'qty_done': 1,
'product_uom_id': move3.product_uom.id,
'location_id': move3.location_id.id,
'location_dest_id': move3.location_dest_id.id,
'lot_id': lot2.id,
})
quants = self.env['stock.quant'].search([
('location_id.usage', '=', 'internal'),
('product_id', '=', self.product_lot.id),
('quantity', '!=', 0),
])
self.assertEqual(len(quants), 2)
for quant in quants:
if quant.lot_id == lot1:
self.assertAlmostEqual(quant.in_date, initial_in_date_lot1, delta=timedelta(seconds=1))
elif quant.lot_id == lot2:
self.assertAlmostEqual(quant.in_date, initial_in_date_lot2, delta=timedelta(seconds=1))
def test_edit_initial_demand_1(self):
""" Increase initial demand once everything is reserved and check if
the existing move_line is updated.
"""
move1 = self.env['stock.move'].create({
'name': 'test_transit_1',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'picking_type_id': self.env.ref('stock.picking_type_in').id,
})
move1._action_confirm()
move1._action_assign()
move1.product_uom_qty = 15
# _action_assign is automatically called
self.assertEqual(move1.state, 'assigned')
self.assertEqual(move1.product_uom_qty, 15)
self.assertEqual(len(move1.move_line_ids), 1)
def test_edit_initial_demand_2(self):
""" Decrease initial demand once everything is reserved and check if
the existing move_line has been dropped after the updated and another
is created once the move is reserved.
"""
move1 = self.env['stock.move'].create({
'name': 'test_transit_1',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'picking_type_id': self.env.ref('stock.picking_type_in').id,
})
move1._action_confirm()
move1._action_assign()
self.assertEqual(move1.state, 'assigned')
move1.product_uom_qty = 5
self.assertEqual(move1.state, 'assigned')
self.assertEqual(move1.product_uom_qty, 5)
self.assertEqual(len(move1.move_line_ids), 1)
def test_initial_demand_3(self):
""" Increase the initial demand on a receipt picking, the system should automatically
reserve the new quantity.
"""
picking = self.env['stock.picking'].create({
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'picking_type_id': self.env.ref('stock.picking_type_in').id,
'immediate_transfer': True,
})
move1 = self.env['stock.move'].create({
'name': 'test_transit_1',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'quantity_done': 10.0,
'picking_id': picking.id,
})
picking._autoconfirm_picking()
self.assertEqual(picking.state, 'assigned')
move1.quantity_done = 12
self.assertEqual(picking.state, 'assigned')
def test_initial_demand_4(self):
""" Increase the initial demand on a delivery picking, the system should not automatically
reserve the new quantity.
"""
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 12)
picking = self.env['stock.picking'].create({
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'picking_type_id': self.env.ref('stock.picking_type_in').id,
})
move1 = self.env['stock.move'].create({
'name': 'test_transit_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'picking_id': picking.id,
})
picking.action_confirm()
picking.action_assign()
self.assertEqual(picking.state, 'assigned')
move1.product_uom_qty = 12
self.assertEqual(picking.state, 'assigned') # actually, partially available
self.assertEqual(move1.state, 'partially_available')
picking.action_assign()
self.assertEqual(move1.state, 'assigned')
def test_change_product_type(self):
""" Changing type of an existing product will raise a user error if
- some move are reserved
- switching from a stockable product when qty_available is not zero
- switching the product type when there are already done moves
"""
move_in = self.env['stock.move'].create({
'name': 'test_customer',
'location_id': self.customer_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 5,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
})
move_in._action_confirm()
move_in._action_assign()
# Check raise UserError(_("You can not change the type of a product that is currently reserved on a stock
with self.assertRaises(UserError):
self.product.detailed_type = 'consu'
move_in._action_cancel()
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 10)
# Check raise UserError(_("Available quantity should be set to zero before changing detailed_type"))
with self.assertRaises(UserError):
self.product.detailed_type = 'consu'
move_out = self.env['stock.move'].create({
'name': 'test_customer',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': self.product.qty_available,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
})
move_out._action_confirm()
move_out._action_assign()
move_out.quantity_done = self.product.qty_available
move_out._action_done()
# Check raise UserError(_("You can not change the type of a product that was already used."))
with self.assertRaises(UserError):
self.product.detailed_type = 'consu'
move2 = self.env['stock.move'].create({
'name': 'test_customer',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 5,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
})
move2._action_confirm()
move2._action_assign()
with self.assertRaises(UserError):
self.product.detailed_type = 'consu'
move2._action_cancel()
with self.assertRaises(UserError):
self.product.detailed_type = 'consu'
def test_edit_done_picking_1(self):
""" Add a new move line in a done picking should generate an
associated move.
"""
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 12)
picking = self.env['stock.picking'].create({
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'picking_type_id': self.env.ref('stock.picking_type_in').id,
})
move1 = self.env['stock.move'].create({
'name': 'test_transit_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'picking_id': picking.id,
})
picking.action_confirm()
picking.action_assign()
move1.quantity_done = 10
picking._action_done()
self.assertEqual(len(picking.move_lines), 1, 'One move should exist for the picking.')
self.assertEqual(len(picking.move_line_ids), 1, 'One move line should exist for the picking.')
ml = self.env['stock.move.line'].create({
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom_id': self.uom_unit.id,
'qty_done': 2.0,
'picking_id': picking.id,
})
self.assertEqual(len(picking.move_lines), 2, 'The new move associated to the move line does not exist.')
self.assertEqual(len(picking.move_line_ids), 2, 'It should be 2 move lines for the picking.')
self.assertTrue(ml.move_id in picking.move_lines, 'Links are not correct between picking, moves and move lines.')
self.assertEqual(picking.state, 'done', 'Picking should still done after adding a new move line.')
self.assertTrue(all(move.state == 'done' for move in picking.move_lines), 'Wrong state for move.')
def test_put_in_pack_1(self):
""" Check that reserving a move and adding its move lines to
different packages work as expected.
"""
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 2)
picking = self.env['stock.picking'].create({
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
})
move1 = self.env['stock.move'].create({
'name': 'test_transit_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 2.0,
'picking_id': picking.id,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
})
picking.action_confirm()
picking.action_assign()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0)
move1.quantity_done = 1
picking.action_put_in_pack()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0)
self.assertEqual(len(picking.move_line_ids), 2)
unpacked_ml = picking.move_line_ids.filtered(lambda ml: not ml.result_package_id)
self.assertEqual(unpacked_ml.product_qty, 1)
unpacked_ml.qty_done = 1
picking.action_put_in_pack()
self.assertEqual(len(picking.move_line_ids), 2)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0)
picking.button_validate()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.customer_location), 2)
def test_put_in_pack_2(self):
"""Check that reserving moves without done quantity
adding in same package.
"""
product1 = self.env['product.product'].create({
'name': 'Product B',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
})
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1)
self.env['stock.quant']._update_available_quantity(product1, self.stock_location, 2)
picking = self.env['stock.picking'].create({
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
})
move1 = self.env['stock.move'].create({
'name': 'test_transit_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
'picking_id': picking.id,
})
move2 = self.env['stock.move'].create({
'name': 'test_transit_2',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 2.0,
'picking_id': picking.id,
})
picking.action_confirm()
picking.action_assign()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(product1, self.stock_location), 0)
picking.action_put_in_pack()
self.assertEqual(len(picking.move_line_ids), 2)
self.assertEqual(picking.move_line_ids[0].qty_done, 1, "Stock move line should have 1 quantity as a done quantity.")
self.assertEqual(picking.move_line_ids[1].qty_done, 2, "Stock move line should have 2 quantity as a done quantity.")
line1_result_package = picking.move_line_ids[0].result_package_id
line2_result_package = picking.move_line_ids[1].result_package_id
self.assertEqual(line1_result_package, line2_result_package, "Product and Product1 should be in a same package.")
def test_put_in_pack_3(self):
"""Check that one reserving move without done quantity and
another reserving move with done quantity adding in different
package.
"""
product1 = self.env['product.product'].create({
'name': 'Product B',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
})
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 1)
self.env['stock.quant']._update_available_quantity(product1, self.stock_location, 2)
picking = self.env['stock.picking'].create({
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
})
move1 = self.env['stock.move'].create({
'name': 'test_transit_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
'picking_id': picking.id,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
})
move2 = self.env['stock.move'].create({
'name': 'test_transit_2',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 2.0,
'picking_id': picking.id,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
})
picking.action_confirm()
picking.action_assign()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(product1, self.stock_location), 0)
move1.quantity_done = 1
picking.action_put_in_pack()
move2.quantity_done = 2
picking.action_put_in_pack()
self.assertEqual(len(picking.move_line_ids), 2)
line1_result_package = picking.move_line_ids[0].result_package_id
line2_result_package = picking.move_line_ids[1].result_package_id
self.assertNotEqual(line1_result_package, line2_result_package, "Product and Product1 should be in a different package.")
def test_move_line_aggregated_product_quantities(self):
""" Test the `stock.move.line` method `_get_aggregated_product_quantities`,
who returns data used to print delivery slips.
"""
# Creates two other products.
product2 = self.env['product.product'].create({
'name': 'Product B',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
})
product3 = self.env['product.product'].create({
'name': 'Product C',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
})
# Adds some quantity on stock.
self.env['stock.quant'].with_context(inventory_mode=True).create([{
'product_id': self.product.id,
'inventory_quantity': 100,
'location_id': self.stock_location.id,
}, {
'product_id': product2.id,
'inventory_quantity': 100,
'location_id': self.stock_location.id,
}, {
'product_id': product3.id,
'inventory_quantity': 100,
'location_id': self.stock_location.id,
}]).action_apply_inventory()
# Creates a delivery for a bunch of products.
delivery_form = Form(self.env['stock.picking'])
delivery_form.picking_type_id = self.env.ref('stock.picking_type_out')
with delivery_form.move_ids_without_package.new() as move:
move.product_id = self.product
move.product_uom_qty = 10
with delivery_form.move_ids_without_package.new() as move:
move.product_id = product2
move.product_uom_qty = 10
with delivery_form.move_ids_without_package.new() as move:
move.product_id = product3
move.product_uom_qty = 10
delivery = delivery_form.save()
delivery.action_confirm()
# Delivers a part of the quantity, creates a backorder for the remaining qty.
delivery.move_line_ids.filtered(lambda ml: ml.product_id == self.product).qty_done = 6
delivery.move_line_ids.filtered(lambda ml: ml.product_id == product2).qty_done = 2
backorder_wizard_dict = delivery.button_validate()
backorder_wizard_form = Form(self.env[backorder_wizard_dict['res_model']].with_context(backorder_wizard_dict['context']))
backorder_wizard_form.save().process() # Creates the backorder.
first_backorder = self.env['stock.picking'].search([('backorder_id', '=', delivery.id)], limit=1)
# Checks the values.
aggregate_values = delivery.move_line_ids._get_aggregated_product_quantities()
self.assertEqual(len(aggregate_values), 2)
sml1 = delivery.move_line_ids.filtered(lambda ml: ml.product_id == self.product)
sml2 = delivery.move_line_ids.filtered(lambda ml: ml.product_id == product2)
aggregate_val_1 = aggregate_values[f'{self.product.id}_{self.product.name}__{sml1.product_uom_id.id}']
aggregate_val_2 = aggregate_values[f'{product2.id}_{product2.name}__{sml2.product_uom_id.id}']
self.assertEqual(aggregate_val_1['qty_ordered'], 10)
self.assertEqual(aggregate_val_1['qty_done'], 6)
self.assertEqual(aggregate_val_2['qty_ordered'], 10)
self.assertEqual(aggregate_val_2['qty_done'], 2)
# Delivers a part of the BO's qty., and creates an another backorder.
first_backorder.move_line_ids.filtered(lambda ml: ml.product_id == self.product).qty_done = 4
first_backorder.move_line_ids.filtered(lambda ml: ml.product_id == product2).qty_done = 6
first_backorder.move_line_ids.filtered(lambda ml: ml.product_id == product3).qty_done = 7
backorder_wizard_dict = first_backorder.button_validate()
backorder_wizard_form = Form(self.env[backorder_wizard_dict['res_model']].with_context(backorder_wizard_dict['context']))
backorder_wizard_form.save().process() # Creates the backorder.
second_backorder = self.env['stock.picking'].search([('backorder_id', '=', first_backorder.id)], limit=1)
# Checks the values for the original delivery.
aggregate_values = delivery.move_line_ids._get_aggregated_product_quantities()
self.assertEqual(len(aggregate_values), 2)
sml1 = delivery.move_line_ids.filtered(lambda ml: ml.product_id == self.product)
sml2 = delivery.move_line_ids.filtered(lambda ml: ml.product_id == product2)
aggregate_val_1 = aggregate_values[f'{self.product.id}_{self.product.name}__{sml1.product_uom_id.id}']
aggregate_val_2 = aggregate_values[f'{product2.id}_{product2.name}__{sml2.product_uom_id.id}']
self.assertEqual(aggregate_val_1['qty_ordered'], 10)
self.assertEqual(aggregate_val_1['qty_done'], 6)
self.assertEqual(aggregate_val_2['qty_ordered'], 10)
self.assertEqual(aggregate_val_2['qty_done'], 2)
# Checks the values for the first back order.
aggregate_values = first_backorder.move_line_ids._get_aggregated_product_quantities()
self.assertEqual(len(aggregate_values), 3)
sml1 = first_backorder.move_line_ids.filtered(lambda ml: ml.product_id == self.product)
sml2 = first_backorder.move_line_ids.filtered(lambda ml: ml.product_id == product2)
sml3 = first_backorder.move_line_ids.filtered(lambda ml: ml.product_id == product3)
aggregate_val_1 = aggregate_values[f'{self.product.id}_{self.product.name}__{sml1.product_uom_id.id}']
aggregate_val_2 = aggregate_values[f'{product2.id}_{product2.name}__{sml2.product_uom_id.id}']
aggregate_val_3 = aggregate_values[f'{product3.id}_{product3.name}__{sml3.product_uom_id.id}']
self.assertEqual(aggregate_val_1['qty_ordered'], 4)
self.assertEqual(aggregate_val_1['qty_done'], 4)
self.assertEqual(aggregate_val_2['qty_ordered'], 8)
self.assertEqual(aggregate_val_2['qty_done'], 6)
self.assertEqual(aggregate_val_3['qty_ordered'], 10)
self.assertEqual(aggregate_val_3['qty_done'], 7)
# Delivers a part of the second BO's qty. but doesn't create a backorder this time.
second_backorder.move_line_ids.filtered(lambda ml: ml.product_id == product3).qty_done = 3
backorder_wizard_dict = second_backorder.button_validate()
backorder_wizard_form = Form(self.env[backorder_wizard_dict['res_model']].with_context(backorder_wizard_dict['context']))
backorder_wizard_form.save().process_cancel_backorder()
# Checks again the values for the original delivery.
aggregate_values = delivery.move_line_ids._get_aggregated_product_quantities()
self.assertEqual(len(aggregate_values), 2)
sml1 = delivery.move_line_ids.filtered(lambda ml: ml.product_id == self.product)
sml2 = delivery.move_line_ids.filtered(lambda ml: ml.product_id == product2)
aggregate_val_1 = aggregate_values[f'{self.product.id}_{self.product.name}__{sml1.product_uom_id.id}']
aggregate_val_2 = aggregate_values[f'{product2.id}_{product2.name}__{sml2.product_uom_id.id}']
self.assertEqual(aggregate_val_1['qty_ordered'], 10)
self.assertEqual(aggregate_val_1['qty_done'], 6)
self.assertEqual(aggregate_val_2['qty_ordered'], 10)
self.assertEqual(aggregate_val_2['qty_done'], 2)
# Checks again the values for the first back order.
aggregate_values = first_backorder.move_line_ids._get_aggregated_product_quantities()
self.assertEqual(len(aggregate_values), 3)
sml1 = first_backorder.move_line_ids.filtered(lambda ml: ml.product_id == self.product)
sml2 = first_backorder.move_line_ids.filtered(lambda ml: ml.product_id == product2)
sml3 = first_backorder.move_line_ids.filtered(lambda ml: ml.product_id == product3)
aggregate_val_1 = aggregate_values[f'{self.product.id}_{self.product.name}__{sml1.product_uom_id.id}']
aggregate_val_2 = aggregate_values[f'{product2.id}_{product2.name}__{sml2.product_uom_id.id}']
aggregate_val_3 = aggregate_values[f'{product3.id}_{product3.name}__{sml3.product_uom_id.id}']
self.assertEqual(aggregate_val_1['qty_ordered'], 4)
self.assertEqual(aggregate_val_1['qty_done'], 4)
self.assertEqual(aggregate_val_2['qty_ordered'], 8)
self.assertEqual(aggregate_val_2['qty_done'], 6)
self.assertEqual(aggregate_val_3['qty_ordered'], 10)
self.assertEqual(aggregate_val_3['qty_done'], 7)
# Checks the values for the second back order.
aggregate_values = second_backorder.move_line_ids._get_aggregated_product_quantities()
self.assertEqual(len(aggregate_values), 2)
sml1 = second_backorder.move_line_ids.filtered(lambda ml: ml.product_id == product3)
sm2 = second_backorder.move_lines.filtered(lambda ml: ml.product_id == product2)
aggregate_val_1 = aggregate_values[f'{product3.id}_{product3.name}__{sml1.product_uom_id.id}']
aggregate_val_2 = aggregate_values[f'{product2.id}_{product2.name}__{sm2.product_uom.id}']
self.assertEqual(aggregate_val_1['qty_ordered'], 3)
self.assertEqual(aggregate_val_1['qty_done'], 3)
self.assertEqual(aggregate_val_2['qty_ordered'], 2)
self.assertEqual(aggregate_val_2['qty_done'], 0)
def test_move_line_aggregated_product_quantities_duplicate_stock_move(self):
""" Test the `stock.move.line` method `_get_aggregated_product_quantities`,
which returns data used to print delivery slips, with two stock moves of the same product
"""
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 25)
picking = self.env['stock.picking'].create({
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
})
move1 = self.env['stock.move'].create({
'name': 'test_transit_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 10.0,
'picking_id': picking.id,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
})
move2 = self.env['stock.move'].create({
'name': 'test_transit_2',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 5.0,
'picking_id': picking.id,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
})
self.env['stock.move.line'].create({
'move_id': move1.id,
'product_id': move1.product_id.id,
'qty_done': 10,
'product_uom_id': move1.product_uom.id,
'picking_id': picking.id,
'location_id': move1.location_id.id,
'location_dest_id': move1.location_dest_id.id,
})
self.env['stock.move.line'].create({
'move_id': move2.id,
'product_id': move2.product_id.id,
'qty_done': 5,
'product_uom_id': move2.product_uom.id,
'picking_id': picking.id,
'location_id': move2.location_id.id,
'location_dest_id': move2.location_dest_id.id,
})
aggregate_values = picking.move_line_ids._get_aggregated_product_quantities()
aggregated_val = aggregate_values[f'{self.product.id}_{self.product.name}__{self.product.uom_id.id}']
self.assertEqual(aggregated_val['qty_ordered'], 15)
picking.button_validate()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 10)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.customer_location), 15)
def test_move_line_aggregated_product_quantities_two_packages(self):
""" Test the `stock.move.line` method `_get_aggregated_product_quantities`,
which returns data used to print delivery slips, with two packages
"""
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 25)
picking = self.env['stock.picking'].create({
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
})
move1 = self.env['stock.move'].create({
'name': 'test_transit_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 15.0,
'picking_id': picking.id,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
})
picking.action_confirm()
picking.action_assign()
move1.quantity_done = 5
picking.action_put_in_pack() # Create a first package
self.assertEqual(len(picking.move_line_ids), 2)
unpacked_ml = picking.move_line_ids.filtered(lambda ml: not ml.result_package_id)
self.assertEqual(unpacked_ml.product_qty, 10)
unpacked_ml.qty_done = 10
picking.action_put_in_pack() # Create a second package
self.assertEqual(len(picking.move_line_ids), 2)
picking.button_validate()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 10)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.customer_location), 15)
aggregate_values1 = picking.move_line_ids[0]._get_aggregated_product_quantities(strict=True)
aggregated_val = aggregate_values1[f'{self.product.id}_{self.product.name}__{self.product.uom_id.id}']
self.assertEqual(aggregated_val['qty_ordered'], 10)
aggregate_values2 = picking.move_line_ids[1]._get_aggregated_product_quantities(strict=True)
aggregated_val = aggregate_values2[f'{self.product.id}_{self.product.name}__{self.product.uom_id.id}']
self.assertEqual(aggregated_val['qty_ordered'], 5)
def test_move_line_aggregated_product_quantities_incomplete_package(self):
""" Test the `stock.move.line` method `_get_aggregated_product_quantities`,
which returns data used to print delivery slips, with an incomplete order put in packages
"""
self.env['stock.quant']._update_available_quantity(self.product, self.stock_location, 25)
picking = self.env['stock.picking'].create({
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
})
move1 = self.env['stock.move'].create({
'name': 'test_transit_1',
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 15.0,
'picking_id': picking.id,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
})
move1.quantity_done = 5
picking.action_put_in_pack() # Create a package
delivery_form = Form(picking)
delivery = delivery_form.save()
delivery.action_confirm()
backorder_wizard_dict = delivery.button_validate()
backorder_wizard_form = Form(self.env[backorder_wizard_dict['res_model']].with_context(backorder_wizard_dict['context']))
backorder_wizard_form.save().process_cancel_backorder() # Don't create a backorder
aggregate_values = picking.move_line_ids._get_aggregated_product_quantities()
aggregated_val = aggregate_values[f'{self.product.id}_{self.product.name}__{self.product.uom_id.id}']
self.assertEqual(aggregated_val['qty_ordered'], 15)
self.assertEqual(aggregated_val['qty_done'], 5)
aggregate_values = picking.move_line_ids._get_aggregated_product_quantities(strict=True)
aggregated_val = aggregate_values[f'{self.product.id}_{self.product.name}__{self.product.uom_id.id}']
self.assertEqual(aggregated_val['qty_ordered'], 5)
self.assertEqual(aggregated_val['qty_done'], 5)
aggregate_values = picking.move_line_ids._get_aggregated_product_quantities(except_package=True)
aggregated_val = aggregate_values[f'{self.product.id}_{self.product.name}__{self.product.uom_id.id}']
self.assertEqual(aggregated_val['qty_ordered'], 10)
self.assertEqual(aggregated_val['qty_done'], False)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.stock_location), 20)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.product, self.customer_location), 5)
def test_move_sn_warning(self):
""" Check that warnings pop up when duplicate SNs added or when SN isn't in
expected location.
Two cases covered:
- Check for dupes when assigning serial number to a stock move
- Check for dupes when assigning serial number to a stock move line
"""
lot1 = self.env['stock.production.lot'].create({
'name': 'serial1',
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
self.env['stock.quant']._update_available_quantity(self.product_serial, self.pack_location, 1, lot1)
move = self.env['stock.move'].create({
'name': 'test sn',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product_serial.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move_line = self.env['stock.move.line'].create({
'move_id': move.id,
'product_id': move.product_id.id,
'qty_done': 1,
'product_uom_id': move.product_uom.id,
'location_id': move.location_id.id,
'location_dest_id': move.location_dest_id.id,
'lot_name': lot1.name,
})
warning = False
warning = move_line._onchange_serial_number()
self.assertTrue(warning, 'Reuse of existing serial number (name) not detected')
self.assertEqual(list(warning.keys())[0], 'warning', 'Warning message was not returned')
move_line.write({
'lot_name': False,
'lot_id': lot1.id
})
warning = False
warning = move_line._onchange_serial_number()
self.assertTrue(warning, 'Reuse of existing serial number (record) not detected')
self.assertEqual(list(warning.keys())[0], 'warning', 'Warning message was not returned')
self.assertEqual(move_line.location_id, self.pack_location, 'Location was not auto-corrected')
move.lot_ids = lot1
warning = False
warning = move._onchange_lot_ids()
self.assertTrue(warning, 'Reuse of existing serial number (record) not detected')
self.assertEqual(list(warning.keys())[0], 'warning', 'Warning message was not returned')
def test_forecast_availability(self):
""" Make an outgoing picking in dozens for a product stored in units.
Check that reserved_availabity is expressed in move uom and forecast_availability is in product base uom
"""
# create product
product = self.env['product.product'].create({
'name': 'Product In Units',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
})
# make some stock
self.env['stock.quant']._update_available_quantity(product, self.stock_location, 36.0)
# create picking
picking_out = self.env['stock.picking'].create({
'picking_type_id': self.env.ref('stock.picking_type_out').id,
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id})
move = self.env['stock.move'].create({
'name': product.name,
'product_id': product.id,
'product_uom': self.uom_dozen.id,
'product_uom_qty': 2.0,
'picking_id': picking_out.id,
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id})
# confirm
picking_out.action_confirm()
# check availability
picking_out.action_assign()
# check reserved_availabity expressed in move uom
self.assertEqual(move.reserved_availability, 2)
# check forecast_availability expressed in product base uom
self.assertEqual(move.forecast_availability, 24)
def test_SML_location_selection(self):
"""
Suppose the setting 'Storage Categories' disabled and the option 'Show Detailed Operations'
for operation 'Internal Transfer' enabled.
A user creates an internal transfer from F to T, confirms it then adds a SML and selects
another destination location L (with L a child of T). When the user completes the field
`qty_done`, the onchange should n't change the destination location L
"""
self.env.user.write({'groups_id': [(3, self.env.ref('stock.group_stock_storage_categories').id)]})
internal_transfer = self.env.ref('stock.picking_type_internal')
internal_transfer.show_operations = True
picking = self.env['stock.picking'].create({
'picking_type_id': internal_transfer.id,
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
})
self.env['stock.move'].create({
'name': self.product_consu.name,
'product_id': self.product_consu.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 2.0,
'picking_id': picking.id,
'location_id': picking.location_id.id,
'location_dest_id': picking.location_dest_id.id,
})
picking.action_confirm()
with Form(picking) as form:
with form.move_line_ids_without_package.edit(0) as line:
line.location_dest_id = self.stock_location.child_ids[0]
line.qty_done = 1
self.assertEqual(picking.move_line_ids_without_package.location_dest_id, self.stock_location.child_ids[0])
def test_inter_wh_and_forecast_availability(self):
dest_wh = self.env['stock.warehouse'].create({
'name': 'Second Warehouse',
'code': 'WH02',
})
move = self.env['stock.move'].create({
'name': 'test_interwh',
'location_id': self.stock_location.id,
'location_dest_id': dest_wh.lot_stock_id.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
self.assertEqual(move.forecast_availability, -1)
move._action_confirm()
self.assertEqual(move.forecast_availability, -1)
def test_receive_more_and_in_child_location(self):
"""
Ensure that, when receiving more than expected, and when the destination
location of the SML is different from the SM one, the SM validation will
not change the destination location of the SML
"""
move = self.env['stock.move'].create({
'name': self.product.name,
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move._action_confirm()
move.move_line_ids.write({
'location_dest_id': self.stock_location.child_ids[0].id,
'qty_done': 3,
})
move._action_done()
self.assertEqual(move.move_line_ids.qty_done, 3)
self.assertEqual(move.move_line_ids.location_dest_id, self.stock_location.child_ids[0])
| 46.878985
| 280,852
|
127,356
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo.addons.stock.tests.common import TestStockCommon
from odoo.exceptions import ValidationError
from odoo.tests import Form
from odoo.tools import mute_logger, float_round
from odoo import fields
class TestStockFlow(TestStockCommon):
def setUp(cls):
super(TestStockFlow, cls).setUp()
decimal_product_uom = cls.env.ref('product.decimal_product_uom')
decimal_product_uom.digits = 3
cls.partner_company2 = cls.env['res.partner'].create({
'name': 'My Company (Chicago)-demo',
'email': 'chicago@yourcompany.com',
'company_id': False,
})
cls.company = cls.env['res.company'].create({
'currency_id': cls.env.ref('base.USD').id,
'partner_id': cls.partner_company2.id,
'name': 'My Company (Chicago)-demo',
})
@mute_logger('odoo.addons.base.models.ir_model', 'odoo.models')
def test_00_picking_create_and_transfer_quantity(self):
""" Basic stock operation on incoming and outgoing shipment. """
LotObj = self.env['stock.production.lot']
# ----------------------------------------------------------------------
# Create incoming shipment of product A, B, C, D
# ----------------------------------------------------------------------
# Product A ( 1 Unit ) , Product C ( 10 Unit )
# Product B ( 1 Unit ) , Product D ( 10 Unit )
# Product D ( 5 Unit )
# ----------------------------------------------------------------------
picking_in = self.PickingObj.create({
'picking_type_id': self.picking_type_in,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location})
move_a = self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 1,
'product_uom': self.productA.uom_id.id,
'picking_id': picking_in.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location})
move_b = self.MoveObj.create({
'name': self.productB.name,
'product_id': self.productB.id,
'product_uom_qty': 1,
'product_uom': self.productB.uom_id.id,
'picking_id': picking_in.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location})
move_c = self.MoveObj.create({
'name': self.productC.name,
'product_id': self.productC.id,
'product_uom_qty': 10,
'product_uom': self.productC.uom_id.id,
'picking_id': picking_in.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location})
move_d = self.MoveObj.create({
'name': self.productD.name,
'product_id': self.productD.id,
'product_uom_qty': 10,
'product_uom': self.productD.uom_id.id,
'picking_id': picking_in.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location})
self.MoveObj.create({
'name': self.productD.name,
'product_id': self.productD.id,
'product_uom_qty': 5,
'product_uom': self.productD.uom_id.id,
'picking_id': picking_in.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location})
# Check incoming shipment move lines state.
for move in picking_in.move_lines:
self.assertEqual(move.state, 'draft', 'Wrong state of move line.')
# Confirm incoming shipment.
picking_in.action_confirm()
# Check incoming shipment move lines state.
for move in picking_in.move_lines:
self.assertEqual(move.state, 'assigned', 'Wrong state of move line.')
# ----------------------------------------------------------------------
# Replace pack operation of incoming shipments.
# ----------------------------------------------------------------------
picking_in.action_assign()
move_a.move_line_ids.qty_done = 4
move_b.move_line_ids.qty_done = 5
move_c.move_line_ids.qty_done = 5
move_d.move_line_ids.qty_done = 5
lot2_productC = LotObj.create({'name': 'C Lot 2', 'product_id': self.productC.id, 'company_id': self.env.company.id})
self.StockPackObj.create({
'product_id': self.productC.id,
'qty_done': 2,
'product_uom_id': self.productC.uom_id.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location,
'move_id': move_c.id,
'lot_id': lot2_productC.id,
})
self.StockPackObj.create({
'product_id': self.productD.id,
'qty_done': 2,
'product_uom_id': self.productD.uom_id.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location,
'move_id': move_d.id
})
# Check incoming shipment total quantity of pack operation
total_qty = sum(self.StockPackObj.search([('move_id', 'in', picking_in.move_lines.ids)]).mapped('qty_done'))
self.assertEqual(total_qty, 23, 'Wrong quantity in pack operation')
# Transfer Incoming Shipment.
picking_in._action_done()
# ----------------------------------------------------------------------
# Check state, quantity and total moves of incoming shipment.
# ----------------------------------------------------------------------
# Check total no of move lines of incoming shipment. move line e disappear from original picking to go in backorder.
self.assertEqual(len(picking_in.move_lines), 4, 'Wrong number of move lines.')
# Check incoming shipment state.
self.assertEqual(picking_in.state, 'done', 'Incoming shipment state should be done.')
# Check incoming shipment move lines state.
for move in picking_in.move_lines:
self.assertEqual(move.state, 'done', 'Wrong state of move line.')
# Check product A done quantity must be 3 and 1
moves = self.MoveObj.search([('product_id', '=', self.productA.id), ('picking_id', '=', picking_in.id)])
self.assertEqual(moves.product_uom_qty, 4.0, 'Wrong move quantity for product A.')
# Check product B done quantity must be 4 and 1
moves = self.MoveObj.search([('product_id', '=', self.productB.id), ('picking_id', '=', picking_in.id)])
self.assertEqual(moves.product_uom_qty, 5.0, 'Wrong move quantity for product B.')
# Check product C done quantity must be 7
c_done_qty = self.MoveObj.search([('product_id', '=', self.productC.id), ('picking_id', '=', picking_in.id)], limit=1).product_uom_qty
self.assertEqual(c_done_qty, 7.0, 'Wrong move quantity of product C (%s found instead of 7)' % (c_done_qty))
# Check product D done quantity must be 7
d_done_qty = self.MoveObj.search([('product_id', '=', self.productD.id), ('picking_id', '=', picking_in.id)], limit=1).product_uom_qty
self.assertEqual(d_done_qty, 7.0, 'Wrong move quantity of product D (%s found instead of 7)' % (d_done_qty))
# ----------------------------------------------------------------------
# Check Back order of Incoming shipment.
# ----------------------------------------------------------------------
# Check back order created or not.
back_order_in = self.PickingObj.search([('backorder_id', '=', picking_in.id)])
self.assertEqual(len(back_order_in), 1, 'Back order should be created.')
# Check total move lines of back order.
self.assertEqual(len(back_order_in.move_lines), 2, 'Wrong number of move lines.')
# Check back order should be created with 3 quantity of product C.
moves = self.MoveObj.search([('product_id', '=', self.productC.id), ('picking_id', '=', back_order_in.id)])
product_c_qty = [move.product_uom_qty for move in moves]
self.assertEqual(sum(product_c_qty), 3.0, 'Wrong move quantity of product C (%s found instead of 3)' % (product_c_qty))
# Check back order should be created with 8 quantity of product D.
moves = self.MoveObj.search([('product_id', '=', self.productD.id), ('picking_id', '=', back_order_in.id)])
product_d_qty = [move.product_uom_qty for move in moves]
self.assertEqual(sum(product_d_qty), 8.0, 'Wrong move quantity of product D (%s found instead of 8)' % (product_d_qty))
# ======================================================================
# Create Outgoing shipment with ...
# product A ( 10 Unit ) , product B ( 5 Unit )
# product C ( 3 unit ) , product D ( 10 Unit )
# ======================================================================
picking_out = self.PickingObj.create({
'picking_type_id': self.picking_type_out,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
move_cust_a = self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 10,
'product_uom': self.productA.uom_id.id,
'picking_id': picking_out.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
move_cust_b = self.MoveObj.create({
'name': self.productB.name,
'product_id': self.productB.id,
'product_uom_qty': 5,
'product_uom': self.productB.uom_id.id,
'picking_id': picking_out.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
move_cust_c = self.MoveObj.create({
'name': self.productC.name,
'product_id': self.productC.id,
'product_uom_qty': 3,
'product_uom': self.productC.uom_id.id,
'picking_id': picking_out.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
move_cust_d = self.MoveObj.create({
'name': self.productD.name,
'product_id': self.productD.id,
'product_uom_qty': 10,
'product_uom': self.productD.uom_id.id,
'picking_id': picking_out.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
# Confirm outgoing shipment.
picking_out.action_confirm()
for move in picking_out.move_lines:
self.assertEqual(move.state, 'confirmed', 'Wrong state of move line.')
# Product assign to outgoing shipments
picking_out.action_assign()
self.assertEqual(move_cust_a.state, 'partially_available', 'Wrong state of move line.')
self.assertEqual(move_cust_b.state, 'assigned', 'Wrong state of move line.')
self.assertEqual(move_cust_c.state, 'assigned', 'Wrong state of move line.')
self.assertEqual(move_cust_d.state, 'partially_available', 'Wrong state of move line.')
# Check availability for product A
aval_a_qty = self.MoveObj.search([('product_id', '=', self.productA.id), ('picking_id', '=', picking_out.id)], limit=1).reserved_availability
self.assertEqual(aval_a_qty, 4.0, 'Wrong move quantity availability of product A (%s found instead of 4)' % (aval_a_qty))
# Check availability for product B
aval_b_qty = self.MoveObj.search([('product_id', '=', self.productB.id), ('picking_id', '=', picking_out.id)], limit=1).reserved_availability
self.assertEqual(aval_b_qty, 5.0, 'Wrong move quantity availability of product B (%s found instead of 5)' % (aval_b_qty))
# Check availability for product C
aval_c_qty = self.MoveObj.search([('product_id', '=', self.productC.id), ('picking_id', '=', picking_out.id)], limit=1).reserved_availability
self.assertEqual(aval_c_qty, 3.0, 'Wrong move quantity availability of product C (%s found instead of 3)' % (aval_c_qty))
# Check availability for product D
aval_d_qty = self.MoveObj.search([('product_id', '=', self.productD.id), ('picking_id', '=', picking_out.id)], limit=1).reserved_availability
self.assertEqual(aval_d_qty, 7.0, 'Wrong move quantity availability of product D (%s found instead of 7)' % (aval_d_qty))
# ----------------------------------------------------------------------
# Replace pack operation of outgoing shipment.
# ----------------------------------------------------------------------
move_cust_a.move_line_ids.qty_done = 2.0
move_cust_b.move_line_ids.qty_done = 3.0
self.StockPackObj.create({
'product_id': self.productB.id,
'qty_done': 2,
'product_uom_id': self.productB.uom_id.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
'move_id': move_cust_b.id})
# TODO care if product_qty and lot_id are set at the same times the system do 2 unreserve.
move_cust_c.move_line_ids[0].write({
'qty_done': 2.0,
'lot_id': lot2_productC.id,
})
self.StockPackObj.create({
'product_id': self.productC.id,
'qty_done': 3.0,
'product_uom_id': self.productC.uom_id.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
'move_id': move_cust_c.id})
move_cust_d.move_line_ids.qty_done = 6.0
# Transfer picking.
picking_out._action_done()
# ----------------------------------------------------------------------
# Check state, quantity and total moves of outgoing shipment.
# ----------------------------------------------------------------------
# check outgoing shipment status.
self.assertEqual(picking_out.state, 'done', 'Wrong state of outgoing shipment.')
# check outgoing shipment total moves and and its state.
self.assertEqual(len(picking_out.move_lines), 4, 'Wrong number of move lines')
for move in picking_out.move_lines:
self.assertEqual(move.state, 'done', 'Wrong state of move line.')
back_order_out = self.PickingObj.search([('backorder_id', '=', picking_out.id)])
# ------------------
# Check back order.
# -----------------
self.assertEqual(len(back_order_out), 1, 'Back order should be created.')
# Check total move lines of back order.
self.assertEqual(len(back_order_out.move_lines), 2, 'Wrong number of move lines')
# Check back order should be created with 8 quantity of product A.
product_a_qty = self.MoveObj.search([('product_id', '=', self.productA.id), ('picking_id', '=', back_order_out.id)], limit=1).product_uom_qty
self.assertEqual(product_a_qty, 8.0, 'Wrong move quantity of product A (%s found instead of 8)' % (product_a_qty))
# Check back order should be created with 4 quantity of product D.
product_d_qty = self.MoveObj.search([('product_id', '=', self.productD.id), ('picking_id', '=', back_order_out.id)], limit=1).product_uom_qty
self.assertEqual(product_d_qty, 4.0, 'Wrong move quantity of product D (%s found instead of 4)' % (product_d_qty))
# -----------------------------------------------------------------------
# Check stock location quant quantity and quantity available
# of product A, B, C, D
# -----------------------------------------------------------------------
# Check quants and available quantity for product A
quants = self.StockQuantObj.search([('product_id', '=', self.productA.id), ('location_id', '=', self.stock_location)])
total_qty = [quant.quantity for quant in quants]
self.assertEqual(sum(total_qty), 2.0, 'Expecting 2.0 Unit , got %.4f Unit on location stock!' % (sum(total_qty)))
self.assertEqual(self.productA.qty_available, 2.0, 'Wrong quantity available (%s found instead of 2.0)' % (self.productA.qty_available))
# Check quants and available quantity for product B
quants = self.StockQuantObj.search([('product_id', '=', self.productB.id), ('location_id', '=', self.stock_location), ('quantity', '!=', 0)])
self.assertFalse(quants, 'No quant should found as outgoing shipment took everything out of stock.')
self.assertEqual(self.productB.qty_available, 0.0, 'Product B should have zero quantity available.')
# Check quants and available quantity for product C
quants = self.StockQuantObj.search([('product_id', '=', self.productC.id), ('location_id', '=', self.stock_location), ('quantity', '!=', 0)])
total_qty = [quant.quantity for quant in quants]
self.assertEqual(sum(total_qty), 2.0, 'Expecting 2.0 Unit, got %.4f Unit on location stock!' % (sum(total_qty)))
self.assertEqual(self.productC.qty_available, 2.0, 'Wrong quantity available (%s found instead of 2.0)' % (self.productC.qty_available))
# Check quants and available quantity for product D
quant = self.StockQuantObj.search([('product_id', '=', self.productD.id), ('location_id', '=', self.stock_location), ('quantity', '!=', 0)], limit=1)
self.assertEqual(quant.quantity, 1.0, 'Expecting 1.0 Unit , got %.4f Unit on location stock!' % (quant.quantity))
self.assertEqual(self.productD.qty_available, 1.0, 'Wrong quantity available (%s found instead of 1.0)' % (self.productD.qty_available))
# -----------------------------------------------------------------------
# Back Order of Incoming shipment
# -----------------------------------------------------------------------
lot3_productC = LotObj.create({'name': 'Lot 3', 'product_id': self.productC.id, 'company_id': self.env.company.id})
lot4_productC = LotObj.create({'name': 'Lot 4', 'product_id': self.productC.id, 'company_id': self.env.company.id})
lot5_productC = LotObj.create({'name': 'Lot 5', 'product_id': self.productC.id, 'company_id': self.env.company.id})
lot6_productC = LotObj.create({'name': 'Lot 6', 'product_id': self.productC.id, 'company_id': self.env.company.id})
lot1_productD = LotObj.create({'name': 'Lot 1', 'product_id': self.productD.id, 'company_id': self.env.company.id})
LotObj.create({'name': 'Lot 2', 'product_id': self.productD.id, 'company_id': self.env.company.id})
# Confirm back order of incoming shipment.
back_order_in.action_confirm()
self.assertEqual(back_order_in.state, 'assigned', 'Wrong state of incoming shipment back order: %s instead of %s' % (back_order_in.state, 'assigned'))
for move in back_order_in.move_lines:
self.assertEqual(move.state, 'assigned', 'Wrong state of move line.')
# ----------------------------------------------------------------------
# Replace pack operation (Back order of Incoming shipment)
# ----------------------------------------------------------------------
packD = self.StockPackObj.search([('product_id', '=', self.productD.id), ('picking_id', '=', back_order_in.id)], order='product_qty')
self.assertEqual(len(packD), 1, 'Wrong number of pack operation.')
packD[0].write({
'qty_done': 8,
'lot_id': lot1_productD.id,
})
packCs = self.StockPackObj.search([('product_id', '=', self.productC.id), ('picking_id', '=', back_order_in.id)], limit=1)
packCs.write({
'qty_done': 1,
'lot_id': lot3_productC.id,
})
self.StockPackObj.create({
'product_id': self.productC.id,
'qty_done': 1,
'product_uom_id': self.productC.uom_id.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location,
'picking_id': back_order_in.id,
'lot_id': lot4_productC.id,
})
self.StockPackObj.create({
'product_id': self.productC.id,
'qty_done': 2,
'product_uom_id': self.productC.uom_id.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location,
'picking_id': back_order_in.id,
'lot_id': lot5_productC.id,
})
self.StockPackObj.create({
'product_id': self.productC.id,
'qty_done': 2,
'product_uom_id': self.productC.uom_id.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location,
'picking_id': back_order_in.id,
'lot_id': lot6_productC.id,
})
self.StockPackObj.create({
'product_id': self.productA.id,
'qty_done': 10,
'product_uom_id': self.productA.uom_id.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location,
'picking_id': back_order_in.id
})
back_order_in._action_done()
# ----------------------------------------------------------------------
# Check state, quantity and total moves (Back order of Incoming shipment).
# ----------------------------------------------------------------------
# Check total no of move lines.
self.assertEqual(len(back_order_in.move_lines), 3, 'Wrong number of move lines')
# Check incoming shipment state must be 'Done'.
self.assertEqual(back_order_in.state, 'done', 'Wrong state of picking.')
# Check incoming shipment move lines state must be 'Done'.
for move in back_order_in.move_lines:
self.assertEqual(move.state, 'done', 'Wrong state of move lines.')
# Check product A done quantity must be 10
movesA = self.MoveObj.search([('product_id', '=', self.productA.id), ('picking_id', '=', back_order_in.id)])
self.assertEqual(movesA.product_uom_qty, 10, "Wrong move quantity of product A (%s found instead of 10)" % (movesA.product_uom_qty))
# Check product C done quantity must be 3.0, 1.0, 2.0
movesC = self.MoveObj.search([('product_id', '=', self.productC.id), ('picking_id', '=', back_order_in.id)])
self.assertEqual(movesC.product_uom_qty, 6.0, 'Wrong quantity of moves product C.')
# Check product D done quantity must be 5.0 and 3.0
movesD = self.MoveObj.search([('product_id', '=', self.productD.id), ('picking_id', '=', back_order_in.id)])
d_done_qty = [move.product_uom_qty for move in movesD]
self.assertEqual(set(d_done_qty), set([8.0]), 'Wrong quantity of moves product D.')
# Check no back order is created.
self.assertFalse(self.PickingObj.search([('backorder_id', '=', back_order_in.id)]), "Should not create any back order.")
# -----------------------------------------------------------------------
# Check stock location quant quantity and quantity available
# of product A, B, C, D
# -----------------------------------------------------------------------
# Check quants and available quantity for product A.
quants = self.StockQuantObj.search([('product_id', '=', self.productA.id), ('location_id', '=', self.stock_location), ('quantity', '!=', 0)])
total_qty = [quant.quantity for quant in quants]
self.assertEqual(sum(total_qty), 12.0, 'Wrong total stock location quantity (%s found instead of 12)' % (sum(total_qty)))
self.assertEqual(self.productA.qty_available, 12.0, 'Wrong quantity available (%s found instead of 12)' % (self.productA.qty_available))
# Check quants and available quantity for product B.
quants = self.StockQuantObj.search([('product_id', '=', self.productB.id), ('location_id', '=', self.stock_location), ('quantity', '!=', 0)])
self.assertFalse(quants, 'No quant should found as outgoing shipment took everything out of stock')
self.assertEqual(self.productB.qty_available, 0.0, 'Total quantity in stock should be 0 as the backorder took everything out of stock')
# Check quants and available quantity for product C.
quants = self.StockQuantObj.search([('product_id', '=', self.productC.id), ('location_id', '=', self.stock_location), ('quantity', '!=', 0)])
total_qty = [quant.quantity for quant in quants]
self.assertEqual(sum(total_qty), 8.0, 'Wrong total stock location quantity (%s found instead of 8)' % (sum(total_qty)))
self.assertEqual(self.productC.qty_available, 8.0, 'Wrong quantity available (%s found instead of 8)' % (self.productC.qty_available))
# Check quants and available quantity for product D.
quants = self.StockQuantObj.search([('product_id', '=', self.productD.id), ('location_id', '=', self.stock_location), ('quantity', '!=', 0)])
total_qty = [quant.quantity for quant in quants]
self.assertEqual(sum(total_qty), 9.0, 'Wrong total stock location quantity (%s found instead of 9)' % (sum(total_qty)))
self.assertEqual(self.productD.qty_available, 9.0, 'Wrong quantity available (%s found instead of 9)' % (self.productD.qty_available))
# -----------------------------------------------------------------------
# Back order of Outgoing shipment
# ----------------------------------------------------------------------
back_order_out._action_done()
# Check stock location quants and available quantity for product A.
quants = self.StockQuantObj.search([('product_id', '=', self.productA.id), ('location_id', '=', self.stock_location), ('quantity', '!=', 0)])
total_qty = [quant.quantity for quant in quants]
self.assertGreaterEqual(float_round(sum(total_qty), precision_rounding=0.0001), 1, 'Total stock location quantity for product A should not be nagative.')
def test_10_pickings_transfer_with_different_uom(self):
""" Picking transfer with diffrent unit of meassure. """
# ----------------------------------------------------------------------
# Create incoming shipment of products DozA, SDozA, SDozARound, kgB, gB
# ----------------------------------------------------------------------
# DozA ( 10 Dozen ) , SDozA ( 10.5 SuperDozen )
# SDozARound ( 10.5 10.5 SuperDozenRound ) , kgB ( 0.020 kg )
# gB ( 525.3 g )
# ----------------------------------------------------------------------
picking_in_A = self.PickingObj.create({
'picking_type_id': self.picking_type_in,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location})
self.MoveObj.create({
'name': self.DozA.name,
'product_id': self.DozA.id,
'product_uom_qty': 10,
'product_uom': self.DozA.uom_id.id,
'picking_id': picking_in_A.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location})
self.MoveObj.create({
'name': self.SDozA.name,
'product_id': self.SDozA.id,
'product_uom_qty': 10.5,
'product_uom': self.SDozA.uom_id.id,
'picking_id': picking_in_A.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location})
self.MoveObj.create({
'name': self.SDozARound.name,
'product_id': self.SDozARound.id,
'product_uom_qty': 10.5,
'product_uom': self.SDozARound.uom_id.id,
'picking_id': picking_in_A.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location})
self.MoveObj.create({
'name': self.kgB.name,
'product_id': self.kgB.id,
'product_uom_qty': 0.020,
'product_uom': self.kgB.uom_id.id,
'picking_id': picking_in_A.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location})
self.MoveObj.create({
'name': self.gB.name,
'product_id': self.gB.id,
'product_uom_qty': 525.3,
'product_uom': self.gB.uom_id.id,
'picking_id': picking_in_A.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location})
# Check incoming shipment move lines state.
for move in picking_in_A.move_lines:
self.assertEqual(move.state, 'draft', 'Move state must be draft.')
# Confirm incoming shipment.
picking_in_A.action_confirm()
# Check incoming shipment move lines state.
for move in picking_in_A.move_lines:
self.assertEqual(move.state, 'assigned', 'Move state must be draft.')
# ----------------------------------------------------
# Check pack operation quantity of incoming shipments.
# ----------------------------------------------------
PackSdozAround = self.StockPackObj.search([('product_id', '=', self.SDozARound.id), ('picking_id', '=', picking_in_A.id)], limit=1)
self.assertEqual(PackSdozAround.product_qty, 11, 'Wrong quantity in pack operation (%s found instead of 11)' % (PackSdozAround.product_qty))
res_dict = picking_in_A.button_validate()
wizard = Form(self.env[(res_dict.get('res_model'))].with_context(res_dict['context'])).save()
wizard.process()
# -----------------------------------------------------------------------
# Check stock location quant quantity and quantity available
# -----------------------------------------------------------------------
# Check quants and available quantity for product DozA
quants = self.StockQuantObj.search([('product_id', '=', self.DozA.id), ('location_id', '=', self.stock_location)])
total_qty = [quant.quantity for quant in quants]
self.assertEqual(sum(total_qty), 10, 'Expecting 10 Dozen , got %.4f Dozen on location stock!' % (sum(total_qty)))
self.assertEqual(self.DozA.qty_available, 10, 'Wrong quantity available (%s found instead of 10)' % (self.DozA.qty_available))
# Check quants and available quantity for product SDozA
quants = self.StockQuantObj.search([('product_id', '=', self.SDozA.id), ('location_id', '=', self.stock_location)])
total_qty = [quant.quantity for quant in quants]
self.assertEqual(sum(total_qty), 10.5, 'Expecting 10.5 SDozen , got %.4f SDozen on location stock!' % (sum(total_qty)))
self.assertEqual(self.SDozA.qty_available, 10.5, 'Wrong quantity available (%s found instead of 10.5)' % (self.SDozA.qty_available))
# Check quants and available quantity for product SDozARound
quants = self.StockQuantObj.search([('product_id', '=', self.SDozARound.id), ('location_id', '=', self.stock_location)])
total_qty = [quant.quantity for quant in quants]
self.assertEqual(sum(total_qty), 11, 'Expecting 11 SDozenRound , got %.4f SDozenRound on location stock!' % (sum(total_qty)))
self.assertEqual(self.SDozARound.qty_available, 11, 'Wrong quantity available (%s found instead of 11)' % (self.SDozARound.qty_available))
# Check quants and available quantity for product gB
quants = self.StockQuantObj.search([('product_id', '=', self.gB.id), ('location_id', '=', self.stock_location)])
total_qty = [quant.quantity for quant in quants]
self.assertAlmostEqual(sum(total_qty), 525.3, msg='Expecting 525.3 gram , got %.4f gram on location stock!' % (sum(total_qty)))
self.assertAlmostEqual(self.gB.qty_available, 525.3, msg='Wrong quantity available (%s found instead of 525.3' % (self.gB.qty_available))
# Check quants and available quantity for product kgB
quants = self.StockQuantObj.search([('product_id', '=', self.kgB.id), ('location_id', '=', self.stock_location)])
total_qty = [quant.quantity for quant in quants]
self.assertEqual(sum(total_qty), 0.020, 'Expecting 0.020 kg , got %.4f kg on location stock!' % (sum(total_qty)))
self.assertEqual(self.kgB.qty_available, 0.020, 'Wrong quantity available (%s found instead of 0.020)' % (self.kgB.qty_available))
# ----------------------------------------------------------------------
# Create Incoming Shipment B
# ----------------------------------------------------------------------
picking_in_B = self.PickingObj.create({
'picking_type_id': self.picking_type_in,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location})
move_in_a = self.MoveObj.create({
'name': self.DozA.name,
'product_id': self.DozA.id,
'product_uom_qty': 120,
'product_uom': self.uom_unit.id,
'picking_id': picking_in_B.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location})
self.MoveObj.create({
'name': self.SDozA.name,
'product_id': self.SDozA.id,
'product_uom_qty': 1512,
'product_uom': self.uom_unit.id,
'picking_id': picking_in_B.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location})
self.MoveObj.create({
'name': self.SDozARound.name,
'product_id': self.SDozARound.id,
'product_uom_qty': 1584,
'product_uom': self.uom_unit.id,
'picking_id': picking_in_B.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location})
self.MoveObj.create({
'name': self.kgB.name,
'product_id': self.kgB.id,
'product_uom_qty': 20.0,
'product_uom': self.uom_gm.id,
'picking_id': picking_in_B.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location})
self.MoveObj.create({
'name': self.gB.name,
'product_id': self.gB.id,
'product_uom_qty': 0.525,
'product_uom': self.uom_kg.id,
'picking_id': picking_in_B.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location})
# Check incoming shipment move lines state.
for move in picking_in_B.move_lines:
self.assertEqual(move.state, 'draft', 'Wrong state of move line.')
# Confirm incoming shipment.
picking_in_B.action_confirm()
# Check incoming shipment move lines state.
for move in picking_in_B.move_lines:
self.assertEqual(move.state, 'assigned', 'Wrong state of move line.')
# ----------------------------------------------------------------------
# Check product quantity and unit of measure of pack operaation.
# ----------------------------------------------------------------------
# Check pack operation quantity and unit of measure for product DozA.
PackdozA = self.StockPackObj.search([('product_id', '=', self.DozA.id), ('picking_id', '=', picking_in_B.id)], limit=1)
self.assertEqual(PackdozA.product_uom_qty, 120, 'Wrong quantity in pack operation (%s found instead of 120)' % (PackdozA.product_uom_qty))
self.assertEqual(PackdozA.product_qty, 10, 'Wrong real quantity in pack operation (%s found instead of 10)' % (PackdozA.product_qty))
self.assertEqual(PackdozA.product_uom_id.id, self.uom_unit.id, 'Wrong uom in pack operation for product DozA.')
# Check pack operation quantity and unit of measure for product SDozA.
PackSdozA = self.StockPackObj.search([('product_id', '=', self.SDozA.id), ('picking_id', '=', picking_in_B.id)], limit=1)
self.assertEqual(PackSdozA.product_uom_qty, 1512, 'Wrong quantity in pack operation (%s found instead of 1512)' % (PackSdozA.product_uom_qty))
self.assertEqual(PackSdozA.product_uom_id.id, self.uom_unit.id, 'Wrong uom in pack operation for product SDozA.')
# Check pack operation quantity and unit of measure for product SDozARound.
PackSdozAround = self.StockPackObj.search([('product_id', '=', self.SDozARound.id), ('picking_id', '=', picking_in_B.id)], limit=1)
self.assertEqual(PackSdozAround.product_uom_qty, 1584, 'Wrong quantity in pack operation (%s found instead of 1584)' % (PackSdozAround.product_uom_qty))
self.assertEqual(PackSdozAround.product_uom_id.id, self.uom_unit.id, 'Wrong uom in pack operation for product SDozARound.')
# Check pack operation quantity and unit of measure for product gB.
packgB = self.StockPackObj.search([('product_id', '=', self.gB.id), ('picking_id', '=', picking_in_B.id)], limit=1)
self.assertEqual(packgB.product_uom_qty, 0.525, 'Wrong quantity in pack operation (%s found instead of 0.525)' % (packgB.product_uom_qty))
self.assertEqual(packgB.product_qty, 525, 'Wrong real quantity in pack operation (%s found instead of 525)' % (packgB.product_qty))
self.assertEqual(packgB.product_uom_id.id, packgB.move_id.product_uom.id, 'Wrong uom in pack operation for product kgB.')
# Check pack operation quantity and unit of measure for product kgB.
packkgB = self.StockPackObj.search([('product_id', '=', self.kgB.id), ('picking_id', '=', picking_in_B.id)], limit=1)
self.assertEqual(packkgB.product_uom_qty, 20.0, 'Wrong quantity in pack operation (%s found instead of 20)' % (packkgB.product_uom_qty))
self.assertEqual(packkgB.product_uom_id.id, self.uom_gm.id, 'Wrong uom in pack operation for product kgB')
# ----------------------------------------------------------------------
# Replace pack operation of incoming shipment.
# ----------------------------------------------------------------------
self.StockPackObj.search([('product_id', '=', self.kgB.id), ('picking_id', '=', picking_in_B.id)]).write({
'product_uom_qty': 0.020, 'product_uom_id': self.uom_kg.id})
self.StockPackObj.search([('product_id', '=', self.gB.id), ('picking_id', '=', picking_in_B.id)]).write({
'product_uom_qty': 526, 'product_uom_id': self.uom_gm.id})
self.StockPackObj.search([('product_id', '=', self.DozA.id), ('picking_id', '=', picking_in_B.id)]).write({
'product_uom_qty': 4, 'product_uom_id': self.uom_dozen.id})
self.StockPackObj.create({
'product_id': self.DozA.id,
'product_uom_qty': 48,
'product_uom_id': self.uom_unit.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location,
'move_id': move_in_a.id
})
# -----------------
# Transfer product.
# -----------------
res_dict = picking_in_B.button_validate()
wizard = Form(self.env[res_dict.get('res_model')].with_context(res_dict['context'])).save()
res_dict_for_back_order = wizard.process()
backorder_wizard = self.env[(res_dict_for_back_order.get('res_model'))].browse(res_dict_for_back_order.get('res_id')).with_context(res_dict_for_back_order['context'])
backorder_wizard.process()
# -----------------------------------------------------------------------
# Check incoming shipment
# -----------------------------------------------------------------------
# Check incoming shipment state.
self.assertEqual(picking_in_B.state, 'done', 'Incoming shipment state should be done.')
# Check incoming shipment move lines state.
for move in picking_in_B.move_lines:
self.assertEqual(move.state, 'done', 'Wrong state of move line.')
# Check total done move lines for incoming shipment.
self.assertEqual(len(picking_in_B.move_lines), 5, 'Wrong number of move lines')
# Check product DozA done quantity.
moves_DozA = self.MoveObj.search([('product_id', '=', self.DozA.id), ('picking_id', '=', picking_in_B.id)], limit=1)
self.assertEqual(moves_DozA.product_uom_qty, 96, 'Wrong move quantity (%s found instead of 96)' % (moves_DozA.product_uom_qty))
self.assertEqual(moves_DozA.product_uom.id, self.uom_unit.id, 'Wrong uom in move for product DozA.')
# Check product SDozA done quantity.
moves_SDozA = self.MoveObj.search([('product_id', '=', self.SDozA.id), ('picking_id', '=', picking_in_B.id)], limit=1)
self.assertEqual(moves_SDozA.product_uom_qty, 1512, 'Wrong move quantity (%s found instead of 1512)' % (moves_SDozA.product_uom_qty))
self.assertEqual(moves_SDozA.product_uom.id, self.uom_unit.id, 'Wrong uom in move for product SDozA.')
# Check product SDozARound done quantity.
moves_SDozARound = self.MoveObj.search([('product_id', '=', self.SDozARound.id), ('picking_id', '=', picking_in_B.id)], limit=1)
self.assertEqual(moves_SDozARound.product_uom_qty, 1584, 'Wrong move quantity (%s found instead of 1584)' % (moves_SDozARound.product_uom_qty))
self.assertEqual(moves_SDozARound.product_uom.id, self.uom_unit.id, 'Wrong uom in move for product SDozARound.')
# Check product kgB done quantity.
moves_kgB = self.MoveObj.search([('product_id', '=', self.kgB.id), ('picking_id', '=', picking_in_B.id)], limit=1)
self.assertEqual(moves_kgB.product_uom_qty, 20, 'Wrong quantity in move (%s found instead of 20)' % (moves_kgB.product_uom_qty))
self.assertEqual(moves_kgB.product_uom.id, self.uom_gm.id, 'Wrong uom in move for product kgB.')
# Check two moves created for product gB with quantity (0.525 kg and 0.3 g)
moves_gB_kg = self.MoveObj.search([('product_id', '=', self.gB.id), ('picking_id', '=', picking_in_B.id), ('product_uom', '=', self.uom_kg.id)], limit=1)
self.assertEqual(moves_gB_kg.product_uom_qty, 0.526, 'Wrong move quantity (%s found instead of 0.526)' % (moves_gB_kg.product_uom_qty))
self.assertEqual(moves_gB_kg.product_uom.id, self.uom_kg.id, 'Wrong uom in move for product gB.')
# TODO Test extra move once the uom is editable in the move_lines
# ----------------------------------------------------------------------
# Check Back order of Incoming shipment.
# ----------------------------------------------------------------------
# Check back order created or not.
bo_in_B = self.PickingObj.search([('backorder_id', '=', picking_in_B.id)])
self.assertEqual(len(bo_in_B), 1, 'Back order should be created.')
# Check total move lines of back order.
self.assertEqual(len(bo_in_B.move_lines), 1, 'Wrong number of move lines')
# Check back order created with correct quantity and uom or not.
moves_DozA = self.MoveObj.search([('product_id', '=', self.DozA.id), ('picking_id', '=', bo_in_B.id)], limit=1)
self.assertEqual(moves_DozA.product_uom_qty, 24.0, 'Wrong move quantity (%s found instead of 0.525)' % (moves_DozA.product_uom_qty))
self.assertEqual(moves_DozA.product_uom.id, self.uom_unit.id, 'Wrong uom in move for product DozA.')
# ----------------------------------------------------------------------
# Check product stock location quantity and quantity available.
# ----------------------------------------------------------------------
# Check quants and available quantity for product DozA
quants = self.StockQuantObj.search([('product_id', '=', self.DozA.id), ('location_id', '=', self.stock_location)])
total_qty = [quant.quantity for quant in quants]
self.assertEqual(sum(total_qty), 18, 'Expecting 18 Dozen , got %.4f Dozen on location stock!' % (sum(total_qty)))
self.assertEqual(self.DozA.qty_available, 18, 'Wrong quantity available (%s found instead of 18)' % (self.DozA.qty_available))
# Check quants and available quantity for product SDozA
quants = self.StockQuantObj.search([('product_id', '=', self.SDozA.id), ('location_id', '=', self.stock_location)])
total_qty = [quant.quantity for quant in quants]
self.assertEqual(sum(total_qty), 21, 'Expecting 21 SDozen , got %.4f SDozen on location stock!' % (sum(total_qty)))
self.assertEqual(self.SDozA.qty_available, 21, 'Wrong quantity available (%s found instead of 21)' % (self.SDozA.qty_available))
# Check quants and available quantity for product SDozARound
quants = self.StockQuantObj.search([('product_id', '=', self.SDozARound.id), ('location_id', '=', self.stock_location)])
total_qty = [quant.quantity for quant in quants]
self.assertEqual(sum(total_qty), 22, 'Expecting 22 SDozenRound , got %.4f SDozenRound on location stock!' % (sum(total_qty)))
self.assertEqual(self.SDozARound.qty_available, 22, 'Wrong quantity available (%s found instead of 22)' % (self.SDozARound.qty_available))
# Check quants and available quantity for product gB.
quants = self.StockQuantObj.search([('product_id', '=', self.gB.id), ('location_id', '=', self.stock_location)])
total_qty = [quant.quantity for quant in quants]
self.assertEqual(round(sum(total_qty), 1), 1051.3, 'Expecting 1051 Gram , got %.4f Gram on location stock!' % (sum(total_qty)))
self.assertEqual(round(self.gB.qty_available, 1), 1051.3, 'Wrong quantity available (%s found instead of 1051)' % (self.gB.qty_available))
# Check quants and available quantity for product kgB.
quants = self.StockQuantObj.search([('product_id', '=', self.kgB.id), ('location_id', '=', self.stock_location)])
total_qty = [quant.quantity for quant in quants]
self.assertEqual(sum(total_qty), 0.040, 'Expecting 0.040 kg , got %.4f kg on location stock!' % (sum(total_qty)))
self.assertEqual(self.kgB.qty_available, 0.040, 'Wrong quantity available (%s found instead of 0.040)' % (self.kgB.qty_available))
# ----------------------------------------------------------------------
# Create outgoing shipment.
# ----------------------------------------------------------------------
before_out_quantity = self.kgB.qty_available
picking_out = self.PickingObj.create({
'picking_type_id': self.picking_type_out,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
self.MoveObj.create({
'name': self.kgB.name,
'product_id': self.kgB.id,
'product_uom_qty': 0.966,
'product_uom': self.uom_gm.id,
'picking_id': picking_out.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
self.MoveObj.create({
'name': self.kgB.name,
'product_id': self.kgB.id,
'product_uom_qty': 0.034,
'product_uom': self.uom_gm.id,
'picking_id': picking_out.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
picking_out.action_confirm()
picking_out.action_assign()
res_dict = picking_out.button_validate()
wizard = Form(self.env[(res_dict.get('res_model'))].with_context(res_dict['context'])).save()
wizard.process()
# Check quantity difference after stock transfer.
quantity_diff = before_out_quantity - self.kgB.qty_available
self.assertEqual(float_round(quantity_diff, precision_rounding=0.0001), 0.001, 'Wrong quantity difference.')
self.assertEqual(self.kgB.qty_available, 0.039, 'Wrong quantity available (%s found instead of 0.039)' % (self.kgB.qty_available))
# ======================================================================
# Outgoing shipments.
# ======================================================================
# Create Outgoing shipment with ...
# product DozA ( 54 Unit ) , SDozA ( 288 Unit )
# product SDozRound ( 360 unit ) , product gB ( 0.503 kg )
# product kgB ( 19 g )
# ======================================================================
picking_out = self.PickingObj.create({
'picking_type_id': self.picking_type_out,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
self.MoveObj.create({
'name': self.DozA.name,
'product_id': self.DozA.id,
'product_uom_qty': 54,
'product_uom': self.uom_unit.id,
'picking_id': picking_out.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
self.MoveObj.create({
'name': self.SDozA.name,
'product_id': self.SDozA.id,
'product_uom_qty': 288,
'product_uom': self.uom_unit.id,
'picking_id': picking_out.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
self.MoveObj.create({
'name': self.SDozARound.name,
'product_id': self.SDozARound.id,
'product_uom_qty': 361,
'product_uom': self.uom_unit.id,
'picking_id': picking_out.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
self.MoveObj.create({
'name': self.gB.name,
'product_id': self.gB.id,
'product_uom_qty': 0.503,
'product_uom': self.uom_kg.id,
'picking_id': picking_out.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
self.MoveObj.create({
'name': self.kgB.name,
'product_id': self.kgB.id,
'product_uom_qty': 20,
'product_uom': self.uom_gm.id,
'picking_id': picking_out.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
# Confirm outgoing shipment.
picking_out.action_confirm()
for move in picking_out.move_lines:
self.assertEqual(move.state, 'confirmed', 'Wrong state of move line.')
# Assing product to outgoing shipments
picking_out.action_assign()
for move in picking_out.move_lines:
self.assertEqual(move.state, 'assigned', 'Wrong state of move line.')
# Check product A available quantity
DozA_qty = self.MoveObj.search([('product_id', '=', self.DozA.id), ('picking_id', '=', picking_out.id)], limit=1).product_qty
self.assertEqual(DozA_qty, 4.5, 'Wrong move quantity availability (%s found instead of 4.5)' % (DozA_qty))
# Check product B available quantity
SDozA_qty = self.MoveObj.search([('product_id', '=', self.SDozA.id), ('picking_id', '=', picking_out.id)], limit=1).product_qty
self.assertEqual(SDozA_qty, 2, 'Wrong move quantity availability (%s found instead of 2)' % (SDozA_qty))
# Check product C available quantity
SDozARound_qty = self.MoveObj.search([('product_id', '=', self.SDozARound.id), ('picking_id', '=', picking_out.id)], limit=1).product_qty
self.assertEqual(SDozARound_qty, 3, 'Wrong move quantity availability (%s found instead of 3)' % (SDozARound_qty))
# Check product D available quantity
gB_qty = self.MoveObj.search([('product_id', '=', self.gB.id), ('picking_id', '=', picking_out.id)], limit=1).product_qty
self.assertEqual(gB_qty, 503, 'Wrong move quantity availability (%s found instead of 503)' % (gB_qty))
# Check product D available quantity
kgB_qty = self.MoveObj.search([('product_id', '=', self.kgB.id), ('picking_id', '=', picking_out.id)], limit=1).product_qty
self.assertEqual(kgB_qty, 0.020, 'Wrong move quantity availability (%s found instead of 0.020)' % (kgB_qty))
res_dict = picking_out.button_validate()
wizard = Form(self.env[(res_dict.get('res_model'))].with_context(res_dict['context'])).save()
wizard.process()
# ----------------------------------------------------------------------
# Check product stock location quantity and quantity available.
# ----------------------------------------------------------------------
# Check quants and available quantity for product DozA
quants = self.StockQuantObj.search([('product_id', '=', self.DozA.id), ('location_id', '=', self.stock_location)])
total_qty = [quant.quantity for quant in quants]
self.assertEqual(sum(total_qty), 13.5, 'Expecting 13.5 Dozen , got %.4f Dozen on location stock!' % (sum(total_qty)))
self.assertEqual(self.DozA.qty_available, 13.5, 'Wrong quantity available (%s found instead of 13.5)' % (self.DozA.qty_available))
# Check quants and available quantity for product SDozA
quants = self.StockQuantObj.search([('product_id', '=', self.SDozA.id), ('location_id', '=', self.stock_location)])
total_qty = [quant.quantity for quant in quants]
self.assertEqual(sum(total_qty), 19, 'Expecting 19 SDozen , got %.4f SDozen on location stock!' % (sum(total_qty)))
self.assertEqual(self.SDozA.qty_available, 19, 'Wrong quantity available (%s found instead of 19)' % (self.SDozA.qty_available))
# Check quants and available quantity for product SDozARound
quants = self.StockQuantObj.search([('product_id', '=', self.SDozARound.id), ('location_id', '=', self.stock_location)])
total_qty = [quant.quantity for quant in quants]
self.assertEqual(sum(total_qty), 19, 'Expecting 19 SDozRound , got %.4f SDozRound on location stock!' % (sum(total_qty)))
self.assertEqual(self.SDozARound.qty_available, 19, 'Wrong quantity available (%s found instead of 19)' % (self.SDozARound.qty_available))
# Check quants and available quantity for product gB.
quants = self.StockQuantObj.search([('product_id', '=', self.gB.id), ('location_id', '=', self.stock_location)])
total_qty = [quant.quantity for quant in quants]
self.assertEqual(round(sum(total_qty), 1), 548.3, 'Expecting 547.6 g , got %.4f g on location stock!' % (sum(total_qty)))
self.assertEqual(round(self.gB.qty_available, 1), 548.3, 'Wrong quantity available (%s found instead of 547.6)' % (self.gB.qty_available))
# Check quants and available quantity for product kgB.
quants = self.StockQuantObj.search([('product_id', '=', self.kgB.id), ('location_id', '=', self.stock_location)])
total_qty = [quant.quantity for quant in quants]
self.assertEqual(sum(total_qty), 0.019, 'Expecting 0.019 kg , got %.4f kg on location stock!' % (sum(total_qty)))
self.assertEqual(self.kgB.qty_available, 0.019, 'Wrong quantity available (%s found instead of 0.019)' % (self.kgB.qty_available))
# ----------------------------------------------------------------------
# Receipt back order of incoming shipment.
# ----------------------------------------------------------------------
res_dict = bo_in_B.button_validate()
wizard = Form(self.env[(res_dict.get('res_model'))].with_context(res_dict['context'])).save()
wizard.process()
# Check quants and available quantity for product kgB.
quants = self.StockQuantObj.search([('product_id', '=', self.DozA.id), ('location_id', '=', self.stock_location)])
total_qty = [quant.quantity for quant in quants]
self.assertEqual(sum(total_qty), 15.5, 'Expecting 15.5 Dozen , got %.4f Dozen on location stock!' % (sum(total_qty)))
self.assertEqual(self.DozA.qty_available, 15.5, 'Wrong quantity available (%s found instead of 15.5)' % (self.DozA.qty_available))
# -----------------------------------------
# Create product in kg and receive in ton.
# -----------------------------------------
productKG = self.ProductObj.create({'name': 'Product KG', 'uom_id': self.uom_kg.id, 'uom_po_id': self.uom_kg.id, 'type': 'product'})
picking_in = self.PickingObj.create({
'picking_type_id': self.picking_type_in,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location})
self.MoveObj.create({
'name': productKG.name,
'product_id': productKG.id,
'product_uom_qty': 1.0,
'product_uom': self.uom_tone.id,
'picking_id': picking_in.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location})
# Check incoming shipment state.
self.assertEqual(picking_in.state, 'draft', 'Incoming shipment state should be draft.')
# Check incoming shipment move lines state.
for move in picking_in.move_lines:
self.assertEqual(move.state, 'draft', 'Wrong state of move line.')
# Confirm incoming shipment.
picking_in.action_confirm()
# Check incoming shipment move lines state.
for move in picking_in.move_lines:
self.assertEqual(move.state, 'assigned', 'Wrong state of move line.')
# Check pack operation quantity.
packKG = self.StockPackObj.search([('product_id', '=', productKG.id), ('picking_id', '=', picking_in.id)], limit=1)
self.assertEqual(packKG.product_qty, 1000, 'Wrong product real quantity in pack operation (%s found instead of 1000)' % (packKG.product_qty))
self.assertEqual(packKG.product_uom_qty, 1, 'Wrong product quantity in pack operation (%s found instead of 1)' % (packKG.product_uom_qty))
self.assertEqual(packKG.product_uom_id.id, self.uom_tone.id, 'Wrong product uom in pack operation.')
# Transfer Incoming shipment.
res_dict = picking_in.button_validate()
wizard = Form(self.env[(res_dict.get('res_model'))].with_context(res_dict['context'])).save()
wizard.process()
# -----------------------------------------------------------------------
# Check incoming shipment after transfer.
# -----------------------------------------------------------------------
# Check incoming shipment state.
self.assertEqual(picking_in.state, 'done', 'Incoming shipment state: %s instead of %s' % (picking_in.state, 'done'))
# Check incoming shipment move lines state.
for move in picking_in.move_lines:
self.assertEqual(move.state, 'done', 'Wrong state of move lines.')
# Check total done move lines for incoming shipment.
self.assertEqual(len(picking_in.move_lines), 1, 'Wrong number of move lines')
# Check product DozA done quantity.
move = self.MoveObj.search([('product_id', '=', productKG.id), ('picking_id', '=', picking_in.id)], limit=1)
self.assertEqual(move.product_uom_qty, 1, 'Wrong product quantity in done move.')
self.assertEqual(move.product_uom.id, self.uom_tone.id, 'Wrong unit of measure in done move.')
self.assertEqual(productKG.qty_available, 1000, 'Wrong quantity available of product (%s found instead of 1000)' % (productKG.qty_available))
picking_out = self.PickingObj.create({
'picking_type_id': self.picking_type_out,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
self.MoveObj.create({
'name': productKG.name,
'product_id': productKG.id,
'product_uom_qty': 25,
'product_uom': self.uom_gm.id,
'picking_id': picking_out.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
picking_out.action_confirm()
picking_out.action_assign()
pack_opt = self.StockPackObj.search([('product_id', '=', productKG.id), ('picking_id', '=', picking_out.id)], limit=1)
pack_opt.write({'product_uom_qty': 5})
res_dict = picking_out.button_validate()
wizard = Form(self.env[(res_dict.get('res_model'))].with_context(res_dict['context'])).save()
res_dict_for_back_order = wizard.process()
backorder_wizard = self.env[(res_dict_for_back_order.get('res_model'))].browse(res_dict_for_back_order.get('res_id')).with_context(res_dict_for_back_order['context'])
backorder_wizard.process()
quants = self.StockQuantObj.search([('product_id', '=', productKG.id), ('location_id', '=', self.stock_location)])
total_qty = [quant.quantity for quant in quants]
# Check total quantity stock location.
self.assertEqual(sum(total_qty), 999.995, 'Expecting 999.995 kg , got %.4f kg on location stock!' % (sum(total_qty)))
# ---------------------------------
# Check Back order created or not.
# ---------------------------------
bo_out_1 = self.PickingObj.search([('backorder_id', '=', picking_out.id)])
self.assertEqual(len(bo_out_1), 1, 'Back order should be created.')
# Check total move lines of back order.
self.assertEqual(len(bo_out_1.move_lines), 1, 'Wrong number of move lines')
moves_KG = self.MoveObj.search([('product_id', '=', productKG.id), ('picking_id', '=', bo_out_1.id)], limit=1)
# Check back order created with correct quantity and uom or not.
self.assertEqual(moves_KG.product_uom_qty, 20, 'Wrong move quantity (%s found instead of 20)' % (moves_KG.product_uom_qty))
self.assertEqual(moves_KG.product_uom.id, self.uom_gm.id, 'Wrong uom in move for product KG.')
bo_out_1.action_assign()
pack_opt = self.StockPackObj.search([('product_id', '=', productKG.id), ('picking_id', '=', bo_out_1.id)], limit=1)
pack_opt.write({'product_uom_qty': 5})
res_dict = bo_out_1.button_validate()
wizard = Form(self.env[(res_dict.get('res_model'))].with_context(res_dict['context'])).save()
res_dict_for_back_order = wizard.process()
backorder_wizard = self.env[(res_dict_for_back_order.get('res_model'))].browse(res_dict_for_back_order.get('res_id')).with_context(res_dict_for_back_order['context'])
backorder_wizard.process()
quants = self.StockQuantObj.search([('product_id', '=', productKG.id), ('location_id', '=', self.stock_location)])
total_qty = [quant.quantity for quant in quants]
# Check total quantity stock location.
self.assertEqual(sum(total_qty), 999.990, 'Expecting 999.990 kg , got %.4f kg on location stock!' % (sum(total_qty)))
# Check Back order created or not.
# ---------------------------------
bo_out_2 = self.PickingObj.search([('backorder_id', '=', bo_out_1.id)])
self.assertEqual(len(bo_out_2), 1, 'Back order should be created.')
# Check total move lines of back order.
self.assertEqual(len(bo_out_2.move_lines), 1, 'Wrong number of move lines')
# Check back order created with correct move quantity and uom or not.
moves_KG = self.MoveObj.search([('product_id', '=', productKG.id), ('picking_id', '=', bo_out_2.id)], limit=1)
self.assertEqual(moves_KG.product_uom_qty, 15, 'Wrong move quantity (%s found instead of 15)' % (moves_KG.product_uom_qty))
self.assertEqual(moves_KG.product_uom.id, self.uom_gm.id, 'Wrong uom in move for product KG.')
bo_out_2.action_assign()
pack_opt = self.StockPackObj.search([('product_id', '=', productKG.id), ('picking_id', '=', bo_out_2.id)], limit=1)
pack_opt.write({'product_uom_qty': 5})
res_dict = bo_out_2.button_validate()
wizard = Form(self.env[(res_dict.get('res_model'))].with_context(res_dict['context'])).save()
res_dict_for_back_order = wizard.process()
backorder_wizard = self.env[(res_dict_for_back_order.get('res_model'))].browse(res_dict_for_back_order.get('res_id')).with_context(res_dict_for_back_order['context'])
backorder_wizard.process()
# Check total quantity stock location of product KG.
quants = self.StockQuantObj.search([('product_id', '=', productKG.id), ('location_id', '=', self.stock_location)])
total_qty = [quant.quantity for quant in quants]
self.assertEqual(sum(total_qty), 999.985, 'Expecting 999.985 kg , got %.4f kg on location stock!' % (sum(total_qty)))
# Check Back order created or not.
# ---------------------------------
bo_out_3 = self.PickingObj.search([('backorder_id', '=', bo_out_2.id)])
self.assertEqual(len(bo_out_3), 1, 'Back order should be created.')
# Check total move lines of back order.
self.assertEqual(len(bo_out_3.move_lines), 1, 'Wrong number of move lines')
# Check back order created with correct quantity and uom or not.
moves_KG = self.MoveObj.search([('product_id', '=', productKG.id), ('picking_id', '=', bo_out_3.id)], limit=1)
self.assertEqual(moves_KG.product_uom_qty, 10, 'Wrong move quantity (%s found instead of 10)' % (moves_KG.product_uom_qty))
self.assertEqual(moves_KG.product_uom.id, self.uom_gm.id, 'Wrong uom in move for product KG.')
bo_out_3.action_assign()
pack_opt = self.StockPackObj.search([('product_id', '=', productKG.id), ('picking_id', '=', bo_out_3.id)], limit=1)
pack_opt.write({'product_uom_qty': 5})
res_dict = bo_out_3.button_validate()
wizard = Form(self.env[(res_dict.get('res_model'))].with_context(res_dict['context'])).save()
res_dict_for_back_order = wizard.process()
backorder_wizard = self.env[(res_dict_for_back_order.get('res_model'))].browse(res_dict_for_back_order.get('res_id')).with_context(res_dict_for_back_order['context'])
backorder_wizard.process()
quants = self.StockQuantObj.search([('product_id', '=', productKG.id), ('location_id', '=', self.stock_location)])
total_qty = [quant.quantity for quant in quants]
self.assertEqual(sum(total_qty), 999.980, 'Expecting 999.980 kg , got %.4f kg on location stock!' % (sum(total_qty)))
# Check Back order created or not.
# ---------------------------------
bo_out_4 = self.PickingObj.search([('backorder_id', '=', bo_out_3.id)])
self.assertEqual(len(bo_out_4), 1, 'Back order should be created.')
# Check total move lines of back order.
self.assertEqual(len(bo_out_4.move_lines), 1, 'Wrong number of move lines')
# Check back order created with correct quantity and uom or not.
moves_KG = self.MoveObj.search([('product_id', '=', productKG.id), ('picking_id', '=', bo_out_4.id)], limit=1)
self.assertEqual(moves_KG.product_uom_qty, 5, 'Wrong move quantity (%s found instead of 5)' % (moves_KG.product_uom_qty))
self.assertEqual(moves_KG.product_uom.id, self.uom_gm.id, 'Wrong uom in move for product KG.')
bo_out_4.action_assign()
pack_opt = self.StockPackObj.search([('product_id', '=', productKG.id), ('picking_id', '=', bo_out_4.id)], limit=1)
pack_opt.write({'product_uom_qty': 5})
res_dict = bo_out_4.button_validate()
wizard = Form(self.env[(res_dict.get('res_model'))].with_context(res_dict['context'])).save()
wizard.process()
quants = self.StockQuantObj.search([('product_id', '=', productKG.id), ('location_id', '=', self.stock_location)])
total_qty = [quant.quantity for quant in quants]
self.assertAlmostEqual(sum(total_qty), 999.975, msg='Expecting 999.975 kg , got %.4f kg on location stock!' % (sum(total_qty)))
def test_20_create_inventory_with_packs_and_lots(self):
# --------------------------------------------------------
# TEST EMPTY INVENTORY WITH PACKS and LOTS
# ---------------------------------------------------------
packproduct = self.ProductObj.create({'name': 'Pack Product', 'uom_id': self.uom_unit.id, 'uom_po_id': self.uom_unit.id, 'type': 'product'})
lotproduct = self.ProductObj.create({'name': 'Lot Product', 'uom_id': self.uom_unit.id, 'uom_po_id': self.uom_unit.id, 'type': 'product'})
quant_obj = self.env['stock.quant'].with_context(inventory_mode=True)
pack_obj = self.env['stock.quant.package']
lot_obj = self.env['stock.production.lot']
pack1 = pack_obj.create({'name': 'PACK00TEST1'})
pack_obj.create({'name': 'PACK00TEST2'})
lot1 = lot_obj.create({'name': 'Lot001', 'product_id': lotproduct.id, 'company_id': self.env.company.id})
packproduct_no_pack_quant = quant_obj.create({
'product_id': packproduct.id,
'inventory_quantity': 10.0,
'location_id': self.stock_location
})
packproduct_quant = quant_obj.create({
'product_id': packproduct.id,
'inventory_quantity': 20.0,
'location_id': self.stock_location,
'package_id': pack1.id
})
lotproduct_no_lot_quant = quant_obj.create({
'product_id': lotproduct.id,
'inventory_quantity': 25.0,
'location_id': self.stock_location
})
lotproduct_quant = quant_obj.create({
'product_id': lotproduct.id,
'inventory_quantity': 30.0,
'location_id': self.stock_location,
'lot_id': lot1.id
})
(packproduct_no_pack_quant | packproduct_quant | lotproduct_no_lot_quant | lotproduct_quant).action_apply_inventory()
self.assertEqual(packproduct.qty_available, 30, "Wrong qty available for packproduct")
self.assertEqual(lotproduct.qty_available, 55, "Wrong qty available for lotproduct")
quants = self.StockQuantObj.search([('product_id', '=', packproduct.id), ('location_id', '=', self.stock_location), ('package_id', '=', pack1.id)])
total_qty = sum([quant.quantity for quant in quants])
self.assertEqual(total_qty, 20, 'Expecting 20 units on package 1 of packproduct, but we got %.4f on location stock!' % (total_qty))
# Create an inventory that will put the lots without lot to 0 and check that taking without pack will not take it from the pack
packproduct_no_pack_quant.inventory_quantity = 20
lotproduct_no_lot_quant.inventory_quantity = 0
lotproduct_quant.inventory_quantity = 10
packproduct_no_pack_quant.action_apply_inventory()
lotproduct_no_lot_quant.action_apply_inventory()
lotproduct_quant.action_apply_inventory()
self.assertEqual(packproduct.qty_available, 40, "Wrong qty available for packproduct")
self.assertEqual(lotproduct.qty_available, 10, "Wrong qty available for lotproduct")
quants = self.StockQuantObj.search([('product_id', '=', lotproduct.id), ('location_id', '=', self.stock_location), ('lot_id', '=', lot1.id)])
total_qty = sum([quant.quantity for quant in quants])
self.assertEqual(total_qty, 10, 'Expecting 10 units lot of lotproduct, but we got %.4f on location stock!' % (total_qty))
quants = self.StockQuantObj.search([('product_id', '=', lotproduct.id), ('location_id', '=', self.stock_location), ('lot_id', '=', False)])
total_qty = sum([quant.quantity for quant in quants])
self.assertEqual(total_qty, 0, 'Expecting 0 units lot of lotproduct, but we got %.4f on location stock!' % (total_qty))
def test_30_check_with_no_incoming_lot(self):
""" Picking in without lots and picking out with"""
# Change basic operation type not to get lots
# Create product with lot tracking
picking_in = self.env['stock.picking.type'].browse(self.picking_type_in)
picking_in.use_create_lots = False
self.productA.tracking = 'lot'
picking_in = self.PickingObj.create({
'picking_type_id': self.picking_type_in,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location})
self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 4,
'product_uom': self.productA.uom_id.id,
'picking_id': picking_in.id,
'picking_type_id': self.picking_type_in,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location})
# Check incoming shipment move lines state.
for move in picking_in.move_lines:
self.assertEqual(move.state, 'draft', 'Wrong state of move line.')
# Confirm incoming shipment.
picking_in.action_confirm()
# Check incoming shipment move lines state.
for move in picking_in.move_lines:
self.assertEqual(move.state, 'assigned', 'Wrong state of move line.')
res_dict = picking_in.button_validate()
wizard = self.env[(res_dict.get('res_model'))].browse(res_dict.get('res_id'))
wizard.process()
picking_out = self.PickingObj.create({
'name': 'testpicking',
'picking_type_id': self.picking_type_out,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
move_out = self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 3,
'product_uom': self.productA.uom_id.id,
'picking_id': picking_out.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
picking_out.action_confirm()
picking_out.action_assign()
pack_opt = self.StockPackObj.search([('picking_id', '=', picking_out.id)], limit=1)
lot1 = self.LotObj.create({'product_id': self.productA.id, 'name': 'LOT1', 'company_id': self.env.company.id})
lot2 = self.LotObj.create({'product_id': self.productA.id, 'name': 'LOT2', 'company_id': self.env.company.id})
lot3 = self.LotObj.create({'product_id': self.productA.id, 'name': 'LOT3', 'company_id': self.env.company.id})
pack_opt.write({'lot_id': lot1.id, 'qty_done': 1.0})
self.StockPackObj.create({'product_id': self.productA.id, 'move_id': move_out.id, 'product_uom_id': move_out.product_uom.id, 'lot_id': lot2.id, 'qty_done': 1.0, 'location_id': self.stock_location, 'location_dest_id': self.customer_location})
self.StockPackObj.create({'product_id': self.productA.id, 'move_id': move_out.id, 'product_uom_id': move_out.product_uom.id, 'lot_id': lot3.id, 'qty_done': 2.0, 'location_id': self.stock_location, 'location_dest_id': self.customer_location})
picking_out._action_done()
quants = self.StockQuantObj.search([('product_id', '=', self.productA.id), ('location_id', '=', self.stock_location)])
# TODO wait sle fix
# self.assertFalse(quants, 'Should not have any quants in stock anymore')
def test_40_pack_in_pack(self):
""" Put a pack in pack"""
self.env['stock.picking.type'].browse(self.picking_type_in).show_reserved = True
picking_out = self.PickingObj.create({
'picking_type_id': self.picking_type_out,
'location_id': self.pack_location,
'location_dest_id': self.customer_location})
move_out = self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 3,
'product_uom': self.productA.uom_id.id,
'picking_id': picking_out.id,
'location_id': self.pack_location,
'location_dest_id': self.customer_location})
picking_pack = self.PickingObj.create({
'picking_type_id': self.picking_type_out,
'location_id': self.stock_location,
'location_dest_id': self.pack_location})
move_pack = self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 3,
'product_uom': self.productA.uom_id.id,
'picking_id': picking_pack.id,
'location_id': self.stock_location,
'location_dest_id': self.pack_location,
'move_dest_ids': [(4, move_out.id, 0)]})
picking_in = self.PickingObj.create({
'picking_type_id': self.picking_type_in,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location})
move_in = self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 3,
'product_uom': self.productA.uom_id.id,
'picking_id': picking_in.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location,
'move_dest_ids': [(4, move_pack.id, 0)]})
# Check incoming shipment move lines state.
for move in picking_in.move_lines:
self.assertEqual(move.state, 'draft', 'Wrong state of move line.')
# Confirm incoming shipment.
picking_in.action_confirm()
# Check incoming shipment move lines state.
for move in picking_in.move_lines:
self.assertEqual(move.state, 'assigned', 'Wrong state of move line.')
# Check incoming shipment move lines state.
for move in picking_pack.move_lines:
self.assertEqual(move.state, 'draft', 'Wrong state of move line.')
# Confirm incoming shipment.
picking_pack.action_confirm()
# Check incoming shipment move lines state.
for move in picking_pack.move_lines:
self.assertEqual(move.state, 'waiting', 'Wrong state of move line.')
# Check incoming shipment move lines state.
for move in picking_out.move_lines:
self.assertEqual(move.state, 'draft', 'Wrong state of move line.')
# Confirm incoming shipment.
picking_out.action_confirm()
# Check incoming shipment move lines state.
for move in picking_out.move_lines:
self.assertEqual(move.state, 'waiting', 'Wrong state of move line.')
# Set the quantity done on the pack operation
move_in.move_line_ids.qty_done = 3.0
# Put in a pack
picking_in.action_put_in_pack()
# Get the new package
picking_in_package = move_in.move_line_ids.result_package_id
# Validate picking
picking_in._action_done()
# Check first picking state changed to done
for move in picking_in.move_lines:
self.assertEqual(move.state, 'done', 'Wrong state of move line.')
# Check next picking state changed to 'assigned'
for move in picking_pack.move_lines:
self.assertEqual(move.state, 'assigned', 'Wrong state of move line.')
# Set the quantity done on the pack operation
move_pack.move_line_ids.qty_done = 3.0
# Get the new package
picking_pack_package = move_pack.move_line_ids.result_package_id
# Validate picking
picking_pack._action_done()
# Check second picking state changed to done
for move in picking_pack.move_lines:
self.assertEqual(move.state, 'done', 'Wrong state of move line.')
# Check next picking state changed to 'assigned'
for move in picking_out.move_lines:
self.assertEqual(move.state, 'assigned', 'Wrong state of move line.')
# Validate picking
picking_out.move_line_ids.qty_done = 3.0
picking_out_package = move_out.move_line_ids.result_package_id
picking_out._action_done()
# check all pickings are done
for move in picking_in.move_lines:
self.assertEqual(move.state, 'done', 'Wrong state of move line.')
for move in picking_pack.move_lines:
self.assertEqual(move.state, 'done', 'Wrong state of move line.')
for move in picking_out.move_lines:
self.assertEqual(move.state, 'done', 'Wrong state of move line.')
# Check picking_in_package is in picking_pack_package
self.assertEqual(picking_in_package.id, picking_pack_package.id, 'The package created in the picking in is not in the one created in picking pack')
self.assertEqual(picking_pack_package.id, picking_out_package.id, 'The package created in the picking in is not in the one created in picking pack')
# Check that we have one quant in customer location.
quant = self.StockQuantObj.search([('product_id', '=', self.productA.id), ('location_id', '=', self.customer_location)])
self.assertEqual(len(quant), 1, 'There should be one quant with package for customer location')
# Check that the parent package of the quant is the picking_in_package
def test_50_create_in_out_with_product_pack_lines(self):
picking_in = self.PickingObj.create({
'picking_type_id': self.picking_type_in,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location})
self.MoveObj.create({
'name': self.productE.name,
'product_id': self.productE.id,
'product_uom_qty': 10,
'product_uom': self.productE.uom_id.id,
'picking_id': picking_in.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location})
picking_in.action_confirm()
pack_obj = self.env['stock.quant.package']
pack1 = pack_obj.create({'name': 'PACKINOUTTEST1'})
pack2 = pack_obj.create({'name': 'PACKINOUTTEST2'})
picking_in.move_line_ids[0].result_package_id = pack1
picking_in.move_line_ids[0].qty_done = 4
packop2 = picking_in.move_line_ids[0].with_context(bypass_reservation_update=True).copy({'product_uom_qty': 0})
packop2.qty_done = 6
packop2.result_package_id = pack2
picking_in._action_done()
quants = self.env['stock.quant']._gather(self.productE, self.env['stock.location'].browse(self.stock_location))
self.assertEqual(sum([x.quantity for x in quants]), 10.0, 'Expecting 10 pieces in stock')
# Check the quants are in the package
self.assertEqual(sum(x.quantity for x in pack1.quant_ids), 4.0, 'Pack 1 should have 4 pieces')
self.assertEqual(sum(x.quantity for x in pack2.quant_ids), 6.0, 'Pack 2 should have 6 pieces')
picking_out = self.PickingObj.create({
'picking_type_id': self.picking_type_out,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
self.MoveObj.create({
'name': self.productE.name,
'product_id': self.productE.id,
'product_uom_qty': 3,
'product_uom': self.productE.uom_id.id,
'picking_id': picking_out.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
picking_out.action_confirm()
picking_out.action_assign()
packout1 = picking_out.move_line_ids[0]
packout2 = picking_out.move_line_ids[0].with_context(bypass_reservation_update=True).copy({'product_uom_qty': 0})
packout1.qty_done = 2
packout1.package_id = pack1
packout2.package_id = pack2
packout2.qty_done = 1
picking_out._action_done()
# Should be only 1 negative quant in supplier location
neg_quants = self.env['stock.quant'].search([('product_id', '=', self.productE.id), ('quantity', '<', 0.0)])
self.assertEqual(len(neg_quants), 1, 'There should be 1 negative quants for supplier!')
self.assertEqual(neg_quants.location_id.id, self.supplier_location, 'There shoud be 1 negative quants for supplier!')
quants = self.env['stock.quant']._gather(self.productE, self.env['stock.location'].browse(self.stock_location))
self.assertEqual(len(quants), 2, 'We should have exactly 2 quants in the end')
def test_60_create_in_out_with_product_pack_lines(self):
picking_in = self.PickingObj.create({
'picking_type_id': self.picking_type_in,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location})
self.MoveObj.create({
'name': self.productE.name,
'product_id': self.productE.id,
'product_uom_qty': 200,
'product_uom': self.productE.uom_id.id,
'picking_id': picking_in.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location})
picking_in.action_confirm()
pack_obj = self.env['stock.quant.package']
pack1 = pack_obj.create({'name': 'PACKINOUTTEST1'})
pack2 = pack_obj.create({'name': 'PACKINOUTTEST2'})
picking_in.move_line_ids[0].result_package_id = pack1
picking_in.move_line_ids[0].qty_done = 120
packop2 = picking_in.move_line_ids[0].with_context(bypass_reservation_update=True).copy({'product_uom_qty': 0})
packop2.qty_done = 80
packop2.result_package_id = pack2
picking_in._action_done()
quants = self.env['stock.quant']._gather(self.productE, self.env['stock.location'].browse(self.stock_location))
self.assertEqual(sum([x.quantity for x in quants]), 200.0, 'Expecting 200 pieces in stock')
# Check the quants are in the package
self.assertEqual(sum(x.quantity for x in pack1.quant_ids), 120, 'Pack 1 should have 120 pieces')
self.assertEqual(sum(x.quantity for x in pack2.quant_ids), 80, 'Pack 2 should have 80 pieces')
picking_out = self.PickingObj.create({
'picking_type_id': self.picking_type_out,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
self.MoveObj.create({
'name': self.productE.name,
'product_id': self.productE.id,
'product_uom_qty': 200,
'product_uom': self.productE.uom_id.id,
'picking_id': picking_out.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
picking_out.action_confirm()
picking_out.action_assign()
# Convert entire packs into taking out of packs
packout0 = picking_out.move_line_ids[0]
packout1 = picking_out.move_line_ids[1]
packout0.write({
'package_id': pack1.id,
'product_id': self.productE.id,
'qty_done': 120.0,
'product_uom_id': self.productE.uom_id.id,
})
packout1.write({
'package_id': pack2.id,
'product_id': self.productE.id,
'qty_done': 80.0,
'product_uom_id': self.productE.uom_id.id,
})
picking_out._action_done()
# Should be only 1 negative quant in supplier location
neg_quants = self.env['stock.quant'].search([('product_id', '=', self.productE.id), ('quantity', '<', 0.0)])
self.assertEqual(len(neg_quants), 1, 'There should be 1 negative quants for supplier!')
self.assertEqual(neg_quants.location_id.id, self.supplier_location, 'There shoud be 1 negative quants for supplier!')
# We should also make sure that when matching stock moves with pack operations, it takes the correct
quants = self.env['stock.quant']._gather(self.productE, self.env['stock.location'].browse(self.stock_location))
self.assertEqual(sum(quants.mapped('quantity')), 0, 'We should have no quants in the end')
def test_70_picking_state_all_at_once_reserve(self):
""" This test will check that the state of the picking is correctly computed according
to the state of its move lines and its move type.
"""
# move_type: direct == partial, one == all at once
# picking: confirmed == waiting availability
# -----------------------------------------------------------
# "all at once" and "reserve" scenario
# -----------------------------------------------------------
# get one product in stock
inventory_quant = self.env['stock.quant'].create({
'location_id': self.stock_location,
'product_id': self.productA.id,
'inventory_quantity': 1,
})
inventory_quant.action_apply_inventory()
# create a "all at once" delivery order for two products
picking_out = self.PickingObj.create({
'picking_type_id': self.picking_type_out,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
picking_out.move_type = 'one'
self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 2,
'product_uom': self.productA.uom_id.id,
'picking_id': picking_out.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
# validate this delivery order, it should be in the waiting state
picking_out.action_assign()
self.assertEqual(picking_out.state, "confirmed")
# receive one product in stock
inventory_quant.inventory_quantity = 2
inventory_quant.action_apply_inventory()
# recheck availability of the delivery order, it should be assigned
picking_out.action_assign()
self.assertEqual(len(picking_out.move_lines), 1.0)
self.assertEqual(picking_out.move_lines.product_qty, 2.0)
self.assertEqual(picking_out.state, "assigned")
def test_71_picking_state_all_at_once_force_assign(self):
""" This test will check that the state of the picking is correctly computed according
to the state of its move lines and its move type.
"""
# move_type: direct == partial, one == all at once
# picking: confirmed == waiting availability, partially_available = partially available
# -----------------------------------------------------------
# "all at once" and "force assign" scenario
# -----------------------------------------------------------
# create a "all at once" delivery order for two products
picking_out = self.PickingObj.create({
'picking_type_id': self.picking_type_out,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
picking_out.move_type = 'direct'
self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 2,
'product_uom': self.productA.uom_id.id,
'picking_id': picking_out.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
# validate this delivery order, it should be in the waiting state
picking_out.action_assign()
self.assertEqual(picking_out.state, "confirmed")
def test_72_picking_state_partial_reserve(self):
""" This test will check that the state of the picking is correctly computed according
to the state of its move lines and its move type.
"""
# move_type: direct == partial, one == all at once
# picking: confirmed == waiting availability, partially_available = partially available
# -----------------------------------------------------------
# "partial" and "reserve" scenario
# -----------------------------------------------------------
# get one product in stock
inventory_quant = self.env['stock.quant'].create({
'location_id': self.stock_location,
'product_id': self.productA.id,
'inventory_quantity': 1,
})
inventory_quant.action_apply_inventory()
# create a "partial" delivery order for two products
picking_out = self.PickingObj.create({
'picking_type_id': self.picking_type_out,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
picking_out.move_type = 'direct'
self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 2,
'product_uom': self.productA.uom_id.id,
'picking_id': picking_out.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
# validate this delivery order, it should be in partially available
picking_out.action_assign()
self.assertEqual(picking_out.state, "assigned")
# receive one product in stock
inventory_quant.inventory_quantity = 2
inventory_quant.action_apply_inventory()
# recheck availability of the delivery order, it should be assigned
picking_out.action_assign()
self.assertEqual(picking_out.state, "assigned")
def test_73_picking_state_partial_force_assign(self):
""" This test will check that the state of the picking is correctly computed according
to the state of its move lines and its move type.
"""
# move_type: direct == partial, one == all at once
# picking: confirmed == waiting availability, partially_available = partially available
# -----------------------------------------------------------
# "partial" and "force assign" scenario
# -----------------------------------------------------------
picking_out = self.PickingObj.create({
'picking_type_id': self.picking_type_out,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
picking_out.move_type = 'direct'
self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 2,
'product_uom': self.productA.uom_id.id,
'picking_id': picking_out.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
# validate this delivery order, it should be in the waiting state
picking_out.action_assign()
self.assertEqual(picking_out.state, "confirmed")
def test_74_move_state_waiting_mto(self):
""" This test will check that when a move is unreserved, its state changes to 'waiting' if
it has ancestors or if it has a 'procure_method' equal to 'make_to_order' else the state
changes to 'confirmed'.
"""
picking_out = self.PickingObj.create({
'picking_type_id': self.picking_type_out,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
move_mto_alone = self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 2,
'product_uom': self.productA.uom_id.id,
'picking_id': picking_out.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
'procure_method': 'make_to_order'})
move_with_ancestors = self.MoveObj.create({
'name': self.productB.name,
'product_id': self.productB.id,
'product_uom_qty': 2,
'product_uom': self.productB.uom_id.id,
'picking_id': picking_out.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
self.MoveObj.create({
'name': self.productB.name,
'product_id': self.productB.id,
'product_uom_qty': 2,
'product_uom': self.productB.uom_id.id,
'picking_id': picking_out.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
'move_dest_ids': [(4, move_with_ancestors.id, 0)]})
other_move = self.MoveObj.create({
'name': self.productC.name,
'product_id': self.productC.id,
'product_uom_qty': 2,
'product_uom': self.productC.uom_id.id,
'picking_id': picking_out.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
move_mto_alone._action_confirm()
move_with_ancestors._action_confirm()
other_move._action_confirm()
move_mto_alone._do_unreserve()
move_with_ancestors._do_unreserve()
other_move._do_unreserve()
self.assertEqual(move_mto_alone.state, "waiting")
self.assertEqual(move_with_ancestors.state, "waiting")
self.assertEqual(other_move.state, "confirmed")
def test_80_partial_picking_without_backorder(self):
""" This test will create a picking with an initial demand for a product
then process a lesser quantity than the expected quantity to be processed.
When the wizard ask for a backorder, the 'NO BACKORDER' option will be selected
and no backorder should be created afterwards
"""
picking = self.PickingObj.create({
'picking_type_id': self.picking_type_in,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location})
move_a = self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 10,
'product_uom': self.productA.uom_id.id,
'picking_id': picking.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location})
picking.action_confirm()
# Only 4 items are processed
move_a.move_line_ids.qty_done = 4
res_dict = picking.button_validate()
backorder_wizard = Form(self.env['stock.backorder.confirmation'].with_context(res_dict['context'])).save()
backorder_wizard.process_cancel_backorder()
# Checking that no backorders were attached to the picking
self.assertFalse(picking.backorder_id)
# Checking that the original move is still in the same picking
self.assertEqual(move_a.picking_id.id, picking.id)
move_lines = picking.move_lines
move_done = move_lines.browse(move_a.id)
move_canceled = move_lines - move_done
# Checking that the original move was set to done
self.assertEqual(move_done.product_uom_qty, 4)
self.assertEqual(move_done.state, 'done')
# Checking that the new move created was canceled
self.assertEqual(move_canceled.product_uom_qty, 6)
self.assertEqual(move_canceled.state, 'cancel')
# Checking that the canceled move is in the original picking
self.assertIn(move_canceled.id, picking.move_lines.mapped('id'))
def test_transit_multi_companies(self):
""" Ensure that inter company rules set the correct company on picking
and their moves.
"""
grp_multi_loc = self.env.ref('stock.group_stock_multi_locations')
grp_multi_routes = self.env.ref('stock.group_adv_location')
grp_multi_companies = self.env.ref('base.group_multi_company')
self.env.user.write({'groups_id': [(4, grp_multi_loc.id)]})
self.env.user.write({'groups_id': [(4, grp_multi_routes.id)]})
self.env.user.write({'groups_id': [(4, grp_multi_companies.id)]})
company_2 = self.company
# Need to add a new company on user.
self.env.user.write({'company_ids': [(4, company_2.id)]})
warehouse_company_1 = self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1)
f = Form(self.env['stock.location.route'])
f.name = 'From Company 1 to InterCompany'
f.company_id = self.env.company
with f.rule_ids.new() as rule:
rule.name = 'From Company 1 to InterCompany'
rule.action = 'pull'
rule.picking_type_id = warehouse_company_1.in_type_id
rule.location_src_id = self.env.ref('stock.stock_location_inter_wh')
rule.procure_method = 'make_to_order'
route_a = f.save()
warehouse_company_2 = self.env['stock.warehouse'].search([('company_id', '=', company_2.id)], limit=1)
f = Form(self.env['stock.location.route'])
f.name = 'From InterCompany to Company 2'
f.company_id = company_2
with f.rule_ids.new() as rule:
rule.name = 'From InterCompany to Company 2'
rule.action = 'pull'
rule.picking_type_id = warehouse_company_2.out_type_id
rule.location_id = self.env.ref('stock.stock_location_inter_wh')
rule.procure_method = 'make_to_stock'
route_b = f.save()
product = self.env['product.product'].create({
'name': 'The product from the other company that I absolutely want',
'type': 'product',
'route_ids': [(4, route_a.id), (4, route_b.id)]
})
replenish_wizard = self.env['product.replenish'].create({
'product_id': product.id,
'product_tmpl_id': product.product_tmpl_id.id,
'product_uom_id': self.uom_unit.id,
'quantity': '5',
'warehouse_id': warehouse_company_1.id,
})
replenish_wizard.launch_replenishment()
incoming_picking = self.env['stock.picking'].search([('product_id', '=', product.id), ('picking_type_id', '=', warehouse_company_1.in_type_id.id)])
outgoing_picking = self.env['stock.picking'].search([('product_id', '=', product.id), ('picking_type_id', '=', warehouse_company_2.out_type_id.id)])
self.assertEqual(incoming_picking.company_id, self.env.company)
self.assertEqual(incoming_picking.move_lines.company_id, self.env.company)
self.assertEqual(outgoing_picking.company_id, company_2)
self.assertEqual(outgoing_picking.move_lines.company_id, company_2)
def test_transit_multi_companies_ultimate(self):
""" Ensure that inter company rules set the correct company on picking
and their moves. This test validate a picking with make_to_order moves.
Moves are created in batch with a company-focused environment. This test
should create moves for company_2 and company_3 at the same time.
Ensure they are not create in the same batch.
"""
grp_multi_loc = self.env.ref('stock.group_stock_multi_locations')
grp_multi_routes = self.env.ref('stock.group_adv_location')
grp_multi_companies = self.env.ref('base.group_multi_company')
self.env.user.write({'groups_id': [(4, grp_multi_loc.id)]})
self.env.user.write({'groups_id': [(4, grp_multi_routes.id)]})
self.env.user.write({'groups_id': [(4, grp_multi_companies.id)]})
company_2 = self.company
# Need to add a new company on user.
self.env.user.write({'company_ids': [(4, company_2.id)]})
warehouse_company_1 = self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1)
f = Form(self.env['stock.location.route'])
f.name = 'From Company 1 to InterCompany'
f.company_id = self.env.company
with f.rule_ids.new() as rule:
rule.name = 'From Company 1 to InterCompany'
rule.action = 'pull'
rule.picking_type_id = warehouse_company_1.in_type_id
rule.location_src_id = self.env.ref('stock.stock_location_inter_wh')
rule.procure_method = 'make_to_order'
route_a = f.save()
warehouse_company_2 = self.env['stock.warehouse'].search([('company_id', '=', company_2.id)], limit=1)
f = Form(self.env['stock.location.route'])
f.name = 'From InterCompany to Company 2'
f.company_id = company_2
with f.rule_ids.new() as rule:
rule.name = 'From InterCompany to Company 2'
rule.action = 'pull'
rule.picking_type_id = warehouse_company_2.out_type_id
rule.location_id = self.env.ref('stock.stock_location_inter_wh')
rule.procure_method = 'make_to_stock'
route_b = f.save()
company_3 = self.env['res.company'].create({
'name': 'Alaska Company'
})
warehouse_company_3 = self.env['stock.warehouse'].search([('company_id', '=', company_3.id)], limit=1)
f = Form(self.env['stock.location.route'])
f.name = 'From InterCompany to Company 3'
f.company_id = company_3
with f.rule_ids.new() as rule:
rule.name = 'From InterCompany to Company 3'
rule.action = 'pull'
rule.picking_type_id = warehouse_company_3.out_type_id
rule.location_id = self.env.ref('stock.stock_location_inter_wh')
rule.procure_method = 'make_to_stock'
route_c = f.save()
product_from_company_2 = self.env['product.product'].create({
'name': 'The product from the other company that I absolutely want',
'type': 'product',
'route_ids': [(4, route_a.id), (4, route_b.id)]
})
product_from_company_3 = self.env['product.product'].create({
'name': 'Ice',
'type': 'product',
'route_ids': [(4, route_a.id), (4, route_c.id)]
})
f = Form(self.env['stock.picking'], view='stock.view_picking_form')
f.picking_type_id = warehouse_company_1.out_type_id
with f.move_ids_without_package.new() as move:
move.product_id = product_from_company_2
move.product_uom_qty = 5
with f.move_ids_without_package.new() as move:
move.product_id = product_from_company_3
move.product_uom_qty = 5
picking = f.save()
picking.move_ids_without_package.write({'procure_method': 'make_to_order'})
picking.action_confirm()
incoming_picking = self.env['stock.picking'].search([('product_id', '=', product_from_company_2.id), ('picking_type_id', '=', warehouse_company_1.in_type_id.id)])
outgoing_picking = self.env['stock.picking'].search([('product_id', '=', product_from_company_2.id), ('picking_type_id', '=', warehouse_company_2.out_type_id.id)])
self.assertEqual(incoming_picking.company_id, self.env.company)
self.assertEqual(incoming_picking.move_lines.mapped('company_id'), self.env.company)
self.assertEqual(outgoing_picking.company_id, company_2)
self.assertEqual(outgoing_picking.move_lines.company_id, company_2)
incoming_picking = self.env['stock.picking'].search([('product_id', '=', product_from_company_3.id), ('picking_type_id', '=', warehouse_company_1.in_type_id.id)])
outgoing_picking = self.env['stock.picking'].search([('product_id', '=', product_from_company_3.id), ('picking_type_id', '=', warehouse_company_3.out_type_id.id)])
self.assertEqual(incoming_picking.company_id, self.env.company)
self.assertEqual(incoming_picking.move_lines.mapped('company_id'), self.env.company)
self.assertEqual(outgoing_picking.company_id, company_3)
self.assertEqual(outgoing_picking.move_lines.company_id, company_3)
def test_picking_scheduled_date_readonlyness(self):
""" As it seems we keep breaking this thing over and over this small
test ensure the scheduled_date is writable on a picking in state 'draft' or 'confirmed'
"""
partner = self.env['res.partner'].create({'name': 'Hubert Bonisseur de la Bath'})
product = self.env['product.product'].create({'name': 'Un petit coup de polish', 'type': 'product'})
wh = self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1)
f = Form(self.env['stock.picking'], view='stock.view_picking_form')
f.partner_id = partner
f.picking_type_id = wh.out_type_id
with f.move_ids_without_package.new() as move:
move.product_id = product
move.product_uom_qty = 5
f.scheduled_date = fields.Datetime.now()
picking = f.save()
f = Form(picking, view='stock.view_picking_form')
f.scheduled_date = fields.Datetime.now()
picking = f.save()
self.assertEqual(f.state, 'draft')
picking.action_confirm()
f = Form(picking, view='stock.view_picking_form')
f.scheduled_date = fields.Datetime.now()
picking = f.save()
self.assertEqual(f.state, 'confirmed')
def test_picking_form_immediate_transfer(self):
picking_form = Form(self.env['stock.picking'].with_context(default_immediate_transfer=True))
picking_form.picking_type_id = self.env.ref('stock.picking_type_in')
with picking_form.move_ids_without_package.new() as move:
self.assertFalse(move._get_modifier('quantity_done', 'column_invisible'))
self.assertTrue(move._get_modifier('forecast_availability', 'column_invisible'))
self.assertTrue(move._get_modifier('reserved_availability', 'column_invisible'))
move.product_id = self.productA
move.quantity_done = 1
picking = picking_form.save()
self.assertEqual(picking.state, 'assigned')
picking_form = Form(self.env['stock.picking'].with_context(default_immediate_transfer=False))
picking_form.picking_type_id = self.env.ref('stock.picking_type_in')
with picking_form.move_ids_without_package.new() as move:
self.assertTrue(move._get_modifier('quantity_done', 'column_invisible'))
self.assertTrue(move._get_modifier('forecast_availability', 'column_invisible'))
self.assertTrue(move._get_modifier('reserved_availability', 'column_invisible'))
move.product_id = self.productA
move.product_uom_qty = 1
picking = picking_form.save()
self.assertEqual(picking.state, 'draft')
def test_validate_multiple_pickings_with_same_lot_names(self):
""" Checks only one lot is created when the same lot name is used in
different pickings and those pickings are validated together.
"""
# Creates two tracked products (one by lots and one by SN).
product_lot = self.env['product.product'].create({
'name': 'Tracked by lot',
'type': 'product',
'tracking': 'lot',
})
product_serial = self.env['product.product'].create({
'name': 'Tracked by SN',
'type': 'product',
'tracking': 'serial',
})
# Creates two receipts using some lot names in common.
picking_type = self.env['stock.picking.type'].browse(self.picking_type_in)
picking_form = Form(self.env['stock.picking'])
picking_form.picking_type_id = picking_type
with picking_form.move_ids_without_package.new() as move:
move.product_id = product_lot
move.product_uom_qty = 8
receipt_1 = picking_form.save()
receipt_1.action_confirm()
move_form = Form(receipt_1.move_lines, view="stock.view_stock_move_operations")
with move_form.move_line_ids.edit(0) as line:
line.lot_name = 'lot-001'
line.qty_done = 3
with move_form.move_line_ids.new() as line:
line.lot_name = 'lot-002'
line.qty_done = 3
with move_form.move_line_ids.new() as line:
line.lot_name = 'lot-003'
line.qty_done = 2
move = move_form.save()
picking_form = Form(self.env['stock.picking'])
picking_form.picking_type_id = picking_type
with picking_form.move_ids_without_package.new() as move:
move.product_id = product_lot
move.product_uom_qty = 8
receipt_2 = picking_form.save()
receipt_2.action_confirm()
move_form = Form(receipt_2.move_lines, view="stock.view_stock_move_operations")
with move_form.move_line_ids.edit(0) as line:
line.lot_name = 'lot-003'
line.qty_done = 2
with move_form.move_line_ids.new() as line:
line.lot_name = 'lot-004'
line.qty_done = 4
with move_form.move_line_ids.new() as line:
line.lot_name = 'lot-001'
line.qty_done = 1
with move_form.move_line_ids.new() as line:
line.lot_name = 'lot-005'
line.qty_done = 1
move = move_form.save()
# Validates the two receipts and checks the move lines' lot.
(receipt_1 | receipt_2).button_validate()
lots = self.env['stock.production.lot'].search([('product_id', '=', product_lot.id)], order='name asc')
self.assertEqual(len(lots), 5)
lot1, lot2, lot3, lot4, lot5 = lots
self.assertEqual(lot1.name, 'lot-001')
self.assertEqual(lot2.name, 'lot-002')
self.assertEqual(lot3.name, 'lot-003')
self.assertEqual(lot4.name, 'lot-004')
self.assertEqual(lot5.name, 'lot-005')
self.assertEqual(receipt_1.move_line_ids[0].lot_id.id, lot1.id)
self.assertEqual(receipt_1.move_line_ids[1].lot_id.id, lot2.id)
self.assertEqual(receipt_1.move_line_ids[2].lot_id.id, lot3.id)
self.assertEqual(receipt_2.move_line_ids[0].lot_id.id, lot3.id)
self.assertEqual(receipt_2.move_line_ids[1].lot_id.id, lot4.id)
self.assertEqual(receipt_2.move_line_ids[2].lot_id.id, lot1.id)
self.assertEqual(receipt_2.move_line_ids[3].lot_id.id, lot5.id)
# Checks also it still raise an error when it tries to create multiple time
# the same serial numbers (same scenario but with SN instead of lots).
picking_type = self.env['stock.picking.type'].browse(self.picking_type_in)
picking_form = Form(self.env['stock.picking'])
picking_form.picking_type_id = picking_type
with picking_form.move_ids_without_package.new() as move:
move.product_id = product_serial
move.product_uom_qty = 2
receipt_1 = picking_form.save()
receipt_1.action_confirm()
move_form = Form(receipt_1.move_lines, view="stock.view_stock_move_operations")
with move_form.move_line_ids.edit(0) as line:
line.lot_name = 'sn-001'
with move_form.move_line_ids.new() as line:
line.lot_name = 'sn-002'
move = move_form.save()
picking_form = Form(self.env['stock.picking'])
picking_form.picking_type_id = picking_type
with picking_form.move_ids_without_package.new() as move:
move.product_id = product_serial
move.product_uom_qty = 2
receipt_2 = picking_form.save()
receipt_2.action_confirm()
move_form = Form(receipt_2.move_lines, view="stock.view_stock_move_operations")
with move_form.move_line_ids.edit(0) as line:
line.lot_name = 'sn-002'
with move_form.move_line_ids.new() as line:
line.lot_name = 'sn-001'
move = move_form.save()
# Validates the two receipts => It should raise an error as there is duplicate SN.
with self.assertRaises(ValidationError):
(receipt_1 | receipt_2).button_validate()
def test_assign_qty_to_first_move(self):
""" Suppose two out picking waiting for an available quantity. When receiving such
a quantity, the latter should be assign to the picking with the highest priority
and the earliest scheduled date. """
def create_picking(type, from_loc, to_loc, sequence=10, delay=0):
picking = self.PickingObj.create({
'picking_type_id': type,
'location_id': from_loc,
'location_dest_id': to_loc,
})
self.MoveObj.create({
'name': self.productA.name,
'sequence': sequence,
'date': fields.Datetime.add(fields.Datetime.now(), second=delay),
'reservation_date': fields.Date.today(),
'product_id': self.productA.id,
'product_uom_qty': 1,
'product_uom': self.productA.uom_id.id,
'picking_id': picking.id,
'location_id': from_loc,
'location_dest_id': to_loc,
})
picking.action_confirm()
return picking
def validate_picking(picking):
res_dict = picking.button_validate()
wizard = Form(self.env[(res_dict.get('res_model'))].with_context(res_dict['context'])).save()
wizard.process()
out01 = create_picking(self.picking_type_out, self.stock_location, self.customer_location)
out02 = create_picking(self.picking_type_out, self.stock_location, self.customer_location, sequence=2, delay=1)
in01 = create_picking(self.picking_type_in, self.supplier_location, self.stock_location, delay=2)
validate_picking(in01)
self.assertEqual(out01.state, 'assigned')
self.assertEqual(out02.state, 'confirmed')
validate_picking(out01)
out03 = create_picking(self.picking_type_out, self.stock_location, self.customer_location, delay=3)
out03.priority = "1"
in02 = create_picking(self.picking_type_in, self.supplier_location, self.stock_location, delay=4)
validate_picking(in02)
self.assertEqual(out02.state, 'confirmed')
self.assertEqual(out03.state, 'assigned')
def test_auto_assign_backorder(self):
""" When a backorder is created, the quantities should be assigned if the reservation method
is set on 'At Confirmation' """
stock_location = self.env['stock.location'].browse(self.stock_location)
picking_type_out = self.env['stock.picking.type'].browse(self.picking_type_out)
self.env['stock.quant']._update_available_quantity(self.productA, stock_location, 10)
picking_type_out.reservation_method = 'at_confirm'
picking_out = self.PickingObj.create({
'picking_type_id': picking_type_out.id,
'location_id': stock_location.id,
'location_dest_id': self.customer_location,
})
move_out = self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 10,
'product_uom': self.productA.uom_id.id,
'picking_id': picking_out.id,
'location_id': stock_location.id,
'location_dest_id': self.customer_location
})
move_out.quantity_done = 7
action_dict = picking_out.button_validate()
backorder_wizard = Form(self.env[action_dict['res_model']].with_context(action_dict['context'])).save()
backorder_wizard.process()
bo = self.env['stock.picking'].search([('backorder_id', '=', picking_out.id)])
self.assertEqual(bo.state, 'assigned')
def test_stock_move_with_partner_id(self):
""" Ensure that the partner_id of the picking entry is
transmitted to the SM upon object creation.
"""
partner_1 = self.env['res.partner'].create({'name': 'Hubert Bonisseur de la Bath'})
partner_2 = self.env['res.partner'].create({'name': 'Donald Clairvoyant du Bled'})
product = self.env['product.product'].create({'name': 'Un petit coup de polish', 'type': 'product'})
wh = self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1)
f = Form(self.env['stock.picking'])
f.partner_id = partner_1
f.picking_type_id = wh.out_type_id
with f.move_ids_without_package.new() as move:
move.product_id = product
move.product_uom_qty = 5
picking = f.save()
self.assertEqual(picking.move_lines.partner_id, partner_1)
picking.write({'partner_id': partner_2.id})
self.assertEqual(picking.move_lines.partner_id, partner_2)
def test_cancel_picking_with_scrapped_products(self):
"""
The user scraps some products of a picking, then cancel this picking
The test ensures that the scrapped SM is not cancelled
"""
stock_location = self.env['stock.location'].browse(self.stock_location)
self.env['stock.quant']._update_available_quantity(self.productA, stock_location, 10)
picking = self.env['stock.picking'].create({
'picking_type_id': self.picking_type_out,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location,
})
move = self.env['stock.move'].create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 1,
'product_uom': self.productA.uom_id.id,
'picking_id': picking.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location,
})
picking.action_confirm()
picking.action_assign()
scrap = self.env['stock.scrap'].create({
'picking_id': picking.id,
'product_id': self.productA.id,
'product_uom_id': self.productA.uom_id.id,
'scrap_qty': 1.0,
})
scrap.do_scrap()
picking.action_cancel()
self.assertEqual(picking.state, 'cancel')
self.assertEqual(move.state, 'cancel')
self.assertEqual(scrap.move_id.state, 'done')
def test_receive_tracked_product(self):
self.productA.tracking = 'serial'
type_in = self.env['stock.picking.type'].browse(self.picking_type_in)
receipt_form = Form(self.env['stock.picking'].with_context(default_immediate_transfer=True))
receipt_form.picking_type_id = type_in
with receipt_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.productA
receipt = receipt_form.save()
move_form = Form(receipt.move_lines, view='stock.view_stock_move_nosuggest_operations')
with move_form.move_line_nosuggest_ids.new() as line:
line.lot_name = "USN01"
move_form.save()
receipt.button_validate()
quant = self.productA.stock_quant_ids.filtered(lambda q: q.location_id.id == self.stock_location)
self.assertEqual(receipt.state, 'done')
self.assertEqual(quant.quantity, 1.0)
self.assertEqual(quant.lot_id.name, 'USN01')
def test_assign_sm_to_existing_picking(self):
"""
Suppose:
- Two warehouses WH01, WH02
- Three products with the route 'WH02 supplied by WH01'
We trigger an orderpoint for each product
There should be two pickings (out from WH01 + in to WH02)
"""
wh01_address, wh02_address = self.env['res.partner'].create([{
'name': 'Address %s' % i,
'parent_id': self.env.company.id,
'type': 'delivery',
} for i in [1, 2]])
warehouse01 = self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1)
warehouse01.partner_id = wh01_address
warehouse02 = self.env['stock.warehouse'].create({
'name': 'Second Warehouse',
'code': 'WH02',
'partner_id': wh02_address.id,
'resupply_wh_ids': [(6, 0, warehouse01.ids)],
})
wh01_stock_location = warehouse01.lot_stock_id
wh02_stock_location = warehouse02.lot_stock_id
products = self.productA + self.productB + self.productC
for product in products:
product.route_ids = [(6, 0, warehouse02.resupply_route_ids.ids)]
self.env['stock.quant']._update_available_quantity(product, wh01_stock_location, 10)
self.env['stock.warehouse.orderpoint'].create({
'name': 'RR for %s' % product.name,
'warehouse_id': warehouse02.id,
'location_id': wh02_stock_location.id,
'product_id': product.id,
'product_min_qty': 1,
'product_max_qty': 5,
})
self.env['procurement.group'].run_scheduler()
out_moves = self.env['stock.move'].search([('product_id', 'in', products.ids), ('picking_id', '!=', False), ('location_id', '=', wh01_stock_location.id)])
in_moves = self.env['stock.move'].search([('product_id', 'in', products.ids), ('picking_id', '!=', False), ('location_dest_id', '=', wh02_stock_location.id)])
out_picking = out_moves[0].picking_id
self.assertEqual(len(out_moves), 3)
self.assertEqual(out_moves.product_id, products)
self.assertEqual(out_moves.picking_id, out_picking, 'All SM should be part of the same picking')
self.assertEqual(out_picking.partner_id, wh02_address, 'It should be an outgoing picking to %s' % wh02_address.display_name)
in_picking = in_moves[0].picking_id
self.assertEqual(len(in_moves), 3)
self.assertEqual(in_moves.product_id, products)
self.assertEqual(in_moves.picking_id, in_picking, 'All SM should be part of the same picking')
self.assertEqual(in_picking.partner_id, wh01_address, 'It should be an incoming picking from %s' % wh01_address.display_name)
def test_assign_done_sml_and_validate_it(self):
"""
From the detailed operations wizard, create a SML that has a
sub-location as destination location. After its creation, the
destination location should not changed. Same when marking the picking
as done
"""
grp_multi_loc = self.env.ref('stock.group_stock_multi_locations')
self.env.user.write({'groups_id': [(4, grp_multi_loc.id, 0)]})
warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1)
stock_location = warehouse.lot_stock_id
sub_loc = stock_location.child_ids[0]
self.productA.tracking = 'lot'
receipt_form = Form(self.env['stock.picking'].with_context(default_immediate_transfer=True))
receipt_form.picking_type_id = self.env.ref('stock.picking_type_in')
with receipt_form.move_ids_without_package.new() as move:
move.product_id = self.productA
receipt = receipt_form.save()
with Form(receipt.move_lines, view='stock.view_stock_move_nosuggest_operations') as move_form:
with move_form.move_line_nosuggest_ids.new() as sml:
sml.location_dest_id = sub_loc
sml.lot_name = '123'
sml.qty_done = 10
done_sml = receipt.move_lines.move_line_ids.filtered(lambda sml: sml.qty_done > 0)
self.assertEqual(done_sml.location_dest_id, sub_loc)
receipt.button_validate()
self.assertEqual(receipt.move_lines.move_line_ids.location_dest_id, sub_loc)
| 55.882405
| 127,356
|
12,461
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# Author: Leonardo Pistone
# Copyright 2015 Camptocamp SA
from odoo.addons.stock.tests.common2 import TestStockCommon
from odoo.exceptions import UserError
from odoo.tests.common import Form
class TestVirtualAvailable(TestStockCommon):
def setUp(self):
super(TestVirtualAvailable, self).setUp()
# Make `product3` a storable product for this test. Indeed, creating quants
# and playing with owners is not possible for consumables.
self.product_3.type = 'product'
self.env['stock.picking.type'].browse(self.ref('stock.picking_type_out')).reservation_method = 'manual'
self.env['stock.quant'].create({
'product_id': self.product_3.id,
'location_id': self.env.ref('stock.stock_location_stock').id,
'quantity': 30.0})
self.env['stock.quant'].create({
'product_id': self.product_3.id,
'location_id': self.env.ref('stock.stock_location_stock').id,
'quantity': 10.0,
'owner_id': self.user_stock_user.partner_id.id})
self.picking_out = self.env['stock.picking'].create({
'picking_type_id': self.ref('stock.picking_type_out'),
'location_id': self.env.ref('stock.stock_location_stock').id,
'location_dest_id': self.env.ref('stock.stock_location_customers').id})
self.env['stock.move'].create({
'name': 'a move',
'product_id': self.product_3.id,
'product_uom_qty': 3.0,
'product_uom': self.product_3.uom_id.id,
'picking_id': self.picking_out.id,
'location_id': self.env.ref('stock.stock_location_stock').id,
'location_dest_id': self.env.ref('stock.stock_location_customers').id})
self.picking_out_2 = self.env['stock.picking'].create({
'picking_type_id': self.ref('stock.picking_type_out'),
'location_id': self.env.ref('stock.stock_location_stock').id,
'location_dest_id': self.env.ref('stock.stock_location_customers').id})
self.env['stock.move'].create({
'restrict_partner_id': self.user_stock_user.partner_id.id,
'name': 'another move',
'product_id': self.product_3.id,
'product_uom_qty': 5.0,
'product_uom': self.product_3.uom_id.id,
'picking_id': self.picking_out_2.id,
'location_id': self.env.ref('stock.stock_location_stock').id,
'location_dest_id': self.env.ref('stock.stock_location_customers').id})
def test_without_owner(self):
self.assertAlmostEqual(40.0, self.product_3.virtual_available)
self.picking_out.action_assign()
self.picking_out_2.action_assign()
self.assertAlmostEqual(32.0, self.product_3.virtual_available)
def test_with_owner(self):
prod_context = self.product_3.with_context(owner_id=self.user_stock_user.partner_id.id)
self.assertAlmostEqual(10.0, prod_context.virtual_available)
self.picking_out.action_assign()
self.picking_out_2.action_assign()
self.assertAlmostEqual(5.0, prod_context.virtual_available)
def test_free_quantity(self):
""" Test the value of product.free_qty. Free_qty = qty_on_hand - qty_reserved"""
self.assertAlmostEqual(40.0, self.product_3.free_qty)
self.picking_out.action_confirm()
self.picking_out_2.action_confirm()
# No reservation so free_qty is unchanged
self.assertAlmostEqual(40.0, self.product_3.free_qty)
self.picking_out.action_assign()
self.picking_out_2.action_assign()
# 8 units are now reserved
self.assertAlmostEqual(32.0, self.product_3.free_qty)
self.picking_out.do_unreserve()
self.picking_out_2.do_unreserve()
# 8 units are available again
self.assertAlmostEqual(40.0, self.product_3.free_qty)
def test_archive_product_1(self):
"""`qty_available` and `virtual_available` are computed on archived products"""
self.assertTrue(self.product_3.active)
self.assertAlmostEqual(40.0, self.product_3.qty_available)
self.assertAlmostEqual(40.0, self.product_3.virtual_available)
self.product_3.active = False
self.assertAlmostEqual(40.0, self.product_3.qty_available)
self.assertAlmostEqual(40.0, self.product_3.virtual_available)
def test_archive_product_2(self):
"""Archiving a product should archive its reordering rules"""
self.assertTrue(self.product_3.active)
orderpoint_form = Form(self.env['stock.warehouse.orderpoint'])
orderpoint_form.product_id = self.product_3
orderpoint_form.location_id = self.env.ref('stock.stock_location_stock')
orderpoint_form.product_min_qty = 0.0
orderpoint_form.product_max_qty = 5.0
orderpoint = orderpoint_form.save()
self.assertTrue(orderpoint.active)
self.product_3.active = False
self.assertFalse(orderpoint.active)
def test_change_product_company(self):
""" Checks we can't change the product's company if this product has
quant in another company. """
company1 = self.env.ref('base.main_company')
company2 = self.env['res.company'].create({'name': 'Second Company'})
product = self.env['product.product'].create({
'name': 'Product [TEST - Change Company]',
'type': 'product',
})
# Creates a quant for productA in the first company.
self.env['stock.quant'].create({
'product_id': product.id,
'product_uom_id': self.uom_unit.id,
'location_id': self.location_1.id,
'quantity': 7,
'reserved_quantity': 0,
})
# Assigns a company: should be OK for company1 but should raise an error for company2.
product.company_id = company1.id
with self.assertRaises(UserError):
product.company_id = company2.id
# Checks we can assing company2 for the product once there is no more quant for it.
quant = self.env['stock.quant'].search([('product_id', '=', product.id)])
quant.quantity = 0
self.env['stock.quant']._unlink_zero_quants()
product.company_id = company2.id # Should work this time.
def test_change_product_company_02(self):
""" Checks we can't change the product's company if this product has
stock move line in another company. """
company1 = self.env.ref('base.main_company')
company2 = self.env['res.company'].create({'name': 'Second Company'})
product = self.env['product.product'].create({
'name': 'Product [TEST - Change Company]',
'type': 'consu',
})
picking = self.env['stock.picking'].create({
'location_id': self.env.ref('stock.stock_location_customers').id,
'location_dest_id': self.env.ref('stock.stock_location_stock').id,
'picking_type_id': self.ref('stock.picking_type_in'),
})
self.env['stock.move'].create({
'name': 'test',
'location_id': self.env.ref('stock.stock_location_customers').id,
'location_dest_id': self.env.ref('stock.stock_location_stock').id,
'product_id': product.id,
'product_uom': product.uom_id.id,
'product_uom_qty': 1,
'picking_id': picking.id,
})
picking.action_confirm()
wizard_data = picking.button_validate()
wizard = Form(self.env[wizard_data['res_model']].with_context(wizard_data['context'])).save()
wizard.process()
product.company_id = company1.id
with self.assertRaises(UserError):
product.company_id = company2.id
def test_change_product_company_exclude_vendor_and_customer_location(self):
""" Checks we can change product company where only exist single company
and exist quant in vendor/customer location"""
company1 = self.env.ref('base.main_company')
customer_location = self.env.ref('stock.stock_location_customers')
supplier_location = self.env.ref('stock.stock_location_suppliers')
product = self.env['product.product'].create({
'name': 'Product Single Company',
'type': 'product',
})
# Creates a quant for company 1.
self.env['stock.quant'].create({
'product_id': product.id,
'product_uom_id': self.uom_unit.id,
'location_id': self.location_1.id,
'quantity': 5,
})
# Creates a quant for vendor location.
self.env['stock.quant'].create({
'product_id': product.id,
'product_uom_id': self.uom_unit.id,
'location_id': supplier_location.id,
'quantity': -15,
})
# Creates a quant for customer location.
self.env['stock.quant'].create({
'product_id': product.id,
'product_uom_id': self.uom_unit.id,
'location_id': customer_location.id,
'quantity': 10,
})
# Assigns a company: should be ok because only exist one company (exclude vendor and customer location)
product.company_id = company1.id
# Reset product company to empty
product.company_id = False
company2 = self.env['res.company'].create({'name': 'Second Company'})
# Assigns to another company: should be not okay because exist quants in defferent company (exclude vendor and customer location)
with self.assertRaises(UserError):
product.company_id = company2.id
def test_search_qty_available(self):
product = self.env['product.product'].create({
'name': 'Brand new product',
'type': 'product',
})
result = self.env['product.product'].search([
('qty_available', '=', 0),
('id', 'in', product.ids),
])
self.assertEqual(product, result)
def test_search_product_template(self):
"""
Suppose a variant V01 that can not be deleted because it is used by a
lot [1]. Then, the variant's template T is changed: we add a dynamic
attribute. Because of [1], V01 is archived. This test ensures that
`name_search` still finds T.
Then, we create a new variant V02 of T. This test also ensures that
calling `name_search` with a negative operator will exclude T from the
result.
"""
template = self.env['product.template'].create({
'name': 'Super Product',
})
product01 = template.product_variant_id
self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': product01.id,
'company_id': self.env.company.id,
})
product_attribute = self.env['product.attribute'].create({
'name': 'PA',
'create_variant': 'dynamic'
})
self.env['product.attribute.value'].create([{
'name': 'PAV' + str(i),
'attribute_id': product_attribute.id
} for i in range(2)])
tmpl_attr_lines = self.env['product.template.attribute.line'].create({
'attribute_id': product_attribute.id,
'product_tmpl_id': product01.product_tmpl_id.id,
'value_ids': [(6, 0, product_attribute.value_ids.ids)],
})
self.assertFalse(product01.active)
self.assertTrue(template.active)
self.assertFalse(template.product_variant_ids)
res = self.env['product.template'].name_search(name='super', operator='ilike')
res_ids = [r[0] for r in res]
self.assertIn(template.id, res_ids)
product02 = self.env['product.product'].create({
'default_code': '123',
'product_tmpl_id': template.id,
'product_template_attribute_value_ids': [(6, 0, tmpl_attr_lines.product_template_value_ids[0].ids)]
})
self.assertFalse(product01.active)
self.assertTrue(product02.active)
self.assertTrue(template)
self.assertEqual(template.product_variant_ids, product02)
res = self.env['product.template'].name_search(name='123', operator='not ilike')
res_ids = [r[0] for r in res]
self.assertNotIn(template.id, res_ids)
| 44.663082
| 12,461
|
4,841
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo.tests import common
class TestStockCommon(common.TransactionCase):
@classmethod
def setUpClass(cls):
super(TestStockCommon, cls).setUpClass()
cls.ProductObj = cls.env['product.product']
cls.UomObj = cls.env['uom.uom']
cls.PartnerObj = cls.env['res.partner']
cls.ModelDataObj = cls.env['ir.model.data']
cls.StockPackObj = cls.env['stock.move.line']
cls.StockQuantObj = cls.env['stock.quant']
cls.PickingObj = cls.env['stock.picking']
cls.MoveObj = cls.env['stock.move']
cls.LotObj = cls.env['stock.production.lot']
# Model Data
cls.picking_type_in = cls.ModelDataObj._xmlid_to_res_id('stock.picking_type_in')
cls.picking_type_out = cls.ModelDataObj._xmlid_to_res_id('stock.picking_type_out')
cls.env['stock.picking.type'].browse(cls.picking_type_out).reservation_method = 'manual'
cls.supplier_location = cls.ModelDataObj._xmlid_to_res_id('stock.stock_location_suppliers')
cls.stock_location = cls.ModelDataObj._xmlid_to_res_id('stock.stock_location_stock')
pack_location = cls.env.ref('stock.location_pack_zone')
pack_location.active = True
cls.pack_location = pack_location.id
output_location = cls.env.ref('stock.stock_location_output')
output_location.active = True
cls.output_location = output_location.id
cls.customer_location = cls.ModelDataObj._xmlid_to_res_id('stock.stock_location_customers')
cls.categ_unit = cls.ModelDataObj._xmlid_to_res_id('uom.product_uom_categ_unit')
cls.categ_kgm = cls.ModelDataObj._xmlid_to_res_id('uom.product_uom_categ_kgm')
# Product Created A, B, C, D
cls.productA = cls.ProductObj.create({'name': 'Product A', 'type': 'product'})
cls.productB = cls.ProductObj.create({'name': 'Product B', 'type': 'product'})
cls.productC = cls.ProductObj.create({'name': 'Product C', 'type': 'product'})
cls.productD = cls.ProductObj.create({'name': 'Product D', 'type': 'product'})
cls.productE = cls.ProductObj.create({'name': 'Product E', 'type': 'product'})
# Configure unit of measure.
cls.uom_kg = cls.env['uom.uom'].search([('category_id', '=', cls.categ_kgm), ('uom_type', '=', 'reference')], limit=1)
cls.uom_kg.write({
'name': 'Test-KG',
'rounding': 0.000001})
cls.uom_tone = cls.UomObj.create({
'name': 'Test-Tone',
'category_id': cls.categ_kgm,
'uom_type': 'bigger',
'factor_inv': 1000.0,
'rounding': 0.001})
cls.uom_gm = cls.UomObj.create({
'name': 'Test-G',
'category_id': cls.categ_kgm,
'uom_type': 'smaller',
'factor': 1000.0,
'rounding': 0.001})
cls.uom_mg = cls.UomObj.create({
'name': 'Test-MG',
'category_id': cls.categ_kgm,
'uom_type': 'smaller',
'factor': 100000.0,
'rounding': 0.001})
# Check Unit
cls.uom_unit = cls.env['uom.uom'].search([('category_id', '=', cls.categ_unit), ('uom_type', '=', 'reference')], limit=1)
cls.uom_unit.write({
'name': 'Test-Unit',
'rounding': 1.0})
cls.uom_dozen = cls.UomObj.create({
'name': 'Test-DozenA',
'category_id': cls.categ_unit,
'factor_inv': 12,
'uom_type': 'bigger',
'rounding': 0.001})
cls.uom_sdozen = cls.UomObj.create({
'name': 'Test-SDozenA',
'category_id': cls.categ_unit,
'factor_inv': 144,
'uom_type': 'bigger',
'rounding': 0.001})
cls.uom_sdozen_round = cls.UomObj.create({
'name': 'Test-SDozenA Round',
'category_id': cls.categ_unit,
'factor_inv': 144,
'uom_type': 'bigger',
'rounding': 1.0})
# Product for different unit of measure.
cls.DozA = cls.ProductObj.create({'name': 'Dozon-A', 'type': 'product', 'uom_id': cls.uom_dozen.id, 'uom_po_id': cls.uom_dozen.id})
cls.SDozA = cls.ProductObj.create({'name': 'SuperDozon-A', 'type': 'product', 'uom_id': cls.uom_sdozen.id, 'uom_po_id': cls.uom_sdozen.id})
cls.SDozARound = cls.ProductObj.create({'name': 'SuperDozenRound-A', 'type': 'product', 'uom_id': cls.uom_sdozen_round.id, 'uom_po_id': cls.uom_sdozen_round.id})
cls.UnitA = cls.ProductObj.create({'name': 'Unit-A', 'type': 'product'})
cls.kgB = cls.ProductObj.create({'name': 'kg-B', 'type': 'product', 'uom_id': cls.uom_kg.id, 'uom_po_id': cls.uom_kg.id})
cls.gB = cls.ProductObj.create({'name': 'g-B', 'type': 'product', 'uom_id': cls.uom_gm.id, 'uom_po_id': cls.uom_gm.id})
| 49.907216
| 4,841
|
29,354
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo.addons.stock.tests.common2 import TestStockCommon
from odoo.tests import Form
from odoo.exceptions import UserError
from odoo.tools import mute_logger
class TestWarehouse(TestStockCommon):
def setUp(self):
super(TestWarehouse, self).setUp()
self.partner = self.env['res.partner'].create({'name': 'Deco Addict'})
def test_inventory_product(self):
self.product_1.type = 'product'
product_1_quant = self.env['stock.quant'].with_context(inventory_mode=True).create({
'product_id': self.product_1.id,
'inventory_quantity': 50.0,
'location_id': self.warehouse_1.lot_stock_id.id,
})
product_1_quant.action_apply_inventory()
# Make sure the inventory was successful
move_in_id = self.env['stock.move'].search([('is_inventory', '=', True), ('product_id', '=', self.product_1.id)])
self.assertEqual(len(move_in_id), 1)
self.assertEqual(move_in_id.product_qty, 50.0)
self.assertEqual(product_1_quant.quantity, 50.0)
self.assertEqual(move_in_id.product_uom, self.product_1.uom_id)
self.assertEqual(move_in_id.state, 'done')
# Update the inventory, set to 35
product_1_quant.inventory_quantity = 35.0
product_1_quant.action_apply_inventory()
# Check related move and quants
move_ids = self.env['stock.move'].search([('is_inventory', '=', True), ('product_id', '=', self.product_1.id)])
self.assertEqual(len(move_ids), 2)
move_out_id = move_ids[-1]
self.assertEqual(move_out_id.product_qty, 15.0)
self.assertEqual(move_out_id.location_id, self.warehouse_1.lot_stock_id)
self.assertEqual(move_out_id.location_dest_id, self.product_1.property_stock_inventory) # Inventory loss
self.assertEqual(move_out_id.state, 'done')
quants = self.env['stock.quant']._gather(self.product_1, self.product_1.property_stock_inventory)
self.assertEqual(len(quants), 1) # One quant created for inventory loss
# Check quantity of product in various locations: current, its parent, brother and other
self.assertEqual(self.env['stock.quant']._gather(self.product_1, self.warehouse_1.lot_stock_id).quantity, 35.0)
self.assertEqual(self.env['stock.quant']._gather(self.product_1, self.warehouse_1.lot_stock_id.location_id).quantity, 35.0)
self.assertEqual(self.env['stock.quant']._gather(self.product_1, self.warehouse_1.view_location_id).quantity, 35.0)
self.assertEqual(self.env['stock.quant']._gather(self.product_1, self.warehouse_1.wh_input_stock_loc_id).quantity, 0.0)
self.assertEqual(self.env['stock.quant']._gather(self.product_1, self.env.ref('stock.stock_location_stock')).quantity, 0.0)
def test_inventory_wizard_as_manager(self):
""" Using the "Update Quantity" wizard as stock manager.
"""
self.product_1.type = 'product'
InventoryWizard = self.env['stock.change.product.qty'].with_user(self.user_stock_manager)
inventory_wizard = InventoryWizard.create({
'product_id': self.product_1.id,
'product_tmpl_id': self.product_1.product_tmpl_id.id,
'new_quantity': 50.0,
})
inventory_wizard.change_product_qty()
# Check quantity was updated
self.assertEqual(self.product_1.virtual_available, 50.0)
self.assertEqual(self.product_1.qty_available, 50.0)
# Check associated quants: 2 quants for the product and the quantity (1 in stock, 1 in inventory adjustment)
quant = self.env['stock.quant'].search([('id', 'not in', self.existing_quants.ids)])
self.assertEqual(len(quant), 2)
def test_inventory_wizard_as_user(self):
""" Using the "Update Quantity" wizard as stock user.
"""
self.product_1.type = 'product'
InventoryWizard = self.env['stock.change.product.qty'].with_user(self.user_stock_user)
inventory_wizard = InventoryWizard.create({
'product_id': self.product_1.id,
'product_tmpl_id': self.product_1.product_tmpl_id.id,
'new_quantity': 50.0,
})
# User has no right on quant, must raise an AccessError
with self.assertRaises(UserError):
inventory_wizard.change_product_qty()
def test_basic_move(self):
product = self.product_3.with_user(self.user_stock_manager)
product.type = 'product'
picking_out = self.env['stock.picking'].create({
'partner_id': self.partner.id,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
'location_id': self.warehouse_1.lot_stock_id.id,
'location_dest_id': self.env.ref('stock.stock_location_customers').id,
})
customer_move = self.env['stock.move'].create({
'name': product.name,
'product_id': product.id,
'product_uom_qty': 5,
'product_uom': product.uom_id.id,
'picking_id': picking_out.id,
'location_id': self.warehouse_1.lot_stock_id.id,
'location_dest_id': self.env.ref('stock.stock_location_customers').id,
})
# simulate create + onchange
# test move values
self.assertEqual(customer_move.product_uom, product.uom_id)
self.assertEqual(customer_move.location_id, self.warehouse_1.lot_stock_id)
self.assertEqual(customer_move.location_dest_id, self.env.ref('stock.stock_location_customers'))
# confirm move, check quantity on hand and virtually available, without location context
customer_move._action_confirm()
self.assertEqual(product.qty_available, 0.0)
self.assertEqual(product.virtual_available, -5.0)
customer_move.quantity_done = 5
customer_move._action_done()
self.assertEqual(product.qty_available, -5.0)
# compensate negative quants by receiving products from supplier
receive_move = self._create_move(product, self.env.ref('stock.stock_location_suppliers'), self.warehouse_1.lot_stock_id, product_uom_qty=15)
receive_move._action_confirm()
receive_move.quantity_done = 15
receive_move._action_done()
product._compute_quantities()
self.assertEqual(product.qty_available, 10.0)
self.assertEqual(product.virtual_available, 10.0)
# new move towards customer
customer_move_2 = self._create_move(product, self.warehouse_1.lot_stock_id, self.env.ref('stock.stock_location_customers'), product_uom_qty=2)
customer_move_2._action_confirm()
product._compute_quantities()
self.assertEqual(product.qty_available, 10.0)
self.assertEqual(product.virtual_available, 8.0)
customer_move_2.quantity_done = 2.0
customer_move_2._action_done()
product._compute_quantities()
self.assertEqual(product.qty_available, 8.0)
def test_inventory_adjustment_and_negative_quants_1(self):
"""Make sure negative quants from returns get wiped out with an inventory adjustment"""
productA = self.env['product.product'].create({'name': 'Product A', 'type': 'product'})
stock_location = self.env.ref('stock.stock_location_stock')
customer_location = self.env.ref('stock.stock_location_customers')
# Create a picking out and force availability
picking_out = self.env['stock.picking'].create({
'partner_id': self.partner.id,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
'location_id': stock_location.id,
'location_dest_id': customer_location.id,
})
self.env['stock.move'].create({
'name': productA.name,
'product_id': productA.id,
'product_uom_qty': 1,
'product_uom': productA.uom_id.id,
'picking_id': picking_out.id,
'location_id': stock_location.id,
'location_dest_id': customer_location.id,
})
picking_out.action_confirm()
picking_out.move_lines.quantity_done = 1
picking_out._action_done()
quant = self.env['stock.quant'].search([('product_id', '=', productA.id), ('location_id', '=', stock_location.id)])
self.assertEqual(len(quant), 1)
stock_return_picking_form = Form(self.env['stock.return.picking']
.with_context(active_ids=picking_out.ids, active_id=picking_out.ids[0],
active_model='stock.picking'))
stock_return_picking = stock_return_picking_form.save()
stock_return_picking.product_return_moves.quantity = 1.0
stock_return_picking_action = stock_return_picking.create_returns()
return_pick = self.env['stock.picking'].browse(stock_return_picking_action['res_id'])
return_pick.action_assign()
return_pick.move_lines.quantity_done = 1
return_pick._action_done()
quant = self.env['stock.quant'].search([('product_id', '=', productA.id), ('location_id', '=', stock_location.id)])
self.assertEqual(sum(quant.mapped('quantity')), 0)
def test_inventory_adjustment_and_negative_quants_2(self):
"""Make sure negative quants get wiped out with an inventory adjustment"""
productA = self.env['product.product'].create({'name': 'Product A', 'type': 'product'})
stock_location = self.env.ref('stock.stock_location_stock')
customer_location = self.env.ref('stock.stock_location_customers')
location_loss = productA.property_stock_inventory
# Create a picking out and force availability
picking_out = self.env['stock.picking'].create({
'partner_id': self.partner.id,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
'location_id': stock_location.id,
'location_dest_id': customer_location.id,
})
self.env['stock.move'].create({
'name': productA.name,
'product_id': productA.id,
'product_uom_qty': 1,
'product_uom': productA.uom_id.id,
'picking_id': picking_out.id,
'location_id': stock_location.id,
'location_dest_id': customer_location.id,
})
picking_out.action_confirm()
picking_out.move_lines.quantity_done = 1
picking_out._action_done()
# Make an inventory adjustment to set the quantity to 0
quant = self.env['stock.quant'].search([('product_id', '=', productA.id), ('location_id', '=', stock_location.id)])
self.assertEqual(len(quant), 1, "Wrong number of quants created.")
self.assertEqual(quant.quantity, -1, "Theoretical quantity should be -1.")
# Put the quantity back to 0
quant.inventory_quantity = 0
quant.action_apply_inventory()
# The inventory adjustment should have created one
move = self.env['stock.move'].search([('product_id', '=', productA.id), ('is_inventory', '=', True)])
self.assertEqual(len(move), 1)
self.assertEqual(move.product_qty, 1, "Moves created with wrong quantity.")
self.assertEqual(move.location_id.id, location_loss.id)
# There should be no quant in the stock location
self.env['stock.quant']._quant_tasks()
quants = self.env['stock.quant'].search([('product_id', '=', productA.id), ('location_id', '=', stock_location.id)])
self.assertEqual(sum(quants.mapped('quantity')), 0)
# There should be one quant in the inventory loss location
quant = self.env['stock.quant'].search([('product_id', '=', productA.id), ('location_id', '=', location_loss.id)])
self.assertEqual(len(quant), 1)
def test_resupply_route(self):
""" Simulate a resupply chain between warehouses.
Stock -> transit -> Dist. -> transit -> Shop -> Customer
Create the move from Shop to Customer and ensure that all the pull
rules are triggered in order to complete the move chain to Stock.
"""
warehouse_stock = self.env['stock.warehouse'].create({
'name': 'Stock.',
'code': 'STK',
})
distribution_partner = self.env['res.partner'].create({'name': 'Distribution Center'})
warehouse_distribution = self.env['stock.warehouse'].create({
'name': 'Dist.',
'code': 'DIST',
'resupply_wh_ids': [(6, 0, [warehouse_stock.id])],
'partner_id': distribution_partner.id,
})
warehouse_shop = self.env['stock.warehouse'].create({
'name': 'Shop',
'code': 'SHOP',
'resupply_wh_ids': [(6, 0, [warehouse_distribution.id])]
})
route_stock_to_dist = warehouse_distribution.resupply_route_ids
route_dist_to_shop = warehouse_shop.resupply_route_ids
# Change the procure_method on the pull rules between dist and shop
# warehouses. Since mto and resupply routes are both on product it will
# select one randomly between them and if it select the resupply it is
# 'make to stock' and it will not create the picking between stock and
# dist warehouses.
route_dist_to_shop.rule_ids.write({'procure_method': 'make_to_order'})
product = self.env['product.product'].create({
'name': 'Fakir',
'type': 'product',
'route_ids': [(4, route_id) for route_id in [route_stock_to_dist.id, route_dist_to_shop.id, self.env.ref('stock.route_warehouse0_mto').id]],
})
picking_out = self.env['stock.picking'].create({
'partner_id': self.partner.id,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
'location_id': warehouse_shop.lot_stock_id.id,
'location_dest_id': self.env.ref('stock.stock_location_customers').id,
})
self.env['stock.move'].create({
'name': product.name,
'product_id': product.id,
'product_uom_qty': 1,
'product_uom': product.uom_id.id,
'picking_id': picking_out.id,
'location_id': warehouse_shop.lot_stock_id.id,
'location_dest_id': self.env.ref('stock.stock_location_customers').id,
'warehouse_id': warehouse_shop.id,
'procure_method': 'make_to_order',
})
picking_out.action_confirm()
moves = self.env['stock.move'].search([('product_id', '=', product.id)])
# Shop/Stock -> Customer
# Transit -> Shop/Stock
# Dist/Stock -> Transit
# Transit -> Dist/Stock
# Stock/Stock -> Transit
self.assertEqual(len(moves), 5, 'Invalid moves number.')
self.assertTrue(self.env['stock.move'].search([('location_id', '=', warehouse_stock.lot_stock_id.id)]))
self.assertTrue(self.env['stock.move'].search([('location_dest_id', '=', warehouse_distribution.lot_stock_id.id)]))
self.assertTrue(self.env['stock.move'].search([('location_id', '=', warehouse_distribution.lot_stock_id.id)]))
self.assertTrue(self.env['stock.move'].search([('location_dest_id', '=', warehouse_shop.lot_stock_id.id)]))
self.assertTrue(self.env['stock.move'].search([('location_id', '=', warehouse_shop.lot_stock_id.id)]))
self.assertTrue(self.env['stock.picking'].search([('location_id', '=', self.env.company.internal_transit_location_id.id), ('partner_id', '=', distribution_partner.id)]))
self.assertTrue(self.env['stock.picking'].search([('location_dest_id', '=', self.env.company.internal_transit_location_id.id), ('partner_id', '=', distribution_partner.id)]))
def test_mutiple_resupply_warehouse(self):
""" Simulate the following situation:
- 2 shops with stock are resupply by 2 distinct warehouses
- Shop Namur is resupply by the warehouse stock Namur
- Shop Wavre is resupply by the warehouse stock Wavre
- Simulate 2 moves for the same product but in different shop.
This test ensure that the move are supplied by the correct distribution
warehouse.
"""
customer_location = self.env.ref('stock.stock_location_customers')
warehouse_distribution_wavre = self.env['stock.warehouse'].create({
'name': 'Stock Wavre.',
'code': 'WV',
})
warehouse_shop_wavre = self.env['stock.warehouse'].create({
'name': 'Shop Wavre',
'code': 'SHWV',
'resupply_wh_ids': [(6, 0, [warehouse_distribution_wavre.id])]
})
warehouse_distribution_namur = self.env['stock.warehouse'].create({
'name': 'Stock Namur.',
'code': 'NM',
})
warehouse_shop_namur = self.env['stock.warehouse'].create({
'name': 'Shop Namur',
'code': 'SHNM',
'resupply_wh_ids': [(6, 0, [warehouse_distribution_namur.id])]
})
route_shop_namur = warehouse_shop_namur.resupply_route_ids
route_shop_wavre = warehouse_shop_wavre.resupply_route_ids
# The product contains the 2 resupply routes.
product = self.env['product.product'].create({
'name': 'Fakir',
'type': 'product',
'route_ids': [(4, route_id) for route_id in [route_shop_namur.id, route_shop_wavre.id, self.env.ref('stock.route_warehouse0_mto').id]],
})
# Add 1 quant in each distribution warehouse.
self.env['stock.quant']._update_available_quantity(product, warehouse_distribution_wavre.lot_stock_id, 1.0)
self.env['stock.quant']._update_available_quantity(product, warehouse_distribution_namur.lot_stock_id, 1.0)
# Create the move for the shop Namur. Should create a resupply from
# distribution warehouse Namur.
picking_out_namur = self.env['stock.picking'].create({
'partner_id': self.partner.id,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
'location_id': warehouse_shop_namur.lot_stock_id.id,
'location_dest_id': customer_location.id,
})
self.env['stock.move'].create({
'name': product.name,
'product_id': product.id,
'product_uom_qty': 1,
'product_uom': product.uom_id.id,
'picking_id': picking_out_namur.id,
'location_id': warehouse_shop_namur.lot_stock_id.id,
'location_dest_id': customer_location.id,
'warehouse_id': warehouse_shop_namur.id,
'procure_method': 'make_to_order',
})
picking_out_namur.action_confirm()
# Validate the picking
# Dist. warehouse Namur -> transit Location -> Shop Namur
picking_stock_transit = self.env['stock.picking'].search([('location_id', '=', warehouse_distribution_namur.lot_stock_id.id)])
self.assertTrue(picking_stock_transit)
picking_stock_transit.action_assign()
picking_stock_transit.move_lines[0].quantity_done = 1.0
picking_stock_transit._action_done()
picking_transit_shop_namur = self.env['stock.picking'].search([('location_dest_id', '=', warehouse_shop_namur.lot_stock_id.id)])
self.assertTrue(picking_transit_shop_namur)
picking_transit_shop_namur.action_assign()
picking_transit_shop_namur.move_lines[0].quantity_done = 1.0
picking_transit_shop_namur._action_done()
picking_out_namur.action_assign()
picking_out_namur.move_lines[0].quantity_done = 1.0
picking_out_namur._action_done()
# Check that the correct quantity has been provided to customer
self.assertEqual(self.env['stock.quant']._gather(product, customer_location).quantity, 1)
# Ensure there still no quants in distribution warehouse
self.assertEqual(sum(self.env['stock.quant']._gather(product, warehouse_distribution_namur.lot_stock_id).mapped('quantity')), 0)
# Create the move for the shop Wavre. Should create a resupply from
# distribution warehouse Wavre.
picking_out_wavre = self.env['stock.picking'].create({
'partner_id': self.partner.id,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
'location_id': warehouse_shop_wavre.lot_stock_id.id,
'location_dest_id': customer_location.id,
})
self.env['stock.move'].create({
'name': product.name,
'product_id': product.id,
'product_uom_qty': 1,
'product_uom': product.uom_id.id,
'picking_id': picking_out_wavre.id,
'location_id': warehouse_shop_wavre.lot_stock_id.id,
'location_dest_id': customer_location.id,
'warehouse_id': warehouse_shop_wavre.id,
'procure_method': 'make_to_order',
})
picking_out_wavre.action_confirm()
# Validate the picking
# Dist. warehouse Wavre -> transit Location -> Shop Wavre
picking_stock_transit = self.env['stock.picking'].search([('location_id', '=', warehouse_distribution_wavre.lot_stock_id.id)])
self.assertTrue(picking_stock_transit)
picking_stock_transit.action_assign()
picking_stock_transit.move_lines[0].quantity_done = 1.0
picking_stock_transit._action_done()
picking_transit_shop_wavre = self.env['stock.picking'].search([('location_dest_id', '=', warehouse_shop_wavre.lot_stock_id.id)])
self.assertTrue(picking_transit_shop_wavre)
picking_transit_shop_wavre.action_assign()
picking_transit_shop_wavre.move_lines[0].quantity_done = 1.0
picking_transit_shop_wavre._action_done()
picking_out_wavre.action_assign()
picking_out_wavre.move_lines[0].quantity_done = 1.0
picking_out_wavre._action_done()
# Check that the correct quantity has been provided to customer
self.assertEqual(self.env['stock.quant']._gather(product, customer_location).quantity, 2)
# Ensure there still no quants in distribution warehouse
self.assertEqual(sum(self.env['stock.quant']._gather(product, warehouse_distribution_wavre.lot_stock_id).mapped('quantity')), 0)
def test_noleak(self):
# non-regression test to avoid company_id leaking to other warehouses (see blame)
partner = self.env['res.partner'].create({'name': 'Chicago partner'})
company = self.env['res.company'].create({
'name': 'My Company (Chicago)1',
'currency_id': self.ref('base.USD')
})
self.env['stock.warehouse'].create({
'name': 'Chicago Warehouse2',
'company_id': company.id,
'code': 'Chic2',
'partner_id': partner.id
})
wh = self.env["stock.warehouse"].search([])
assert len(set(wh.mapped("company_id.id"))) > 1
companies_before = wh.mapped(lambda w: (w.id, w.company_id))
# writing on any field should change the company of warehouses
wh.write({"name": "whatever"})
companies_after = wh.mapped(lambda w: (w.id, w.company_id))
self.assertEqual(companies_after, companies_before)
def test_toggle_active_warehouse_1(self):
""" Basic test that create a warehouse with classic configuration.
Archive it and check that locations, picking types, routes, rules are
correclty active or archive.
"""
wh = Form(self.env['stock.warehouse'])
wh.name = "The attic of Willy"
wh.code = "WIL"
warehouse = wh.save()
custom_location = Form(self.env['stock.location'])
custom_location.name = "A Trunk"
custom_location.location_id = warehouse.lot_stock_id
custom_location = custom_location.save()
# Archive warehouse
warehouse.toggle_active()
# Global rule
self.assertFalse(warehouse.mto_pull_id.active)
# Route
self.assertFalse(warehouse.reception_route_id.active)
self.assertFalse(warehouse.delivery_route_id.active)
# Location
self.assertFalse(warehouse.lot_stock_id.active)
self.assertFalse(warehouse.wh_input_stock_loc_id.active)
self.assertFalse(warehouse.wh_qc_stock_loc_id.active)
self.assertFalse(warehouse.wh_output_stock_loc_id.active)
self.assertFalse(warehouse.wh_pack_stock_loc_id.active)
self.assertFalse(custom_location.active)
# Picking Type
self.assertFalse(warehouse.in_type_id.active)
self.assertFalse(warehouse.in_type_id.show_operations)
self.assertFalse(warehouse.out_type_id.active)
self.assertFalse(warehouse.int_type_id.active)
self.assertFalse(warehouse.pick_type_id.active)
self.assertFalse(warehouse.pack_type_id.active)
# Active warehouse
warehouse.toggle_active()
# Global rule
self.assertTrue(warehouse.mto_pull_id.active)
# Route
self.assertTrue(warehouse.reception_route_id.active)
self.assertTrue(warehouse.delivery_route_id.active)
# Location
self.assertTrue(warehouse.lot_stock_id.active)
self.assertFalse(warehouse.wh_input_stock_loc_id.active)
self.assertFalse(warehouse.wh_qc_stock_loc_id.active)
self.assertFalse(warehouse.wh_output_stock_loc_id.active)
self.assertFalse(warehouse.wh_pack_stock_loc_id.active)
self.assertTrue(custom_location.active)
# Picking Type
self.assertTrue(warehouse.in_type_id.active)
self.assertFalse(warehouse.in_type_id.show_operations)
self.assertTrue(warehouse.out_type_id.active)
self.assertTrue(warehouse.int_type_id.active)
self.assertFalse(warehouse.pick_type_id.active)
self.assertFalse(warehouse.pack_type_id.active)
def test_toggle_active_warehouse_2(self):
wh = Form(self.env['stock.warehouse'])
wh.name = "The attic of Willy"
wh.code = "WIL"
wh.reception_steps = "two_steps"
wh.delivery_steps = "pick_pack_ship"
warehouse = wh.save()
warehouse.resupply_wh_ids = [(6, 0, [self.warehouse_1.id])]
custom_location = Form(self.env['stock.location'])
custom_location.name = "A Trunk"
custom_location.location_id = warehouse.lot_stock_id
custom_location = custom_location.save()
# Add a warehouse on the route.
warehouse.reception_route_id.write({
'warehouse_ids': [(4, self.warehouse_1.id)]
})
route = Form(self.env['stock.location.route'])
route.name = "Stair"
route = route.save()
route.warehouse_ids = [(6, 0, [warehouse.id, self.warehouse_1.id])]
# Pre archive a location and a route
warehouse.delivery_route_id.toggle_active()
warehouse.wh_pack_stock_loc_id.toggle_active()
# Archive warehouse
warehouse.toggle_active()
# Global rule
self.assertFalse(warehouse.mto_pull_id.active)
# Route
self.assertTrue(warehouse.reception_route_id.active)
self.assertFalse(warehouse.delivery_route_id.active)
self.assertTrue(route.active)
# Location
self.assertFalse(warehouse.lot_stock_id.active)
self.assertFalse(warehouse.wh_input_stock_loc_id.active)
self.assertFalse(warehouse.wh_qc_stock_loc_id.active)
self.assertFalse(warehouse.wh_output_stock_loc_id.active)
self.assertFalse(warehouse.wh_pack_stock_loc_id.active)
self.assertFalse(custom_location.active)
# Picking Type
self.assertFalse(warehouse.in_type_id.active)
self.assertFalse(warehouse.out_type_id.active)
self.assertFalse(warehouse.int_type_id.active)
self.assertFalse(warehouse.pick_type_id.active)
self.assertFalse(warehouse.pack_type_id.active)
# Active warehouse
warehouse.toggle_active()
# Global rule
self.assertTrue(warehouse.mto_pull_id.active)
# Route
self.assertTrue(warehouse.reception_route_id.active)
self.assertTrue(warehouse.delivery_route_id.active)
# Location
self.assertTrue(warehouse.lot_stock_id.active)
self.assertTrue(warehouse.wh_input_stock_loc_id.active)
self.assertFalse(warehouse.wh_qc_stock_loc_id.active)
self.assertTrue(warehouse.wh_output_stock_loc_id.active)
self.assertTrue(warehouse.wh_pack_stock_loc_id.active)
self.assertTrue(custom_location.active)
# Picking Type
self.assertTrue(warehouse.in_type_id.active)
self.assertTrue(warehouse.out_type_id.active)
self.assertTrue(warehouse.int_type_id.active)
self.assertTrue(warehouse.pick_type_id.active)
self.assertTrue(warehouse.pack_type_id.active)
def test_edit_warehouse_1(self):
wh = Form(self.env['stock.warehouse'])
wh.name = "Chicago"
wh.code = "chic"
warehouse = wh.save()
self.assertEqual(warehouse.int_type_id.barcode, 'CHIC-INTERNAL')
self.assertEqual(warehouse.int_type_id.sequence_id.prefix, 'chic/INT/')
wh = Form(warehouse)
wh.code = 'CH'
wh.save()
self.assertEqual(warehouse.int_type_id.barcode, 'CH-INTERNAL')
self.assertEqual(warehouse.int_type_id.sequence_id.prefix, 'CH/INT/')
| 46.742038
| 29,354
|
2,515
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo.addons.stock.tests.common import TestStockCommon
class TestReturnPicking(TestStockCommon):
def test_stock_return_picking_line_creation(self):
StockReturnObj = self.env['stock.return.picking']
picking_out = self.PickingObj.create({
'picking_type_id': self.picking_type_out,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
move_1 = self.MoveObj.create({
'name': self.UnitA.name,
'product_id': self.UnitA.id,
'product_uom_qty': 2,
'product_uom': self.uom_unit.id,
'picking_id': picking_out.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
move_2 = self.MoveObj.create({
'name': self.UnitA.name,
'product_id': self.UnitA.id,
'product_uom_qty': 1,
'product_uom': self.uom_dozen.id,
'picking_id': picking_out.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location})
picking_out.action_confirm()
picking_out.action_assign()
move_1.quantity_done = 2
move_2.quantity_done = 1
picking_out.button_validate()
return_wizard = StockReturnObj.with_context(active_id=picking_out.id, active_ids=picking_out.ids).create({
'location_id': self.stock_location,
'picking_id': picking_out.id,
})
return_wizard._onchange_picking_id()
ReturnPickingLineObj = self.env['stock.return.picking.line']
# Check return line of uom_unit move
return_line = ReturnPickingLineObj.search([('move_id', '=', move_1.id), ('wizard_id.picking_id', '=', picking_out.id)], limit=1)
self.assertEqual(return_line.product_id.id, self.UnitA.id, 'Return line should have exact same product as outgoing move')
self.assertEqual(return_line.uom_id.id, self.uom_unit.id, 'Return line should have exact same uom as product uom')
# Check return line of uom_dozen move
return_line = ReturnPickingLineObj.search([('move_id', '=', move_2.id), ('wizard_id.picking_id', '=', picking_out.id)], limit=1)
self.assertEqual(return_line.product_id.id, self.UnitA.id, 'Return line should have exact same product as outgoing move')
self.assertEqual(return_line.uom_id.id, self.uom_unit.id, 'Return line should have exact same uom as product uom')
| 50.3
| 2,515
|
71,868
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests import Form
from odoo.tests.common import TransactionCase
from odoo.tools import float_round
from odoo.exceptions import UserError
class TestPackingCommon(TransactionCase):
@classmethod
def setUpClass(cls):
super(TestPackingCommon, cls).setUpClass()
cls.stock_location = cls.env.ref('stock.stock_location_stock')
cls.warehouse = cls.env['stock.warehouse'].search([('lot_stock_id', '=', cls.stock_location.id)], limit=1)
cls.warehouse.write({'delivery_steps': 'pick_pack_ship'})
cls.warehouse.int_type_id.reservation_method = 'manual'
cls.pack_location = cls.warehouse.wh_pack_stock_loc_id
cls.ship_location = cls.warehouse.wh_output_stock_loc_id
cls.customer_location = cls.env.ref('stock.stock_location_customers')
cls.productA = cls.env['product.product'].create({'name': 'Product A', 'type': 'product'})
cls.productB = cls.env['product.product'].create({'name': 'Product B', 'type': 'product'})
class TestPacking(TestPackingCommon):
def test_put_in_pack(self):
""" In a pick pack ship scenario, create two packs in pick and check that
they are correctly recognised and handled by the pack and ship picking.
Along this test, we'll use action_toggle_processed to process a pack
from the entire_package_ids one2many and we'll directly fill the move
lines, the latter is the behavior when the user did not enable the display
of entire packs on the picking type.
"""
self.env['stock.quant']._update_available_quantity(self.productA, self.stock_location, 20.0)
self.env['stock.quant']._update_available_quantity(self.productB, self.stock_location, 20.0)
ship_move_a = self.env['stock.move'].create({
'name': 'The ship move',
'product_id': self.productA.id,
'product_uom_qty': 5.0,
'product_uom': self.productA.uom_id.id,
'location_id': self.ship_location.id,
'location_dest_id': self.customer_location.id,
'warehouse_id': self.warehouse.id,
'picking_type_id': self.warehouse.out_type_id.id,
'procure_method': 'make_to_order',
'state': 'draft',
})
ship_move_b = self.env['stock.move'].create({
'name': 'The ship move',
'product_id': self.productB.id,
'product_uom_qty': 5.0,
'product_uom': self.productB.uom_id.id,
'location_id': self.ship_location.id,
'location_dest_id': self.customer_location.id,
'warehouse_id': self.warehouse.id,
'picking_type_id': self.warehouse.out_type_id.id,
'procure_method': 'make_to_order',
'state': 'draft',
})
ship_move_a._assign_picking()
ship_move_b._assign_picking()
ship_move_a._action_confirm()
ship_move_b._action_confirm()
pack_move_a = ship_move_a.move_orig_ids[0]
pick_move_a = pack_move_a.move_orig_ids[0]
pick_picking = pick_move_a.picking_id
packing_picking = pack_move_a.picking_id
shipping_picking = ship_move_a.picking_id
pick_picking.picking_type_id.show_entire_packs = True
packing_picking.picking_type_id.show_entire_packs = True
shipping_picking.picking_type_id.show_entire_packs = True
pick_picking.action_assign()
self.assertEqual(len(pick_picking.move_ids_without_package), 2)
pick_picking.move_line_ids.filtered(lambda ml: ml.product_id == self.productA).qty_done = 1.0
pick_picking.move_line_ids.filtered(lambda ml: ml.product_id == self.productB).qty_done = 2.0
first_pack = pick_picking.action_put_in_pack()
self.assertEqual(len(pick_picking.package_level_ids), 1, 'Put some products in pack should create a package_level')
self.assertEqual(pick_picking.package_level_ids[0].state, 'new', 'A new pack should be in state "new"')
pick_picking.move_line_ids.filtered(lambda ml: ml.product_id == self.productA and ml.qty_done == 0.0).qty_done = 4.0
pick_picking.move_line_ids.filtered(lambda ml: ml.product_id == self.productB and ml.qty_done == 0.0).qty_done = 3.0
second_pack = pick_picking.action_put_in_pack()
self.assertEqual(len(pick_picking.move_ids_without_package), 0)
self.assertEqual(len(packing_picking.move_ids_without_package), 2)
pick_picking.button_validate()
self.assertEqual(len(packing_picking.move_ids_without_package), 0)
self.assertEqual(len(first_pack.quant_ids), 2)
self.assertEqual(len(second_pack.quant_ids), 2)
packing_picking.action_assign()
self.assertEqual(len(packing_picking.package_level_ids), 2, 'Two package levels must be created after assigning picking')
packing_picking.package_level_ids.write({'is_done': True})
packing_picking._action_done()
def test_pick_a_pack_confirm(self):
pack = self.env['stock.quant.package'].create({'name': 'The pack to pick'})
self.env['stock.quant']._update_available_quantity(self.productA, self.stock_location, 20.0, package_id=pack)
picking = self.env['stock.picking'].create({
'picking_type_id': self.warehouse.int_type_id.id,
'location_id': self.stock_location.id,
'location_dest_id': self.stock_location.id,
'state': 'draft',
})
picking.picking_type_id.show_entire_packs = True
package_level = self.env['stock.package_level'].create({
'package_id': pack.id,
'picking_id': picking.id,
'location_dest_id': self.stock_location.id,
'company_id': picking.company_id.id,
})
self.assertEqual(package_level.state, 'draft',
'The package_level should be in draft as it has no moves, move lines and is not confirmed')
picking.action_confirm()
self.assertEqual(len(picking.move_ids_without_package), 0)
self.assertEqual(len(picking.move_lines), 1,
'One move should be created when the package_level has been confirmed')
self.assertEqual(len(package_level.move_ids), 1,
'The move should be in the package level')
self.assertEqual(package_level.state, 'confirmed',
'The package level must be state confirmed when picking is confirmed')
picking.action_assign()
self.assertEqual(len(picking.move_lines), 1,
'You still have only one move when the picking is assigned')
self.assertEqual(len(picking.move_lines.move_line_ids), 1,
'The move should have one move line which is the reservation')
self.assertEqual(picking.move_line_ids.package_level_id.id, package_level.id,
'The move line created should be linked to the package level')
self.assertEqual(picking.move_line_ids.package_id.id, pack.id,
'The move line must have been reserved on the package of the package_level')
self.assertEqual(picking.move_line_ids.result_package_id.id, pack.id,
'The move line must have the same package as result package')
self.assertEqual(package_level.state, 'assigned', 'The package level must be in state assigned')
package_level.write({'is_done': True})
self.assertEqual(len(package_level.move_line_ids), 1,
'The package level should still keep one move line after have been set to "done"')
self.assertEqual(package_level.move_line_ids[0].qty_done, 20.0,
'All quantity in package must be procesed in move line')
picking.button_validate()
self.assertEqual(len(picking.move_lines), 1,
'You still have only one move when the picking is assigned')
self.assertEqual(len(picking.move_lines.move_line_ids), 1,
'The move should have one move line which is the reservation')
self.assertEqual(package_level.state, 'done', 'The package level must be in state done')
self.assertEqual(pack.location_id.id, picking.location_dest_id.id,
'The quant package must be in the destination location')
self.assertEqual(pack.quant_ids[0].location_id.id, picking.location_dest_id.id,
'The quant must be in the destination location')
def test_pick_a_pack_cancel(self):
"""Cancel a reserved operation with a not-done package level (is_done=False)."""
pack = self.env['stock.quant.package'].create({'name': 'The pack to pick'})
self.env['stock.quant']._update_available_quantity(self.productA, self.stock_location, 20.0, package_id=pack)
picking = self.env['stock.picking'].create({
'picking_type_id': self.warehouse.int_type_id.id,
'location_id': self.stock_location.id,
'location_dest_id': self.stock_location.id,
'state': 'draft',
})
picking.picking_type_id.show_entire_packs = True
package_level = self.env['stock.package_level'].create({
'package_id': pack.id,
'picking_id': picking.id,
'location_dest_id': self.stock_location.id,
'company_id': picking.company_id.id,
})
picking.action_confirm()
picking.action_assign()
self.assertEqual(package_level.state, 'assigned')
self.assertTrue(package_level.move_line_ids)
picking.action_cancel()
self.assertEqual(package_level.state, 'cancel')
self.assertFalse(package_level.move_line_ids)
def test_pick_a_pack_cancel_is_done(self):
"""Cancel a reserved operation with a package level that is done (is_done=True)."""
pack = self.env['stock.quant.package'].create({'name': 'The pack to pick'})
self.env['stock.quant']._update_available_quantity(self.productA, self.stock_location, 20.0, package_id=pack)
picking = self.env['stock.picking'].create({
'picking_type_id': self.warehouse.int_type_id.id,
'location_id': self.stock_location.id,
'location_dest_id': self.stock_location.id,
'state': 'draft',
})
picking.picking_type_id.show_entire_packs = True
package_level = self.env['stock.package_level'].create({
'package_id': pack.id,
'picking_id': picking.id,
'location_dest_id': self.stock_location.id,
'company_id': picking.company_id.id,
})
picking.action_confirm()
picking.action_assign()
self.assertEqual(package_level.state, 'assigned')
self.assertTrue(package_level.move_line_ids)
# By setting the package_level as 'done', all related lines will be kept
# when cancelling the transfer
package_level.is_done = True
picking.action_cancel()
self.assertEqual(picking.state, 'cancel')
self.assertEqual(package_level.state, 'cancel')
self.assertTrue(package_level.move_line_ids)
self.assertTrue(
all(package_level.move_line_ids.mapped(lambda l: l.state == 'cancel'))
)
def test_multi_pack_reservation(self):
""" When we move entire packages, it is possible to have a multiple times
the same package in package level list, we make sure that only one is reserved,
and that the location_id of the package is the one where the package is once it
is reserved.
"""
pack = self.env['stock.quant.package'].create({'name': 'The pack to pick'})
shelf1_location = self.env['stock.location'].create({
'name': 'shelf1',
'usage': 'internal',
'location_id': self.stock_location.id,
})
self.env['stock.quant']._update_available_quantity(self.productA, shelf1_location, 20.0, package_id=pack)
picking = self.env['stock.picking'].create({
'picking_type_id': self.warehouse.int_type_id.id,
'location_id': self.stock_location.id,
'location_dest_id': self.stock_location.id,
'state': 'draft',
})
package_level = self.env['stock.package_level'].create({
'package_id': pack.id,
'picking_id': picking.id,
'location_dest_id': self.stock_location.id,
'company_id': picking.company_id.id,
})
package_level = self.env['stock.package_level'].create({
'package_id': pack.id,
'picking_id': picking.id,
'location_dest_id': self.stock_location.id,
'company_id': picking.company_id.id,
})
picking.action_confirm()
self.assertEqual(picking.package_level_ids.mapped('location_id.id'), [shelf1_location.id],
'The package levels should still in the same location after confirmation.')
picking.action_assign()
package_level_reserved = picking.package_level_ids.filtered(lambda pl: pl.state == 'assigned')
package_level_confirmed = picking.package_level_ids.filtered(lambda pl: pl.state == 'confirmed')
self.assertEqual(package_level_reserved.location_id.id, shelf1_location.id, 'The reserved package level must be reserved in shelf1')
self.assertEqual(package_level_confirmed.location_id.id, shelf1_location.id, 'The not reserved package should keep its location')
picking.do_unreserve()
self.assertEqual(picking.package_level_ids.mapped('location_id.id'), [shelf1_location.id],
'The package levels should have back the original location.')
picking.package_level_ids.write({'is_done': True})
picking.action_assign()
package_level_reserved = picking.package_level_ids.filtered(lambda pl: pl.state == 'assigned')
package_level_confirmed = picking.package_level_ids.filtered(lambda pl: pl.state == 'confirmed')
self.assertEqual(package_level_reserved.location_id.id, shelf1_location.id, 'The reserved package level must be reserved in shelf1')
self.assertEqual(package_level_confirmed.location_id.id, shelf1_location.id, 'The not reserved package should keep its location')
self.assertEqual(picking.package_level_ids.mapped('is_done'), [True, True], 'Both package should still done')
def test_put_in_pack_to_different_location(self):
""" Hitting 'Put in pack' button while some move lines go to different
location should trigger a wizard. This wizard applies the same destination
location to all the move lines
"""
self.warehouse.in_type_id.show_reserved = True
shelf1_location = self.env['stock.location'].create({
'name': 'shelf1',
'usage': 'internal',
'location_id': self.stock_location.id,
})
shelf2_location = self.env['stock.location'].create({
'name': 'shelf2',
'usage': 'internal',
'location_id': self.stock_location.id,
})
picking = self.env['stock.picking'].create({
'picking_type_id': self.warehouse.in_type_id.id,
'location_id': self.customer_location.id,
'location_dest_id': self.stock_location.id,
'state': 'draft',
})
ship_move_a = self.env['stock.move'].create({
'name': 'move 1',
'product_id': self.productA.id,
'product_uom_qty': 5.0,
'product_uom': self.productA.uom_id.id,
'location_id': self.customer_location.id,
'location_dest_id': shelf1_location.id,
'picking_id': picking.id,
'state': 'draft',
})
picking.action_confirm()
picking.action_assign()
picking.move_line_ids.filtered(lambda ml: ml.product_id == self.productA).qty_done = 5.0
picking.action_put_in_pack()
pack1 = self.env['stock.quant.package'].search([])[-1]
picking.write({
'move_line_ids': [(0, 0, {
'product_id': self.productB.id,
'product_uom_qty': 7.0,
'qty_done': 7.0,
'product_uom_id': self.productB.uom_id.id,
'location_id': self.customer_location.id,
'location_dest_id': shelf2_location.id,
'picking_id': picking.id,
'state': 'confirmed',
})]
})
picking.write({
'move_line_ids': [(0, 0, {
'product_id': self.productA.id,
'product_uom_qty': 5.0,
'qty_done': 5.0,
'product_uom_id': self.productA.uom_id.id,
'location_id': self.customer_location.id,
'location_dest_id': shelf1_location.id,
'picking_id': picking.id,
'state': 'confirmed',
})]
})
wizard_values = picking.action_put_in_pack()
wizard = self.env[(wizard_values.get('res_model'))].browse(wizard_values.get('res_id'))
wizard.location_dest_id = shelf2_location.id
wizard.action_done()
picking._action_done()
pack2 = self.env['stock.quant.package'].search([])[-1]
self.assertEqual(pack2.location_id.id, shelf2_location.id, 'The package must be stored in shelf2')
self.assertEqual(pack1.location_id.id, shelf1_location.id, 'The package must be stored in shelf1')
qp1 = pack2.quant_ids[0]
qp2 = pack2.quant_ids[1]
self.assertEqual(qp1.quantity + qp2.quantity, 12, 'The quant has not the good quantity')
def test_move_picking_with_package(self):
"""
355.4 rounded with 0.01 precision is 355.40000000000003.
check that nonetheless, moving a picking is accepted
"""
self.assertEqual(self.productA.uom_id.rounding, 0.01)
self.assertEqual(
float_round(355.4, precision_rounding=self.productA.uom_id.rounding),
355.40000000000003,
)
location_dict = {
'location_id': self.stock_location.id,
}
quant = self.env['stock.quant'].create({
**location_dict,
**{'product_id': self.productA.id, 'quantity': 355.4}, # important number
})
package = self.env['stock.quant.package'].create({
**location_dict, **{'quant_ids': [(6, 0, [quant.id])]},
})
location_dict.update({
'state': 'draft',
'location_dest_id': self.ship_location.id,
})
move = self.env['stock.move'].create({
**location_dict,
**{
'name': "XXX",
'product_id': self.productA.id,
'product_uom': self.productA.uom_id.id,
'product_uom_qty': 355.40000000000003, # other number
}})
picking = self.env['stock.picking'].create({
**location_dict,
**{
'picking_type_id': self.warehouse.in_type_id.id,
'move_lines': [(6, 0, [move.id])],
}})
picking.action_confirm()
picking.action_assign()
move.quantity_done = move.reserved_availability
picking._action_done()
# if we managed to get there, there was not any exception
# complaining that 355.4 is not 355.40000000000003. Good job!
def test_move_picking_with_package_2(self):
""" Generate two move lines going to different location in the same
package.
"""
shelf1 = self.env['stock.location'].create({
'location_id': self.stock_location.id,
'name': 'Shelf 1',
})
shelf2 = self.env['stock.location'].create({
'location_id': self.stock_location.id,
'name': 'Shelf 2',
})
package = self.env['stock.quant.package'].create({})
picking = self.env['stock.picking'].create({
'picking_type_id': self.warehouse.in_type_id.id,
'location_id': self.stock_location.id,
'location_dest_id': self.stock_location.id,
'state': 'draft',
})
self.env['stock.move.line'].create({
'location_id': self.stock_location.id,
'location_dest_id': shelf1.id,
'product_id': self.productA.id,
'product_uom_id': self.productA.uom_id.id,
'qty_done': 5.0,
'picking_id': picking.id,
'result_package_id': package.id,
})
self.env['stock.move.line'].create({
'location_id': self.stock_location.id,
'location_dest_id': shelf2.id,
'product_id': self.productA.id,
'product_uom_id': self.productA.uom_id.id,
'qty_done': 5.0,
'picking_id': picking.id,
'result_package_id': package.id,
})
picking.action_confirm()
with self.assertRaises(UserError):
picking._action_done()
def test_pack_in_receipt_two_step_single_putway(self):
""" Checks all works right in the following specific corner case:
* For a two-step receipt, receives two products using the same putaway
* Puts these products in a package then valid the receipt.
* Cancels the automatically generated internal transfer then create a new one.
* In this internal transfer, adds the package then valid it.
"""
grp_multi_loc = self.env.ref('stock.group_stock_multi_locations')
grp_multi_step_rule = self.env.ref('stock.group_adv_location')
grp_pack = self.env.ref('stock.group_tracking_lot')
self.env.user.write({'groups_id': [(3, grp_multi_loc.id)]})
self.env.user.write({'groups_id': [(3, grp_multi_step_rule.id)]})
self.env.user.write({'groups_id': [(3, grp_pack.id)]})
self.warehouse.reception_steps = 'two_steps'
# Settings of receipt.
self.warehouse.in_type_id.show_operations = True
self.warehouse.in_type_id.show_entire_packs = True
self.warehouse.in_type_id.show_reserved = True
# Settings of internal transfer.
self.warehouse.int_type_id.show_operations = True
self.warehouse.int_type_id.show_entire_packs = True
self.warehouse.int_type_id.show_reserved = True
# Creates two new locations for putaway.
location_form = Form(self.env['stock.location'])
location_form.name = 'Shelf A'
location_form.location_id = self.stock_location
loc_shelf_A = location_form.save()
# Creates a new putaway rule for productA and productB.
putaway_A = self.env['stock.putaway.rule'].create({
'product_id': self.productA.id,
'location_in_id': self.stock_location.id,
'location_out_id': loc_shelf_A.id,
})
putaway_B = self.env['stock.putaway.rule'].create({
'product_id': self.productB.id,
'location_in_id': self.stock_location.id,
'location_out_id': loc_shelf_A.id,
})
self.stock_location.putaway_rule_ids = [(4, putaway_A.id, 0), (4, putaway_B.id, 0)]
# Create a new receipt with the two products.
receipt_form = Form(self.env['stock.picking'])
receipt_form.picking_type_id = self.warehouse.in_type_id
# Add 2 lines
with receipt_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.productA
move_line.product_uom_qty = 1
with receipt_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.productB
move_line.product_uom_qty = 1
receipt = receipt_form.save()
receipt.action_confirm()
# Adds quantities then packs them and valids the receipt.
receipt_form = Form(receipt)
with receipt_form.move_line_ids_without_package.edit(0) as move_line:
move_line.qty_done = 1
with receipt_form.move_line_ids_without_package.edit(1) as move_line:
move_line.qty_done = 1
receipt = receipt_form.save()
receipt.action_put_in_pack()
receipt.button_validate()
receipt_package = receipt.package_level_ids_details[0]
self.assertEqual(receipt_package.location_dest_id.id, receipt.location_dest_id.id)
self.assertEqual(
receipt_package.move_line_ids[0].location_dest_id.id,
receipt.location_dest_id.id)
self.assertEqual(
receipt_package.move_line_ids[1].location_dest_id.id,
receipt.location_dest_id.id)
# Checks an internal transfer was created following the validation of the receipt.
internal_transfer = self.env['stock.picking'].search([
('picking_type_id', '=', self.warehouse.int_type_id.id)
], order='id desc', limit=1)
self.assertEqual(internal_transfer.origin, receipt.name)
self.assertEqual(
len(internal_transfer.package_level_ids_details), 1)
internal_package = internal_transfer.package_level_ids_details[0]
self.assertNotEqual(
internal_package.location_dest_id.id,
internal_transfer.location_dest_id.id)
self.assertEqual(
internal_package.location_dest_id.id,
putaway_A.location_out_id.id,
"The package destination location must be the one from the putaway.")
self.assertEqual(
internal_package.move_line_ids[0].location_dest_id.id,
putaway_A.location_out_id.id,
"The move line destination location must be the one from the putaway.")
self.assertEqual(
internal_package.move_line_ids[1].location_dest_id.id,
putaway_A.location_out_id.id,
"The move line destination location must be the one from the putaway.")
# Cancels the internal transfer and creates a new one.
internal_transfer.action_cancel()
internal_form = Form(self.env['stock.picking'])
internal_form.picking_type_id = self.warehouse.int_type_id
internal_form.location_id = self.warehouse.wh_input_stock_loc_id
with internal_form.package_level_ids_details.new() as pack_line:
pack_line.package_id = receipt_package.package_id
internal_transfer = internal_form.save()
# Checks the package fields have been correctly set.
internal_package = internal_transfer.package_level_ids_details[0]
self.assertEqual(
internal_package.location_dest_id.id,
internal_transfer.location_dest_id.id)
internal_transfer.action_assign()
self.assertNotEqual(
internal_package.location_dest_id.id,
internal_transfer.location_dest_id.id)
self.assertEqual(
internal_package.location_dest_id.id,
putaway_A.location_out_id.id,
"The package destination location must be the one from the putaway.")
self.assertEqual(
internal_package.move_line_ids[0].location_dest_id.id,
putaway_A.location_out_id.id,
"The move line destination location must be the one from the putaway.")
self.assertEqual(
internal_package.move_line_ids[1].location_dest_id.id,
putaway_A.location_out_id.id,
"The move line destination location must be the one from the putaway.")
internal_transfer.button_validate()
def test_pack_in_receipt_two_step_multi_putaway(self):
""" Checks all works right in the following specific corner case:
* For a two-step receipt, receives two products using two putaways
targeting different locations.
* Puts these products in a package then valid the receipt.
* Cancels the automatically generated internal transfer then create a new one.
* In this internal transfer, adds the package then valid it.
"""
grp_multi_loc = self.env.ref('stock.group_stock_multi_locations')
grp_multi_step_rule = self.env.ref('stock.group_adv_location')
grp_pack = self.env.ref('stock.group_tracking_lot')
self.env.user.write({'groups_id': [(3, grp_multi_loc.id)]})
self.env.user.write({'groups_id': [(3, grp_multi_step_rule.id)]})
self.env.user.write({'groups_id': [(3, grp_pack.id)]})
self.warehouse.reception_steps = 'two_steps'
# Settings of receipt.
self.warehouse.in_type_id.show_operations = True
self.warehouse.in_type_id.show_entire_packs = True
self.warehouse.in_type_id.show_reserved = True
# Settings of internal transfer.
self.warehouse.int_type_id.show_operations = True
self.warehouse.int_type_id.show_entire_packs = True
self.warehouse.int_type_id.show_reserved = True
# Creates two new locations for putaway.
location_form = Form(self.env['stock.location'])
location_form.name = 'Shelf A'
location_form.location_id = self.stock_location
loc_shelf_A = location_form.save()
location_form = Form(self.env['stock.location'])
location_form.name = 'Shelf B'
location_form.location_id = self.stock_location
loc_shelf_B = location_form.save()
# Creates a new putaway rule for productA and productB.
putaway_A = self.env['stock.putaway.rule'].create({
'product_id': self.productA.id,
'location_in_id': self.stock_location.id,
'location_out_id': loc_shelf_A.id,
})
putaway_B = self.env['stock.putaway.rule'].create({
'product_id': self.productB.id,
'location_in_id': self.stock_location.id,
'location_out_id': loc_shelf_B.id,
})
self.stock_location.putaway_rule_ids = [(4, putaway_A.id, 0), (4, putaway_B.id, 0)]
# location_form = Form(self.stock_location)
# location_form.putaway_rule_ids = [(4, putaway_A.id, 0), (4, putaway_B.id, 0), ],
# self.stock_location = location_form.save()
# Create a new receipt with the two products.
receipt_form = Form(self.env['stock.picking'])
receipt_form.picking_type_id = self.warehouse.in_type_id
# Add 2 lines
with receipt_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.productA
move_line.product_uom_qty = 1
with receipt_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.productB
move_line.product_uom_qty = 1
receipt = receipt_form.save()
receipt.action_confirm()
# Adds quantities then packs them and valids the receipt.
receipt_form = Form(receipt)
with receipt_form.move_line_ids_without_package.edit(0) as move_line:
move_line.qty_done = 1
with receipt_form.move_line_ids_without_package.edit(1) as move_line:
move_line.qty_done = 1
receipt = receipt_form.save()
receipt.action_put_in_pack()
receipt.button_validate()
receipt_package = receipt.package_level_ids_details[0]
self.assertEqual(receipt_package.location_dest_id.id, receipt.location_dest_id.id)
self.assertEqual(
receipt_package.move_line_ids[0].location_dest_id.id,
receipt.location_dest_id.id)
self.assertEqual(
receipt_package.move_line_ids[1].location_dest_id.id,
receipt.location_dest_id.id)
# Checks an internal transfer was created following the validation of the receipt.
internal_transfer = self.env['stock.picking'].search([
('picking_type_id', '=', self.warehouse.int_type_id.id)
], order='id desc', limit=1)
self.assertEqual(internal_transfer.origin, receipt.name)
self.assertEqual(
len(internal_transfer.package_level_ids_details), 1)
internal_package = internal_transfer.package_level_ids_details[0]
self.assertEqual(
internal_package.location_dest_id.id,
internal_transfer.location_dest_id.id)
self.assertNotEqual(
internal_package.location_dest_id.id,
putaway_A.location_out_id.id,
"The package destination location must be the one from the picking.")
self.assertNotEqual(
internal_package.move_line_ids[0].location_dest_id.id,
putaway_A.location_out_id.id,
"The move line destination location must be the one from the picking.")
self.assertNotEqual(
internal_package.move_line_ids[1].location_dest_id.id,
putaway_A.location_out_id.id,
"The move line destination location must be the one from the picking.")
# Cancels the internal transfer and creates a new one.
internal_transfer.action_cancel()
internal_form = Form(self.env['stock.picking'])
internal_form.picking_type_id = self.warehouse.int_type_id
internal_form.location_id = self.warehouse.wh_input_stock_loc_id
with internal_form.package_level_ids_details.new() as pack_line:
pack_line.package_id = receipt_package.package_id
internal_transfer = internal_form.save()
# Checks the package fields have been correctly set.
internal_package = internal_transfer.package_level_ids_details[0]
self.assertEqual(
internal_package.location_dest_id.id,
internal_transfer.location_dest_id.id)
internal_transfer.action_assign()
self.assertEqual(
internal_package.location_dest_id.id,
internal_transfer.location_dest_id.id)
self.assertNotEqual(
internal_package.location_dest_id.id,
putaway_A.location_out_id.id,
"The package destination location must be the one from the picking.")
self.assertNotEqual(
internal_package.move_line_ids[0].location_dest_id.id,
putaway_A.location_out_id.id,
"The move line destination location must be the one from the picking.")
self.assertNotEqual(
internal_package.move_line_ids[1].location_dest_id.id,
putaway_A.location_out_id.id,
"The move line destination location must be the one from the picking.")
internal_transfer.button_validate()
def test_partial_put_in_pack(self):
""" Create a simple move in a delivery. Reserve the quantity but set as quantity done only a part.
Call Put In Pack button. """
self.productA.tracking = 'lot'
lot1 = self.env['stock.production.lot'].create({
'product_id': self.productA.id,
'name': '00001',
'company_id': self.warehouse.company_id.id
})
self.env['stock.quant']._update_available_quantity(self.productA, self.stock_location, 20.0, lot_id=lot1)
ship_move_a = self.env['stock.move'].create({
'name': 'The ship move',
'product_id': self.productA.id,
'product_uom_qty': 5.0,
'product_uom': self.productA.uom_id.id,
'location_id': self.ship_location.id,
'location_dest_id': self.customer_location.id,
'warehouse_id': self.warehouse.id,
'picking_type_id': self.warehouse.out_type_id.id,
'procure_method': 'make_to_order',
'state': 'draft',
})
ship_move_a._assign_picking()
ship_move_a._action_confirm()
pack_move_a = ship_move_a.move_orig_ids[0]
pick_move_a = pack_move_a.move_orig_ids[0]
pick_picking = pick_move_a.picking_id
pick_picking.picking_type_id.show_entire_packs = True
pick_picking.action_assign()
pick_picking.move_line_ids.qty_done = 3
first_pack = pick_picking.action_put_in_pack()
def test_action_assign_package_level(self):
"""calling _action_assign on move does not erase lines' "result_package_id"
At the end of the method ``StockMove._action_assign()``, the method
``StockPicking._check_entire_pack()`` is called. This method compares
the move lines with the quants of their source package, and if the entire
package is moved at once in the same transfer, a ``stock.package_level`` is
created. On creation of a ``stock.package_level``, the result package of
the move lines is directly updated with the entire package.
This is good on the first assign of the move, but when we call assign for
the second time on a move, for instance because it was made partially available
and we want to assign the remaining, it can override the result package we
selected before.
An override of ``StockPicking._check_move_lines_map_quant_package()`` ensures
that we ignore:
* picked lines (qty_done > 0)
* lines with a different result package already
"""
package = self.env["stock.quant.package"].create({"name": "Src Pack"})
dest_package1 = self.env["stock.quant.package"].create({"name": "Dest Pack1"})
# Create new picking: 120 productA
picking_form = Form(self.env['stock.picking'])
picking_form.picking_type_id = self.warehouse.pick_type_id
with picking_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.productA
move_line.product_uom_qty = 120
picking = picking_form.save()
# mark as TO-DO
picking.action_confirm()
# Update quantity on hand: 100 units in package
self.env['stock.quant']._update_available_quantity(self.productA, self.stock_location, 100, package_id=package)
# Check Availability
picking.action_assign()
self.assertEqual(picking.state, "assigned")
self.assertEqual(picking.package_level_ids.package_id, package)
move = picking.move_lines
line = move.move_line_ids
# change the result package and set a qty_done
line.qty_done = 100
line.result_package_id = dest_package1
# Update quantity on hand: 20 units in new_package
new_package = self.env["stock.quant.package"].create({"name": "New Pack"})
self.env['stock.quant']._update_available_quantity(self.productA, self.stock_location, 20, package_id=new_package)
# Check Availability
picking.action_assign()
# Check that result package is not changed on first line
new_line = move.move_line_ids - line
self.assertRecordValues(
line + new_line,
[
{"qty_done": 100, "result_package_id": dest_package1.id},
{"qty_done": 0, "result_package_id": new_package.id},
],
)
def test_entire_pack_overship(self):
"""
Test the scenario of overshipping: we send the customer an entire package, even though it might be more than
what they initially ordered, and update the quantity on the sales order to reflect what was actually sent.
"""
self.warehouse.delivery_steps = 'ship_only'
package = self.env["stock.quant.package"].create({"name": "Src Pack"})
self.env['stock.quant']._update_available_quantity(self.productA, self.stock_location, 100, package_id=package)
self.warehouse.out_type_id.show_entire_packs = True
picking = self.env['stock.picking'].create({
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'picking_type_id': self.warehouse.out_type_id.id,
})
with Form(picking) as picking_form:
with picking_form.move_ids_without_package.new() as move:
move.product_id = self.productA
move.product_uom_qty = 75
picking.action_confirm()
picking.action_assign()
with Form(picking) as picking_form:
with picking_form.package_level_ids_details.new() as package_level:
package_level.package_id = package
self.assertEqual(len(picking.move_lines), 1, 'Should have only 1 stock move')
self.assertEqual(len(picking.move_lines), 1, 'Should have only 1 stock move')
with Form(picking) as picking_form:
with picking_form.package_level_ids_details.edit(0) as package_level:
package_level.is_done = True
action = picking.button_validate()
self.assertEqual(action, True, 'Should not open wizard')
for ml in picking.move_line_ids:
self.assertEqual(ml.package_id, package, 'move_line.package')
self.assertEqual(ml.result_package_id, package, 'move_line.result_package')
self.assertEqual(ml.state, 'done', 'move_line.state')
quant = package.quant_ids.filtered(lambda q: q.location_id == self.customer_location)
self.assertEqual(len(quant), 1, 'Should have quant at customer location')
self.assertEqual(quant.reserved_quantity, 0, 'quant.reserved_quantity should = 0')
self.assertEqual(quant.quantity, 100.0, 'quant.quantity should = 100')
self.assertEqual(sum(ml.qty_done for ml in picking.move_line_ids), 100.0, 'total move_line.qty_done should = 100')
backorders = self.env['stock.picking'].search([('backorder_id', '=', picking.id)])
self.assertEqual(len(backorders), 0, 'Should not create a backorder')
def test_remove_package(self):
"""
In the overshipping scenario, if I remove the package after adding it, we should not remove the associated
stock move.
"""
self.warehouse.delivery_steps = 'ship_only'
package = self.env["stock.quant.package"].create({"name": "Src Pack"})
self.env['stock.quant']._update_available_quantity(self.productA, self.stock_location, 100, package_id=package)
self.warehouse.out_type_id.show_entire_packs = True
picking = self.env['stock.picking'].create({
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'picking_type_id': self.warehouse.out_type_id.id,
})
with Form(picking) as picking_form:
with picking_form.move_ids_without_package.new() as move:
move.product_id = self.productA
move.product_uom_qty = 75
picking.action_assign()
with Form(picking) as picking_form:
with picking_form.package_level_ids_details.new() as package_level:
package_level.package_id = package
with Form(picking) as picking_form:
picking_form.package_level_ids.remove(0)
self.assertEqual(len(picking.move_lines), 1, 'Should have only 1 stock move')
def test_picking_state_with_null_qty(self):
receipt_form = Form(self.env['stock.picking'].with_context(default_immediate_transfer=False))
picking_type_id = self.warehouse.out_type_id
receipt_form.picking_type_id = picking_type_id
with receipt_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.productA
move_line.product_uom_qty = 10
with receipt_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.productB
move_line.product_uom_qty = 10
receipt = receipt_form.save()
receipt.action_confirm()
self.assertEqual(receipt.state, 'confirmed')
receipt.move_ids_without_package[1].product_uom_qty = 0
self.assertEqual(receipt.state, 'confirmed')
receipt_form = Form(self.env['stock.picking'].with_context(default_immediate_transfer=True))
picking_type_id = self.warehouse.out_type_id
receipt_form.picking_type_id = picking_type_id
with receipt_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.productA
move_line.quantity_done = 10
with receipt_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.productB
move_line.quantity_done = 10
receipt = receipt_form.save()
receipt.action_confirm()
self.assertEqual(receipt.state, 'assigned')
receipt.move_ids_without_package[1].product_uom_qty = 0
self.assertEqual(receipt.state, 'assigned')
def test_2_steps_and_backorder(self):
""" When creating a backorder with a package, the latter should be reserved in the new picking. Moreover,
the initial picking shouldn't have any line about this package """
def create_picking(type, from_loc, to_loc):
picking = self.env['stock.picking'].create({
'picking_type_id': type.id,
'location_id': from_loc.id,
'location_dest_id': to_loc.id,
})
move_A, move_B = self.env['stock.move'].create([{
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 1,
'product_uom': self.productA.uom_id.id,
'picking_id': picking.id,
'location_id': from_loc.id,
'location_dest_id': to_loc.id,
}, {
'name': self.productB.name,
'product_id': self.productB.id,
'product_uom_qty': 1,
'product_uom': self.productB.uom_id.id,
'picking_id': picking.id,
'location_id': from_loc.id,
'location_dest_id': to_loc.id,
}])
picking.action_confirm()
picking.action_assign()
return picking, move_A, move_B
self.warehouse.delivery_steps = 'pick_ship'
output_location = self.warehouse.wh_output_stock_loc_id
pick_type = self.warehouse.pick_type_id
delivery_type = self.warehouse.out_type_id
self.env['stock.quant']._update_available_quantity(self.productA, self.stock_location, 1)
self.env['stock.quant']._update_available_quantity(self.productB, self.stock_location, 1)
picking, moveA, moveB = create_picking(pick_type, pick_type.default_location_src_id, pick_type.default_location_dest_id)
moveA.move_line_ids.qty_done = 1
picking.action_put_in_pack()
moveB.move_line_ids.qty_done = 1
picking.action_put_in_pack()
picking.button_validate()
picking, _, _ = create_picking(delivery_type, delivery_type.default_location_src_id, self.customer_location)
packB = picking.package_level_ids[1]
with Form(picking) as picking_form:
with picking_form.package_level_ids_details.edit(0) as package_level:
package_level.is_done = True
action_data = picking.button_validate()
backorder_wizard = Form(self.env['stock.backorder.confirmation'].with_context(action_data['context'])).save()
backorder_wizard.process()
bo = self.env['stock.picking'].search([('backorder_id', '=', picking.id)])
self.assertNotIn(packB, picking.package_level_ids)
self.assertEqual(packB, bo.package_level_ids)
self.assertEqual(bo.package_level_ids.state, 'assigned')
def test_package_and_sub_location(self):
"""
Suppose there are some products P available in shelf1, a child location of the pack location.
When moving these P to another child location of pack location, the source location of the
related package level should be shelf1
"""
shelf1_location = self.env['stock.location'].create({
'name': 'shelf1',
'usage': 'internal',
'location_id': self.pack_location.id,
})
shelf2_location = self.env['stock.location'].create({
'name': 'shelf2',
'usage': 'internal',
'location_id': self.pack_location.id,
})
pack = self.env['stock.quant.package'].create({'name': 'Super Package'})
self.env['stock.quant']._update_available_quantity(self.productA, shelf1_location, 20.0, package_id=pack)
picking = self.env['stock.picking'].create({
'picking_type_id': self.warehouse.in_type_id.id,
'location_id': self.pack_location.id,
'location_dest_id': shelf2_location.id,
})
package_level = self.env['stock.package_level'].create({
'package_id': pack.id,
'picking_id': picking.id,
'location_dest_id': picking.location_dest_id.id,
'company_id': picking.company_id.id,
})
self.assertEqual(package_level.location_id, shelf1_location)
picking.action_confirm()
package_level.is_done = True
picking.button_validate()
self.assertEqual(package_level.location_id, shelf1_location)
def test_pack_in_receipt_two_step_multi_putaway_02(self):
"""
Suppose a product P, its weight is equal to 1kg
We have 100 x P on two pallets.
Receipt in two steps + Sub locations in WH/Stock + Storage Category
The Storage Category adds some constraints on weight/pallets capacity
"""
warehouse = self.stock_location.warehouse_id
warehouse.reception_steps = "two_steps"
self.productA.weight = 1.0
self.env.user.write({'groups_id': [(4, self.env.ref('stock.group_stock_storage_categories').id)]})
self.env.user.write({'groups_id': [(4, self.env.ref('stock.group_stock_multi_locations').id)]})
package_type = self.env['stock.package.type'].create({
'name': "Super Pallet",
})
package_01, package_02 = self.env['stock.quant.package'].create([{
'name': 'Pallet %s' % i,
'package_type_id': package_type.id,
} for i in [1, 2]])
# max 100kg (so 100 x P) and max 1 pallet -> we will work with pallets,
# so the pallet capacity constraint should be the effective one
stor_category = self.env['stock.storage.category'].create({
'name': 'Super Storage Category',
'max_weight': 100,
'package_capacity_ids': [(0, 0, {
'package_type_id': package_type.id,
'quantity': 1,
})]
})
# 3 sub locations with the storage category
# (the third location should never be used)
sub_loc_01, sub_loc_02, dummy = self.env['stock.location'].create([{
'name': 'Sub Location %s' % i,
'usage': 'internal',
'location_id': self.stock_location.id,
'storage_category_id': stor_category.id,
} for i in [1, 2, 3]])
self.env['stock.putaway.rule'].create({
'location_in_id': self.stock_location.id,
'location_out_id': self.stock_location.id,
'package_type_ids': [(4, package_type.id)],
'storage_category_id': stor_category.id,
})
# Receive 100 x P
receipt_picking = self.env['stock.picking'].create({
'picking_type_id': warehouse.in_type_id.id,
'location_id': self.env.ref('stock.stock_location_suppliers').id,
'location_dest_id': warehouse.wh_input_stock_loc_id.id,
})
self.env['stock.move'].create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom': self.productA.uom_id.id,
'product_uom_qty': 100.0,
'picking_id': receipt_picking.id,
'location_id': receipt_picking.location_id.id,
'location_dest_id': receipt_picking.location_dest_id.id,
})
receipt_picking.action_confirm()
# Distribute the products on two pallets, one with 49 x P and a second
# one with 51 x P (to easy the debugging in case of trouble)
move_form = Form(receipt_picking.move_lines, view="stock.view_stock_move_operations")
with move_form.move_line_ids.edit(0) as line:
line.qty_done = 49
line.result_package_id = package_01
with move_form.move_line_ids.new() as line:
line.qty_done = 51
line.result_package_id = package_02
move_form.save()
receipt_picking.button_validate()
# We are in two-steps receipt -> check the internal picking
internal_picking = self.env['stock.picking'].search([], order='id desc', limit=1)
self.assertRecordValues(internal_picking.move_line_ids, [
{'product_uom_qty': 49, 'qty_done': 0, 'result_package_id': package_01.id, 'location_dest_id': sub_loc_01.id},
{'product_uom_qty': 51, 'qty_done': 0, 'result_package_id': package_02.id, 'location_dest_id': sub_loc_02.id},
])
# Change the constraints of the storage category:
# max 75kg (so 75 x P) and max 2 pallet -> this time, the weight
# constraint should be the effective one
stor_category.max_weight = 75
stor_category.package_capacity_ids.quantity = 2
internal_picking.do_unreserve()
internal_picking.action_assign()
self.assertRecordValues(internal_picking.move_line_ids, [
{'product_uom_qty': 49, 'qty_done': 0, 'result_package_id': package_01.id, 'location_dest_id': sub_loc_01.id},
{'product_uom_qty': 51, 'qty_done': 0, 'result_package_id': package_02.id, 'location_dest_id': sub_loc_02.id},
])
move_form = Form(internal_picking.move_lines, view="stock.view_stock_move_operations")
# lines order is reversed: [Pallet 02, Pallet 01]
with move_form.move_line_ids.edit(0) as line:
line.qty_done = 51
with move_form.move_line_ids.edit(1) as line:
line.qty_done = 49
move_form.save()
# lines order is reversed: [Pallet 02, Pallet 01]
self.assertRecordValues(internal_picking.move_line_ids, [
{'product_uom_qty': 51, 'qty_done': 51, 'result_package_id': package_02.id, 'location_dest_id': sub_loc_02.id},
{'product_uom_qty': 49, 'qty_done': 49, 'result_package_id': package_01.id, 'location_dest_id': sub_loc_01.id},
])
def test_pack_in_receipt_two_step_multi_putaway_03(self):
"""
Two sublocations (max 100kg, max 2 pallet)
Two products P1, P2, weight = 1kg
There are 10 x P1 on a pallet in the first sub location
Receive a pallet of 50 x P1 + 50 x P2 => because of weight constraint, should be redirected to the
second sub location
Then, same with max 200kg max 1 pallet => same result, this time because of pallet count constraint
"""
warehouse = self.stock_location.warehouse_id
warehouse.reception_steps = "two_steps"
self.productA.weight = 1.0
self.productB.weight = 1.0
self.env.user.write({'groups_id': [(4, self.env.ref('stock.group_stock_storage_categories').id)]})
self.env.user.write({'groups_id': [(4, self.env.ref('stock.group_stock_multi_locations').id)]})
package_type = self.env['stock.package.type'].create({
'name': "Super Pallet",
})
package_01, package_02 = self.env['stock.quant.package'].create([{
'name': 'Pallet %s' % i,
'package_type_id': package_type.id,
} for i in [1, 2]])
# max 100kg and max 2 pallets
stor_category = self.env['stock.storage.category'].create({
'name': 'Super Storage Category',
'max_weight': 100,
'package_capacity_ids': [(0, 0, {
'package_type_id': package_type.id,
'quantity': 2,
})]
})
# 3 sub locations with the storage category
# (the third location should never be used)
sub_loc_01, sub_loc_02, dummy = self.env['stock.location'].create([{
'name': 'Sub Location %s' % i,
'usage': 'internal',
'location_id': self.stock_location.id,
'storage_category_id': stor_category.id,
} for i in [1, 2, 3]])
self.env['stock.quant']._update_available_quantity(self.productA, sub_loc_01, 10, package_id=package_01)
self.env['stock.putaway.rule'].create({
'location_in_id': self.stock_location.id,
'location_out_id': self.stock_location.id,
'package_type_ids': [(4, package_type.id)],
'storage_category_id': stor_category.id,
})
# Receive 50 x P_A and 50 x P_B
receipt_picking = self.env['stock.picking'].create({
'picking_type_id': warehouse.in_type_id.id,
'location_id': self.env.ref('stock.stock_location_suppliers').id,
'location_dest_id': warehouse.wh_input_stock_loc_id.id,
})
self.env['stock.move'].create([{
'name': p.name,
'product_id': p.id,
'product_uom': p.uom_id.id,
'product_uom_qty': 50,
'picking_id': receipt_picking.id,
'location_id': receipt_picking.location_id.id,
'location_dest_id': receipt_picking.location_dest_id.id,
} for p in [self.productA, self.productB]])
receipt_picking.action_confirm()
move_form = Form(receipt_picking.move_lines[0], view="stock.view_stock_move_operations")
with move_form.move_line_ids.edit(0) as line:
line.qty_done = 50
line.result_package_id = package_02
move_form.save()
move_form = Form(receipt_picking.move_lines[1], view="stock.view_stock_move_operations")
with move_form.move_line_ids.edit(0) as line:
line.qty_done = 50
line.result_package_id = package_02
move_form.save()
receipt_picking.button_validate()
# We are in two-steps receipt -> check the internal picking
internal_picking = self.env['stock.picking'].search([], order='id desc', limit=1)
self.assertRecordValues(internal_picking.move_line_ids, [
{'product_id': self.productA.id, 'product_uom_qty': 50, 'qty_done': 0, 'result_package_id': package_02.id, 'location_dest_id': sub_loc_02.id},
{'product_id': self.productB.id, 'product_uom_qty': 50, 'qty_done': 0, 'result_package_id': package_02.id, 'location_dest_id': sub_loc_02.id},
])
# Change the constraints of the storage category:
# max 200kg and max 1 pallet
stor_category.max_weight = 200
stor_category.package_capacity_ids.quantity = 1
internal_picking.do_unreserve()
internal_picking.action_assign()
self.assertRecordValues(internal_picking.move_line_ids, [
{'product_id': self.productA.id, 'product_uom_qty': 50, 'qty_done': 0, 'result_package_id': package_02.id, 'location_dest_id': sub_loc_02.id},
{'product_id': self.productB.id, 'product_uom_qty': 50, 'qty_done': 0, 'result_package_id': package_02.id, 'location_dest_id': sub_loc_02.id},
])
def test_pack_in_receipt_two_step_multi_putaway_04(self):
"""
Create a putaway rules for package type T and storage category SC. SC
only allows same products and has a maximum of 2 x T. Four SC locations
L1, L2, L3 and L4.
First, move a package that contains two different products: should not
redirect to L1/L2 because of the "same products" contraint.
Then, add one T-package (with product P01) at L1 and move 2 T-packages
(both with product P01): one should be redirected to L1 and the second
one to L2
Finally, move 3 T-packages (two with 1xP01, one with 1xP02): one P01
should be redirected to L2 and the second one to L3 (because of capacity
constraint), then P02 should be redirected to L4 (because of "same
product" policy)
"""
self.warehouse.reception_steps = "two_steps"
supplier_location = self.env.ref('stock.stock_location_suppliers')
input_location = self.warehouse.wh_input_stock_loc_id
package_type = self.env['stock.package.type'].create({
'name': "package type",
})
storage_category = self.env['stock.storage.category'].create({
'name': "storage category",
'allow_new_product': "same",
'max_weight': 1000,
'package_capacity_ids': [(0, 0, {
'package_type_id': package_type.id,
'quantity': 2,
})],
})
loc01, loc02, loc03, loc04 = self.env['stock.location'].create([{
'name': 'loc 0%d' % i,
'usage': 'internal',
'location_id': self.stock_location.id,
'storage_category_id': storage_category.id,
} for i in range(1, 5)])
self.env['stock.putaway.rule'].create({
'location_in_id': self.stock_location.id,
'location_out_id': self.stock_location.id,
'storage_category_id': storage_category.id,
'package_type_ids': [(4, package_type.id, 0)],
})
receipt = self.env['stock.picking'].create({
'picking_type_id': self.warehouse.in_type_id.id,
'location_id': supplier_location.id,
'location_dest_id': input_location.id,
'move_lines': [(0, 0, {
'name': p.name,
'location_id': supplier_location.id,
'location_dest_id': input_location.id,
'product_id': p.id,
'product_uom': p.uom_id.id,
'product_uom_qty': 1.0,
}) for p in (self.productA, self.productB)],
})
receipt.action_confirm()
moves = receipt.move_lines
moves.move_line_ids.qty_done = 1
moves.move_line_ids.result_package_id = self.env['stock.quant.package'].create({'package_type_id': package_type.id})
receipt.button_validate()
internal_picking = moves.move_dest_ids.picking_id
self.assertEqual(internal_picking.move_line_ids.location_dest_id, self.stock_location,
'Storage location only accepts one same product. Here the package contains two different '
'products so it should not be redirected.')
internal_picking.action_cancel()
# Second test part
package = self.env['stock.quant.package'].create({'package_type_id': package_type.id})
self.env['stock.quant']._update_available_quantity(self.productA, loc01, 1.0, package_id=package)
receipt = self.env['stock.picking'].create({
'picking_type_id': self.warehouse.in_type_id.id,
'location_id': supplier_location.id,
'location_dest_id': input_location.id,
'move_lines': [(0, 0, {
'name': self.productA.name,
'location_id': supplier_location.id,
'location_dest_id': input_location.id,
'product_id': self.productA.id,
'product_uom': self.productA.uom_id.id,
'product_uom_qty': 2.0,
})],
})
receipt.action_confirm()
receipt.do_unreserve()
self.env['stock.move.line'].create([{
'move_id': receipt.move_lines.id,
'qty_done': 1,
'product_id': self.productA.id,
'product_uom_id': self.productA.uom_id.id,
'location_id': supplier_location.id,
'location_dest_id': input_location.id,
'result_package_id': self.env['stock.quant.package'].create({'package_type_id': package_type.id}).id,
'picking_id': receipt.id,
} for _ in range(2)])
receipt.button_validate()
internal_transfer = receipt.move_lines.move_dest_ids.picking_id
self.assertEqual(internal_transfer.move_line_ids.location_dest_id, loc01 | loc02,
'There is already one package at L1, so the first SML should be redirected to L1 '
'and the second one to L2')
internal_transfer.move_line_ids.qty_done = 1
internal_transfer.button_validate()
# Third part (move 3 packages, 2 x P01 and 1 x P02)
receipt = self.env['stock.picking'].create({
'picking_type_id': self.warehouse.in_type_id.id,
'location_id': supplier_location.id,
'location_dest_id': input_location.id,
'move_lines': [(0, 0, {
'name': product.name,
'location_id': supplier_location.id,
'location_dest_id': input_location.id,
'product_id': product.id,
'product_uom': product.uom_id.id,
'product_uom_qty': qty,
}) for qty, product in [(2.0, self.productA), (1.0, self.productB)]],
})
receipt.action_confirm()
receipt.do_unreserve()
moves = receipt.move_lines
self.env['stock.move.line'].create([{
'move_id': move.id,
'qty_done': 1,
'product_id': product.id,
'product_uom_id': product.uom_id.id,
'location_id': supplier_location.id,
'location_dest_id': input_location.id,
'result_package_id': self.env['stock.quant.package'].create({'package_type_id': package_type.id}).id,
'picking_id': receipt.id,
} for product, move in [
(self.productA, moves[0]),
(self.productA, moves[0]),
(self.productB, moves[1]),
]])
receipt.button_validate()
internal_transfer = receipt.move_lines.move_dest_ids.picking_id
self.assertRecordValues(internal_transfer.move_line_ids, [
{'product_id': self.productA.id, 'product_uom_qty': 1.0, 'location_dest_id': loc02.id},
{'product_id': self.productA.id, 'product_uom_qty': 1.0, 'location_dest_id': loc03.id},
{'product_id': self.productB.id, 'product_uom_qty': 1.0, 'location_dest_id': loc04.id},
])
def test_rounding_and_reserved_qty(self):
"""
Basic use case: deliver a storable product put in two packages. This
test actually ensures that the process 'put in pack' handles some
possible issues with the floating point representation
"""
self.env['stock.quant']._update_available_quantity(self.productA, self.stock_location, 0.4)
picking = self.env['stock.picking'].create({
'picking_type_id': self.warehouse.out_type_id.id,
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'move_lines': [(0, 0, {
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 0.4,
'product_uom': self.productA.uom_id.id,
'location_id': self.stock_location.id,
'location_dest_id': self.customer_location.id,
'picking_type_id': self.warehouse.out_type_id.id,
})],
})
picking.action_confirm()
picking.move_line_ids.qty_done = 0.3
picking.action_put_in_pack()
picking.move_line_ids.filtered(lambda ml: not ml.result_package_id).qty_done = 0.1
picking.action_put_in_pack()
quant = self.env['stock.quant'].search([('product_id', '=', self.productA.id), ('location_id', '=', self.stock_location.id)])
self.assertEqual(quant.available_quantity, 0)
picking.button_validate()
self.assertEqual(picking.state, 'done')
self.assertEqual(picking.move_lines.quantity_done, 0.4)
self.assertEqual(len(picking.move_line_ids.result_package_id), 2)
def test_put_out_of_pack_transfer(self):
""" When a transfer has multiple products all in the same package, removing a product from the destination package
(i.e. removing it from the package but still putting it in the same location) shouldn't remove it for other products. """
loc_1 = self.env['stock.location'].create({
'name': 'Location A',
'location_id': self.stock_location.id,
})
loc_2 = self.env['stock.location'].create({
'name': 'Location B',
'location_id': self.stock_location.id,
})
pack = self.env['stock.quant.package'].create({'name': 'New Package'})
self.env['stock.quant']._update_available_quantity(self.productA, loc_1, 5, package_id=pack)
self.env['stock.quant']._update_available_quantity(self.productB, loc_1, 4, package_id=pack)
picking = self.env['stock.picking'].create({
'location_id': loc_1.id,
'location_dest_id': loc_2.id,
'picking_type_id': self.warehouse.int_type_id.id,
})
moveA = self.env['stock.move'].create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 5,
'product_uom': self.productA.uom_id.id,
'picking_id': picking.id,
'location_id': loc_1.id,
'location_dest_id': loc_2.id,
})
moveB = self.env['stock.move'].create({
'name': self.productB.name,
'product_id': self.productB.id,
'product_uom_qty': 4,
'product_uom': self.productB.uom_id.id,
'picking_id': picking.id,
'location_id': loc_1.id,
'location_dest_id': loc_2.id,
})
# Check availabilities
picking.action_assign()
self.assertEqual(len(moveA.move_line_ids), 1, "A move line should have been created for the reservation of the package.")
self.assertEqual(moveA.move_line_ids.package_id.id, pack.id, "The package should have been reserved for both products.")
self.assertEqual(moveB.move_line_ids.package_id.id, pack.id, "The package should have been reserved for both products.")
pack_level = moveA.move_line_ids.package_level_id
# Remove the product A from the package in the destination.
moveA.move_line_ids.result_package_id = False
self.assertEqual(moveA.move_line_ids.result_package_id.id, False, "No package should be linked in the destination.")
self.assertEqual(moveA.move_line_ids.package_level_id.id, False, "Package level should have been unlinked from this move line.")
self.assertEqual(moveB.move_line_ids.result_package_id.id, pack.id, "Package should have stayed the same.")
self.assertEqual(moveB.move_line_ids.package_level_id.id, pack_level.id, "Package level should have stayed the same.")
# Validate the picking
moveA.move_line_ids.qty_done = 5
moveB.move_line_ids.qty_done = 4
picking.button_validate()
# Check that the quants have their expected location/package/quantities
quantA = self.env['stock.quant'].search([('product_id', '=', self.productA.id), ('location_id', '=', loc_2.id)])
quantB = self.env['stock.quant'].search([('product_id', '=', self.productB.id), ('location_id', '=', loc_2.id)])
self.assertEqual(pack.location_id.id, loc_2.id, "Package should have been moved to Location B.")
self.assertEqual(quantA.quantity, 5, "All 5 units of product A should be in location B")
self.assertEqual(quantA.package_id.id, False, "There should be no package for product A as it was removed in the move.")
self.assertEqual(quantB.quantity, 4, "All 4 units of product B should be in location B")
self.assertEqual(quantB.package_id.id, pack.id, "Product B should still be in the initial package.")
| 49.427785
| 71,868
|
1,508
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo.tests import common
class TestStockLocationSearch(common.TransactionCase):
def setUp(self):
super(TestStockLocationSearch, self).setUp()
self.location = self.env['stock.location']
self.stock_location = self.env.ref('stock.stock_location_stock')
self.sublocation = self.env['stock.location'].create({
'name': 'Shelf 2',
'barcode': 1201985,
'location_id': self.stock_location.id
})
self.location_barcode_id = self.sublocation.id
self.barcode = self.sublocation.barcode
self.name = self.sublocation.name
def test_10_location_search_by_barcode(self):
"""Search stock location by barcode"""
location_names = self.location.name_search(name=self.barcode)
self.assertEqual(len(location_names), 1)
location_id_found = location_names[0][0]
self.assertEqual(self.location_barcode_id, location_id_found)
def test_20_location_search_by_name(self):
"""Search stock location by name"""
location_names = self.location.name_search(name=self.name)
location_ids_found = [location_name[0] for location_name in location_names]
self.assertTrue(self.location_barcode_id in location_ids_found)
def test_30_location_search_wo_results(self):
"""Search stock location without results"""
location_names = self.location.name_search(name='nonexistent')
self.assertFalse(location_names)
| 41.888889
| 1,508
|
167,429
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import timedelta
from odoo.addons.stock.tests.common import TestStockCommon
from odoo.exceptions import UserError
from odoo.tests import Form
from odoo.tools import float_is_zero, float_compare
from datetime import datetime
from dateutil.relativedelta import relativedelta
class TestPickShip(TestStockCommon):
def create_pick_ship(self):
picking_client = self.env['stock.picking'].create({
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
'picking_type_id': self.picking_type_out,
})
dest = self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 10,
'product_uom': self.productA.uom_id.id,
'picking_id': picking_client.id,
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
'state': 'waiting',
'procure_method': 'make_to_order',
})
picking_pick = self.env['stock.picking'].create({
'location_id': self.stock_location,
'location_dest_id': self.pack_location,
'picking_type_id': self.picking_type_out,
})
self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 10,
'product_uom': self.productA.uom_id.id,
'picking_id': picking_pick.id,
'location_id': self.stock_location,
'location_dest_id': self.pack_location,
'move_dest_ids': [(4, dest.id)],
'state': 'confirmed',
})
return picking_pick, picking_client
def create_pick_pack_ship(self):
picking_ship = self.env['stock.picking'].create({
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
'picking_type_id': self.picking_type_out,
})
ship = self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 1,
'product_uom': self.productA.uom_id.id,
'picking_id': picking_ship.id,
'location_id': self.output_location,
'location_dest_id': self.customer_location,
})
picking_pack = self.env['stock.picking'].create({
'location_id': self.stock_location,
'location_dest_id': self.pack_location,
'picking_type_id': self.picking_type_out,
})
pack = self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 1,
'product_uom': self.productA.uom_id.id,
'picking_id': picking_pack.id,
'location_id': self.pack_location,
'location_dest_id': self.output_location,
'move_dest_ids': [(4, ship.id)],
})
picking_pick = self.env['stock.picking'].create({
'location_id': self.stock_location,
'location_dest_id': self.pack_location,
'picking_type_id': self.picking_type_out,
})
self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 1,
'product_uom': self.productA.uom_id.id,
'picking_id': picking_pick.id,
'location_id': self.stock_location,
'location_dest_id': self.pack_location,
'move_dest_ids': [(4, pack.id)],
'state': 'confirmed',
})
return picking_pick, picking_pack, picking_ship
def test_unreserve_only_required_quantity(self):
product_unreserve = self.env['product.product'].create({
'name': 'product unreserve',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
})
stock_location = self.env['stock.location'].browse(self.stock_location)
self.env['stock.quant']._update_available_quantity(product_unreserve, stock_location, 4.0)
quants = self.env['stock.quant']._gather(product_unreserve, stock_location, strict=True)
self.assertEqual(quants[0].reserved_quantity, 0)
move = self.MoveObj.create({
'name': product_unreserve.name,
'product_id': product_unreserve.id,
'product_uom_qty': 3,
'product_uom': product_unreserve.uom_id.id,
'state': 'confirmed',
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
})
move._action_assign()
self.assertEqual(quants[0].reserved_quantity, 3)
move_2 = self.MoveObj.create({
'name': product_unreserve.name,
'product_id': product_unreserve.id,
'product_uom_qty': 2,
'quantity_done':2,
'product_uom': product_unreserve.uom_id.id,
'state': 'confirmed',
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
})
move_2._action_assign()
move_2._action_done()
quants = self.env['stock.quant']._gather(product_unreserve, stock_location, strict=True)
self.assertEqual(quants[0].reserved_quantity, 2)
def test_mto_moves(self):
"""
10 in stock, do pick->ship and check ship is assigned when pick is done, then backorder of ship
"""
picking_pick, picking_client = self.create_pick_ship()
location = self.env['stock.location'].browse(self.stock_location)
# make some stock
self.env['stock.quant']._update_available_quantity(self.productA, location, 10.0)
picking_pick.action_assign()
picking_pick.move_lines[0].move_line_ids[0].qty_done = 10.0
picking_pick._action_done()
self.assertEqual(picking_client.state, 'assigned', 'The state of the client should be assigned')
# Now partially transfer the ship
picking_client.move_lines[0].move_line_ids[0].qty_done = 5
picking_client._action_done() # no new in order to create backorder
backorder = self.env['stock.picking'].search([('backorder_id', '=', picking_client.id)])
self.assertEqual(backorder.state, 'waiting', 'Backorder should be waiting for reservation')
def test_mto_moves_transfer(self):
"""
10 in stock, 5 in pack. Make sure it does not assign the 5 pieces in pack
"""
picking_pick, picking_client = self.create_pick_ship()
stock_location = self.env['stock.location'].browse(self.stock_location)
self.env['stock.quant']._update_available_quantity(self.productA, stock_location, 10.0)
pack_location = self.env['stock.location'].browse(self.pack_location)
self.env['stock.quant']._update_available_quantity(self.productA, pack_location, 5.0)
self.assertEqual(len(self.env['stock.quant']._gather(self.productA, stock_location)), 1.0)
self.assertEqual(len(self.env['stock.quant']._gather(self.productA, pack_location)), 1.0)
(picking_pick + picking_client).action_assign()
move_pick = picking_pick.move_lines
move_cust = picking_client.move_lines
self.assertEqual(move_pick.state, 'assigned')
self.assertEqual(picking_pick.state, 'assigned')
self.assertEqual(move_cust.state, 'waiting')
self.assertEqual(picking_client.state, 'waiting', 'The picking should not assign what it does not have')
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.productA, stock_location), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.productA, pack_location), 5.0)
move_pick.move_line_ids[0].qty_done = 10.0
picking_pick._action_done()
self.assertEqual(move_pick.state, 'done')
self.assertEqual(picking_pick.state, 'done')
self.assertEqual(move_cust.state, 'assigned')
self.assertEqual(picking_client.state, 'assigned', 'The picking should not assign what it does not have')
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.productA, stock_location), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.productA, pack_location), 5.0)
self.assertEqual(sum(self.env['stock.quant']._gather(self.productA, stock_location).mapped('quantity')), 0.0)
self.assertEqual(len(self.env['stock.quant']._gather(self.productA, pack_location)), 1.0)
def test_mto_moves_return(self):
picking_pick, picking_client = self.create_pick_ship()
stock_location = self.env['stock.location'].browse(self.stock_location)
self.env['stock.quant']._update_available_quantity(self.productA, stock_location, 10.0)
picking_pick.action_assign()
picking_pick.move_lines[0].move_line_ids[0].qty_done = 10.0
picking_pick._action_done()
self.assertEqual(picking_pick.state, 'done')
self.assertEqual(picking_client.state, 'assigned')
# return a part of what we've done
stock_return_picking_form = Form(self.env['stock.return.picking']
.with_context(active_ids=picking_pick.ids, active_id=picking_pick.ids[0],
active_model='stock.picking'))
stock_return_picking = stock_return_picking_form.save()
stock_return_picking = stock_return_picking_form.save()
stock_return_picking.product_return_moves.quantity = 2.0 # Return only 2
stock_return_picking_action = stock_return_picking.create_returns()
return_pick = self.env['stock.picking'].browse(stock_return_picking_action['res_id'])
return_pick.move_lines[0].move_line_ids[0].qty_done = 2.0
return_pick._action_done()
# the client picking should not be assigned anymore, as we returned partially what we took
self.assertEqual(picking_client.state, 'confirmed')
def test_mto_moves_extra_qty(self):
""" Ensure that a move in MTO will support an extra quantity. The extra
move should be created in MTS and should not be merged in the initial
move if it's in MTO. It should also avoid to trigger the rules.
"""
picking_pick, picking_client = self.create_pick_ship()
stock_location = self.env['stock.location'].browse(self.stock_location)
self.productA.write({'route_ids': [(4, self.env.ref('stock.route_warehouse0_mto').id)]})
self.env['stock.quant']._update_available_quantity(self.productA, stock_location, 10.0)
picking_pick.action_assign()
picking_pick.move_lines[0].move_line_ids[0].qty_done = 15.0
picking_pick._action_done()
self.assertEqual(picking_pick.state, 'done')
self.assertEqual(picking_client.state, 'assigned')
picking_client.move_lines[0].move_line_ids[0].qty_done = 15.0
picking_client.move_lines._action_done()
self.assertEqual(len(picking_client.move_lines), 2)
move_lines = picking_client.move_lines.sorted()
self.assertEqual(move_lines.mapped('procure_method'), ['make_to_order', 'make_to_stock'])
self.assertEqual(move_lines.mapped('product_uom_qty'), [10.0, 5.0])
def test_mto_moves_return_extra(self):
picking_pick, picking_client = self.create_pick_ship()
stock_location = self.env['stock.location'].browse(self.stock_location)
self.env['stock.quant']._update_available_quantity(self.productA, stock_location, 10.0)
picking_pick.action_assign()
picking_pick.move_lines[0].move_line_ids[0].qty_done = 10.0
picking_pick._action_done()
self.assertEqual(picking_pick.state, 'done')
self.assertEqual(picking_client.state, 'assigned')
# return more than we've done
stock_return_picking_form = Form(self.env['stock.return.picking']
.with_context(active_ids=picking_pick.ids, active_id=picking_pick.ids[0],
active_model='stock.picking'))
stock_return_picking = stock_return_picking_form.save()
stock_return_picking.product_return_moves.quantity = 12.0 # Return 2 extra
stock_return_picking_action = stock_return_picking.create_returns()
return_pick = self.env['stock.picking'].browse(stock_return_picking_action['res_id'])
# Verify the extra move has been merged with the original move
self.assertAlmostEqual(return_pick.move_lines.product_uom_qty, 12.0)
self.assertAlmostEqual(return_pick.move_lines.quantity_done, 0.0)
self.assertAlmostEqual(return_pick.move_lines.reserved_availability, 10.0)
def test_mto_resupply_cancel_ship(self):
""" This test simulates a pick pack ship with a resupply route
set. Pick and pack are validated, ship is cancelled. This test
ensure that new picking are not created from the cancelled
ship after the scheduler task. The supply route is only set in
order to make the scheduler run without mistakes (no next
activity).
"""
picking_pick, picking_pack, picking_ship = self.create_pick_pack_ship()
stock_location = self.env['stock.location'].browse(self.stock_location)
warehouse_1 = self.env['stock.warehouse'].search([('company_id', '=', self.env.user.id)], limit=1)
warehouse_1.write({'delivery_steps': 'pick_pack_ship'})
warehouse_2 = self.env['stock.warehouse'].create({
'name': 'Small Warehouse',
'code': 'SWH'
})
warehouse_1.write({
'resupply_wh_ids': [(6, 0, [warehouse_2.id])]
})
resupply_route = self.env['stock.location.route'].search([('supplier_wh_id', '=', warehouse_2.id), ('supplied_wh_id', '=', warehouse_1.id)])
self.assertTrue(resupply_route)
self.productA.write({'route_ids': [(4, resupply_route.id), (4, self.env.ref('stock.route_warehouse0_mto').id)]})
self.env['stock.quant']._update_available_quantity(self.productA, stock_location, 10.0)
picking_pick.action_assign()
picking_pick.move_lines[0].move_line_ids[0].qty_done = 10.0
picking_pick._action_done()
picking_pack.action_assign()
picking_pack.move_lines[0].move_line_ids[0].qty_done = 10.0
picking_pack._action_done()
picking_ship.action_cancel()
picking_ship.move_lines.write({'procure_method': 'make_to_order'})
self.env['procurement.group'].run_scheduler()
next_activity = self.env['mail.activity'].search([('res_model', '=', 'product.template'), ('res_id', '=', self.productA.product_tmpl_id.id)])
self.assertEqual(picking_ship.state, 'cancel')
self.assertFalse(next_activity, 'If a next activity has been created if means that scheduler failed\
and the end of this test do not have sense.')
self.assertEqual(len(picking_ship.move_lines.mapped('move_orig_ids')), 0,
'Scheduler should not create picking pack and pick since ship has been manually cancelled.')
def test_no_backorder_1(self):
""" Check the behavior of doing less than asked in the picking pick and chosing not to
create a backorder. In this behavior, the second picking should obviously only be able to
reserve what was brought, but its initial demand should stay the same and the system will
ask the user will have to consider again if he wants to create a backorder or not.
"""
picking_pick, picking_client = self.create_pick_ship()
location = self.env['stock.location'].browse(self.stock_location)
# make some stock
self.env['stock.quant']._update_available_quantity(self.productA, location, 10.0)
picking_pick.action_assign()
picking_pick.move_lines[0].move_line_ids[0].qty_done = 5.0
# create a backorder
picking_pick._action_done()
picking_pick_backorder = self.env['stock.picking'].search([('backorder_id', '=', picking_pick.id)])
self.assertEqual(picking_pick_backorder.state, 'confirmed')
self.assertEqual(picking_pick_backorder.move_lines.product_qty, 5.0)
self.assertEqual(picking_client.state, 'assigned')
# cancel the backorder
picking_pick_backorder.action_cancel()
self.assertEqual(picking_client.state, 'assigned')
def test_edit_done_chained_move(self):
""" Let’s say two moves are chained: the first is done and the second is assigned.
Editing the move line of the first move should impact the reservation of the second one.
"""
picking_pick, picking_client = self.create_pick_ship()
location = self.env['stock.location'].browse(self.stock_location)
# make some stock
self.env['stock.quant']._update_available_quantity(self.productA, location, 10.0)
picking_pick.action_assign()
picking_pick.move_lines[0].move_line_ids[0].qty_done = 10.0
picking_pick._action_done()
self.assertEqual(picking_pick.state, 'done', 'The state of the pick should be done')
self.assertEqual(picking_client.state, 'assigned', 'The state of the client should be assigned')
self.assertEqual(picking_pick.move_lines.quantity_done, 10.0, 'Wrong quantity_done for pick move')
self.assertEqual(picking_client.move_lines.product_qty, 10.0, 'Wrong initial demand for client move')
self.assertEqual(picking_client.move_lines.reserved_availability, 10.0, 'Wrong quantity already reserved for client move')
picking_pick.move_lines[0].move_line_ids[0].qty_done = 5.0
self.assertEqual(picking_pick.state, 'done', 'The state of the pick should be done')
self.assertEqual(picking_client.state, 'assigned', 'The state of the client should be partially available')
self.assertEqual(picking_pick.move_lines.quantity_done, 5.0, 'Wrong quantity_done for pick move')
self.assertEqual(picking_client.move_lines.product_qty, 10.0, 'Wrong initial demand for client move')
self.assertEqual(picking_client.move_lines.reserved_availability, 5.0, 'Wrong quantity already reserved for client move')
# Check if run action_assign does not crash
picking_client.action_assign()
def test_edit_done_chained_move_with_lot(self):
""" Let’s say two moves are chained: the first is done and the second is assigned.
Editing the lot on the move line of the first move should impact the reservation of the second one.
"""
self.productA.tracking = 'lot'
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.productA.id,
'company_id': self.env.company.id,
})
lot2 = self.env['stock.production.lot'].create({
'name': 'lot2',
'product_id': self.productA.id,
'company_id': self.env.company.id,
})
picking_pick, picking_client = self.create_pick_ship()
location = self.env['stock.location'].browse(self.stock_location)
# make some stock
self.env['stock.quant']._update_available_quantity(self.productA, location, 10.0)
picking_pick.action_assign()
picking_pick.move_lines[0].move_line_ids[0].write({
'qty_done': 10.0,
'lot_id': lot1.id,
})
picking_pick._action_done()
self.assertEqual(picking_pick.state, 'done', 'The state of the pick should be done')
self.assertEqual(picking_client.state, 'assigned', 'The state of the client should be assigned')
self.assertEqual(picking_pick.move_lines.quantity_done, 10.0, 'Wrong quantity_done for pick move')
self.assertEqual(picking_client.move_lines.product_qty, 10.0, 'Wrong initial demand for client move')
self.assertEqual(picking_client.move_lines.move_line_ids.lot_id, lot1, 'Wrong lot for client move line')
self.assertEqual(picking_client.move_lines.reserved_availability, 10.0, 'Wrong quantity already reserved for client move')
picking_pick.move_lines[0].move_line_ids[0].lot_id = lot2.id
self.assertEqual(picking_pick.state, 'done', 'The state of the pick should be done')
self.assertEqual(picking_client.state, 'assigned', 'The state of the client should be partially available')
self.assertEqual(picking_pick.move_lines.quantity_done, 10.0, 'Wrong quantity_done for pick move')
self.assertEqual(picking_client.move_lines.product_qty, 10.0, 'Wrong initial demand for client move')
self.assertEqual(picking_client.move_lines.move_line_ids.lot_id, lot2, 'Wrong lot for client move line')
self.assertEqual(picking_client.move_lines.reserved_availability, 10.0, 'Wrong quantity already reserved for client move')
# Check if run action_assign does not crash
picking_client.action_assign()
def test_chained_move_with_uom(self):
""" Create pick ship with a different uom than the once used for quant.
Check that reserved quantity and flow work correctly.
"""
picking_client = self.env['stock.picking'].create({
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
'picking_type_id': self.picking_type_out,
})
dest = self.MoveObj.create({
'name': self.gB.name,
'product_id': self.gB.id,
'product_uom_qty': 5,
'product_uom': self.uom_kg.id,
'picking_id': picking_client.id,
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
'state': 'waiting',
})
picking_pick = self.env['stock.picking'].create({
'location_id': self.stock_location,
'location_dest_id': self.pack_location,
'picking_type_id': self.picking_type_out,
})
self.MoveObj.create({
'name': self.gB.name,
'product_id': self.gB.id,
'product_uom_qty': 5,
'product_uom': self.uom_kg.id,
'picking_id': picking_pick.id,
'location_id': self.stock_location,
'location_dest_id': self.pack_location,
'move_dest_ids': [(4, dest.id)],
'state': 'confirmed',
})
location = self.env['stock.location'].browse(self.stock_location)
pack_location = self.env['stock.location'].browse(self.pack_location)
# make some stock
self.env['stock.quant']._update_available_quantity(self.gB, location, 10000.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.gB, pack_location), 0.0)
picking_pick.action_assign()
picking_pick.move_lines[0].move_line_ids[0].qty_done = 5.0
picking_pick._action_done()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.gB, location), 5000.0)
self.assertEqual(self.env['stock.quant']._gather(self.gB, pack_location).quantity, 5000.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.gB, pack_location), 0.0)
self.assertEqual(picking_client.state, 'assigned')
self.assertEqual(picking_client.move_lines.reserved_availability, 5.0)
def test_pick_ship_return(self):
""" Create pick and ship. Bring it ot the customer and then return
it to stock. This test check the state and the quantity after each move in
order to ensure that it is correct.
"""
picking_pick, picking_ship = self.create_pick_ship()
stock_location = self.env['stock.location'].browse(self.stock_location)
pack_location = self.env['stock.location'].browse(self.pack_location)
customer_location = self.env['stock.location'].browse(self.customer_location)
self.productA.tracking = 'lot'
lot = self.env['stock.production.lot'].create({
'product_id': self.productA.id,
'name': '123456789',
'company_id': self.env.company.id,
})
self.env['stock.quant']._update_available_quantity(self.productA, stock_location, 10.0, lot_id=lot)
picking_pick.action_assign()
picking_pick.move_lines[0].move_line_ids[0].qty_done = 10.0
picking_pick._action_done()
self.assertEqual(picking_pick.state, 'done')
self.assertEqual(picking_ship.state, 'assigned')
picking_ship.action_assign()
picking_ship.move_lines[0].move_line_ids[0].qty_done = 10.0
picking_ship._action_done()
customer_quantity = self.env['stock.quant']._get_available_quantity(self.productA, customer_location, lot_id=lot)
self.assertEqual(customer_quantity, 10, 'It should be one product in customer')
""" First we create the return picking for pick pinking.
Since we do not have created the return between customer and
output. This return should not be available and should only have
picking pick as origin move.
"""
stock_return_picking_form = Form(self.env['stock.return.picking']
.with_context(active_ids=picking_pick.ids, active_id=picking_pick.ids[0],
active_model='stock.picking'))
stock_return_picking = stock_return_picking_form.save()
stock_return_picking.product_return_moves.quantity = 10.0
stock_return_picking_action = stock_return_picking.create_returns()
return_pick_picking = self.env['stock.picking'].browse(stock_return_picking_action['res_id'])
self.assertEqual(return_pick_picking.state, 'waiting')
stock_return_picking_form = Form(self.env['stock.return.picking']
.with_context(active_ids=picking_ship.ids, active_id=picking_ship.ids[0],
active_model='stock.picking'))
stock_return_picking = stock_return_picking_form.save()
stock_return_picking.product_return_moves.quantity = 10.0
stock_return_picking_action = stock_return_picking.create_returns()
return_ship_picking = self.env['stock.picking'].browse(stock_return_picking_action['res_id'])
self.assertEqual(return_ship_picking.state, 'assigned', 'Return ship picking should automatically be assigned')
""" We created the return for ship picking. The origin/destination
link between return moves should have been created during return creation.
"""
self.assertTrue(return_ship_picking.move_lines in return_pick_picking.move_lines.mapped('move_orig_ids'),
'The pick return picking\'s moves should have the ship return picking\'s moves as origin')
self.assertTrue(return_pick_picking.move_lines in return_ship_picking.move_lines.mapped('move_dest_ids'),
'The ship return picking\'s moves should have the pick return picking\'s moves as destination')
return_ship_picking.move_lines[0].move_line_ids[0].write({
'qty_done': 10.0,
'lot_id': lot.id,
})
return_ship_picking._action_done()
self.assertEqual(return_ship_picking.state, 'done')
self.assertEqual(return_pick_picking.state, 'assigned')
customer_quantity = self.env['stock.quant']._get_available_quantity(self.productA, customer_location, lot_id=lot)
self.assertEqual(customer_quantity, 0, 'It should be one product in customer')
pack_quantity = self.env['stock.quant']._get_available_quantity(self.productA, pack_location, lot_id=lot)
self.assertEqual(pack_quantity, 0, 'It should be one product in pack location but is reserved')
# Should use previous move lot.
return_pick_picking.move_lines[0].move_line_ids[0].qty_done = 10.0
return_pick_picking._action_done()
self.assertEqual(return_pick_picking.state, 'done')
stock_quantity = self.env['stock.quant']._get_available_quantity(self.productA, stock_location, lot_id=lot)
self.assertEqual(stock_quantity, 10, 'The product is not back in stock')
def test_pick_pack_ship_return(self):
""" This test do a pick pack ship delivery to customer and then
return it to stock. Once everything is done, this test will check
if all the link orgini/destination between moves are correct.
"""
picking_pick, picking_pack, picking_ship = self.create_pick_pack_ship()
stock_location = self.env['stock.location'].browse(self.stock_location)
self.productA.tracking = 'serial'
lot = self.env['stock.production.lot'].create({
'product_id': self.productA.id,
'name': '123456789',
'company_id': self.env.company.id,
})
self.env['stock.quant']._update_available_quantity(self.productA, stock_location, 1.0, lot_id=lot)
picking_pick.action_assign()
picking_pick.move_lines[0].move_line_ids[0].qty_done = 1.0
picking_pick._action_done()
picking_pack.action_assign()
picking_pack.move_lines[0].move_line_ids[0].qty_done = 1.0
picking_pack._action_done()
picking_ship.action_assign()
picking_ship.move_lines[0].move_line_ids[0].qty_done = 1.0
picking_ship._action_done()
stock_return_picking_form = Form(self.env['stock.return.picking']
.with_context(active_ids=picking_ship.ids, active_id=picking_ship.ids[0],
active_model='stock.picking'))
stock_return_picking = stock_return_picking_form.save()
stock_return_picking.product_return_moves.quantity = 1.0
stock_return_picking_action = stock_return_picking.create_returns()
return_ship_picking = self.env['stock.picking'].browse(stock_return_picking_action['res_id'])
return_ship_picking.move_lines[0].move_line_ids[0].write({
'qty_done': 1.0,
'lot_id': lot.id,
})
return_ship_picking._action_done()
stock_return_picking_form = Form(self.env['stock.return.picking']
.with_context(active_ids=picking_pack.ids, active_id=picking_pack.ids[0],
active_model='stock.picking'))
stock_return_picking = stock_return_picking_form.save()
stock_return_picking.product_return_moves.quantity = 1.0
stock_return_picking_action = stock_return_picking.create_returns()
return_pack_picking = self.env['stock.picking'].browse(stock_return_picking_action['res_id'])
return_pack_picking.move_lines[0].move_line_ids[0].qty_done = 1.0
return_pack_picking._action_done()
stock_return_picking_form = Form(self.env['stock.return.picking']
.with_context(active_ids=picking_pick.ids, active_id=picking_pick.ids[0],
active_model='stock.picking'))
stock_return_picking = stock_return_picking_form.save()
stock_return_picking.product_return_moves.quantity = 1.0
stock_return_picking_action = stock_return_picking.create_returns()
return_pick_picking = self.env['stock.picking'].browse(stock_return_picking_action['res_id'])
return_pick_picking.move_lines[0].move_line_ids[0].qty_done = 1.0
return_pick_picking._action_done()
# Now that everything is returned we will check if the return moves are correctly linked between them.
# +--------------------------------------------------------------------------------------------------------+
# | -- picking_pick(1) --> -- picking_pack(2) --> -- picking_ship(3) -->
# | Stock Pack Output Customer
# | <--- return pick(6) -- <--- return pack(5) -- <--- return ship(4) --
# +--------------------------------------------------------------------------------------------------------+
# Recaps of final link (MO = move_orig_ids, MD = move_dest_ids)
# picking_pick(1) : MO = (), MD = (2,6)
# picking_pack(2) : MO = (1), MD = (3,5)
# picking ship(3) : MO = (2), MD = (4)
# return ship(4) : MO = (3), MD = (5)
# return pack(5) : MO = (2, 4), MD = (6)
# return pick(6) : MO = (1, 5), MD = ()
self.assertEqual(len(picking_pick.move_lines.move_orig_ids), 0, 'Picking pick should not have origin moves')
self.assertEqual(set(picking_pick.move_lines.move_dest_ids.ids), set((picking_pack.move_lines | return_pick_picking.move_lines).ids))
self.assertEqual(set(picking_pack.move_lines.move_orig_ids.ids), set(picking_pick.move_lines.ids))
self.assertEqual(set(picking_pack.move_lines.move_dest_ids.ids), set((picking_ship.move_lines | return_pack_picking.move_lines).ids))
self.assertEqual(set(picking_ship.move_lines.move_orig_ids.ids), set(picking_pack.move_lines.ids))
self.assertEqual(set(picking_ship.move_lines.move_dest_ids.ids), set(return_ship_picking.move_lines.ids))
self.assertEqual(set(return_ship_picking.move_lines.move_orig_ids.ids), set(picking_ship.move_lines.ids))
self.assertEqual(set(return_ship_picking.move_lines.move_dest_ids.ids), set(return_pack_picking.move_lines.ids))
self.assertEqual(set(return_pack_picking.move_lines.move_orig_ids.ids), set((picking_pack.move_lines | return_ship_picking.move_lines).ids))
self.assertEqual(set(return_pack_picking.move_lines.move_dest_ids.ids), set(return_pick_picking.move_lines.ids))
self.assertEqual(set(return_pick_picking.move_lines.move_orig_ids.ids), set((picking_pick.move_lines | return_pack_picking.move_lines).ids))
self.assertEqual(len(return_pick_picking.move_lines.move_dest_ids), 0)
def test_merge_move_mto_mts(self):
""" Create 2 moves of the same product in the same picking with
one in 'MTO' and the other one in 'MTS'. The moves shouldn't be merged
"""
picking_pick, picking_client = self.create_pick_ship()
self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 3,
'product_uom': self.productA.uom_id.id,
'picking_id': picking_client.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
'origin': 'MPS',
'procure_method': 'make_to_stock',
})
picking_client.action_confirm()
self.assertEqual(len(picking_client.move_lines), 2, 'Moves should not be merged')
def test_mto_cancel_move_line(self):
""" Create a pick ship situation. Then process the pick picking
with a backorder. Then try to unlink the move line created on
the ship and check if the picking and move state are updated.
Then validate the backorder and unlink the ship move lines in
order to check again if the picking and state are updated.
"""
picking_pick, picking_client = self.create_pick_ship()
location = self.env['stock.location'].browse(self.stock_location)
# make some stock
self.env['stock.quant']._update_available_quantity(self.productA, location, 10.0)
picking_pick.move_lines.quantity_done = 5.0
backorder_wizard_values = picking_pick.button_validate()
backorder_wizard = self.env[(backorder_wizard_values.get('res_model'))].browse(backorder_wizard_values.get('res_id')).with_context(backorder_wizard_values['context'])
backorder_wizard.process()
self.assertTrue(picking_client.move_line_ids, 'A move line should be created.')
self.assertEqual(picking_client.move_line_ids.product_uom_qty, 5, 'The move line should have 5 unit reserved.')
# Directly delete the move lines on the picking. (Use show detail operation on picking type)
# Should do the same behavior than unreserve
picking_client.move_line_ids.unlink()
self.assertEqual(picking_client.move_lines.state, 'waiting', 'The move state should be waiting since nothing is reserved and another origin move still in progess.')
self.assertEqual(picking_client.state, 'waiting', 'The picking state should not be ready anymore.')
picking_client.action_assign()
back_order = self.env['stock.picking'].search([('backorder_id', '=', picking_pick.id)])
back_order.move_lines.quantity_done = 5
back_order.button_validate()
self.assertEqual(picking_client.move_lines.reserved_availability, 10, 'The total quantity should be reserved since everything is available.')
picking_client.move_line_ids.unlink()
self.assertEqual(picking_client.move_lines.state, 'confirmed', 'The move should be confirmed since all the origin moves are processed.')
self.assertEqual(picking_client.state, 'confirmed', 'The picking should be confirmed since all the moves are confirmed.')
def test_unreserve(self):
picking_pick, picking_client = self.create_pick_ship()
self.assertEqual(picking_pick.state, 'confirmed')
picking_pick.do_unreserve()
self.assertEqual(picking_pick.state, 'confirmed')
location = self.env['stock.location'].browse(self.stock_location)
self.env['stock.quant']._update_available_quantity(self.productA, location, 10.0)
picking_pick.action_assign()
self.assertEqual(picking_pick.state, 'assigned')
picking_pick.do_unreserve()
self.assertEqual(picking_pick.state, 'confirmed')
self.assertEqual(picking_client.state, 'waiting')
picking_client.do_unreserve()
self.assertEqual(picking_client.state, 'waiting')
def test_return_location(self):
""" In a pick ship scenario, send two items to the customer, then return one in the ship
location and one in a return location that is located in another warehouse.
"""
pick_location = self.env['stock.location'].browse(self.stock_location)
pick_location.return_location = True
return_warehouse = self.env['stock.warehouse'].create({'name': 'return warehouse', 'code': 'rw'})
return_location = self.env['stock.location'].create({
'name': 'return internal',
'usage': 'internal',
'location_id': return_warehouse.view_location_id.id
})
self.env['stock.quant']._update_available_quantity(self.productA, pick_location, 10.0)
picking_pick, picking_client = self.create_pick_ship()
# send the items to the customer
picking_pick.action_assign()
picking_pick.move_lines[0].move_line_ids[0].qty_done = 10.0
picking_pick._action_done()
picking_client.move_lines[0].move_line_ids[0].qty_done = 10.0
picking_client._action_done()
# return half in the pick location
stock_return_picking_form = Form(self.env['stock.return.picking']
.with_context(active_ids=picking_client.ids, active_id=picking_client.ids[0],
active_model='stock.picking'))
return1 = stock_return_picking_form.save()
return1.product_return_moves.quantity = 5.0
return1.location_id = pick_location.id
return_to_pick_picking_action = return1.create_returns()
return_to_pick_picking = self.env['stock.picking'].browse(return_to_pick_picking_action['res_id'])
return_to_pick_picking.move_lines[0].move_line_ids[0].qty_done = 5.0
return_to_pick_picking._action_done()
# return the remainig products in the return warehouse
stock_return_picking_form = Form(self.env['stock.return.picking']
.with_context(active_ids=picking_client.ids, active_id=picking_client.ids[0],
active_model='stock.picking'))
return2 = stock_return_picking_form.save()
return2.product_return_moves.quantity = 5.0
return2.location_id = return_location.id
return_to_return_picking_action = return2.create_returns()
return_to_return_picking = self.env['stock.picking'].browse(return_to_return_picking_action['res_id'])
return_to_return_picking.move_lines[0].move_line_ids[0].qty_done = 5.0
return_to_return_picking._action_done()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.productA, pick_location), 5.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.productA, return_location), 5.0)
self.assertEqual(len(self.env['stock.quant'].search([('product_id', '=', self.productA.id), ('quantity', '!=', 0)])), 2)
def test_return_lot(self):
""" With two distinct deliveries for the same product tracked by lot, ensure that the
return of the second picking suggest the lot from the picking returned.
"""
self.productA.tracking = 'lot'
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.productA.id,
'company_id': self.env.company.id,
})
lot2 = self.env['stock.production.lot'].create({
'name': 'lot2',
'product_id': self.productA.id,
'company_id': self.env.company.id,
})
lot3 = self.env['stock.production.lot'].create({
'name': 'lot3',
'product_id': self.productA.id,
'company_id': self.env.company.id,
})
stock_location = self.env['stock.location'].browse(self.stock_location)
self.env['stock.quant']._update_available_quantity(self.productA, stock_location, 7.0, lot_id=lot1)
self.env['stock.quant']._update_available_quantity(self.productA, stock_location, 7.0, lot_id=lot2)
self.env['stock.quant']._update_available_quantity(self.productA, stock_location, 7.0, lot_id=lot3)
picking_pick, picking_client = self.create_pick_ship()
picking_pick.action_confirm()
picking_pick.action_assign()
for move_line in picking_pick.move_line_ids:
move_line.qty_done = move_line.product_uom_qty
picking_pick._action_done()
picking_client.action_confirm()
picking_client.action_assign()
for move_line in picking_client.move_line_ids:
move_line.qty_done = move_line.product_uom_qty
picking_client._action_done()
picking_pick, picking_client = self.create_pick_ship()
picking_pick.action_confirm()
picking_pick.action_assign()
for move_line in picking_pick.move_line_ids:
move_line.qty_done = move_line.product_uom_qty
picking_pick._action_done()
picking_client.action_confirm()
picking_client.action_assign()
for move_line in picking_client.move_line_ids:
move_line.qty_done = move_line.product_uom_qty
picking_client._action_done()
# Following FIFO strategy, First picking should have empty lot1 and took 3 of lot2.
# So the second picking contains 4 lot2 and 6 lot3
self.assertEqual(picking_client.move_line_ids[0].lot_id, lot2)
self.assertEqual(picking_client.move_line_ids[0].qty_done, 4)
self.assertEqual(picking_client.move_line_ids[1].lot_id, lot3)
self.assertEqual(picking_client.move_line_ids[1].qty_done, 6)
stock_return_picking_form = Form(self.env['stock.return.picking'].with_context(
active_ids=picking_client.ids, active_id=picking_client.ids[0], active_model='stock.picking'))
stock_return_picking = stock_return_picking_form.save()
stock_return_picking.product_return_moves.quantity = 10.0
return_pick = self.env['stock.picking'].browse(stock_return_picking.create_returns()['res_id'])
self.assertEqual(len(return_pick.move_line_ids), 2)
self.assertEqual(return_pick.move_line_ids[0].lot_id, lot2)
self.assertEqual(return_pick.move_line_ids[0].product_uom_qty, 4)
self.assertEqual(return_pick.move_line_ids[1].lot_id, lot3)
self.assertEqual(return_pick.move_line_ids[1].product_uom_qty, 6)
self.assertEqual(return_pick.picking_type_id, picking_client.location_id.warehouse_id.return_type_id)
class TestSinglePicking(TestStockCommon):
def test_backorder_1(self):
""" Check the good behavior of creating a backorder for an available stock move.
"""
delivery_order = self.env['stock.picking'].create({
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
'picking_type_id': self.picking_type_out,
})
self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 2,
'product_uom': self.productA.uom_id.id,
'picking_id': delivery_order.id,
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
})
# make some stock
pack_location = self.env['stock.location'].browse(self.pack_location)
self.env['stock.quant']._update_available_quantity(self.productA, pack_location, 2)
# assign
delivery_order.action_confirm()
delivery_order.action_assign()
self.assertEqual(delivery_order.state, 'assigned')
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.productA, pack_location), 0.0)
# valid with backorder creation
delivery_order.move_lines[0].move_line_ids[0].qty_done = 1
delivery_order._action_done()
self.assertNotEqual(delivery_order.date_done, False)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.productA, pack_location), 1.0)
backorder = self.env['stock.picking'].search([('backorder_id', '=', delivery_order.id)])
self.assertEqual(backorder.state, 'confirmed')
backorder.action_assign()
self.assertEqual(backorder.state, 'assigned')
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.productA, pack_location), 0.0)
def test_backorder_2(self):
""" Check the good behavior of creating a backorder for a partially available stock move.
"""
delivery_order = self.env['stock.picking'].create({
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
'picking_type_id': self.picking_type_out,
})
self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 2,
'product_uom': self.productA.uom_id.id,
'picking_id': delivery_order.id,
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
})
# make some stock
pack_location = self.env['stock.location'].browse(self.pack_location)
self.env['stock.quant']._update_available_quantity(self.productA, pack_location, 1)
# assign to partially available
delivery_order.action_confirm()
delivery_order.action_assign()
self.assertEqual(delivery_order.state, 'assigned')
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.productA, pack_location), 0.0)
# valid with backorder creation
delivery_order.move_lines[0].move_line_ids[0].qty_done = 1
delivery_order._action_done()
self.assertNotEqual(delivery_order.date_done, False)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.productA, pack_location), 0.0)
backorder = self.env['stock.picking'].search([('backorder_id', '=', delivery_order.id)])
self.assertEqual(backorder.state, 'confirmed')
def test_backorder_3(self):
""" Check the good behavior of creating a backorder for an available move on a picking with
two available moves.
"""
delivery_order = self.env['stock.picking'].create({
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
'picking_type_id': self.picking_type_out,
})
self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 2,
'product_uom': self.productA.uom_id.id,
'picking_id': delivery_order.id,
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
})
self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productB.id,
'product_uom_qty': 2,
'product_uom': self.productB.uom_id.id,
'picking_id': delivery_order.id,
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
})
# make some stock
pack_location = self.env['stock.location'].browse(self.pack_location)
self.env['stock.quant']._update_available_quantity(self.productA, pack_location, 2)
self.env['stock.quant']._update_available_quantity(self.productA, pack_location, 2)
# assign to partially available
delivery_order.action_confirm()
delivery_order.action_assign()
self.assertEqual(delivery_order.state, 'assigned')
delivery_order.move_lines[0].move_line_ids[0].qty_done = 2
delivery_order._action_done()
backorder = self.env['stock.picking'].search([('backorder_id', '=', delivery_order.id)])
self.assertEqual(backorder.state, 'confirmed')
def test_backorder_4(self):
""" Check the good behavior if no backorder are created
for a picking with a missing product.
"""
delivery_order = self.env['stock.picking'].create({
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
'picking_type_id': self.picking_type_out,
})
self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 2,
'product_uom': self.productA.uom_id.id,
'picking_id': delivery_order.id,
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
})
self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productB.id,
'product_uom_qty': 2,
'product_uom': self.productB.uom_id.id,
'picking_id': delivery_order.id,
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
})
# Update available quantities for each products
pack_location = self.env['stock.location'].browse(self.pack_location)
self.env['stock.quant']._update_available_quantity(self.productA, pack_location, 2)
self.env['stock.quant']._update_available_quantity(self.productB, pack_location, 2)
delivery_order.action_confirm()
delivery_order.action_assign()
self.assertEqual(delivery_order.state, 'assigned')
# Process only one product without creating a backorder
delivery_order.move_lines[0].move_line_ids[0].qty_done = 2
res_dict = delivery_order.button_validate()
backorder_wizard = Form(self.env['stock.backorder.confirmation'].with_context(res_dict['context'])).save()
backorder_wizard.process_cancel_backorder()
# No backorder should be created and the move corresponding to the missing product should be cancelled
backorder = self.env['stock.picking'].search([('backorder_id', '=', delivery_order.id)])
self.assertFalse(backorder)
self.assertEqual(delivery_order.state, 'done')
self.assertEqual(delivery_order.move_lines[1].state, 'cancel')
def test_assign_deadline(self):
""" Check if similar items with shorter deadline are prioritized. """
delivery_order = self.PickingObj.create({
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
'picking_type_id': self.picking_type_out,
})
# Avoid to merge move3 and move4 for the test case
self.env['ir.config_parameter'].create({
'key': 'stock.merge_only_same_date',
'value': True
})
move1 = self.MoveObj.create({
'name': "move1",
'product_id': self.productA.id,
'product_uom_qty': 4,
'product_uom': self.productA.uom_id.id,
'picking_id': delivery_order.id,
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
'date_deadline': datetime.now() + relativedelta(days=1)
})
move2 = self.MoveObj.create({
'name': "move2",
'product_id': self.productA.id,
'product_uom_qty': 4,
'product_uom': self.productA.uom_id.id,
'picking_id': delivery_order.id,
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
'date_deadline': datetime.now() + relativedelta(days=2)
})
move3 = self.MoveObj.create({
'name': "move3",
'product_id': self.productA.id,
'product_uom_qty': 1,
'product_uom': self.productA.uom_id.id,
'picking_id': delivery_order.id,
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
'date': datetime.now() + relativedelta(days=10)
})
move4 = self.MoveObj.create({
'name': "move4",
'product_id': self.productA.id,
'product_uom_qty': 1,
'product_uom': self.productA.uom_id.id,
'picking_id': delivery_order.id,
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
'date': datetime.now() + relativedelta(days=0)
})
# make some stock
pack_location = self.env['stock.location'].browse(self.pack_location)
self.StockQuantObj._update_available_quantity(self.productA, pack_location, 2)
# assign to partially available
delivery_order.action_confirm()
delivery_order.action_assign()
self.assertEqual(move1.reserved_availability, 2, "Earlier deadline should have reserved quantity")
self.assertEqual(move2.reserved_availability, 0, "Later deadline should not have reserved quantity")
# add new stock
self.StockQuantObj._update_available_quantity(self.productA, pack_location, 2)
delivery_order.action_assign()
self.assertEqual(move1.reserved_availability, 4, "Earlier deadline should have reserved quantity")
self.assertEqual(move2.reserved_availability, 0, "Later deadline should not have reserved quantity")
self.StockQuantObj._update_available_quantity(self.productA, pack_location, 1)
delivery_order.action_assign()
self.assertEqual(move1.reserved_availability, 4, "Earlier deadline should have reserved quantity")
self.assertEqual(move2.reserved_availability, 1, "Move with deadline should take priority")
self.assertEqual(move3.reserved_availability, 0, "Move without deadline should not have reserved quantity")
self.assertEqual(move4.reserved_availability, 0, "Move without deadline should not have reserved quantity")
self.StockQuantObj._update_available_quantity(self.productA, pack_location, 4)
delivery_order.action_assign()
self.assertEqual(move1.reserved_availability, 4, "Earlier deadline should have reserved quantity")
self.assertEqual(move2.reserved_availability, 4, "Move with deadline should take priority")
self.assertEqual(move3.reserved_availability, 0, "Latest move without deadline should not have reserved quantity")
self.assertEqual(move4.reserved_availability, 1, "Earlier move without deadline should take the priority")
def test_extra_move_1(self):
""" Check the good behavior of creating an extra move in a delivery order. This usecase
simulates the delivery of 2 item while the initial stock move had to move 1 and there's
only 1 in stock.
"""
delivery_order = self.env['stock.picking'].create({
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
'picking_type_id': self.picking_type_out,
})
move1 = self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 1,
'product_uom': self.productA.uom_id.id,
'picking_id': delivery_order.id,
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
})
# make some stock
pack_location = self.env['stock.location'].browse(self.pack_location)
self.env['stock.quant']._update_available_quantity(self.productA, pack_location, 1)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.productA, pack_location), 1.0)
# assign to available
delivery_order.action_confirm()
delivery_order.action_assign()
self.assertEqual(delivery_order.state, 'assigned')
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.productA, pack_location), 0.0)
# valid with backorder creation
delivery_order.move_lines[0].move_line_ids[0].qty_done = 2
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.productA, pack_location), 0.0)
delivery_order._action_done()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.productA, pack_location), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.productA, pack_location, allow_negative=True), -1.0)
self.assertEqual(move1.product_qty, 2.0)
self.assertEqual(move1.quantity_done, 2.0)
self.assertEqual(move1.reserved_availability, 0.0)
self.assertEqual(move1.move_line_ids.product_qty, 0.0) # change reservation to 0 for done move
self.assertEqual(sum(move1.move_line_ids.mapped('qty_done')), 2.0)
self.assertEqual(move1.state, 'done')
def test_extra_move_2(self):
""" Check the good behavior of creating an extra move in a delivery order. This usecase
simulates the delivery of 3 item while the initial stock move had to move 1 and there's
only 1 in stock.
"""
delivery_order = self.env['stock.picking'].create({
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
'picking_type_id': self.picking_type_out,
})
move1 = self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 1,
'product_uom': self.productA.uom_id.id,
'picking_id': delivery_order.id,
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
})
# make some stock
pack_location = self.env['stock.location'].browse(self.pack_location)
self.env['stock.quant']._update_available_quantity(self.productA, pack_location, 1)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.productA, pack_location), 1.0)
# assign to available
delivery_order.action_confirm()
delivery_order.action_assign()
self.assertEqual(delivery_order.state, 'assigned')
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.productA, pack_location), 0.0)
# valid with backorder creation
delivery_order.move_lines[0].move_line_ids[0].qty_done = 3
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.productA, pack_location), 0.0)
delivery_order._action_done()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.productA, pack_location), 0.0)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.productA, pack_location, allow_negative=True), -2.0)
self.assertEqual(move1.product_qty, 3.0)
self.assertEqual(move1.quantity_done, 3.0)
self.assertEqual(move1.reserved_availability, 0.0)
self.assertEqual(move1.move_line_ids.product_qty, 0.0) # change reservation to 0 for done move
self.assertEqual(sum(move1.move_line_ids.mapped('qty_done')), 3.0)
self.assertEqual(move1.state, 'done')
def test_extra_move_3(self):
""" Check the good behavior of creating an extra move in a receipt. This usecase simulates
the receipt of 2 item while the initial stock move had to move 1.
"""
receipt = self.env['stock.picking'].create({
'location_id': self.supplier_location,
'location_dest_id': self.stock_location,
'picking_type_id': self.picking_type_in,
})
move1 = self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 1,
'product_uom': self.productA.uom_id.id,
'picking_id': receipt.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location,
})
stock_location = self.env['stock.location'].browse(self.stock_location)
# assign to available
receipt.action_confirm()
receipt.action_assign()
self.assertEqual(receipt.state, 'assigned')
# valid with backorder creation
receipt.move_lines[0].move_line_ids[0].qty_done = 2
receipt._action_done()
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.productA, stock_location), 2.0)
self.assertEqual(move1.product_qty, 2.0)
self.assertEqual(move1.quantity_done, 2.0)
self.assertEqual(move1.reserved_availability, 0.0)
self.assertEqual(move1.move_line_ids.product_qty, 0.0) # change reservation to 0 for done move
self.assertEqual(sum(move1.move_line_ids.mapped('qty_done')), 2.0)
self.assertEqual(move1.state, 'done')
def test_extra_move_4(self):
""" Create a picking with similar moves (created after
confirmation). Action done should propagate all the extra
quantity and only merge extra moves in their original moves.
"""
delivery = self.env['stock.picking'].create({
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
'picking_type_id': self.picking_type_out,
})
self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 5,
'quantity_done': 10,
'product_uom': self.productA.uom_id.id,
'picking_id': delivery.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
})
stock_location = self.env['stock.location'].browse(self.stock_location)
self.env['stock.quant']._update_available_quantity(self.productA, stock_location, 5)
delivery.action_confirm()
delivery.action_assign()
delivery.write({
'move_lines': [(0, 0, {
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 0,
'quantity_done': 10,
'state': 'assigned',
'product_uom': self.productA.uom_id.id,
'picking_id': delivery.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
})]
})
delivery._action_done()
self.assertEqual(len(delivery.move_lines), 2, 'Move should not be merged together')
for move in delivery.move_lines:
self.assertEqual(move.quantity_done, move.product_uom_qty, 'Initial demand should be equals to quantity done')
def test_extra_move_5(self):
""" Create a picking a move that is problematic with
rounding (5.95 - 5.5 = 0.4500000000000002). Ensure that
initial demand is corrct afer action_done and backoder
are not created.
"""
delivery = self.env['stock.picking'].create({
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
'picking_type_id': self.picking_type_out,
})
product = self.kgB
self.MoveObj.create({
'name': product.name,
'product_id': product.id,
'product_uom_qty': 5.5,
'quantity_done': 5.95,
'product_uom': product.uom_id.id,
'picking_id': delivery.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
})
stock_location = self.env['stock.location'].browse(self.stock_location)
self.env['stock.quant']._update_available_quantity(product, stock_location, 5.5)
delivery.action_confirm()
delivery.action_assign()
delivery._action_done()
self.assertEqual(delivery.move_lines.product_uom_qty, 5.95, 'Move initial demand should be 5.95')
back_order = self.env['stock.picking'].search([('backorder_id', '=', delivery.id)])
self.assertFalse(back_order, 'There should be no back order')
def test_recheck_availability_1(self):
""" Check the good behavior of check availability. I create a DO for 2 unit with
only one in stock. After the first check availability, I should have 1 reserved
product with one move line. After adding a second unit in stock and recheck availability.
The DO should have 2 reserved unit, be in available state and have only one move line.
"""
self.env['stock.quant']._update_available_quantity(self.productA, self.env['stock.location'].browse(self.stock_location), 1.0)
delivery_order = self.env['stock.picking'].create({
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
'picking_type_id': self.picking_type_out,
})
move1 = self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 2,
'product_uom': self.productA.uom_id.id,
'picking_id': delivery_order.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
})
delivery_order.action_confirm()
delivery_order.action_assign()
# Check State
self.assertEqual(delivery_order.state, 'assigned')
self.assertEqual(move1.state, 'partially_available')
# Check reserved quantity
self.assertEqual(move1.reserved_availability, 1.0)
self.assertEqual(len(move1.move_line_ids), 1)
self.assertEqual(move1.move_line_ids.product_qty, 1)
inventory_quant = self.env['stock.quant'].create({
'location_id': self.stock_location,
'product_id': self.productA.id,
'inventory_quantity': 2
})
inventory_quant.action_apply_inventory()
delivery_order.action_assign()
self.assertEqual(delivery_order.state, 'assigned')
self.assertEqual(move1.state, 'assigned')
# Check reserved quantity
self.assertEqual(move1.reserved_availability, 2.0)
self.assertEqual(len(move1.move_line_ids), 1)
self.assertEqual(move1.move_line_ids.product_qty, 2)
def test_recheck_availability_2(self):
""" Same check than test_recheck_availability_1 but with lot this time.
If the new product has the same lot that already reserved one, the move lines
reserved quantity should be updated.
Otherwise a new move lines with the new lot should be added.
"""
self.productA.tracking = 'lot'
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.productA.id,
'company_id': self.env.company.id,
})
stock_location = self.env['stock.location'].browse(self.stock_location)
self.env['stock.quant']._update_available_quantity(self.productA, stock_location, 1.0, lot_id=lot1)
delivery_order = self.env['stock.picking'].create({
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
'picking_type_id': self.picking_type_out,
})
move1 = self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 2,
'product_uom': self.productA.uom_id.id,
'picking_id': delivery_order.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
})
delivery_order.action_confirm()
delivery_order.action_assign()
# Check State
self.assertEqual(delivery_order.state, 'assigned')
self.assertEqual(move1.state, 'partially_available')
# Check reserved quantity
self.assertEqual(move1.reserved_availability, 1.0)
self.assertEqual(len(move1.move_line_ids), 1)
self.assertEqual(move1.move_line_ids.product_qty, 1)
inventory_quant = self.env['stock.quant'].create({
'location_id': self.stock_location,
'product_id': self.productA.id,
'inventory_quantity': 2,
'lot_id': lot1.id
})
inventory_quant.action_apply_inventory()
delivery_order.action_assign()
self.assertEqual(delivery_order.state, 'assigned')
self.assertEqual(move1.state, 'assigned')
# Check reserved quantity
self.assertEqual(move1.reserved_availability, 2.0)
self.assertEqual(len(move1.move_line_ids), 1)
self.assertEqual(move1.move_line_ids.lot_id.id, lot1.id)
self.assertEqual(move1.move_line_ids.product_qty, 2)
def test_recheck_availability_3(self):
""" Same check than test_recheck_availability_2 but with different lots.
"""
self.productA.tracking = 'lot'
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.productA.id,
'company_id': self.env.company.id,
})
lot2 = self.env['stock.production.lot'].create({
'name': 'lot2',
'product_id': self.productA.id,
'company_id': self.env.company.id,
})
stock_location = self.env['stock.location'].browse(self.stock_location)
self.env['stock.quant']._update_available_quantity(self.productA, stock_location, 1.0, lot_id=lot1)
delivery_order = self.env['stock.picking'].create({
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
'picking_type_id': self.picking_type_out,
})
move1 = self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 2,
'product_uom': self.productA.uom_id.id,
'picking_id': delivery_order.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
})
delivery_order.action_confirm()
delivery_order.action_assign()
# Check State
self.assertEqual(delivery_order.state, 'assigned')
self.assertEqual(move1.state, 'partially_available')
# Check reserved quantity
self.assertEqual(move1.reserved_availability, 1.0)
self.assertEqual(len(move1.move_line_ids), 1)
self.assertEqual(move1.move_line_ids.product_qty, 1)
inventory_quant = self.env['stock.quant'].create({
'location_id': self.stock_location,
'product_id': self.productA.id,
'inventory_quantity': 1,
'lot_id': lot2.id
})
inventory_quant.action_apply_inventory()
delivery_order.action_assign()
self.assertEqual(delivery_order.state, 'assigned')
self.assertEqual(move1.state, 'assigned')
# Check reserved quantity
self.assertEqual(move1.reserved_availability, 2.0)
self.assertEqual(len(move1.move_line_ids), 2)
move_lines = move1.move_line_ids.sorted()
self.assertEqual(move_lines[0].lot_id.id, lot1.id)
self.assertEqual(move_lines[1].lot_id.id, lot2.id)
def test_recheck_availability_4(self):
""" Same check than test_recheck_availability_2 but with serial number this time.
Serial number reservation should always create a new move line.
"""
self.productA.tracking = 'serial'
serial1 = self.env['stock.production.lot'].create({
'name': 'serial1',
'product_id': self.productA.id,
'company_id': self.env.company.id,
})
serial2 = self.env['stock.production.lot'].create({
'name': 'serial2',
'product_id': self.productA.id,
'company_id': self.env.company.id,
})
stock_location = self.env['stock.location'].browse(self.stock_location)
self.env['stock.quant']._update_available_quantity(self.productA, stock_location, 1.0, lot_id=serial1)
delivery_order = self.env['stock.picking'].create({
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
'picking_type_id': self.picking_type_out,
})
move1 = self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 2,
'product_uom': self.productA.uom_id.id,
'picking_id': delivery_order.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
})
delivery_order.action_confirm()
delivery_order.action_assign()
# Check State
self.assertEqual(delivery_order.state, 'assigned')
self.assertEqual(move1.state, 'partially_available')
# Check reserved quantity
self.assertEqual(move1.reserved_availability, 1.0)
self.assertEqual(len(move1.move_line_ids), 1)
self.assertEqual(move1.move_line_ids.product_qty, 1)
inventory_quant = self.env['stock.quant'].create({
'location_id': self.stock_location,
'product_id': self.productA.id,
'inventory_quantity': 1,
'lot_id': serial2.id
})
inventory_quant.action_apply_inventory()
delivery_order.action_assign()
self.assertEqual(delivery_order.state, 'assigned')
self.assertEqual(move1.state, 'assigned')
# Check reserved quantity
self.assertEqual(move1.reserved_availability, 2.0)
self.assertEqual(len(move1.move_line_ids), 2)
move_lines = move1.move_line_ids.sorted()
self.assertEqual(move_lines[0].lot_id.id, serial1.id)
self.assertEqual(move_lines[1].lot_id.id, serial2.id)
def test_use_create_lot_use_existing_lot_1(self):
""" Check the behavior of a picking when `use_create_lot` and `use_existing_lot` are
set to False and there's a move for a tracked product.
"""
self.env['stock.picking.type']\
.browse(self.picking_type_out)\
.write({
'use_create_lots': False,
'use_existing_lots': False,
})
self.productA.tracking = 'lot'
delivery_order = self.env['stock.picking'].create({
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
'picking_type_id': self.picking_type_out,
})
self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 2,
'product_uom': self.productA.uom_id.id,
'picking_id': delivery_order.id,
'picking_type_id': self.picking_type_out,
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
})
delivery_order.action_confirm()
delivery_order.move_lines.quantity_done = 2
# do not set a lot_id or lot_name, it should work
delivery_order._action_done()
def test_use_create_lot_use_existing_lot_2(self):
""" Check the behavior of a picking when `use_create_lot` and `use_existing_lot` are
set to True and there's a move for a tracked product.
"""
self.env['stock.picking.type']\
.browse(self.picking_type_out)\
.write({
'use_create_lots': True,
'use_existing_lots': True,
})
self.productA.tracking = 'lot'
delivery_order = self.env['stock.picking'].create({
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
'picking_type_id': self.picking_type_out,
})
self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 2,
'product_uom': self.productA.uom_id.id,
'picking_id': delivery_order.id,
'picking_type_id': self.picking_type_out,
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
})
delivery_order.action_confirm()
delivery_order.move_lines.quantity_done = 2
move_line = delivery_order.move_lines.move_line_ids
# not lot_name set, should raise
with self.assertRaises(UserError):
delivery_order._action_done()
# enter a new lot name, should work
move_line.lot_name = 'newlot'
delivery_order._action_done()
def test_use_create_lot_use_existing_lot_3(self):
""" Check the behavior of a picking when `use_create_lot` is set to True and
`use_existing_lot` is set to False and there's a move for a tracked product.
"""
self.env['stock.picking.type']\
.browse(self.picking_type_out)\
.write({
'use_create_lots': True,
'use_existing_lots': False,
})
self.productA.tracking = 'lot'
delivery_order = self.env['stock.picking'].create({
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
'picking_type_id': self.picking_type_out,
})
self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 2,
'product_uom': self.productA.uom_id.id,
'picking_id': delivery_order.id,
'picking_type_id': self.picking_type_out,
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
})
delivery_order.action_confirm()
delivery_order.move_lines.quantity_done = 2
move_line = delivery_order.move_lines.move_line_ids
# not lot_name set, should raise
with self.assertRaises(UserError):
delivery_order._action_done()
# enter a new lot name, should work
move_line.lot_name = 'newlot'
delivery_order._action_done()
def test_use_create_lot_use_existing_lot_4(self):
""" Check the behavior of a picking when `use_create_lot` is set to False and
`use_existing_lot` is set to True and there's a move for a tracked product.
"""
self.env['stock.picking.type']\
.browse(self.picking_type_out)\
.write({
'use_create_lots': False,
'use_existing_lots': True,
})
self.productA.tracking = 'lot'
delivery_order = self.env['stock.picking'].create({
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
'picking_type_id': self.picking_type_out,
})
self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 2,
'product_uom': self.productA.uom_id.id,
'picking_id': delivery_order.id,
'picking_type_id': self.picking_type_out,
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
})
delivery_order.action_confirm()
delivery_order.move_lines.quantity_done = 2
move_line = delivery_order.move_lines.move_line_ids
# not lot_name set, should raise
with self.assertRaises(UserError):
delivery_order._action_done()
# creating a lot from the view should raise
with self.assertRaises(UserError):
self.env['stock.production.lot']\
.with_context(active_picking_id=delivery_order.id)\
.create({
'name': 'lot1',
'product_id': self.productA.id,
'company_id': self.env.company.id,
})
# enter an existing lot_id, should work
lot1 = self.env['stock.production.lot'].create({
'name': 'lot1',
'product_id': self.productA.id,
'company_id': self.env.company.id,
})
move_line.lot_id = lot1
delivery_order._action_done()
def test_merge_moves_1(self):
receipt = self.env['stock.picking'].create({
'location_id': self.supplier_location,
'location_dest_id': self.stock_location,
'picking_type_id': self.picking_type_in,
})
self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 3,
'product_uom': self.productA.uom_id.id,
'picking_id': receipt.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location,
})
self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 5,
'product_uom': self.productA.uom_id.id,
'picking_id': receipt.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location,
})
self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 1,
'product_uom': self.productA.uom_id.id,
'picking_id': receipt.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location,
})
self.MoveObj.create({
'name': self.productB.name,
'product_id': self.productB.id,
'product_uom_qty': 5,
'product_uom': self.productB.uom_id.id,
'picking_id': receipt.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location,
})
receipt.action_confirm()
self.assertEqual(len(receipt.move_lines), 2, 'Moves were not merged')
self.assertEqual(receipt.move_lines.filtered(lambda m: m.product_id == self.productA).product_uom_qty, 9, 'Merged quantity is not correct')
self.assertEqual(receipt.move_lines.filtered(lambda m: m.product_id == self.productB).product_uom_qty, 5, 'Merge should not impact product B reserved quantity')
def test_merge_moves_2(self):
receipt = self.env['stock.picking'].create({
'location_id': self.supplier_location,
'location_dest_id': self.stock_location,
'picking_type_id': self.picking_type_in,
})
self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 3,
'product_uom': self.productA.uom_id.id,
'picking_id': receipt.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location,
'origin': 'MPS'
})
self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 5,
'product_uom': self.productA.uom_id.id,
'picking_id': receipt.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location,
'origin': 'PO0001'
})
self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 3,
'product_uom': self.productA.uom_id.id,
'picking_id': receipt.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location,
'origin': 'MPS'
})
receipt.action_confirm()
self.assertEqual(len(receipt.move_lines), 1, 'Moves were not merged')
self.assertEqual(receipt.move_lines.origin.count('MPS'), 1, 'Origin not merged together or duplicated')
self.assertEqual(receipt.move_lines.origin.count('PO0001'), 1, 'Origin not merged together or duplicated')
def test_merge_moves_3(self):
""" Create 2 moves without initial_demand and already a
quantity done. Check that we still have only 2 moves after
validation.
"""
receipt = self.env['stock.picking'].create({
'location_id': self.supplier_location,
'location_dest_id': self.stock_location,
'picking_type_id': self.picking_type_in,
})
move_1 = self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 0,
'product_uom': self.productA.uom_id.id,
'picking_id': receipt.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location,
'origin': 'MPS'
})
move_2 = self.MoveObj.create({
'name': self.productB.name,
'product_id': self.productB.id,
'product_uom_qty': 0,
'product_uom': self.productB.uom_id.id,
'picking_id': receipt.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location,
'origin': 'PO0001'
})
move_1.quantity_done = 5
move_2.quantity_done = 5
receipt.button_validate()
self.assertEqual(len(receipt.move_lines), 2, 'Moves were not merged')
def test_merge_chained_moves(self):
""" Imagine multiple step delivery. Two different receipt picking for the same product should only generate
1 picking from input to QC and another from QC to stock. The link at the end should follow this scheme.
Move receipt 1 \
Move Input-> QC - Move QC -> Stock
Move receipt 2 /
"""
warehouse = self.env['stock.warehouse'].create({
'name': 'TEST WAREHOUSE',
'code': 'TEST1',
'reception_steps': 'three_steps',
})
receipt1 = self.env['stock.picking'].create({
'location_id': self.supplier_location,
'location_dest_id': warehouse.wh_input_stock_loc_id.id,
'picking_type_id': warehouse.in_type_id.id,
})
move_receipt_1 = self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 5,
'product_uom': self.productA.uom_id.id,
'picking_id': receipt1.id,
'location_id': self.supplier_location,
'location_dest_id': warehouse.wh_input_stock_loc_id.id,
})
receipt2 = self.env['stock.picking'].create({
'location_id': self.supplier_location,
'location_dest_id': warehouse.wh_input_stock_loc_id.id,
'picking_type_id': warehouse.in_type_id.id,
})
move_receipt_2 = self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 3,
'product_uom': self.productA.uom_id.id,
'picking_id': receipt2.id,
'location_id': self.supplier_location,
'location_dest_id': warehouse.wh_input_stock_loc_id.id,
})
receipt1.action_confirm()
receipt2.action_confirm()
# Check following move has been created and grouped in one picking.
self.assertTrue(move_receipt_1.move_dest_ids, 'No move created from push rules')
self.assertTrue(move_receipt_2.move_dest_ids, 'No move created from push rules')
self.assertEqual(move_receipt_1.move_dest_ids.picking_id, move_receipt_2.move_dest_ids.picking_id, 'Destination moves should be in the same picking')
# Check link for input move are correct.
input_move = move_receipt_2.move_dest_ids
self.assertEqual(len(input_move.move_dest_ids), 1)
self.assertEqual(set(input_move.move_orig_ids.ids), set((move_receipt_2 | move_receipt_1).ids),
'Move from input to QC should be merged and have the two receipt moves as origin.')
self.assertEqual(move_receipt_1.move_dest_ids, input_move)
self.assertEqual(move_receipt_2.move_dest_ids, input_move)
# Check link for quality check move are also correct.
qc_move = input_move.move_dest_ids
self.assertEqual(len(qc_move), 1)
self.assertTrue(qc_move.move_orig_ids == input_move, 'Move between QC and stock should only have the input move as origin')
def test_merge_chained_moves_multi_confirm(self):
""" Imagine multiple step delivery. A receipt picking for the same product should by add to
a existing picking from input to QC and another from QC to stock.
This existing picking is confirm in the same time (not possible in stock, but can be with batch picking)
and have some move to merge.
"""
warehouse = self.env['stock.warehouse'].create({
'name': 'TEST WAREHOUSE',
'code': 'TEST1',
'reception_steps': 'three_steps',
})
receipt1 = self.env['stock.picking'].create({
'location_id': self.supplier_location,
'location_dest_id': warehouse.wh_input_stock_loc_id.id,
'picking_type_id': warehouse.in_type_id.id,
})
move_receipt_1 = self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 5,
'product_uom': self.productA.uom_id.id,
'picking_id': receipt1.id,
'location_id': self.supplier_location,
'location_dest_id': warehouse.wh_input_stock_loc_id.id,
})
receipt2 = self.env['stock.picking'].create({
'location_id': warehouse.wh_input_stock_loc_id.id,
'location_dest_id': warehouse.wh_qc_stock_loc_id.id,
'picking_type_id': warehouse.int_type_id.id,
})
move1_receipt_2 = self.MoveObj.create({
'name': self.productB.name,
'product_id': self.productB.id,
'product_uom_qty': 1,
'product_uom': self.productB.uom_id.id,
'picking_id': receipt2.id,
'location_id': warehouse.wh_input_stock_loc_id.id,
'location_dest_id': warehouse.wh_qc_stock_loc_id.id,
})
move2_receipt_2 = self.MoveObj.create({
'name': self.productB.name,
'product_id': self.productB.id,
'product_uom_qty': 2,
'product_uom': self.productB.uom_id.id,
'picking_id': receipt2.id,
'location_id': warehouse.wh_input_stock_loc_id.id,
'location_dest_id': warehouse.wh_qc_stock_loc_id.id,
})
(receipt1 | receipt2).action_confirm()
# Check following move has been created
self.assertTrue(move_receipt_1.move_dest_ids, 'No move created from push rules')
self.assertTrue((move1_receipt_2 | move2_receipt_2).exists().move_dest_ids, 'No move created from push rules')
self.assertEqual(len((move1_receipt_2 | move2_receipt_2).exists()), 1, 'Move has been merged with the other one')
self.assertEqual(move_receipt_1.move_dest_ids.picking_id, receipt2, 'Dest Move of receipt1 should be in the receipt2')
# Check no move is still in draft
self.assertTrue("draft" not in (receipt1 | receipt2).move_lines.mapped("state"))
# Check the content of the pickings
self.assertEqual(receipt1.move_lines.mapped("product_uom_qty"), [5])
self.assertEqual(receipt2.move_lines.filtered(lambda m: m.product_id == self.productB).mapped("product_uom_qty"), [3])
self.assertEqual(receipt2.move_lines.filtered(lambda m: m.product_id == self.productA).mapped("product_uom_qty"), [5])
def test_empty_moves_validation_1(self):
""" Use button validate on a picking that contains only moves
without initial demand and without quantity done should be
impossible and raise a usererror.
"""
delivery_order = self.env['stock.picking'].create({
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
'picking_type_id': self.picking_type_out,
})
self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 0,
'product_uom': self.productA.uom_id.id,
'picking_id': delivery_order.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
})
self.MoveObj.create({
'name': self.productB.name,
'product_id': self.productB.id,
'product_uom_qty': 0,
'product_uom': self.productB.uom_id.id,
'picking_id': delivery_order.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
})
delivery_order.action_confirm()
delivery_order.action_assign()
with self.assertRaises(UserError):
delivery_order.button_validate()
def test_empty_moves_validation_2(self):
""" Use button validate on a picking that contains only moves
without initial demand but at least one with a quantity done
should process the move with quantity done and cancel the
other.
"""
delivery_order = self.env['stock.picking'].create({
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
'picking_type_id': self.picking_type_out,
})
move_a = self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 0,
'product_uom': self.productA.uom_id.id,
'picking_id': delivery_order.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
})
move_b = self.MoveObj.create({
'name': self.productB.name,
'product_id': self.productB.id,
'product_uom_qty': 0,
'product_uom': self.productB.uom_id.id,
'picking_id': delivery_order.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
})
delivery_order.action_confirm()
delivery_order.action_assign()
move_a.quantity_done = 1
delivery_order.button_validate()
self.assertEqual(move_a.state, 'done')
self.assertEqual(move_b.state, 'cancel')
back_order = self.env['stock.picking'].search([('backorder_id', '=', delivery_order.id)])
self.assertFalse(back_order, 'There should be no back order')
def test_unlink_move_1(self):
picking = Form(self.env['stock.picking'])
ptout = self.env['stock.picking.type'].browse(self.picking_type_out)
picking.picking_type_id = ptout
with picking.move_ids_without_package.new() as move:
move.product_id = self.productA
move.product_uom_qty = 10
picking = picking.save()
self.assertEqual(picking.immediate_transfer, False)
self.assertEqual(picking.state, 'draft')
picking = Form(picking)
picking.move_ids_without_package.remove(0)
picking = picking.save()
self.assertEqual(len(picking.move_ids_without_package), 0)
def test_additional_move_1(self):
""" On a planned trasfer, add a stock move when the picking is already ready. Check that
the check availability button appears and work.
"""
# Make some stock for productA and productB.
receipt = self.env['stock.picking'].create({
'location_id': self.supplier_location,
'location_dest_id': self.stock_location,
'picking_type_id': self.picking_type_in,
})
move_1 = self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 10,
'product_uom': self.productA.uom_id.id,
'picking_id': receipt.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location,
})
move_2 = self.MoveObj.create({
'name': self.productB.name,
'product_id': self.productB.id,
'product_uom_qty': 10,
'product_uom': self.productB.uom_id.id,
'picking_id': receipt.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location,
})
receipt.action_confirm()
move_1.quantity_done = 10
move_2.quantity_done = 10
receipt.button_validate()
self.assertEqual(self.productA.qty_available, 10)
self.assertEqual(self.productB.qty_available, 10)
# Create a delivery for 1 productA, reserve, check the picking is ready
delivery_order = self.env['stock.picking'].create({
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
'picking_type_id': self.picking_type_out,
'move_type': 'one',
})
move_3 = self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 10,
'product_uom': self.productA.uom_id.id,
'picking_id': delivery_order.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
})
delivery_order.action_confirm()
delivery_order.action_assign()
self.assertEqual(delivery_order.state, 'assigned')
# Add a unit of productB, the check_availability button should appear.
delivery_order = Form(delivery_order)
with delivery_order.move_ids_without_package.new() as move:
move.product_id = self.productB
move.product_uom_qty = 10
delivery_order = delivery_order.save()
# The autocoform ran, the picking shoud be confirmed and reservable.
self.assertEqual(delivery_order.state, 'confirmed')
self.assertEqual(delivery_order.show_mark_as_todo, False)
self.assertEqual(delivery_order.show_check_availability, True)
delivery_order.action_assign()
self.assertEqual(delivery_order.state, 'assigned')
self.assertEqual(delivery_order.show_check_availability, False)
self.assertEqual(delivery_order.show_mark_as_todo, False)
stock_location = self.env['stock.location'].browse(self.stock_location)
self.assertEqual(self.env['stock.quant']._gather(self.productA, stock_location).reserved_quantity, 10.0)
self.assertEqual(self.env['stock.quant']._gather(self.productB, stock_location).reserved_quantity, 10.0)
def test_additional_move_2(self):
""" On an immediate trasfer, add a stock move when the picking is already ready. Check that
the check availability button doest not appear.
"""
# Create a delivery for 1 productA, check the picking is ready
delivery_order = self.env['stock.picking'].create({
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
'picking_type_id': self.picking_type_out,
'immediate_transfer': True,
'move_ids_without_package': [(0, 0, {
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom': self.productA.uom_id.id,
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
'quantity_done': 5,
})],
})
self.assertEqual(delivery_order.state, 'assigned')
# Add a unit of productB, the check_availability button should not appear.
delivery_order = Form(delivery_order)
with delivery_order.move_ids_without_package.new() as move:
move.product_id = self.productB
delivery_order = delivery_order.save()
self.assertEqual(delivery_order.state, 'assigned')
self.assertEqual(delivery_order.show_check_availability, False)
self.assertEqual(delivery_order.show_mark_as_todo, False)
def test_owner_1(self):
"""Make a receipt, set an owner and validate"""
owner1 = self.env['res.partner'].create({'name': 'owner'})
receipt = self.env['stock.picking'].create({
'location_id': self.supplier_location,
'location_dest_id': self.stock_location,
'picking_type_id': self.picking_type_in,
})
move1 = self.env['stock.move'].create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 1,
'product_uom': self.productA.uom_id.id,
'picking_id': receipt.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location,
})
receipt.action_confirm()
receipt = Form(receipt)
receipt.owner_id = owner1
receipt = receipt.save()
wiz = receipt.button_validate()
wiz = Form(self.env['stock.immediate.transfer'].with_context(wiz['context'])).save()
wiz.process()
supplier_location = self.env['stock.location'].browse(self.supplier_location)
stock_location = self.env['stock.location'].browse(self.stock_location)
supplier_quant = self.env['stock.quant']._gather(self.productA, supplier_location)
stock_quant = self.env['stock.quant']._gather(self.productA, stock_location)
self.assertEqual(supplier_quant.owner_id, owner1)
self.assertEqual(supplier_quant.quantity, -1)
self.assertEqual(stock_quant.owner_id, owner1)
self.assertEqual(stock_quant.quantity, 1)
def test_putaway_for_picking_sml(self):
""" Checks picking's move lines will take in account the putaway rules
to define the `location_dest_id`.
"""
partner = self.env['res.partner'].create({'name': 'Partner'})
supplier_location = self.env['stock.location'].browse(self.supplier_location)
stock_location = self.env['stock.location'].create({
'name': 'test-stock',
'usage': 'internal',
})
shelf_location = self.env['stock.location'].create({
'name': 'shelf1',
'usage': 'internal',
'location_id': stock_location.id,
})
# We need to activate multi-locations to use putaway rules.
grp_multi_loc = self.env.ref('stock.group_stock_multi_locations')
self.env.user.write({'groups_id': [(4, grp_multi_loc.id)]})
putaway_product = self.env['stock.putaway.rule'].create({
'product_id': self.productA.id,
'location_in_id': stock_location.id,
'location_out_id': shelf_location.id,
})
# Changes config of receipt type to allow to edit move lines directly.
picking_type = self.env['stock.picking.type'].browse(self.picking_type_in)
picking_type.show_operations = True
receipt_form = Form(self.env['stock.picking'].with_context(
force_detailed_view=True
), view='stock.view_picking_form')
receipt_form.partner_id = partner
receipt_form.picking_type_id = picking_type
receipt_form.location_id = supplier_location
receipt_form.location_dest_id = stock_location
receipt = receipt_form.save()
with receipt_form.move_line_nosuggest_ids.new() as move_line:
move_line.product_id = self.productA
move_line.qty_done = 1.0
receipt = receipt_form.save()
# Checks receipt has still its destination location and checks its move
# line took the one from the putaway rule.
self.assertEqual(receipt.location_dest_id.id, stock_location.id)
self.assertEqual(receipt.move_line_ids.location_dest_id.id, shelf_location.id)
def test_cancel_plan_transfer(self):
""" Test canceling plan transfer """
# Create picking with stock move.
picking = self.env['stock.picking'].create({
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
'picking_type_id': self.picking_type_out,
'move_lines': [(0, 0, {
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 10,
'product_uom': self.productA.uom_id.id,
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
})]
})
# Confirm the outgoing picking, state should be changed.
picking.action_confirm()
self.assertEqual(picking.state, 'confirmed', "Picking should be in a confirmed state.")
# Picking in a confirmed state and try to cancel it.
picking.action_cancel()
self.assertEqual(picking.state, 'cancel', "Picking should be in a cancel state.")
def test_immediate_transfer(self):
""" Test picking should be in ready state if immediate transfer and SML is created via view +
Test picking cancelation with immediate transfer and done quantity"""
# create picking with stock move line
picking = self.env['stock.picking'].create({
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
'picking_type_id': self.picking_type_out,
'immediate_transfer': True,
'move_line_ids': [(0, 0, {
'product_id': self.productA.id,
'qty_done': 10,
'product_uom_id': self.productA.uom_id.id,
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
})]
})
self.assertEqual(picking.state, 'assigned', "Picking should not be in a draft state.")
self.assertEqual(len(picking.move_lines), 1, "Picking should have stock move.")
picking.action_cancel()
self.assertEqual(picking.move_lines.state, 'cancel', "Stock move should be in a cancel state.")
self.assertEqual(picking.state, 'cancel', "Picking should be in a cancel state.")
class TestStockUOM(TestStockCommon):
def setUp(self):
super(TestStockUOM, self).setUp()
dp = self.env.ref('product.decimal_product_uom')
dp.digits = 7
def test_pickings_transfer_with_different_uom_and_back_orders(self):
""" Picking transfer with diffrent unit of meassure. """
# weight category
categ_test = self.env['uom.category'].create({'name': 'Bigger than tons'})
T_LBS = self.env['uom.uom'].create({
'name': 'T-LBS',
'category_id': categ_test.id,
'uom_type': 'reference',
'rounding': 0.01
})
T_GT = self.env['uom.uom'].create({
'name': 'T-GT',
'category_id': categ_test.id,
'uom_type': 'bigger',
'rounding': 0.0000001,
'factor_inv': 2240.00,
})
T_TEST = self.env['product.product'].create({
'name': 'T_TEST',
'type': 'product',
'uom_id': T_LBS.id,
'uom_po_id': T_LBS.id,
'tracking': 'lot',
})
picking_in = self.env['stock.picking'].create({
'picking_type_id': self.picking_type_in,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location
})
move = self.env['stock.move'].create({
'name': 'First move with 60 GT',
'product_id': T_TEST.id,
'product_uom_qty': 60,
'product_uom': T_GT.id,
'picking_id': picking_in.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location
})
picking_in.action_confirm()
self.assertEqual(move.product_uom_qty, 60.00, 'Wrong T_GT quantity')
self.assertEqual(move.product_qty, 134400.00, 'Wrong T_LBS quantity')
lot = self.env['stock.production.lot'].create({'name': 'Lot TEST', 'product_id': T_TEST.id, 'company_id': self.env.company.id, })
self.env['stock.move.line'].create({
'move_id': move.id,
'product_id': T_TEST.id,
'product_uom_id': T_LBS.id,
'location_id': self.supplier_location,
'location_dest_id': self.stock_location,
'qty_done': 42760.00,
'lot_id': lot.id,
})
picking_in._action_done()
back_order_in = self.env['stock.picking'].search([('backorder_id', '=', picking_in.id)])
self.assertEqual(len(back_order_in), 1.00, 'There should be one back order created')
self.assertEqual(back_order_in.move_lines.product_qty, 91640.00, 'There should be one back order created')
def test_move_product_with_different_uom(self):
""" Product defined in g with 0.01 rounding
Decimal Accuracy (DA) 3 digits.
Quantity on hand: 149.88g
Picking of 1kg
kg has 0.0001 rounding
Due to conversions, we may end up reserving 150g
(more than the quantity in stock), we check that
we reserve less than the quantity in stock
"""
precision = self.env.ref('product.decimal_product_uom')
precision.digits = 3
precision_digits = precision.digits
self.uom_kg.rounding = 0.0001
self.uom_gm.rounding = 0.01
product_G = self.env['product.product'].create({
'name': 'Product G',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
'uom_id': self.uom_gm.id,
'uom_po_id': self.uom_gm.id,
})
stock_location = self.env['stock.location'].browse(self.stock_location)
self.env['stock.quant']._update_available_quantity(product_G, stock_location, 149.88)
self.assertEqual(len(product_G.stock_quant_ids), 1, 'One quant should exist for the product.')
quant = product_G.stock_quant_ids
# transfer 1kg of product_G
picking = self.env['stock.picking'].create({
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
'picking_type_id': self.env.ref('stock.picking_type_out').id,
})
move = self.env['stock.move'].create({
'name': 'test_reserve_product_G',
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
'picking_id': picking.id,
'product_id': product_G.id,
'product_uom': self.uom_kg.id,
'product_uom_qty': 1,
})
self.assertEqual(move.product_uom.id, self.uom_kg.id)
self.assertEqual(move.product_uom_qty, 1.0)
picking.action_confirm()
picking.action_assign()
self.assertEqual(product_G.uom_id.rounding, 0.01)
self.assertEqual(move.product_uom.rounding, 0.0001)
self.assertEqual(len(picking.move_line_ids), 1, 'One move line should exist for the picking.')
move_line = picking.move_line_ids
# check that we do not reserve more (in the same UOM) than the quantity in stock
self.assertEqual(float_compare(move_line.product_qty, quant.quantity, precision_digits=precision_digits), -1, "We do not reserve more (in the same UOM) than the quantity in stock")
# check that we reserve the same quantity in the ml and the quant
self.assertTrue(float_is_zero(move_line.product_qty - quant.reserved_quantity, precision_digits=precision_digits))
def test_update_product_move_line_with_different_uom(self):
""" Check that when the move line and corresponding
product have different UOM with possibly conflicting
precisions, we do not reserve more than the quantity
in stock. Similar initial configuration as
test_move_product_with_different_uom.
"""
precision = self.env.ref('product.decimal_product_uom')
precision.digits = 3
precision_digits = precision.digits
self.uom_kg.rounding = 0.0001
self.uom_gm.rounding = 0.01
product_LtDA = self.env['product.product'].create({
'name': 'Product Less than DA',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
'uom_id': self.uom_gm.id,
'uom_po_id': self.uom_gm.id,
})
product_GtDA = self.env['product.product'].create({
'name': 'Product Greater than DA',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
'uom_id': self.uom_gm.id,
'uom_po_id': self.uom_gm.id,
})
stock_location = self.env['stock.location'].browse(self.stock_location)
# quantity in hand converted to kg is not more precise than the DA
self.env['stock.quant']._update_available_quantity(product_LtDA, stock_location, 149)
# quantity in hand converted to kg is more precise than the DA
self.env['stock.quant']._update_available_quantity(product_GtDA, stock_location, 149.88)
self.assertEqual(len(product_LtDA.stock_quant_ids), 1, 'One quant should exist for the product.')
self.assertEqual(len(product_GtDA.stock_quant_ids), 1, 'One quant should exist for the product.')
quant_LtDA = product_LtDA.stock_quant_ids
quant_GtDA = product_GtDA.stock_quant_ids
# create 2 moves of 1kg
move_LtDA = self.env['stock.move'].create({
'name': 'test_reserve_product_LtDA',
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
'product_id': product_LtDA.id,
'product_uom': self.uom_kg.id,
'product_uom_qty': 1,
})
move_GtDA = self.env['stock.move'].create({
'name': 'test_reserve_product_GtDA',
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
'product_id': product_GtDA.id,
'product_uom': self.uom_kg.id,
'product_uom_qty': 1,
})
self.assertEqual(move_LtDA.state, 'draft')
self.assertEqual(move_GtDA.state, 'draft')
move_LtDA._action_confirm()
move_GtDA._action_confirm()
self.assertEqual(move_LtDA.state, 'confirmed')
self.assertEqual(move_GtDA.state, 'confirmed')
# check availability, less than initial demand
move_LtDA._action_assign()
move_GtDA._action_assign()
self.assertEqual(move_LtDA.state, 'partially_available')
self.assertEqual(move_GtDA.state, 'partially_available')
# the initial demand is 1kg
self.assertEqual(move_LtDA.product_uom.id, self.uom_kg.id)
self.assertEqual(move_GtDA.product_uom.id, self.uom_kg.id)
self.assertEqual(move_LtDA.product_uom_qty, 1.0)
self.assertEqual(move_GtDA.product_uom_qty, 1.0)
# one move line is created
self.assertEqual(len(move_LtDA.move_line_ids), 1)
self.assertEqual(len(move_GtDA.move_line_ids), 1)
# increase quantity by 0.14988 kg (more precise than DA)
self.env['stock.quant']._update_available_quantity(product_LtDA, stock_location, 149.88)
self.env['stock.quant']._update_available_quantity(product_GtDA, stock_location, 149.88)
# _update_reserved_quantity is called on a move only in _action_assign
move_LtDA._action_assign()
move_GtDA._action_assign()
# as the move line for LtDA and its corresponding quant can be
# in different UOMs, a new move line can be created
# from _update_reserved_quantity
move_lines_LtDA = self.env["stock.move.line"].search([
('product_id', '=', quant_LtDA.product_id.id),
('location_id', '=', quant_LtDA.location_id.id),
('lot_id', '=', quant_LtDA.lot_id.id),
('package_id', '=', quant_LtDA.package_id.id),
('owner_id', '=', quant_LtDA.owner_id.id),
('product_qty', '!=', 0)
])
reserved_on_move_lines_LtDA = sum(move_lines_LtDA.mapped('product_qty'))
move_lines_GtDA = self.env["stock.move.line"].search([
('product_id', '=', quant_GtDA.product_id.id),
('location_id', '=', quant_GtDA.location_id.id),
('lot_id', '=', quant_GtDA.lot_id.id),
('package_id', '=', quant_GtDA.package_id.id),
('owner_id', '=', quant_GtDA.owner_id.id),
('product_qty', '!=', 0)
])
reserved_on_move_lines_GtDA = sum(move_lines_GtDA.mapped('product_qty'))
# check that we do not reserve more (in the same UOM) than the quantity in stock
self.assertEqual(float_compare(reserved_on_move_lines_LtDA, quant_LtDA.quantity, precision_digits=precision_digits), -1, "We do not reserve more (in the same UOM) than the quantity in stock")
self.assertEqual(float_compare(reserved_on_move_lines_GtDA, quant_GtDA.quantity, precision_digits=precision_digits), -1, "We do not reserve more (in the same UOM) than the quantity in stock")
# check that we reserve the same quantity in the ml and the quant
self.assertTrue(float_is_zero(reserved_on_move_lines_LtDA - quant_LtDA.reserved_quantity, precision_digits=precision_digits))
self.assertTrue(float_is_zero(reserved_on_move_lines_GtDA - quant_GtDA.reserved_quantity, precision_digits=precision_digits))
class TestRoutes(TestStockCommon):
def setUp(self):
super(TestRoutes, self).setUp()
self.product1 = self.env['product.product'].create({
'name': 'product a',
'type': 'product',
'categ_id': self.env.ref('product.product_category_all').id,
})
self.uom_unit = self.env.ref('uom.product_uom_unit')
self.partner = self.env['res.partner'].create({'name': 'Partner'})
def _enable_pick_ship(self):
self.wh = self.env['stock.warehouse'].search([('company_id', '=', self.env.user.id)], limit=1)
# create and get back the pick ship route
self.wh.write({'delivery_steps': 'pick_ship'})
self.pick_ship_route = self.wh.route_ids.filtered(lambda r: '(pick + ship)' in r.name)
def test_pick_ship_1(self):
""" Enable the pick ship route, force a procurement group on the
pick. When a second move is added, make sure the `partner_id` and
`origin` fields are erased.
"""
self._enable_pick_ship()
# create a procurement group and set in on the pick stock rule
procurement_group0 = self.env['procurement.group'].create({})
pick_rule = self.pick_ship_route.rule_ids.filtered(lambda rule: 'Stock → Output' in rule.name)
push_rule = self.pick_ship_route.rule_ids - pick_rule
pick_rule.write({
'group_propagation_option': 'fixed',
'group_id': procurement_group0.id,
})
ship_location = pick_rule.location_id
customer_location = push_rule.location_id
partners = self.env['res.partner'].search([], limit=2)
partner0 = partners[0]
partner1 = partners[1]
procurement_group1 = self.env['procurement.group'].create({'partner_id': partner0.id})
procurement_group2 = self.env['procurement.group'].create({'partner_id': partner1.id})
move1 = self.env['stock.move'].create({
'name': 'first out move',
'procure_method': 'make_to_order',
'location_id': ship_location.id,
'location_dest_id': customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
'warehouse_id': self.wh.id,
'group_id': procurement_group1.id,
'origin': 'origin1',
})
move2 = self.env['stock.move'].create({
'name': 'second out move',
'procure_method': 'make_to_order',
'location_id': ship_location.id,
'location_dest_id': customer_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
'warehouse_id': self.wh.id,
'group_id': procurement_group2.id,
'origin': 'origin2',
})
# first out move, the "pick" picking should have a partner and an origin
move1._action_confirm()
picking_pick = move1.move_orig_ids.picking_id
self.assertEqual(picking_pick.partner_id.id, procurement_group1.partner_id.id)
self.assertEqual(picking_pick.origin, move1.group_id.name)
# second out move, the "pick" picking should have lost its partner and origin
move2._action_confirm()
self.assertEqual(picking_pick.partner_id.id, False)
self.assertEqual(picking_pick.origin, False)
def test_replenish_pick_ship_1(self):
""" Creates 2 warehouses and make a replenish using one warehouse
to ressuply the other one, Then check if the quantity and the product are matching
"""
self.product_uom_qty = 42
warehouse_1 = self.env['stock.warehouse'].search([('company_id', '=', self.env.user.id)], limit=1)
warehouse_2 = self.env['stock.warehouse'].create({
'name': 'Small Warehouse',
'code': 'SWH'
})
warehouse_1.write({
'resupply_wh_ids': [(6, 0, [warehouse_2.id])]
})
resupply_route = self.env['stock.location.route'].search([('supplier_wh_id', '=', warehouse_2.id), ('supplied_wh_id', '=', warehouse_1.id)])
self.assertTrue(resupply_route, "Ressuply route not found")
self.product1.write({'route_ids': [(4, resupply_route.id), (4, self.env.ref('stock.route_warehouse0_mto').id)]})
self.wh = warehouse_1
replenish_wizard = self.env['product.replenish'].create({
'product_id': self.product1.id,
'product_tmpl_id': self.product1.product_tmpl_id.id,
'product_uom_id': self.uom_unit.id,
'quantity': self.product_uom_qty,
'warehouse_id': self.wh.id,
})
replenish_wizard.launch_replenishment()
last_picking_id = self.env['stock.picking'].search([('origin', '=', 'Manual Replenishment')])[-1]
self.assertTrue(last_picking_id, 'Picking not found')
move_line = last_picking_id.move_lines.search([('product_id','=', self.product1.id)])
self.assertTrue(move_line,'The product is not in the picking')
self.assertEqual(move_line[0].product_uom_qty, self.product_uom_qty, 'Quantities does not match')
self.assertEqual(move_line[1].product_uom_qty, self.product_uom_qty, 'Quantities does not match')
def test_push_rule_on_move_1(self):
""" Create a route with a push rule, force it on a move, check that it is applied.
"""
self._enable_pick_ship()
stock_location = self.env.ref('stock.stock_location_stock')
push_location = self.env['stock.location'].create({
'location_id': stock_location.location_id.id,
'name': 'push location',
})
# TODO: maybe add a new type on the "applicable on" fields?
route = self.env['stock.location.route'].create({
'name': 'new route',
'rule_ids': [(0, False, {
'name': 'create a move to push location',
'location_src_id': stock_location.id,
'location_id': push_location.id,
'company_id': self.env.company.id,
'action': 'push',
'auto': 'manual',
'picking_type_id': self.env.ref('stock.picking_type_in').id,
})],
})
move1 = self.env['stock.move'].create({
'name': 'move with a route',
'location_id': stock_location.id,
'location_dest_id': stock_location.id,
'product_id': self.product1.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
'route_ids': [(4, route.id)]
})
move1._action_confirm()
pushed_move = move1.move_dest_ids
self.assertEqual(pushed_move.location_dest_id.id, push_location.id)
def test_location_dest_update(self):
""" Check the location dest of a stock move changed by a push rule
with auto field set to transparent is done correctly. The stock_move
is create with the move line directly to pass into action_confirm() via
action_done(). """
self.wh = self.env['stock.warehouse'].search([('company_id', '=', self.env.user.id)], limit=1)
new_loc = self.env['stock.location'].create({
'name': 'New_location',
'usage': 'internal',
'location_id': self.env.ref('stock.stock_location_locations').id,
})
picking_type = self.env['stock.picking.type'].create({
'name': 'new_picking_type',
'code': 'internal',
'sequence_code': 'NPT',
'default_location_src_id': self.env.ref('stock.stock_location_stock').id,
'default_location_dest_id': new_loc.id,
'warehouse_id': self.wh.id,
})
route = self.env['stock.location.route'].create({
'name': 'new route',
'rule_ids': [(0, False, {
'name': 'create a move to push location',
'location_src_id': self.env.ref('stock.stock_location_stock').id,
'location_id': new_loc.id,
'company_id': self.env.company.id,
'action': 'push',
'auto': 'transparent',
'picking_type_id': picking_type.id,
})],
})
product = self.env['product.product'].create({
'name': 'new_product',
'type': 'product',
'route_ids': [(4, route.id)]
})
move1 = self.env['stock.move'].create({
'name': 'move with a route',
'location_id': self.supplier_location,
'location_dest_id': self.env.ref('stock.stock_location_stock').id,
'product_id': product.id,
'product_uom_qty': 1.0,
'product_uom': self.uom_unit.id,
'move_line_ids': [(0, 0, {
'product_id': product.id,
'product_uom_id': self.uom_unit.id,
'location_id': self.supplier_location,
'location_dest_id': self.env.ref('stock.stock_location_stock').id,
'qty_done': 1.00,
})],
})
move1._action_done()
self.assertEqual(move1.location_dest_id, new_loc)
positive_quant = product.stock_quant_ids.filtered(lambda q: q.quantity > 0)
self.assertEqual(positive_quant.location_id, new_loc)
def test_mtso_mto(self):
""" Run a procurement for 5 products when there are only 4 in stock then
check that MTO is applied on the moves when the rule is set to 'mts_else_mto'
"""
warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.env.user.id)], limit=1)
warehouse.delivery_steps = 'pick_pack_ship'
partner_demo_customer = self.partner
final_location = partner_demo_customer.property_stock_customer
product_a = self.env['product.product'].create({
'name': 'ProductA',
'type': 'product',
})
self.env['stock.quant']._update_available_quantity(product_a, warehouse.wh_output_stock_loc_id, 4.0)
# We set quantities in the stock location to avoid warnings
# triggered by '_onchange_product_id_check_availability'
self.env['stock.quant']._update_available_quantity(product_a, warehouse.lot_stock_id, 4.0)
# We alter one rule and we set it to 'mts_else_mto'
values = {'warehouse_id': warehouse}
rule = self.env['procurement.group']._get_rule(product_a, final_location, values)
rule.procure_method = 'mts_else_mto'
pg = self.env['procurement.group'].create({'name': 'Test-pg-mtso-mto'})
self.env['procurement.group'].run([
pg.Procurement(
product_a,
5.0,
product_a.uom_id,
final_location,
'test_mtso_mto',
'test_mtso_mto',
warehouse.company_id,
{
'warehouse_id': warehouse,
'group_id': pg
}
)
])
qty_available = self.env['stock.quant']._get_available_quantity(product_a, warehouse.wh_output_stock_loc_id)
# 3 pickings should be created.
picking_ids = self.env['stock.picking'].search([('group_id', '=', pg.id)])
self.assertEqual(len(picking_ids), 3)
for picking in picking_ids:
# Only the picking from Stock to Pack should be MTS
if picking.location_id == warehouse.lot_stock_id:
self.assertEqual(picking.move_lines.procure_method, 'make_to_stock')
else:
self.assertEqual(picking.move_lines.procure_method, 'make_to_order')
self.assertEqual(len(picking.move_lines), 1)
self.assertEqual(picking.move_lines.product_uom_qty, 5, 'The quantity of the move should be the same as on the SO')
self.assertEqual(qty_available, 4, 'The 4 products should still be available')
def test_mtso_mts(self):
""" Run a procurement for 4 products when there are 4 in stock then
check that MTS is applied on the moves when the rule is set to 'mts_else_mto'
"""
warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.env.user.id)], limit=1)
warehouse.delivery_steps = 'pick_pack_ship'
partner_demo_customer = self.partner
final_location = partner_demo_customer.property_stock_customer
product_a = self.env['product.product'].create({
'name': 'ProductA',
'type': 'product',
})
self.env['stock.quant']._update_available_quantity(product_a, warehouse.wh_output_stock_loc_id, 4.0)
# We alter one rule and we set it to 'mts_else_mto'
values = {'warehouse_id': warehouse}
rule = self.env['procurement.group']._get_rule(product_a, final_location, values)
rule.procure_method = 'mts_else_mto'
pg = self.env['procurement.group'].create({'name': 'Test-pg-mtso-mts'})
self.env['procurement.group'].run([
pg.Procurement(
product_a,
4.0,
product_a.uom_id,
final_location,
'test_mtso_mts',
'test_mtso_mts',
warehouse.company_id,
{
'warehouse_id': warehouse,
'group_id': pg
}
)
])
# A picking should be created with its move having MTS as procure method.
picking_ids = self.env['stock.picking'].search([('group_id', '=', pg.id)])
self.assertEqual(len(picking_ids), 1)
picking = picking_ids
self.assertEqual(picking.move_lines.procure_method, 'make_to_stock')
self.assertEqual(len(picking.move_lines), 1)
self.assertEqual(picking.move_lines.product_uom_qty, 4)
def test_mtso_multi_pg(self):
""" Run 3 procurements for 2 products at the same times when there are 4 in stock then
check that MTS is applied on the moves when the rule is set to 'mts_else_mto'
"""
warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.env.user.id)], limit=1)
warehouse.delivery_steps = 'pick_pack_ship'
partner_demo_customer = self.partner
final_location = partner_demo_customer.property_stock_customer
product_a = self.env['product.product'].create({
'name': 'ProductA',
'type': 'product',
})
self.env['stock.quant']._update_available_quantity(product_a, warehouse.wh_output_stock_loc_id, 4.0)
# We alter one rule and we set it to 'mts_else_mto'
values = {'warehouse_id': warehouse}
rule = self.env['procurement.group']._get_rule(product_a, final_location, values)
rule.procure_method = 'mts_else_mto'
pg1 = self.env['procurement.group'].create({'name': 'Test-pg-mtso-mts-1'})
pg2 = self.env['procurement.group'].create({'name': 'Test-pg-mtso-mts-2'})
pg3 = self.env['procurement.group'].create({'name': 'Test-pg-mtso-mts-3'})
self.env['procurement.group'].run([
pg1.Procurement(
product_a,
2.0,
product_a.uom_id,
final_location,
'test_mtso_mts_1',
'test_mtso_mts_1',
warehouse.company_id,
{
'warehouse_id': warehouse,
'group_id': pg1
}
),
pg2.Procurement(
product_a,
2.0,
product_a.uom_id,
final_location,
'test_mtso_mts_2',
'test_mtso_mts_2',
warehouse.company_id,
{
'warehouse_id': warehouse,
'group_id': pg2
}
),
pg3.Procurement(
product_a,
2.0,
product_a.uom_id,
final_location,
'test_mtso_mts_3',
'test_mtso_mts_3',
warehouse.company_id,
{
'warehouse_id': warehouse,
'group_id': pg3
}
)
])
pickings_pg1 = self.env['stock.picking'].search([('group_id', '=', pg1.id)])
pickings_pg2 = self.env['stock.picking'].search([('group_id', '=', pg2.id)])
pickings_pg3 = self.env['stock.picking'].search([('group_id', '=', pg3.id)])
# The 2 first procurements should have create only 1 picking since enough quantities
# are left in the delivery location
self.assertEqual(len(pickings_pg1), 1)
self.assertEqual(len(pickings_pg2), 1)
self.assertEqual(pickings_pg1.move_lines.procure_method, 'make_to_stock')
self.assertEqual(pickings_pg2.move_lines.procure_method, 'make_to_stock')
# The last one should have 3 pickings as there's nothing left in the delivery location
self.assertEqual(len(pickings_pg3), 3)
for picking in pickings_pg3:
# Only the picking from Stock to Pack should be MTS
if picking.location_id == warehouse.lot_stock_id:
self.assertEqual(picking.move_lines.procure_method, 'make_to_stock')
else:
self.assertEqual(picking.move_lines.procure_method, 'make_to_order')
# All the moves should be should have the same quantity as it is on each procurements
self.assertEqual(len(picking.move_lines), 1)
self.assertEqual(picking.move_lines.product_uom_qty, 2)
def test_mtso_mto_adjust_01(self):
""" Run '_adjust_procure_method' for products A & B:
- Product A has 5.0 available
- Product B has 3.0 available
Stock moves (SM) are created for 4.0 units
After '_adjust_procure_method':
- SM for A is 'make_to_stock'
- SM for B is 'make_to_order'
"""
warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.env.user.id)], limit=1)
final_location = self.partner.property_stock_customer
product_A = self.env['product.product'].create({
'name': 'Product A',
'type': 'product',
})
product_B = self.env['product.product'].create({
'name': 'Product B',
'type': 'product',
})
# We alter one rule and we set it to 'mts_else_mto'
rule = self.env['procurement.group']._get_rule(product_A, final_location, {'warehouse_id': warehouse})
rule.procure_method = 'mts_else_mto'
self.env['stock.quant']._update_available_quantity(product_A, warehouse.lot_stock_id, 5.0)
self.env['stock.quant']._update_available_quantity(product_B, warehouse.lot_stock_id, 3.0)
move_tmpl = {
'name': 'Product',
'product_uom': self.uom_unit.id,
'product_uom_qty': 4.0,
'location_id': warehouse.lot_stock_id.id,
'location_dest_id': self.partner.property_stock_customer.id,
'warehouse_id': warehouse.id,
}
move_A_vals = dict(move_tmpl)
move_A_vals.update({
'product_id': product_A.id,
})
move_A = self.env['stock.move'].create(move_A_vals)
move_B_vals = dict(move_tmpl)
move_B_vals.update({
'product_id': product_B.id,
})
move_B = self.env['stock.move'].create(move_B_vals)
moves = move_A + move_B
self.assertEqual(move_A.procure_method, 'make_to_stock', 'Move A should be "make_to_stock"')
self.assertEqual(move_B.procure_method, 'make_to_stock', 'Move A should be "make_to_order"')
moves._adjust_procure_method()
self.assertEqual(move_A.procure_method, 'make_to_stock', 'Move A should be "make_to_stock"')
self.assertEqual(move_B.procure_method, 'make_to_order', 'Move A should be "make_to_order"')
def test_mtso_mto_adjust_02(self):
""" Run '_adjust_procure_method' for products A & B:
- Product A has 5.0 available
- Product B has 3.0 available
Stock moves (SM) are created for 2.0 + 2.0 units
After '_adjust_procure_method':
- SM for A is 'make_to_stock'
- SM for B is 'make_to_stock' and 'make_to_order'
"""
warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.env.user.id)], limit=1)
final_location = self.partner.property_stock_customer
product_A = self.env['product.product'].create({
'name': 'Product A',
'type': 'product',
})
product_B = self.env['product.product'].create({
'name': 'Product B',
'type': 'product',
})
# We alter one rule and we set it to 'mts_else_mto'
rule = self.env['procurement.group']._get_rule(product_A, final_location, {'warehouse_id': warehouse})
rule.procure_method = 'mts_else_mto'
self.env['stock.quant']._update_available_quantity(product_A, warehouse.lot_stock_id, 5.0)
self.env['stock.quant']._update_available_quantity(product_B, warehouse.lot_stock_id, 3.0)
move_tmpl = {
'name': 'Product',
'product_uom': self.uom_unit.id,
'product_uom_qty': 2.0,
'location_id': warehouse.lot_stock_id.id,
'location_dest_id': self.partner.property_stock_customer.id,
'warehouse_id': warehouse.id,
}
move_A1_vals = dict(move_tmpl)
move_A1_vals.update({
'product_id': product_A.id,
})
move_A1 = self.env['stock.move'].create(move_A1_vals)
move_A2_vals = dict(move_tmpl)
move_A2_vals.update({
'product_id': product_A.id,
})
move_A2 = self.env['stock.move'].create(move_A2_vals)
move_B1_vals = dict(move_tmpl)
move_B1_vals.update({
'product_id': product_B.id,
})
move_B1 = self.env['stock.move'].create(move_B1_vals)
move_B2_vals = dict(move_tmpl)
move_B2_vals.update({
'product_id': product_B.id,
})
move_B2 = self.env['stock.move'].create(move_B2_vals)
moves = move_A1 + move_A2 + move_B1 + move_B2
self.assertEqual(move_A1.procure_method, 'make_to_stock', 'Move A1 should be "make_to_stock"')
self.assertEqual(move_A2.procure_method, 'make_to_stock', 'Move A2 should be "make_to_stock"')
self.assertEqual(move_B1.procure_method, 'make_to_stock', 'Move B1 should be "make_to_stock"')
self.assertEqual(move_B2.procure_method, 'make_to_stock', 'Move B2 should be "make_to_stock"')
moves._adjust_procure_method()
self.assertEqual(move_A1.procure_method, 'make_to_stock', 'Move A1 should be "make_to_stock"')
self.assertEqual(move_A2.procure_method, 'make_to_stock', 'Move A2 should be "make_to_stock"')
self.assertEqual(move_B1.procure_method, 'make_to_stock', 'Move B1 should be "make_to_stock"')
self.assertEqual(move_B2.procure_method, 'make_to_order', 'Move B2 should be "make_to_order"')
def test_mtso_mto_adjust_03(self):
""" Run '_adjust_procure_method' for products A with 4.0 available
2 Stock moves (SM) are created:
- SM1 for 5.0 Units
- SM2 for 3.0 Units
SM1 is confirmed, so 'virtual_available' is -1.0.
SM1 should become 'make_to_order'
SM2 should remain 'make_to_stock'
"""
warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.env.user.id)], limit=1)
final_location = self.partner.property_stock_customer
product_A = self.env['product.product'].create({
'name': 'Product A',
'type': 'product',
})
# We alter one rule and we set it to 'mts_else_mto'
rule = self.env['procurement.group']._get_rule(product_A, final_location, {'warehouse_id': warehouse})
rule.procure_method = 'mts_else_mto'
self.env['stock.quant']._update_available_quantity(product_A, warehouse.lot_stock_id, 4.0)
move_tmpl = {
'name': 'Product',
'product_id': product_A.id,
'product_uom': self.uom_unit.id,
'location_id': warehouse.lot_stock_id.id,
'location_dest_id': self.partner.property_stock_customer.id,
'warehouse_id': warehouse.id,
}
move_A1_vals = dict(move_tmpl)
move_A1_vals.update({
'product_uom_qty': 5.0,
})
move_A1 = self.env['stock.move'].create(move_A1_vals)
move_A2_vals = dict(move_tmpl)
move_A2_vals.update({
'product_uom_qty': 3.0,
})
move_A2 = self.env['stock.move'].create(move_A2_vals)
moves = move_A1 + move_A2
self.assertEqual(move_A1.procure_method, 'make_to_stock', 'Move A1 should be "make_to_stock"')
self.assertEqual(move_A2.procure_method, 'make_to_stock', 'Move A2 should be "make_to_stock"')
move_A1._action_confirm()
moves._adjust_procure_method()
self.assertEqual(move_A1.procure_method, 'make_to_order', 'Move A should be "make_to_stock"')
self.assertEqual(move_A2.procure_method, 'make_to_stock', 'Move A should be "make_to_order"')
def test_delay_alert_3(self):
warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1)
warehouse.delivery_steps = 'pick_pack_ship'
partner_demo_customer = self.partner
final_location = partner_demo_customer.property_stock_customer
product_a = self.env['product.product'].create({
'name': 'ProductA',
'type': 'product',
})
pg = self.env['procurement.group'].create({'name': 'Test-delay_alert_3'})
self.env['procurement.group'].run([
pg.Procurement(
product_a,
4.0,
product_a.uom_id,
final_location,
'delay',
'delay',
warehouse.company_id,
{
'warehouse_id': warehouse,
'group_id': pg
}
),
])
ship, pack, pick = self.env['stock.move'].search([('product_id', '=', product_a.id)])
# by default they all the same `date`
self.assertEqual(set((ship + pack + pick).mapped('date')), {pick.date})
# pick - pack - ship
ship.date += timedelta(days=2)
pack.date += timedelta(days=1)
self.assertFalse(pick.delay_alert_date)
self.assertFalse(pack.delay_alert_date)
self.assertFalse(ship.delay_alert_date)
# move the pack after the ship
# pick - ship - pack
pack.date += timedelta(days=2)
self.assertFalse(pick.delay_alert_date)
self.assertFalse(pack.delay_alert_date)
self.assertTrue(ship.delay_alert_date)
self.assertAlmostEqual(ship.delay_alert_date, pack.date)
# restore the pack before the ship
# pick - pack - ship
pack.date -= timedelta(days=2)
self.assertFalse(pick.delay_alert_date)
self.assertFalse(pack.delay_alert_date)
self.assertFalse(ship.delay_alert_date)
# move the pick after the pack
# pack - ship - pick
pick.date += timedelta(days=3)
self.assertFalse(pick.delay_alert_date)
self.assertTrue(pack.delay_alert_date)
self.assertFalse(ship.delay_alert_date)
self.assertAlmostEqual(pack.delay_alert_date, pick.date)
# move the ship before the pack
# ship - pack - pick
ship.date -= timedelta(days=2)
self.assertFalse(pick.delay_alert_date)
self.assertTrue(pack.delay_alert_date)
self.assertTrue(ship.delay_alert_date)
self.assertAlmostEqual(pack.delay_alert_date, pick.date)
self.assertAlmostEqual(ship.delay_alert_date, pack.date)
# move the pack at the end
# ship - pick - pack
pack.date = pick.date + timedelta(days=2)
self.assertFalse(pick.delay_alert_date)
self.assertFalse(pack.delay_alert_date)
self.assertTrue(ship.delay_alert_date)
self.assertAlmostEqual(ship.delay_alert_date, pack.date)
# fix the ship
ship.date = pack.date + timedelta(days=2)
self.assertFalse(pick.delay_alert_date)
self.assertFalse(pack.delay_alert_date)
self.assertFalse(ship.delay_alert_date)
def test_packaging_route(self):
"""Create a route for product and another route for its packaging. Create
a move of this product with this packaging. Check packaging route has
priority over product route.
"""
stock_location = self.env.ref('stock.stock_location_stock')
push_location_1 = self.env['stock.location'].create({
'location_id': stock_location.location_id.id,
'name': 'push location 1',
})
push_location_2 = self.env['stock.location'].create({
'location_id': stock_location.location_id.id,
'name': 'push location 2',
})
route_on_product = self.env['stock.location.route'].create({
'name': 'route on product',
'rule_ids': [(0, False, {
'name': 'create a move to push location 1',
'location_src_id': stock_location.id,
'location_id': push_location_1.id,
'company_id': self.env.company.id,
'action': 'push',
'auto': 'manual',
'picking_type_id': self.env.ref('stock.picking_type_in').id,
})],
})
route_on_packaging = self.env['stock.location.route'].create({
'name': 'route on packaging',
'packaging_selectable': True,
'rule_ids': [(0, False, {
'name': 'create a move to push location 2',
'location_src_id': stock_location.id,
'location_id': push_location_2.id,
'company_id': self.env.company.id,
'action': 'push',
'auto': 'manual',
'picking_type_id': self.env.ref('stock.picking_type_in').id,
})],
})
product = self.env['product.product'].create({
'name': 'Product with packaging',
'type': 'product',
'route_ids': [(4, route_on_product.id, 0)]
})
packaging = self.env['product.packaging'].create({
'name': 'box',
'product_id': product.id,
'route_ids': [(4, route_on_packaging.id, 0)]
})
move1 = self.env['stock.move'].create({
'name': 'move with a route',
'location_id': stock_location.id,
'location_dest_id': stock_location.id,
'product_id': product.id,
'product_packaging_id': packaging.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 1.0,
})
move1._action_confirm()
pushed_move = move1.move_dest_ids
self.assertEqual(pushed_move.location_dest_id.id, push_location_2.id)
class TestAutoAssign(TestStockCommon):
def create_pick_ship(self):
picking_client = self.env['stock.picking'].create({
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
'picking_type_id': self.picking_type_out,
})
dest = self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 10,
'product_uom': self.productA.uom_id.id,
'picking_id': picking_client.id,
'location_id': self.pack_location,
'location_dest_id': self.customer_location,
'state': 'waiting',
'procure_method': 'make_to_order',
})
picking_pick = self.env['stock.picking'].create({
'location_id': self.stock_location,
'location_dest_id': self.pack_location,
'picking_type_id': self.picking_type_out,
})
self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 10,
'product_uom': self.productA.uom_id.id,
'picking_id': picking_pick.id,
'location_id': self.stock_location,
'location_dest_id': self.pack_location,
'move_dest_ids': [(4, dest.id)],
'state': 'confirmed',
})
return picking_pick, picking_client
def test_auto_assign_0(self):
"""Create a outgoing MTS move without enough products in stock, then
validate a incoming move to check if the outgoing move is automatically
assigned.
"""
pack_location = self.env['stock.location'].browse(self.pack_location)
stock_location = self.env['stock.location'].browse(self.stock_location)
self.env['stock.picking.type'].browse(self.picking_type_out).reservation_method = 'at_confirm'
# create customer picking and move
customer_picking = self.env['stock.picking'].create({
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
'picking_type_id': self.picking_type_out,
})
customer_move = self.env['stock.move'].create({
'name': 'customer move',
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
'product_id': self.productA.id,
'product_uom': self.productA.uom_id.id,
'product_uom_qty': 10.0,
'picking_id': customer_picking.id,
'picking_type_id': self.picking_type_out,
})
customer_picking.action_confirm()
customer_picking.action_assign()
self.assertEqual(customer_move.state, 'confirmed')
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.productA, stock_location), 0)
# create supplier picking and move
supplier_picking = self.env['stock.picking'].create({
'location_id': self.customer_location,
'location_dest_id': self.stock_location,
'picking_type_id': self.picking_type_in,
})
supplier_move = self.env['stock.move'].create({
'name': 'test_transit_1',
'location_id': self.customer_location,
'location_dest_id': self.stock_location,
'product_id': self.productA.id,
'product_uom': self.productA.uom_id.id,
'product_uom_qty': 10.0,
'picking_id': supplier_picking.id,
})
customer_picking.action_confirm()
customer_picking.action_assign()
supplier_move.quantity_done = 10
supplier_picking._action_done()
# customer move should be automatically assigned and no more available product in stock
self.assertEqual(customer_move.state, 'assigned')
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.productA, stock_location), 0)
def test_auto_assign_1(self):
"""Create a outgoing MTO move without enough products, then validate a
move to make it available to check if the outgoing move is not
automatically assigned.
"""
picking_pick, picking_client = self.create_pick_ship()
pack_location = self.env['stock.location'].browse(self.pack_location)
stock_location = self.env['stock.location'].browse(self.stock_location)
self.env['stock.picking.type'].browse(self.picking_type_out).reservation_method = 'at_confirm'
# make some stock
self.env['stock.quant']._update_available_quantity(self.productA, stock_location, 10.0)
# create another move to make product available in pack_location
picking_pick_2 = self.env['stock.picking'].create({
'location_id': self.stock_location,
'location_dest_id': self.pack_location,
'picking_type_id': self.picking_type_out,
})
self.MoveObj.create({
'name': self.productA.name,
'product_id': self.productA.id,
'product_uom_qty': 10,
'product_uom': self.productA.uom_id.id,
'picking_id': picking_pick_2.id,
'location_id': self.stock_location,
'location_dest_id': self.pack_location,
'state': 'confirmed',
})
picking_pick_2.action_assign()
picking_pick_2.move_lines[0].move_line_ids[0].qty_done = 10.0
picking_pick_2._action_done()
self.assertEqual(picking_client.state, 'waiting', "MTO moves can't be automatically assigned.")
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.productA, pack_location), 10.0)
def test_auto_assign_reservation_method(self):
"""Test different stock.picking.type reservation methods by:
1. Create multiple delivery picking types with different reservation methods
2. Create/confirm outgoing pickings for each of these picking types for a product not in stock
3. Create/do an incoming picking that fulfills all of the outgoing pickings
4. Check that only the correct outgoing pickings are auto_assigned
5. Additionally check that auto-assignment at confirmation correctly works when products are in stock
Note, default reservation method is expected to be covered by other tests.
Also check reservation_dates are as expected
"""
stock_location = self.env['stock.location'].browse(self.stock_location)
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.productA, stock_location), 0)
picking_type_out1 = self.env['stock.picking.type'].browse(self.picking_type_out).copy()
picking_type_out2 = picking_type_out1.copy()
picking_type_out3 = picking_type_out1.copy()
picking_type_out4 = picking_type_out1.copy()
picking_type_out1.reservation_method = 'manual'
picking_type_out2.reservation_method = 'by_date'
picking_type_out2.reservation_days_before = '1'
picking_type_out3.reservation_method = 'by_date'
picking_type_out3.reservation_days_before = '10'
picking_type_out4.reservation_method = 'at_confirm'
# 'manual' assign picking => should never auto-assign
customer_picking1 = self.env['stock.picking'].create({
'name': "Delivery 1",
'location_id': self.stock_location,
'location_dest_id': self.customer_location,
'picking_type_id': picking_type_out1.id,
})
# 'by_date' picking w/ 1 day before scheduled date auto-assign setting, set to 5 days in advance => shouldn't auto-assign
customer_picking2 = customer_picking1.copy({'name': "Delivery 2",
'picking_type_id': picking_type_out2.id,
'scheduled_date': customer_picking1.scheduled_date + timedelta(days=5)})
# 'by_date' picking w/ 10 days before scheduled date auto-assign setting, set to 5 days in advance => should auto-assign
customer_picking3 = customer_picking2.copy({'name': "Delivery 3", 'picking_type_id': picking_type_out3.id})
customer_picking4 = customer_picking3.copy({'name': "Delivery 4", 'picking_type_id': picking_type_out3.id})
# 'at_confirm' picking
customer_picking5 = customer_picking1.copy({'name': "Delivery 5", 'picking_type_id': picking_type_out4.id})
# create their associated moves (needs to be in form view so compute functions properly trigger)
customer_picking1 = Form(customer_picking1)
with customer_picking1.move_ids_without_package.new() as move:
move.product_id = self.productA
move.product_uom_qty = 10
customer_picking1 = customer_picking1.save()
customer_picking2 = Form(customer_picking2)
with customer_picking2.move_ids_without_package.new() as move:
move.product_id = self.productA
move.product_uom_qty = 10
customer_picking2 = customer_picking2.save()
customer_picking3 = Form(customer_picking3)
with customer_picking3.move_ids_without_package.new() as move:
move.product_id = self.productA
move.product_uom_qty = 10
customer_picking3 = customer_picking3.save()
customer_picking4 = Form(customer_picking4)
with customer_picking4.move_ids_without_package.new() as move:
move.product_id = self.productA
move.product_uom_qty = 10
customer_picking4 = customer_picking4.save()
customer_picking5 = Form(customer_picking5)
with customer_picking5.move_ids_without_package.new() as move:
move.product_id = self.productA
move.product_uom_qty = 10
customer_picking5 = customer_picking5.save()
customer_picking1.action_assign()
customer_picking2.action_assign()
customer_picking3.action_assign()
self.assertEqual(customer_picking1.move_lines.reserved_availability, 0, "There should be no products available to reserve yet.")
self.assertEqual(customer_picking2.move_lines.reserved_availability, 0, "There should be no products available to reserve yet.")
self.assertEqual(customer_picking3.move_lines.reserved_availability, 0, "There should be no products available to reserve yet.")
self.assertFalse(customer_picking1.move_lines.reservation_date, "Reservation Method: 'manual' shouldn't have a reservation_date")
self.assertEqual(customer_picking2.move_lines.reservation_date, (customer_picking2.scheduled_date - timedelta(days=1)).date(),
"Reservation Method: 'by_date' should have a reservation_date = scheduled_date - reservation_days_before")
self.assertFalse(customer_picking5.move_lines.reservation_date, "Reservation Method: 'at_confirm' shouldn't have a reservation_date until confirmed")
# create supplier picking and move
supplier_picking = self.env['stock.picking'].create({
'location_id': self.customer_location,
'location_dest_id': self.stock_location,
'picking_type_id': self.picking_type_in,
})
supplier_move = self.env['stock.move'].create({
'name': 'test_transit_1',
'location_id': self.customer_location,
'location_dest_id': self.stock_location,
'product_id': self.productA.id,
'product_uom': self.productA.uom_id.id,
'product_uom_qty': 50.0,
'picking_id': supplier_picking.id,
})
supplier_move.quantity_done = 50
supplier_picking._action_done()
self.assertEqual(customer_picking1.move_lines.reserved_availability, 0, "Reservation Method: 'manual' shouldn't ever auto-assign")
self.assertEqual(customer_picking2.move_lines.reserved_availability, 0, "Reservation Method: 'by_date' shouldn't auto-assign when not within reservation date range")
self.assertEqual(customer_picking3.move_lines.reserved_availability, 10, "Reservation Method: 'by_date' should auto-assign when within reservation date range")
self.assertEqual(self.env['stock.quant']._get_available_quantity(self.productA, stock_location), 40)
customer_picking4.action_confirm()
customer_picking5.action_confirm()
self.assertEqual(customer_picking4.move_lines.reserved_availability, 10, "Reservation Method: 'by_date' should auto-assign when within reservation date range at confirmation")
self.assertEqual(customer_picking5.move_lines.reserved_availability, 10, "Reservation Method: 'at_confirm' should auto-assign at confirmation")
def test_serial_lot_ids(self):
self.stock_location = self.env.ref('stock.stock_location_stock')
self.customer_location = self.env.ref('stock.stock_location_customers')
self.supplier_location = self.env.ref('stock.stock_location_suppliers')
self.uom_unit = self.env.ref('uom.product_uom_unit')
self.product_serial = self.env['product.product'].create({
'name': 'PSerial',
'type': 'product',
'tracking': 'serial',
'categ_id': self.env.ref('product.product_category_all').id,
})
move = self.env['stock.move'].create({
'name': 'TestReceive',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product_serial.id,
'product_uom': self.uom_unit.id,
'picking_type_id': self.env.ref('stock.picking_type_in').id,
})
self.assertEqual(move.state, 'draft')
lot1 = self.env['stock.production.lot'].create({
'name': 'serial1',
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
lot2 = self.env['stock.production.lot'].create({
'name': 'serial2',
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
lot3 = self.env['stock.production.lot'].create({
'name': 'serial3',
'product_id': self.product_serial.id,
'company_id': self.env.company.id,
})
move.lot_ids = [(4, lot1.id)]
move.lot_ids = [(4, lot2.id)]
move.lot_ids = [(4, lot3.id)]
self.assertEqual(move.quantity_done, 3.0)
move.lot_ids = [(3, lot2.id)]
self.assertEqual(move.quantity_done, 2.0)
self.uom_dozen = self.env.ref('uom.product_uom_dozen')
move = self.env['stock.move'].create({
'name': 'TestReceiveDozen',
'location_id': self.supplier_location.id,
'location_dest_id': self.stock_location.id,
'product_id': self.product_serial.id,
'product_uom': self.uom_dozen.id,
'picking_type_id': self.env.ref('stock.picking_type_in').id,
})
move.lot_ids = [(4, lot1.id)]
move.lot_ids = [(4, lot2.id)]
move.lot_ids = [(4, lot3.id)]
self.assertEqual(move.quantity_done, 3.0/12.0)
def test_update_description(self):
""" Create an empty picking. Adds a move on product1, select the picking type, add
again a move on product1. Confirm the picking. The two stock moves should be merged. """
product1 = self.env['product.product'].create({
'name': 'product',
'type':'product',
})
picking_form = Form(self.env['stock.picking'])
with picking_form.move_ids_without_package.new() as move:
move.product_id = product1
move.product_uom_qty = 10
move.location_id = self.env.ref('stock.stock_location_suppliers')
move.location_dest_id = self.env.ref('stock.stock_location_stock')
picking_form.picking_type_id = self.env.ref('stock.picking_type_in')
with picking_form.move_ids_without_package.new() as move:
move.product_id = product1
move.product_uom_qty = 15
picking = picking_form.save()
picking.action_confirm()
self.assertEqual(len(picking.move_lines), 1)
self.assertEqual(picking.move_lines.product_uom_qty, 25)
| 46.897199
| 167,423
|
2,023
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
from odoo.addons.mail.tests.common import mail_new_test_user
from odoo.addons.product.tests import common
class TestStockCommon(common.TestProductCommon):
def _create_move(self, product, src_location, dst_location, **values):
# TDE FIXME: user as parameter
Move = self.env['stock.move'].with_user(self.user_stock_manager)
# simulate create + onchange
move = Move.new({'product_id': product.id, 'location_id': src_location.id, 'location_dest_id': dst_location.id})
move._onchange_product_id()
move_values = move._convert_to_write(move._cache)
move_values.update(**values)
return Move.create(move_values)
@classmethod
def setUpClass(cls):
super(TestStockCommon, cls).setUpClass()
# User Data: stock user and stock manager
cls.user_stock_user = mail_new_test_user(
cls.env,
name='Pauline Poivraisselle',
login='pauline',
email='p.p@example.com',
notification_type='inbox',
groups='stock.group_stock_user',
)
cls.user_stock_manager = mail_new_test_user(
cls.env,
name='Julie Tablier',
login='julie',
email='j.j@example.com',
notification_type='inbox',
groups='stock.group_stock_manager',
)
# Warehouses
cls.warehouse_1 = cls.env['stock.warehouse'].create({
'name': 'Base Warehouse',
'reception_steps': 'one_step',
'delivery_steps': 'ship_only',
'code': 'BWH'})
# Locations
cls.location_1 = cls.env['stock.location'].create({
'name': 'TestLocation1',
'posx': 3,
'location_id': cls.warehouse_1.lot_stock_id.id,
})
# Existing data
cls.existing_inventories = cls.env['stock.quant'].search([('inventory_quantity', '!=', 0.0)])
cls.existing_quants = cls.env['stock.quant'].search([])
| 35.491228
| 2,023
|
19,037
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.exceptions import UserError, ValidationError
from odoo.tests.common import Form, TransactionCase
class StockGenerate(TransactionCase):
@classmethod
def setUpClass(cls):
super(StockGenerate, cls).setUpClass()
Product = cls.env['product.product']
cls.product_serial = Product.create({
'name': 'Tracked by SN',
'type': 'product',
'tracking': 'serial',
})
cls.uom_unit = cls.env.ref('uom.product_uom_unit')
cls.warehouse = cls.env['stock.warehouse'].create({
'name': 'Base Warehouse',
'reception_steps': 'one_step',
'delivery_steps': 'ship_only',
'code': 'BWH'
})
cls.location = cls.env['stock.location'].create({
'name': 'Room A',
'location_id': cls.warehouse.lot_stock_id.id,
})
cls.location_dest = cls.env['stock.location'].create({
'name': 'Room B',
'location_id': cls.warehouse.lot_stock_id.id,
})
cls.Wizard = cls.env['stock.assign.serial']
def get_new_move(self, nbre_of_lines):
move_lines_val = []
for i in range(nbre_of_lines):
move_lines_val.append({
'product_id': self.product_serial.id,
'product_uom_id': self.uom_unit.id,
'product_uom_qty': 1,
'location_id': self.location.id,
'location_dest_id': self.location_dest.id
})
return self.env['stock.move'].create({
'name': 'Move Test',
'product_id': self.product_serial.id,
'product_uom': self.uom_unit.id,
'location_id': self.location.id,
'location_dest_id': self.location_dest.id,
'move_line_ids': [(0, 0, line_vals) for line_vals in move_lines_val]
})
def test_generate_01_sn(self):
""" Creates a move with 5 move lines, then asks for generates 5 Serial
Numbers. Checks move has 5 new move lines with each a SN, and the 5
original move lines are still unchanged.
"""
nbre_of_lines = 5
move = self.get_new_move(nbre_of_lines)
form_wizard = Form(self.env['stock.assign.serial'].with_context(
default_move_id=move.id,
default_next_serial_number='001',
default_next_serial_count=nbre_of_lines,
))
wiz = form_wizard.save()
self.assertEqual(len(move.move_line_ids), nbre_of_lines)
wiz.generate_serial_numbers()
# Checks new move lines have the right SN
generated_numbers = ['001', '002', '003', '004', '005']
self.assertEqual(len(move.move_line_ids), nbre_of_lines + len(generated_numbers))
for move_line in move.move_line_nosuggest_ids:
# For a product tracked by SN, the `qty_done` is set on 1 when
# `lot_name` is set.
self.assertEqual(move_line.qty_done, 1)
self.assertEqual(move_line.lot_name, generated_numbers.pop(0))
# Checks pre-generated move lines didn't change
for move_line in (move.move_line_ids - move.move_line_nosuggest_ids):
self.assertEqual(move_line.qty_done, 0)
self.assertEqual(move_line.lot_name, False)
def test_generate_02_prefix_suffix(self):
""" Generates some Serial Numbers and checks the prefix and/or suffix
are correctly used.
"""
nbre_of_lines = 10
# Case #1: Prefix, no suffix
move = self.get_new_move(nbre_of_lines)
form_wizard = Form(self.env['stock.assign.serial'].with_context(
default_move_id=move.id,
default_next_serial_number='bilou-87',
default_next_serial_count=nbre_of_lines,
))
wiz = form_wizard.save()
wiz.generate_serial_numbers()
# Checks all move lines have the right SN
generated_numbers = [
'bilou-87', 'bilou-88', 'bilou-89', 'bilou-90', 'bilou-91',
'bilou-92', 'bilou-93', 'bilou-94', 'bilou-95', 'bilou-96'
]
for move_line in move.move_line_nosuggest_ids:
# For a product tracked by SN, the `qty_done` is set on 1 when
# `lot_name` is set.
self.assertEqual(move_line.qty_done, 1)
self.assertEqual(
move_line.lot_name,
generated_numbers.pop(0)
)
# Case #2: No prefix, suffix
move = self.get_new_move(nbre_of_lines)
form_wizard = Form(self.env['stock.assign.serial'].with_context(
default_move_id=move.id,
default_next_serial_number='005-ccc',
default_next_serial_count=nbre_of_lines,
))
wiz = form_wizard.save()
wiz.generate_serial_numbers()
# Checks all move lines have the right SN
generated_numbers = [
'005-ccc', '006-ccc', '007-ccc', '008-ccc', '009-ccc',
'010-ccc', '011-ccc', '012-ccc', '013-ccc', '014-ccc'
]
for move_line in move.move_line_nosuggest_ids:
# For a product tracked by SN, the `qty_done` is set on 1 when
# `lot_name` is set.
self.assertEqual(move_line.qty_done, 1)
self.assertEqual(
move_line.lot_name,
generated_numbers.pop(0)
)
# Case #3: Prefix + suffix
move = self.get_new_move(nbre_of_lines)
form_wizard = Form(self.env['stock.assign.serial'].with_context(
default_move_id=move.id,
default_next_serial_number='alpha-012-345-beta',
default_next_serial_count=nbre_of_lines,
))
wiz = form_wizard.save()
wiz.generate_serial_numbers()
# Checks all move lines have the right SN
generated_numbers = [
'alpha-012-345-beta', 'alpha-012-346-beta', 'alpha-012-347-beta',
'alpha-012-348-beta', 'alpha-012-349-beta', 'alpha-012-350-beta',
'alpha-012-351-beta', 'alpha-012-352-beta', 'alpha-012-353-beta',
'alpha-012-354-beta'
]
for move_line in move.move_line_nosuggest_ids:
# For a product tracked by SN, the `qty_done` is set on 1 when
# `lot_name` is set.
self.assertEqual(move_line.qty_done, 1)
self.assertEqual(
move_line.lot_name,
generated_numbers.pop(0)
)
# Case #4: Prefix + suffix, identical number pattern
move = self.get_new_move(nbre_of_lines)
form_wizard = Form(self.env['stock.assign.serial'].with_context(
default_move_id=move.id,
default_next_serial_number='BAV023B00001S00001',
default_next_serial_count=nbre_of_lines,
))
wiz = form_wizard.save()
wiz.generate_serial_numbers()
# Checks all move lines have the right SN
generated_numbers = [
'BAV023B00001S00001', 'BAV023B00001S00002', 'BAV023B00001S00003',
'BAV023B00001S00004', 'BAV023B00001S00005', 'BAV023B00001S00006',
'BAV023B00001S00007', 'BAV023B00001S00008', 'BAV023B00001S00009',
'BAV023B00001S00010'
]
for move_line in move.move_line_nosuggest_ids:
# For a product tracked by SN, the `qty_done` is set on 1 when
# `lot_name` is set.
self.assertEqual(move_line.qty_done, 1)
self.assertEqual(
move_line.lot_name,
generated_numbers.pop(0)
)
def test_generate_03_raise_exception(self):
""" Tries to generate some SN but with invalid initial number.
"""
move = self.get_new_move(3)
form_wizard = Form(self.env['stock.assign.serial'].with_context(
default_move_id=move.id,
default_next_serial_number='code-xxx',
))
form_wizard.next_serial_count = 0
# Must raise an exception because `next_serial_count` must be greater than 0.
with self.assertRaises(ValidationError):
form_wizard.save()
form_wizard.next_serial_count = 3
wiz = form_wizard.save()
wiz.generate_serial_numbers()
self.assertEqual(move.move_line_nosuggest_ids.mapped('lot_name'), ["code-xxx0", "code-xxx1", "code-xxx2"])
def test_generate_04_generate_in_multiple_time(self):
""" Generates a Serial Number for each move lines (except the last one)
but with multiple assignments, and checks the generated Serial Numbers
are what we expect.
"""
nbre_of_lines = 10
move = self.get_new_move(nbre_of_lines)
form_wizard = Form(self.env['stock.assign.serial'].with_context(
default_move_id=move.id,
))
# First assignment
form_wizard.next_serial_count = 3
form_wizard.next_serial_number = '001'
wiz = form_wizard.save()
wiz.generate_serial_numbers()
# Second assignment
form_wizard.next_serial_count = 2
form_wizard.next_serial_number = 'bilou-64'
wiz = form_wizard.save()
wiz.generate_serial_numbers()
# Third assignment
form_wizard.next_serial_count = 4
form_wizard.next_serial_number = 'ro-1337-bot'
wiz = form_wizard.save()
wiz.generate_serial_numbers()
# Checks all move lines have the right SN
generated_numbers = [
# Correspond to the first assignment
'001', '002', '003',
# Correspond to the second assignment
'bilou-64', 'bilou-65',
# Correspond to the third assignment
'ro-1337-bot', 'ro-1338-bot', 'ro-1339-bot', 'ro-1340-bot',
]
self.assertEqual(len(move.move_line_ids), nbre_of_lines + len(generated_numbers))
self.assertEqual(len(move.move_line_nosuggest_ids), len(generated_numbers))
for move_line in move.move_line_nosuggest_ids:
self.assertEqual(move_line.qty_done, 1)
self.assertEqual(move_line.lot_name, generated_numbers.pop(0))
for move_line in (move.move_line_ids - move.move_line_nosuggest_ids):
self.assertEqual(move_line.qty_done, 0)
self.assertEqual(move_line.lot_name, False)
def test_generate_with_putaway(self):
""" Checks the `location_dest_id` of generated move lines is correclty
set in fonction of defined putaway rules.
"""
nbre_of_lines = 4
shelf_location = self.env['stock.location'].create({
'name': 'shelf1',
'usage': 'internal',
'location_id': self.location_dest.id,
})
# Checks a first time without putaway...
move = self.get_new_move(nbre_of_lines)
form_wizard = Form(self.env['stock.assign.serial'].with_context(
default_move_id=move.id,
))
form_wizard.next_serial_count = nbre_of_lines
form_wizard.next_serial_number = '001'
wiz = form_wizard.save()
wiz.generate_serial_numbers()
for move_line in move.move_line_nosuggest_ids:
self.assertEqual(move_line.qty_done, 1)
# The location dest must be the default one.
self.assertEqual(move_line.location_dest_id.id, self.location_dest.id)
# We need to activate multi-locations to use putaway rules.
grp_multi_loc = self.env.ref('stock.group_stock_multi_locations')
self.env.user.write({'groups_id': [(4, grp_multi_loc.id)]})
# Creates a putaway rule
putaway_product = self.env['stock.putaway.rule'].create({
'product_id': self.product_serial.id,
'location_in_id': self.location_dest.id,
'location_out_id': shelf_location.id,
})
# Checks now with putaway...
move = self.get_new_move(nbre_of_lines)
form_wizard = Form(self.env['stock.assign.serial'].with_context(
default_move_id=move.id,
))
form_wizard.next_serial_count = nbre_of_lines
form_wizard.next_serial_number = '001'
wiz = form_wizard.save()
wiz.generate_serial_numbers()
for move_line in move.move_line_nosuggest_ids:
self.assertEqual(move_line.qty_done, 1)
# The location dest must be now the one from the putaway.
self.assertEqual(move_line.location_dest_id.id, shelf_location.id)
def test_set_multiple_lot_name_01(self):
""" Sets five SN in one time in stock move view form, then checks move
has five new move lines with the right `lot_name`.
"""
nbre_of_lines = 10
picking_type = self.env['stock.picking.type'].search([
('use_create_lots', '=', True),
('warehouse_id', '=', self.warehouse.id)
])
move = self.get_new_move(nbre_of_lines)
move.picking_type_id = picking_type
# We must begin with a move with 10 move lines.
self.assertEqual(len(move.move_line_ids), nbre_of_lines)
value_list = [
'abc-235',
'abc-237',
'abc-238',
'abc-282',
'abc-301',
]
values = '\n'.join(value_list)
move_form = Form(move, view='stock.view_stock_move_nosuggest_operations')
with move_form.move_line_nosuggest_ids.new() as line:
line.lot_name = values
move = move_form.save()
# After we set multiple SN, we must have now 15 move lines.
self.assertEqual(len(move.move_line_ids), nbre_of_lines + len(value_list))
# Then we look each SN name is correct.
for move_line in move.move_line_nosuggest_ids:
self.assertEqual(move_line.lot_name, value_list.pop(0))
for move_line in (move.move_line_ids - move.move_line_nosuggest_ids):
self.assertEqual(move_line.lot_name, False)
def test_set_multiple_lot_name_02_empty_values(self):
""" Sets multiple values with some empty lines in one time, then checks
we haven't create useless move line and all move line's `lot_name` have
been correctly set.
"""
nbre_of_lines = 5
picking_type = self.env['stock.picking.type'].search([
('use_create_lots', '=', True),
('warehouse_id', '=', self.warehouse.id)
])
move = self.get_new_move(nbre_of_lines)
move.picking_type_id = picking_type
# We must begin with a move with five move lines.
self.assertEqual(len(move.move_line_ids), nbre_of_lines)
value_list = [
'',
'abc-235',
'',
'abc-237',
'',
'',
'abc-238',
'abc-282',
'abc-301',
'',
]
values = '\n'.join(value_list)
# Checks we have more values than move lines.
self.assertTrue(len(move.move_line_ids) < len(value_list))
move_form = Form(move, view='stock.view_stock_move_nosuggest_operations')
with move_form.move_line_nosuggest_ids.new() as line:
line.lot_name = values
move = move_form.save()
filtered_value_list = list(filter(lambda line: len(line), value_list))
# After we set multiple SN, we must have a line for each value.
self.assertEqual(len(move.move_line_ids), nbre_of_lines + len(filtered_value_list))
# Then we look each SN name is correct.
for move_line in move.move_line_nosuggest_ids:
self.assertEqual(move_line.lot_name, filtered_value_list.pop(0))
for move_line in (move.move_line_ids - move.move_line_nosuggest_ids):
self.assertEqual(move_line.lot_name, False)
def test_generate_with_putaway_02(self):
"""
Suppose a tracked-by-USN product P
Sub locations in WH/Stock + Storage Category
The Storage Category adds a capacity constraint (max 1 x P / Location)
- Plan a receipt with 2 x P
- Receive 4 x P
-> The test ensures that the destination locations are correct
"""
stock_location = self.warehouse.lot_stock_id
self.env.user.write({'groups_id': [(4, self.env.ref('stock.group_stock_storage_categories').id)]})
self.env.user.write({'groups_id': [(4, self.env.ref('stock.group_stock_multi_locations').id)]})
# max 1 x product_serial
stor_category = self.env['stock.storage.category'].create({
'name': 'Super Storage Category',
'product_capacity_ids': [(0, 0, {
'product_id': self.product_serial.id,
'quantity': 1,
})]
})
# 5 sub locations with the storage category
# (the last one should never be used)
sub_loc_01, sub_loc_02, sub_loc_03, sub_loc_04, dummy = self.env['stock.location'].create([{
'name': 'Sub Location %s' % i,
'usage': 'internal',
'location_id': stock_location.id,
'storage_category_id': stor_category.id,
} for i in [1, 2, 3, 4, 5]])
self.env['stock.putaway.rule'].create({
'location_in_id': stock_location.id,
'location_out_id': stock_location.id,
'product_id': self.product_serial.id,
'storage_category_id': stor_category.id,
})
# Receive 1 x P
receipt_picking = self.env['stock.picking'].create({
'picking_type_id': self.warehouse.in_type_id.id,
'location_id': self.env.ref('stock.stock_location_suppliers').id,
'location_dest_id': stock_location.id,
})
move = self.env['stock.move'].create({
'name': self.product_serial.name,
'product_id': self.product_serial.id,
'product_uom': self.product_serial.uom_id.id,
'product_uom_qty': 2.0,
'picking_id': receipt_picking.id,
'location_id': receipt_picking.location_id.id,
'location_dest_id': receipt_picking.location_dest_id.id,
})
receipt_picking.action_confirm()
self.assertEqual(move.move_line_ids[0].location_dest_id, sub_loc_01)
self.assertEqual(move.move_line_ids[1].location_dest_id, sub_loc_02)
form_wizard = Form(self.env['stock.assign.serial'].with_context(
default_move_id=move.id,
default_next_serial_number='001',
default_next_serial_count=4,
))
wiz = form_wizard.save()
wiz.generate_serial_numbers()
self.assertRecordValues(move.move_line_ids, [
{'qty_done': 1, 'lot_name': '001', 'location_dest_id': sub_loc_01.id},
{'qty_done': 1, 'lot_name': '002', 'location_dest_id': sub_loc_02.id},
{'qty_done': 1, 'lot_name': '003', 'location_dest_id': sub_loc_03.id},
{'qty_done': 1, 'lot_name': '004', 'location_dest_id': sub_loc_04.id},
])
| 42.024283
| 19,037
|
21,730
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import date, datetime, timedelta
from odoo.tests.common import Form, TransactionCase
from odoo.tools import mute_logger
from odoo.exceptions import UserError
class TestProcRule(TransactionCase):
def setUp(self):
super(TestProcRule, self).setUp()
self.uom_unit = self.env.ref('uom.product_uom_unit')
self.product = self.env['product.product'].create({
'name': 'Desk Combination',
'type': 'consu',
})
self.partner = self.env['res.partner'].create({'name': 'Partner'})
def test_endless_loop_rules_from_location(self):
""" Creates and configure a rule the way, when trying to get rules from
location, it goes in a state where the found rule tries to trigger another
rule but finds nothing else than itself and so get stuck in a recursion error."""
warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1)
reception_route = warehouse.reception_route_id
self.product.type = 'product'
# Creates a delivery for this product, that way, this product will be to resupply.
picking_form = Form(self.env['stock.picking'])
picking_form.picking_type_id = warehouse.out_type_id
with picking_form.move_ids_without_package.new() as move_line:
move_line.product_id = self.product
move_line.product_uom_qty = 10
delivery = picking_form.save()
delivery.action_confirm()
self.product._compute_quantities() # Computes `outgoing_qty` to have the orderpoint.
# Then, creates a rule and adds it into the route's rules.
reception_route.rule_ids.action_archive()
self.env['stock.rule'].create({
'name': 'Looping Rule',
'route_id': reception_route.id,
'location_id': warehouse.lot_stock_id.id,
'location_src_id': warehouse.lot_stock_id.id,
'action': 'pull_push',
'procure_method': 'make_to_order',
'picking_type_id': warehouse.int_type_id.id,
})
# Tries to open the Replenishment view -> It should raise an UserError.
with self.assertRaises(UserError):
self.env['stock.warehouse.orderpoint'].action_open_orderpoints()
def test_proc_rule(self):
# Create a product route containing a stock rule that will
# generate a move from Stock for every procurement created in Output
product_route = self.env['stock.location.route'].create({
'name': 'Stock -> output route',
'product_selectable': True,
'rule_ids': [(0, 0, {
'name': 'Stock -> output rule',
'action': 'pull',
'picking_type_id': self.ref('stock.picking_type_internal'),
'location_src_id': self.ref('stock.stock_location_stock'),
'location_id': self.ref('stock.stock_location_output'),
})],
})
# Set this route on `product.product_product_3`
self.product.write({
'route_ids': [(4, product_route.id)]})
# Create Delivery Order of 10 `product.product_product_3` from Output -> Customer
product = self.product
vals = {
'name': 'Delivery order for procurement',
'partner_id': self.partner.id,
'picking_type_id': self.ref('stock.picking_type_out'),
'location_id': self.ref('stock.stock_location_output'),
'location_dest_id': self.ref('stock.stock_location_customers'),
'move_lines': [(0, 0, {
'name': '/',
'product_id': product.id,
'product_uom': product.uom_id.id,
'product_uom_qty': 10.00,
'procure_method': 'make_to_order',
'location_id': self.ref('stock.stock_location_output'),
'location_dest_id': self.ref('stock.stock_location_customers'),
})],
}
pick_output = self.env['stock.picking'].create(vals)
pick_output.move_lines._onchange_product_id()
# Confirm delivery order.
pick_output.action_confirm()
# I run the scheduler.
# Note: If purchase if already installed, the method _run_buy will be called due
# to the purchase demo data. As we update the stock module to run this test, the
# method won't be an attribute of stock.procurement at this moment. For that reason
# we mute the logger when running the scheduler.
with mute_logger('odoo.addons.stock.models.procurement'):
self.env['procurement.group'].run_scheduler()
# Check that a picking was created from stock to output.
moves = self.env['stock.move'].search([
('product_id', '=', self.product.id),
('location_id', '=', self.ref('stock.stock_location_stock')),
('location_dest_id', '=', self.ref('stock.stock_location_output')),
('move_dest_ids', 'in', [pick_output.move_lines[0].id])
])
self.assertEqual(len(moves.ids), 1, "It should have created a picking from Stock to Output with the original picking as destination")
def test_propagate_deadline_move(self):
deadline = datetime.now()
move_dest = self.env['stock.move'].create({
'name': 'move_dest',
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'date_deadline': deadline,
'location_id': self.ref('stock.stock_location_output'),
'location_dest_id': self.ref('stock.stock_location_customers'),
})
move_orig = self.env['stock.move'].create({
'name': 'move_orig',
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'date_deadline': deadline,
'move_dest_ids': [(4, move_dest.id)],
'location_id': self.ref('stock.stock_location_stock'),
'location_dest_id': self.ref('stock.stock_location_output'),
'quantity_done': 10,
})
new_deadline = move_orig.date_deadline - timedelta(days=6)
move_orig.date_deadline = new_deadline
self.assertEqual(move_dest.date_deadline, new_deadline, msg='deadline date should be propagated')
move_orig._action_done()
self.assertAlmostEqual(move_orig.date, datetime.now(), delta=timedelta(seconds=10), msg='date should be now')
self.assertEqual(move_orig.date_deadline, new_deadline, msg='deadline date should be unchanged')
self.assertEqual(move_dest.date_deadline, new_deadline, msg='deadline date should be unchanged')
def test_reordering_rule_1(self):
warehouse = self.env['stock.warehouse'].search([], limit=1)
orderpoint_form = Form(self.env['stock.warehouse.orderpoint'])
orderpoint_form.product_id = self.product
orderpoint_form.location_id = warehouse.lot_stock_id
orderpoint_form.product_min_qty = 0.0
orderpoint_form.product_max_qty = 5.0
orderpoint = orderpoint_form.save()
# get auto-created pull rule from when warehouse is created
rule = self.env['stock.rule'].search([
('route_id', '=', warehouse.reception_route_id.id),
('location_id', '=', warehouse.lot_stock_id.id),
('location_src_id', '=', self.env.ref('stock.stock_location_suppliers').id),
('action', '=', 'pull'),
('procure_method', '=', 'make_to_stock'),
('picking_type_id', '=', warehouse.in_type_id.id)])
# add a delay [i.e. lead days] so procurement will be triggered based on forecasted stock
rule.delay = 9.0
delivery_move = self.env['stock.move'].create({
'name': 'Delivery',
'date': datetime.today() + timedelta(days=5),
'product_id': self.product.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 12.0,
'location_id': warehouse.lot_stock_id.id,
'location_dest_id': self.ref('stock.stock_location_customers'),
})
delivery_move._action_confirm()
orderpoint._compute_qty()
self.env['procurement.group'].run_scheduler()
receipt_move = self.env['stock.move'].search([
('product_id', '=', self.product.id),
('location_id', '=', self.env.ref('stock.stock_location_suppliers').id)
])
self.assertTrue(receipt_move)
self.assertEqual(receipt_move.date.date(), date.today())
self.assertEqual(receipt_move.product_uom_qty, 17.0)
def test_reordering_rule_2(self):
"""Test when there is not enough product to assign a picking => automatically run
reordering rule (RR). Add extra product to already confirmed picking => automatically
run another RR
"""
self.productA = self.env['product.product'].create({
'name': 'Desk Combination',
'type': 'product',
})
self.productB = self.env['product.product'].create({
'name': 'Desk Decoration',
'type': 'product',
})
warehouse = self.env['stock.warehouse'].search([], limit=1)
orderpoint_form = Form(self.env['stock.warehouse.orderpoint'])
orderpoint_form.product_id = self.productA
orderpoint_form.location_id = warehouse.lot_stock_id
orderpoint_form.product_min_qty = 0.0
orderpoint_form.product_max_qty = 5.0
orderpoint = orderpoint_form.save()
self.env['stock.warehouse.orderpoint'].create({
'name': 'ProductB RR',
'location_id': warehouse.lot_stock_id.id,
'product_id': self.productB.id,
'product_min_qty': 0,
'product_max_qty': 5,
})
self.env['stock.rule'].create({
'name': 'Rule Supplier',
'route_id': warehouse.reception_route_id.id,
'location_id': warehouse.lot_stock_id.id,
'location_src_id': self.env.ref('stock.stock_location_suppliers').id,
'action': 'pull',
'delay': 9.0,
'procure_method': 'make_to_stock',
'picking_type_id': warehouse.in_type_id.id,
})
delivery_picking = self.env['stock.picking'].create({
'location_id': warehouse.lot_stock_id.id,
'location_dest_id': self.ref('stock.stock_location_customers'),
'picking_type_id': self.ref('stock.picking_type_out'),
})
delivery_move = self.env['stock.move'].create({
'name': 'Delivery',
'product_id': self.productA.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 12.0,
'location_id': warehouse.lot_stock_id.id,
'location_dest_id': self.ref('stock.stock_location_customers'),
'picking_id': delivery_picking.id,
})
delivery_picking.action_confirm()
delivery_picking.action_assign()
receipt_move = self.env['stock.move'].search([
('product_id', '=', self.productA.id),
('location_id', '=', self.env.ref('stock.stock_location_suppliers').id)
])
self.assertTrue(receipt_move)
self.assertEqual(receipt_move.date.date(), date.today())
self.assertEqual(receipt_move.product_uom_qty, 17.0)
delivery_picking.write({'move_lines': [(0, 0, {
'name': 'Extra Move',
'product_id': self.productB.id,
'product_uom': self.uom_unit.id,
'product_uom_qty': 5.0,
'location_id': warehouse.lot_stock_id.id,
'location_dest_id': self.ref('stock.stock_location_customers'),
'picking_id': delivery_picking.id,
'additional': True
})]})
receipt_move2 = self.env['stock.move'].search([
('product_id', '=', self.productB.id),
('location_id', '=', self.env.ref('stock.stock_location_suppliers').id)
])
self.assertTrue(receipt_move2)
self.assertEqual(receipt_move2.date.date(), date.today())
self.assertEqual(receipt_move2.product_uom_qty, 10.0)
def test_fixed_procurement_01(self):
""" Run a procurement for 5 products when there are only 4 in stock then
check that MTO is applied on the moves when the rule is set to 'mts_else_mto'
"""
self.partner = self.env['res.partner'].create({'name': 'Partner'})
warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.env.user.id)], limit=1)
warehouse.delivery_steps = 'pick_ship'
final_location = self.partner.property_stock_customer
# Create a product and add 10 units in stock
product_a = self.env['product.product'].create({
'name': 'ProductA',
'type': 'product',
})
self.env['stock.quant']._update_available_quantity(product_a, warehouse.lot_stock_id, 10.0)
# Create a route which will allows 'wave picking'
wave_pg = self.env['procurement.group'].create({'name': 'Wave PG'})
wave_route = self.env['stock.location.route'].create({
'name': 'Wave for ProductA',
'product_selectable': True,
'sequence': 1,
'rule_ids': [(0, 0, {
'name': 'Stock -> output rule',
'action': 'pull',
'picking_type_id': self.ref('stock.picking_type_internal'),
'location_src_id': self.ref('stock.stock_location_stock'),
'location_id': self.ref('stock.stock_location_output'),
'group_propagation_option': 'fixed',
'group_id': wave_pg.id,
})],
})
# Set this route on `product_a`
product_a.write({
'route_ids': [(4, wave_route.id)]
})
# Create a procurement for 2 units
pg = self.env['procurement.group'].create({'name': 'Wave 1'})
self.env['procurement.group'].run([
pg.Procurement(
product_a,
2.0,
product_a.uom_id,
final_location,
'wave_part_1',
'wave_part_1',
warehouse.company_id,
{
'warehouse_id': warehouse,
'group_id': pg
}
)
])
# 2 pickings should be created: 1 for pick, 1 for ship
picking_pick = self.env['stock.picking'].search([('group_id', '=', wave_pg.id)])
picking_ship = self.env['stock.picking'].search([('group_id', '=', pg.id)])
self.assertAlmostEqual(picking_pick.move_lines.product_uom_qty, 2.0)
self.assertAlmostEqual(picking_ship.move_lines.product_uom_qty, 2.0)
# Create a procurement for 3 units
pg = self.env['procurement.group'].create({'name': 'Wave 2'})
self.env['procurement.group'].run([
pg.Procurement(
product_a,
3.0,
product_a.uom_id,
final_location,
'wave_part_2',
'wave_part_2',
warehouse.company_id,
{
'warehouse_id': warehouse,
'group_id': pg
}
)
])
# The picking for the pick operation should be reused and the lines merged.
picking_ship = self.env['stock.picking'].search([('group_id', '=', pg.id)])
self.assertAlmostEqual(picking_pick.move_lines.product_uom_qty, 5.0)
self.assertAlmostEqual(picking_ship.move_lines.product_uom_qty, 3.0)
def test_orderpoint_replenishment_view(self):
""" Create two warehouses + two moves
verify that the replenishment view is consistent"""
warehouse_1 = self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1)
warehouse_2, warehouse_3 = self.env['stock.warehouse'].create([{
'name': 'Warehouse Two',
'code': 'WH2',
'resupply_wh_ids': [warehouse_1.id],
}, {
'name': 'Warehouse Three',
'code': 'WH3',
'resupply_wh_ids': [warehouse_1.id],
}])
route_2 = self.env['stock.location.route'].search([
('supplied_wh_id', '=', warehouse_2.id),
('supplier_wh_id', '=', warehouse_1.id),
])
route_3 = self.env['stock.location.route'].search([
('supplied_wh_id', '=', warehouse_3.id),
('supplier_wh_id', '=', warehouse_1.id),
])
product = self.env['product.product'].create({
'name': 'Super Product',
'type': 'product',
'route_ids': [route_2.id, route_3.id]
})
moves = self.env['stock.move'].create([{
'name': 'Move WH2',
'location_id': warehouse_2.lot_stock_id.id,
'location_dest_id': self.partner.property_stock_customer.id,
'product_id': product.id,
'product_uom': product.uom_id.id,
'product_uom_qty': 1,
}, {
'name': 'Move WH3',
'location_id': warehouse_3.lot_stock_id.id,
'location_dest_id': self.partner.property_stock_customer.id,
'product_id': product.id,
'product_uom': product.uom_id.id,
'product_uom_qty': 1,
}])
moves._action_confirm()
# activate action of opening the replenishment view
self.env['report.stock.quantity'].flush()
self.env['stock.warehouse.orderpoint'].action_open_orderpoints()
replenishments = self.env['stock.warehouse.orderpoint'].search([
('product_id', '=', product.id),
])
# Verify that the location and the route make sense
self.assertRecordValues(replenishments, [
{'location_id': warehouse_2.lot_stock_id.id, 'route_id': route_2.id},
{'location_id': warehouse_3.lot_stock_id.id, 'route_id': route_3.id},
])
class TestProcRuleLoad(TransactionCase):
def setUp(cls):
super(TestProcRuleLoad, cls).setUp()
cls.skipTest("Performance test, too heavy to run.")
def test_orderpoint_1(self):
""" Try 500 products with a 1000 RR(stock -> shelf1 and stock -> shelf2)
Also randomly include 4 miss configuration.
"""
warehouse = self.env['stock.warehouse'].create({
'name': 'Test Warehouse',
'code': 'TWH'
})
warehouse.reception_steps = 'three_steps'
supplier_loc = self.env.ref('stock.stock_location_suppliers')
stock_loc = warehouse.lot_stock_id
shelf1 = self.env['stock.location'].create({
'location_id': stock_loc.id,
'usage': 'internal',
'name': 'shelf1'
})
shelf2 = self.env['stock.location'].create({
'location_id': stock_loc.id,
'usage': 'internal',
'name': 'shelf2'
})
products = self.env['product.product'].create([{'name': i, 'type': 'product'} for i in range(500)])
self.env['stock.warehouse.orderpoint'].create([{
'product_id': products[i // 2].id,
'location_id': (i % 2 == 0) and shelf1.id or shelf2.id,
'warehouse_id': warehouse.id,
'product_min_qty': 5,
'product_max_qty': 10,
} for i in range(1000)])
self.env['stock.rule'].create({
'name': 'Rule Shelf1',
'route_id': warehouse.reception_route_id.id,
'location_id': shelf1.id,
'location_src_id': stock_loc.id,
'action': 'pull',
'procure_method': 'make_to_order',
'picking_type_id': warehouse.int_type_id.id,
})
self.env['stock.rule'].create({
'name': 'Rule Shelf2',
'route_id': warehouse.reception_route_id.id,
'location_id': shelf2.id,
'location_src_id': stock_loc.id,
'action': 'pull',
'procure_method': 'make_to_order',
'picking_type_id': warehouse.int_type_id.id,
})
self.env['stock.rule'].create({
'name': 'Rule Supplier',
'route_id': warehouse.reception_route_id.id,
'location_id': warehouse.wh_input_stock_loc_id.id,
'location_src_id': supplier_loc.id,
'action': 'pull',
'procure_method': 'make_to_stock',
'picking_type_id': warehouse.in_type_id.id,
})
wrong_route = self.env['stock.location.route'].create({
'name': 'Wrong Route',
})
self.env['stock.rule'].create({
'name': 'Trap Rule',
'route_id': wrong_route.id,
'location_id': warehouse.wh_input_stock_loc_id.id,
'location_src_id': supplier_loc.id,
'action': 'pull',
'procure_method': 'make_to_order',
'picking_type_id': warehouse.in_type_id.id,
})
(products[50] | products[99] | products[150] | products[199]).write({
'route_ids': [(4, wrong_route.id)]
})
self.env['procurement.group'].run_scheduler()
self.assertTrue(self.env['stock.move'].search([('product_id', 'in', products.ids)]))
for index in [50, 99, 150, 199]:
self.assertTrue(self.env['mail.activity'].search([
('res_id', '=', products[index].product_tmpl_id.id),
('res_model_id', '=', self.env.ref('product.model_product_template').id)
]))
| 43.373253
| 21,730
|
8,710
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests.common import TransactionCase
class TestPackingNeg(TransactionCase):
def test_packing_neg(self):
res_partner_2 = self.env['res.partner'].create({
'name': 'Deco Addict',
'email': 'deco.addict82@example.com',
})
res_partner_4 = self.env['res.partner'].create({
'name': 'Ready Mat',
'email': 'ready.mat28@example.com',
})
# Create a new "negative" storable product
product_neg = self.env['product.product'].create({
'name': 'Negative product',
'type': 'product',
'categ_id': self.ref('product.product_category_1'),
'list_price': 100.0,
'standard_price': 70.0,
'seller_ids': [(0, 0, {
'delay': 1,
'name': res_partner_2.id,
'min_qty': 2.0,})],
'uom_id': self.ref('uom.product_uom_unit'),
'uom_po_id': self.ref('uom.product_uom_unit'),
})
# Create an incoming picking for this product of 300 PCE from suppliers to stock
vals = {
'name': 'Incoming picking (negative product)',
'partner_id': res_partner_2.id,
'picking_type_id': self.ref('stock.picking_type_in'),
'location_id': self.ref('stock.stock_location_suppliers'),
'location_dest_id': self.ref('stock.stock_location_stock'),
'move_lines': [(0, 0, {
'name': 'NEG',
'product_id': product_neg.id,
'product_uom': product_neg.uom_id.id,
'product_uom_qty': 300.00,
'location_id': self.ref('stock.stock_location_suppliers'),
'location_dest_id': self.ref('stock.stock_location_stock'),
})],
}
pick_neg = self.env['stock.picking'].create(vals)
pick_neg._onchange_picking_type()
pick_neg.move_lines._onchange_product_id()
# Confirm and assign picking
pick_neg.action_confirm()
pick_neg.action_assign()
# Put 120 pieces on Palneg 1 (package), 120 pieces on Palneg 2 with lot A and 60 pieces on Palneg 3
# create lot A
lot_a = self.env['stock.production.lot'].create({'name': 'Lot neg', 'product_id': product_neg.id, 'company_id': self.env.company.id})
# create package
package1 = self.env['stock.quant.package'].create({'name': 'Palneg 1'})
package2 = self.env['stock.quant.package'].create({'name': 'Palneg 2'})
package3 = self.env['stock.quant.package'].create({'name': 'Palneg 3'})
# Create package for each line and assign it as result_package_id
# create pack operation
pick_neg.move_line_ids[0].write({'result_package_id': package1.id, 'qty_done': 120})
new_pack1 = self.env['stock.move.line'].create({
'product_id': product_neg.id,
'product_uom_id': self.ref('uom.product_uom_unit'),
'picking_id': pick_neg.id,
'lot_id': lot_a.id,
'qty_done': 120,
'result_package_id': package2.id,
'location_id': self.ref('stock.stock_location_suppliers'),
'location_dest_id': self.ref('stock.stock_location_stock')
})
new_pack2 = self.env['stock.move.line'].create({
'product_id': product_neg.id,
'product_uom_id': self.ref('uom.product_uom_unit'),
'picking_id': pick_neg.id,
'result_package_id': package3.id,
'qty_done': 60,
'location_id': self.ref('stock.stock_location_suppliers'),
'location_dest_id': self.ref('stock.stock_location_stock')
})
# Transfer the receipt
pick_neg._action_done()
# Make a delivery order of 300 pieces to the customer
vals = {
'name': 'outgoing picking (negative product)',
'partner_id': res_partner_4.id,
'picking_type_id': self.ref('stock.picking_type_out'),
'location_id': self.ref('stock.stock_location_stock'),
'location_dest_id': self.ref('stock.stock_location_customers'),
'move_lines': [(0, 0, {
'name': 'NEG',
'product_id': product_neg.id,
'product_uom': product_neg.uom_id.id,
'product_uom_qty': 300.00,
'location_id': self.ref('stock.stock_location_stock'),
'location_dest_id': self.ref('stock.stock_location_customers'),
})],
}
delivery_order_neg = self.env['stock.picking'].create(vals)
delivery_order_neg._onchange_picking_type()
delivery_order_neg.move_lines._onchange_product_id()
# Assign and confirm
delivery_order_neg.action_confirm()
delivery_order_neg.action_assign()
# Instead of doing the 300 pieces, you decide to take pallet 1 (do not mention
# product in operation here) and 140 pieces from lot A/pallet 2 and 10 pieces from pallet 3
for rec in delivery_order_neg.move_line_ids:
if rec.package_id.name == 'Palneg 1':
rec.qty_done = rec.product_qty
rec.result_package_id = False
elif rec.package_id.name == 'Palneg 2' and rec.lot_id.name == 'Lot neg':
rec.write({
'qty_done': 140,
'result_package_id': False,
})
elif rec.package_id.name == 'Palneg 3':
rec.qty_done = 10
rec.result_package_id = False
# Process this picking
delivery_order_neg._action_done()
# Check the quants that you have -20 pieces pallet 2 in stock, and a total quantity
# of 50 in stock from pallet 3 (should be 20+30, as it has been split by reservation)
records = self.env['stock.quant'].search([('product_id', '=', product_neg.id), ('quantity', '!=', '0')])
pallet_3_stock_qty = 0
for rec in records:
if rec.package_id.name == 'Palneg 2' and rec.location_id.id == self.ref('stock.stock_location_stock'):
self.assertTrue(rec.quantity == -20, "Should have -20 pieces in stock on pallet 2. Got " + str(rec.quantity))
self.assertTrue(rec.lot_id.name == 'Lot neg', "It should have kept its Lot")
elif rec.package_id.name == 'Palneg 3' and rec.location_id.id == self.ref('stock.stock_location_stock'):
pallet_3_stock_qty += rec.quantity
else:
self.assertTrue(rec.location_id.id != self.ref('stock.stock_location_stock'), "Unrecognized quant in stock")
self.assertEqual(pallet_3_stock_qty, 50, "Should have 50 pieces in stock on pallet 3")
# Create a picking for reconciling the negative quant
vals = {
'name': 'reconciling_delivery',
'partner_id': res_partner_4.id,
'picking_type_id': self.ref('stock.picking_type_in'),
'location_id': self.ref('stock.stock_location_suppliers'),
'location_dest_id': self.ref('stock.stock_location_stock'),
'move_lines': [(0, 0, {
'name': 'NEG',
'product_id': product_neg.id,
'product_uom': product_neg.uom_id.id,
'product_uom_qty': 20.0,
'location_id': self.ref('stock.stock_location_suppliers'),
'location_dest_id': self.ref('stock.stock_location_stock'),
})],
}
delivery_reconcile = self.env['stock.picking'].create(vals)
delivery_reconcile._onchange_picking_type()
delivery_reconcile.move_lines._onchange_product_id()
# Receive 20 products with lot neg in stock with a new incoming shipment that should be on pallet 2
delivery_reconcile.action_confirm()
lot = self.env["stock.production.lot"].search([
('product_id', '=', product_neg.id),
('name', '=', 'Lot neg')], limit=1)
pack = self.env["stock.quant.package"].search([('name', '=', 'Palneg 2')], limit=1)
delivery_reconcile.move_line_ids[0].write({'lot_id': lot.id, 'qty_done': 20.0, 'result_package_id': pack.id})
delivery_reconcile._action_done()
# Check the negative quant was reconciled
neg_quants = self.env['stock.quant'].search([
('product_id', '=', product_neg.id),
('quantity', '<', 0),
('location_id.id', '!=', self.ref('stock.stock_location_suppliers'))])
self.assertTrue(len(neg_quants) == 0, "Negative quants should have been reconciled")
| 47.595628
| 8,710
|
27,253
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.exceptions import UserError
from odoo.tests.common import TransactionCase, Form
class TestMultiCompany(TransactionCase):
@classmethod
def setUpClass(cls):
super(TestMultiCompany, cls).setUpClass()
group_user = cls.env.ref('base.group_user')
group_stock_manager = cls.env.ref('stock.group_stock_manager')
cls.company_a = cls.env['res.company'].create({'name': 'Company A'})
cls.company_b = cls.env['res.company'].create({'name': 'Company B'})
cls.warehouse_a = cls.env['stock.warehouse'].search([('company_id', '=', cls.company_a.id)], limit=1)
cls.warehouse_b = cls.env['stock.warehouse'].search([('company_id', '=', cls.company_b.id)], limit=1)
cls.stock_location_a = cls.warehouse_a.lot_stock_id
cls.stock_location_b = cls.warehouse_b.lot_stock_id
cls.user_a = cls.env['res.users'].create({
'name': 'user company a with access to company b',
'login': 'user a',
'groups_id': [(6, 0, [group_user.id, group_stock_manager.id])],
'company_id': cls.company_a.id,
'company_ids': [(6, 0, [cls.company_a.id, cls.company_b.id])]
})
cls.user_b = cls.env['res.users'].create({
'name': 'user company b with access to company a',
'login': 'user b',
'groups_id': [(6, 0, [group_user.id, group_stock_manager.id])],
'company_id': cls.company_b.id,
'company_ids': [(6, 0, [cls.company_a.id, cls.company_b.id])]
})
def test_picking_type_1(self):
"""As a user of Company A, check it is not possible to use a warehouse of Company B in a
picking type of Company A.
"""
picking_type_company_a = self.env['stock.picking.type'].search([
('company_id', '=', self.company_a.id)
], limit=1)
with self.assertRaises(UserError):
picking_type_company_a.warehouse_id = self.warehouse_b
def test_picking_type_2(self):
"""As a user of Company A, check it is not possible to change the company on an existing
picking type of Company A to Company B.
"""
picking_type_company_a = self.env['stock.picking.type'].search([
('company_id', '=', self.company_a.id)
], limit=1)
with self.assertRaises(UserError):
picking_type_company_a.with_user(self.user_a).company_id = self.company_b
def test_putaway_1(self):
"""As a user of Company A, create a putaway rule with locations of Company A and set the
company to Company B before saving. Check it is not possible.
"""
stock_location_a_1 = self.env['stock.location'].with_user(self.user_a).create({
'location_id': self.stock_location_a.id,
'usage': 'internal',
'name': 'A_1',
})
putaway_form = Form(self.env['stock.putaway.rule'])
putaway_form.location_in_id = self.stock_location_a
putaway_form.location_out_id = stock_location_a_1
putaway_form.company_id = self.company_b
with self.assertRaises(UserError):
putaway_form.save()
def test_putaway_2(self):
"""As a user of Company A, check it is not possible to change the company on an existing
putaway rule to Company B.
"""
stock_location_a_1 = self.env['stock.location'].with_user(self.user_a).create({
'name': 'A_1',
'location_id': self.stock_location_a.id,
'usage': 'internal',
})
putaway_rule = self.env['stock.putaway.rule'].with_user(self.user_a).create({
'location_in_id': self.stock_location_a.id,
'location_out_id': stock_location_a_1.id
})
with self.assertRaises(UserError):
putaway_rule.company_id = self.company_b
def test_company_1(self):
"""Check it is not possible to use the internal transit location of Company B on Company A."""
with self.assertRaises(UserError):
self.company_a.internal_transit_location_id = self.company_b.internal_transit_location_id
def test_partner_1(self):
"""On a partner without company, as a user of Company B, check it is not possible to use a
location limited to Company A as `property_stock_supplier` or `property_stock_customer`.
"""
shared_partner = self.env['res.partner'].create({
'name': 'Shared Partner',
'company_id': False,
})
with self.assertRaises(UserError):
shared_partner.with_user(self.user_b).property_stock_customer = self.stock_location_a
def test_inventory_1(self):
"""Create a quant (inventory adjustment) in Company A for a product limited to Company A and
as a user of company B, apply the inventory adjustment and set its counted quantity to 10
before validating. The quant and stock moves should belong to Company A.
"""
product = self.env['product.product'].create({
'type': 'product',
'company_id': self.company_a.id,
'name': 'Product limited to company A',
})
inventory_quant = self.env['stock.quant'].with_user(self.user_a).with_context(inventory_mode=True).create({
'location_id': self.stock_location_a.id,
'product_id': product.id,
'inventory_quantity': 0
})
self.assertEqual(inventory_quant.company_id, self.company_a)
inventory_quant.with_user(self.user_b).inventory_quantity = 10
inventory_quant.with_user(self.user_b).action_apply_inventory()
last_move_id = self.env['stock.move'].search([('is_inventory', '=', True)])[-1]
self.assertEqual(inventory_quant.company_id, self.company_a)
self.assertEqual(last_move_id.company_id, self.company_a)
self.assertEqual(last_move_id.quantity_done, 10)
self.assertEqual(last_move_id.location_id.company_id, self.company_a)
def test_inventory_2(self):
"""Try to create a quant (inventory adjustment) in Company A and check it is not possible to use
products limited to Company B in it.
"""
product = self.env['product.product'].create({
'name': 'product limited to company b',
'company_id': self.company_b.id,
'type': 'product'
})
with self.assertRaises(UserError):
self.env['stock.quant'].with_user(self.user_a).with_context(inventory_mode=True).create({
'location_id': self.stock_location_a.id,
'product_id': product.id,
'inventory_quantity': 10
})
def test_picking_1(self):
"""As a user of Company A, create a picking and use a picking type of Company B, check the
create picking belongs to Company B.
"""
picking_type_company_b = self.env['stock.picking.type'].search([('company_id', '=', self.company_b.id)], limit=1)
picking_form = Form(self.env['stock.picking'].with_user(self.user_a))
picking_form.picking_type_id = picking_type_company_b
picking = picking_form.save()
self.assertEqual(picking.company_id, self.company_b)
def test_location_1(self):
"""Check it is not possible to set a location of Company B under a location of Company A."""
with self.assertRaises(UserError):
self.stock_location_b.location_id = self.stock_location_a
def test_lot_1(self):
"""Check it is possible to create a stock.production.lot with the same name in Company A and
Company B"""
product_lot = self.env['product.product'].create({
'type': 'product',
'tracking': 'lot',
'name': 'product lot',
})
self.env['stock.production.lot'].create({
'name': 'lotA',
'company_id': self.company_a.id,
'product_id': product_lot.id,
})
self.env['stock.production.lot'].create({
'name': 'lotA',
'company_id': self.company_b.id,
'product_id': product_lot.id,
})
def test_lot_2(self):
"""Validate a picking of Company A receiving lot1 while being logged into Company B. Check
the lot is created in Company A.
"""
product = self.env['product.product'].create({
'type': 'product',
'tracking': 'serial',
'name': 'product',
})
picking = self.env['stock.picking'].with_user(self.user_a).create({
'picking_type_id': self.warehouse_a.in_type_id.id,
'location_id': self.env.ref('stock.stock_location_suppliers').id,
'location_dest_id': self.stock_location_a.id,
})
self.assertEqual(picking.company_id, self.company_a)
move1 = self.env['stock.move'].create({
'name': 'test_lot_2',
'picking_type_id': picking.picking_type_id.id,
'location_id': picking.location_id.id,
'location_dest_id': picking.location_dest_id.id,
'product_id': product.id,
'product_uom': product.uom_id.id,
'product_uom_qty': 1.0,
'picking_id': picking.id,
'company_id': picking.company_id.id,
})
picking.with_user(self.user_b).action_confirm()
self.assertEqual(picking.state, 'assigned')
move1.with_user(self.user_b).move_line_ids[0].qty_done = 1
move1.with_user(self.user_b).move_line_ids[0].lot_name = 'receipt_serial'
self.assertEqual(move1.move_line_ids[0].company_id, self.company_a)
picking.with_user(self.user_b).button_validate()
self.assertEqual(picking.state, 'done')
created_serial = self.env['stock.production.lot'].search([
('name', '=', 'receipt_serial')
])
self.assertEqual(created_serial.company_id, self.company_a)
def test_orderpoint_1(self):
"""As a user of company A, create an orderpoint for company B. Check itsn't possible to
use a warehouse of companny A"""
product = self.env['product.product'].create({
'type': 'product',
'name': 'shared product',
})
orderpoint = Form(self.env['stock.warehouse.orderpoint'].with_user(self.user_a))
orderpoint.company_id = self.company_b
orderpoint.warehouse_id = self.warehouse_b
orderpoint.location_id = self.stock_location_a
orderpoint.product_id = product
with self.assertRaises(UserError):
orderpoint.save()
orderpoint.location_id = self.stock_location_b
orderpoint = orderpoint.save()
self.assertEqual(orderpoint.company_id, self.company_b)
def test_orderpoint_2(self):
"""As a user of Company A, check it is not possible to change the company on an existing
orderpoint to Company B.
"""
product = self.env['product.product'].create({
'type': 'product',
'name': 'shared product',
})
orderpoint = Form(self.env['stock.warehouse.orderpoint'].with_user(self.user_a))
orderpoint.company_id = self.company_a
orderpoint.warehouse_id = self.warehouse_a
orderpoint.location_id = self.stock_location_a
orderpoint.product_id = product
orderpoint = orderpoint.save()
self.assertEqual(orderpoint.company_id, self.company_a)
with self.assertRaises(UserError):
orderpoint.company_id = self.company_b.id
def test_product_1(self):
""" As an user of Company A, checks we can or cannot create new product
depending of its `company_id`."""
# Creates a new product with no company_id and set a responsible.
# The product must be created as there is no company on the product.
product_form = Form(self.env['product.template'].with_user(self.user_a))
product_form.name = 'Paramite Pie'
product_form.responsible_id = self.user_b
product = product_form.save()
self.assertEqual(product.company_id.id, False)
self.assertEqual(product.responsible_id.id, self.user_b.id)
# Creates a new product belong to Company A and set a responsible belong
# to Company B. The product mustn't be created as the product and the
# user don't belong of the same company.
self.user_b.company_ids = [(6, 0, [self.company_b.id])]
product_form = Form(self.env['product.template'].with_user(self.user_a))
product_form.name = 'Meech Munchy'
product_form.company_id = self.company_a
product_form.responsible_id = self.user_b
with self.assertRaises(UserError):
# Raises an UserError for company incompatibility.
product = product_form.save()
# Creates a new product belong to Company A and set a responsible belong
# to Company A & B (default B). The product must be created as the user
# belongs to product's company.
self.user_b.company_ids = [(6, 0, [self.company_a.id, self.company_b.id])]
product_form = Form(self.env['product.template'].with_user(self.user_a))
product_form.name = 'Scrab Cake'
product_form.company_id = self.company_a
product_form.responsible_id = self.user_b
product = product_form.save()
self.assertEqual(product.company_id.id, self.company_a.id)
self.assertEqual(product.responsible_id.id, self.user_b.id)
def test_warehouse_1(self):
"""As a user of Company A, on its main warehouse, see it is impossible to change the
company_id, to use a view location of another company, to set a picking type to one
of another company
"""
with self.assertRaises(UserError):
self.warehouse_a.company_id = self.company_b.id
with self.assertRaises(UserError):
self.warehouse_a.view_location_id = self.warehouse_b.view_location_id
with self.assertRaises(UserError):
self.warehouse_a.pick_type_id = self.warehouse_b.pick_type_id
def test_move_1(self):
"""See it is not possible to confirm a stock move of Company A with a picking type of
Company B.
"""
product = self.env['product.product'].create({
'name': 'p1',
'type': 'product'
})
picking_type_b = self.env['stock.picking.type'].search([
('company_id', '=', self.company_b.id),
], limit=1)
move = self.env['stock.move'].create({
'company_id': self.company_a.id,
'picking_type_id': picking_type_b.id,
'location_id': self.stock_location_a.id,
'location_dest_id': self.stock_location_a.id,
'product_id': product.id,
'product_uom': product.uom_id.id,
'name': 'stock_move',
})
with self.assertRaises(UserError):
move._action_confirm()
def test_move_2(self):
"""See it is not possible to confirm a stock move of Company A with a destination location
of Company B.
"""
product = self.env['product.product'].create({
'name': 'p1',
'type': 'product'
})
picking_type_b = self.env['stock.picking.type'].search([
('company_id', '=', self.company_b.id),
], limit=1)
move = self.env['stock.move'].create({
'company_id': self.company_a.id,
'picking_type_id': picking_type_b.id,
'location_id': self.stock_location_a.id,
'location_dest_id': self.stock_location_b.id,
'product_id': product.id,
'product_uom': product.uom_id.id,
'name': 'stock_move',
})
with self.assertRaises(UserError):
move._action_confirm()
def test_move_3(self):
"""See it is not possible to confirm a stock move of Company A with a product restricted to
Company B.
"""
product = self.env['product.product'].create({
'name': 'p1',
'type': 'product',
'company_id': self.company_b.id,
})
picking_type_b = self.env['stock.picking.type'].search([
('company_id', '=', self.company_b.id),
], limit=1)
move = self.env['stock.move'].create({
'company_id': self.company_a.id,
'picking_type_id': picking_type_b.id,
'location_id': self.stock_location_a.id,
'location_dest_id': self.stock_location_a.id,
'product_id': product.id,
'product_uom': product.uom_id.id,
'name': 'stock_move',
})
with self.assertRaises(UserError):
move._action_confirm()
def test_intercom_lot_push(self):
""" Create a push rule to transfer products received in inter company
transit location to company b. Move a lot product from company a to the
transit location. Check the move created by the push rule is not chained
with previous move, and no product are reserved from inter-company
transit. """
supplier_location = self.env.ref('stock.stock_location_suppliers')
intercom_location = self.env.ref('stock.stock_location_inter_wh')
intercom_location.write({'active': True})
product_lot = self.env['product.product'].create({
'type': 'product',
'tracking': 'lot',
'name': 'product lot',
})
picking_type_to_transit = self.env['stock.picking.type'].create({
'name': 'To Transit',
'sequence_code': 'TRANSIT',
'code': 'outgoing',
'company_id': self.company_a.id,
'warehouse_id': False,
'default_location_src_id': self.stock_location_a.id,
'default_location_dest_id': intercom_location.id,
'sequence_id': self.env['ir.sequence'].create({
'code': 'transit',
'name': 'transit sequence',
'company_id': self.company_a.id,
}).id,
})
route = self.env['stock.location.route'].create({
'name': 'Push',
'company_id': False,
'rule_ids': [(0, False, {
'name': 'create a move to company b',
'company_id': self.company_b.id,
'location_src_id': intercom_location.id,
'location_id': self.stock_location_b.id,
'action': 'push',
'auto': 'manual',
'picking_type_id': self.warehouse_b.in_type_id.id,
})],
})
move_from_supplier = self.env['stock.move'].create({
'company_id': self.company_a.id,
'name': 'test_from_supplier',
'location_id': supplier_location.id,
'location_dest_id': self.stock_location_a.id,
'product_id': product_lot.id,
'product_uom': product_lot.uom_id.id,
'product_uom_qty': 1.0,
'picking_type_id': self.warehouse_a.in_type_id.id,
})
move_from_supplier._action_confirm()
move_line_1 = move_from_supplier.move_line_ids[0]
move_line_1.lot_name = 'lot 1'
move_line_1.qty_done = 1.0
move_from_supplier._action_done()
lot_1 = move_line_1.lot_id
move_to_transit = self.env['stock.move'].create({
'company_id': self.company_a.id,
'name': 'test_to_transit',
'location_id': self.stock_location_a.id,
'location_dest_id': intercom_location.id,
'product_id': product_lot.id,
'product_uom': product_lot.uom_id.id,
'product_uom_qty': 1.0,
'picking_type_id': picking_type_to_transit.id,
'route_ids': [(4, route.id)],
})
move_to_transit._action_confirm()
move_to_transit._action_assign()
move_line_2 = move_to_transit.move_line_ids[0]
self.assertTrue(move_line_2.lot_id, move_line_1.lot_id)
move_line_2.qty_done = 1.0
move_to_transit._action_done()
move_push = self.env['stock.move'].search([('location_id', '=', intercom_location.id),
('product_id', '=', product_lot.id)])
self.assertTrue(move_push, 'No move created from push rules')
self.assertEqual(move_push.state, "assigned")
self.assertTrue(move_push.move_line_ids, "No move line created for the move")
self.assertFalse(move_push in move_to_transit.move_dest_ids,
"Chained move created in transit location")
self.assertNotEqual(move_push.move_line_ids.lot_id, move_line_2.lot_id,
"Reserved from transit location")
picking_receipt = move_push.picking_id
with self.assertRaises(UserError):
picking_receipt.button_validate()
move_line_3 = move_push.move_line_ids[0]
move_line_3.lot_name = 'lot 2'
move_line_3.qty_done = 1.0
picking_receipt.button_validate()
lot_2 = move_line_3.lot_id
self.assertEqual(lot_1.company_id, self.company_a)
self.assertEqual(lot_1.name, 'lot 1')
self.assertEqual(self.env['stock.quant']._get_available_quantity(product_lot, intercom_location, lot_1), 1.0)
self.assertEqual(lot_2.company_id, self.company_b)
self.assertEqual(lot_2.name, 'lot 2')
self.assertEqual(self.env['stock.quant']._get_available_quantity(product_lot, self.stock_location_b, lot_2), 1.0)
def test_intercom_lot_pull(self):
"""Use warehouse of comany a to resupply warehouse of company b. Check
pull rule works correctly in two companies and moves are unchained from
inter-company transit location."""
customer_location = self.env.ref('stock.stock_location_customers')
supplier_location = self.env.ref('stock.stock_location_suppliers')
intercom_location = self.env.ref('stock.stock_location_inter_wh')
intercom_location.write({'active': True})
partner = self.env['res.partner'].create({'name': 'Deco Addict'})
self.warehouse_a.resupply_wh_ids = [(6, 0, [self.warehouse_b.id])]
resupply_route = self.env['stock.location.route'].search([('supplier_wh_id', '=', self.warehouse_b.id),
('supplied_wh_id', '=', self.warehouse_a.id)])
self.assertTrue(resupply_route, "Resupply route not found")
product_lot = self.env['product.product'].create({
'type': 'product',
'tracking': 'lot',
'name': 'product lot',
'route_ids': [(4, resupply_route.id), (4, self.env.ref('stock.route_warehouse0_mto').id)],
})
move_sup_to_whb = self.env['stock.move'].create({
'company_id': self.company_b.id,
'name': 'from_supplier_to_whb',
'location_id': supplier_location.id,
'location_dest_id': self.warehouse_b.lot_stock_id.id,
'product_id': product_lot.id,
'product_uom': product_lot.uom_id.id,
'product_uom_qty': 1.0,
'picking_type_id': self.warehouse_b.in_type_id.id,
})
move_sup_to_whb._action_confirm()
move_line_1 = move_sup_to_whb.move_line_ids[0]
move_line_1.lot_name = 'lot b'
move_line_1.qty_done = 1.0
move_sup_to_whb._action_done()
lot_b = move_line_1.lot_id
picking_out = self.env['stock.picking'].create({
'company_id': self.company_a.id,
'partner_id': partner.id,
'picking_type_id': self.warehouse_a.out_type_id.id,
'location_id': self.stock_location_a.id,
'location_dest_id': customer_location.id,
})
move_wha_to_cus = self.env['stock.move'].create({
'name': "WH_A to Customer",
'product_id': product_lot.id,
'product_uom_qty': 1,
'product_uom': product_lot.uom_id.id,
'picking_id': picking_out.id,
'location_id': self.stock_location_a.id,
'location_dest_id': customer_location.id,
'warehouse_id': self.warehouse_a.id,
'procure_method': 'make_to_order',
'company_id': self.company_a.id,
})
picking_out.action_confirm()
move_whb_to_transit = self.env['stock.move'].search([('location_id', '=', self.stock_location_b.id),
('product_id', '=', product_lot.id)])
move_transit_to_wha = self.env['stock.move'].search([('location_id', '=', intercom_location.id),
('product_id', '=', product_lot.id)])
self.assertTrue(move_whb_to_transit, "No move created by pull rule")
self.assertTrue(move_transit_to_wha, "No move created by pull rule")
self.assertTrue(move_wha_to_cus in move_transit_to_wha.move_dest_ids,
"Moves are not chained")
self.assertFalse(move_transit_to_wha in move_whb_to_transit.move_dest_ids,
"Chained move created in transit location")
self.assertEqual(move_wha_to_cus.state, "waiting")
self.assertEqual(move_transit_to_wha.state, "waiting")
self.assertEqual(move_whb_to_transit.state, "assigned")
(move_wha_to_cus + move_whb_to_transit + move_transit_to_wha).picking_id.action_assign()
self.assertEqual(move_wha_to_cus.state, "waiting")
self.assertEqual(move_transit_to_wha.state, "assigned")
self.assertEqual(move_whb_to_transit.state, "assigned")
res_dict = move_whb_to_transit.picking_id.button_validate()
self.assertEqual(res_dict.get('res_model'), 'stock.immediate.transfer')
wizard = Form(self.env[res_dict['res_model']].with_context(res_dict['context'])).save()
wizard.process()
self.assertEqual(self.env['stock.quant']._get_available_quantity(product_lot, intercom_location, lot_b), 1.0)
with self.assertRaises(UserError):
move_transit_to_wha.picking_id.button_validate()
move_line_2 = move_transit_to_wha.move_line_ids[0]
move_line_2.lot_name = 'lot a'
move_line_2.qty_done = 1.0
move_transit_to_wha._action_done()
lot_a = move_line_2.lot_id
move_wha_to_cus._action_assign()
self.assertEqual(move_wha_to_cus.state, "assigned")
res_dict = move_wha_to_cus.picking_id.button_validate()
self.assertEqual(res_dict.get('res_model'), 'stock.immediate.transfer')
wizard = Form(self.env[res_dict['res_model']].with_context(res_dict['context'])).save()
wizard.process()
self.assertEqual(self.env['stock.quant']._get_available_quantity(product_lot, customer_location, lot_a), 1.0)
self.assertEqual(lot_a.company_id, self.company_a)
self.assertEqual(lot_a.name, 'lot a')
self.assertEqual(lot_b.company_id, self.company_b)
self.assertEqual(lot_b.name, 'lot b')
| 46.746141
| 27,253
|
896
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class StockInventoryConflict(models.TransientModel):
_name = 'stock.inventory.conflict'
_description = 'Conflict in Inventory'
quant_ids = fields.Many2many(
'stock.quant', 'stock_conflict_quant_rel', string='Quants')
quant_to_fix_ids = fields.Many2many(
'stock.quant', string='Conflicts')
def action_keep_counted_quantity(self):
for quant in self.quant_ids:
quant.inventory_diff_quantity = quant.inventory_quantity - quant.quantity
return self.quant_ids.action_apply_inventory()
def action_keep_difference(self):
for quant in self.quant_ids:
quant.inventory_quantity = quant.quantity + quant.inventory_diff_quantity
return self.quant_ids.action_apply_inventory()
| 37.333333
| 896
|
4,243
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import datetime
from odoo import _, api, fields, models
from odoo.exceptions import UserError
from odoo.tools.misc import clean_context
class ProductReplenish(models.TransientModel):
_name = 'product.replenish'
_description = 'Product Replenish'
product_id = fields.Many2one('product.product', string='Product', required=True)
product_tmpl_id = fields.Many2one('product.template', string='Product Template', required=True)
product_has_variants = fields.Boolean('Has variants', default=False, required=True)
product_uom_category_id = fields.Many2one('uom.category', related='product_id.uom_id.category_id', readonly=True, required=True)
product_uom_id = fields.Many2one('uom.uom', string='Unit of measure', required=True)
quantity = fields.Float('Quantity', default=1, required=True)
date_planned = fields.Datetime('Scheduled Date', required=True, help="Date at which the replenishment should take place.")
warehouse_id = fields.Many2one(
'stock.warehouse', string='Warehouse', required=True,
domain="[('company_id', '=', company_id)]")
route_ids = fields.Many2many(
'stock.location.route', string='Preferred Routes',
help="Apply specific route(s) for the replenishment instead of product's default routes.",
domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]")
company_id = fields.Many2one('res.company')
@api.model
def default_get(self, fields):
res = super(ProductReplenish, self).default_get(fields)
product_tmpl_id = self.env['product.template']
if 'product_id' in fields:
if self.env.context.get('default_product_id'):
product_id = self.env['product.product'].browse(self.env.context['default_product_id'])
product_tmpl_id = product_id.product_tmpl_id
res['product_tmpl_id'] = product_id.product_tmpl_id.id
res['product_id'] = product_id.id
elif self.env.context.get('default_product_tmpl_id'):
product_tmpl_id = self.env['product.template'].browse(self.env.context['default_product_tmpl_id'])
res['product_tmpl_id'] = product_tmpl_id.id
res['product_id'] = product_tmpl_id.product_variant_id.id
if len(product_tmpl_id.product_variant_ids) > 1:
res['product_has_variants'] = True
company = product_tmpl_id.company_id or self.env.company
if 'product_uom_id' in fields:
res['product_uom_id'] = product_tmpl_id.uom_id.id
if 'company_id' in fields:
res['company_id'] = company.id
if 'warehouse_id' in fields and 'warehouse_id' not in res:
warehouse = self.env['stock.warehouse'].search([('company_id', '=', company.id)], limit=1)
res['warehouse_id'] = warehouse.id
if 'date_planned' in fields:
res['date_planned'] = datetime.datetime.now()
return res
def launch_replenishment(self):
uom_reference = self.product_id.uom_id
self.quantity = self.product_uom_id._compute_quantity(self.quantity, uom_reference)
try:
self.env['procurement.group'].with_context(clean_context(self.env.context)).run([
self.env['procurement.group'].Procurement(
self.product_id,
self.quantity,
uom_reference,
self.warehouse_id.lot_stock_id, # Location
_("Manual Replenishment"), # Name
_("Manual Replenishment"), # Origin
self.warehouse_id.company_id,
self._prepare_run_values() # Values
)
])
except UserError as error:
raise UserError(error)
def _prepare_run_values(self):
replenishment = self.env['procurement.group'].create({})
values = {
'warehouse_id': self.warehouse_id,
'route_ids': self.route_ids,
'date_planned': self.date_planned,
'group_id': replenishment,
}
return values
| 48.770115
| 4,243
|
1,163
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
from odoo.tools.date_utils import add
class StockOrderpointSnooze(models.TransientModel):
_name = 'stock.orderpoint.snooze'
_description = 'Snooze Orderpoint'
orderpoint_ids = fields.Many2many('stock.warehouse.orderpoint')
predefined_date = fields.Selection([
('day', '1 Day'),
('week', '1 Week'),
('month', '1 Month'),
('custom', 'Custom')
], string='Snooze for', default='day')
snoozed_until = fields.Date('Snooze Date')
@api.onchange('predefined_date')
def _onchange_predefined_date(self):
today = fields.Date.context_today(self)
if self.predefined_date == 'day':
self.snoozed_until = add(today, days=1)
elif self.predefined_date == 'week':
self.snoozed_until = add(today, weeks=1)
elif self.predefined_date == 'month':
self.snoozed_until = add(today, months=1)
def action_snooze(self):
self.orderpoint_ids.write({
'snoozed_until': self.snoozed_until
})
| 34.205882
| 1,163
|
1,684
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, fields, models
from odoo.osv import expression
from odoo.tools.misc import format_datetime
class StockQuantityHistory(models.TransientModel):
_name = 'stock.quantity.history'
_description = 'Stock Quantity History'
inventory_datetime = fields.Datetime('Inventory at Date',
help="Choose a date to get the inventory at that date",
default=fields.Datetime.now)
def open_at_date(self):
tree_view_id = self.env.ref('stock.view_stock_product_tree').id
form_view_id = self.env.ref('stock.product_form_view_procurement_button').id
domain = [('type', '=', 'product')]
product_id = self.env.context.get('product_id', False)
product_tmpl_id = self.env.context.get('product_tmpl_id', False)
if product_id:
domain = expression.AND([domain, [('id', '=', product_id)]])
elif product_tmpl_id:
domain = expression.AND([domain, [('product_tmpl_id', '=', product_tmpl_id)]])
# We pass `to_date` in the context so that `qty_available` will be computed across
# moves until date.
action = {
'type': 'ir.actions.act_window',
'views': [(tree_view_id, 'tree'), (form_view_id, 'form')],
'view_mode': 'tree,form',
'name': _('Products'),
'res_model': 'product.product',
'domain': domain,
'context': dict(self.env.context, to_date=self.inventory_datetime),
'display_name': format_datetime(self.env, self.inventory_datetime)
}
return action
| 43.179487
| 1,684
|
3,493
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
from odoo.tools.float_utils import float_compare
class StockBackorderConfirmationLine(models.TransientModel):
_name = 'stock.backorder.confirmation.line'
_description = 'Backorder Confirmation Line'
backorder_confirmation_id = fields.Many2one('stock.backorder.confirmation', 'Immediate Transfer')
picking_id = fields.Many2one('stock.picking', 'Transfer')
to_backorder = fields.Boolean('To Backorder')
class StockBackorderConfirmation(models.TransientModel):
_name = 'stock.backorder.confirmation'
_description = 'Backorder Confirmation'
pick_ids = fields.Many2many('stock.picking', 'stock_picking_backorder_rel')
show_transfers = fields.Boolean()
backorder_confirmation_line_ids = fields.One2many(
'stock.backorder.confirmation.line',
'backorder_confirmation_id',
string="Backorder Confirmation Lines")
@api.model
def default_get(self, fields):
res = super().default_get(fields)
if 'backorder_confirmation_line_ids' in fields and res.get('pick_ids'):
res['backorder_confirmation_line_ids'] = [
(0, 0, {'to_backorder': True, 'picking_id': pick_id})
for pick_id in res['pick_ids'][0][2]
]
# default_get returns x2m values as [(6, 0, ids)]
# because of webclient limitations
return res
def _check_less_quantities_than_expected(self, pickings):
for pick_id in pickings:
moves_to_log = {}
for move in pick_id.move_lines:
if float_compare(move.product_uom_qty,
move.quantity_done,
precision_rounding=move.product_uom.rounding) > 0:
moves_to_log[move] = (move.quantity_done, move.product_uom_qty)
if moves_to_log:
pick_id._log_less_quantities_than_expected(moves_to_log)
def process(self):
pickings_to_do = self.env['stock.picking']
pickings_not_to_do = self.env['stock.picking']
for line in self.backorder_confirmation_line_ids:
if line.to_backorder is True:
pickings_to_do |= line.picking_id
else:
pickings_not_to_do |= line.picking_id
pickings_to_validate = self.env.context.get('button_validate_picking_ids')
if pickings_to_validate:
pickings_to_validate = self.env['stock.picking'].browse(pickings_to_validate).with_context(skip_backorder=True)
if pickings_not_to_do:
self._check_less_quantities_than_expected(pickings_not_to_do)
pickings_to_validate = pickings_to_validate.with_context(picking_ids_not_to_backorder=pickings_not_to_do.ids)
return pickings_to_validate.button_validate()
return True
def process_cancel_backorder(self):
pickings_to_validate_ids = self.env.context.get('button_validate_picking_ids')
if pickings_to_validate_ids:
pickings_to_validate = self.env['stock.picking'].browse(pickings_to_validate_ids)
self._check_less_quantities_than_expected(pickings_to_validate)
return pickings_to_validate\
.with_context(skip_backorder=True, picking_ids_not_to_backorder=self.pick_ids.ids)\
.button_validate()
return True
| 44.782051
| 3,493
|
1,900
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class StockWarnInsufficientQty(models.AbstractModel):
_name = 'stock.warn.insufficient.qty'
_description = 'Warn Insufficient Quantity'
product_id = fields.Many2one('product.product', 'Product', required=True)
location_id = fields.Many2one('stock.location', 'Location', domain="[('usage', '=', 'internal')]", required=True)
quant_ids = fields.Many2many('stock.quant', compute='_compute_quant_ids')
quantity = fields.Float(string="Quantity", required=True)
product_uom_name = fields.Char("Unit of Measure", required=True)
def _get_reference_document_company_id(self):
raise NotImplementedError()
@api.depends('product_id')
def _compute_quant_ids(self):
for quantity in self:
quantity.quant_ids = self.env['stock.quant'].search([
('product_id', '=', quantity.product_id.id),
('location_id.usage', '=', 'internal'),
('company_id', '=', quantity._get_reference_document_company_id().id)
])
def action_done(self):
raise NotImplementedError()
class StockWarnInsufficientQtyScrap(models.TransientModel):
_name = 'stock.warn.insufficient.qty.scrap'
_inherit = 'stock.warn.insufficient.qty'
_description = 'Warn Insufficient Scrap Quantity'
scrap_id = fields.Many2one('stock.scrap', 'Scrap')
def _get_reference_document_company_id(self):
return self.scrap_id.company_id
def action_done(self):
return self.scrap_id.do_scrap()
def action_cancel(self):
# FIXME in master: we should not have created the scrap in a first place
if self.env.context.get('not_unlink_on_discard'):
return True
else:
return self.scrap_id.sudo().unlink()
| 37.254902
| 1,900
|
1,335
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class ChooseDestinationLocation(models.TransientModel):
_name = 'stock.package.destination'
_description = 'Stock Package Destination'
picking_id = fields.Many2one('stock.picking', required=True)
move_line_ids = fields.Many2many('stock.move.line', 'Products', compute='_compute_move_line_ids', required=True)
location_dest_id = fields.Many2one('stock.location', 'Destination location', required=True)
filtered_location = fields.One2many(comodel_name='stock.location', compute='_filter_location')
@api.depends('picking_id')
def _compute_move_line_ids(self):
for destination in self:
destination.move_line_ids = destination.picking_id.move_line_ids.filtered(lambda l: l.qty_done > 0 and not l.result_package_id)
@api.depends('move_line_ids')
def _filter_location(self):
for destination in self:
destination.filtered_location = destination.move_line_ids.mapped('location_dest_id')
def action_done(self):
# set the same location on each move line and pass again in action_put_in_pack
self.move_line_ids.location_dest_id = self.location_dest_id
return self.picking_id.action_put_in_pack()
| 46.034483
| 1,335
|
604
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class StockInventoryWarning(models.TransientModel):
_name = 'stock.inventory.warning'
_description = 'Inventory Adjustment Warning'
quant_ids = fields.Many2many('stock.quant')
def action_reset(self):
return self.quant_ids.action_set_inventory_quantity_to_zero()
def action_set(self):
valid_quants = self.quant_ids.filtered(lambda quant: not quant.inventory_quantity_set)
return valid_quants.action_set_inventory_quantity()
| 33.555556
| 604
|
1,861
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
#
# Order Point Method:
# - Order if the virtual stock of today is below the min of the defined order point
#
from odoo import models, tools
import logging
import threading
_logger = logging.getLogger(__name__)
class StockSchedulerCompute(models.TransientModel):
_name = 'stock.scheduler.compute'
_description = 'Run Scheduler Manually'
def _procure_calculation_orderpoint(self):
# As this function is in a new thread, I need to open a new cursor, because the old one may be closed
with self.pool.cursor() as new_cr:
self = self.with_env(self.env(cr=new_cr))
scheduler_cron = self.sudo().env.ref('stock.ir_cron_scheduler_action')
# Avoid to run the scheduler multiple times in the same time
try:
with tools.mute_logger('odoo.sql_db'):
self._cr.execute("SELECT id FROM ir_cron WHERE id = %s FOR UPDATE NOWAIT", (scheduler_cron.id,))
except Exception:
_logger.info('Attempt to run procurement scheduler aborted, as already running')
self._cr.rollback()
return {}
for company in self.env.user.company_ids:
cids = (self.env.user.company_id | self.env.user.company_ids).ids
self.env['procurement.group'].with_context(allowed_company_ids=cids).run_scheduler(
use_new_cursor=self._cr.dbname,
company_id=company.id)
self._cr.rollback()
return {}
def procure_calculation(self):
threaded_calculation = threading.Thread(target=self._procure_calculation_orderpoint, args=())
threaded_calculation.start()
return {'type': 'ir.actions.client', 'tag': 'reload'}
| 40.456522
| 1,861
|
1,441
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class StockTrackConfirmation(models.TransientModel):
_name = 'stock.track.confirmation'
_description = 'Stock Track Confirmation'
tracking_line_ids = fields.One2many('stock.track.line', 'wizard_id')
quant_ids = fields.Many2many('stock.quant', string='Quants')
product_ids = fields.Many2many('product.product', string='Products')
def action_confirm(self):
self.quant_ids._apply_inventory()
self.quant_ids.inventory_quantity_set = False
@api.onchange('product_ids')
def _onchange_quants(self):
self.tracking_line_ids = [(0, 0, {'product_id': product}) for product in self.product_ids]
class StockTrackingLines(models.TransientModel):
_name = 'stock.track.line'
_description = 'Stock Track Line'
product_display_name = fields.Char('Name', compute='_compute_display_name', readonly=True)
product_id = fields.Many2one('product.product', 'Product', readonly=True)
tracking = fields.Selection(related='product_id.tracking')
wizard_id = fields.Many2one('stock.track.confirmation', readonly=True)
def _compute_display_name(self):
""" Onchange results in product.display_name not being directly accessible """
for line in self:
line.product_display_name = line.product_id._origin.display_name
| 40.027778
| 1,441
|
1,764
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import defaultdict
from odoo import fields, models
class ProductLabelLayout(models.TransientModel):
_inherit = 'product.label.layout'
move_line_ids = fields.Many2many('stock.move.line')
picking_quantity = fields.Selection([
('picking', 'Transfer Quantities'),
('custom', 'Custom')], string="Quantity to print", required=True, default='custom')
print_format = fields.Selection(selection_add=[
('zpl', 'ZPL Labels'),
('zplxprice', 'ZPL Labels with price')
], ondelete={'zpl': 'set default', 'zplxprice': 'set default'})
def _prepare_report_data(self):
xml_id, data = super()._prepare_report_data()
if 'zpl' in self.print_format:
xml_id = 'stock.label_product_product'
if self.picking_quantity == 'picking' and self.move_line_ids:
qties = defaultdict(int)
custom_barcodes = defaultdict(list)
uom_unit = self.env.ref('uom.product_uom_categ_unit', raise_if_not_found=False)
for line in self.move_line_ids:
if line.product_uom_id.category_id == uom_unit:
if (line.lot_id or line.lot_name) and int(line.qty_done):
custom_barcodes[line.product_id.id].append((line.lot_id.name or line.lot_name, int(line.qty_done)))
continue
qties[line.product_id.id] += line.qty_done
# Pass only products with some quantity done to the report
data['quantity_by_product'] = {p: int(q) for p, q in qties.items() if q}
data['custom_barcodes'] = custom_barcodes
return xml_id, data
| 45.230769
| 1,764
|
10,902
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, api, fields, models
from odoo.exceptions import UserError
from odoo.tools.float_utils import float_round
class ReturnPickingLine(models.TransientModel):
_name = "stock.return.picking.line"
_rec_name = 'product_id'
_description = 'Return Picking Line'
product_id = fields.Many2one('product.product', string="Product", required=True, domain="[('id', '=', product_id)]")
quantity = fields.Float("Quantity", digits='Product Unit of Measure', required=True)
uom_id = fields.Many2one('uom.uom', string='Unit of Measure', related='product_id.uom_id')
wizard_id = fields.Many2one('stock.return.picking', string="Wizard")
move_id = fields.Many2one('stock.move', "Move")
class ReturnPicking(models.TransientModel):
_name = 'stock.return.picking'
_description = 'Return Picking'
@api.model
def default_get(self, fields):
res = super(ReturnPicking, self).default_get(fields)
if self.env.context.get('active_id') and self.env.context.get('active_model') == 'stock.picking':
if len(self.env.context.get('active_ids', list())) > 1:
raise UserError(_("You may only return one picking at a time."))
picking = self.env['stock.picking'].browse(self.env.context.get('active_id'))
if picking.exists():
res.update({'picking_id': picking.id})
return res
picking_id = fields.Many2one('stock.picking')
product_return_moves = fields.One2many('stock.return.picking.line', 'wizard_id', 'Moves')
move_dest_exists = fields.Boolean('Chained Move Exists', readonly=True)
original_location_id = fields.Many2one('stock.location')
parent_location_id = fields.Many2one('stock.location')
company_id = fields.Many2one(related='picking_id.company_id')
location_id = fields.Many2one(
'stock.location', 'Return Location',
domain="['|', ('id', '=', original_location_id), '|', '&', ('return_location', '=', True), ('company_id', '=', False), '&', ('return_location', '=', True), ('company_id', '=', company_id)]")
@api.onchange('picking_id')
def _onchange_picking_id(self):
move_dest_exists = False
product_return_moves = [(5,)]
if self.picking_id and self.picking_id.state != 'done':
raise UserError(_("You may only return Done pickings."))
# In case we want to set specific default values (e.g. 'to_refund'), we must fetch the
# default values for creation.
line_fields = [f for f in self.env['stock.return.picking.line']._fields.keys()]
product_return_moves_data_tmpl = self.env['stock.return.picking.line'].default_get(line_fields)
for move in self.picking_id.move_lines:
if move.state == 'cancel':
continue
if move.scrapped:
continue
if move.move_dest_ids:
move_dest_exists = True
product_return_moves_data = dict(product_return_moves_data_tmpl)
product_return_moves_data.update(self._prepare_stock_return_picking_line_vals_from_move(move))
product_return_moves.append((0, 0, product_return_moves_data))
if self.picking_id and not product_return_moves:
raise UserError(_("No products to return (only lines in Done state and not fully returned yet can be returned)."))
if self.picking_id:
self.product_return_moves = product_return_moves
self.move_dest_exists = move_dest_exists
self.parent_location_id = self.picking_id.picking_type_id.warehouse_id and self.picking_id.picking_type_id.warehouse_id.view_location_id.id or self.picking_id.location_id.location_id.id
self.original_location_id = self.picking_id.location_id.id
location_id = self.picking_id.location_id.id
if self.picking_id.picking_type_id.return_picking_type_id.default_location_dest_id.return_location:
location_id = self.picking_id.picking_type_id.return_picking_type_id.default_location_dest_id.id
self.location_id = location_id
@api.model
def _prepare_stock_return_picking_line_vals_from_move(self, stock_move):
quantity = stock_move.product_qty
for move in stock_move.move_dest_ids:
if not move.origin_returned_move_id or move.origin_returned_move_id != stock_move:
continue
if move.state in ('partially_available', 'assigned'):
quantity -= sum(move.move_line_ids.mapped('product_qty'))
elif move.state in ('done'):
quantity -= move.product_qty
quantity = float_round(quantity, precision_rounding=stock_move.product_id.uom_id.rounding)
return {
'product_id': stock_move.product_id.id,
'quantity': quantity,
'move_id': stock_move.id,
'uom_id': stock_move.product_id.uom_id.id,
}
def _prepare_move_default_values(self, return_line, new_picking):
vals = {
'product_id': return_line.product_id.id,
'product_uom_qty': return_line.quantity,
'product_uom': return_line.product_id.uom_id.id,
'picking_id': new_picking.id,
'state': 'draft',
'date': fields.Datetime.now(),
'location_id': return_line.move_id.location_dest_id.id,
'location_dest_id': self.location_id.id or return_line.move_id.location_id.id,
'picking_type_id': new_picking.picking_type_id.id,
'warehouse_id': self.picking_id.picking_type_id.warehouse_id.id,
'origin_returned_move_id': return_line.move_id.id,
'procure_method': 'make_to_stock',
}
return vals
def _prepare_picking_default_values(self):
return {
'move_lines': [],
'picking_type_id': self.picking_id.picking_type_id.return_picking_type_id.id or self.picking_id.picking_type_id.id,
'state': 'draft',
'origin': _("Return of %s") % self.picking_id.name,
'location_id': self.picking_id.location_dest_id.id,
'location_dest_id': self.location_id.id
}
def _create_returns(self):
# TODO sle: the unreserve of the next moves could be less brutal
for return_move in self.product_return_moves.mapped('move_id'):
return_move.move_dest_ids.filtered(lambda m: m.state not in ('done', 'cancel'))._do_unreserve()
# create new picking for returned products
new_picking = self.picking_id.copy(self._prepare_picking_default_values())
picking_type_id = new_picking.picking_type_id.id
new_picking.message_post_with_view('mail.message_origin_link',
values={'self': new_picking, 'origin': self.picking_id},
subtype_id=self.env.ref('mail.mt_note').id)
returned_lines = 0
for return_line in self.product_return_moves:
if not return_line.move_id:
raise UserError(_("You have manually created product lines, please delete them to proceed."))
# TODO sle: float_is_zero?
if return_line.quantity:
returned_lines += 1
vals = self._prepare_move_default_values(return_line, new_picking)
r = return_line.move_id.copy(vals)
vals = {}
# +--------------------------------------------------------------------------------------------------------+
# | picking_pick <--Move Orig-- picking_pack --Move Dest--> picking_ship
# | | returned_move_ids ↑ | returned_move_ids
# | ↓ | return_line.move_id ↓
# | return pick(Add as dest) return toLink return ship(Add as orig)
# +--------------------------------------------------------------------------------------------------------+
move_orig_to_link = return_line.move_id.move_dest_ids.mapped('returned_move_ids')
# link to original move
move_orig_to_link |= return_line.move_id
# link to siblings of original move, if any
move_orig_to_link |= return_line.move_id\
.mapped('move_dest_ids').filtered(lambda m: m.state not in ('cancel'))\
.mapped('move_orig_ids').filtered(lambda m: m.state not in ('cancel'))
move_dest_to_link = return_line.move_id.move_orig_ids.mapped('returned_move_ids')
# link to children of originally returned moves, if any. Note that the use of
# 'return_line.move_id.move_orig_ids.returned_move_ids.move_orig_ids.move_dest_ids'
# instead of 'return_line.move_id.move_orig_ids.move_dest_ids' prevents linking a
# return directly to the destination moves of its parents. However, the return of
# the return will be linked to the destination moves.
move_dest_to_link |= return_line.move_id.move_orig_ids.mapped('returned_move_ids')\
.mapped('move_orig_ids').filtered(lambda m: m.state not in ('cancel'))\
.mapped('move_dest_ids').filtered(lambda m: m.state not in ('cancel'))
vals['move_orig_ids'] = [(4, m.id) for m in move_orig_to_link]
vals['move_dest_ids'] = [(4, m.id) for m in move_dest_to_link]
r.write(vals)
if not returned_lines:
raise UserError(_("Please specify at least one non-zero quantity."))
new_picking.action_confirm()
new_picking.action_assign()
return new_picking.id, picking_type_id
def create_returns(self):
for wizard in self:
new_picking_id, pick_type_id = wizard._create_returns()
# Override the context to disable all the potential filters that could have been set previously
ctx = dict(self.env.context)
ctx.update({
'default_partner_id': self.picking_id.partner_id.id,
'search_default_picking_type_id': pick_type_id,
'search_default_draft': False,
'search_default_assigned': False,
'search_default_confirmed': False,
'search_default_ready': False,
'search_default_planning_issues': False,
'search_default_available': False,
})
return {
'name': _('Returned Picking'),
'view_mode': 'form,tree,calendar',
'res_model': 'stock.picking',
'res_id': new_picking_id,
'type': 'ir.actions.act_window',
'context': ctx,
}
| 54.753769
| 10,896
|
1,445
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
class StockAssignSerialNumbers(models.TransientModel):
_name = 'stock.assign.serial'
_description = 'Stock Assign Serial Numbers'
def _default_next_serial_count(self):
move = self.env['stock.move'].browse(self.env.context.get('default_move_id'))
if move.exists():
filtered_move_lines = move.move_line_ids.filtered(lambda l: not l.lot_name and not l.lot_id)
return len(filtered_move_lines)
product_id = fields.Many2one('product.product', 'Product',
related='move_id.product_id')
move_id = fields.Many2one('stock.move')
next_serial_number = fields.Char('First SN', required=True)
next_serial_count = fields.Integer('Number of SN',
default=_default_next_serial_count, required=True)
@api.constrains('next_serial_count')
def _check_next_serial_count(self):
for wizard in self:
if wizard.next_serial_count < 1:
raise ValidationError(_("The number of Serial Numbers to generate must be greater than zero."))
def generate_serial_numbers(self):
self.ensure_one()
self.move_id.next_serial = self.next_serial_number or ""
return self.move_id._generate_serial_numbers(next_serial_count=self.next_serial_count)
| 42.5
| 1,445
|
1,263
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class StockRequestCount(models.TransientModel):
_name = 'stock.request.count'
_description = 'Stock Request an Inventory Count'
inventory_date = fields.Date(
'Inventory Date', required=True,
help="Choose a date to get the inventory at that date",
default=fields.Datetime.now)
user_id = fields.Many2one('res.users', string="User")
quant_ids = fields.Many2many('stock.quant')
set_count = fields.Selection([('empty', 'Leave Empty'), ('set', 'Set Current Value')], default='empty', string='Count')
def action_request_count(self):
for count_request in self:
if count_request.set_count == 'set':
count_request.quant_ids.filtered(lambda q: not q.inventory_quantity_set).action_set_inventory_quantity()
count_request.quant_ids.with_context(inventory_mode=True).write(
count_request._get_values_to_write())
def _get_values_to_write(self):
values = {
'inventory_date': self.inventory_date,
}
if self.user_id:
values['user_id'] = self.user_id.id,
return values
| 39.46875
| 1,263
|
2,757
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, api, fields, models
from odoo.exceptions import UserError
class StockImmediateTransferLine(models.TransientModel):
_name = 'stock.immediate.transfer.line'
_description = 'Immediate Transfer Line'
immediate_transfer_id = fields.Many2one('stock.immediate.transfer', 'Immediate Transfer', required=True)
picking_id = fields.Many2one('stock.picking', 'Transfer', required=True)
to_immediate = fields.Boolean('To Process')
class StockImmediateTransfer(models.TransientModel):
_name = 'stock.immediate.transfer'
_description = 'Immediate Transfer'
pick_ids = fields.Many2many('stock.picking', 'stock_picking_transfer_rel')
show_transfers = fields.Boolean()
immediate_transfer_line_ids = fields.One2many(
'stock.immediate.transfer.line',
'immediate_transfer_id',
string="Immediate Transfer Lines")
@api.model
def default_get(self, fields):
res = super().default_get(fields)
if 'immediate_transfer_line_ids' in fields and res.get('pick_ids'):
res['immediate_transfer_line_ids'] = [
(0, 0, {'to_immediate': True, 'picking_id': pick_id})
for pick_id in res['pick_ids'][0][2]
]
# default_get returns x2m values as [(6, 0, ids)]
# because of webclient limitations
return res
def process(self):
pickings_to_do = self.env['stock.picking']
pickings_not_to_do = self.env['stock.picking']
for line in self.immediate_transfer_line_ids:
if line.to_immediate is True:
pickings_to_do |= line.picking_id
else:
pickings_not_to_do |= line.picking_id
for picking in pickings_to_do:
# If still in draft => confirm and assign
if picking.state == 'draft':
picking.action_confirm()
if picking.state != 'assigned':
picking.action_assign()
if picking.state != 'assigned':
raise UserError(_("Could not reserve all requested products. Please use the \'Mark as Todo\' button to handle the reservation manually."))
picking.move_lines._set_quantities_to_reservation()
pickings_to_validate = self.env.context.get('button_validate_picking_ids')
if pickings_to_validate:
pickings_to_validate = self.env['stock.picking'].browse(pickings_to_validate)
pickings_to_validate = pickings_to_validate - pickings_not_to_do
return pickings_to_validate.with_context(skip_immediate=True).button_validate()
return True
| 43.078125
| 2,757
|
4,484
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from json import dumps
from datetime import datetime, time
from odoo import api, fields, models, SUPERUSER_ID
from odoo.osv.expression import AND
from odoo.tools import get_month, subtract, format_date
class StockReplenishmentInfo(models.TransientModel):
_name = 'stock.replenishment.info'
_description = 'Stock supplier replenishment information'
_rec_name = 'orderpoint_id'
orderpoint_id = fields.Many2one('stock.warehouse.orderpoint')
product_id = fields.Many2one('product.product', related='orderpoint_id.product_id')
qty_to_order = fields.Float(related='orderpoint_id.qty_to_order')
json_lead_days = fields.Char(compute='_compute_json_lead_days')
json_replenishment_history = fields.Char(compute='_compute_json_replenishment_history')
@api.depends('orderpoint_id')
def _compute_json_lead_days(self):
self.json_lead_days = False
for replenishment_report in self:
if not replenishment_report.orderpoint_id.product_id or not replenishment_report.orderpoint_id.location_id:
continue
orderpoint = replenishment_report.orderpoint_id
orderpoints_values = orderpoint._get_lead_days_values()
dummy, lead_days_description = orderpoint.rule_ids._get_lead_days(
orderpoint.product_id, **orderpoints_values)
replenishment_report.json_lead_days = dumps({
'template': 'stock.leadDaysPopOver',
'lead_days_date': format_date(self.env, replenishment_report.orderpoint_id.lead_days_date),
'lead_days_description': lead_days_description,
'today': format_date(self.env, fields.Date.today()),
'trigger': orderpoint.trigger,
'qty_forecast': self.env['ir.qweb.field.float'].value_to_html(orderpoint.qty_forecast, {'decimal_precision': 'Product Unit of Measure'}),
'qty_to_order': self.env['ir.qweb.field.float'].value_to_html(orderpoint.qty_to_order, {'decimal_precision': 'Product Unit of Measure'}),
'product_min_qty': self.env['ir.qweb.field.float'].value_to_html(orderpoint.product_min_qty, {'decimal_precision': 'Product Unit of Measure'}),
'product_max_qty': self.env['ir.qweb.field.float'].value_to_html(orderpoint.product_max_qty, {'decimal_precision': 'Product Unit of Measure'}),
'product_uom_name': orderpoint.product_uom_name,
'virtual': orderpoint.trigger == 'manual' and orderpoint.create_uid.id == SUPERUSER_ID,
})
@api.depends('orderpoint_id')
def _compute_json_replenishment_history(self):
for replenishment_report in self:
replenishment_history = []
today = fields.Datetime.now()
first_month = subtract(today, months=2)
date_from, dummy = get_month(first_month)
dummy, date_to = get_month(today)
domain = [
('product_id', '=', replenishment_report.product_id.id),
('date', '>=', date_from),
('date', '<=', datetime.combine(date_to, time.max)),
('state', '=', 'done'),
('company_id', '=', replenishment_report.orderpoint_id.company_id.id)
]
quantity_by_month_out = self.env['stock.move'].read_group(
AND([domain, [('location_dest_id.usage', '=', 'customer')]]),
['date', 'product_qty'], ['date:month'])
quantity_by_month_returned = self.env['stock.move'].read_group(
AND([domain, [('location_id.usage', '=', 'customer')]]),
['date', 'product_qty'], ['date:month'])
quantity_by_month_returned = {
g['date:month']: g['product_qty'] for g in quantity_by_month_returned}
for group in quantity_by_month_out:
month = group['date:month']
replenishment_history.append({
'name': month,
'quantity': group['product_qty'] - quantity_by_month_returned.get(month, 0),
'uom_name': replenishment_report.product_id.uom_id.display_name,
})
replenishment_report.json_replenishment_history = dumps({
'template': 'stock.replenishmentHistory',
'replenishment_history': replenishment_history
})
| 56.05
| 4,484
|
2,347
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class StockRulesReport(models.TransientModel):
_name = 'stock.rules.report'
_description = 'Stock Rules report'
product_id = fields.Many2one('product.product', string='Product', required=True)
product_tmpl_id = fields.Many2one('product.template', string='Product Template', required=True)
warehouse_ids = fields.Many2many('stock.warehouse', string='Warehouses', required=True,
help="Show the routes that apply on selected warehouses.")
product_has_variants = fields.Boolean('Has variants', default=False, required=True)
@api.model
def default_get(self, fields):
res = super(StockRulesReport, self).default_get(fields)
product_tmpl_id = self.env['product.template']
if 'product_id' in fields:
if self.env.context.get('default_product_id'):
product_id = self.env['product.product'].browse(self.env.context['default_product_id'])
product_tmpl_id = product_id.product_tmpl_id
res['product_tmpl_id'] = product_id.product_tmpl_id.id
res['product_id'] = product_id.id
elif self.env.context.get('default_product_tmpl_id'):
product_tmpl_id = self.env['product.template'].browse(self.env.context['default_product_tmpl_id'])
res['product_tmpl_id'] = product_tmpl_id.id
res['product_id'] = product_tmpl_id.product_variant_id.id
if len(product_tmpl_id.product_variant_ids) > 1:
res['product_has_variants'] = True
if 'warehouse_ids' in fields:
company = product_tmpl_id.company_id or self.env.company
warehouse_id = self.env['stock.warehouse'].search([('company_id', '=', company.id)], limit=1).id
res['warehouse_ids'] = [(6, 0, [warehouse_id])]
return res
def _prepare_report_data(self):
data = {
'product_id': self.product_id.id,
'warehouse_ids': self.warehouse_ids.ids,
}
return data
def print_report(self):
self.ensure_one()
data = self._prepare_report_data()
return self.env.ref('stock.action_report_stock_rule').report_action(None, data=data)
| 46.94
| 2,347
|
1,900
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, api, fields, models
from odoo.exceptions import UserError
class ProductChangeQuantity(models.TransientModel):
_name = "stock.change.product.qty"
_description = "Change Product Quantity"
product_id = fields.Many2one('product.product', 'Product', required=True)
product_tmpl_id = fields.Many2one('product.template', 'Template', required=True)
product_variant_count = fields.Integer('Variant Count', related='product_tmpl_id.product_variant_count')
new_quantity = fields.Float(
'New Quantity on Hand', default=1,
digits='Product Unit of Measure', required=True,
help='This quantity is expressed in the Default Unit of Measure of the product.')
@api.onchange('product_id')
def _onchange_product_id(self):
self.new_quantity = self.product_id.qty_available
@api.constrains('new_quantity')
def check_new_quantity(self):
if any(wizard.new_quantity < 0 for wizard in self):
raise UserError(_('Quantity cannot be negative.'))
def change_product_qty(self):
""" Changes the Product Quantity by creating/editing corresponding quant.
"""
warehouse = self.env['stock.warehouse'].search(
[('company_id', '=', self.env.company.id)], limit=1
)
# Before creating a new quant, the quand `create` method will check if
# it exists already. If it does, it'll edit its `inventory_quantity`
# instead of create a new one.
self.env['stock.quant'].with_context(inventory_mode=True).create({
'product_id': self.product_id.id,
'location_id': warehouse.lot_stock_id.id,
'inventory_quantity': self.new_quantity,
})._apply_inventory()
return {'type': 'ir.actions.act_window_close'}
| 44.186047
| 1,900
|
1,176
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, _
class StockInventoryAdjustmentName(models.TransientModel):
_name = 'stock.inventory.adjustment.name'
_description = 'Inventory Adjustment Reference / Reason'
def default_get(self, fields_list):
res = super().default_get(fields_list)
if self.env.context.get('default_quant_ids'):
quants = self.env['stock.quant'].browse(self.env.context['default_quant_ids'])
res['show_info'] = any(not quant.inventory_quantity_set for quant in quants)
return res
def _default_inventory_adjustment_name(self):
return _("Inventory Adjustment") + " - " + fields.Date.to_string(fields.Date.today())
quant_ids = fields.Many2many('stock.quant')
inventory_adjustment_name = fields.Char(default=_default_inventory_adjustment_name)
show_info = fields.Boolean('Show warning')
def action_apply(self):
quants = self.quant_ids.filtered('inventory_quantity_set')
return quants.with_context(inventory_name=self.inventory_adjustment_name).action_apply_inventory()
| 43.555556
| 1,176
|
27,511
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import calendar
from collections import defaultdict, OrderedDict
from datetime import timedelta
from odoo import _, api, fields, models
from odoo.exceptions import UserError
from odoo.tools.misc import groupby
from odoo.osv import expression
from odoo.tools.float_utils import float_compare
class Location(models.Model):
_name = "stock.location"
_description = "Inventory Locations"
_parent_name = "location_id"
_parent_store = True
_order = 'complete_name, id'
_rec_name = 'complete_name'
_check_company_auto = True
@api.model
def default_get(self, fields):
res = super(Location, self).default_get(fields)
if 'barcode' in fields and 'barcode' not in res and res.get('complete_name'):
res['barcode'] = res['complete_name']
return res
name = fields.Char('Location Name', required=True)
complete_name = fields.Char("Full Location Name", compute='_compute_complete_name', recursive=True, store=True)
active = fields.Boolean('Active', default=True, help="By unchecking the active field, you may hide a location without deleting it.")
usage = fields.Selection([
('supplier', 'Vendor Location'),
('view', 'View'),
('internal', 'Internal Location'),
('customer', 'Customer Location'),
('inventory', 'Inventory Loss'),
('production', 'Production'),
('transit', 'Transit Location')], string='Location Type',
default='internal', index=True, required=True,
help="* Vendor Location: Virtual location representing the source location for products coming from your vendors"
"\n* View: Virtual location used to create a hierarchical structures for your warehouse, aggregating its child locations ; can't directly contain products"
"\n* Internal Location: Physical locations inside your own warehouses,"
"\n* Customer Location: Virtual location representing the destination location for products sent to your customers"
"\n* Inventory Loss: Virtual location serving as counterpart for inventory operations used to correct stock levels (Physical inventories)"
"\n* Production: Virtual counterpart location for production operations: this location consumes the components and produces finished products"
"\n* Transit Location: Counterpart location that should be used in inter-company or inter-warehouses operations")
location_id = fields.Many2one(
'stock.location', 'Parent Location', index=True, ondelete='cascade', check_company=True,
help="The parent location that includes this location. Example : The 'Dispatch Zone' is the 'Gate 1' parent location.")
child_ids = fields.One2many('stock.location', 'location_id', 'Contains')
child_internal_location_ids = fields.Many2many(
'stock.location',
string='Internal locations amoung descendants',
compute='_compute_child_internal_location_ids',
recursive=True,
help='This location (if it\'s internal) and all its descendants filtered by type=Internal.'
)
comment = fields.Html('Additional Information')
posx = fields.Integer('Corridor (X)', default=0, help="Optional localization details, for information purpose only")
posy = fields.Integer('Shelves (Y)', default=0, help="Optional localization details, for information purpose only")
posz = fields.Integer('Height (Z)', default=0, help="Optional localization details, for information purpose only")
parent_path = fields.Char(index=True)
company_id = fields.Many2one(
'res.company', 'Company',
default=lambda self: self.env.company, index=True,
help='Let this field empty if this location is shared between companies')
scrap_location = fields.Boolean('Is a Scrap Location?', default=False, help='Check this box to allow using this location to put scrapped/damaged goods.')
return_location = fields.Boolean('Is a Return Location?', help='Check this box to allow using this location as a return location.')
removal_strategy_id = fields.Many2one(
'product.removal', 'Removal Strategy',
help="Defines the default method used for suggesting the exact location (shelf) "
"where to take the products from, which lot etc. for this location. "
"This method can be enforced at the product category level, "
"and a fallback is made on the parent locations if none is set here.\n\n"
"FIFO: products/lots that were stocked first will be moved out first.\n"
"LIFO: products/lots that were stocked last will be moved out first.\n"
"Closet location: products/lots closest to the target location will be moved out first.\n"
"FEFO: products/lots with the closest removal date will be moved out first "
"(the availability of this method depends on the \"Expiration Dates\" setting).")
putaway_rule_ids = fields.One2many('stock.putaway.rule', 'location_in_id', 'Putaway Rules')
barcode = fields.Char('Barcode', copy=False)
quant_ids = fields.One2many('stock.quant', 'location_id')
cyclic_inventory_frequency = fields.Integer("Inventory Frequency (Days)", default=0, help=" When different than 0, inventory count date for products stored at this location will be automatically set at the defined frequency.")
last_inventory_date = fields.Date("Last Effective Inventory", readonly=True, help="Date of the last inventory at this location.")
next_inventory_date = fields.Date("Next Expected Inventory", compute="_compute_next_inventory_date", store=True, help="Date for next planned inventory based on cyclic schedule.")
warehouse_view_ids = fields.One2many('stock.warehouse', 'view_location_id', readonly=True)
warehouse_id = fields.Many2one('stock.warehouse', compute='_compute_warehouse_id')
storage_category_id = fields.Many2one('stock.storage.category', string='Storage Category', check_company=True)
outgoing_move_line_ids = fields.One2many('stock.move.line', 'location_id', help='Technical: used to compute weight.')
incoming_move_line_ids = fields.One2many('stock.move.line', 'location_dest_id', help='Technical: used to compute weight.')
net_weight = fields.Float('Net Weight', compute="_compute_weight")
forecast_weight = fields.Float('Forecasted Weight', compute="_compute_weight")
_sql_constraints = [('barcode_company_uniq', 'unique (barcode,company_id)', 'The barcode for a location must be unique per company !'),
('inventory_freq_nonneg', 'check(cyclic_inventory_frequency >= 0)', 'The inventory frequency (days) for a location must be non-negative')]
@api.depends('outgoing_move_line_ids.product_qty', 'incoming_move_line_ids.product_qty',
'outgoing_move_line_ids.state', 'incoming_move_line_ids.state',
'outgoing_move_line_ids.product_id.weight', 'outgoing_move_line_ids.product_id.weight',
'quant_ids.quantity', 'quant_ids.product_id.weight')
@api.depends_context('exclude_sml_ids')
def _compute_weight(self):
for location in self:
location.net_weight = 0
quants = location.quant_ids.filtered(lambda q: q.product_id.type != 'service')
excluded_sml_ids = self._context.get('exclude_sml_ids', [])
incoming_move_lines = location.incoming_move_line_ids.filtered(lambda ml: ml.product_id.type != 'service' and ml.state not in ['draft', 'done', 'cancel'] and ml.id not in excluded_sml_ids)
outgoing_move_lines = location.outgoing_move_line_ids.filtered(lambda ml: ml.product_id.type != 'service' and ml.state not in ['draft', 'done', 'cancel'] and ml.id not in excluded_sml_ids)
for quant in quants:
location.net_weight += quant.product_id.weight * quant.quantity
location.forecast_weight = location.net_weight
for line in incoming_move_lines:
location.forecast_weight += line.product_id.weight * line.product_qty
for line in outgoing_move_lines:
location.forecast_weight -= line.product_id.weight * line.product_qty
@api.depends('name', 'location_id.complete_name', 'usage')
def _compute_complete_name(self):
for location in self:
if location.location_id and location.usage != 'view':
location.complete_name = '%s/%s' % (location.location_id.complete_name, location.name)
else:
location.complete_name = location.name
@api.depends('cyclic_inventory_frequency', 'last_inventory_date', 'usage', 'company_id')
def _compute_next_inventory_date(self):
for location in self:
if location.company_id and location.usage in ['internal', 'transit'] and location.cyclic_inventory_frequency > 0:
try:
if location.last_inventory_date:
days_until_next_inventory = location.cyclic_inventory_frequency - (fields.Date.today() - location.last_inventory_date).days
if days_until_next_inventory <= 0:
location.next_inventory_date = fields.Date.today() + timedelta(days=1)
else:
location.next_inventory_date = location.last_inventory_date + timedelta(days=location.cyclic_inventory_frequency)
else:
location.next_inventory_date = fields.Date.today() + timedelta(days=location.cyclic_inventory_frequency)
except OverflowError:
raise UserError(_("The selected Inventory Frequency (Days) creates a date too far into the future."))
else:
location.next_inventory_date = False
@api.depends('warehouse_view_ids')
def _compute_warehouse_id(self):
warehouses = self.env['stock.warehouse'].search([('view_location_id', 'parent_of', self.ids)])
view_by_wh = OrderedDict((wh.view_location_id.id, wh.id) for wh in warehouses)
self.warehouse_id = False
for loc in self:
path = set(int(loc_id) for loc_id in loc.parent_path.split('/')[:-1])
for view_location_id in view_by_wh:
if view_location_id in path:
loc.warehouse_id = view_by_wh[view_location_id]
break
@api.depends('child_ids.usage', 'child_ids.child_internal_location_ids')
def _compute_child_internal_location_ids(self):
# batch reading optimization is not possible because the field has recursive=True
for loc in self:
loc.child_internal_location_ids = self.search([('id', 'child_of', loc.id), ('usage', '=', 'internal')])
@api.onchange('usage')
def _onchange_usage(self):
if self.usage not in ('internal', 'inventory'):
self.scrap_location = False
def write(self, values):
if 'company_id' in values:
for location in self:
if location.company_id.id != values['company_id']:
raise UserError(_("Changing the company of this record is forbidden at this point, you should rather archive it and create a new one."))
if 'usage' in values and values['usage'] == 'view':
if self.mapped('quant_ids'):
raise UserError(_("This location's usage cannot be changed to view as it contains products."))
if 'usage' in values or 'scrap_location' in values:
modified_locations = self.filtered(
lambda l: any(l[f] != values[f] if f in values else False
for f in {'usage', 'scrap_location'}))
reserved_quantities = self.env['stock.move.line'].search_count([
('location_id', 'in', modified_locations.ids),
('product_qty', '>', 0),
])
if reserved_quantities:
raise UserError(_(
"You cannot change the location type or its use as a scrap"
" location as there are products reserved in this location."
" Please unreserve the products first."
))
if 'active' in values:
if values['active'] == False:
for location in self:
warehouses = self.env['stock.warehouse'].search([('active', '=', True), '|', ('lot_stock_id', '=', location.id), ('view_location_id', '=', location.id)])
if warehouses:
raise UserError(_("You cannot archive the location %s as it is"
" used by your warehouse %s") % (location.display_name, warehouses[0].display_name))
if not self.env.context.get('do_not_check_quant'):
children_location = self.env['stock.location'].with_context(active_test=False).search([('id', 'child_of', self.ids)])
internal_children_locations = children_location.filtered(lambda l: l.usage == 'internal')
children_quants = self.env['stock.quant'].search(['&', '|', ('quantity', '!=', 0), ('reserved_quantity', '!=', 0), ('location_id', 'in', internal_children_locations.ids)])
if children_quants and values['active'] == False:
raise UserError(_('You still have some product in locations %s') %
(', '.join(children_quants.mapped('location_id.display_name'))))
else:
super(Location, children_location - self).with_context(do_not_check_quant=True).write({
'active': values['active'],
})
res = super(Location, self).write(values)
self.invalidate_cache(['warehouse_id'])
return res
@api.model_create_multi
def create(self, vals_list):
res = super().create(vals_list)
self.invalidate_cache(['warehouse_id'])
return res
@api.model
def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None):
""" search full name and barcode """
args = args or []
if operator == 'ilike' and not (name or '').strip():
domain = []
elif operator in expression.NEGATIVE_TERM_OPERATORS:
domain = [('barcode', operator, name), ('complete_name', operator, name)]
else:
domain = ['|', ('barcode', operator, name), ('complete_name', operator, name)]
return self._search(expression.AND([domain, args]), limit=limit, access_rights_uid=name_get_uid)
def _get_putaway_strategy(self, product, quantity=0, package=None, packaging=None, additional_qty=None):
"""Returns the location where the product has to be put, if any compliant
putaway strategy is found. Otherwise returns self.
The quantity should be in the default UOM of the product, it is used when
no package is specified.
"""
products = self.env.context.get('products', self.env['product.product'])
products |= product
# find package type on package or packaging
package_type = self.env['stock.package.type']
if package:
package_type = package.package_type_id
elif packaging:
package_type = packaging.package_type_id
categ = products.categ_id if len(products.categ_id) == 1 else self.env['product.category']
categs = categ
while categ.parent_id:
categ = categ.parent_id
categs |= categ
putaway_rules = self.putaway_rule_ids.filtered(lambda rule:
(not rule.product_id or rule.product_id in products) and
(not rule.category_id or rule.category_id in categs) and
(not rule.package_type_ids or package_type in rule.package_type_ids))
putaway_rules = putaway_rules.sorted(lambda rule: (rule.package_type_ids,
rule.product_id,
rule.category_id == categs[:1], # same categ, not a parent
rule.category_id),
reverse=True)
putaway_location = None
locations = self.child_internal_location_ids
if putaway_rules:
# get current product qty (qty in current quants and future qty on assigned ml) of all child locations
qty_by_location = defaultdict(lambda: 0)
if locations.storage_category_id:
if package and package.package_type_id:
move_line_data = self.env['stock.move.line'].read_group([
('id', 'not in', self._context.get('exclude_sml_ids', [])),
('result_package_id.package_type_id', '=', package_type.id),
('state', 'not in', ['draft', 'cancel', 'done']),
], ['result_package_id:count_distinct'], ['location_dest_id'])
quant_data = self.env['stock.quant'].read_group([
('package_id.package_type_id', '=', package_type.id),
('location_id', 'in', locations.ids),
], ['package_id:count_distinct'], ['location_id'])
for values in move_line_data:
qty_by_location[values['location_dest_id'][0]] = values['result_package_id']
for values in quant_data:
qty_by_location[values['location_id'][0]] += values['package_id']
else:
move_line_data = self.env['stock.move.line'].read_group([
('id', 'not in', self._context.get('exclude_sml_ids', [])),
('product_id', '=', product.id),
('location_dest_id', 'in', locations.ids),
('state', 'not in', ['draft', 'done', 'cancel'])
], ['location_dest_id', 'product_id', 'product_qty:array_agg', 'qty_done:array_agg', 'product_uom_id:array_agg'], ['location_dest_id'])
quant_data = self.env['stock.quant'].read_group([
('product_id', '=', product.id),
('location_id', 'in', locations.ids),
], ['location_id', 'product_id', 'quantity:sum'], ['location_id'])
for values in move_line_data:
uoms = self.env['uom.uom'].browse(values['product_uom_id'])
qty_done = sum(max(ml_uom._compute_quantity(float(qty), product.uom_id), float(qty_reserved))
for qty_reserved, qty, ml_uom in zip(values['product_qty'], values['qty_done'], list(uoms)))
qty_by_location[values['location_dest_id'][0]] = qty_done
for values in quant_data:
qty_by_location[values['location_id'][0]] += values['quantity']
if additional_qty:
for location_id, qty in additional_qty.items():
qty_by_location[location_id] += qty
putaway_location = putaway_rules._get_putaway_location(product, quantity, package, packaging, qty_by_location)
if not putaway_location:
putaway_location = locations[0] if locations and self.usage == 'view' else self
return putaway_location
def _get_next_inventory_date(self):
""" Used to get the next inventory date for a quant located in this location. It is
based on:
1. Does the location have a cyclic inventory set?
2. If not 1, then is there an annual inventory date set (for its company)?
3. If not 1 and 2, then quants have no next inventory date."""
if self.usage not in ['internal', 'transit']:
return False
next_inventory_date = False
if self.next_inventory_date:
next_inventory_date = self.next_inventory_date
elif self.company_id.annual_inventory_month:
today = fields.Date.today()
annual_inventory_month = int(self.company_id.annual_inventory_month)
# Manage 0 and negative annual_inventory_day
annual_inventory_day = max(self.company_id.annual_inventory_day, 1)
max_day = calendar.monthrange(today.year, annual_inventory_month)[1]
# Manage annual_inventory_day bigger than last_day
annual_inventory_day = min(annual_inventory_day, max_day)
next_inventory_date = today.replace(
month=annual_inventory_month, day=annual_inventory_day)
if next_inventory_date <= today:
# Manage leap year with the february
max_day = calendar.monthrange(today.year + 1, annual_inventory_month)[1]
annual_inventory_day = min(annual_inventory_day, max_day)
next_inventory_date = next_inventory_date.replace(
day=annual_inventory_day, year=today.year + 1)
return next_inventory_date
def should_bypass_reservation(self):
self.ensure_one()
return self.usage in ('supplier', 'customer', 'inventory', 'production') or self.scrap_location or (self.usage == 'transit' and not self.company_id)
def _check_can_be_used(self, product, quantity=0, package=None, location_qty=0):
"""Check if product/package can be stored in the location. Quantity
should in the default uom of product, it's only used when no package is
specified."""
self.ensure_one()
if self.storage_category_id:
# check if enough space
if package and package.package_type_id:
# check weight
package_smls = self.env['stock.move.line'].search([('result_package_id', '=', package.id)])
if self.storage_category_id.max_weight < self.forecast_weight + sum(package_smls.mapped(lambda sml: sml.product_qty * sml.product_id.weight)):
return False
# check if enough space
package_capacity = self.storage_category_id.package_capacity_ids.filtered(lambda pc: pc.package_type_id == package.package_type_id)
if package_capacity and location_qty >= package_capacity.quantity:
return False
else:
# check weight
if self.storage_category_id.max_weight < self.forecast_weight + product.weight * quantity:
return False
product_capacity = self.storage_category_id.product_capacity_ids.filtered(lambda pc: pc.product_id == product)
# To handle new line without quantity in order to avoid suggesting a location already full
if product_capacity and location_qty >= product_capacity.quantity:
return False
if product_capacity and quantity + location_qty > product_capacity.quantity:
return False
positive_quant = self.quant_ids.filtered(lambda q: float_compare(q.quantity, 0, precision_rounding=q.product_id.uom_id.rounding) > 0)
# check if only allow new product when empty
if self.storage_category_id.allow_new_product == "empty" and positive_quant:
return False
# check if only allow same product
if self.storage_category_id.allow_new_product == "same":
# In case it's a package, `product` is not defined, so try to get
# the package products from the context
product = product or self._context.get('products')
if (positive_quant and positive_quant.product_id != product) or len(product) > 1:
return False
if self.env['stock.move.line'].search([
('product_id', '!=', product.id),
('state', 'not in', ('done', 'cancel')),
('location_dest_id', '=', self.id),
], limit=1):
return False
return True
class Route(models.Model):
_name = 'stock.location.route'
_description = "Inventory Routes"
_order = 'sequence'
_check_company_auto = True
name = fields.Char('Route', required=True, translate=True)
active = fields.Boolean('Active', default=True, help="If the active field is set to False, it will allow you to hide the route without removing it.")
sequence = fields.Integer('Sequence', default=0)
rule_ids = fields.One2many('stock.rule', 'route_id', 'Rules', copy=True)
product_selectable = fields.Boolean('Applicable on Product', default=True, help="When checked, the route will be selectable in the Inventory tab of the Product form.")
product_categ_selectable = fields.Boolean('Applicable on Product Category', help="When checked, the route will be selectable on the Product Category.")
warehouse_selectable = fields.Boolean('Applicable on Warehouse', help="When a warehouse is selected for this route, this route should be seen as the default route when products pass through this warehouse.")
packaging_selectable = fields.Boolean('Applicable on Packaging', help="When checked, the route will be selectable on the Product Packaging.")
supplied_wh_id = fields.Many2one('stock.warehouse', 'Supplied Warehouse')
supplier_wh_id = fields.Many2one('stock.warehouse', 'Supplying Warehouse')
company_id = fields.Many2one(
'res.company', 'Company',
default=lambda self: self.env.company, index=True,
help='Leave this field empty if this route is shared between all companies')
product_ids = fields.Many2many(
'product.template', 'stock_route_product', 'route_id', 'product_id',
'Products', copy=False, check_company=True)
categ_ids = fields.Many2many('product.category', 'stock_location_route_categ', 'route_id', 'categ_id', 'Product Categories', copy=False)
packaging_ids = fields.Many2many('product.packaging', 'stock_location_route_packaging', 'route_id', 'packaging_id', 'Packagings', copy=False, check_company=True)
warehouse_domain_ids = fields.One2many('stock.warehouse', compute='_compute_warehouses')
warehouse_ids = fields.Many2many(
'stock.warehouse', 'stock_route_warehouse', 'route_id', 'warehouse_id',
'Warehouses', copy=False, domain="[('id', 'in', warehouse_domain_ids)]")
@api.depends('company_id')
def _compute_warehouses(self):
for loc in self:
domain = [('company_id', '=', loc.company_id.id)] if loc.company_id else []
loc.warehouse_domain_ids = self.env['stock.warehouse'].search(domain)
@api.onchange('company_id')
def _onchange_company(self):
if self.company_id:
self.warehouse_ids = self.warehouse_ids.filtered(lambda w: w.company_id == self.company_id)
@api.onchange('warehouse_selectable')
def _onchange_warehouse_selectable(self):
if not self.warehouse_selectable:
self.warehouse_ids = [(5, 0, 0)]
def toggle_active(self):
for route in self:
route.with_context(active_test=False).rule_ids.filtered(lambda ru: ru.active == route.active).toggle_active()
super(Route, self).toggle_active()
| 62.10158
| 27,511
|
56,738
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from collections import namedtuple
from odoo import _, _lt, api, fields, models
from odoo.exceptions import UserError
_logger = logging.getLogger(__name__)
ROUTE_NAMES = {
'one_step': _lt('Receive in 1 step (stock)'),
'two_steps': _lt('Receive in 2 steps (input + stock)'),
'three_steps': _lt('Receive in 3 steps (input + quality + stock)'),
'crossdock': _lt('Cross-Dock'),
'ship_only': _lt('Deliver in 1 step (ship)'),
'pick_ship': _lt('Deliver in 2 steps (pick + ship)'),
'pick_pack_ship': _lt('Deliver in 3 steps (pick + pack + ship)'),
}
class Warehouse(models.Model):
_name = "stock.warehouse"
_description = "Warehouse"
_order = 'sequence,id'
_check_company_auto = True
# namedtuple used in helper methods generating values for routes
Routing = namedtuple('Routing', ['from_loc', 'dest_loc', 'picking_type', 'action'])
def _default_name(self):
count = self.env['stock.warehouse'].with_context(active_test=False).search_count([('company_id', '=', self.env.company.id)])
return "%s - warehouse # %s" % (self.env.company.name, count + 1) if count else self.env.company.name
name = fields.Char('Warehouse', index=True, required=True, default=_default_name)
active = fields.Boolean('Active', default=True)
company_id = fields.Many2one(
'res.company', 'Company', default=lambda self: self.env.company,
index=True, readonly=True, required=True,
help='The company is automatically set from your user preferences.')
partner_id = fields.Many2one('res.partner', 'Address', default=lambda self: self.env.company.partner_id, check_company=True)
view_location_id = fields.Many2one(
'stock.location', 'View Location',
domain="[('usage', '=', 'view'), ('company_id', '=', company_id)]",
required=True, check_company=True)
lot_stock_id = fields.Many2one(
'stock.location', 'Location Stock',
domain="[('usage', '=', 'internal'), ('company_id', '=', company_id)]",
required=True, check_company=True)
code = fields.Char('Short Name', required=True, size=5, help="Short name used to identify your warehouse")
route_ids = fields.Many2many(
'stock.location.route', 'stock_route_warehouse', 'warehouse_id', 'route_id',
'Routes',
domain="[('warehouse_selectable', '=', True), '|', ('company_id', '=', False), ('company_id', '=', company_id)]",
help='Defaults routes through the warehouse', check_company=True)
reception_steps = fields.Selection([
('one_step', 'Receive goods directly (1 step)'),
('two_steps', 'Receive goods in input and then stock (2 steps)'),
('three_steps', 'Receive goods in input, then quality and then stock (3 steps)')],
'Incoming Shipments', default='one_step', required=True,
help="Default incoming route to follow")
delivery_steps = fields.Selection([
('ship_only', 'Deliver goods directly (1 step)'),
('pick_ship', 'Send goods in output and then deliver (2 steps)'),
('pick_pack_ship', 'Pack goods, send goods in output and then deliver (3 steps)')],
'Outgoing Shipments', default='ship_only', required=True,
help="Default outgoing route to follow")
wh_input_stock_loc_id = fields.Many2one('stock.location', 'Input Location', check_company=True)
wh_qc_stock_loc_id = fields.Many2one('stock.location', 'Quality Control Location', check_company=True)
wh_output_stock_loc_id = fields.Many2one('stock.location', 'Output Location', check_company=True)
wh_pack_stock_loc_id = fields.Many2one('stock.location', 'Packing Location', check_company=True)
mto_pull_id = fields.Many2one('stock.rule', 'MTO rule')
pick_type_id = fields.Many2one('stock.picking.type', 'Pick Type', check_company=True)
pack_type_id = fields.Many2one('stock.picking.type', 'Pack Type', check_company=True)
out_type_id = fields.Many2one('stock.picking.type', 'Out Type', check_company=True)
in_type_id = fields.Many2one('stock.picking.type', 'In Type', check_company=True)
int_type_id = fields.Many2one('stock.picking.type', 'Internal Type', check_company=True)
return_type_id = fields.Many2one('stock.picking.type', 'Return Type', check_company=True)
crossdock_route_id = fields.Many2one('stock.location.route', 'Crossdock Route', ondelete='restrict')
reception_route_id = fields.Many2one('stock.location.route', 'Receipt Route', ondelete='restrict')
delivery_route_id = fields.Many2one('stock.location.route', 'Delivery Route', ondelete='restrict')
resupply_wh_ids = fields.Many2many(
'stock.warehouse', 'stock_wh_resupply_table', 'supplied_wh_id', 'supplier_wh_id',
'Resupply From', help="Routes will be created automatically to resupply this warehouse from the warehouses ticked")
resupply_route_ids = fields.One2many(
'stock.location.route', 'supplied_wh_id', 'Resupply Routes',
help="Routes will be created for these resupply warehouses and you can select them on products and product categories")
sequence = fields.Integer(default=10,
help="Gives the sequence of this line when displaying the warehouses.")
_sql_constraints = [
('warehouse_name_uniq', 'unique(name, company_id)', 'The name of the warehouse must be unique per company!'),
('warehouse_code_uniq', 'unique(code, company_id)', 'The short name of the warehouse must be unique per company!'),
]
@api.onchange('company_id')
def _onchange_company_id(self):
group_user = self.env.ref('base.group_user')
group_stock_multi_warehouses = self.env.ref('stock.group_stock_multi_warehouses')
group_stock_multi_location = self.env.ref('stock.group_stock_multi_locations')
if group_stock_multi_warehouses not in group_user.implied_ids and group_stock_multi_location not in group_user.implied_ids:
return {
'warning': {
'title': _('Warning'),
'message': _('Creating a new warehouse will automatically activate the Storage Locations setting')
}
}
@api.model
def create(self, vals):
# create view location for warehouse then create all locations
loc_vals = {'name': vals.get('code'), 'usage': 'view',
'location_id': self.env.ref('stock.stock_location_locations').id}
if vals.get('company_id'):
loc_vals['company_id'] = vals.get('company_id')
vals['view_location_id'] = self.env['stock.location'].create(loc_vals).id
sub_locations = self._get_locations_values(vals)
for field_name, values in sub_locations.items():
values['location_id'] = vals['view_location_id']
if vals.get('company_id'):
values['company_id'] = vals.get('company_id')
vals[field_name] = self.env['stock.location'].with_context(active_test=False).create(values).id
# actually create WH
warehouse = super(Warehouse, self).create(vals)
# create sequences and operation types
new_vals = warehouse._create_or_update_sequences_and_picking_types()
warehouse.write(new_vals) # TDE FIXME: use super ?
# create routes and push/stock rules
route_vals = warehouse._create_or_update_route()
warehouse.write(route_vals)
# Update global route with specific warehouse rule.
warehouse._create_or_update_global_routes_rules()
# create route selectable on the product to resupply the warehouse from another one
warehouse.create_resupply_routes(warehouse.resupply_wh_ids)
# update partner data if partner assigned
if vals.get('partner_id'):
self._update_partner_data(vals['partner_id'], vals.get('company_id'))
self._check_multiwarehouse_group()
return warehouse
def write(self, vals):
if 'company_id' in vals:
for warehouse in self:
if warehouse.company_id.id != vals['company_id']:
raise UserError(_("Changing the company of this record is forbidden at this point, you should rather archive it and create a new one."))
Route = self.env['stock.location.route']
warehouses = self.with_context(active_test=False)
warehouses._create_missing_locations(vals)
if vals.get('reception_steps'):
warehouses._update_location_reception(vals['reception_steps'])
if vals.get('delivery_steps'):
warehouses._update_location_delivery(vals['delivery_steps'])
if vals.get('reception_steps') or vals.get('delivery_steps'):
warehouses._update_reception_delivery_resupply(vals.get('reception_steps'), vals.get('delivery_steps'))
if vals.get('resupply_wh_ids') and not vals.get('resupply_route_ids'):
new_resupply_whs = self.new({
'resupply_wh_ids': vals['resupply_wh_ids']
}).resupply_wh_ids._origin
old_resupply_whs = {warehouse.id: warehouse.resupply_wh_ids for warehouse in warehouses}
# If another partner assigned
if vals.get('partner_id'):
if vals.get('company_id'):
warehouses._update_partner_data(vals['partner_id'], vals.get('company_id'))
else:
for warehouse in self:
warehouse._update_partner_data(vals['partner_id'], warehouse.company_id.id)
res = super(Warehouse, self).write(vals)
if vals.get('code') or vals.get('name'):
warehouses._update_name_and_code(vals.get('name'), vals.get('code'))
for warehouse in warehouses:
# check if we need to delete and recreate route
depends = [depend for depends in [value.get('depends', []) for value in warehouse._get_routes_values().values()] for depend in depends]
if 'code' in vals or any(depend in vals for depend in depends):
picking_type_vals = warehouse._create_or_update_sequences_and_picking_types()
if picking_type_vals:
warehouse.write(picking_type_vals)
if any(depend in vals for depend in depends):
route_vals = warehouse._create_or_update_route()
if route_vals:
warehouse.write(route_vals)
# Check if a global rule(mto, buy, ...) need to be modify.
# The field that impact those rules are listed in the
# _get_global_route_rules_values method under the key named
# 'depends'.
global_rules = warehouse._get_global_route_rules_values()
depends = [depend for depends in [value.get('depends', []) for value in global_rules.values()] for depend in depends]
if any(rule in vals for rule in global_rules) or\
any(depend in vals for depend in depends):
warehouse._create_or_update_global_routes_rules()
if 'active' in vals:
picking_type_ids = self.env['stock.picking.type'].with_context(active_test=False).search([('warehouse_id', '=', warehouse.id)])
move_ids = self.env['stock.move'].search([
('picking_type_id', 'in', picking_type_ids.ids),
('state', 'not in', ('done', 'cancel')),
])
if move_ids:
raise UserError(_('You still have ongoing operations for picking types %s in warehouse %s') %
(', '.join(move_ids.mapped('picking_type_id.name')), warehouse.name))
else:
picking_type_ids.write({'active': vals['active']})
location_ids = self.env['stock.location'].with_context(active_test=False).search([('location_id', 'child_of', warehouse.view_location_id.id)])
picking_type_using_locations = self.env['stock.picking.type'].search([
('default_location_src_id', 'in', location_ids.ids),
('default_location_dest_id', 'in', location_ids.ids),
('id', 'not in', picking_type_ids.ids),
])
if picking_type_using_locations:
raise UserError(_('%s use default source or destination locations from warehouse %s that will be archived.') %
(', '.join(picking_type_using_locations.mapped('name')), warehouse.name))
warehouse.view_location_id.write({'active': vals['active']})
rule_ids = self.env['stock.rule'].with_context(active_test=False).search([('warehouse_id', '=', warehouse.id)])
# Only modify route that apply on this warehouse.
warehouse.route_ids.filtered(lambda r: len(r.warehouse_ids) == 1).write({'active': vals['active']})
rule_ids.write({'active': vals['active']})
if warehouse.active:
# Catch all warehouse fields that trigger a modfication on
# routes, rules, picking types and locations (e.g the reception
# steps). The purpose is to write on it in order to let the
# write method set the correct field to active or archive.
depends = set([])
for rule_item in warehouse._get_global_route_rules_values().values():
for depend in rule_item.get('depends', []):
depends.add(depend)
for rule_item in warehouse._get_routes_values().values():
for depend in rule_item.get('depends', []):
depends.add(depend)
values = {'resupply_route_ids': [(4, route.id) for route in warehouse.resupply_route_ids]}
for depend in depends:
values.update({depend: warehouse[depend]})
warehouse.write(values)
if vals.get('resupply_wh_ids') and not vals.get('resupply_route_ids'):
for warehouse in warehouses:
to_add = new_resupply_whs - old_resupply_whs[warehouse.id]
to_remove = old_resupply_whs[warehouse.id] - new_resupply_whs
if to_add:
existing_route = Route.search([
('supplied_wh_id', '=', warehouse.id),
('supplier_wh_id', 'in', to_remove.ids),
('active', '=', False)
])
if existing_route:
existing_route.toggle_active()
else:
warehouse.create_resupply_routes(to_add)
if to_remove:
to_disable_route_ids = Route.search([
('supplied_wh_id', '=', warehouse.id),
('supplier_wh_id', 'in', to_remove.ids),
('active', '=', True)
])
to_disable_route_ids.toggle_active()
if 'active' in vals:
self._check_multiwarehouse_group()
return res
def unlink(self):
res = super().unlink()
self._check_multiwarehouse_group()
return res
def _check_multiwarehouse_group(self):
cnt_by_company = self.env['stock.warehouse'].sudo().read_group([('active', '=', True)], ['company_id'], groupby=['company_id'])
if cnt_by_company:
max_cnt = max(cnt_by_company, key=lambda k: k['company_id_count'])
group_user = self.env.ref('base.group_user')
group_stock_multi_warehouses = self.env.ref('stock.group_stock_multi_warehouses')
if max_cnt['company_id_count'] <= 1 and group_stock_multi_warehouses in group_user.implied_ids:
group_user.write({'implied_ids': [(3, group_stock_multi_warehouses.id)]})
group_stock_multi_warehouses.write({'users': [(3, user.id) for user in group_user.users]})
if max_cnt['company_id_count'] > 1 and group_stock_multi_warehouses not in group_user.implied_ids:
group_user.write({'implied_ids': [(4, group_stock_multi_warehouses.id), (4, self.env.ref('stock.group_stock_multi_locations').id)]})
@api.model
def _update_partner_data(self, partner_id, company_id):
if not partner_id:
return
ResCompany = self.env['res.company']
if company_id:
transit_loc = ResCompany.browse(company_id).internal_transit_location_id.id
self.env['res.partner'].browse(partner_id).with_company(company_id).write({'property_stock_customer': transit_loc, 'property_stock_supplier': transit_loc})
else:
transit_loc = self.env.company.internal_transit_location_id.id
self.env['res.partner'].browse(partner_id).write({'property_stock_customer': transit_loc, 'property_stock_supplier': transit_loc})
def _create_or_update_sequences_and_picking_types(self):
""" Create or update existing picking types for a warehouse.
Pikcing types are stored on the warehouse in a many2one. If the picking
type exist this method will update it. The update values can be found in
the method _get_picking_type_update_values. If the picking type does not
exist it will be created with a new sequence associated to it.
"""
self.ensure_one()
IrSequenceSudo = self.env['ir.sequence'].sudo()
PickingType = self.env['stock.picking.type']
# choose the next available color for the operation types of this warehouse
all_used_colors = [res['color'] for res in PickingType.search_read([('warehouse_id', '!=', False), ('color', '!=', False)], ['color'], order='color')]
available_colors = [zef for zef in range(0, 12) if zef not in all_used_colors]
color = available_colors[0] if available_colors else 0
warehouse_data = {}
sequence_data = self._get_sequence_values()
# suit for each warehouse: reception, internal, pick, pack, ship
max_sequence = self.env['stock.picking.type'].search_read([('sequence', '!=', False)], ['sequence'], limit=1, order='sequence desc')
max_sequence = max_sequence and max_sequence[0]['sequence'] or 0
data = self._get_picking_type_update_values()
create_data, max_sequence = self._get_picking_type_create_values(max_sequence)
for picking_type, values in data.items():
if self[picking_type]:
self[picking_type].update(values)
else:
data[picking_type].update(create_data[picking_type])
sequence = IrSequenceSudo.create(sequence_data[picking_type])
values.update(warehouse_id=self.id, color=color, sequence_id=sequence.id)
warehouse_data[picking_type] = PickingType.create(values).id
if 'out_type_id' in warehouse_data:
PickingType.browse(warehouse_data['out_type_id']).write({'return_picking_type_id': warehouse_data.get('return_type_id', False)})
if 'in_type_id' in warehouse_data:
PickingType.browse(warehouse_data['in_type_id']).write({'return_picking_type_id': warehouse_data.get('out_type_id', False)})
return warehouse_data
def _create_or_update_global_routes_rules(self):
""" Some rules are not specific to a warehouse(e.g MTO, Buy, ...)
however they contain rule(s) for a specific warehouse. This method will
update the rules contained in global routes in order to make them match
with the wanted reception, delivery,... steps.
"""
for rule_field, rule_details in self._get_global_route_rules_values().items():
values = rule_details.get('update_values', {})
if self[rule_field]:
self[rule_field].write(values)
else:
values.update(rule_details['create_values'])
values.update({'warehouse_id': self.id})
self[rule_field] = self.env['stock.rule'].create(values)
return True
def _find_global_route(self, xml_id, route_name):
""" return a route record set from an xml_id or its name. """
route = self.env.ref(xml_id, raise_if_not_found=False)
if not route:
route = self.env['stock.location.route'].search([('name', 'like', route_name)], limit=1)
if not route:
raise UserError(_('Can\'t find any generic route %s.') % (route_name))
return route
def _get_global_route_rules_values(self):
""" Method used by _create_or_update_global_routes_rules. It's
purpose is to return a dict with this format.
key: The rule contained in a global route that have to be create/update
entry a dict with the following values:
-depends: Field that impact the rule. When a field in depends is
write on the warehouse the rule set as key have to be update.
-create_values: values used in order to create the rule if it does
not exist.
-update_values: values used to update the route when a field in
depends is modify on the warehouse.
"""
# We use 0 since routing are order from stock to cust. If the routing
# order is modify, the mto rule will be wrong.
rule = self.get_rules_dict()[self.id][self.delivery_steps]
rule = [r for r in rule if r.from_loc == self.lot_stock_id][0]
location_id = rule.from_loc
location_dest_id = rule.dest_loc
picking_type_id = rule.picking_type
return {
'mto_pull_id': {
'depends': ['delivery_steps'],
'create_values': {
'active': True,
'procure_method': 'mts_else_mto',
'company_id': self.company_id.id,
'action': 'pull',
'auto': 'manual',
'propagate_carrier': True,
'route_id': self._find_global_route('stock.route_warehouse0_mto', _('Make To Order')).id
},
'update_values': {
'name': self._format_rulename(location_id, location_dest_id, 'MTO'),
'location_id': location_dest_id.id,
'location_src_id': location_id.id,
'picking_type_id': picking_type_id.id,
}
}
}
def _create_or_update_route(self):
""" Create or update the warehouse's routes.
_get_routes_values method return a dict with:
- route field name (e.g: crossdock_route_id).
- field that trigger an update on the route (key 'depends').
- routing_key used in order to find rules contained in the route.
- create values.
- update values when a field in depends is modified.
- rules default values.
This method do an iteration on each route returned and update/create
them. In order to update the rules contained in the route it will
use the get_rules_dict that return a dict:
- a receptions/delivery,... step value as key (e.g 'pick_ship')
- a list of routing object that represents the rules needed to
fullfil the pupose of the route.
The routing_key from _get_routes_values is match with the get_rules_dict
key in order to create/update the rules in the route
(_find_existing_rule_or_create method is responsible for this part).
"""
# Create routes and active/create their related rules.
routes = []
rules_dict = self.get_rules_dict()
for route_field, route_data in self._get_routes_values().items():
# If the route exists update it
if self[route_field]:
route = self[route_field]
if 'route_update_values' in route_data:
route.write(route_data['route_update_values'])
route.rule_ids.write({'active': False})
# Create the route
else:
if 'route_update_values' in route_data:
route_data['route_create_values'].update(route_data['route_update_values'])
route = self.env['stock.location.route'].create(route_data['route_create_values'])
self[route_field] = route
# Get rules needed for the route
routing_key = route_data.get('routing_key')
rules = rules_dict[self.id][routing_key]
if 'rules_values' in route_data:
route_data['rules_values'].update({'route_id': route.id})
else:
route_data['rules_values'] = {'route_id': route.id}
rules_list = self._get_rule_values(
rules, values=route_data['rules_values'])
# Create/Active rules
self._find_existing_rule_or_create(rules_list)
if route_data['route_create_values'].get('warehouse_selectable', False) or route_data['route_update_values'].get('warehouse_selectable', False):
routes.append(self[route_field])
return {
'route_ids': [(4, route.id) for route in routes],
}
def _get_routes_values(self):
""" Return information in order to update warehouse routes.
- The key is a route field sotred as a Many2one on the warehouse
- This key contains a dict with route values:
- routing_key: a key used in order to match rules from
get_rules_dict function. It would be usefull in order to generate
the route's rules.
- route_create_values: When the Many2one does not exist the route
is created based on values contained in this dict.
- route_update_values: When a field contained in 'depends' key is
modified and the Many2one exist on the warehouse, the route will be
update with the values contained in this dict.
- rules_values: values added to the routing in order to create the
route's rules.
"""
return {
'reception_route_id': {
'routing_key': self.reception_steps,
'depends': ['reception_steps'],
'route_update_values': {
'name': self._format_routename(route_type=self.reception_steps),
'active': self.active,
},
'route_create_values': {
'product_categ_selectable': True,
'warehouse_selectable': True,
'product_selectable': False,
'company_id': self.company_id.id,
'sequence': 9,
},
'rules_values': {
'active': True,
'propagate_cancel': True,
}
},
'delivery_route_id': {
'routing_key': self.delivery_steps,
'depends': ['delivery_steps'],
'route_update_values': {
'name': self._format_routename(route_type=self.delivery_steps),
'active': self.active,
},
'route_create_values': {
'product_categ_selectable': True,
'warehouse_selectable': True,
'product_selectable': False,
'company_id': self.company_id.id,
'sequence': 10,
},
'rules_values': {
'active': True,
'propagate_carrier': True
}
},
'crossdock_route_id': {
'routing_key': 'crossdock',
'depends': ['delivery_steps', 'reception_steps'],
'route_update_values': {
'name': self._format_routename(route_type='crossdock'),
'active': self.reception_steps != 'one_step' and self.delivery_steps != 'ship_only'
},
'route_create_values': {
'product_selectable': True,
'product_categ_selectable': True,
'active': self.delivery_steps != 'ship_only' and self.reception_steps != 'one_step',
'company_id': self.company_id.id,
'sequence': 20,
},
'rules_values': {
'active': True,
'procure_method': 'make_to_order'
}
}
}
def _get_receive_routes_values(self, installed_depends):
""" Return receive route values with 'procure_method': 'make_to_order'
in order to update warehouse routes.
This function has the same receive route values as _get_routes_values with the addition of
'procure_method': 'make_to_order' to the 'rules_values'. This is expected to be used by
modules that extend stock and add actions that can trigger receive 'make_to_order' rules (i.e.
we don't want any of the generated rules by get_rules_dict to default to 'make_to_stock').
Additionally this is expected to be used in conjunction with _get_receive_rules_dict().
args:
installed_depends - string value of installed (warehouse) boolean to trigger updating of reception route.
"""
return {
'reception_route_id': {
'routing_key': self.reception_steps,
'depends': ['reception_steps', installed_depends],
'route_update_values': {
'name': self._format_routename(route_type=self.reception_steps),
'active': self.active,
},
'route_create_values': {
'product_categ_selectable': True,
'warehouse_selectable': True,
'product_selectable': False,
'company_id': self.company_id.id,
'sequence': 9,
},
'rules_values': {
'active': True,
'propagate_cancel': True,
'procure_method': 'make_to_order',
}
}
}
def _find_existing_rule_or_create(self, rules_list):
""" This method will find existing rules or create new one. """
for rule_vals in rules_list:
existing_rule = self.env['stock.rule'].search([
('picking_type_id', '=', rule_vals['picking_type_id']),
('location_src_id', '=', rule_vals['location_src_id']),
('location_id', '=', rule_vals['location_id']),
('route_id', '=', rule_vals['route_id']),
('action', '=', rule_vals['action']),
('active', '=', False),
])
if not existing_rule:
self.env['stock.rule'].create(rule_vals)
else:
existing_rule.write({'active': True})
def _get_locations_values(self, vals, code=False):
""" Update the warehouse locations. """
def_values = self.default_get(['reception_steps', 'delivery_steps'])
reception_steps = vals.get('reception_steps', def_values['reception_steps'])
delivery_steps = vals.get('delivery_steps', def_values['delivery_steps'])
code = vals.get('code') or code or ''
code = code.replace(' ', '').upper()
company_id = vals.get('company_id', self.default_get(['company_id'])['company_id'])
sub_locations = {
'lot_stock_id': {
'name': _('Stock'),
'active': True,
'usage': 'internal',
'barcode': self._valid_barcode(code + '-STOCK', company_id)
},
'wh_input_stock_loc_id': {
'name': _('Input'),
'active': reception_steps != 'one_step',
'usage': 'internal',
'barcode': self._valid_barcode(code + '-INPUT', company_id)
},
'wh_qc_stock_loc_id': {
'name': _('Quality Control'),
'active': reception_steps == 'three_steps',
'usage': 'internal',
'barcode': self._valid_barcode(code + '-QUALITY', company_id)
},
'wh_output_stock_loc_id': {
'name': _('Output'),
'active': delivery_steps != 'ship_only',
'usage': 'internal',
'barcode': self._valid_barcode(code + '-OUTPUT', company_id)
},
'wh_pack_stock_loc_id': {
'name': _('Packing Zone'),
'active': delivery_steps == 'pick_pack_ship',
'usage': 'internal',
'barcode': self._valid_barcode(code + '-PACKING', company_id)
},
}
return sub_locations
def _valid_barcode(self, barcode, company_id):
location = self.env['stock.location'].with_context(active_test=False).search([
('barcode', '=', barcode),
('company_id', '=', company_id)
])
return not location and barcode
def _create_missing_locations(self, vals):
""" It could happen that the user delete a mandatory location or a
module with new locations was installed after some warehouses creation.
In this case, this function will create missing locations in order to
avoid mistakes during picking types and rules creation.
"""
for warehouse in self:
company_id = vals.get('company_id', warehouse.company_id.id)
sub_locations = warehouse._get_locations_values(dict(vals, company_id=company_id), warehouse.code)
missing_location = {}
for location, location_values in sub_locations.items():
if not warehouse[location] and location not in vals:
location_values['location_id'] = vals.get('view_location_id', warehouse.view_location_id.id)
location_values['company_id'] = company_id
missing_location[location] = self.env['stock.location'].create(location_values).id
if missing_location:
warehouse.write(missing_location)
def create_resupply_routes(self, supplier_warehouses):
Route = self.env['stock.location.route']
Rule = self.env['stock.rule']
input_location, output_location = self._get_input_output_locations(self.reception_steps, self.delivery_steps)
internal_transit_location, external_transit_location = self._get_transit_locations()
for supplier_wh in supplier_warehouses:
transit_location = internal_transit_location if supplier_wh.company_id == self.company_id else external_transit_location
if not transit_location:
continue
transit_location.active = True
output_location = supplier_wh.lot_stock_id if supplier_wh.delivery_steps == 'ship_only' else supplier_wh.wh_output_stock_loc_id
# Create extra MTO rule (only for 'ship only' because in the other cases MTO rules already exists)
if supplier_wh.delivery_steps == 'ship_only':
routing = [self.Routing(output_location, transit_location, supplier_wh.out_type_id, 'pull')]
mto_vals = supplier_wh._get_global_route_rules_values().get('mto_pull_id')
values = mto_vals['create_values']
mto_rule_val = supplier_wh._get_rule_values(routing, values, name_suffix='MTO')
Rule.create(mto_rule_val[0])
inter_wh_route = Route.create(self._get_inter_warehouse_route_values(supplier_wh))
pull_rules_list = supplier_wh._get_supply_pull_rules_values(
[self.Routing(output_location, transit_location, supplier_wh.out_type_id, 'pull')],
values={'route_id': inter_wh_route.id})
pull_rules_list += self._get_supply_pull_rules_values(
[self.Routing(transit_location, input_location, self.in_type_id, 'pull')],
values={'route_id': inter_wh_route.id, 'propagate_warehouse_id': supplier_wh.id})
for pull_rule_vals in pull_rules_list:
Rule.create(pull_rule_vals)
# Routing tools
# ------------------------------------------------------------
def _get_input_output_locations(self, reception_steps, delivery_steps):
return (self.lot_stock_id if reception_steps == 'one_step' else self.wh_input_stock_loc_id,
self.lot_stock_id if delivery_steps == 'ship_only' else self.wh_output_stock_loc_id)
def _get_transit_locations(self):
return self.company_id.internal_transit_location_id, self.env.ref('stock.stock_location_inter_wh', raise_if_not_found=False) or self.env['stock.location']
@api.model
def _get_partner_locations(self):
''' returns a tuple made of the browse record of customer location and the browse record of supplier location'''
Location = self.env['stock.location']
customer_loc = self.env.ref('stock.stock_location_customers', raise_if_not_found=False)
supplier_loc = self.env.ref('stock.stock_location_suppliers', raise_if_not_found=False)
if not customer_loc:
customer_loc = Location.search([('usage', '=', 'customer')], limit=1)
if not supplier_loc:
supplier_loc = Location.search([('usage', '=', 'supplier')], limit=1)
if not customer_loc and not supplier_loc:
raise UserError(_('Can\'t find any customer or supplier location.'))
return customer_loc, supplier_loc
def _get_route_name(self, route_type):
return str(ROUTE_NAMES[route_type])
def get_rules_dict(self):
""" Define the rules source/destination locations, picking_type and
action needed for each warehouse route configuration.
"""
customer_loc, supplier_loc = self._get_partner_locations()
return {
warehouse.id: {
'one_step': [self.Routing(supplier_loc, warehouse.lot_stock_id, warehouse.in_type_id, 'pull')],
'two_steps': [
self.Routing(supplier_loc, warehouse.wh_input_stock_loc_id, warehouse.in_type_id, 'pull'),
self.Routing(warehouse.wh_input_stock_loc_id, warehouse.lot_stock_id, warehouse.int_type_id, 'pull_push')],
'three_steps': [
self.Routing(supplier_loc, warehouse.wh_input_stock_loc_id, warehouse.in_type_id, 'pull'),
self.Routing(warehouse.wh_input_stock_loc_id, warehouse.wh_qc_stock_loc_id, warehouse.int_type_id, 'pull_push'),
self.Routing(warehouse.wh_qc_stock_loc_id, warehouse.lot_stock_id, warehouse.int_type_id, 'pull_push')],
'crossdock': [
self.Routing(warehouse.wh_input_stock_loc_id, warehouse.wh_output_stock_loc_id, warehouse.int_type_id, 'pull'),
self.Routing(warehouse.wh_output_stock_loc_id, customer_loc, warehouse.out_type_id, 'pull')],
'ship_only': [self.Routing(warehouse.lot_stock_id, customer_loc, warehouse.out_type_id, 'pull')],
'pick_ship': [
self.Routing(warehouse.lot_stock_id, warehouse.wh_output_stock_loc_id, warehouse.pick_type_id, 'pull'),
self.Routing(warehouse.wh_output_stock_loc_id, customer_loc, warehouse.out_type_id, 'pull')],
'pick_pack_ship': [
self.Routing(warehouse.lot_stock_id, warehouse.wh_pack_stock_loc_id, warehouse.pick_type_id, 'pull'),
self.Routing(warehouse.wh_pack_stock_loc_id, warehouse.wh_output_stock_loc_id, warehouse.pack_type_id, 'pull'),
self.Routing(warehouse.wh_output_stock_loc_id, customer_loc, warehouse.out_type_id, 'pull')],
'company_id': warehouse.company_id.id,
} for warehouse in self
}
def _get_receive_rules_dict(self):
""" Return receive route rules without initial pull rule in order to update warehouse routes.
This function has the same receive route rules as get_rules_dict without an initial pull rule.
This is expected to be used by modules that extend stock and add actions that can trigger receive
'make_to_order' rules (i.e. we don't expect the receive route to be able to pull on its own anymore).
This is also expected to be used in conjuction with _get_receive_routes_values()
"""
return {
'one_step': [],
'two_steps': [self.Routing(self.wh_input_stock_loc_id, self.lot_stock_id, self.int_type_id, 'pull_push')],
'three_steps': [
self.Routing(self.wh_input_stock_loc_id, self.wh_qc_stock_loc_id, self.int_type_id, 'pull_push'),
self.Routing(self.wh_qc_stock_loc_id, self.lot_stock_id, self.int_type_id, 'pull_push')],
}
def _get_inter_warehouse_route_values(self, supplier_warehouse):
return {
'name': _('%(warehouse)s: Supply Product from %(supplier)s', warehouse=self.name, supplier=supplier_warehouse.name),
'warehouse_selectable': True,
'product_selectable': True,
'product_categ_selectable': True,
'supplied_wh_id': self.id,
'supplier_wh_id': supplier_warehouse.id,
'company_id': self.company_id.id,
}
# Pull / Push tools
# ------------------------------------------------------------
def _get_rule_values(self, route_values, values=None, name_suffix=''):
first_rule = True
rules_list = []
for routing in route_values:
route_rule_values = {
'name': self._format_rulename(routing.from_loc, routing.dest_loc, name_suffix),
'location_src_id': routing.from_loc.id,
'location_id': routing.dest_loc.id,
'action': routing.action,
'auto': 'manual',
'picking_type_id': routing.picking_type.id,
'procure_method': first_rule and 'make_to_stock' or 'make_to_order',
'warehouse_id': self.id,
'company_id': self.company_id.id,
}
route_rule_values.update(values or {})
rules_list.append(route_rule_values)
first_rule = False
if values and values.get('propagate_cancel') and rules_list:
# In case of rules chain with cancel propagation set, we need to stop
# the cancellation for the last step in order to avoid cancelling
# any other move after the chain.
# Example: In the following flow:
# Input -> Quality check -> Stock -> Customer
# We want that cancelling I->GC cancel QC -> S but not S -> C
# which means:
# Input -> Quality check should have propagate_cancel = True
# Quality check -> Stock should have propagate_cancel = False
rules_list[-1]['propagate_cancel'] = False
return rules_list
def _get_supply_pull_rules_values(self, route_values, values=None):
pull_values = {}
pull_values.update(values)
pull_values.update({'active': True})
rules_list = self._get_rule_values(route_values, values=pull_values)
for pull_rules in rules_list:
pull_rules['procure_method'] = self.lot_stock_id.id != pull_rules['location_src_id'] and 'make_to_order' or 'make_to_stock' # first part of the resuply route is MTS
return rules_list
def _update_reception_delivery_resupply(self, reception_new, delivery_new):
""" Check if we need to change something to resupply warehouses and associated MTO rules """
for warehouse in self:
input_loc, output_loc = warehouse._get_input_output_locations(reception_new, delivery_new)
if reception_new and warehouse.reception_steps != reception_new and (warehouse.reception_steps == 'one_step' or reception_new == 'one_step'):
warehouse._check_reception_resupply(input_loc)
if delivery_new and warehouse.delivery_steps != delivery_new and (warehouse.delivery_steps == 'ship_only' or delivery_new == 'ship_only'):
change_to_multiple = warehouse.delivery_steps == 'ship_only'
warehouse._check_delivery_resupply(output_loc, change_to_multiple)
def _check_delivery_resupply(self, new_location, change_to_multiple):
""" Check if the resupply routes from this warehouse follow the changes of number of delivery steps
Check routes being delivery bu this warehouse and change the rule going to transit location """
Rule = self.env["stock.rule"]
routes = self.env['stock.location.route'].search([('supplier_wh_id', '=', self.id)])
rules = Rule.search(['&', '&', ('route_id', 'in', routes.ids), ('action', '!=', 'push'), ('location_id.usage', '=', 'transit')])
rules.write({
'location_src_id': new_location.id,
'procure_method': change_to_multiple and "make_to_order" or "make_to_stock"})
if not change_to_multiple:
# If single delivery we should create the necessary MTO rules for the resupply
routings = [self.Routing(self.lot_stock_id, location, self.out_type_id, 'pull') for location in rules.mapped('location_id')]
mto_vals = self._get_global_route_rules_values().get('mto_pull_id')
values = mto_vals['create_values']
mto_rule_vals = self._get_rule_values(routings, values, name_suffix='MTO')
for mto_rule_val in mto_rule_vals:
Rule.create(mto_rule_val)
else:
# We need to delete all the MTO stock rules, otherwise they risk to be used in the system
Rule.search([
'&', ('route_id', '=', self._find_global_route('stock.route_warehouse0_mto', _('Make To Order')).id),
('location_id.usage', '=', 'transit'),
('action', '!=', 'push'),
('location_src_id', '=', self.lot_stock_id.id)]).write({'active': False})
def _check_reception_resupply(self, new_location):
""" Check routes being delivered by the warehouses (resupply routes) and
change their rule coming from the transit location """
routes = self.env['stock.location.route'].search([('supplied_wh_id', 'in', self.ids)])
self.env['stock.rule'].search([
'&',
('route_id', 'in', routes.ids),
'&',
('action', '!=', 'push'),
('location_src_id.usage', '=', 'transit')
]).write({'location_id': new_location.id})
def _update_name_and_code(self, new_name=False, new_code=False):
if new_code:
self.mapped('lot_stock_id').mapped('location_id').write({'name': new_code})
if new_name:
# TDE FIXME: replacing the route name ? not better to re-generate the route naming ?
for warehouse in self:
routes = warehouse.route_ids
for route in routes:
route.write({'name': route.name.replace(warehouse.name, new_name, 1)})
for pull in route.rule_ids:
pull.write({'name': pull.name.replace(warehouse.name, new_name, 1)})
if warehouse.mto_pull_id:
warehouse.mto_pull_id.write({'name': warehouse.mto_pull_id.name.replace(warehouse.name, new_name, 1)})
for warehouse in self:
sequence_data = warehouse._get_sequence_values()
# `ir.sequence` write access is limited to system user
if self.user_has_groups('stock.group_stock_manager'):
warehouse = warehouse.sudo()
warehouse.in_type_id.sequence_id.write(sequence_data['in_type_id'])
warehouse.out_type_id.sequence_id.write(sequence_data['out_type_id'])
warehouse.pack_type_id.sequence_id.write(sequence_data['pack_type_id'])
warehouse.pick_type_id.sequence_id.write(sequence_data['pick_type_id'])
warehouse.int_type_id.sequence_id.write(sequence_data['int_type_id'])
def _update_location_reception(self, new_reception_step):
self.mapped('wh_qc_stock_loc_id').write({'active': new_reception_step == 'three_steps'})
self.mapped('wh_input_stock_loc_id').write({'active': new_reception_step != 'one_step'})
def _update_location_delivery(self, new_delivery_step):
self.mapped('wh_pack_stock_loc_id').write({'active': new_delivery_step == 'pick_pack_ship'})
self.mapped('wh_output_stock_loc_id').write({'active': new_delivery_step != 'ship_only'})
# Misc
# ------------------------------------------------------------
def _get_picking_type_update_values(self):
""" Return values in order to update the existing picking type when the
warehouse's delivery_steps or reception_steps are modify.
"""
input_loc, output_loc = self._get_input_output_locations(self.reception_steps, self.delivery_steps)
return {
'in_type_id': {
'default_location_dest_id': input_loc.id,
'barcode': self.code.replace(" ", "").upper() + "-RECEIPTS",
},
'out_type_id': {
'default_location_src_id': output_loc.id,
'barcode': self.code.replace(" ", "").upper() + "-DELIVERY",
},
'pick_type_id': {
'active': self.delivery_steps != 'ship_only' and self.active,
'default_location_dest_id': output_loc.id if self.delivery_steps == 'pick_ship' else self.wh_pack_stock_loc_id.id,
'barcode': self.code.replace(" ", "").upper() + "-PICK",
},
'pack_type_id': {
'active': self.delivery_steps == 'pick_pack_ship' and self.active,
'barcode': self.code.replace(" ", "").upper() + "-PACK",
},
'int_type_id': {
'barcode': self.code.replace(" ", "").upper() + "-INTERNAL",
},
'return_type_id': {
'default_location_dest_id': output_loc.id,
'barcode': self.code.replace(" ", "").upper() + "-RETURNS",
},
}
def _get_picking_type_create_values(self, max_sequence):
""" When a warehouse is created this method return the values needed in
order to create the new picking types for this warehouse. Every picking
type are created at the same time than the warehouse howver they are
activated or archived depending the delivery_steps or reception_steps.
"""
input_loc, output_loc = self._get_input_output_locations(self.reception_steps, self.delivery_steps)
return {
'in_type_id': {
'name': _('Receipts'),
'code': 'incoming',
'use_create_lots': True,
'use_existing_lots': False,
'default_location_src_id': False,
'sequence': max_sequence + 1,
'show_reserved': False,
'show_operations': False,
'sequence_code': 'IN',
'company_id': self.company_id.id,
}, 'out_type_id': {
'name': _('Delivery Orders'),
'code': 'outgoing',
'use_create_lots': False,
'use_existing_lots': True,
'default_location_dest_id': False,
'sequence': max_sequence + 5,
'sequence_code': 'OUT',
'print_label': True,
'company_id': self.company_id.id,
}, 'pack_type_id': {
'name': _('Pack'),
'code': 'internal',
'use_create_lots': False,
'use_existing_lots': True,
'default_location_src_id': self.wh_pack_stock_loc_id.id,
'default_location_dest_id': output_loc.id,
'sequence': max_sequence + 4,
'sequence_code': 'PACK',
'company_id': self.company_id.id,
}, 'pick_type_id': {
'name': _('Pick'),
'code': 'internal',
'use_create_lots': False,
'use_existing_lots': True,
'default_location_src_id': self.lot_stock_id.id,
'sequence': max_sequence + 3,
'sequence_code': 'PICK',
'company_id': self.company_id.id,
}, 'int_type_id': {
'name': _('Internal Transfers'),
'code': 'internal',
'use_create_lots': False,
'use_existing_lots': True,
'default_location_src_id': self.lot_stock_id.id,
'default_location_dest_id': self.lot_stock_id.id,
'active': self.reception_steps != 'one_step' or self.delivery_steps != 'ship_only' or self.user_has_groups('stock.group_stock_multi_locations'),
'sequence': max_sequence + 2,
'sequence_code': 'INT',
'company_id': self.company_id.id,
}, 'return_type_id': {
'name': _('Returns'),
'code': 'incoming',
'use_create_lots': False,
'use_existing_lots': True,
'default_location_src_id': False,
'sequence': max_sequence + 6,
'show_reserved': True,
'sequence_code': 'IN',
'company_id': self.company_id.id,
},
}, max_sequence + 6
def _get_sequence_values(self):
""" Each picking type is created with a sequence. This method returns
the sequence values associated to each picking type.
"""
return {
'in_type_id': {
'name': self.name + ' ' + _('Sequence in'),
'prefix': self.code + '/IN/', 'padding': 5,
'company_id': self.company_id.id,
},
'out_type_id': {
'name': self.name + ' ' + _('Sequence out'),
'prefix': self.code + '/OUT/', 'padding': 5,
'company_id': self.company_id.id,
},
'pack_type_id': {
'name': self.name + ' ' + _('Sequence packing'),
'prefix': self.code + '/PACK/', 'padding': 5,
'company_id': self.company_id.id,
},
'pick_type_id': {
'name': self.name + ' ' + _('Sequence picking'),
'prefix': self.code + '/PICK/', 'padding': 5,
'company_id': self.company_id.id,
},
'int_type_id': {
'name': self.name + ' ' + _('Sequence internal'),
'prefix': self.code + '/INT/', 'padding': 5,
'company_id': self.company_id.id,
},
'return_type_id': {
'name': self.name + ' ' + _('Sequence return'),
'prefix': self.code + '/RET/', 'padding': 5,
'company_id': self.company_id.id,
},
}
def _format_rulename(self, from_loc, dest_loc, suffix):
rulename = '%s: %s' % (self.code, from_loc.name)
if dest_loc:
rulename += ' → %s' % (dest_loc.name)
if suffix:
rulename += ' (' + suffix + ')'
return rulename
def _format_routename(self, name=None, route_type=None):
if route_type:
name = self._get_route_name(route_type)
return '%s: %s' % (self.name, name)
@api.returns('self')
def _get_all_routes(self):
routes = self.mapped('route_ids') | self.mapped('mto_pull_id').mapped('route_id')
routes |= self.env["stock.location.route"].search([('supplied_wh_id', 'in', self.ids)])
return routes
def action_view_all_routes(self):
routes = self._get_all_routes()
return {
'name': _('Warehouse\'s Routes'),
'domain': [('id', 'in', routes.ids)],
'res_model': 'stock.location.route',
'type': 'ir.actions.act_window',
'view_id': False,
'view_mode': 'tree,form',
'limit': 20,
'context': dict(self._context, default_warehouse_selectable=True, default_warehouse_ids=self.ids)
}
| 53.073901
| 56,736
|
4,043
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, api, fields, models
class StorageCategory(models.Model):
_name = 'stock.storage.category'
_description = "Storage Category"
_order = "name"
name = fields.Char('Storage Category', required=True)
max_weight = fields.Float('Max Weight', digits='Stock Weight')
capacity_ids = fields.One2many('stock.storage.category.capacity', 'storage_category_id', copy=True)
product_capacity_ids = fields.One2many('stock.storage.category.capacity', compute="_compute_storage_capacity_ids", inverse="_set_storage_capacity_ids")
package_capacity_ids = fields.One2many('stock.storage.category.capacity', compute="_compute_storage_capacity_ids", inverse="_set_storage_capacity_ids")
allow_new_product = fields.Selection([
('empty', 'If the location is empty'),
('same', 'If all products are same'),
('mixed', 'Allow mixed products')], default='mixed', required=True)
location_ids = fields.One2many('stock.location', 'storage_category_id')
company_id = fields.Many2one('res.company', 'Company')
weight_uom_name = fields.Char(string='Weight unit', compute='_compute_weight_uom_name')
_sql_constraints = [
('positive_max_weight', 'CHECK(max_weight >= 0)', 'Max weight should be a positive number.'),
]
@api.depends('capacity_ids')
def _compute_storage_capacity_ids(self):
for storage_category in self:
storage_category.product_capacity_ids = storage_category.capacity_ids.filtered(lambda c: c.product_id)
storage_category.package_capacity_ids = storage_category.capacity_ids.filtered(lambda c: c.package_type_id)
def _compute_weight_uom_name(self):
self.weight_uom_name = self.env['product.template']._get_weight_uom_name_from_ir_config_parameter()
def _set_storage_capacity_ids(self):
for storage_category in self:
storage_category.capacity_ids = storage_category.product_capacity_ids | storage_category.package_capacity_ids
def copy(self, default=None):
default = dict(default or {})
default.update(name=_("%s (copy)") % self.name)
return super().copy(default)
class StorageCategoryProductCapacity(models.Model):
_name = 'stock.storage.category.capacity'
_description = "Storage Category Capacity"
_check_company_auto = True
_order = "storage_category_id"
@api.model
def _domain_product_id(self):
domain = "('type', '=', 'product')"
if self.env.context.get('active_model') == 'product.template':
product_template_id = self.env.context.get('active_id', False)
domain = f"('product_tmpl_id', '=', {product_template_id})"
elif self.env.context.get('default_product_id', False):
product_id = self.env.context.get('default_product_id', False)
domain = f"('id', '=', {product_id})"
return f"[{domain}, '|', ('company_id', '=', False), ('company_id', '=', company_id)]"
storage_category_id = fields.Many2one('stock.storage.category', ondelete='cascade', required=True, index=True)
product_id = fields.Many2one('product.product', 'Product', domain=lambda self: self._domain_product_id(), ondelete='cascade', check_company=True)
package_type_id = fields.Many2one('stock.package.type', 'Package Type', ondelete='cascade', check_company=True)
quantity = fields.Float('Quantity', required=True)
product_uom_id = fields.Many2one(related='product_id.uom_id')
company_id = fields.Many2one('res.company', 'Company', related="storage_category_id.company_id")
_sql_constraints = [
('positive_quantity', 'CHECK(quantity > 0)', 'Quantity should be a positive number.'),
('unique_product', 'UNIQUE(product_id, storage_category_id)', 'Multiple capacity rules for one product.'),
('unique_package_type', 'UNIQUE(package_type_id, storage_category_id)', 'Multiple capacity rules for one package type.'),
]
| 53.197368
| 4,043
|
10,473
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, api, fields, models
from odoo.exceptions import UserError
from odoo.tools import float_compare
class StockScrap(models.Model):
_name = 'stock.scrap'
_inherit = ['mail.thread']
_order = 'id desc'
_description = 'Scrap'
def _get_default_scrap_location_id(self):
company_id = self.env.context.get('default_company_id') or self.env.company.id
return self.env['stock.location'].search([('scrap_location', '=', True), ('company_id', 'in', [company_id, False])], limit=1).id
def _get_default_location_id(self):
company_id = self.env.context.get('default_company_id') or self.env.company.id
warehouse = self.env['stock.warehouse'].search([('company_id', '=', company_id)], limit=1)
if warehouse:
return warehouse.lot_stock_id.id
return None
name = fields.Char(
'Reference', default=lambda self: _('New'),
copy=False, readonly=True, required=True,
states={'done': [('readonly', True)]})
company_id = fields.Many2one('res.company', string='Company', default=lambda self: self.env.company, required=True, states={'done': [('readonly', True)]})
origin = fields.Char(string='Source Document')
product_id = fields.Many2one(
'product.product', 'Product', domain="[('type', 'in', ['product', 'consu']), '|', ('company_id', '=', False), ('company_id', '=', company_id)]",
required=True, states={'done': [('readonly', True)]}, check_company=True)
product_uom_id = fields.Many2one(
'uom.uom', 'Unit of Measure',
required=True, states={'done': [('readonly', True)]}, domain="[('category_id', '=', product_uom_category_id)]")
product_uom_category_id = fields.Many2one(related='product_id.uom_id.category_id')
tracking = fields.Selection(string='Product Tracking', readonly=True, related="product_id.tracking")
lot_id = fields.Many2one(
'stock.production.lot', 'Lot/Serial',
states={'done': [('readonly', True)]}, domain="[('product_id', '=', product_id), ('company_id', '=', company_id)]", check_company=True)
package_id = fields.Many2one(
'stock.quant.package', 'Package',
states={'done': [('readonly', True)]}, check_company=True)
owner_id = fields.Many2one('res.partner', 'Owner', states={'done': [('readonly', True)]}, check_company=True)
move_id = fields.Many2one('stock.move', 'Scrap Move', readonly=True, check_company=True, copy=False)
picking_id = fields.Many2one('stock.picking', 'Picking', states={'done': [('readonly', True)]}, check_company=True)
location_id = fields.Many2one(
'stock.location', 'Source Location', domain="[('usage', '=', 'internal'), ('company_id', 'in', [company_id, False])]",
required=True, states={'done': [('readonly', True)]}, default=_get_default_location_id, check_company=True)
scrap_location_id = fields.Many2one(
'stock.location', 'Scrap Location', default=_get_default_scrap_location_id,
domain="[('scrap_location', '=', True), ('company_id', 'in', [company_id, False])]", required=True, states={'done': [('readonly', True)]}, check_company=True)
scrap_qty = fields.Float('Quantity', default=1.0, required=True, states={'done': [('readonly', True)]}, digits='Product Unit of Measure')
state = fields.Selection([
('draft', 'Draft'),
('done', 'Done')],
string='Status', default="draft", readonly=True, tracking=True)
date_done = fields.Datetime('Date', readonly=True)
@api.onchange('picking_id')
def _onchange_picking_id(self):
if self.picking_id:
self.location_id = (self.picking_id.state == 'done') and self.picking_id.location_dest_id.id or self.picking_id.location_id.id
@api.onchange('product_id')
def _onchange_product_id(self):
if self.product_id:
if self.tracking == 'serial':
self.scrap_qty = 1
self.product_uom_id = self.product_id.uom_id.id
# Check if we can get a more precise location instead of
# the default location (a location corresponding to where the
# reserved product is stored)
if self.picking_id:
for move_line in self.picking_id.move_line_ids:
if move_line.product_id == self.product_id:
self.location_id = move_line.location_id if move_line.state != 'done' else move_line.location_dest_id
break
@api.onchange('company_id')
def _onchange_company_id(self):
if self.company_id:
warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.company_id.id)], limit=1)
# Change the locations only if their company doesn't match the company set, otherwise
# user defaults are overridden.
if self.location_id.company_id != self.company_id:
self.location_id = warehouse.lot_stock_id
if self.scrap_location_id.company_id != self.company_id:
self.scrap_location_id = self.env['stock.location'].search([
('scrap_location', '=', True),
('company_id', 'in', [self.company_id.id, False]),
], limit=1)
else:
self.location_id = False
self.scrap_location_id = False
@api.onchange('lot_id')
def _onchange_serial_number(self):
if self.product_id.tracking == 'serial' and self.lot_id:
message, recommended_location = self.env['stock.quant']._check_serial_number(self.product_id,
self.lot_id,
self.company_id,
self.location_id,
self.picking_id.location_dest_id)
if message:
if recommended_location:
self.location_id = recommended_location
return {'warning': {'title': _('Warning'), 'message': message}}
@api.ondelete(at_uninstall=False)
def _unlink_except_done(self):
if 'done' in self.mapped('state'):
raise UserError(_('You cannot delete a scrap which is done.'))
def _prepare_move_values(self):
self.ensure_one()
return {
'name': self.name,
'origin': self.origin or self.picking_id.name or self.name,
'company_id': self.company_id.id,
'product_id': self.product_id.id,
'product_uom': self.product_uom_id.id,
'state': 'draft',
'product_uom_qty': self.scrap_qty,
'location_id': self.location_id.id,
'scrapped': True,
'location_dest_id': self.scrap_location_id.id,
'move_line_ids': [(0, 0, {'product_id': self.product_id.id,
'product_uom_id': self.product_uom_id.id,
'qty_done': self.scrap_qty,
'location_id': self.location_id.id,
'location_dest_id': self.scrap_location_id.id,
'package_id': self.package_id.id,
'owner_id': self.owner_id.id,
'lot_id': self.lot_id.id, })],
# 'restrict_partner_id': self.owner_id.id,
'picking_id': self.picking_id.id
}
def do_scrap(self):
self._check_company()
for scrap in self:
scrap.name = self.env['ir.sequence'].next_by_code('stock.scrap') or _('New')
move = self.env['stock.move'].create(scrap._prepare_move_values())
# master: replace context by cancel_backorder
move.with_context(is_scrap=True)._action_done()
scrap.write({'move_id': move.id, 'state': 'done'})
scrap.date_done = fields.Datetime.now()
return True
def action_get_stock_picking(self):
action = self.env['ir.actions.act_window']._for_xml_id('stock.action_picking_tree_all')
action['domain'] = [('id', '=', self.picking_id.id)]
return action
def action_get_stock_move_lines(self):
action = self.env['ir.actions.act_window']._for_xml_id('stock.stock_move_line_action')
action['domain'] = [('move_id', '=', self.move_id.id)]
return action
def action_validate(self):
self.ensure_one()
if self.product_id.type != 'product':
return self.do_scrap()
precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')
available_qty = sum(self.env['stock.quant']._gather(self.product_id,
self.location_id,
self.lot_id,
self.package_id,
self.owner_id,
strict=True).mapped('quantity'))
scrap_qty = self.product_uom_id._compute_quantity(self.scrap_qty, self.product_id.uom_id)
if float_compare(available_qty, scrap_qty, precision_digits=precision) >= 0:
return self.do_scrap()
else:
ctx = dict(self.env.context)
ctx.update({
'default_product_id': self.product_id.id,
'default_location_id': self.location_id.id,
'default_scrap_id': self.id,
'default_quantity': scrap_qty,
'default_product_uom_name': self.product_id.uom_name
})
return {
'name': self.product_id.display_name + _(': Insufficient Quantity To Scrap'),
'view_mode': 'form',
'res_model': 'stock.warn.insufficient.qty.scrap',
'view_id': self.env.ref('stock.stock_warn_insufficient_qty_scrap_form_view').id,
'type': 'ir.actions.act_window',
'context': ctx,
'target': 'new'
}
| 53.984536
| 10,473
|
52,515
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import Counter, defaultdict
from odoo import _, api, fields, tools, models
from odoo.exceptions import UserError, ValidationError
from odoo.tools import OrderedSet, groupby
from odoo.tools.float_utils import float_compare, float_is_zero, float_round
from odoo.addons.base.models.ir_model import MODULE_UNINSTALL_FLAG
class StockMoveLine(models.Model):
_name = "stock.move.line"
_description = "Product Moves (Stock Move Line)"
_rec_name = "product_id"
_order = "result_package_id desc, location_id asc, location_dest_id asc, picking_id asc, id"
picking_id = fields.Many2one(
'stock.picking', 'Transfer', auto_join=True,
check_company=True,
index=True,
help='The stock operation where the packing has been made')
move_id = fields.Many2one(
'stock.move', 'Stock Move',
check_company=True,
help="Change to a better name", index=True)
company_id = fields.Many2one('res.company', string='Company', readonly=True, required=True, index=True)
product_id = fields.Many2one('product.product', 'Product', ondelete="cascade", check_company=True, domain="[('type', '!=', 'service'), '|', ('company_id', '=', False), ('company_id', '=', company_id)]", index=True)
product_uom_id = fields.Many2one('uom.uom', 'Unit of Measure', required=True, domain="[('category_id', '=', product_uom_category_id)]")
product_uom_category_id = fields.Many2one(related='product_id.uom_id.category_id')
product_qty = fields.Float(
'Real Reserved Quantity', digits=0, copy=False,
compute='_compute_product_qty', inverse='_set_product_qty', store=True)
product_uom_qty = fields.Float(
'Reserved', default=0.0, digits='Product Unit of Measure', required=True, copy=False)
qty_done = fields.Float('Done', default=0.0, digits='Product Unit of Measure', copy=False)
package_id = fields.Many2one(
'stock.quant.package', 'Source Package', ondelete='restrict',
check_company=True,
domain="[('location_id', '=', location_id)]")
package_level_id = fields.Many2one('stock.package_level', 'Package Level', check_company=True)
lot_id = fields.Many2one(
'stock.production.lot', 'Lot/Serial Number',
domain="[('product_id', '=', product_id), ('company_id', '=', company_id)]", check_company=True)
lot_name = fields.Char('Lot/Serial Number Name')
result_package_id = fields.Many2one(
'stock.quant.package', 'Destination Package',
ondelete='restrict', required=False, check_company=True,
domain="['|', '|', ('location_id', '=', False), ('location_id', '=', location_dest_id), ('id', '=', package_id)]",
help="If set, the operations are packed into this package")
date = fields.Datetime('Date', default=fields.Datetime.now, required=True)
owner_id = fields.Many2one(
'res.partner', 'From Owner',
check_company=True,
help="When validating the transfer, the products will be taken from this owner.")
location_id = fields.Many2one('stock.location', 'From', domain="[('usage', '!=', 'view')]", check_company=True, required=True)
location_dest_id = fields.Many2one('stock.location', 'To', domain="[('usage', '!=', 'view')]", check_company=True, required=True)
lots_visible = fields.Boolean(compute='_compute_lots_visible')
picking_partner_id = fields.Many2one(related='picking_id.partner_id', readonly=True)
picking_code = fields.Selection(related='picking_id.picking_type_id.code', readonly=True)
picking_type_id = fields.Many2one(
'stock.picking.type', 'Operation type', compute='_compute_picking_type_id', search='_search_picking_type_id')
picking_type_use_create_lots = fields.Boolean(related='picking_id.picking_type_id.use_create_lots', readonly=True)
picking_type_use_existing_lots = fields.Boolean(related='picking_id.picking_type_id.use_existing_lots', readonly=True)
picking_type_entire_packs = fields.Boolean(related='picking_id.picking_type_id.show_entire_packs', readonly=True)
state = fields.Selection(related='move_id.state', store=True, related_sudo=False)
is_initial_demand_editable = fields.Boolean(related='move_id.is_initial_demand_editable')
is_inventory = fields.Boolean(related='move_id.is_inventory')
is_locked = fields.Boolean(related='move_id.is_locked', readonly=True)
consume_line_ids = fields.Many2many('stock.move.line', 'stock_move_line_consume_rel', 'consume_line_id', 'produce_line_id', help="Technical link to see who consumed what. ")
produce_line_ids = fields.Many2many('stock.move.line', 'stock_move_line_consume_rel', 'produce_line_id', 'consume_line_id', help="Technical link to see which line was produced with this. ")
reference = fields.Char(related='move_id.reference', store=True, related_sudo=False, readonly=False)
tracking = fields.Selection(related='product_id.tracking', readonly=True)
origin = fields.Char(related='move_id.origin', string='Source')
description_picking = fields.Text(string="Description picking")
@api.depends('picking_id.picking_type_id', 'product_id.tracking')
def _compute_lots_visible(self):
for line in self:
picking = line.picking_id
if picking.picking_type_id and line.product_id.tracking != 'none': # TDE FIXME: not sure correctly migrated
line.lots_visible = picking.picking_type_id.use_existing_lots or picking.picking_type_id.use_create_lots
else:
line.lots_visible = line.product_id.tracking != 'none'
@api.depends('picking_id')
def _compute_picking_type_id(self):
self.picking_type_id = False
for line in self:
if line.picking_id:
line.picking_type_id = line.picking_id.picking_type_id
def _search_picking_type_id(self, operator, value):
return [('picking_id.picking_type_id', operator, value)]
@api.depends('product_id', 'product_uom_id', 'product_uom_qty')
def _compute_product_qty(self):
for line in self:
line.product_qty = line.product_uom_id._compute_quantity(line.product_uom_qty, line.product_id.uom_id, rounding_method='HALF-UP')
def _set_product_qty(self):
""" The meaning of product_qty field changed lately and is now a functional field computing the quantity
in the default product UoM. This code has been added to raise an error if a write is made given a value
for `product_qty`, where the same write should set the `product_uom_qty` field instead, in order to
detect errors. """
raise UserError(_('The requested operation cannot be processed because of a programming error setting the `product_qty` field instead of the `product_uom_qty`.'))
@api.constrains('lot_id', 'product_id')
def _check_lot_product(self):
for line in self:
if line.lot_id and line.product_id != line.lot_id.sudo().product_id:
raise ValidationError(_(
'This lot %(lot_name)s is incompatible with this product %(product_name)s',
lot_name=line.lot_id.name,
product_name=line.product_id.display_name
))
@api.constrains('product_uom_qty')
def _check_reserved_done_quantity(self):
for move_line in self:
if move_line.state == 'done' and not float_is_zero(move_line.product_uom_qty, precision_digits=self.env['decimal.precision'].precision_get('Product Unit of Measure')):
raise ValidationError(_('A done move line should never have a reserved quantity.'))
@api.constrains('qty_done')
def _check_positive_qty_done(self):
if any(ml.qty_done < 0 for ml in self):
raise ValidationError(_('You can not enter negative quantities.'))
@api.onchange('product_id', 'product_uom_id')
def _onchange_product_id(self):
if self.product_id:
if self.picking_id:
product = self.product_id.with_context(lang=self.picking_id.partner_id.lang or self.env.user.lang)
self.description_picking = product._get_description(self.picking_id.picking_type_id)
self.lots_visible = self.product_id.tracking != 'none'
if not self.product_uom_id or self.product_uom_id.category_id != self.product_id.uom_id.category_id:
if self.move_id.product_uom:
self.product_uom_id = self.move_id.product_uom.id
else:
self.product_uom_id = self.product_id.uom_id.id
@api.onchange('lot_name', 'lot_id')
def _onchange_serial_number(self):
""" When the user is encoding a move line for a tracked product, we apply some logic to
help him. This includes:
- automatically switch `qty_done` to 1.0
- warn if he has already encoded `lot_name` in another move line
- warn (and update if appropriate) if the SN is in a different source location than selected
"""
res = {}
if self.product_id.tracking == 'serial':
if not self.qty_done:
self.qty_done = 1
message = None
if self.lot_name or self.lot_id:
move_lines_to_check = self._get_similar_move_lines() - self
if self.lot_name:
counter = Counter([line.lot_name for line in move_lines_to_check])
if counter.get(self.lot_name) and counter[self.lot_name] > 1:
message = _('You cannot use the same serial number twice. Please correct the serial numbers encoded.')
elif not self.lot_id:
lots = self.env['stock.production.lot'].search([('product_id', '=', self.product_id.id),
('name', '=', self.lot_name),
('company_id', '=', self.company_id.id)])
quants = lots.quant_ids.filtered(lambda q: q.quantity != 0 and q.location_id.usage in ['customer', 'internal', 'transit'])
if quants:
message = _('Serial number (%s) already exists in location(s): %s. Please correct the serial number encoded.', self.lot_name, ', '.join(quants.location_id.mapped('display_name')))
elif self.lot_id:
counter = Counter([line.lot_id.id for line in move_lines_to_check])
if counter.get(self.lot_id.id) and counter[self.lot_id.id] > 1:
message = _('You cannot use the same serial number twice. Please correct the serial numbers encoded.')
else:
# check if in correct source location
message, recommended_location = self.env['stock.quant']._check_serial_number(self.product_id,
self.lot_id,
self.company_id,
self.location_id,
self.picking_id.location_id)
if recommended_location:
self.location_id = recommended_location
if message:
res['warning'] = {'title': _('Warning'), 'message': message}
return res
@api.onchange('qty_done', 'product_uom_id')
def _onchange_qty_done(self):
""" When the user is encoding a move line for a tracked product, we apply some logic to
help him. This onchange will warn him if he set `qty_done` to a non-supported value.
"""
res = {}
if self.qty_done and self.product_id.tracking == 'serial':
qty_done = self.product_uom_id._compute_quantity(self.qty_done, self.product_id.uom_id)
if float_compare(qty_done, 1.0, precision_rounding=self.product_id.uom_id.rounding) != 0:
message = _('You can only process 1.0 %s of products with unique serial number.', self.product_id.uom_id.name)
res['warning'] = {'title': _('Warning'), 'message': message}
return res
@api.onchange('result_package_id', 'product_id', 'product_uom_id', 'qty_done')
def _onchange_putaway_location(self):
if not self.id and self.user_has_groups('stock.group_stock_multi_locations') and self.product_id and self.qty_done:
qty_done = self.product_uom_id._compute_quantity(self.qty_done, self.product_id.uom_id)
default_dest_location = self._get_default_dest_location()
self.location_dest_id = default_dest_location.with_context(exclude_sml_ids=self.ids)._get_putaway_strategy(
self.product_id, quantity=qty_done, package=self.result_package_id,
packaging=self.move_id.product_packaging_id)
def _apply_putaway_strategy(self):
if self._context.get('avoid_putaway_rules'):
return
self = self.with_context(do_not_unreserve=True)
for package, smls in groupby(self, lambda sml: sml.result_package_id):
smls = self.env['stock.move.line'].concat(*smls)
excluded_smls = smls
if package.package_type_id:
best_loc = smls.move_id.location_dest_id.with_context(exclude_sml_ids=excluded_smls.ids, products=smls.product_id)._get_putaway_strategy(self.env['product.product'], package=package)
smls.location_dest_id = smls.package_level_id.location_dest_id = best_loc
elif package:
used_locations = set()
for sml in smls:
if len(used_locations) > 1:
break
sml.location_dest_id = sml.move_id.location_dest_id.with_context(exclude_sml_ids=excluded_smls.ids)._get_putaway_strategy(sml.product_id, quantity=sml.product_uom_qty)
excluded_smls -= sml
used_locations.add(sml.location_dest_id)
if len(used_locations) > 1:
smls.location_dest_id = smls.move_id.location_dest_id
else:
smls.package_level_id.location_dest_id = smls.location_dest_id
else:
for sml in smls:
qty = max(sml.product_uom_qty, sml.qty_done)
putaway_loc_id = sml.move_id.location_dest_id.with_context(exclude_sml_ids=excluded_smls.ids)._get_putaway_strategy(
sml.product_id, quantity=qty, packaging=sml.move_id.product_packaging_id,
)
if putaway_loc_id != sml.location_dest_id:
sml.location_dest_id = putaway_loc_id
excluded_smls -= sml
def _get_default_dest_location(self):
if not self.user_has_groups('stock.group_stock_storage_categories'):
return self.location_dest_id[:1]
if self.env.context.get('default_location_dest_id'):
return self.env['stock.location'].browse([self.env.context.get('default_location_dest_id')])
return (self.move_id.location_dest_id or self.picking_id.location_dest_id or self.location_dest_id)[0]
def _get_putaway_additional_qty(self):
addtional_qty = {}
for ml in self._origin:
qty = max(ml.product_uom_id._compute_quantity(ml.qty_done, ml.product_id.uom_id), ml.product_uom_qty)
addtional_qty[ml.location_dest_id.id] = addtional_qty.get(ml.location_dest_id.id, 0) - qty
return addtional_qty
def init(self):
if not tools.index_exists(self._cr, 'stock_move_line_free_reservation_index'):
self._cr.execute("""
CREATE INDEX stock_move_line_free_reservation_index
ON
stock_move_line (id, company_id, product_id, lot_id, location_id, owner_id, package_id)
WHERE
(state IS NULL OR state NOT IN ('cancel', 'done')) AND product_qty > 0""")
@api.model_create_multi
def create(self, vals_list):
for vals in vals_list:
if vals.get('move_id'):
vals['company_id'] = self.env['stock.move'].browse(vals['move_id']).company_id.id
elif vals.get('picking_id'):
vals['company_id'] = self.env['stock.picking'].browse(vals['picking_id']).company_id.id
if self.env.context.get('import_file') and vals.get('product_uom_qty'):
raise UserError(_("It is not allowed to import reserved quantity, you have to use the quantity directly."))
mls = super().create(vals_list)
def create_move(move_line):
new_move = self.env['stock.move'].create(move_line._prepare_stock_move_vals())
move_line.move_id = new_move.id
# If the move line is directly create on the picking view.
# If this picking is already done we should generate an
# associated done move.
for move_line in mls:
if move_line.move_id or not move_line.picking_id:
continue
if move_line.picking_id.state != 'done':
moves = move_line.picking_id.move_lines.filtered(lambda x: x.product_id == move_line.product_id)
moves = sorted(moves, key=lambda m: m.quantity_done < m.product_qty, reverse=True)
if moves:
move_line.move_id = moves[0].id
else:
create_move(move_line)
else:
create_move(move_line)
moves_to_update = mls.filtered(
lambda ml:
ml.move_id and
ml.qty_done and (
ml.move_id.state == 'done' or (
ml.move_id.picking_id and
ml.move_id.picking_id.immediate_transfer
))
).move_id
for move in moves_to_update:
move.with_context(avoid_putaway_rules=True).product_uom_qty = move.quantity_done
for ml, vals in zip(mls, vals_list):
if ml.state == 'done':
if ml.product_id.type == 'product':
Quant = self.env['stock.quant']
quantity = ml.product_uom_id._compute_quantity(ml.qty_done, ml.move_id.product_id.uom_id,rounding_method='HALF-UP')
in_date = None
available_qty, in_date = Quant._update_available_quantity(ml.product_id, ml.location_id, -quantity, lot_id=ml.lot_id, package_id=ml.package_id, owner_id=ml.owner_id)
if available_qty < 0 and ml.lot_id:
# see if we can compensate the negative quants with some untracked quants
untracked_qty = Quant._get_available_quantity(ml.product_id, ml.location_id, lot_id=False, package_id=ml.package_id, owner_id=ml.owner_id, strict=True)
if untracked_qty:
taken_from_untracked_qty = min(untracked_qty, abs(quantity))
Quant._update_available_quantity(ml.product_id, ml.location_id, -taken_from_untracked_qty, lot_id=False, package_id=ml.package_id, owner_id=ml.owner_id)
Quant._update_available_quantity(ml.product_id, ml.location_id, taken_from_untracked_qty, lot_id=ml.lot_id, package_id=ml.package_id, owner_id=ml.owner_id)
Quant._update_available_quantity(ml.product_id, ml.location_dest_id, quantity, lot_id=ml.lot_id, package_id=ml.result_package_id, owner_id=ml.owner_id, in_date=in_date)
next_moves = ml.move_id.move_dest_ids.filtered(lambda move: move.state not in ('done', 'cancel'))
next_moves._do_unreserve()
next_moves._action_assign()
return mls
def write(self, vals):
if self.env.context.get('bypass_reservation_update'):
return super(StockMoveLine, self).write(vals)
if 'product_id' in vals and any(vals.get('state', ml.state) != 'draft' and vals['product_id'] != ml.product_id.id for ml in self):
raise UserError(_("Changing the product is only allowed in 'Draft' state."))
moves_to_recompute_state = self.env['stock.move']
Quant = self.env['stock.quant']
precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')
triggers = [
('location_id', 'stock.location'),
('location_dest_id', 'stock.location'),
('lot_id', 'stock.production.lot'),
('package_id', 'stock.quant.package'),
('result_package_id', 'stock.quant.package'),
('owner_id', 'res.partner'),
('product_uom_id', 'uom.uom')
]
updates = {}
for key, model in triggers:
if key in vals:
updates[key] = self.env[model].browse(vals[key])
if 'result_package_id' in updates:
for ml in self.filtered(lambda ml: ml.package_level_id):
if updates.get('result_package_id'):
ml.package_level_id.package_id = updates.get('result_package_id')
else:
# TODO: make package levels less of a pain and fix this
package_level = ml.package_level_id
ml.package_level_id = False
# Only need to unlink the package level if it's empty. Otherwise will unlink it to still valid move lines.
if not package_level.move_line_ids:
package_level.unlink()
# When we try to write on a reserved move line any fields from `triggers` or directly
# `product_uom_qty` (the actual reserved quantity), we need to make sure the associated
# quants are correctly updated in order to not make them out of sync (i.e. the sum of the
# move lines `product_uom_qty` should always be equal to the sum of `reserved_quantity` on
# the quants). If the new charateristics are not available on the quants, we chose to
# reserve the maximum possible.
if updates or 'product_uom_qty' in vals:
for ml in self.filtered(lambda ml: ml.state in ['partially_available', 'assigned'] and ml.product_id.type == 'product'):
if 'product_uom_qty' in vals:
new_product_uom_qty = ml.product_uom_id._compute_quantity(
vals['product_uom_qty'], ml.product_id.uom_id, rounding_method='HALF-UP')
# Make sure `product_uom_qty` is not negative.
if float_compare(new_product_uom_qty, 0, precision_rounding=ml.product_id.uom_id.rounding) < 0:
raise UserError(_('Reserving a negative quantity is not allowed.'))
else:
new_product_uom_qty = ml.product_qty
# Unreserve the old charateristics of the move line.
if not ml.move_id._should_bypass_reservation(ml.location_id):
Quant._update_reserved_quantity(ml.product_id, ml.location_id, -ml.product_qty, lot_id=ml.lot_id, package_id=ml.package_id, owner_id=ml.owner_id, strict=True)
# Reserve the maximum available of the new charateristics of the move line.
if not ml.move_id._should_bypass_reservation(updates.get('location_id', ml.location_id)):
reserved_qty = 0
try:
q = Quant._update_reserved_quantity(ml.product_id, updates.get('location_id', ml.location_id), new_product_uom_qty, lot_id=updates.get('lot_id', ml.lot_id),
package_id=updates.get('package_id', ml.package_id), owner_id=updates.get('owner_id', ml.owner_id), strict=True)
reserved_qty = sum([x[1] for x in q])
except UserError:
pass
if reserved_qty != new_product_uom_qty:
new_product_uom_qty = ml.product_id.uom_id._compute_quantity(reserved_qty, ml.product_uom_id, rounding_method='HALF-UP')
moves_to_recompute_state |= ml.move_id
ml.with_context(bypass_reservation_update=True).product_uom_qty = new_product_uom_qty
# we don't want to override the new reserved quantity
vals.pop('product_uom_qty', None)
# When editing a done move line, the reserved availability of a potential chained move is impacted. Take care of running again `_action_assign` on the concerned moves.
if updates or 'qty_done' in vals:
next_moves = self.env['stock.move']
mls = self.filtered(lambda ml: ml.move_id.state == 'done' and ml.product_id.type == 'product')
if not updates: # we can skip those where qty_done is already good up to UoM rounding
mls = mls.filtered(lambda ml: not float_is_zero(ml.qty_done - vals['qty_done'], precision_rounding=ml.product_uom_id.rounding))
for ml in mls:
# undo the original move line
qty_done_orig = ml.product_uom_id._compute_quantity(ml.qty_done, ml.move_id.product_id.uom_id, rounding_method='HALF-UP')
in_date = Quant._update_available_quantity(ml.product_id, ml.location_dest_id, -qty_done_orig, lot_id=ml.lot_id,
package_id=ml.result_package_id, owner_id=ml.owner_id)[1]
Quant._update_available_quantity(ml.product_id, ml.location_id, qty_done_orig, lot_id=ml.lot_id,
package_id=ml.package_id, owner_id=ml.owner_id, in_date=in_date)
# move what's been actually done
product_id = ml.product_id
location_id = updates.get('location_id', ml.location_id)
location_dest_id = updates.get('location_dest_id', ml.location_dest_id)
qty_done = vals.get('qty_done', ml.qty_done)
lot_id = updates.get('lot_id', ml.lot_id)
package_id = updates.get('package_id', ml.package_id)
result_package_id = updates.get('result_package_id', ml.result_package_id)
owner_id = updates.get('owner_id', ml.owner_id)
product_uom_id = updates.get('product_uom_id', ml.product_uom_id)
quantity = product_uom_id._compute_quantity(qty_done, ml.move_id.product_id.uom_id, rounding_method='HALF-UP')
if not ml.move_id._should_bypass_reservation(location_id):
ml._free_reservation(product_id, location_id, quantity, lot_id=lot_id, package_id=package_id, owner_id=owner_id)
if not float_is_zero(quantity, precision_digits=precision):
available_qty, in_date = Quant._update_available_quantity(product_id, location_id, -quantity, lot_id=lot_id, package_id=package_id, owner_id=owner_id)
if available_qty < 0 and lot_id:
# see if we can compensate the negative quants with some untracked quants
untracked_qty = Quant._get_available_quantity(product_id, location_id, lot_id=False, package_id=package_id, owner_id=owner_id, strict=True)
if untracked_qty:
taken_from_untracked_qty = min(untracked_qty, abs(available_qty))
Quant._update_available_quantity(product_id, location_id, -taken_from_untracked_qty, lot_id=False, package_id=package_id, owner_id=owner_id)
Quant._update_available_quantity(product_id, location_id, taken_from_untracked_qty, lot_id=lot_id, package_id=package_id, owner_id=owner_id)
if not ml.move_id._should_bypass_reservation(location_id):
ml._free_reservation(ml.product_id, location_id, untracked_qty, lot_id=False, package_id=package_id, owner_id=owner_id)
Quant._update_available_quantity(product_id, location_dest_id, quantity, lot_id=lot_id, package_id=result_package_id, owner_id=owner_id, in_date=in_date)
# Unreserve and reserve following move in order to have the real reserved quantity on move_line.
next_moves |= ml.move_id.move_dest_ids.filtered(lambda move: move.state not in ('done', 'cancel'))
# Log a note
if ml.picking_id:
ml._log_message(ml.picking_id, ml, 'stock.track_move_template', vals)
res = super(StockMoveLine, self).write(vals)
# Update scrap object linked to move_lines to the new quantity.
if 'qty_done' in vals:
for move in self.mapped('move_id'):
if move.scrapped:
move.scrap_ids.write({'scrap_qty': move.quantity_done})
# As stock_account values according to a move's `product_uom_qty`, we consider that any
# done stock move should have its `quantity_done` equals to its `product_uom_qty`, and
# this is what move's `action_done` will do. So, we replicate the behavior here.
if updates or 'qty_done' in vals:
moves = self.filtered(lambda ml: ml.move_id.state == 'done').mapped('move_id')
moves |= self.filtered(lambda ml: ml.move_id.state not in ('done', 'cancel') and ml.move_id.picking_id.immediate_transfer and not ml.product_uom_qty).mapped('move_id')
for move in moves:
move.product_uom_qty = move.quantity_done
next_moves._do_unreserve()
next_moves._action_assign()
if moves_to_recompute_state:
moves_to_recompute_state._recompute_state()
return res
@api.ondelete(at_uninstall=False)
def _unlink_except_done_or_cancel(self):
for ml in self:
if ml.state in ('done', 'cancel'):
raise UserError(_('You can not delete product moves if the picking is done. You can only correct the done quantities.'))
def unlink(self):
precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')
for ml in self:
# Unlinking a move line should unreserve.
if ml.product_id.type == 'product' and ml.move_id and not ml.move_id._should_bypass_reservation(ml.location_id) and not float_is_zero(ml.product_qty, precision_digits=precision):
self.env['stock.quant']._update_reserved_quantity(ml.product_id, ml.location_id, -ml.product_qty, lot_id=ml.lot_id, package_id=ml.package_id, owner_id=ml.owner_id, strict=True)
moves = self.mapped('move_id')
res = super(StockMoveLine, self).unlink()
if moves:
# Add with_prefetch() to set the _prefecht_ids = _ids
# because _prefecht_ids generator look lazily on the cache of move_id
# which is clear by the unlink of move line
moves.with_prefetch()._recompute_state()
return res
def _action_done(self):
""" This method is called during a move's `action_done`. It'll actually move a quant from
the source location to the destination location, and unreserve if needed in the source
location.
This method is intended to be called on all the move lines of a move. This method is not
intended to be called when editing a `done` move (that's what the override of `write` here
is done.
"""
Quant = self.env['stock.quant']
# First, we loop over all the move lines to do a preliminary check: `qty_done` should not
# be negative and, according to the presence of a picking type or a linked inventory
# adjustment, enforce some rules on the `lot_id` field. If `qty_done` is null, we unlink
# the line. It is mandatory in order to free the reservation and correctly apply
# `action_done` on the next move lines.
ml_ids_tracked_without_lot = OrderedSet()
ml_ids_to_delete = OrderedSet()
ml_ids_to_create_lot = OrderedSet()
for ml in self:
# Check here if `ml.qty_done` respects the rounding of `ml.product_uom_id`.
uom_qty = float_round(ml.qty_done, precision_rounding=ml.product_uom_id.rounding, rounding_method='HALF-UP')
precision_digits = self.env['decimal.precision'].precision_get('Product Unit of Measure')
qty_done = float_round(ml.qty_done, precision_digits=precision_digits, rounding_method='HALF-UP')
if float_compare(uom_qty, qty_done, precision_digits=precision_digits) != 0:
raise UserError(_('The quantity done for the product "%s" doesn\'t respect the rounding precision '
'defined on the unit of measure "%s". Please change the quantity done or the '
'rounding precision of your unit of measure.') % (ml.product_id.display_name, ml.product_uom_id.name))
qty_done_float_compared = float_compare(ml.qty_done, 0, precision_rounding=ml.product_uom_id.rounding)
if qty_done_float_compared > 0:
if ml.product_id.tracking != 'none':
picking_type_id = ml.move_id.picking_type_id
if picking_type_id:
if picking_type_id.use_create_lots:
# If a picking type is linked, we may have to create a production lot on
# the fly before assigning it to the move line if the user checked both
# `use_create_lots` and `use_existing_lots`.
if ml.lot_name and not ml.lot_id:
lot = self.env['stock.production.lot'].search([
('company_id', '=', ml.company_id.id),
('product_id', '=', ml.product_id.id),
('name', '=', ml.lot_name),
], limit=1)
if lot:
ml.lot_id = lot.id
else:
ml_ids_to_create_lot.add(ml.id)
elif not picking_type_id.use_create_lots and not picking_type_id.use_existing_lots:
# If the user disabled both `use_create_lots` and `use_existing_lots`
# checkboxes on the picking type, he's allowed to enter tracked
# products without a `lot_id`.
continue
elif ml.is_inventory:
# If an inventory adjustment is linked, the user is allowed to enter
# tracked products without a `lot_id`.
continue
if not ml.lot_id and ml.id not in ml_ids_to_create_lot:
ml_ids_tracked_without_lot.add(ml.id)
elif qty_done_float_compared < 0:
raise UserError(_('No negative quantities allowed'))
elif not ml.is_inventory:
ml_ids_to_delete.add(ml.id)
if ml_ids_tracked_without_lot:
mls_tracked_without_lot = self.env['stock.move.line'].browse(ml_ids_tracked_without_lot)
raise UserError(_('You need to supply a Lot/Serial Number for product: \n - ') +
'\n - '.join(mls_tracked_without_lot.mapped('product_id.display_name')))
ml_to_create_lot = self.env['stock.move.line'].browse(ml_ids_to_create_lot)
ml_to_create_lot.with_context(bypass_reservation_update=True)._create_and_assign_production_lot()
mls_to_delete = self.env['stock.move.line'].browse(ml_ids_to_delete)
mls_to_delete.unlink()
mls_todo = (self - mls_to_delete)
mls_todo._check_company()
# Now, we can actually move the quant.
ml_ids_to_ignore = OrderedSet()
for ml in mls_todo:
if ml.product_id.type == 'product':
rounding = ml.product_uom_id.rounding
# if this move line is force assigned, unreserve elsewhere if needed
if not ml.move_id._should_bypass_reservation(ml.location_id) and float_compare(ml.qty_done, ml.product_uom_qty, precision_rounding=rounding) > 0:
qty_done_product_uom = ml.product_uom_id._compute_quantity(ml.qty_done, ml.product_id.uom_id, rounding_method='HALF-UP')
extra_qty = qty_done_product_uom - ml.product_qty
ml._free_reservation(ml.product_id, ml.location_id, extra_qty, lot_id=ml.lot_id, package_id=ml.package_id, owner_id=ml.owner_id, ml_ids_to_ignore=ml_ids_to_ignore)
# unreserve what's been reserved
if not ml.move_id._should_bypass_reservation(ml.location_id) and ml.product_id.type == 'product' and ml.product_qty:
Quant._update_reserved_quantity(ml.product_id, ml.location_id, -ml.product_qty, lot_id=ml.lot_id, package_id=ml.package_id, owner_id=ml.owner_id, strict=True)
# move what's been actually done
quantity = ml.product_uom_id._compute_quantity(ml.qty_done, ml.move_id.product_id.uom_id, rounding_method='HALF-UP')
available_qty, in_date = Quant._update_available_quantity(ml.product_id, ml.location_id, -quantity, lot_id=ml.lot_id, package_id=ml.package_id, owner_id=ml.owner_id)
if available_qty < 0 and ml.lot_id:
# see if we can compensate the negative quants with some untracked quants
untracked_qty = Quant._get_available_quantity(ml.product_id, ml.location_id, lot_id=False, package_id=ml.package_id, owner_id=ml.owner_id, strict=True)
if untracked_qty:
taken_from_untracked_qty = min(untracked_qty, abs(quantity))
Quant._update_available_quantity(ml.product_id, ml.location_id, -taken_from_untracked_qty, lot_id=False, package_id=ml.package_id, owner_id=ml.owner_id)
Quant._update_available_quantity(ml.product_id, ml.location_id, taken_from_untracked_qty, lot_id=ml.lot_id, package_id=ml.package_id, owner_id=ml.owner_id)
Quant._update_available_quantity(ml.product_id, ml.location_dest_id, quantity, lot_id=ml.lot_id, package_id=ml.result_package_id, owner_id=ml.owner_id, in_date=in_date)
ml_ids_to_ignore.add(ml.id)
# Reset the reserved quantity as we just moved it to the destination location.
mls_todo.with_context(bypass_reservation_update=True).write({
'product_uom_qty': 0.00,
'date': fields.Datetime.now(),
})
def _get_similar_move_lines(self):
self.ensure_one()
lines = self.env['stock.move.line']
picking_id = self.move_id.picking_id if self.move_id else self.picking_id
if picking_id:
lines |= picking_id.move_line_ids.filtered(lambda ml: ml.product_id == self.product_id and (ml.lot_id or ml.lot_name))
return lines
def _get_value_production_lot(self):
self.ensure_one()
return {
'company_id': self.company_id.id,
'name': self.lot_name,
'product_id': self.product_id.id
}
def _create_and_assign_production_lot(self):
""" Creates and assign new production lots for move lines."""
lot_vals = []
# It is possible to have multiple time the same lot to create & assign,
# so we handle the case with 2 dictionaries.
key_to_index = {} # key to index of the lot
key_to_mls = defaultdict(lambda: self.env['stock.move.line']) # key to all mls
for ml in self:
key = (ml.company_id.id, ml.product_id.id, ml.lot_name)
key_to_mls[key] |= ml
if ml.tracking != 'lot' or key not in key_to_index:
key_to_index[key] = len(lot_vals)
lot_vals.append(ml._get_value_production_lot())
lots = self.env['stock.production.lot'].create(lot_vals)
for key, mls in key_to_mls.items():
mls._assign_production_lot(lots[key_to_index[key]].with_prefetch(lots._ids)) # With prefetch to reconstruct the ones broke by accessing by index
def _assign_production_lot(self, lot):
self.write({'lot_id': lot.id})
def _reservation_is_updatable(self, quantity, reserved_quant):
self.ensure_one()
if (self.product_id.tracking != 'serial' and
self.location_id.id == reserved_quant.location_id.id and
self.lot_id.id == reserved_quant.lot_id.id and
self.package_id.id == reserved_quant.package_id.id and
self.owner_id.id == reserved_quant.owner_id.id):
return True
return False
def _log_message(self, record, move, template, vals):
data = vals.copy()
if 'lot_id' in vals and vals['lot_id'] != move.lot_id.id:
data['lot_name'] = self.env['stock.production.lot'].browse(vals.get('lot_id')).name
if 'location_id' in vals:
data['location_name'] = self.env['stock.location'].browse(vals.get('location_id')).name
if 'location_dest_id' in vals:
data['location_dest_name'] = self.env['stock.location'].browse(vals.get('location_dest_id')).name
if 'package_id' in vals and vals['package_id'] != move.package_id.id:
data['package_name'] = self.env['stock.quant.package'].browse(vals.get('package_id')).name
if 'package_result_id' in vals and vals['package_result_id'] != move.package_result_id.id:
data['result_package_name'] = self.env['stock.quant.package'].browse(vals.get('result_package_id')).name
if 'owner_id' in vals and vals['owner_id'] != move.owner_id.id:
data['owner_name'] = self.env['res.partner'].browse(vals.get('owner_id')).name
record.message_post_with_view(template, values={'move': move, 'vals': dict(vals, **data)}, subtype_id=self.env.ref('mail.mt_note').id)
def _free_reservation(self, product_id, location_id, quantity, lot_id=None, package_id=None, owner_id=None, ml_ids_to_ignore=None):
""" When editing a done move line or validating one with some forced quantities, it is
possible to impact quants that were not reserved. It is therefore necessary to edit or
unlink the move lines that reserved a quantity now unavailable.
:param ml_ids_to_ignore: OrderedSet of `stock.move.line` ids that should NOT be unreserved
"""
self.ensure_one()
if ml_ids_to_ignore is None:
ml_ids_to_ignore = OrderedSet()
ml_ids_to_ignore |= self.ids
# Check the available quantity, with the `strict` kw set to `True`. If the available
# quantity is greather than the quantity now unavailable, there is nothing to do.
available_quantity = self.env['stock.quant']._get_available_quantity(
product_id, location_id, lot_id=lot_id, package_id=package_id, owner_id=owner_id, strict=True
)
if quantity > available_quantity:
quantity = quantity - available_quantity
# We now have to find the move lines that reserved our now unavailable quantity. We
# take care to exclude ourselves and the move lines were work had already been done.
outdated_move_lines_domain = [
('state', 'not in', ['done', 'cancel']),
('product_id', '=', product_id.id),
('lot_id', '=', lot_id.id if lot_id else False),
('location_id', '=', location_id.id),
('owner_id', '=', owner_id.id if owner_id else False),
('package_id', '=', package_id.id if package_id else False),
('product_qty', '>', 0.0),
('id', 'not in', tuple(ml_ids_to_ignore)),
]
# We take the current picking first, then the pickings with the latest scheduled date
current_picking_first = lambda cand: (
cand.picking_id != self.move_id.picking_id,
-(cand.picking_id.scheduled_date or cand.move_id.date).timestamp()
if cand.picking_id or cand.move_id
else -cand.id,
)
outdated_candidates = self.env['stock.move.line'].search(outdated_move_lines_domain).sorted(current_picking_first)
# As the move's state is not computed over the move lines, we'll have to manually
# recompute the moves which we adapted their lines.
move_to_recompute_state = self.env['stock.move']
to_unlink_candidate_ids = set()
rounding = self.product_uom_id.rounding
for candidate in outdated_candidates:
if float_compare(candidate.product_qty, quantity, precision_rounding=rounding) <= 0:
quantity -= candidate.product_qty
if candidate.qty_done:
move_to_recompute_state |= candidate.move_id
candidate.product_uom_qty = 0.0
else:
to_unlink_candidate_ids.add(candidate.id)
if float_is_zero(quantity, precision_rounding=rounding):
break
else:
# split this move line and assign the new part to our extra move
quantity_split = float_round(
candidate.product_qty - quantity,
precision_rounding=self.product_uom_id.rounding,
rounding_method='UP')
candidate.product_uom_qty = self.product_id.uom_id._compute_quantity(quantity_split, candidate.product_uom_id, rounding_method='HALF-UP')
move_to_recompute_state |= candidate.move_id
break
self.env['stock.move.line'].browse(to_unlink_candidate_ids).unlink()
move_to_recompute_state._recompute_state()
def _get_aggregated_product_quantities(self, **kwargs):
""" Returns a dictionary of products (key = id+name+description+uom) and corresponding values of interest.
Allows aggregation of data across separate move lines for the same product. This is expected to be useful
in things such as delivery reports. Dict key is made as a combination of values we expect to want to group
the products by (i.e. so data is not lost). This function purposely ignores lots/SNs because these are
expected to already be properly grouped by line.
returns: dictionary {product_id+name+description+uom: {product, name, description, qty_done, product_uom}, ...}
"""
aggregated_move_lines = {}
def get_aggregated_properties(move_line=False, move=False):
move = move or move_line.move_id
uom = move.product_uom or move_line.product_uom_id
name = move.product_id.display_name
description = move.description_picking
if description == name or description == move.product_id.name:
description = False
product = move.product_id
line_key = f'{product.id}_{product.display_name}_{description or ""}_{uom.id}'
return (line_key, name, description, uom)
# Loops to get backorders, backorders' backorders, and so and so...
backorders = self.env['stock.picking']
pickings = self.picking_id
while pickings.backorder_ids:
backorders |= pickings.backorder_ids
pickings = pickings.backorder_ids
for move_line in self:
if kwargs.get('except_package') and move_line.result_package_id:
continue
line_key, name, description, uom = get_aggregated_properties(move_line=move_line)
qty_done = move_line.product_uom_id._compute_quantity(move_line.qty_done, uom)
if line_key not in aggregated_move_lines:
qty_ordered = None
if backorders and not kwargs.get('strict'):
qty_ordered = move_line.move_id.product_uom_qty
# Filters on the aggregation key (product, description and uom) to add the
# quantities delayed to backorders to retrieve the original ordered qty.
following_move_lines = backorders.move_line_ids.filtered(
lambda ml: get_aggregated_properties(move=ml.move_id)[0] == line_key
)
qty_ordered += sum(following_move_lines.move_id.mapped('product_uom_qty'))
# Remove the done quantities of the other move lines of the stock move
previous_move_lines = move_line.move_id.move_line_ids.filtered(
lambda ml: get_aggregated_properties(move=ml.move_id)[0] == line_key and ml.id != move_line.id
)
qty_ordered -= sum(map(lambda m: m.product_uom_id._compute_quantity(m.qty_done, uom), previous_move_lines))
aggregated_move_lines[line_key] = {'name': name,
'description': description,
'qty_done': qty_done,
'qty_ordered': qty_ordered or qty_done,
'product_uom': uom.name,
'product_uom_rec': uom,
'product': move_line.product_id}
else:
aggregated_move_lines[line_key]['qty_ordered'] += qty_done
aggregated_move_lines[line_key]['qty_done'] += qty_done
# Does the same for empty move line to retrieve the ordered qty. for partially done moves
# (as they are splitted when the transfer is done and empty moves don't have move lines).
if kwargs.get('strict'):
return aggregated_move_lines
pickings = (self.picking_id | backorders)
for empty_move in pickings.move_lines:
if not (empty_move.state == "cancel" and empty_move.product_uom_qty
and float_is_zero(empty_move.quantity_done, precision_rounding=empty_move.product_uom.rounding)):
continue
line_key, name, description, uom = get_aggregated_properties(move=empty_move)
if line_key not in aggregated_move_lines:
qty_ordered = empty_move.product_uom_qty
aggregated_move_lines[line_key] = {
'name': name,
'description': description,
'qty_done': False,
'qty_ordered': qty_ordered,
'product_uom': uom.name,
'product_uom_rec': uom,
'product': empty_move.product_id,
}
else:
aggregated_move_lines[line_key]['qty_ordered'] += empty_move.product_uom_qty
return aggregated_move_lines
def _compute_sale_price(self):
# To Override
pass
@api.model
def _prepare_stock_move_vals(self):
self.ensure_one()
return {
'name': _('New Move:') + self.product_id.display_name,
'product_id': self.product_id.id,
'product_uom_qty': 0 if self.picking_id and self.picking_id.state != 'done' else self.qty_done,
'product_uom': self.product_uom_id.id,
'description_picking': self.description_picking,
'location_id': self.picking_id.location_id.id,
'location_dest_id': self.picking_id.location_dest_id.id,
'picking_id': self.picking_id.id,
'state': self.picking_id.state,
'picking_type_id': self.picking_id.picking_type_id.id,
'restrict_partner_id': self.picking_id.owner_id.id,
'company_id': self.picking_id.company_id.id,
'partner_id': self.picking_id.partner_id.id,
}
| 61.928066
| 52,515
|
55,111
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from psycopg2 import Error, OperationalError
from odoo import _, api, fields, models
from odoo.exceptions import UserError, ValidationError
from odoo.osv import expression
from odoo.tools.float_utils import float_compare, float_is_zero
_logger = logging.getLogger(__name__)
class StockQuant(models.Model):
_name = 'stock.quant'
_description = 'Quants'
_rec_name = 'product_id'
def _domain_location_id(self):
if not self._is_inventory_mode():
return
return [('usage', 'in', ['internal', 'transit'])]
def _domain_lot_id(self):
if not self._is_inventory_mode():
return
domain = [
"'|'",
"('company_id', '=', company_id)",
"('company_id', '=', False)"
]
if self.env.context.get('active_model') == 'product.product':
domain.insert(0, "('product_id', '=', %s)" % self.env.context.get('active_id'))
elif self.env.context.get('active_model') == 'product.template':
product_template = self.env['product.template'].browse(self.env.context.get('active_id'))
if product_template.exists():
domain.insert(0, "('product_id', 'in', %s)" % product_template.product_variant_ids.ids)
else:
domain.insert(0, "('product_id', '=', product_id)")
return '[' + ', '.join(domain) + ']'
def _domain_product_id(self):
if not self._is_inventory_mode():
return
domain = [('type', '=', 'product')]
if self.env.context.get('product_tmpl_ids') or self.env.context.get('product_tmpl_id'):
products = self.env.context.get('product_tmpl_ids', []) + [self.env.context.get('product_tmpl_id', 0)]
domain = expression.AND([domain, [('product_tmpl_id', 'in', products)]])
return domain
product_id = fields.Many2one(
'product.product', 'Product',
domain=lambda self: self._domain_product_id(),
ondelete='restrict', required=True, index=True, check_company=True)
product_tmpl_id = fields.Many2one(
'product.template', string='Product Template',
related='product_id.product_tmpl_id')
product_uom_id = fields.Many2one(
'uom.uom', 'Unit of Measure',
readonly=True, related='product_id.uom_id')
company_id = fields.Many2one(related='location_id.company_id', string='Company', store=True, readonly=True)
location_id = fields.Many2one(
'stock.location', 'Location',
domain=lambda self: self._domain_location_id(),
auto_join=True, ondelete='restrict', required=True, index=True, check_company=True)
lot_id = fields.Many2one(
'stock.production.lot', 'Lot/Serial Number', index=True,
ondelete='restrict', check_company=True,
domain=lambda self: self._domain_lot_id())
package_id = fields.Many2one(
'stock.quant.package', 'Package',
domain="[('location_id', '=', location_id)]",
help='The package containing this quant', ondelete='restrict', check_company=True)
owner_id = fields.Many2one(
'res.partner', 'Owner',
help='This is the owner of the quant', check_company=True)
quantity = fields.Float(
'Quantity',
help='Quantity of products in this quant, in the default unit of measure of the product',
readonly=True, digits='Product Unit of Measure')
reserved_quantity = fields.Float(
'Reserved Quantity',
default=0.0,
help='Quantity of reserved products in this quant, in the default unit of measure of the product',
readonly=True, required=True, digits='Product Unit of Measure')
available_quantity = fields.Float(
'Available Quantity',
help="On hand quantity which hasn't been reserved on a transfer, in the default unit of measure of the product",
compute='_compute_available_quantity', digits='Product Unit of Measure')
in_date = fields.Datetime('Incoming Date', readonly=True, required=True, default=fields.Datetime.now)
tracking = fields.Selection(related='product_id.tracking', readonly=True)
on_hand = fields.Boolean('On Hand', store=False, search='_search_on_hand')
product_categ_id = fields.Many2one(related='product_tmpl_id.categ_id')
# Inventory Fields
inventory_quantity = fields.Float(
'Counted Quantity', digits='Product Unit of Measure',
help="The product's counted quantity.")
inventory_quantity_auto_apply = fields.Float(
'Inventoried Quantity', compute='_compute_inventory_quantity_auto_apply',
inverse='_set_inventory_quantity', groups='stock.group_stock_manager'
)
inventory_diff_quantity = fields.Float(
'Difference', compute='_compute_inventory_diff_quantity', store=True,
help="Indicates the gap between the product's theoretical quantity and its counted quantity.",
readonly=True, digits='Product Unit of Measure')
inventory_date = fields.Date(
'Scheduled Date', compute='_compute_inventory_date', store=True, readonly=False,
help="Next date the On Hand Quantity should be counted.")
inventory_quantity_set = fields.Boolean(store=True, compute='_compute_inventory_quantity_set', readonly=False, default=False)
is_outdated = fields.Boolean('Quantity has been moved since last count', compute='_compute_is_outdated')
user_id = fields.Many2one(
'res.users', 'Assigned To', help="User assigned to do product count.")
@api.depends('quantity', 'reserved_quantity')
def _compute_available_quantity(self):
for quant in self:
quant.available_quantity = quant.quantity - quant.reserved_quantity
@api.depends('location_id')
def _compute_inventory_date(self):
quants = self.filtered(lambda q: not q.inventory_date and q.location_id.usage in ['internal', 'transit'])
date_by_location = {loc: loc._get_next_inventory_date() for loc in quants.location_id}
for quant in quants:
quant.inventory_date = date_by_location[quant.location_id]
@api.depends('inventory_quantity')
def _compute_inventory_diff_quantity(self):
for quant in self:
quant.inventory_diff_quantity = quant.inventory_quantity - quant.quantity
@api.depends('inventory_quantity')
def _compute_inventory_quantity_set(self):
self.inventory_quantity_set = True
@api.depends('inventory_quantity', 'quantity', 'product_id')
def _compute_is_outdated(self):
self.is_outdated = False
for quant in self:
if quant.product_id and float_compare(quant.inventory_quantity - quant.inventory_diff_quantity, quant.quantity, precision_rounding=quant.product_uom_id.rounding) and quant.inventory_quantity_set:
quant.is_outdated = True
@api.depends('quantity')
def _compute_inventory_quantity_auto_apply(self):
for quant in self:
quant.inventory_quantity_auto_apply = quant.quantity
def _set_inventory_quantity(self):
""" Inverse method to create stock move when `inventory_quantity` is set
(`inventory_quantity` is only accessible in inventory mode).
"""
if not self._is_inventory_mode():
return
for quant in self:
quant.inventory_quantity = quant.inventory_quantity_auto_apply
self.action_apply_inventory()
def _search_on_hand(self, operator, value):
"""Handle the "on_hand" filter, indirectly calling `_get_domain_locations`."""
if operator not in ['=', '!='] or not isinstance(value, bool):
raise UserError(_('Operation not supported'))
domain_loc = self.env['product.product']._get_domain_locations()[0]
quant_query = self.env['stock.quant']._search(domain_loc)
if (operator == '!=' and value is True) or (operator == '=' and value is False):
domain_operator = 'not in'
else:
domain_operator = 'in'
return [('id', domain_operator, quant_query)]
@api.model
def create(self, vals):
""" Override to handle the "inventory mode" and create a quant as
superuser the conditions are met.
"""
if self._is_inventory_mode() and any(f in vals for f in ['inventory_quantity', 'inventory_quantity_auto_apply']):
allowed_fields = self._get_inventory_fields_create()
if any(field for field in vals.keys() if field not in allowed_fields):
raise UserError(_("Quant's creation is restricted, you can't do this operation."))
auto_apply = 'inventory_quantity_auto_apply' in vals
inventory_quantity = vals.pop('inventory_quantity_auto_apply', False) or vals.pop(
'inventory_quantity', False) or 0
# Create an empty quant or write on a similar one.
product = self.env['product.product'].browse(vals['product_id'])
location = self.env['stock.location'].browse(vals['location_id'])
lot_id = self.env['stock.production.lot'].browse(vals.get('lot_id'))
package_id = self.env['stock.quant.package'].browse(vals.get('package_id'))
owner_id = self.env['res.partner'].browse(vals.get('owner_id'))
quant = self.env["stock.quant"]
if not self.env.context.get('import_file'):
# Merge quants later, to make sure one line = one record during batch import
quant = self._gather(product, location, lot_id=lot_id, package_id=package_id, owner_id=owner_id, strict=True)
if lot_id:
quant = quant.filtered(lambda q: q.lot_id)
if quant:
quant = quant[0].sudo()
else:
quant = self.sudo().create(vals)
if auto_apply:
quant.write({'inventory_quantity_auto_apply': inventory_quantity})
else:
# Set the `inventory_quantity` field to create the necessary move.
quant.inventory_quantity = inventory_quantity
quant.user_id = vals.get('user_id', self.env.user.id)
quant.inventory_date = fields.Date.today()
return quant
res = super(StockQuant, self).create(vals)
if self._is_inventory_mode():
res._check_company()
return res
def _load_records_create(self, values):
""" Add default location if import file did not fill it"""
company_user = self.env.company
self = self.with_context(inventory_mode=True)
warehouse = self.env['stock.warehouse'].search([('company_id', '=', company_user.id)], limit=1)
for value in values:
if 'location_id' not in value:
value['location_id'] = warehouse.lot_stock_id.id
return super()._load_records_create(values)
def _load_records_write(self, values):
""" Only allowed fields should be modified """
self = self.with_context(inventory_mode=True)
allowed_fields = self._get_inventory_fields_write()
for field in values.keys():
if field not in allowed_fields:
raise UserError(_("Changing %s is restricted, you can't do this operation.") % (field))
return super()._load_records_write(values)
@api.model
def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True):
""" Override to set the `inventory_quantity` field if we're in "inventory mode" as well
as to compute the sum of the `available_quantity` field.
"""
if 'available_quantity' in fields:
if 'quantity' not in fields:
fields.append('quantity')
if 'reserved_quantity' not in fields:
fields.append('reserved_quantity')
if 'inventory_quantity_auto_apply' in fields and 'quantity' not in fields:
fields.append('quantity')
result = super(StockQuant, self).read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy)
for group in result:
if self.env.context.get('inventory_report_mode'):
group['inventory_quantity'] = False
if 'available_quantity' in fields:
group['available_quantity'] = group['quantity'] - group['reserved_quantity']
if 'inventory_quantity_auto_apply' in fields:
group['inventory_quantity_auto_apply'] = group['quantity']
return result
def write(self, vals):
""" Override to handle the "inventory mode" and create the inventory move. """
allowed_fields = self._get_inventory_fields_write()
if self._is_inventory_mode() and any(field for field in allowed_fields if field in vals.keys()):
if any(quant.location_id.usage == 'inventory' for quant in self):
# Do nothing when user tries to modify manually a inventory loss
return
if any(field for field in vals.keys() if field not in allowed_fields):
raise UserError(_("Quant's editing is restricted, you can't do this operation."))
self = self.sudo()
return super(StockQuant, self).write(vals)
@api.ondelete(at_uninstall=False)
def _unlink_except_wrong_permission(self):
if not self.env.is_superuser():
if not self.user_has_groups('stock.group_stock_manager'):
raise UserError(_("Quants are auto-deleted when appropriate. If you must manually delete them, please ask a stock manager to do it."))
self = self.with_context(inventory_mode=True)
self.inventory_quantity = 0
self._apply_inventory()
def action_view_stock_moves(self):
self.ensure_one()
action = self.env["ir.actions.actions"]._for_xml_id("stock.stock_move_line_action")
action['domain'] = [
('product_id', '=', self.product_id.id),
'|',
('location_id', '=', self.location_id.id),
('location_dest_id', '=', self.location_id.id),
('lot_id', '=', self.lot_id.id),
'|',
('package_id', '=', self.package_id.id),
('result_package_id', '=', self.package_id.id),
]
return action
@api.model
def action_view_quants(self):
self = self.with_context(search_default_internal_loc=1)
self = self._set_view_context()
return self._get_quants_action(extend=True)
@api.model
def action_view_inventory(self):
""" Similar to _get_quants_action except specific for inventory adjustments (i.e. inventory counts). """
self = self._set_view_context()
self._quant_tasks()
ctx = dict(self.env.context or {})
ctx['no_at_date'] = True
if self.user_has_groups('stock.group_stock_user') and not self.user_has_groups('stock.group_stock_manager'):
ctx['search_default_my_count'] = True
action = {
'name': _('Inventory Adjustments'),
'view_mode': 'list',
'view_id': self.env.ref('stock.view_stock_quant_tree_inventory_editable').id,
'res_model': 'stock.quant',
'type': 'ir.actions.act_window',
'context': ctx,
'domain': [('location_id.usage', 'in', ['internal', 'transit'])],
'help': """
<p class="o_view_nocontent_smiling_face">
{}
</p><p>
{} <span class="fa fa-long-arrow-right"/> {}</p>
""".format(_('Your stock is currently empty'),
_('Press the CREATE button to define quantity for each product in your stock or import them from a spreadsheet throughout Favorites'),
_('Import')),
}
return action
def action_apply_inventory(self):
products_tracked_without_lot = []
for quant in self:
rounding = quant.product_uom_id.rounding
if fields.Float.is_zero(quant.inventory_diff_quantity, precision_rounding=rounding)\
and fields.Float.is_zero(quant.inventory_quantity, precision_rounding=rounding)\
and fields.Float.is_zero(quant.quantity, precision_rounding=rounding):
continue
if quant.product_id.tracking in ['lot', 'serial'] and\
not quant.lot_id and quant.inventory_quantity != quant.quantity:
products_tracked_without_lot.append(quant.product_id.id)
# for some reason if multi-record, env.context doesn't pass to wizards...
ctx = dict(self.env.context or {})
ctx['default_quant_ids'] = self.ids
quants_outdated = self.filtered(lambda quant: quant.is_outdated)
if quants_outdated:
ctx['default_quant_to_fix_ids'] = quants_outdated.ids
return {
'name': _('Conflict in Inventory Adjustment'),
'type': 'ir.actions.act_window',
'view_mode': 'form',
'views': [(False, 'form')],
'res_model': 'stock.inventory.conflict',
'target': 'new',
'context': ctx,
}
if products_tracked_without_lot:
ctx['default_product_ids'] = products_tracked_without_lot
return {
'name': _('Tracked Products in Inventory Adjustment'),
'type': 'ir.actions.act_window',
'view_mode': 'form',
'views': [(False, 'form')],
'res_model': 'stock.track.confirmation',
'target': 'new',
'context': ctx,
}
self._apply_inventory()
self.inventory_quantity_set = False
def action_inventory_history(self):
self.ensure_one()
action = {
'name': _('History'),
'view_mode': 'list,form',
'res_model': 'stock.move.line',
'views': [(self.env.ref('stock.view_move_line_tree').id, 'list'), (False, 'form')],
'type': 'ir.actions.act_window',
'context': {
'search_default_inventory': 1,
'search_default_done': 1,
},
'domain': [
('product_id', '=', self.product_id.id),
('company_id', '=', self.company_id.id),
'|',
('location_id', '=', self.location_id.id),
('location_dest_id', '=', self.location_id.id),
],
}
if self.lot_id:
action['context']['search_default_lot_id'] = self.lot_id.id
if self.package_id:
action['context']['search_default_package_id'] = self.package_id.id
action['context']['search_default_result_package_id'] = self.package_id.id
if self.owner_id:
action['context']['search_default_owner_id'] = self.owner_id.id
return action
def action_set_inventory_quantity(self):
quants_already_set = self.filtered(lambda quant: quant.inventory_quantity_set)
if quants_already_set:
ctx = dict(self.env.context or {}, default_quant_ids=self.ids)
view = self.env.ref('stock.inventory_warning_set_view', False)
return {
'name': _('Quantities Already Set'),
'type': 'ir.actions.act_window',
'view_mode': 'form',
'views': [(view.id, 'form')],
'view_id': view.id,
'res_model': 'stock.inventory.warning',
'target': 'new',
'context': ctx,
}
for quant in self:
quant.inventory_quantity = quant.quantity
self.user_id = self.env.user.id
self.inventory_quantity_set = True
def action_reset(self):
ctx = dict(self.env.context or {}, default_quant_ids=self.ids)
view = self.env.ref('stock.inventory_warning_reset_view', False)
return {
'name': _('Quantities To Reset'),
'type': 'ir.actions.act_window',
'view_mode': 'form',
'views': [(view.id, 'form')],
'view_id': view.id,
'res_model': 'stock.inventory.warning',
'target': 'new',
'context': ctx,
}
def action_set_inventory_quantity_to_zero(self):
self.inventory_quantity = 0
self.inventory_diff_quantity = 0
self.inventory_quantity_set = False
@api.constrains('product_id')
def check_product_id(self):
if any(elem.product_id.type != 'product' for elem in self):
raise ValidationError(_('Quants cannot be created for consumables or services.'))
@api.constrains('quantity')
def check_quantity(self):
for quant in self:
if quant.location_id.usage != 'inventory' and quant.lot_id and quant.product_id.tracking == 'serial' \
and float_compare(abs(quant.quantity), 1, precision_rounding=quant.product_uom_id.rounding) > 0:
raise ValidationError(_('The serial number has already been assigned: \n Product: %s, Serial Number: %s') % (quant.product_id.display_name, quant.lot_id.name))
@api.constrains('location_id')
def check_location_id(self):
for quant in self:
if quant.location_id.usage == 'view':
raise ValidationError(_('You cannot take products from or deliver products to a location of type "view" (%s).') % quant.location_id.name)
@api.model
def _get_removal_strategy(self, product_id, location_id):
if product_id.categ_id.removal_strategy_id:
return product_id.categ_id.removal_strategy_id.method
loc = location_id
while loc:
if loc.removal_strategy_id:
return loc.removal_strategy_id.method
loc = loc.location_id
return 'fifo'
@api.model
def _get_removal_strategy_order(self, removal_strategy):
if removal_strategy == 'fifo':
return 'in_date ASC, id'
elif removal_strategy == 'lifo':
return 'in_date DESC, id DESC'
elif removal_strategy == 'closest':
return 'location_id ASC, id DESC'
raise UserError(_('Removal strategy %s not implemented.') % (removal_strategy,))
def _gather(self, product_id, location_id, lot_id=None, package_id=None, owner_id=None, strict=False):
removal_strategy = self._get_removal_strategy(product_id, location_id)
removal_strategy_order = self._get_removal_strategy_order(removal_strategy)
domain = [('product_id', '=', product_id.id)]
if not strict:
if lot_id:
domain = expression.AND([['|', ('lot_id', '=', lot_id.id), ('lot_id', '=', False)], domain])
if package_id:
domain = expression.AND([[('package_id', '=', package_id.id)], domain])
if owner_id:
domain = expression.AND([[('owner_id', '=', owner_id.id)], domain])
domain = expression.AND([[('location_id', 'child_of', location_id.id)], domain])
else:
domain = expression.AND([['|', ('lot_id', '=', lot_id.id), ('lot_id', '=', False)] if lot_id else [('lot_id', '=', False)], domain])
domain = expression.AND([[('package_id', '=', package_id and package_id.id or False)], domain])
domain = expression.AND([[('owner_id', '=', owner_id and owner_id.id or False)], domain])
domain = expression.AND([[('location_id', '=', location_id.id)], domain])
return self.search(domain, order=removal_strategy_order).sorted(lambda q: not q.lot_id)
@api.model
def _get_available_quantity(self, product_id, location_id, lot_id=None, package_id=None, owner_id=None, strict=False, allow_negative=False):
""" Return the available quantity, i.e. the sum of `quantity` minus the sum of
`reserved_quantity`, for the set of quants sharing the combination of `product_id,
location_id` if `strict` is set to False or sharing the *exact same characteristics*
otherwise.
This method is called in the following usecases:
- when a stock move checks its availability
- when a stock move actually assign
- when editing a move line, to check if the new value is forced or not
- when validating a move line with some forced values and have to potentially unlink an
equivalent move line in another picking
In the two first usecases, `strict` should be set to `False`, as we don't know what exact
quants we'll reserve, and the characteristics are meaningless in this context.
In the last ones, `strict` should be set to `True`, as we work on a specific set of
characteristics.
:return: available quantity as a float
"""
self = self.sudo()
quants = self._gather(product_id, location_id, lot_id=lot_id, package_id=package_id, owner_id=owner_id, strict=strict)
rounding = product_id.uom_id.rounding
if product_id.tracking == 'none':
available_quantity = sum(quants.mapped('quantity')) - sum(quants.mapped('reserved_quantity'))
if allow_negative:
return available_quantity
else:
return available_quantity if float_compare(available_quantity, 0.0, precision_rounding=rounding) >= 0.0 else 0.0
else:
availaible_quantities = {lot_id: 0.0 for lot_id in list(set(quants.mapped('lot_id'))) + ['untracked']}
for quant in quants:
if not quant.lot_id:
availaible_quantities['untracked'] += quant.quantity - quant.reserved_quantity
else:
availaible_quantities[quant.lot_id] += quant.quantity - quant.reserved_quantity
if allow_negative:
return sum(availaible_quantities.values())
else:
return sum([available_quantity for available_quantity in availaible_quantities.values() if float_compare(available_quantity, 0, precision_rounding=rounding) > 0])
@api.onchange('location_id', 'product_id', 'lot_id', 'package_id', 'owner_id')
def _onchange_location_or_product_id(self):
vals = {}
# Once the new line is complete, fetch the new theoretical values.
if self.product_id and self.location_id:
# Sanity check if a lot has been set.
if self.lot_id:
if self.tracking == 'none' or self.product_id != self.lot_id.product_id:
vals['lot_id'] = None
quant = self._gather(
self.product_id, self.location_id, lot_id=self.lot_id,
package_id=self.package_id, owner_id=self.owner_id, strict=True)
if quant:
self.quantity = quant.filtered(lambda q: q.lot_id == self.lot_id).quantity
# Special case: directly set the quantity to one for serial numbers,
# it'll trigger `inventory_quantity` compute.
if self.lot_id and self.tracking == 'serial':
vals['inventory_quantity'] = 1
vals['inventory_quantity_auto_apply'] = 1
if vals:
self.update(vals)
@api.onchange('inventory_quantity')
def _onchange_inventory_quantity(self):
if self.location_id and self.location_id.usage == 'inventory':
warning = {
'title': _('You cannot modify inventory loss quantity'),
'message': _(
'Editing quantities in an Inventory Adjustment location is forbidden,'
'those locations are used as counterpart when correcting the quantities.'
)
}
return {'warning': warning}
@api.onchange('lot_id')
def _onchange_serial_number(self):
if self.lot_id and self.product_id.tracking == 'serial':
message, dummy = self.env['stock.quant']._check_serial_number(self.product_id,
self.lot_id,
self.company_id)
if message:
return {'warning': {'title': _('Warning'), 'message': message}}
@api.onchange('product_id', 'company_id')
def _onchange_product_id(self):
if self.location_id:
return
if self.product_id.tracking in ['lot', 'serial']:
previous_quants = self.env['stock.quant'].search([
('product_id', '=', self.product_id.id),
('location_id.usage', 'in', ['internal', 'transit'])], limit=1, order='create_date desc')
if previous_quants:
self.location_id = previous_quants.location_id
if not self.location_id:
company_id = self.company_id and self.company_id.id or self.env.company.id
self.location_id = self.env['stock.warehouse'].search(
[('company_id', '=', company_id)], limit=1).in_type_id.default_location_dest_id
def _apply_inventory(self):
move_vals = []
if not self.user_has_groups('stock.group_stock_manager'):
raise UserError(_('Only a stock manager can validate an inventory adjustment.'))
for quant in self:
# Create and validate a move so that the quant matches its `inventory_quantity`.
if float_compare(quant.inventory_diff_quantity, 0, precision_rounding=quant.product_uom_id.rounding) > 0:
move_vals.append(
quant._get_inventory_move_values(quant.inventory_diff_quantity,
quant.product_id.with_company(quant.company_id).property_stock_inventory,
quant.location_id))
else:
move_vals.append(
quant._get_inventory_move_values(-quant.inventory_diff_quantity,
quant.location_id,
quant.product_id.with_company(quant.company_id).property_stock_inventory,
out=True))
moves = self.env['stock.move'].with_context(inventory_mode=False).create(move_vals)
moves._action_done()
self.location_id.write({'last_inventory_date': fields.Date.today()})
date_by_location = {loc: loc._get_next_inventory_date() for loc in self.mapped('location_id')}
for quant in self:
quant.inventory_date = date_by_location[quant.location_id]
self.write({'inventory_quantity': 0, 'user_id': False})
self.write({'inventory_diff_quantity': 0})
@api.model
def _update_available_quantity(self, product_id, location_id, quantity, lot_id=None, package_id=None, owner_id=None, in_date=None):
""" Increase or decrease `reserved_quantity` of a set of quants for a given set of
product_id/location_id/lot_id/package_id/owner_id.
:param product_id:
:param location_id:
:param quantity:
:param lot_id:
:param package_id:
:param owner_id:
:param datetime in_date: Should only be passed when calls to this method are done in
order to move a quant. When creating a tracked quant, the
current datetime will be used.
:return: tuple (available_quantity, in_date as a datetime)
"""
self = self.sudo()
quants = self._gather(product_id, location_id, lot_id=lot_id, package_id=package_id, owner_id=owner_id, strict=True)
if lot_id and quantity > 0:
quants = quants.filtered(lambda q: q.lot_id)
if location_id.should_bypass_reservation():
incoming_dates = []
else:
incoming_dates = [quant.in_date for quant in quants if quant.in_date and
float_compare(quant.quantity, 0, precision_rounding=quant.product_uom_id.rounding) > 0]
if in_date:
incoming_dates += [in_date]
# If multiple incoming dates are available for a given lot_id/package_id/owner_id, we
# consider only the oldest one as being relevant.
if incoming_dates:
in_date = min(incoming_dates)
else:
in_date = fields.Datetime.now()
quant = None
if quants:
# see _acquire_one_job for explanations
self._cr.execute("SELECT id FROM stock_quant WHERE id IN %s ORDER BY lot_id LIMIT 1 FOR NO KEY UPDATE SKIP LOCKED", [tuple(quants.ids)])
stock_quant_result = self._cr.fetchone()
if stock_quant_result:
quant = self.browse(stock_quant_result[0])
if quant:
quant.write({
'quantity': quant.quantity + quantity,
'in_date': in_date,
})
else:
self.create({
'product_id': product_id.id,
'location_id': location_id.id,
'quantity': quantity,
'lot_id': lot_id and lot_id.id,
'package_id': package_id and package_id.id,
'owner_id': owner_id and owner_id.id,
'in_date': in_date,
})
return self._get_available_quantity(product_id, location_id, lot_id=lot_id, package_id=package_id, owner_id=owner_id, strict=False, allow_negative=True), in_date
@api.model
def _update_reserved_quantity(self, product_id, location_id, quantity, lot_id=None, package_id=None, owner_id=None, strict=False):
""" Increase the reserved quantity, i.e. increase `reserved_quantity` for the set of quants
sharing the combination of `product_id, location_id` if `strict` is set to False or sharing
the *exact same characteristics* otherwise. Typically, this method is called when reserving
a move or updating a reserved move line. When reserving a chained move, the strict flag
should be enabled (to reserve exactly what was brought). When the move is MTS,it could take
anything from the stock, so we disable the flag. When editing a move line, we naturally
enable the flag, to reflect the reservation according to the edition.
:return: a list of tuples (quant, quantity_reserved) showing on which quant the reservation
was done and how much the system was able to reserve on it
"""
self = self.sudo()
rounding = product_id.uom_id.rounding
quants = self._gather(product_id, location_id, lot_id=lot_id, package_id=package_id, owner_id=owner_id, strict=strict)
reserved_quants = []
if float_compare(quantity, 0, precision_rounding=rounding) > 0:
# if we want to reserve
available_quantity = sum(quants.filtered(lambda q: float_compare(q.quantity, 0, precision_rounding=rounding) > 0).mapped('quantity')) - sum(quants.mapped('reserved_quantity'))
if float_compare(quantity, available_quantity, precision_rounding=rounding) > 0:
raise UserError(_('It is not possible to reserve more products of %s than you have in stock.', product_id.display_name))
elif float_compare(quantity, 0, precision_rounding=rounding) < 0:
# if we want to unreserve
available_quantity = sum(quants.mapped('reserved_quantity'))
if float_compare(abs(quantity), available_quantity, precision_rounding=rounding) > 0:
raise UserError(_('It is not possible to unreserve more products of %s than you have in stock.', product_id.display_name))
else:
return reserved_quants
for quant in quants:
if float_compare(quantity, 0, precision_rounding=rounding) > 0:
max_quantity_on_quant = quant.quantity - quant.reserved_quantity
if float_compare(max_quantity_on_quant, 0, precision_rounding=rounding) <= 0:
continue
max_quantity_on_quant = min(max_quantity_on_quant, quantity)
quant.reserved_quantity += max_quantity_on_quant
reserved_quants.append((quant, max_quantity_on_quant))
quantity -= max_quantity_on_quant
available_quantity -= max_quantity_on_quant
else:
max_quantity_on_quant = min(quant.reserved_quantity, abs(quantity))
quant.reserved_quantity -= max_quantity_on_quant
reserved_quants.append((quant, -max_quantity_on_quant))
quantity += max_quantity_on_quant
available_quantity += max_quantity_on_quant
if float_is_zero(quantity, precision_rounding=rounding) or float_is_zero(available_quantity, precision_rounding=rounding):
break
return reserved_quants
@api.model
def _unlink_zero_quants(self):
""" _update_available_quantity may leave quants with no
quantity and no reserved_quantity. It used to directly unlink
these zero quants but this proved to hurt the performance as
this method is often called in batch and each unlink invalidate
the cache. We defer the calls to unlink in this method.
"""
precision_digits = max(6, self.sudo().env.ref('product.decimal_product_uom').digits * 2)
# Use a select instead of ORM search for UoM robustness.
query = """SELECT id FROM stock_quant WHERE (round(quantity::numeric, %s) = 0 OR quantity IS NULL)
AND round(reserved_quantity::numeric, %s) = 0
AND (round(inventory_quantity::numeric, %s) = 0 OR inventory_quantity IS NULL)
AND user_id IS NULL;"""
params = (precision_digits, precision_digits, precision_digits)
self.env.cr.execute(query, params)
quant_ids = self.env['stock.quant'].browse([quant['id'] for quant in self.env.cr.dictfetchall()])
quant_ids.sudo().unlink()
@api.model
def _merge_quants(self):
""" In a situation where one transaction is updating a quant via
`_update_available_quantity` and another concurrent one calls this function with the same
argument, we’ll create a new quant in order for these transactions to not rollback. This
method will find and deduplicate these quants.
"""
query = """WITH
dupes AS (
SELECT min(id) as to_update_quant_id,
(array_agg(id ORDER BY id))[2:array_length(array_agg(id), 1)] as to_delete_quant_ids,
SUM(reserved_quantity) as reserved_quantity,
SUM(inventory_quantity) as inventory_quantity,
SUM(quantity) as quantity,
MIN(in_date) as in_date
FROM stock_quant
GROUP BY product_id, company_id, location_id, lot_id, package_id, owner_id
HAVING count(id) > 1
),
_up AS (
UPDATE stock_quant q
SET quantity = d.quantity,
reserved_quantity = d.reserved_quantity,
inventory_quantity = d.inventory_quantity,
in_date = d.in_date
FROM dupes d
WHERE d.to_update_quant_id = q.id
)
DELETE FROM stock_quant WHERE id in (SELECT unnest(to_delete_quant_ids) from dupes)
"""
try:
with self.env.cr.savepoint():
self.env.cr.execute(query)
self.invalidate_cache()
except Error as e:
_logger.info('an error occurred while merging quants: %s', e.pgerror)
@api.model
def _quant_tasks(self):
self._merge_quants()
self._unlink_zero_quants()
@api.model
def _is_inventory_mode(self):
""" Used to control whether a quant was written on or created during an
"inventory session", meaning a mode where we need to create the stock.move
record necessary to be consistent with the `inventory_quantity` field.
"""
return self.env.context.get('inventory_mode') and self.user_has_groups('stock.group_stock_user')
@api.model
def _get_inventory_fields_create(self):
""" Returns a list of fields user can edit when he want to create a quant in `inventory_mode`.
"""
return ['product_id', 'location_id', 'lot_id', 'package_id', 'owner_id'] + self._get_inventory_fields_write()
@api.model
def _get_inventory_fields_write(self):
""" Returns a list of fields user can edit when he want to edit a quant in `inventory_mode`.
"""
fields = ['inventory_quantity', 'inventory_quantity_auto_apply', 'inventory_diff_quantity',
'inventory_date', 'user_id', 'inventory_quantity_set', 'is_outdated']
return fields
def _get_inventory_move_values(self, qty, location_id, location_dest_id, out=False):
""" Called when user manually set a new quantity (via `inventory_quantity`)
just before creating the corresponding stock move.
:param location_id: `stock.location`
:param location_dest_id: `stock.location`
:param out: boolean to set on True when the move go to inventory adjustment location.
:return: dict with all values needed to create a new `stock.move` with its move line.
"""
self.ensure_one()
if fields.Float.is_zero(qty, 0, precision_rounding=self.product_uom_id.rounding):
name = _('Product Quantity Confirmed')
else:
name = _('Product Quantity Updated')
return {
'name': self.env.context.get('inventory_name') or name,
'product_id': self.product_id.id,
'product_uom': self.product_uom_id.id,
'product_uom_qty': qty,
'company_id': self.company_id.id or self.env.company.id,
'state': 'confirmed',
'location_id': location_id.id,
'location_dest_id': location_dest_id.id,
'is_inventory': True,
'move_line_ids': [(0, 0, {
'product_id': self.product_id.id,
'product_uom_id': self.product_uom_id.id,
'qty_done': qty,
'location_id': location_id.id,
'location_dest_id': location_dest_id.id,
'company_id': self.company_id.id or self.env.company.id,
'lot_id': self.lot_id.id,
'package_id': out and self.package_id.id or False,
'result_package_id': (not out) and self.package_id.id or False,
'owner_id': self.owner_id.id,
})]
}
def _set_view_context(self):
""" Adds context when opening quants related views. """
if not self.user_has_groups('stock.group_stock_multi_locations'):
company_user = self.env.company
warehouse = self.env['stock.warehouse'].search([('company_id', '=', company_user.id)], limit=1)
if warehouse:
self = self.with_context(default_location_id=warehouse.lot_stock_id.id, hide_location=True)
# If user have rights to write on quant, we set quants in inventory mode.
if self.user_has_groups('stock.group_stock_user'):
self = self.with_context(inventory_mode=True)
return self
@api.model
def _get_quants_action(self, domain=None, extend=False):
""" Returns an action to open (non-inventory adjustment) quant view.
Depending of the context (user have right to be inventory mode or not),
the list view will be editable or readonly.
:param domain: List for the domain, empty by default.
:param extend: If True, enables form, graph and pivot views. False by default.
"""
if not self.env['ir.config_parameter'].sudo().get_param('stock.skip_quant_tasks'):
self._quant_tasks()
ctx = dict(self.env.context or {})
ctx['inventory_report_mode'] = True
ctx.pop('group_by', None)
action = {
'name': _('Stock On Hand'),
'view_type': 'tree',
'view_mode': 'list,form',
'res_model': 'stock.quant',
'type': 'ir.actions.act_window',
'context': ctx,
'domain': domain or [],
'help': """
<p class="o_view_nocontent_empty_folder">{}</p>
<p>{}</p>
""".format(_('No Stock On Hand'),
_('This analysis gives you an overview of the current stock level of your products.')),
}
target_action = self.env.ref('stock.dashboard_open_quants', False)
if target_action:
action['id'] = target_action.id
form_view = self.env.ref('stock.view_stock_quant_form_editable').id
if self.env.context.get('inventory_mode') and self.user_has_groups('stock.group_stock_manager'):
action['view_id'] = self.env.ref('stock.view_stock_quant_tree_editable').id
else:
action['view_id'] = self.env.ref('stock.view_stock_quant_tree').id
action.update({
'views': [
(action['view_id'], 'list'),
(form_view, 'form'),
],
})
if extend:
action.update({
'view_mode': 'tree,form,pivot,graph',
'views': [
(action['view_id'], 'list'),
(form_view, 'form'),
(self.env.ref('stock.view_stock_quant_pivot').id, 'pivot'),
(self.env.ref('stock.stock_quant_view_graph').id, 'graph'),
],
})
return action
@api.model
def _check_serial_number(self, product_id, lot_id, company_id, source_location_id=None, ref_doc_location_id=None):
""" Checks for duplicate serial numbers (SN) when assigning a SN (i.e. no source_location_id)
and checks for potential incorrect location selection of a SN when using a SN (i.e.
source_location_id). Returns warning message of all locations the SN is located at and
(optionally) a recommended source location of the SN (when using SN from incorrect location).
This function is designed to be used by onchange functions across differing situations including,
but not limited to scrap, incoming picking SN encoding, and outgoing picking SN selection.
:param product_id: `product.product` product to check SN for
:param lot_id: `stock.production.lot` SN to check
:param company_id: `res.company` company to check against (i.e. we ignore duplicate SNs across
different companies)
:param source_location_id: `stock.location` optional source location if using the SN rather
than assigning it
:param ref_doc_location_id: `stock.location` optional reference document location for
determining recommended location. This is param expected to only be used when a
`source_location_id` is provided.
:return: tuple(message, recommended_location) If not None, message is a string expected to be
used in warning message dict and recommended_location is a `location_id`
"""
message = None
recommended_location = None
if product_id.tracking == 'serial':
quants = self.env['stock.quant'].search([('product_id', '=', product_id.id),
('lot_id', '=', lot_id.id),
('quantity', '!=', 0),
'|', ('location_id.usage', '=', 'customer'),
'&', ('company_id', '=', company_id.id),
('location_id.usage', 'in', ('internal', 'transit'))])
sn_locations = quants.mapped('location_id')
if quants:
if not source_location_id:
# trying to assign an already existing SN
message = _('The Serial Number (%s) is already used in these location(s): %s.\n\n'
'Is this expected? For example this can occur if a delivery operation is validated '
'before its corresponding receipt operation is validated. In this case the issue will be solved '
'automatically once all steps are completed. Otherwise, the serial number should be corrected to '
'prevent inconsistent data.',
lot_id.name, ', '.join(sn_locations.mapped('display_name')))
elif source_location_id and source_location_id not in sn_locations:
# using an existing SN in the wrong location
recommended_location = self.env['stock.location']
if ref_doc_location_id:
for location in sn_locations:
if ref_doc_location_id.parent_path in location.parent_path:
recommended_location = location
break
else:
for location in sn_locations:
if location.usage != 'customer':
recommended_location = location
break
if recommended_location:
message = _('Serial number (%s) is not located in %s, but is located in location(s): %s.\n\n'
'Source location for this move will be changed to %s',
lot_id.name, source_location_id.display_name, ', '.join(sn_locations.mapped('display_name')), recommended_location.display_name)
else:
message = _('Serial number (%s) is not located in %s, but is located in location(s): %s.\n\n'
'Please correct this to prevent inconsistent data.',
lot_id.name, source_location_id.display_name, ', '.join(sn_locations.mapped('display_name')))
return message, recommended_location
class QuantPackage(models.Model):
""" Packages containing quants and/or other packages """
_name = "stock.quant.package"
_description = "Packages"
_order = 'name'
name = fields.Char(
'Package Reference', copy=False, index=True, required=True,
default=lambda self: self.env['ir.sequence'].next_by_code('stock.quant.package') or _('Unknown Pack'))
quant_ids = fields.One2many('stock.quant', 'package_id', 'Bulk Content', readonly=True,
domain=['|', ('quantity', '!=', 0), ('reserved_quantity', '!=', 0)])
package_type_id = fields.Many2one(
'stock.package.type', 'Package Type', index=True)
location_id = fields.Many2one(
'stock.location', 'Location', compute='_compute_package_info',
index=True, readonly=True, store=True)
company_id = fields.Many2one(
'res.company', 'Company', compute='_compute_package_info',
index=True, readonly=True, store=True)
owner_id = fields.Many2one(
'res.partner', 'Owner', compute='_compute_package_info', search='_search_owner',
index=True, readonly=True, compute_sudo=True)
package_use = fields.Selection([
('disposable', 'Disposable Box'),
('reusable', 'Reusable Box'),
], string='Package Use', default='disposable', required=True,
help="""Reusable boxes are used for batch picking and emptied afterwards to be reused. In the barcode application, scanning a reusable box will add the products in this box.
Disposable boxes aren't reused, when scanning a disposable box in the barcode application, the contained products are added to the transfer.""")
@api.depends('quant_ids.package_id', 'quant_ids.location_id', 'quant_ids.company_id', 'quant_ids.owner_id', 'quant_ids.quantity', 'quant_ids.reserved_quantity')
def _compute_package_info(self):
for package in self:
values = {'location_id': False, 'owner_id': False}
if package.quant_ids:
values['location_id'] = package.quant_ids[0].location_id
if all(q.owner_id == package.quant_ids[0].owner_id for q in package.quant_ids):
values['owner_id'] = package.quant_ids[0].owner_id
if all(q.company_id == package.quant_ids[0].company_id for q in package.quant_ids):
values['company_id'] = package.quant_ids[0].company_id
package.location_id = values['location_id']
package.company_id = values.get('company_id')
package.owner_id = values['owner_id']
def _search_owner(self, operator, value):
if value:
packs = self.search([('quant_ids.owner_id', operator, value)])
else:
packs = self.search([('quant_ids', operator, value)])
if packs:
return [('id', 'in', packs.ids)]
else:
return [('id', '=', False)]
def unpack(self):
for package in self:
move_line_to_modify = self.env['stock.move.line'].search([
('package_id', '=', package.id),
('state', 'in', ('assigned', 'partially_available')),
('product_qty', '!=', 0),
])
move_line_to_modify.write({'package_id': False})
package.mapped('quant_ids').sudo().write({'package_id': False})
# Quant clean-up, mostly to avoid multiple quants of the same product. For example, unpack
# 2 packages of 50, then reserve 100 => a quant of -50 is created at transfer validation.
self.env['stock.quant']._quant_tasks()
def action_view_picking(self):
action = self.env["ir.actions.actions"]._for_xml_id("stock.action_picking_tree_all")
domain = ['|', ('result_package_id', 'in', self.ids), ('package_id', 'in', self.ids)]
pickings = self.env['stock.move.line'].search(domain).mapped('picking_id')
action['domain'] = [('id', 'in', pickings.ids)]
return action
def _get_contained_quants(self):
return self.env['stock.quant'].search([('package_id', 'in', self.ids)])
| 51.648547
| 55,109
|
11,453
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from itertools import groupby
from operator import itemgetter
from collections import defaultdict
from odoo import _, api, fields, models
from odoo.tools.float_utils import float_is_zero
class StockPackageLevel(models.Model):
_name = 'stock.package_level'
_description = 'Stock Package Level'
_check_company_auto = True
package_id = fields.Many2one(
'stock.quant.package', 'Package', required=True, check_company=True,
domain="[('location_id', 'child_of', parent.location_id), '|', ('company_id', '=', False), ('company_id', '=', company_id)]")
picking_id = fields.Many2one('stock.picking', 'Picking', check_company=True)
move_ids = fields.One2many('stock.move', 'package_level_id')
move_line_ids = fields.One2many('stock.move.line', 'package_level_id')
location_id = fields.Many2one('stock.location', 'From', compute='_compute_location_id', check_company=True)
location_dest_id = fields.Many2one(
'stock.location', 'To', check_company=True,
domain="[('id', 'child_of', parent.location_dest_id), '|', ('company_id', '=', False), ('company_id', '=', company_id)]")
is_done = fields.Boolean('Done', compute='_compute_is_done', inverse='_set_is_done')
state = fields.Selection([
('draft', 'Draft'),
('confirmed', 'Confirmed'),
('assigned', 'Reserved'),
('new', 'New'),
('done', 'Done'),
('cancel', 'Cancelled'),
],string='State', compute='_compute_state')
is_fresh_package = fields.Boolean(compute='_compute_fresh_pack')
picking_type_code = fields.Selection(related='picking_id.picking_type_code')
show_lots_m2o = fields.Boolean(compute='_compute_show_lot')
show_lots_text = fields.Boolean(compute='_compute_show_lot')
company_id = fields.Many2one('res.company', 'Company', required=True, index=True)
@api.depends('move_line_ids', 'move_line_ids.qty_done')
def _compute_is_done(self):
for package_level in self:
# If it is an existing package
if package_level.is_fresh_package:
package_level.is_done = True
else:
package_level.is_done = package_level._check_move_lines_map_quant_package(package_level.package_id)
def _set_is_done(self):
for package_level in self:
if package_level.is_done:
if not package_level.is_fresh_package:
ml_update_dict = defaultdict(float)
for quant in package_level.package_id.quant_ids:
corresponding_mls = package_level.move_line_ids.filtered(lambda ml: ml.product_id == quant.product_id and ml.lot_id == quant.lot_id)
to_dispatch = quant.quantity
if corresponding_mls:
for ml in corresponding_mls:
qty = min(to_dispatch, ml.product_qty) if len(corresponding_mls) > 1 else to_dispatch
to_dispatch = to_dispatch - qty
ml_update_dict[ml] += qty
if float_is_zero(to_dispatch, precision_rounding=ml.product_uom_id.rounding):
break
else:
corresponding_move = package_level.move_ids.filtered(lambda m: m.product_id == quant.product_id)[:1]
self.env['stock.move.line'].create({
'location_id': package_level.location_id.id,
'location_dest_id': package_level.location_dest_id.id,
'picking_id': package_level.picking_id.id,
'product_id': quant.product_id.id,
'qty_done': quant.quantity,
'product_uom_id': quant.product_id.uom_id.id,
'lot_id': quant.lot_id.id,
'package_id': package_level.package_id.id,
'result_package_id': package_level.package_id.id,
'package_level_id': package_level.id,
'move_id': corresponding_move.id,
'owner_id': quant.owner_id.id,
})
for rec, quant in ml_update_dict.items():
rec.qty_done = quant
else:
package_level.move_line_ids.filtered(lambda ml: ml.product_qty == 0).unlink()
package_level.move_line_ids.filtered(lambda ml: ml.product_qty != 0).write({'qty_done': 0})
@api.depends('move_line_ids', 'move_line_ids.package_id', 'move_line_ids.result_package_id')
def _compute_fresh_pack(self):
for package_level in self:
if not package_level.move_line_ids or all(ml.package_id and ml.package_id == ml.result_package_id for ml in package_level.move_line_ids):
package_level.is_fresh_package = False
else:
package_level.is_fresh_package = True
@api.depends('move_ids', 'move_ids.state', 'move_line_ids', 'move_line_ids.state')
def _compute_state(self):
for package_level in self:
if not package_level.move_ids and not package_level.move_line_ids:
package_level.state = 'draft'
elif not package_level.move_line_ids and package_level.move_ids.filtered(lambda m: m.state not in ('done', 'cancel')):
package_level.state = 'confirmed'
elif package_level.move_line_ids and not package_level.move_line_ids.filtered(lambda ml: ml.state in ('done', 'cancel')):
if package_level.is_fresh_package:
package_level.state = 'new'
elif package_level._check_move_lines_map_quant_package(package_level.package_id, 'product_uom_qty'):
package_level.state = 'assigned'
else:
package_level.state = 'confirmed'
elif package_level.move_line_ids.filtered(lambda ml: ml.state =='done'):
package_level.state = 'done'
elif package_level.move_line_ids.filtered(lambda ml: ml.state == 'cancel') or package_level.move_ids.filtered(lambda m: m.state == 'cancel'):
package_level.state = 'cancel'
else:
package_level.state = 'draft'
def _compute_show_lot(self):
for package_level in self:
if any(ml.product_id.tracking != 'none' for ml in package_level.move_line_ids):
if package_level.picking_id.picking_type_id.use_existing_lots or package_level.state == 'done':
package_level.show_lots_m2o = True
package_level.show_lots_text = False
else:
if self.picking_id.picking_type_id.use_create_lots and package_level.state != 'done':
package_level.show_lots_m2o = False
package_level.show_lots_text = True
else:
package_level.show_lots_m2o = False
package_level.show_lots_text = False
else:
package_level.show_lots_m2o = False
package_level.show_lots_text = False
def _generate_moves(self):
for package_level in self:
if package_level.package_id:
for quant in package_level.package_id.quant_ids:
self.env['stock.move'].create({
'picking_id': package_level.picking_id.id,
'name': quant.product_id.display_name,
'product_id': quant.product_id.id,
'product_uom_qty': quant.quantity,
'product_uom': quant.product_id.uom_id.id,
'location_id': package_level.location_id.id,
'location_dest_id': package_level.location_dest_id.id,
'package_level_id': package_level.id,
'company_id': package_level.company_id.id,
})
@api.model
def create(self, vals):
result = super(StockPackageLevel, self).create(vals)
if vals.get('location_dest_id'):
result.mapped('move_line_ids').write({'location_dest_id': vals['location_dest_id']})
result.mapped('move_ids').write({'location_dest_id': vals['location_dest_id']})
return result
def write(self, vals):
result = super(StockPackageLevel, self).write(vals)
if vals.get('location_dest_id'):
self.mapped('move_line_ids').write({'location_dest_id': vals['location_dest_id']})
self.mapped('move_ids').write({'location_dest_id': vals['location_dest_id']})
return result
def unlink(self):
self.mapped('move_ids').write({'package_level_id': False})
self.mapped('move_line_ids').write({'result_package_id': False})
return super(StockPackageLevel, self).unlink()
def _check_move_lines_map_quant_package(self, package, field='qty_done'):
""" should compare in good uom """
all_in = True
pack_move_lines = self.move_line_ids
keys = ['product_id', 'lot_id']
def sorted_key(object):
object.ensure_one()
return [object.product_id.id, object.lot_id.id]
grouped_quants = {}
for k, g in groupby(sorted(package.quant_ids, key=sorted_key), key=itemgetter(*keys)):
grouped_quants[k] = sum(self.env['stock.quant'].concat(*list(g)).mapped('quantity'))
grouped_ops = {}
for k, g in groupby(sorted(pack_move_lines, key=sorted_key), key=itemgetter(*keys)):
grouped_ops[k] = sum(self.env['stock.move.line'].concat(*list(g)).mapped(field))
if any(grouped_quants.get(key, 0) - grouped_ops.get(key, 0) != 0 for key in grouped_quants) \
or any(grouped_ops.get(key, 0) - grouped_quants.get(key, 0) != 0 for key in grouped_ops):
all_in = False
return all_in
@api.depends('package_id', 'state', 'is_fresh_package', 'move_ids', 'move_line_ids')
def _compute_location_id(self):
for pl in self:
if pl.state == 'new' or pl.is_fresh_package:
pl.location_id = False
elif pl.state != 'done' and pl.package_id:
pl.location_id = pl.package_id.location_id
elif pl.state == 'confirmed' and pl.move_ids:
pl.location_id = pl.move_ids[0].location_id
elif pl.state in ('assigned', 'done') and pl.move_line_ids:
pl.location_id = pl.move_line_ids[0].location_id
else:
pl.location_id = pl.picking_id.location_id
def action_show_package_details(self):
self.ensure_one()
view = self.env.ref('stock.package_level_form_edit_view')
return {
'name': _('Package Content'),
'type': 'ir.actions.act_window',
'view_mode': 'form',
'res_model': 'stock.package_level',
'views': [(view.id, 'form')],
'view_id': view.id,
'target': 'new',
'res_id': self.id,
'flags': {'mode': 'readonly'},
}
| 51.823529
| 11,453
|
123,122
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import defaultdict
from datetime import timedelta
from itertools import groupby
from odoo.tools import groupby as groupbyelem
from operator import itemgetter
from odoo import _, api, Command, fields, models
from odoo.exceptions import UserError
from odoo.osv import expression
from odoo.tools.float_utils import float_compare, float_is_zero, float_round
from odoo.tools.misc import clean_context, OrderedSet
PROCUREMENT_PRIORITIES = [('0', 'Normal'), ('1', 'Urgent')]
class StockMove(models.Model):
_name = "stock.move"
_description = "Stock Move"
_order = 'sequence, id'
def _default_group_id(self):
if self.env.context.get('default_picking_id'):
return self.env['stock.picking'].browse(self.env.context['default_picking_id']).group_id.id
return False
name = fields.Char('Description', required=True)
sequence = fields.Integer('Sequence', default=10)
priority = fields.Selection(
PROCUREMENT_PRIORITIES, 'Priority', default='0',
compute="_compute_priority", store=True)
date = fields.Datetime(
'Date Scheduled', default=fields.Datetime.now, index=True, required=True,
help="Scheduled date until move is done, then date of actual move processing")
date_deadline = fields.Datetime(
"Deadline", readonly=True,
help="Date Promise to the customer on the top level document (SO/PO)")
company_id = fields.Many2one(
'res.company', 'Company',
default=lambda self: self.env.company,
index=True, required=True)
product_id = fields.Many2one(
'product.product', 'Product',
check_company=True,
domain="[('type', 'in', ['product', 'consu']), '|', ('company_id', '=', False), ('company_id', '=', company_id)]", index=True, required=True,
states={'done': [('readonly', True)]})
description_picking = fields.Text('Description of Picking')
product_qty = fields.Float(
'Real Quantity', compute='_compute_product_qty', inverse='_set_product_qty',
digits=0, store=True, compute_sudo=True,
help='Quantity in the default UoM of the product')
product_uom_qty = fields.Float(
'Demand',
digits='Product Unit of Measure',
default=1.0, required=True, states={'done': [('readonly', True)]},
help="This is the quantity of products from an inventory "
"point of view. For moves in the state 'done', this is the "
"quantity of products that were actually moved. For other "
"moves, this is the quantity of product that is planned to "
"be moved. Lowering this quantity does not generate a "
"backorder. Changing this quantity on assigned moves affects "
"the product reservation, and should be done with care.")
product_uom = fields.Many2one('uom.uom', "UoM", required=True, domain="[('category_id', '=', product_uom_category_id)]")
product_uom_category_id = fields.Many2one(related='product_id.uom_id.category_id')
# TDE FIXME: make it stored, otherwise group will not work
product_tmpl_id = fields.Many2one(
'product.template', 'Product Template',
related='product_id.product_tmpl_id',
help="Technical: used in views")
location_id = fields.Many2one(
'stock.location', 'Source Location',
auto_join=True, index=True, required=True,
check_company=True,
help="Sets a location if you produce at a fixed location. This can be a partner location if you subcontract the manufacturing operations.")
location_dest_id = fields.Many2one(
'stock.location', 'Destination Location',
auto_join=True, index=True, required=True,
check_company=True,
help="Location where the system will stock the finished products.")
partner_id = fields.Many2one(
'res.partner', 'Destination Address ',
states={'done': [('readonly', True)]},
help="Optional address where goods are to be delivered, specifically used for allotment")
move_dest_ids = fields.Many2many(
'stock.move', 'stock_move_move_rel', 'move_orig_id', 'move_dest_id', 'Destination Moves',
copy=False,
help="Optional: next stock move when chaining them")
move_orig_ids = fields.Many2many(
'stock.move', 'stock_move_move_rel', 'move_dest_id', 'move_orig_id', 'Original Move',
copy=False,
help="Optional: previous stock move when chaining them")
picking_id = fields.Many2one('stock.picking', 'Transfer', index=True, states={'done': [('readonly', True)]}, check_company=True)
state = fields.Selection([
('draft', 'New'), ('cancel', 'Cancelled'),
('waiting', 'Waiting Another Move'),
('confirmed', 'Waiting Availability'),
('partially_available', 'Partially Available'),
('assigned', 'Available'),
('done', 'Done')], string='Status',
copy=False, default='draft', index=True, readonly=True,
help="* New: When the stock move is created and not yet confirmed.\n"
"* Waiting Another Move: This state can be seen when a move is waiting for another one, for example in a chained flow.\n"
"* Waiting Availability: This state is reached when the procurement resolution is not straight forward. It may need the scheduler to run, a component to be manufactured...\n"
"* Available: When products are reserved, it is set to \'Available\'.\n"
"* Done: When the shipment is processed, the state is \'Done\'.")
price_unit = fields.Float(
'Unit Price', help="Technical field used to record the product cost set by the user during a picking confirmation (when costing "
"method used is 'average price' or 'real'). Value given in company currency and in product uom.", copy=False) # as it's a technical field, we intentionally don't provide the digits attribute
origin = fields.Char("Source Document")
procure_method = fields.Selection([
('make_to_stock', 'Default: Take From Stock'),
('make_to_order', 'Advanced: Apply Procurement Rules')], string='Supply Method',
default='make_to_stock', required=True, copy=False,
help="By default, the system will take from the stock in the source location and passively wait for availability. "
"The other possibility allows you to directly create a procurement on the source location (and thus ignore "
"its current stock) to gather products. If we want to chain moves and have this one to wait for the previous, "
"this second option should be chosen.")
scrapped = fields.Boolean('Scrapped', related='location_dest_id.scrap_location', readonly=True, store=True)
scrap_ids = fields.One2many('stock.scrap', 'move_id')
group_id = fields.Many2one('procurement.group', 'Procurement Group', default=_default_group_id, index=True)
rule_id = fields.Many2one(
'stock.rule', 'Stock Rule', ondelete='restrict', help='The stock rule that created this stock move',
check_company=True)
propagate_cancel = fields.Boolean(
'Propagate cancel and split', default=True,
help='If checked, when this move is cancelled, cancel the linked move too')
delay_alert_date = fields.Datetime('Delay Alert Date', help='Process at this date to be on time', compute="_compute_delay_alert_date", store=True)
picking_type_id = fields.Many2one('stock.picking.type', 'Operation Type', compute='_compute_picking_type_id', store=True, check_company=True)
is_inventory = fields.Boolean('Inventory')
move_line_ids = fields.One2many('stock.move.line', 'move_id')
move_line_nosuggest_ids = fields.One2many('stock.move.line', 'move_id', domain=['|', ('product_qty', '=', 0.0), ('qty_done', '!=', 0.0)])
origin_returned_move_id = fields.Many2one(
'stock.move', 'Origin return move', copy=False, index=True,
help='Move that created the return move', check_company=True)
returned_move_ids = fields.One2many('stock.move', 'origin_returned_move_id', 'All returned moves', help='Optional: all returned moves created from this move')
reserved_availability = fields.Float(
'Quantity Reserved', compute='_compute_reserved_availability',
digits='Product Unit of Measure',
readonly=True, help='Quantity that has already been reserved for this move')
availability = fields.Float(
'Forecasted Quantity', compute='_compute_product_availability',
readonly=True, help='Quantity in stock that can still be reserved for this move')
restrict_partner_id = fields.Many2one(
'res.partner', 'Owner ', help="Technical field used to depict a restriction on the ownership of quants to consider when marking this move as 'done'",
check_company=True)
route_ids = fields.Many2many(
'stock.location.route', 'stock_location_route_move', 'move_id', 'route_id', 'Destination route', help="Preferred route",
check_company=True)
warehouse_id = fields.Many2one('stock.warehouse', 'Warehouse', help="Technical field depicting the warehouse to consider for the route selection on the next procurement (if any).")
has_tracking = fields.Selection(related='product_id.tracking', string='Product with Tracking')
quantity_done = fields.Float('Quantity Done', compute='_quantity_done_compute', digits='Product Unit of Measure', inverse='_quantity_done_set')
show_operations = fields.Boolean(related='picking_id.picking_type_id.show_operations')
picking_code = fields.Selection(related='picking_id.picking_type_id.code', readonly=True)
show_details_visible = fields.Boolean('Details Visible', compute='_compute_show_details_visible')
show_reserved_availability = fields.Boolean('From Supplier', compute='_compute_show_reserved_availability')
product_type = fields.Selection(related='product_id.detailed_type', readonly=True)
additional = fields.Boolean("Whether the move was added after the picking's confirmation", default=False)
is_locked = fields.Boolean(compute='_compute_is_locked', readonly=True)
is_initial_demand_editable = fields.Boolean('Is initial demand editable', compute='_compute_is_initial_demand_editable')
is_quantity_done_editable = fields.Boolean('Is quantity done editable', compute='_compute_is_quantity_done_editable')
reference = fields.Char(compute='_compute_reference', string="Reference", store=True)
move_lines_count = fields.Integer(compute='_compute_move_lines_count')
package_level_id = fields.Many2one('stock.package_level', 'Package Level', check_company=True, copy=False)
picking_type_entire_packs = fields.Boolean(related='picking_type_id.show_entire_packs', readonly=True)
display_assign_serial = fields.Boolean(compute='_compute_display_assign_serial')
next_serial = fields.Char('First SN')
next_serial_count = fields.Integer('Number of SN')
orderpoint_id = fields.Many2one('stock.warehouse.orderpoint', 'Original Reordering Rule', check_company=True, index=True)
forecast_availability = fields.Float('Forecast Availability', compute='_compute_forecast_information', digits='Product Unit of Measure', compute_sudo=True)
forecast_expected_date = fields.Datetime('Forecasted Expected date', compute='_compute_forecast_information', compute_sudo=True)
lot_ids = fields.Many2many('stock.production.lot', compute='_compute_lot_ids', inverse='_set_lot_ids', string='Serial Numbers', readonly=False)
reservation_date = fields.Date('Date to Reserve', compute='_compute_reservation_date', store=True,
help="This is a technical field for calculating when a move should be reserved")
product_packaging_id = fields.Many2one('product.packaging', 'Packaging', domain="[('product_id', '=', product_id)]", check_company=True)
from_immediate_transfer = fields.Boolean(related="picking_id.immediate_transfer")
@api.depends('has_tracking', 'picking_type_id.use_create_lots', 'picking_type_id.use_existing_lots', 'state')
def _compute_display_assign_serial(self):
for move in self:
move.display_assign_serial = (
move.has_tracking == 'serial' and
move.state in ('partially_available', 'assigned', 'confirmed') and
move.picking_type_id.use_create_lots and
not move.picking_type_id.use_existing_lots
and not move.origin_returned_move_id.id
)
@api.depends('picking_id.priority')
def _compute_priority(self):
for move in self:
move.priority = move.picking_id.priority or '0'
@api.depends('picking_id.picking_type_id')
def _compute_picking_type_id(self):
for move in self:
if move.picking_id:
move.picking_type_id = move.picking_id.picking_type_id
@api.depends('picking_id.is_locked')
def _compute_is_locked(self):
for move in self:
if move.picking_id:
move.is_locked = move.picking_id.is_locked
else:
move.is_locked = False
@api.depends('product_id', 'has_tracking', 'move_line_ids')
def _compute_show_details_visible(self):
""" According to this field, the button that calls `action_show_details` will be displayed
to work on a move from its picking form view, or not.
"""
has_package = self.user_has_groups('stock.group_tracking_lot')
multi_locations_enabled = self.user_has_groups('stock.group_stock_multi_locations')
consignment_enabled = self.user_has_groups('stock.group_tracking_owner')
show_details_visible = multi_locations_enabled or has_package
for move in self:
if not move.product_id:
move.show_details_visible = False
elif len(move._get_move_lines()) > 1:
move.show_details_visible = True
else:
move.show_details_visible = (((consignment_enabled and move.picking_code != 'incoming') or
show_details_visible or move.has_tracking != 'none') and
move._show_details_in_draft() and
move.show_operations is False)
def _compute_show_reserved_availability(self):
""" This field is only of use in an attrs in the picking view, in order to hide the
"available" column if the move is coming from a supplier.
"""
for move in self:
move.show_reserved_availability = not move.location_id.usage == 'supplier'
@api.depends('state', 'picking_id')
def _compute_is_initial_demand_editable(self):
for move in self:
if not move.picking_id.immediate_transfer and move.state == 'draft':
move.is_initial_demand_editable = True
elif not move.picking_id.is_locked and move.state != 'done' and move.picking_id:
move.is_initial_demand_editable = True
else:
move.is_initial_demand_editable = False
@api.depends('state', 'picking_id', 'product_id')
def _compute_is_quantity_done_editable(self):
for move in self:
if not move.product_id:
move.is_quantity_done_editable = False
elif not move.picking_id.immediate_transfer and move.picking_id.state == 'draft':
move.is_quantity_done_editable = False
elif move.picking_id.is_locked and move.state in ('done', 'cancel'):
move.is_quantity_done_editable = False
elif move.show_details_visible:
move.is_quantity_done_editable = False
elif move.show_operations:
move.is_quantity_done_editable = False
else:
move.is_quantity_done_editable = True
@api.depends('picking_id', 'name')
def _compute_reference(self):
for move in self:
move.reference = move.picking_id.name if move.picking_id else move.name
@api.depends('move_line_ids')
def _compute_move_lines_count(self):
for move in self:
move.move_lines_count = len(move.move_line_ids)
@api.depends('product_id', 'product_uom', 'product_uom_qty')
def _compute_product_qty(self):
for move in self:
move.product_qty = move.product_uom._compute_quantity(
move.product_uom_qty, move.product_id.uom_id, rounding_method='HALF-UP')
def _get_move_lines(self):
""" This will return the move lines to consider when applying _quantity_done_compute on a stock.move.
In some context, such as MRP, it is necessary to compute quantity_done on filtered sock.move.line."""
self.ensure_one()
if self.picking_type_id.show_reserved is False:
return self.move_line_nosuggest_ids
return self.move_line_ids
@api.depends('move_orig_ids.date', 'move_orig_ids.state', 'state', 'date')
def _compute_delay_alert_date(self):
for move in self:
if move.state in ('done', 'cancel'):
move.delay_alert_date = False
continue
prev_moves = move.move_orig_ids.filtered(lambda m: m.state not in ('done', 'cancel') and m.date)
prev_max_date = max(prev_moves.mapped("date"), default=False)
if prev_max_date and prev_max_date > move.date:
move.delay_alert_date = prev_max_date
else:
move.delay_alert_date = False
@api.depends('move_line_ids.qty_done', 'move_line_ids.product_uom_id', 'move_line_nosuggest_ids.qty_done', 'picking_type_id.show_reserved')
def _quantity_done_compute(self):
""" This field represents the sum of the move lines `qty_done`. It allows the user to know
if there is still work to do.
We take care of rounding this value at the general decimal precision and not the rounding
of the move's UOM to make sure this value is really close to the real sum, because this
field will be used in `_action_done` in order to know if the move will need a backorder or
an extra move.
"""
if not any(self._ids):
# onchange
for move in self:
quantity_done = 0
for move_line in move._get_move_lines():
quantity_done += move_line.product_uom_id._compute_quantity(
move_line.qty_done, move.product_uom, round=False)
move.quantity_done = quantity_done
else:
# compute
move_lines_ids = set()
for move in self:
move_lines_ids |= set(move._get_move_lines().ids)
data = self.env['stock.move.line'].read_group(
[('id', 'in', list(move_lines_ids))],
['move_id', 'product_uom_id', 'qty_done'], ['move_id', 'product_uom_id'],
lazy=False
)
rec = defaultdict(list)
for d in data:
rec[d['move_id'][0]] += [(d['product_uom_id'][0], d['qty_done'])]
for move in self:
uom = move.product_uom
move.quantity_done = sum(
self.env['uom.uom'].browse(line_uom_id)._compute_quantity(qty, uom, round=False)
for line_uom_id, qty in rec.get(move.ids[0] if move.ids else move.id, [])
)
def _quantity_done_set(self):
quantity_done = self[0].quantity_done # any call to create will invalidate `move.quantity_done`
for move in self:
move_lines = move._get_move_lines()
if not move_lines:
if quantity_done:
# do not impact reservation here
move_line = self.env['stock.move.line'].create(dict(move._prepare_move_line_vals(), qty_done=quantity_done))
move.write({'move_line_ids': [(4, move_line.id)]})
move_line._apply_putaway_strategy()
elif len(move_lines) == 1:
move_lines[0].qty_done = quantity_done
else:
move._multi_line_quantity_done_set(quantity_done)
def _multi_line_quantity_done_set(self, quantity_done):
move_lines = self._get_move_lines()
# Bypass the error if we're trying to write the same value.
ml_quantity_done = 0
for move_line in move_lines:
ml_quantity_done += move_line.product_uom_id._compute_quantity(move_line.qty_done, self.product_uom, round=False)
if float_compare(quantity_done, ml_quantity_done, precision_rounding=self.product_uom.rounding) != 0:
raise UserError(_("Cannot set the done quantity from this stock move, work directly with the move lines."))
def _set_product_qty(self):
""" The meaning of product_qty field changed lately and is now a functional field computing the quantity
in the default product UoM. This code has been added to raise an error if a write is made given a value
for `product_qty`, where the same write should set the `product_uom_qty` field instead, in order to
detect errors. """
raise UserError(_('The requested operation cannot be processed because of a programming error setting the `product_qty` field instead of the `product_uom_qty`.'))
@api.depends('move_line_ids.product_qty')
def _compute_reserved_availability(self):
""" Fill the `availability` field on a stock move, which is the actual reserved quantity
and is represented by the aggregated `product_qty` on the linked move lines. If the move
is force assigned, the value will be 0.
"""
if not any(self._ids):
# onchange
for move in self:
reserved_availability = sum(move.move_line_ids.mapped('product_qty'))
move.reserved_availability = move.product_id.uom_id._compute_quantity(
reserved_availability, move.product_uom, rounding_method='HALF-UP')
else:
# compute
result = {data['move_id'][0]: data['product_qty'] for data in
self.env['stock.move.line'].read_group([('move_id', 'in', self.ids)], ['move_id', 'product_qty'], ['move_id'])}
for move in self:
move.reserved_availability = move.product_id.uom_id._compute_quantity(
result.get(move.id, 0.0), move.product_uom, rounding_method='HALF-UP')
@api.depends('state', 'product_id', 'product_qty', 'location_id')
def _compute_product_availability(self):
""" Fill the `availability` field on a stock move, which is the quantity to potentially
reserve. When the move is done, `availability` is set to the quantity the move did actually
move.
"""
for move in self:
if move.state == 'done':
move.availability = move.product_qty
else:
total_availability = self.env['stock.quant']._get_available_quantity(move.product_id, move.location_id) if move.product_id else 0.0
move.availability = min(move.product_qty, total_availability)
@api.depends('product_id', 'product_qty', 'picking_type_id', 'reserved_availability', 'priority', 'state', 'product_uom_qty', 'location_id')
def _compute_forecast_information(self):
""" Compute forecasted information of the related product by warehouse."""
self.forecast_availability = False
self.forecast_expected_date = False
# Prefetch product info to avoid fetching all product fields
self.product_id.read(['type', 'uom_id'], load=False)
not_product_moves = self.filtered(lambda move: move.product_id.type != 'product')
for move in not_product_moves:
move.forecast_availability = move.product_qty
product_moves = (self - not_product_moves)
outgoing_unreserved_moves_per_warehouse = defaultdict(set)
now = fields.Datetime.now()
def key_virtual_available(move, incoming=False):
warehouse_id = move.location_dest_id.warehouse_id.id if incoming else move.location_id.warehouse_id.id
return warehouse_id, max(move.date or now, now)
# Prefetch efficiently virtual_available for _consuming_picking_types draft move.
prefetch_virtual_available = defaultdict(set)
virtual_available_dict = {}
for move in product_moves:
if (move.picking_type_id.code in self._consuming_picking_types() or move._is_inter_wh()) and move.state == 'draft':
prefetch_virtual_available[key_virtual_available(move)].add(move.product_id.id)
elif move.picking_type_id.code == 'incoming':
prefetch_virtual_available[key_virtual_available(move, incoming=True)].add(move.product_id.id)
for key_context, product_ids in prefetch_virtual_available.items():
read_res = self.env['product.product'].browse(product_ids).with_context(warehouse=key_context[0], to_date=key_context[1]).read(['virtual_available'])
virtual_available_dict[key_context] = {res['id']: res['virtual_available'] for res in read_res}
for move in product_moves:
if move.picking_type_id.code in self._consuming_picking_types() or move._is_inter_wh():
if move.state == 'assigned':
move.forecast_availability = move.product_uom._compute_quantity(
move.reserved_availability, move.product_id.uom_id, rounding_method='HALF-UP')
elif move.state == 'draft':
# for move _consuming_picking_types and in draft -> the forecast_availability > 0 if in stock
move.forecast_availability = virtual_available_dict[key_virtual_available(move)][move.product_id.id] - move.product_qty
elif move.state in ('waiting', 'confirmed', 'partially_available'):
outgoing_unreserved_moves_per_warehouse[move.location_id.warehouse_id].add(move.id)
elif move.picking_type_id.code == 'incoming':
forecast_availability = virtual_available_dict[key_virtual_available(move, incoming=True)][move.product_id.id]
if move.state == 'draft':
forecast_availability += move.product_qty
move.forecast_availability = forecast_availability
for warehouse, moves_ids in outgoing_unreserved_moves_per_warehouse.items():
if not warehouse: # No prediction possible if no warehouse.
continue
moves = self.browse(moves_ids)
forecast_info = moves._get_forecast_availability_outgoing(warehouse)
for move in moves:
move.forecast_availability, move.forecast_expected_date = forecast_info[move]
def _set_date_deadline(self, new_deadline):
# Handle the propagation of `date_deadline` fields (up and down stream - only update by up/downstream documents)
already_propagate_ids = self.env.context.get('date_deadline_propagate_ids', set()) | set(self.ids)
self = self.with_context(date_deadline_propagate_ids=already_propagate_ids)
for move in self:
moves_to_update = (move.move_dest_ids | move.move_orig_ids)
if move.date_deadline:
delta = move.date_deadline - fields.Datetime.to_datetime(new_deadline)
else:
delta = 0
for move_update in moves_to_update:
if move_update.state in ('done', 'cancel'):
continue
if move_update.id in already_propagate_ids:
continue
if move_update.date_deadline and delta:
move_update.date_deadline -= delta
else:
move_update.date_deadline = new_deadline
@api.depends('move_line_ids', 'move_line_ids.lot_id', 'move_line_ids.qty_done')
def _compute_lot_ids(self):
domain_nosuggest = [('move_id', 'in', self.ids), ('lot_id', '!=', False), '|', ('qty_done', '!=', 0.0), ('product_qty', '=', 0.0)]
domain_suggest = [('move_id', 'in', self.ids), ('lot_id', '!=', False), ('qty_done', '!=', 0.0)]
lots_by_move_id_list = []
for domain in [domain_nosuggest, domain_suggest]:
lots_by_move_id = self.env['stock.move.line'].read_group(
domain,
['move_id', 'lot_ids:array_agg(lot_id)'], ['move_id'],
)
lots_by_move_id_list.append({by_move['move_id'][0]: by_move['lot_ids'] for by_move in lots_by_move_id})
for move in self:
move.lot_ids = lots_by_move_id_list[0 if move.picking_type_id.show_reserved else 1].get(move._origin.id, [])
def _set_lot_ids(self):
for move in self:
if move.product_id.tracking != 'serial':
continue
move_lines_commands = []
if move.picking_type_id.show_reserved is False:
mls = move.move_line_nosuggest_ids
else:
mls = move.move_line_ids
mls = mls.filtered(lambda ml: ml.lot_id)
for ml in mls:
if ml.qty_done and ml.lot_id not in move.lot_ids:
move_lines_commands.append((2, ml.id))
ls = move.move_line_ids.lot_id
for lot in move.lot_ids:
if lot not in ls:
move_line_vals = self._prepare_move_line_vals(quantity=0)
move_line_vals['lot_id'] = lot.id
move_line_vals['lot_name'] = lot.name
move_line_vals['product_uom_id'] = move.product_id.uom_id.id
move_line_vals['qty_done'] = 1
move_lines_commands.append((0, 0, move_line_vals))
else:
move_line = move.move_line_ids.filtered(lambda line: line.lot_id.id == lot.id)
move_line.qty_done = 1
move.write({'move_line_ids': move_lines_commands})
@api.depends('picking_type_id', 'date', 'priority')
def _compute_reservation_date(self):
for move in self:
if move.picking_type_id.reservation_method == 'by_date' and move.state in ['draft', 'confirmed', 'waiting', 'partially_available']:
days = move.picking_type_id.reservation_days_before
if move.priority == '1':
days = move.picking_type_id.reservation_days_before_priority
move.reservation_date = fields.Date.to_date(move.date) - timedelta(days=days)
@api.constrains('product_uom')
def _check_uom(self):
moves_error = self.filtered(lambda move: move.product_id.uom_id.category_id != move.product_uom.category_id)
if moves_error:
user_warning = _('You cannot perform the move because the unit of measure has a different category as the product unit of measure.')
for move in moves_error:
user_warning += _('\n\n%s --> Product UoM is %s (%s) - Move UoM is %s (%s)') % (move.product_id.display_name, move.product_id.uom_id.name, move.product_id.uom_id.category_id.name, move.product_uom.name, move.product_uom.category_id.name)
user_warning += _('\n\nBlocking: %s') % ' ,'.join(moves_error.mapped('name'))
raise UserError(user_warning)
def init(self):
self._cr.execute('SELECT indexname FROM pg_indexes WHERE indexname = %s', ('stock_move_product_location_index',))
if not self._cr.fetchone():
self._cr.execute('CREATE INDEX stock_move_product_location_index ON stock_move (product_id, location_id, location_dest_id, company_id, state)')
@api.model
def default_get(self, fields_list):
# We override the default_get to make stock moves created after the picking was confirmed
# directly as available in immediate transfer mode. This allows to create extra move lines
# in the fp view. In planned transfer, the stock move are marked as `additional` and will be
# auto-confirmed.
defaults = super(StockMove, self).default_get(fields_list)
if self.env.context.get('default_picking_id'):
picking_id = self.env['stock.picking'].browse(self.env.context['default_picking_id'])
if picking_id.state == 'done':
defaults['state'] = 'done'
defaults['product_uom_qty'] = 0.0
defaults['additional'] = True
elif picking_id.state not in ['cancel', 'draft', 'done']:
if picking_id.immediate_transfer:
defaults['state'] = 'assigned'
defaults['product_uom_qty'] = 0.0
defaults['additional'] = True # to trigger `_autoconfirm_picking`
return defaults
def name_get(self):
res = []
for move in self:
res.append((move.id, '%s%s%s>%s' % (
move.picking_id.origin and '%s/' % move.picking_id.origin or '',
move.product_id.code and '%s: ' % move.product_id.code or '',
move.location_id.name, move.location_dest_id.name)))
return res
def write(self, vals):
# Handle the write on the initial demand by updating the reserved quantity and logging
# messages according to the state of the stock.move records.
receipt_moves_to_reassign = self.env['stock.move']
move_to_recompute_state = self.env['stock.move']
if 'quantity_done' in vals and any(move.state == 'cancel' for move in self):
raise UserError(_('You cannot change a cancelled stock move, create a new line instead.'))
if 'product_uom' in vals and any(move.state == 'done' for move in self):
raise UserError(_('You cannot change the UoM for a stock move that has been set to \'Done\'.'))
if 'product_uom_qty' in vals:
move_to_unreserve = self.env['stock.move']
for move in self.filtered(lambda m: m.state not in ('done', 'draft') and m.picking_id):
if float_compare(vals['product_uom_qty'], move.product_uom_qty, precision_rounding=move.product_uom.rounding):
self.env['stock.move.line']._log_message(move.picking_id, move, 'stock.track_move_template', vals)
if self.env.context.get('do_not_unreserve') is None:
move_to_unreserve = self.filtered(
lambda m: m.state not in ['draft', 'done', 'cancel'] and float_compare(m.reserved_availability, vals.get('product_uom_qty'), precision_rounding=m.product_uom.rounding) == 1
)
move_to_unreserve._do_unreserve()
(self - move_to_unreserve).filtered(lambda m: m.state == 'assigned').write({'state': 'partially_available'})
# When editing the initial demand, directly run again action assign on receipt moves.
receipt_moves_to_reassign |= move_to_unreserve.filtered(lambda m: m.location_id.usage == 'supplier')
receipt_moves_to_reassign |= (self - move_to_unreserve).filtered(lambda m: m.location_id.usage == 'supplier' and m.state in ('partially_available', 'assigned'))
move_to_recompute_state |= self - move_to_unreserve - receipt_moves_to_reassign
# propagate product_packaging_id changes in the stock move chain
if 'product_packaging_id' in vals:
self._propagate_product_packaging(vals['product_packaging_id'])
if 'date_deadline' in vals:
self._set_date_deadline(vals.get('date_deadline'))
res = super(StockMove, self).write(vals)
if move_to_recompute_state:
move_to_recompute_state._recompute_state()
if receipt_moves_to_reassign:
receipt_moves_to_reassign._action_assign()
return res
def _propagate_product_packaging(self, product_package_id):
"""
Propagate the product_packaging_id of a move to its destination and origin.
If there is a bifurcation in the chain we do not propagate the package.
"""
already_propagated_ids = self.env.context.get('product_packaging_propagation_ids', set()) | set(self.ids)
self = self.with_context(product_packaging_propagation_ids=already_propagated_ids)
for move in self:
# propagate on destination move
for move_dest in move.move_dest_ids:
if move_dest.id not in already_propagated_ids and \
move_dest.state not in ['cancel', 'done'] and \
move_dest.product_packaging_id.id != product_package_id and \
move_dest.move_orig_ids == move: # checks that you are the only parent move of your destination
move_dest.product_packaging_id = product_package_id
# propagate on origin move
for move_orig in move.move_orig_ids:
if move_orig.id not in already_propagated_ids and \
move_orig.state not in ['cancel', 'done'] and \
move_orig.product_packaging_id.id != product_package_id and \
move_orig.move_dest_ids == move: # checks that you are the only child move of your origin
move_orig.product_packaging_id = product_package_id
def _delay_alert_get_documents(self):
"""Returns a list of recordset of the documents linked to the stock.move in `self` in order
to post the delay alert next activity. These documents are deduplicated. This method is meant
to be overridden by other modules, each of them adding an element by type of recordset on
this list.
:return: a list of recordset of the documents linked to `self`
:rtype: list
"""
return list(self.mapped('picking_id'))
def _propagate_date_log_note(self, move_orig):
"""Post a deadline change alert log note on the documents linked to `self`."""
# TODO : get the end document (PO/SO/MO)
doc_orig = move_orig._delay_alert_get_documents()
documents = self._delay_alert_get_documents()
if not documents or not doc_orig:
return
msg = _("The deadline has been automatically updated due to a delay on <a href='#' data-oe-model='%s' data-oe-id='%s'>%s</a>.") % (doc_orig[0]._name, doc_orig[0].id, doc_orig[0].name)
msg_subject = _("Deadline updated due to delay on %s", doc_orig[0].name)
# write the message on each document
for doc in documents:
last_message = doc.message_ids[:1]
# Avoids to write the exact same message multiple times.
if last_message and last_message.subject == msg_subject:
continue
odoobot_id = self.env['ir.model.data']._xmlid_to_res_id("base.partner_root")
doc.message_post(body=msg, author_id=odoobot_id, subject=msg_subject)
def action_show_details(self):
""" Returns an action that will open a form view (in a popup) allowing to work on all the
move lines of a particular move. This form view is used when "show operations" is not
checked on the picking type.
"""
self.ensure_one()
# If "show suggestions" is not checked on the picking type, we have to filter out the
# reserved move lines. We do this by displaying `move_line_nosuggest_ids`. We use
# different views to display one field or another so that the webclient doesn't have to
# fetch both.
if self.picking_type_id.show_reserved:
view = self.env.ref('stock.view_stock_move_operations')
else:
view = self.env.ref('stock.view_stock_move_nosuggest_operations')
if self.product_id.tracking == "serial" and self.state == "assigned":
self.next_serial = self.env['stock.production.lot']._get_next_serial(self.company_id, self.product_id)
return {
'name': _('Detailed Operations'),
'type': 'ir.actions.act_window',
'view_mode': 'form',
'res_model': 'stock.move',
'views': [(view.id, 'form')],
'view_id': view.id,
'target': 'new',
'res_id': self.id,
'context': dict(
self.env.context,
show_owner=self.picking_type_id.code != 'incoming',
show_lots_m2o=self.has_tracking != 'none' and (self.picking_type_id.use_existing_lots or self.state == 'done' or self.origin_returned_move_id.id), # able to create lots, whatever the value of ` use_create_lots`.
show_lots_text=self.has_tracking != 'none' and self.picking_type_id.use_create_lots and not self.picking_type_id.use_existing_lots and self.state != 'done' and not self.origin_returned_move_id.id,
show_source_location=self.picking_type_id.code != 'incoming',
show_destination_location=self.picking_type_id.code != 'outgoing',
show_package=not self.location_id.usage == 'supplier',
show_reserved_quantity=self.state != 'done' and not self.picking_id.immediate_transfer and self.picking_type_id.code != 'incoming'
),
}
def action_assign_serial_show_details(self):
""" On `self.move_line_ids`, assign `lot_name` according to
`self.next_serial` before returning `self.action_show_details`.
"""
self.ensure_one()
if not self.next_serial:
raise UserError(_("You need to set a Serial Number before generating more."))
self._generate_serial_numbers()
return self.action_show_details()
def action_clear_lines_show_details(self):
""" Unlink `self.move_line_ids` before returning `self.action_show_details`.
Useful for if a user creates too many SNs by accident via action_assign_serial_show_details
since there's no way to undo the action.
"""
self.ensure_one()
if self.picking_type_id.show_reserved:
move_lines = self.move_line_ids
else:
move_lines = self.move_line_nosuggest_ids
move_lines.unlink()
return self.action_show_details()
def action_assign_serial(self):
""" Opens a wizard to assign SN's name on each move lines.
"""
self.ensure_one()
action = self.env["ir.actions.actions"]._for_xml_id("stock.act_assign_serial_numbers")
action['context'] = {
'default_product_id': self.product_id.id,
'default_move_id': self.id,
}
return action
def action_product_forecast_report(self):
self.ensure_one()
action = self.product_id.action_product_forecast_report()
action['context'] = {
'active_id': self.product_id.id,
'active_model': 'product.product',
'move_to_match_ids': self.ids,
}
if self.picking_type_id.code in self._consuming_picking_types():
warehouse = self.location_id.warehouse_id
else:
warehouse = self.location_dest_id.warehouse_id
if warehouse:
action['context']['warehouse'] = warehouse.id
return action
def _do_unreserve(self):
moves_to_unreserve = OrderedSet()
for move in self:
if move.state == 'cancel' or (move.state == 'done' and move.scrapped):
# We may have cancelled move in an open picking in a "propagate_cancel" scenario.
# We may have done move in an open picking in a scrap scenario.
continue
elif move.state == 'done':
raise UserError(_("You cannot unreserve a stock move that has been set to 'Done'."))
moves_to_unreserve.add(move.id)
moves_to_unreserve = self.env['stock.move'].browse(moves_to_unreserve)
ml_to_update, ml_to_unlink = OrderedSet(), OrderedSet()
moves_not_to_recompute = OrderedSet()
for ml in moves_to_unreserve.move_line_ids:
if ml.qty_done:
ml_to_update.add(ml.id)
else:
ml_to_unlink.add(ml.id)
moves_not_to_recompute.add(ml.move_id.id)
ml_to_update, ml_to_unlink = self.env['stock.move.line'].browse(ml_to_update), self.env['stock.move.line'].browse(ml_to_unlink)
moves_not_to_recompute = self.env['stock.move'].browse(moves_not_to_recompute)
ml_to_update.write({'product_uom_qty': 0})
ml_to_unlink.unlink()
# `write` on `stock.move.line` doesn't call `_recompute_state` (unlike to `unlink`),
# so it must be called for each move where no move line has been deleted.
(moves_to_unreserve - moves_not_to_recompute)._recompute_state()
return True
def _generate_serial_numbers(self, next_serial_count=False):
""" This method will generate `lot_name` from a string (field
`next_serial`) and create a move line for each generated `lot_name`.
"""
self.ensure_one()
lot_names = self.env['stock.production.lot'].generate_lot_names(self.next_serial, next_serial_count or self.next_serial_count)
move_lines_commands = self._generate_serial_move_line_commands(lot_names)
self.write({'move_line_ids': move_lines_commands})
return True
def _push_apply(self):
new_moves = []
for move in self:
# if the move is already chained, there is no need to check push rules
if move.move_dest_ids:
continue
# if the move is a returned move, we don't want to check push rules, as returning a returned move is the only decent way
# to receive goods without triggering the push rules again (which would duplicate chained operations)
domain = [('location_src_id', '=', move.location_dest_id.id), ('action', 'in', ('push', 'pull_push'))]
# first priority goes to the preferred routes defined on the move itself (e.g. coming from a SO line)
warehouse_id = move.warehouse_id or move.picking_id.picking_type_id.warehouse_id
if move.location_dest_id.company_id == self.env.company:
rule = self.env['procurement.group']._search_rule(move.route_ids, move.product_packaging_id, move.product_id, warehouse_id, domain)
else:
rule = self.sudo().env['procurement.group']._search_rule(move.route_ids, move.product_packaging_id, move.product_id, warehouse_id, domain)
# Make sure it is not returning the return
if rule and (not move.origin_returned_move_id or move.origin_returned_move_id.location_dest_id.id != rule.location_id.id):
new_move = rule._run_push(move)
if new_move:
new_moves.append(new_move)
return self.env['stock.move'].concat(*new_moves)
def _merge_moves_fields(self):
""" This method will return a dict of stock move’s values that represent the values of all moves in `self` merged. """
state = self._get_relevant_state_among_moves()
origin = '/'.join(set(self.filtered(lambda m: m.origin).mapped('origin')))
return {
'product_uom_qty': sum(self.mapped('product_uom_qty')),
'date': min(self.mapped('date')) if all(p.move_type == 'direct' for p in self.picking_id) else max(self.mapped('date')),
'move_dest_ids': [(4, m.id) for m in self.mapped('move_dest_ids')],
'move_orig_ids': [(4, m.id) for m in self.mapped('move_orig_ids')],
'state': state,
'origin': origin,
}
@api.model
def _prepare_merge_moves_distinct_fields(self):
fields = [
'product_id', 'price_unit', 'procure_method', 'location_id', 'location_dest_id',
'product_uom', 'restrict_partner_id', 'scrapped', 'origin_returned_move_id',
'package_level_id', 'propagate_cancel', 'description_picking', 'date_deadline',
'product_packaging_id',
]
if self.env['ir.config_parameter'].sudo().get_param('stock.merge_only_same_date'):
fields.append('date')
return fields
@api.model
def _prepare_merge_negative_moves_excluded_distinct_fields(self):
return ['description_picking', 'price_unit']
def _clean_merged(self):
"""Cleanup hook used when merging moves"""
self.write({'propagate_cancel': False})
def _update_candidate_moves_list(self, candidate_moves_list):
for picking in self.mapped('picking_id'):
candidate_moves_list.append(picking.move_lines)
def _merge_moves(self, merge_into=False):
""" This method will, for each move in `self`, go up in their linked picking and try to
find in their existing moves a candidate into which we can merge the move.
:return: Recordset of moves passed to this method. If some of the passed moves were merged
into another existing one, return this one and not the (now unlinked) original.
"""
distinct_fields = self._prepare_merge_moves_distinct_fields()
candidate_moves_list = []
if not merge_into:
self._update_candidate_moves_list(candidate_moves_list)
else:
candidate_moves_list.append(merge_into | self)
# Move removed after merge
moves_to_unlink = self.env['stock.move']
# Moves successfully merged
merged_moves = self.env['stock.move']
moves_by_neg_key = defaultdict(lambda: self.env['stock.move'])
# Need to check less fields for negative moves as some might not be set.
neg_qty_moves = self.filtered(lambda m: float_compare(m.product_qty, 0.0, precision_rounding=m.product_uom.rounding) < 0)
# Detach their picking as they will either get absorbed or create a backorder, so no extra logs will be put in the chatter
neg_qty_moves.picking_id = False
excluded_fields = self._prepare_merge_negative_moves_excluded_distinct_fields()
neg_key = itemgetter(*[field for field in distinct_fields if field not in excluded_fields])
price_unit_prec = self.env['decimal.precision'].precision_get('Product Price')
for candidate_moves in candidate_moves_list:
# First step find move to merge.
candidate_moves = candidate_moves.filtered(lambda m: m.state not in ('done', 'cancel', 'draft')) - neg_qty_moves
for k, g in groupbyelem(candidate_moves, key=itemgetter(*distinct_fields)):
moves = self.env['stock.move'].concat(*g)
# Merge all positive moves together
if len(moves) > 1:
# link all move lines to record 0 (the one we will keep).
moves.mapped('move_line_ids').write({'move_id': moves[0].id})
# merge move data
moves[0].write(moves._merge_moves_fields())
# update merged moves dicts
moves_to_unlink |= moves[1:]
merged_moves |= moves[0]
# Add the now single positive move to its limited key record
moves_by_neg_key[neg_key(moves[0])] |= moves[0]
for neg_move in neg_qty_moves:
# Check all the candidates that matches the same limited key, and adjust their quantites to absorb negative moves
for pos_move in moves_by_neg_key.get(neg_key(neg_move), []):
currency_prec = pos_move.product_id.currency_id.decimal_places
rounding = min(currency_prec, price_unit_prec)
if float_compare(pos_move.price_unit, neg_move.price_unit, precision_digits=rounding) == 0:
new_total_value = pos_move.product_qty * pos_move.price_unit + neg_move.product_qty * neg_move.price_unit
# If quantity can be fully absorbed by a single move, update its quantity and remove the negative move
if float_compare(pos_move.product_uom_qty, abs(neg_move.product_uom_qty), precision_rounding=pos_move.product_uom.rounding) >= 0:
pos_move.product_uom_qty += neg_move.product_uom_qty
pos_move.write({
'price_unit': float_round(new_total_value / pos_move.product_qty, precision_digits=price_unit_prec) if pos_move.product_qty else 0,
'move_dest_ids': [Command.link(m.id) for m in neg_move.mapped('move_dest_ids') if m.location_id == pos_move.location_dest_id],
'move_orig_ids': [Command.link(m.id) for m in neg_move.mapped('move_orig_ids') if m.location_dest_id == pos_move.location_id],
})
merged_moves |= pos_move
moves_to_unlink |= neg_move
break
neg_move.product_uom_qty += pos_move.product_uom_qty
neg_move.price_unit = float_round(new_total_value / neg_move.product_qty, precision_digits=price_unit_prec)
pos_move.product_uom_qty = 0
if moves_to_unlink:
# We are using propagate to False in order to not cancel destination moves merged in moves[0]
moves_to_unlink._clean_merged()
moves_to_unlink._action_cancel()
moves_to_unlink.sudo().unlink()
return (self | merged_moves) - moves_to_unlink
def _get_relevant_state_among_moves(self):
# We sort our moves by importance of state:
# ------------- 0
# | Assigned |
# -------------
# | Waiting |
# -------------
# | Partial |
# -------------
# | Confirm |
# ------------- len-1
sort_map = {
'assigned': 4,
'waiting': 3,
'partially_available': 2,
'confirmed': 1,
}
moves_todo = self\
.filtered(lambda move: move.state not in ['cancel', 'done'] and not (move.state == 'assigned' and not move.product_uom_qty))\
.sorted(key=lambda move: (sort_map.get(move.state, 0), move.product_uom_qty))
if not moves_todo:
return 'assigned'
# The picking should be the same for all moves.
if moves_todo[:1].picking_id and moves_todo[:1].picking_id.move_type == 'one':
most_important_move = moves_todo[0]
if most_important_move.state == 'confirmed':
return 'confirmed' if most_important_move.product_uom_qty else 'assigned'
elif most_important_move.state == 'partially_available':
return 'confirmed'
else:
return moves_todo[:1].state or 'draft'
elif moves_todo[:1].state != 'assigned' and any(move.state in ['assigned', 'partially_available'] for move in moves_todo):
return 'partially_available'
else:
least_important_move = moves_todo[-1:]
if least_important_move.state == 'confirmed' and least_important_move.product_uom_qty == 0:
return 'assigned'
else:
return moves_todo[-1:].state or 'draft'
@api.onchange('product_id', 'picking_type_id')
def _onchange_product_id(self):
product = self.product_id.with_context(lang=self._get_lang())
self.name = product.partner_ref
self.product_uom = product.uom_id.id
if product:
self.description_picking = product._get_description(self.picking_type_id)
@api.onchange('product_id', 'product_qty', 'product_uom')
def _onchange_suggest_packaging(self):
# remove packaging if not match the product
if self.product_packaging_id.product_id != self.product_id:
self.product_packaging_id = False
# suggest biggest suitable packaging
if self.product_id and self.product_qty and self.product_uom:
self.product_packaging_id = self.product_id.packaging_ids._find_suitable_product_packaging(self.product_qty, self.product_uom)
@api.onchange('lot_ids')
def _onchange_lot_ids(self):
quantity_done = sum(ml.product_uom_id._compute_quantity(ml.qty_done, self.product_uom) for ml in self.move_line_ids.filtered(lambda ml: not ml.lot_id and ml.lot_name))
quantity_done += self.product_id.uom_id._compute_quantity(len(self.lot_ids), self.product_uom)
self.update({'quantity_done': quantity_done})
quants = self.env['stock.quant'].search([('product_id', '=', self.product_id.id),
('lot_id', 'in', self.lot_ids.ids),
('quantity', '!=', 0),
'|', ('location_id.usage', '=', 'customer'),
'&', ('company_id', '=', self.company_id.id),
('location_id.usage', 'in', ('internal', 'transit'))])
if quants:
sn_to_location = ""
for quant in quants:
sn_to_location += _("\n(%s) exists in location %s", quant.lot_id.display_name, quant.location_id.display_name)
return {
'warning': {'title': _('Warning'), 'message': _('Existing Serial numbers. Please correct the serial numbers encoded:') + sn_to_location}
}
@api.onchange('move_line_ids', 'move_line_nosuggest_ids', 'picking_type_id')
def _onchange_move_line_ids(self):
if not self.picking_type_id.use_create_lots:
# This onchange manages the creation of multiple lot name. We don't
# need that if the picking type disallows the creation of new lots.
return
breaking_char = '\n'
if self.picking_type_id.show_reserved:
move_lines = self.move_line_ids
else:
move_lines = self.move_line_nosuggest_ids
for move_line in move_lines:
# Look if the `lot_name` contains multiple values.
if breaking_char in (move_line.lot_name or ''):
split_lines = move_line.lot_name.split(breaking_char)
split_lines = list(filter(None, split_lines))
move_line.lot_name = split_lines[0] if split_lines else ''
move_lines_commands = self._generate_serial_move_line_commands(
split_lines[1:],
origin_move_line=move_line,
)
if self.picking_type_id.show_reserved:
self.update({'move_line_ids': move_lines_commands})
else:
self.update({'move_line_nosuggest_ids': move_lines_commands})
existing_lots = self.env['stock.production.lot'].search([
('company_id', '=', self.company_id.id),
('product_id', '=', self.product_id.id),
('name', 'in', split_lines),
])
if existing_lots:
return {
'warning': {'title': _('Warning'), 'message': _('Existing Serial Numbers (%s). Please correct the serial numbers encoded.') % ','.join(existing_lots.mapped('display_name'))}
}
break
@api.onchange('product_uom')
def _onchange_product_uom(self):
if self.product_uom.factor > self.product_id.uom_id.factor:
return {
'warning': {
'title': "Unsafe unit of measure",
'message': _("You are using a unit of measure smaller than the one you are using in "
"order to stock your product. This can lead to rounding problem on reserved quantity. "
"You should use the smaller unit of measure possible in order to valuate your stock or "
"change its rounding precision to a smaller value (example: 0.00001)."),
}
}
def _key_assign_picking(self):
self.ensure_one()
keys = (self.group_id, self.location_id, self.location_dest_id, self.picking_type_id)
if self.partner_id and (self.location_id.usage == 'transit' or self.location_dest_id.usage == 'transit'):
keys += (self.partner_id, )
return keys
def _search_picking_for_assignation_domain(self):
domain = [
('group_id', '=', self.group_id.id),
('location_id', '=', self.location_id.id),
('location_dest_id', '=', self.location_dest_id.id),
('picking_type_id', '=', self.picking_type_id.id),
('printed', '=', False),
('immediate_transfer', '=', False),
('state', 'in', ['draft', 'confirmed', 'waiting', 'partially_available', 'assigned'])]
if self.partner_id and (self.location_id.usage == 'transit' or self.location_dest_id.usage == 'transit'):
domain += [('partner_id', '=', self.partner_id.id)]
return domain
def _search_picking_for_assignation(self):
self.ensure_one()
domain = self._search_picking_for_assignation_domain()
picking = self.env['stock.picking'].search(domain, limit=1)
return picking
def _assign_picking(self):
""" Try to assign the moves to an existing picking that has not been
reserved yet and has the same procurement group, locations and picking
type (moves should already have them identical). Otherwise, create a new
picking to assign them to. """
Picking = self.env['stock.picking']
grouped_moves = groupby(sorted(self, key=lambda m: [f.id for f in m._key_assign_picking()]), key=lambda m: [m._key_assign_picking()])
for group, moves in grouped_moves:
moves = self.env['stock.move'].concat(*list(moves))
new_picking = False
# Could pass the arguments contained in group but they are the same
# for each move that why moves[0] is acceptable
picking = moves[0]._search_picking_for_assignation()
if picking:
# If a picking is found, we'll append `move` to its move list and thus its
# `partner_id` and `ref` field will refer to multiple records. In this
# case, we chose to wipe them.
vals = {}
if any(picking.partner_id.id != m.partner_id.id for m in moves):
vals['partner_id'] = False
if any(picking.origin != m.origin for m in moves):
vals['origin'] = False
if vals:
picking.write(vals)
else:
# Don't create picking for negative moves since they will be
# reverse and assign to another picking
moves = moves.filtered(lambda m: float_compare(m.product_uom_qty, 0.0, precision_rounding=m.product_uom.rounding) >= 0)
if not moves:
continue
new_picking = True
picking = Picking.create(moves._get_new_picking_values())
moves.write({'picking_id': picking.id})
moves._assign_picking_post_process(new=new_picking)
return True
def _assign_picking_post_process(self, new=False):
pass
def _generate_serial_move_line_commands(self, lot_names, origin_move_line=None):
"""Return a list of commands to update the move lines (write on
existing ones or create new ones).
Called when user want to create and assign multiple serial numbers in
one time (using the button/wizard or copy-paste a list in the field).
:param lot_names: A list containing all serial number to assign.
:type lot_names: list
:param origin_move_line: A move line to duplicate the value from, default to None
:type origin_move_line: record of :class:`stock.move.line`
:return: A list of commands to create/update :class:`stock.move.line`
:rtype: list
"""
self.ensure_one()
# Select the right move lines depending of the picking type configuration.
move_lines = self.env['stock.move.line']
if self.picking_type_id.show_reserved:
move_lines = self.move_line_ids.filtered(lambda ml: not ml.lot_id and not ml.lot_name)
else:
move_lines = self.move_line_nosuggest_ids.filtered(lambda ml: not ml.lot_id and not ml.lot_name)
loc_dest = origin_move_line and origin_move_line.location_dest_id
move_line_vals = {
'picking_id': self.picking_id.id,
'location_id': self.location_id.id,
'product_id': self.product_id.id,
'product_uom_id': self.product_id.uom_id.id,
'qty_done': 1,
}
if origin_move_line:
# `owner_id` and `package_id` are taken only in the case we create
# new move lines from an existing move line. Also, updates the
# `qty_done` because it could be usefull for products tracked by lot.
move_line_vals.update({
'owner_id': origin_move_line.owner_id.id,
'package_id': origin_move_line.package_id.id,
'qty_done': origin_move_line.qty_done or 1,
})
move_lines_commands = []
qty_by_location = defaultdict(float)
for lot_name in lot_names:
# We write the lot name on an existing move line (if we have still one)...
if move_lines:
move_lines_commands.append((1, move_lines[0].id, {
'lot_name': lot_name,
'qty_done': 1,
}))
qty_by_location[move_lines[0].location_dest_id.id] += 1
move_lines = move_lines[1:]
# ... or create a new move line with the serial name.
else:
loc = loc_dest or self.location_dest_id._get_putaway_strategy(self.product_id, quantity=1, packaging=self.product_packaging_id, additional_qty=qty_by_location)
move_line_cmd = dict(move_line_vals, lot_name=lot_name, location_dest_id=loc.id)
move_lines_commands.append((0, 0, move_line_cmd))
qty_by_location[loc.id] += 1
return move_lines_commands
def _get_new_picking_values(self):
""" return create values for new picking that will be linked with group
of moves in self.
"""
origins = self.filtered(lambda m: m.origin).mapped('origin')
origins = list(dict.fromkeys(origins)) # create a list of unique items
# Will display source document if any, when multiple different origins
# are found display a maximum of 5
if len(origins) == 0:
origin = False
else:
origin = ','.join(origins[:5])
if len(origins) > 5:
origin += "..."
partners = self.mapped('partner_id')
partner = len(partners) == 1 and partners.id or False
return {
'origin': origin,
'company_id': self.mapped('company_id').id,
'user_id': False,
'move_type': self.mapped('group_id').move_type or 'direct',
'partner_id': partner,
'picking_type_id': self.mapped('picking_type_id').id,
'location_id': self.mapped('location_id').id,
'location_dest_id': self.mapped('location_dest_id').id,
}
def _should_be_assigned(self):
self.ensure_one()
return bool(not self.picking_id and self.picking_type_id)
def _is_inter_wh(self):
self.ensure_one()
from_wh = self.location_id.warehouse_id
to_wh = self.location_dest_id.warehouse_id
return from_wh and to_wh and from_wh != to_wh
def _action_confirm(self, merge=True, merge_into=False):
""" Confirms stock move or put it in waiting if it's linked to another move.
:param: merge: According to this boolean, a newly confirmed move will be merged
in another move of the same picking sharing its characteristics.
"""
# Use OrderedSet of id (instead of recordset + |= ) for performance
move_create_proc, move_to_confirm, move_waiting = OrderedSet(), OrderedSet(), OrderedSet()
to_assign = defaultdict(OrderedSet)
for move in self:
if move.state != 'draft':
continue
# if the move is preceded, then it's waiting (if preceding move is done, then action_assign has been called already and its state is already available)
if move.move_orig_ids:
move_waiting.add(move.id)
else:
if move.procure_method == 'make_to_order':
move_create_proc.add(move.id)
else:
move_to_confirm.add(move.id)
if move._should_be_assigned():
key = (move.group_id.id, move.location_id.id, move.location_dest_id.id)
to_assign[key].add(move.id)
move_create_proc, move_to_confirm, move_waiting = self.browse(move_create_proc), self.browse(move_to_confirm), self.browse(move_waiting)
# create procurements for make to order moves
procurement_requests = []
for move in move_create_proc:
values = move._prepare_procurement_values()
origin = move._prepare_procurement_origin()
procurement_requests.append(self.env['procurement.group'].Procurement(
move.product_id, move.product_uom_qty, move.product_uom,
move.location_id, move.rule_id and move.rule_id.name or "/",
origin, move.company_id, values))
self.env['procurement.group'].run(procurement_requests, raise_user_error=not self.env.context.get('from_orderpoint'))
move_to_confirm.write({'state': 'confirmed'})
(move_waiting | move_create_proc).write({'state': 'waiting'})
# procure_method sometimes changes with certain workflows so just in case, apply to all moves
(move_to_confirm | move_waiting | move_create_proc).filtered(lambda m: m.picking_type_id.reservation_method == 'at_confirm')\
.write({'reservation_date': fields.Date.today()})
# assign picking in batch for all confirmed move that share the same details
for moves_ids in to_assign.values():
self.browse(moves_ids).with_context(clean_context(self.env.context))._assign_picking()
new_push_moves = self.filtered(lambda m: not m.picking_id.immediate_transfer)._push_apply()
self._check_company()
moves = self
if merge:
moves = self._merge_moves(merge_into=merge_into)
# Transform remaining move in return in case of negative initial demand
neg_r_moves = moves.filtered(lambda move: float_compare(
move.product_uom_qty, 0, precision_rounding=move.product_uom.rounding) < 0)
for move in neg_r_moves:
move.location_id, move.location_dest_id = move.location_dest_id, move.location_id
orig_move_ids, dest_move_ids = [], []
for m in move.move_orig_ids | move.move_dest_ids:
from_loc, to_loc = m.location_id, m.location_dest_id
if float_compare(m.product_uom_qty, 0, precision_rounding=m.product_uom.rounding) < 0:
from_loc, to_loc = to_loc, from_loc
if to_loc == move.location_id:
orig_move_ids += m.ids
elif move.location_dest_id == from_loc:
dest_move_ids += m.ids
move.move_orig_ids, move.move_dest_ids = [(6, 0, orig_move_ids)], [(6, 0, dest_move_ids)]
move.product_uom_qty *= -1
if move.picking_type_id.return_picking_type_id:
move.picking_type_id = move.picking_type_id.return_picking_type_id
# We are returning some products, we must take them in the source location
move.procure_method = 'make_to_stock'
neg_r_moves._assign_picking()
# call `_action_assign` on every confirmed move which location_id bypasses the reservation + those expected to be auto-assigned
moves.filtered(lambda move: not move.picking_id.immediate_transfer
and move.state in ('confirmed', 'partially_available')
and (move._should_bypass_reservation()
or move.picking_type_id.reservation_method == 'at_confirm'
or (move.reservation_date and move.reservation_date <= fields.Date.today())))\
._action_assign()
if new_push_moves:
neg_push_moves = new_push_moves.filtered(lambda sm: float_compare(sm.product_uom_qty, 0, precision_rounding=sm.product_uom.rounding) < 0)
(new_push_moves - neg_push_moves)._action_confirm()
# Negative moves do not have any picking, so we should try to merge it with their siblings
neg_push_moves._action_confirm(merge_into=neg_push_moves.move_orig_ids.move_dest_ids)
return moves
def _prepare_procurement_origin(self):
self.ensure_one()
return self.group_id and self.group_id.name or (self.origin or self.picking_id.name or "/")
def _prepare_procurement_values(self):
""" Prepare specific key for moves or other componenets that will be created from a stock rule
comming from a stock move. This method could be override in order to add other custom key that could
be used in move/po creation.
"""
self.ensure_one()
group_id = self.group_id or False
if self.rule_id:
if self.rule_id.group_propagation_option == 'fixed' and self.rule_id.group_id:
group_id = self.rule_id.group_id
elif self.rule_id.group_propagation_option == 'none':
group_id = False
product_id = self.product_id.with_context(lang=self._get_lang())
return {
'product_description_variants': self.description_picking and self.description_picking.replace(product_id._get_description(self.picking_type_id), ''),
'date_planned': self.date,
'date_deadline': self.date_deadline,
'move_dest_ids': self,
'group_id': group_id,
'route_ids': self.route_ids,
'warehouse_id': self.warehouse_id or self.picking_type_id.warehouse_id,
'priority': self.priority,
'orderpoint_id': self.orderpoint_id,
'product_packaging_id': self.product_packaging_id,
}
def _prepare_move_line_vals(self, quantity=None, reserved_quant=None):
self.ensure_one()
vals = {
'move_id': self.id,
'product_id': self.product_id.id,
'product_uom_id': self.product_uom.id,
'location_id': self.location_id.id,
'location_dest_id': self.location_dest_id.id,
'picking_id': self.picking_id.id,
'company_id': self.company_id.id,
}
if quantity:
rounding = self.env['decimal.precision'].precision_get('Product Unit of Measure')
uom_quantity = self.product_id.uom_id._compute_quantity(quantity, self.product_uom, rounding_method='HALF-UP')
uom_quantity = float_round(uom_quantity, precision_digits=rounding)
uom_quantity_back_to_product_uom = self.product_uom._compute_quantity(uom_quantity, self.product_id.uom_id, rounding_method='HALF-UP')
if float_compare(quantity, uom_quantity_back_to_product_uom, precision_digits=rounding) == 0:
vals = dict(vals, product_uom_qty=uom_quantity)
else:
vals = dict(vals, product_uom_qty=quantity, product_uom_id=self.product_id.uom_id.id)
package = None
if reserved_quant:
package = reserved_quant.package_id
vals = dict(
vals,
location_id=reserved_quant.location_id.id,
lot_id=reserved_quant.lot_id.id or False,
package_id=package.id or False,
owner_id =reserved_quant.owner_id.id or False,
)
return vals
def _update_reserved_quantity(self, need, available_quantity, location_id, lot_id=None, package_id=None, owner_id=None, strict=True):
""" Create or update move lines.
"""
self.ensure_one()
if not lot_id:
lot_id = self.env['stock.production.lot']
if not package_id:
package_id = self.env['stock.quant.package']
if not owner_id:
owner_id = self.env['res.partner']
# do full packaging reservation when it's needed
if self.product_packaging_id and self.product_id.product_tmpl_id.categ_id.packaging_reserve_method == "full":
available_quantity = self.product_packaging_id._check_qty(available_quantity, self.product_id.uom_id, "DOWN")
taken_quantity = min(available_quantity, need)
# `taken_quantity` is in the quants unit of measure. There's a possibility that the move's
# unit of measure won't be respected if we blindly reserve this quantity, a common usecase
# is if the move's unit of measure's rounding does not allow fractional reservation. We chose
# to convert `taken_quantity` to the move's unit of measure with a down rounding method and
# then get it back in the quants unit of measure with an half-up rounding_method. This
# way, we'll never reserve more than allowed. We do not apply this logic if
# `available_quantity` is brought by a chained move line. In this case, `_prepare_move_line_vals`
# will take care of changing the UOM to the UOM of the product.
if not strict and self.product_id.uom_id != self.product_uom:
taken_quantity_move_uom = self.product_id.uom_id._compute_quantity(taken_quantity, self.product_uom, rounding_method='DOWN')
taken_quantity = self.product_uom._compute_quantity(taken_quantity_move_uom, self.product_id.uom_id, rounding_method='HALF-UP')
quants = []
rounding = self.env['decimal.precision'].precision_get('Product Unit of Measure')
if self.product_id.tracking == 'serial':
if float_compare(taken_quantity, int(taken_quantity), precision_digits=rounding) != 0:
taken_quantity = 0
self.env['base'].flush()
try:
with self.env.cr.savepoint():
if not float_is_zero(taken_quantity, precision_rounding=self.product_id.uom_id.rounding):
quants = self.env['stock.quant']._update_reserved_quantity(
self.product_id, location_id, taken_quantity, lot_id=lot_id,
package_id=package_id, owner_id=owner_id, strict=strict
)
except UserError:
taken_quantity = 0
# Find a candidate move line to update or create a new one.
serial_move_line_vals = []
for reserved_quant, quantity in quants:
to_update = next((line for line in self.move_line_ids if line._reservation_is_updatable(quantity, reserved_quant)), False)
if to_update:
uom_quantity = self.product_id.uom_id._compute_quantity(quantity, to_update.product_uom_id, rounding_method='HALF-UP')
uom_quantity = float_round(uom_quantity, precision_digits=rounding)
uom_quantity_back_to_product_uom = to_update.product_uom_id._compute_quantity(uom_quantity, self.product_id.uom_id, rounding_method='HALF-UP')
if to_update and float_compare(quantity, uom_quantity_back_to_product_uom, precision_digits=rounding) == 0:
to_update.with_context(bypass_reservation_update=True).product_uom_qty += uom_quantity
else:
if self.product_id.tracking == 'serial':
# Move lines with serial tracked product_id cannot be to-update candidates. Delay the creation to speed up candidates search + create.
serial_move_line_vals.extend([self._prepare_move_line_vals(quantity=1, reserved_quant=reserved_quant) for i in range(int(quantity))])
else:
self.env['stock.move.line'].create(self._prepare_move_line_vals(quantity=quantity, reserved_quant=reserved_quant))
self.env['stock.move.line'].create(serial_move_line_vals)
return taken_quantity
def _should_bypass_reservation(self, forced_location=False):
self.ensure_one()
location = forced_location or self.location_id
return location.should_bypass_reservation() or self.product_id.type != 'product'
# necessary hook to be able to override move reservation to a restrict lot, owner, pack, location...
def _get_available_quantity(self, location_id, lot_id=None, package_id=None, owner_id=None, strict=False, allow_negative=False):
self.ensure_one()
if location_id.should_bypass_reservation():
return self.product_qty
return self.env['stock.quant']._get_available_quantity(self.product_id, location_id, lot_id=lot_id, package_id=package_id, owner_id=owner_id, strict=strict, allow_negative=allow_negative)
def _get_available_move_lines_in(self):
move_lines_in = self.move_orig_ids.filtered(lambda m: m.state == 'done').mapped('move_line_ids')
keys_in_groupby = ['location_dest_id', 'lot_id', 'result_package_id', 'owner_id']
def _keys_in_sorted(ml):
return (ml.location_dest_id.id, ml.lot_id.id, ml.result_package_id.id, ml.owner_id.id)
grouped_move_lines_in = {}
for k, g in groupby(sorted(move_lines_in, key=_keys_in_sorted), key=itemgetter(*keys_in_groupby)):
qty_done = 0
for ml in g:
qty_done += ml.product_uom_id._compute_quantity(ml.qty_done, ml.product_id.uom_id)
grouped_move_lines_in[k] = qty_done
return grouped_move_lines_in
def _get_available_move_lines_out(self, assigned_moves_ids, partially_available_moves_ids):
move_lines_out_done = (self.move_orig_ids.mapped('move_dest_ids') - self)\
.filtered(lambda m: m.state in ['done'])\
.mapped('move_line_ids')
# As we defer the write on the stock.move's state at the end of the loop, there
# could be moves to consider in what our siblings already took.
StockMove = self.env['stock.move']
moves_out_siblings = self.move_orig_ids.mapped('move_dest_ids') - self
moves_out_siblings_to_consider = moves_out_siblings & (StockMove.browse(assigned_moves_ids) + StockMove.browse(partially_available_moves_ids))
reserved_moves_out_siblings = moves_out_siblings.filtered(lambda m: m.state in ['partially_available', 'assigned'])
move_lines_out_reserved = (reserved_moves_out_siblings | moves_out_siblings_to_consider).mapped('move_line_ids')
keys_out_groupby = ['location_id', 'lot_id', 'package_id', 'owner_id']
def _keys_out_sorted(ml):
return (ml.location_id.id, ml.lot_id.id, ml.package_id.id, ml.owner_id.id)
grouped_move_lines_out = {}
for k, g in groupby(sorted(move_lines_out_done, key=_keys_out_sorted), key=itemgetter(*keys_out_groupby)):
qty_done = 0
for ml in g:
qty_done += ml.product_uom_id._compute_quantity(ml.qty_done, ml.product_id.uom_id)
grouped_move_lines_out[k] = qty_done
for k, g in groupby(sorted(move_lines_out_reserved, key=_keys_out_sorted), key=itemgetter(*keys_out_groupby)):
grouped_move_lines_out[k] = sum(self.env['stock.move.line'].concat(*list(g)).mapped('product_qty'))
return grouped_move_lines_out
def _get_available_move_lines(self, assigned_moves_ids, partially_available_moves_ids):
grouped_move_lines_in = self._get_available_move_lines_in()
grouped_move_lines_out = self._get_available_move_lines_out(assigned_moves_ids, partially_available_moves_ids)
available_move_lines = {key: grouped_move_lines_in[key] - grouped_move_lines_out.get(key, 0) for key in grouped_move_lines_in}
# pop key if the quantity available amount to 0
rounding = self.product_id.uom_id.rounding
return dict((k, v) for k, v in available_move_lines.items() if float_compare(v, 0, precision_rounding=rounding) > 0)
def _action_assign(self):
""" Reserve stock moves by creating their stock move lines. A stock move is
considered reserved once the sum of `product_qty` for all its move lines is
equal to its `product_qty`. If it is less, the stock move is considered
partially available.
"""
StockMove = self.env['stock.move']
assigned_moves_ids = OrderedSet()
partially_available_moves_ids = OrderedSet()
# Read the `reserved_availability` field of the moves out of the loop to prevent unwanted
# cache invalidation when actually reserving the move.
reserved_availability = {move: move.reserved_availability for move in self}
roundings = {move: move.product_id.uom_id.rounding for move in self}
move_line_vals_list = []
# Once the quantities are assigned, we want to find a better destination location thanks
# to the putaway rules. This redirection will be applied on moves of `moves_to_redirect`.
moves_to_redirect = OrderedSet()
for move in self.filtered(lambda m: m.state in ['confirmed', 'waiting', 'partially_available']):
rounding = roundings[move]
missing_reserved_uom_quantity = move.product_uom_qty - reserved_availability[move]
missing_reserved_quantity = move.product_uom._compute_quantity(missing_reserved_uom_quantity, move.product_id.uom_id, rounding_method='HALF-UP')
if move._should_bypass_reservation():
# create the move line(s) but do not impact quants
if move.move_orig_ids:
available_move_lines = move._get_available_move_lines(assigned_moves_ids, partially_available_moves_ids)
for (location_id, lot_id, package_id, owner_id), quantity in available_move_lines.items():
qty_added = min(missing_reserved_quantity, quantity)
move_line_vals = move._prepare_move_line_vals(qty_added)
move_line_vals.update({
'location_id': location_id.id,
'lot_id': lot_id.id,
'lot_name': lot_id.name,
'owner_id': owner_id.id,
})
move_line_vals_list.append(move_line_vals)
missing_reserved_quantity -= qty_added
if float_is_zero(missing_reserved_quantity, precision_rounding=move.product_id.uom_id.rounding):
break
if missing_reserved_quantity and move.product_id.tracking == 'serial' and (move.picking_type_id.use_create_lots or move.picking_type_id.use_existing_lots):
for i in range(0, int(missing_reserved_quantity)):
move_line_vals_list.append(move._prepare_move_line_vals(quantity=1))
elif missing_reserved_quantity:
to_update = move.move_line_ids.filtered(lambda ml: ml.product_uom_id == move.product_uom and
ml.location_id == move.location_id and
ml.location_dest_id == move.location_dest_id and
ml.picking_id == move.picking_id and
not ml.lot_id and
not ml.package_id and
not ml.owner_id)
if to_update:
to_update[0].product_uom_qty += move.product_id.uom_id._compute_quantity(
missing_reserved_quantity, move.product_uom, rounding_method='HALF-UP')
else:
move_line_vals_list.append(move._prepare_move_line_vals(quantity=missing_reserved_quantity))
assigned_moves_ids.add(move.id)
moves_to_redirect.add(move.id)
else:
if float_is_zero(move.product_uom_qty, precision_rounding=move.product_uom.rounding):
assigned_moves_ids.add(move.id)
elif not move.move_orig_ids:
if move.procure_method == 'make_to_order':
continue
# If we don't need any quantity, consider the move assigned.
need = missing_reserved_quantity
if float_is_zero(need, precision_rounding=rounding):
assigned_moves_ids.add(move.id)
continue
# Reserve new quants and create move lines accordingly.
forced_package_id = move.package_level_id.package_id or None
available_quantity = move._get_available_quantity(move.location_id, package_id=forced_package_id)
if available_quantity <= 0:
continue
taken_quantity = move._update_reserved_quantity(need, available_quantity, move.location_id, package_id=forced_package_id, strict=False)
if float_is_zero(taken_quantity, precision_rounding=rounding):
continue
moves_to_redirect.add(move.id)
if float_compare(need, taken_quantity, precision_rounding=rounding) == 0:
assigned_moves_ids.add(move.id)
else:
partially_available_moves_ids.add(move.id)
else:
# Check what our parents brought and what our siblings took in order to
# determine what we can distribute.
# `qty_done` is in `ml.product_uom_id` and, as we will later increase
# the reserved quantity on the quants, convert it here in
# `product_id.uom_id` (the UOM of the quants is the UOM of the product).
available_move_lines = move._get_available_move_lines(assigned_moves_ids, partially_available_moves_ids)
if not available_move_lines:
continue
for move_line in move.move_line_ids.filtered(lambda m: m.product_qty):
if available_move_lines.get((move_line.location_id, move_line.lot_id, move_line.result_package_id, move_line.owner_id)):
available_move_lines[(move_line.location_id, move_line.lot_id, move_line.result_package_id, move_line.owner_id)] -= move_line.product_qty
for (location_id, lot_id, package_id, owner_id), quantity in available_move_lines.items():
need = move.product_qty - sum(move.move_line_ids.mapped('product_qty'))
# `quantity` is what is brought by chained done move lines. We double check
# here this quantity is available on the quants themselves. If not, this
# could be the result of an inventory adjustment that removed totally of
# partially `quantity`. When this happens, we chose to reserve the maximum
# still available. This situation could not happen on MTS move, because in
# this case `quantity` is directly the quantity on the quants themselves.
available_quantity = move._get_available_quantity(location_id, lot_id=lot_id, package_id=package_id, owner_id=owner_id, strict=True)
if float_is_zero(available_quantity, precision_rounding=rounding):
continue
taken_quantity = move._update_reserved_quantity(need, min(quantity, available_quantity), location_id, lot_id, package_id, owner_id)
if float_is_zero(taken_quantity, precision_rounding=rounding):
continue
moves_to_redirect.add(move.id)
if float_is_zero(need - taken_quantity, precision_rounding=rounding):
assigned_moves_ids.add(move.id)
break
partially_available_moves_ids.add(move.id)
if move.product_id.tracking == 'serial':
move.next_serial_count = move.product_uom_qty
self.env['stock.move.line'].create(move_line_vals_list)
StockMove.browse(partially_available_moves_ids).write({'state': 'partially_available'})
StockMove.browse(assigned_moves_ids).write({'state': 'assigned'})
if not self.env.context.get('bypass_entire_pack'):
self.mapped('picking_id')._check_entire_pack()
StockMove.browse(moves_to_redirect).move_line_ids._apply_putaway_strategy()
def _action_cancel(self):
if any(move.state == 'done' and not move.scrapped for move in self):
raise UserError(_('You cannot cancel a stock move that has been set to \'Done\'. Create a return in order to reverse the moves which took place.'))
moves_to_cancel = self.filtered(lambda m: m.state != 'cancel' and not (m.state == 'done' and m.scrapped))
# self cannot contain moves that are either cancelled or done, therefore we can safely
# unlink all associated move_line_ids
moves_to_cancel._do_unreserve()
for move in moves_to_cancel:
siblings_states = (move.move_dest_ids.mapped('move_orig_ids') - move).mapped('state')
if move.propagate_cancel:
# only cancel the next move if all my siblings are also cancelled
if all(state == 'cancel' for state in siblings_states):
move.move_dest_ids.filtered(lambda m: m.state != 'done')._action_cancel()
else:
if all(state in ('done', 'cancel') for state in siblings_states):
move.move_dest_ids.write({'procure_method': 'make_to_stock'})
move.move_dest_ids.write({'move_orig_ids': [(3, move.id, 0)]})
moves_to_cancel.write({
'state': 'cancel',
'move_orig_ids': [(5, 0, 0)],
'procure_method': 'make_to_stock',
})
return True
def _prepare_extra_move_vals(self, qty):
vals = {
'procure_method': 'make_to_stock',
'origin_returned_move_id': self.origin_returned_move_id.id,
'product_uom_qty': qty,
'picking_id': self.picking_id.id,
'price_unit': self.price_unit,
}
return vals
def _create_extra_move(self):
""" If the quantity done on a move exceeds its quantity todo, this method will create an
extra move attached to a (potentially split) move line. If the previous condition is not
met, it'll return an empty recordset.
The rationale for the creation of an extra move is the application of a potential push
rule that will handle the extra quantities.
"""
extra_move = self
rounding = self.product_uom.rounding
# moves created after the picking is assigned do not have `product_uom_qty`, but we shouldn't create extra moves for them
if float_compare(self.quantity_done, self.product_uom_qty, precision_rounding=rounding) > 0:
# create the extra moves
extra_move_quantity = float_round(
self.quantity_done - self.product_uom_qty,
precision_rounding=rounding,
rounding_method='HALF-UP')
extra_move_vals = self._prepare_extra_move_vals(extra_move_quantity)
extra_move = self.copy(default=extra_move_vals).with_context(avoid_putaway_rules=True)
merge_into_self = all(self[field] == extra_move[field] for field in self._prepare_merge_moves_distinct_fields())
if merge_into_self:
extra_move = extra_move._action_confirm(merge_into=self)
return extra_move
else:
extra_move = extra_move._action_confirm()
return extra_move | self
def _action_done(self, cancel_backorder=False):
moves = self.filtered(lambda move: move.state == 'draft')._action_confirm() # MRP allows scrapping draft moves
moves = (self | moves).exists().filtered(lambda x: x.state not in ('done', 'cancel'))
moves_ids_todo = OrderedSet()
# Cancel moves where necessary ; we should do it before creating the extra moves because
# this operation could trigger a merge of moves.
for move in moves:
if move.quantity_done <= 0 and not move.is_inventory:
if float_compare(move.product_uom_qty, 0.0, precision_rounding=move.product_uom.rounding) == 0 or cancel_backorder:
move._action_cancel()
# Create extra moves where necessary
for move in moves:
if move.state == 'cancel' or (move.quantity_done <= 0 and not move.is_inventory):
continue
moves_ids_todo |= move._create_extra_move().ids
moves_todo = self.browse(moves_ids_todo)
moves_todo._check_company()
# Split moves where necessary and move quants
backorder_moves_vals = []
for move in moves_todo:
# To know whether we need to create a backorder or not, round to the general product's
# decimal precision and not the product's UOM.
rounding = self.env['decimal.precision'].precision_get('Product Unit of Measure')
if float_compare(move.quantity_done, move.product_uom_qty, precision_digits=rounding) < 0:
# Need to do some kind of conversion here
qty_split = move.product_uom._compute_quantity(move.product_uom_qty - move.quantity_done, move.product_id.uom_id, rounding_method='HALF-UP')
new_move_vals = move._split(qty_split)
backorder_moves_vals += new_move_vals
backorder_moves = self.env['stock.move'].create(backorder_moves_vals)
# The backorder moves are not yet in their own picking. We do not want to check entire packs for those
# ones as it could messed up the result_package_id of the moves being currently validated
backorder_moves.with_context(bypass_entire_pack=True)._action_confirm(merge=False)
if cancel_backorder:
backorder_moves.with_context(moves_todo=moves_todo)._action_cancel()
moves_todo.mapped('move_line_ids').sorted()._action_done()
# Check the consistency of the result packages; there should be an unique location across
# the contained quants.
for result_package in moves_todo\
.mapped('move_line_ids.result_package_id')\
.filtered(lambda p: p.quant_ids and len(p.quant_ids) > 1):
if len(result_package.quant_ids.filtered(lambda q: not float_is_zero(abs(q.quantity) + abs(q.reserved_quantity), precision_rounding=q.product_uom_id.rounding)).mapped('location_id')) > 1:
raise UserError(_('You cannot move the same package content more than once in the same transfer or split the same package into two location.'))
if any(ml.package_id and ml.package_id == ml.result_package_id for ml in moves_todo.move_line_ids):
self.env['stock.quant']._unlink_zero_quants()
picking = moves_todo.mapped('picking_id')
moves_todo.write({'state': 'done', 'date': fields.Datetime.now()})
new_push_moves = moves_todo.filtered(lambda m: m.picking_id.immediate_transfer)._push_apply()
if new_push_moves:
new_push_moves._action_confirm()
move_dests_per_company = defaultdict(lambda: self.env['stock.move'])
for move_dest in moves_todo.move_dest_ids:
move_dests_per_company[move_dest.company_id.id] |= move_dest
for company_id, move_dests in move_dests_per_company.items():
move_dests.sudo().with_company(company_id)._action_assign()
# We don't want to create back order for scrap moves
# Replace by a kwarg in master
if self.env.context.get('is_scrap'):
return moves_todo
if picking and not cancel_backorder:
backorder = picking._create_backorder()
if any([m.state == 'assigned' for m in backorder.move_lines]):
backorder._check_entire_pack()
return moves_todo
@api.ondelete(at_uninstall=False)
def _unlink_if_draft_or_cancel(self):
if any(move.state not in ('draft', 'cancel') for move in self):
raise UserError(_('You can only delete draft moves.'))
def unlink(self):
# With the non plannified picking, draft moves could have some move lines.
self.with_context(prefetch_fields=False).mapped('move_line_ids').unlink()
return super(StockMove, self).unlink()
def _prepare_move_split_vals(self, qty):
vals = {
'product_uom_qty': qty,
'procure_method': self.procure_method,
'move_dest_ids': [(4, x.id) for x in self.move_dest_ids if x.state not in ('done', 'cancel')],
'move_orig_ids': [(4, x.id) for x in self.move_orig_ids],
'origin_returned_move_id': self.origin_returned_move_id.id,
'price_unit': self.price_unit,
}
if self.env.context.get('force_split_uom_id'):
vals['product_uom'] = self.env.context['force_split_uom_id']
return vals
def _split(self, qty, restrict_partner_id=False):
""" Splits `self` quantity and return values for a new moves to be created afterwards
:param qty: float. quantity to split (given in product UoM)
:param restrict_partner_id: optional partner that can be given in order to force the new move to restrict its choice of quants to the ones belonging to this partner.
:returns: list of dict. stock move values """
self.ensure_one()
if self.state in ('done', 'cancel'):
raise UserError(_('You cannot split a stock move that has been set to \'Done\'.'))
elif self.state == 'draft':
# we restrict the split of a draft move because if not confirmed yet, it may be replaced by several other moves in
# case of phantom bom (with mrp module). And we don't want to deal with this complexity by copying the product that will explode.
raise UserError(_('You cannot split a draft move. It needs to be confirmed first.'))
if float_is_zero(qty, precision_rounding=self.product_id.uom_id.rounding) or self.product_qty <= qty:
return []
decimal_precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')
# `qty` passed as argument is the quantity to backorder and is always expressed in the
# quants UOM. If we're able to convert back and forth this quantity in the move's and the
# quants UOM, the backordered move can keep the UOM of the move. Else, we'll create is in
# the UOM of the quants.
uom_qty = self.product_id.uom_id._compute_quantity(qty, self.product_uom, rounding_method='HALF-UP')
if float_compare(qty, self.product_uom._compute_quantity(uom_qty, self.product_id.uom_id, rounding_method='HALF-UP'), precision_digits=decimal_precision) == 0:
defaults = self._prepare_move_split_vals(uom_qty)
else:
defaults = self.with_context(force_split_uom_id=self.product_id.uom_id.id)._prepare_move_split_vals(qty)
if restrict_partner_id:
defaults['restrict_partner_id'] = restrict_partner_id
# TDE CLEANME: remove context key + add as parameter
if self.env.context.get('source_location_id'):
defaults['location_id'] = self.env.context['source_location_id']
new_move_vals = self.copy_data(defaults)
# Update the original `product_qty` of the move. Use the general product's decimal
# precision and not the move's UOM to handle case where the `quantity_done` is not
# compatible with the move's UOM.
new_product_qty = self.product_id.uom_id._compute_quantity(self.product_qty - qty, self.product_uom, round=False)
new_product_qty = float_round(new_product_qty, precision_digits=self.env['decimal.precision'].precision_get('Product Unit of Measure'))
self.with_context(do_not_unreserve=True).write({'product_uom_qty': new_product_qty})
return new_move_vals
def _recompute_state(self):
moves_state_to_write = defaultdict(set)
for move in self:
rounding = move.product_uom.rounding
if move.state in ('cancel', 'done', 'draft'):
continue
elif float_compare(move.reserved_availability, move.product_uom_qty, precision_rounding=rounding) == 0:
moves_state_to_write['assigned'].add(move.id)
elif move.reserved_availability and float_compare(move.reserved_availability, move.product_uom_qty, precision_rounding=rounding) <= 0:
moves_state_to_write['partially_available'].add(move.id)
elif move.procure_method == 'make_to_order' and not move.move_orig_ids:
moves_state_to_write['waiting'].add(move.id)
elif move.move_orig_ids and any(orig.state not in ('done', 'cancel') for orig in move.move_orig_ids):
moves_state_to_write['waiting'].add(move.id)
else:
moves_state_to_write['confirmed'].add(move.id)
for state, moves_ids in moves_state_to_write.items():
self.browse(moves_ids).filtered(lambda m: m.state != state).state = state
@api.model
def _consuming_picking_types(self):
return ['outgoing']
def _get_lang(self):
"""Determine language to use for translated description"""
return self.picking_id.partner_id.lang or self.partner_id.lang or self.env.user.lang
def _get_source_document(self):
""" Return the move's document, used by `report.stock.report_product_product_replenishment`
and must be overrided to add more document type in the report.
"""
self.ensure_one()
return self.picking_id or False
def _get_upstream_documents_and_responsibles(self, visited):
if self.move_orig_ids and any(m.state not in ('done', 'cancel') for m in self.move_orig_ids):
result = set()
visited |= self
for move in self.move_orig_ids:
if move.state not in ('done', 'cancel'):
for document, responsible, visited in move._get_upstream_documents_and_responsibles(visited):
result.add((document, responsible, visited))
return result
else:
return []
def _set_quantity_done_prepare_vals(self, qty):
res = []
for ml in self.move_line_ids:
ml_qty = ml.product_uom_qty - ml.qty_done
if float_compare(ml_qty, 0, precision_rounding=ml.product_uom_id.rounding) <= 0:
continue
# Convert move line qty into move uom
if ml.product_uom_id != self.product_uom:
ml_qty = ml.product_uom_id._compute_quantity(ml_qty, self.product_uom, round=False)
taken_qty = min(qty, ml_qty)
# Convert taken qty into move line uom
if ml.product_uom_id != self.product_uom:
taken_qty = self.product_uom._compute_quantity(ml_qty, ml.product_uom_id, round=False)
# Assign qty_done and explicitly round to make sure there is no inconsistency between
# ml.qty_done and qty.
taken_qty = float_round(taken_qty, precision_rounding=ml.product_uom_id.rounding)
res.append((1, ml.id, {'qty_done': ml.qty_done + taken_qty}))
if ml.product_uom_id != self.product_uom:
taken_qty = ml.product_uom_id._compute_quantity(ml_qty, self.product_uom, round=False)
qty -= taken_qty
if float_compare(qty, 0.0, precision_rounding=self.product_uom.rounding) <= 0:
break
for ml in self.move_line_ids:
if float_is_zero(ml.product_uom_qty, precision_rounding=ml.product_uom_id.rounding) and float_is_zero(ml.qty_done, precision_rounding=ml.product_uom_id.rounding):
res.append((2, ml.id))
if float_compare(qty, 0.0, precision_rounding=self.product_uom.rounding) > 0:
if self.product_id.tracking != 'serial':
vals = self._prepare_move_line_vals(quantity=0)
vals['qty_done'] = qty
res.append((0, 0, vals))
else:
uom_qty = self.product_uom._compute_quantity(qty, self.product_id.uom_id)
for i in range(0, int(uom_qty)):
vals = self._prepare_move_line_vals(quantity=0)
vals['qty_done'] = 1
vals['product_uom_id'] = self.product_id.uom_id.id
res.append((0, 0, vals))
return res
def _set_quantity_done(self, qty):
"""
Set the given quantity as quantity done on the move through the move lines. The method is
able to handle move lines with a different UoM than the move (but honestly, this would be
looking for trouble...).
@param qty: quantity in the UoM of move.product_uom
"""
existing_smls = self.move_line_ids
self.move_line_ids = self._set_quantity_done_prepare_vals(qty)
# `_set_quantity_done_prepare_vals` may return some commands to create new SMLs
# These new SMLs need to be redirected thanks to putaway rules
(self.move_line_ids - existing_smls)._apply_putaway_strategy()
def _set_quantities_to_reservation(self):
for move in self:
if move.state not in ('partially_available', 'assigned'):
continue
for move_line in move.move_line_ids:
if move.has_tracking == 'none' or\
(move.picking_type_id.use_existing_lots and move_line.lot_id) or\
(move.picking_type_id.use_create_lots and move_line.lot_name) or\
(not move.picking_type_id.use_existing_lots and not move.picking_type_id.use_create_lots):
move_line.qty_done = move_line.product_uom_qty
def _adjust_procure_method(self):
""" This method will try to apply the procure method MTO on some moves if
a compatible MTO route is found. Else the procure method will be set to MTS
"""
# Prepare the MTSO variables. They are needed since MTSO moves are handled separately.
# We need 2 dicts:
# - needed quantity per location per product
# - forecasted quantity per location per product
mtso_products_by_locations = defaultdict(list)
mtso_needed_qties_by_loc = defaultdict(dict)
mtso_free_qties_by_loc = {}
mtso_moves = self.env['stock.move']
for move in self:
product_id = move.product_id
domain = [
('location_src_id', '=', move.location_id.id),
('location_id', '=', move.location_dest_id.id),
('action', '!=', 'push')
]
rules = self.env['procurement.group']._search_rule(False, move.product_packaging_id, product_id, move.warehouse_id, domain)
if rules:
if rules.procure_method in ['make_to_order', 'make_to_stock']:
move.procure_method = rules.procure_method
else:
# Get the needed quantity for the `mts_else_mto` moves.
mtso_needed_qties_by_loc[rules.location_src_id].setdefault(product_id.id, 0)
mtso_needed_qties_by_loc[rules.location_src_id][product_id.id] += move.product_qty
# This allow us to get the forecasted quantity in batch later on
mtso_products_by_locations[rules.location_src_id].append(product_id.id)
mtso_moves |= move
else:
move.procure_method = 'make_to_stock'
# Get the forecasted quantity for the `mts_else_mto` moves.
for location, product_ids in mtso_products_by_locations.items():
products = self.env['product.product'].browse(product_ids).with_context(location=location.id)
mtso_free_qties_by_loc[location] = {product.id: product.free_qty for product in products}
# Now that we have the needed and forecasted quantity per location and per product, we can
# choose whether the mtso_moves need to be MTO or MTS.
for move in mtso_moves:
needed_qty = move.product_qty
forecasted_qty = mtso_free_qties_by_loc[move.location_id][move.product_id.id]
if float_compare(needed_qty, forecasted_qty, precision_rounding=move.product_uom.rounding) <= 0:
move.procure_method = 'make_to_stock'
mtso_free_qties_by_loc[move.location_id][move.product_id.id] -= needed_qty
else:
move.procure_method = 'make_to_order'
def _show_details_in_draft(self):
self.ensure_one()
return self.state != 'draft' or (self.picking_id.immediate_transfer and self.state == 'draft')
def _trigger_scheduler(self):
""" Check for auto-triggered orderpoints and trigger them. """
if not self or self.env['ir.config_parameter'].sudo().get_param('stock.no_auto_scheduler'):
return
orderpoints_by_company = defaultdict(lambda: self.env['stock.warehouse.orderpoint'])
orderpoints_context_by_company = defaultdict(dict)
for move in self:
orderpoint = self.env['stock.warehouse.orderpoint'].search([
('product_id', '=', move.product_id.id),
('trigger', '=', 'auto'),
('location_id', 'parent_of', move.location_id.id),
('company_id', '=', move.company_id.id),
'!', ('location_id', 'parent_of', move.location_dest_id.id),
], limit=1)
if orderpoint:
orderpoints_by_company[orderpoint.company_id] |= orderpoint
if orderpoint and move.product_qty > orderpoint.product_min_qty and move.origin:
orderpoints_context_by_company[orderpoint.company_id].setdefault(orderpoint.id, [])
orderpoints_context_by_company[orderpoint.company_id][orderpoint.id].append(move.origin)
for company, orderpoints in orderpoints_by_company.items():
orderpoints.with_context(origins=orderpoints_context_by_company[company])._procure_orderpoint_confirm(
company_id=company, raise_user_error=False)
def _trigger_assign(self):
""" Check for and trigger action_assign for confirmed/partially_available moves related to done moves.
Disable auto reservation if user configured to do so.
"""
if not self or self.env['ir.config_parameter'].sudo().get_param('stock.picking_no_auto_reserve'):
return
domains = []
for move in self:
domains.append([('product_id', '=', move.product_id.id), ('location_id', '=', move.location_dest_id.id)])
static_domain = [('state', 'in', ['confirmed', 'partially_available']),
('procure_method', '=', 'make_to_stock'),
('reservation_date', '<=', fields.Date.today())]
moves_to_reserve = self.env['stock.move'].search(expression.AND([static_domain, expression.OR(domains)]),
order='reservation_date, priority desc, date asc, id asc')
moves_to_reserve._action_assign()
def _rollup_move_dests(self, seen):
for dst in self.move_dest_ids:
if dst.id not in seen:
seen.add(dst.id)
dst._rollup_move_dests(seen)
return seen
def _get_forecast_availability_outgoing(self, warehouse):
""" Get forcasted information (sum_qty_expected, max_date_expected) of self for in_locations_ids as the in locations.
It differ from _get_report_lines because it computes only the necessary information and return a
dict by move, which is making faster to use and compute.
:param qty: ids list/tuple of locations to consider as interne
:return: a defaultdict of moves in self, values are tuple(sum_qty_expected, max_date_expected)
:rtype: defaultdict
"""
def _reconcile_out_with_ins(result, out, ins, demand, product_rounding, only_matching_move_dest=True):
index_to_remove = []
for index, in_ in enumerate(ins):
if float_is_zero(in_['qty'], precision_rounding=product_rounding):
index_to_remove.append(index)
continue
if only_matching_move_dest and in_['move_dests'] and out.id not in in_['move_dests']:
continue
taken_from_in = min(demand, in_['qty'])
demand -= taken_from_in
if out.id in ids_in_self:
result[out] = (result[out][0] + taken_from_in, max(d for d in (in_['move_date'], result[out][1]) if d))
in_['qty'] -= taken_from_in
if in_['qty'] <= 0:
index_to_remove.append(index)
if float_is_zero(demand, precision_rounding=product_rounding):
break
for index in reversed(index_to_remove):
# TODO: avoid this O(n²), maybe we shouldn't "clean" the in list
del ins[index]
return demand
ids_in_self = set(self.ids)
product_ids = self.product_id
wh_location_query = self.env['stock.location']._search([('id', 'child_of', warehouse.view_location_id.id)])
in_domain, out_domain = self.env['report.stock.report_product_product_replenishment']._move_confirmed_domain(
None, product_ids.ids, wh_location_query
)
outs = self.env['stock.move'].search(out_domain, order='reservation_date, priority desc, date, id')
reserved_outs = self.env['stock.move'].search(
out_domain + [('state', 'in', ('partially_available', 'assigned'))],
order='priority desc, date, id')
ins = self.env['stock.move'].search(in_domain, order='priority desc, date, id')
# Prefetch data to avoid future request
(outs - self).read(['product_id', 'product_uom', 'product_qty', 'state'], load=False) # remove self because data is already fetch
ins.read(['product_id', 'product_qty', 'date', 'move_dest_ids'], load=False)
currents = product_ids.with_context(warehouse=warehouse.id)._get_only_qty_available()
outs_per_product = defaultdict(list)
reserved_outs_per_product = defaultdict(list)
ins_per_product = defaultdict(list)
for out in outs:
outs_per_product[out.product_id.id].append(out)
for out in reserved_outs:
reserved_outs_per_product[out.product_id.id].append(out)
for in_ in ins:
ins_per_product[in_.product_id.id].append({
'qty': in_.product_qty,
'move_date': in_.date,
'move_dests': in_._rollup_move_dests(set())
})
result = defaultdict(lambda: (0.0, False))
for product in product_ids:
product_rounding = product.uom_id.rounding
for out in reserved_outs_per_product[product.id]:
# Reconcile with reserved stock.
current = currents[product.id]
reserved = out.product_uom._compute_quantity(out.reserved_availability, product.uom_id)
currents[product.id] -= reserved
if out.id in ids_in_self:
result[out] = (result[out][0] + reserved, False)
unreconciled_outs = []
for out in outs_per_product[product.id]:
# Reconcile with the current stock.
reserved = 0.0
if out.state in ('partially_available', 'assigned'):
reserved = out.product_uom._compute_quantity(out.reserved_availability, product.uom_id)
demand = out.product_qty - reserved
if float_is_zero(demand, precision_rounding=product_rounding):
continue
current = currents[product.id]
taken_from_stock = min(demand, current)
if not float_is_zero(taken_from_stock, precision_rounding=product_rounding):
currents[product.id] -= taken_from_stock
demand -= taken_from_stock
if out.id in ids_in_self:
result[out] = (result[out][0] + taken_from_stock, False)
# Reconcile with the ins.
# The while loop will finish because it will pop from ins_per_product or decrease the demand until zero
if not float_is_zero(demand, precision_rounding=product_rounding):
demand = _reconcile_out_with_ins(result, out, ins_per_product[product.id], demand, product_rounding, only_matching_move_dest=True)
if not float_is_zero(demand, precision_rounding=product_rounding):
unreconciled_outs.append((demand, out))
for demand, out in unreconciled_outs:
remaining = _reconcile_out_with_ins(result, out, ins_per_product[product.id], demand, product_rounding, only_matching_move_dest=False)
if not float_is_zero(remaining, precision_rounding=out.product_id.uom_id.rounding) and out not in result:
result[out] = (-remaining, False)
return result
def _get_moves_orig(self, moves=False):
self.ensure_one()
if not moves:
moves = self.env['stock.move']
if self in moves:
return self.env['stock.move']
if self.picking_type_id.code == 'incoming':
return self.env['stock.move']
moves |= self
for move in self.move_orig_ids:
moves |= move._get_moves_orig(moves)
return moves
| 56.920481
| 123,119
|
9,211
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, api, fields, models
class Company(models.Model):
_inherit = "res.company"
_check_company_auto = True
def _default_confirmation_mail_template(self):
try:
return self.env.ref('stock.mail_template_data_delivery_confirmation').id
except ValueError:
return False
internal_transit_location_id = fields.Many2one(
'stock.location', 'Internal Transit Location', ondelete="restrict", check_company=True,
help="Technical field used for resupply routes between warehouses that belong to this company")
stock_move_email_validation = fields.Boolean("Email Confirmation picking", default=False)
stock_mail_confirmation_template_id = fields.Many2one('mail.template', string="Email Template confirmation picking",
domain="[('model', '=', 'stock.picking')]",
default=_default_confirmation_mail_template,
help="Email sent to the customer once the order is done.")
annual_inventory_month = fields.Selection([
('1', 'January'),
('2', 'February'),
('3', 'March'),
('4', 'April'),
('5', 'May'),
('6', 'June'),
('7', 'July'),
('8', 'August'),
('9', 'September'),
('10', 'October'),
('11', 'November'),
('12', 'December'),
], string='Annual Inventory Month',
default='12',
help="Annual inventory month for products not in a location with a cyclic inventory date. Set to no month if no automatic annual inventory.")
annual_inventory_day = fields.Integer(
string='Day of the month', default=31,
help="""Day of the month when the annual inventory should occur. If zero or negative, then the first day of the month will be selected instead.
If greater than the last day of a month, then the last day of the month will be selected instead.""")
def _create_transit_location(self):
'''Create a transit location with company_id being the given company_id. This is needed
in case of resuply routes between warehouses belonging to the same company, because
we don't want to create accounting entries at that time.
'''
parent_location = self.env.ref('stock.stock_location_locations', raise_if_not_found=False)
for company in self:
location = self.env['stock.location'].create({
'name': _('Inter-warehouse transit'),
'usage': 'transit',
'location_id': parent_location and parent_location.id or False,
'company_id': company.id,
'active': False
})
company.write({'internal_transit_location_id': location.id})
company.partner_id.with_company(company).write({
'property_stock_customer': location.id,
'property_stock_supplier': location.id,
})
def _create_inventory_loss_location(self):
parent_location = self.env.ref('stock.stock_location_locations_virtual', raise_if_not_found=False)
for company in self:
inventory_loss_location = self.env['stock.location'].create({
'name': 'Inventory adjustment',
'usage': 'inventory',
'location_id': parent_location.id,
'company_id': company.id,
})
self.env['ir.property']._set_default(
"property_stock_inventory",
"product.template",
inventory_loss_location,
company.id,
)
def _create_production_location(self):
parent_location = self.env.ref('stock.stock_location_locations_virtual', raise_if_not_found=False)
for company in self:
production_location = self.env['stock.location'].create({
'name': 'Production',
'usage': 'production',
'location_id': parent_location.id,
'company_id': company.id,
})
self.env['ir.property']._set_default(
"property_stock_production",
"product.template",
production_location,
company.id,
)
def _create_scrap_location(self):
parent_location = self.env.ref('stock.stock_location_locations_virtual', raise_if_not_found=False)
for company in self:
scrap_location = self.env['stock.location'].create({
'name': 'Scrap',
'usage': 'inventory',
'location_id': parent_location.id,
'company_id': company.id,
'scrap_location': True,
})
def _create_scrap_sequence(self):
scrap_vals = []
for company in self:
scrap_vals.append({
'name': '%s Sequence scrap' % company.name,
'code': 'stock.scrap',
'company_id': company.id,
'prefix': 'SP/',
'padding': 5,
'number_next': 1,
'number_increment': 1
})
if scrap_vals:
self.env['ir.sequence'].create(scrap_vals)
@api.model
def create_missing_warehouse(self):
""" This hook is used to add a warehouse on existing companies
when module stock is installed.
"""
company_ids = self.env['res.company'].search([])
company_with_warehouse = self.env['stock.warehouse'].with_context(active_test=False).search([]).mapped('company_id')
company_without_warehouse = company_ids - company_with_warehouse
for company in company_without_warehouse:
self.env['stock.warehouse'].create({
'name': company.name,
'code': company.name[:5],
'company_id': company.id,
'partner_id': company.partner_id.id,
})
@api.model
def create_missing_transit_location(self):
company_without_transit = self.env['res.company'].search([('internal_transit_location_id', '=', False)])
company_without_transit._create_transit_location()
@api.model
def create_missing_inventory_loss_location(self):
company_ids = self.env['res.company'].search([])
inventory_loss_product_template_field = self.env['ir.model.fields']._get('product.template', 'property_stock_inventory')
companies_having_property = self.env['ir.property'].sudo().search([('fields_id', '=', inventory_loss_product_template_field.id), ('res_id', '=', False)]).mapped('company_id')
company_without_property = company_ids - companies_having_property
company_without_property._create_inventory_loss_location()
@api.model
def create_missing_production_location(self):
company_ids = self.env['res.company'].search([])
production_product_template_field = self.env['ir.model.fields']._get('product.template', 'property_stock_production')
companies_having_property = self.env['ir.property'].sudo().search([('fields_id', '=', production_product_template_field.id), ('res_id', '=', False)]).mapped('company_id')
company_without_property = company_ids - companies_having_property
company_without_property._create_production_location()
@api.model
def create_missing_scrap_location(self):
company_ids = self.env['res.company'].search([])
companies_having_scrap_loc = self.env['stock.location'].search([('scrap_location', '=', True)]).mapped('company_id')
company_without_property = company_ids - companies_having_scrap_loc
company_without_property._create_scrap_location()
@api.model
def create_missing_scrap_sequence(self):
company_ids = self.env['res.company'].search([])
company_has_scrap_seq = self.env['ir.sequence'].search([('code', '=', 'stock.scrap')]).mapped('company_id')
company_todo_sequence = company_ids - company_has_scrap_seq
company_todo_sequence._create_scrap_sequence()
def _create_per_company_locations(self):
self.ensure_one()
self._create_transit_location()
self._create_inventory_loss_location()
self._create_production_location()
self._create_scrap_location()
def _create_per_company_sequences(self):
self.ensure_one()
self._create_scrap_sequence()
def _create_per_company_picking_types(self):
self.ensure_one()
def _create_per_company_rules(self):
self.ensure_one()
@api.model
def create(self, vals):
company = super(Company, self).create(vals)
company.sudo()._create_per_company_locations()
company.sudo()._create_per_company_sequences()
company.sudo()._create_per_company_picking_types()
company.sudo()._create_per_company_rules()
self.env['stock.warehouse'].sudo().create({
'name': company.name,
'code': self.env.context.get('default_code') or company.name[:5],
'company_id': company.id,
'partner_id': company.partner_id.id
})
return company
| 44.497585
| 9,211
|
30,378
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from collections import defaultdict
from datetime import datetime, time
from dateutil import relativedelta
from itertools import groupby
from psycopg2 import OperationalError
from odoo import SUPERUSER_ID, _, api, fields, models, registry
from odoo.addons.stock.models.stock_rule import ProcurementException
from odoo.exceptions import RedirectWarning, UserError, ValidationError
from odoo.osv import expression
from odoo.tools import add, float_compare, frozendict, split_every
_logger = logging.getLogger(__name__)
class StockWarehouseOrderpoint(models.Model):
""" Defines Minimum stock rules. """
_name = "stock.warehouse.orderpoint"
_description = "Minimum Inventory Rule"
_check_company_auto = True
_order = "location_id,company_id,id"
@api.model
def default_get(self, fields):
res = super().default_get(fields)
warehouse = None
if 'warehouse_id' not in res and res.get('company_id'):
warehouse = self.env['stock.warehouse'].search([('company_id', '=', res['company_id'])], limit=1)
if warehouse:
res['warehouse_id'] = warehouse.id
res['location_id'] = warehouse.lot_stock_id.id
return res
@api.model
def _domain_product_id(self):
domain = "('type', '=', 'product')"
if self.env.context.get('active_model') == 'product.template':
product_template_id = self.env.context.get('active_id', False)
domain = f"('product_tmpl_id', '=', {product_template_id})"
elif self.env.context.get('default_product_id', False):
product_id = self.env.context.get('default_product_id', False)
domain = f"('id', '=', {product_id})"
return f"[{domain}, '|', ('company_id', '=', False), ('company_id', '=', company_id)]"
name = fields.Char(
'Name', copy=False, required=True, readonly=True,
default=lambda self: self.env['ir.sequence'].next_by_code('stock.orderpoint'))
trigger = fields.Selection([
('auto', 'Auto'), ('manual', 'Manual')], string='Trigger', default='auto', required=True)
active = fields.Boolean(
'Active', default=True,
help="If the active field is set to False, it will allow you to hide the orderpoint without removing it.")
snoozed_until = fields.Date('Snoozed', help="Hidden until next scheduler.")
warehouse_id = fields.Many2one(
'stock.warehouse', 'Warehouse',
check_company=True, ondelete="cascade", required=True)
location_id = fields.Many2one(
'stock.location', 'Location', index=True,
ondelete="cascade", required=True, check_company=True)
product_tmpl_id = fields.Many2one('product.template', related='product_id.product_tmpl_id')
product_id = fields.Many2one(
'product.product', 'Product', index=True,
domain=lambda self: self._domain_product_id(),
ondelete='cascade', required=True, check_company=True)
product_category_id = fields.Many2one('product.category', name='Product Category', related='product_id.categ_id', store=True)
product_uom = fields.Many2one(
'uom.uom', 'Unit of Measure', related='product_id.uom_id')
product_uom_name = fields.Char(string='Product unit of measure label', related='product_uom.display_name', readonly=True)
product_min_qty = fields.Float(
'Min Quantity', digits='Product Unit of Measure', required=True, default=0.0,
help="When the virtual stock goes below the Min Quantity specified for this field, Odoo generates "
"a procurement to bring the forecasted quantity to the Max Quantity.")
product_max_qty = fields.Float(
'Max Quantity', digits='Product Unit of Measure', required=True, default=0.0,
help="When the virtual stock goes below the Min Quantity, Odoo generates "
"a procurement to bring the forecasted quantity to the Quantity specified as Max Quantity.")
qty_multiple = fields.Float(
'Multiple Quantity', digits='Product Unit of Measure',
default=1, required=True,
help="The procurement quantity will be rounded up to this multiple. If it is 0, the exact quantity will be used.")
group_id = fields.Many2one(
'procurement.group', 'Procurement Group', copy=False,
help="Moves created through this orderpoint will be put in this procurement group. If none is given, the moves generated by stock rules will be grouped into one big picking.")
company_id = fields.Many2one(
'res.company', 'Company', required=True, index=True,
default=lambda self: self.env.company)
allowed_location_ids = fields.One2many(comodel_name='stock.location', compute='_compute_allowed_location_ids')
rule_ids = fields.Many2many('stock.rule', string='Rules used', compute='_compute_rules')
lead_days_date = fields.Date(compute='_compute_lead_days')
route_id = fields.Many2one(
'stock.location.route', string='Preferred Route', domain="[('product_selectable', '=', True)]")
qty_on_hand = fields.Float('On Hand', readonly=True, compute='_compute_qty')
qty_forecast = fields.Float('Forecast', readonly=True, compute='_compute_qty')
qty_to_order = fields.Float('To Order', compute='_compute_qty_to_order', store=True, readonly=False)
_sql_constraints = [
('qty_multiple_check', 'CHECK( qty_multiple >= 0 )', 'Qty Multiple must be greater than or equal to zero.'),
('product_location_check', 'unique (product_id, location_id, company_id)', 'The combination of product and location must be unique.'),
]
@api.depends('warehouse_id')
def _compute_allowed_location_ids(self):
loc_domain = [('usage', 'in', ('internal', 'view'))]
# We want to keep only the locations
# - strictly belonging to our warehouse
# - not belonging to any warehouses
for orderpoint in self:
other_warehouses = self.env['stock.warehouse'].search([('id', '!=', orderpoint.warehouse_id.id)])
for view_location_id in other_warehouses.mapped('view_location_id'):
loc_domain = expression.AND([loc_domain, ['!', ('id', 'child_of', view_location_id.id)]])
loc_domain = expression.AND([loc_domain, ['|', ('company_id', '=', False), ('company_id', '=', orderpoint.company_id.id)]])
orderpoint.allowed_location_ids = self.env['stock.location'].search(loc_domain)
@api.depends('rule_ids', 'product_id.seller_ids', 'product_id.seller_ids.delay')
def _compute_lead_days(self):
for orderpoint in self.with_context(bypass_delay_description=True):
if not orderpoint.product_id or not orderpoint.location_id:
orderpoint.lead_days_date = False
continue
values = orderpoint._get_lead_days_values()
lead_days, dummy = orderpoint.rule_ids._get_lead_days(orderpoint.product_id, **values)
lead_days_date = fields.Date.today() + relativedelta.relativedelta(days=lead_days)
orderpoint.lead_days_date = lead_days_date
@api.depends('route_id', 'product_id', 'location_id', 'company_id', 'warehouse_id', 'product_id.route_ids')
def _compute_rules(self):
for orderpoint in self:
if not orderpoint.product_id or not orderpoint.location_id:
orderpoint.rule_ids = False
continue
orderpoint.rule_ids = orderpoint.product_id._get_rules_from_location(orderpoint.location_id, route_ids=orderpoint.route_id)
@api.constrains('product_id')
def _check_product_uom(self):
''' Check if the UoM has the same category as the product standard UoM '''
if any(orderpoint.product_id.uom_id.category_id != orderpoint.product_uom.category_id for orderpoint in self):
raise ValidationError(_('You have to select a product unit of measure that is in the same category as the default unit of measure of the product'))
@api.onchange('location_id')
def _onchange_location_id(self):
warehouse = self.location_id.warehouse_id.id
if warehouse:
self.warehouse_id = warehouse
@api.onchange('warehouse_id')
def _onchange_warehouse_id(self):
""" Finds location id for changed warehouse. """
if self.warehouse_id:
self.location_id = self.warehouse_id.lot_stock_id.id
else:
self.location_id = False
@api.onchange('product_id')
def _onchange_product_id(self):
if self.product_id:
self.product_uom = self.product_id.uom_id.id
@api.onchange('company_id')
def _onchange_company_id(self):
if self.company_id:
self.warehouse_id = self.env['stock.warehouse'].search([
('company_id', '=', self.company_id.id)
], limit=1)
@api.onchange('route_id')
def _onchange_route_id(self):
if self.route_id:
self.qty_multiple = self._get_qty_multiple_to_order()
def write(self, vals):
if 'company_id' in vals:
for orderpoint in self:
if orderpoint.company_id.id != vals['company_id']:
raise UserError(_("Changing the company of this record is forbidden at this point, you should rather archive it and create a new one."))
return super().write(vals)
def action_product_forecast_report(self):
self.ensure_one()
action = self.product_id.action_product_forecast_report()
action['context'] = {
'active_id': self.product_id.id,
'active_model': 'product.product',
}
warehouse = self.warehouse_id
if warehouse:
action['context']['warehouse'] = warehouse.id
return action
@api.model
def action_open_orderpoints(self):
return self._get_orderpoint_action()
def action_stock_replenishment_info(self):
self.ensure_one()
action = self.env['ir.actions.actions']._for_xml_id('stock.action_stock_replenishment_info')
action['name'] = _('Replenishment Information for %s in %s', self.product_id.display_name, self.warehouse_id.display_name)
res = self.env['stock.replenishment.info'].create({
'orderpoint_id': self.id,
})
action['res_id'] = res.id
return action
def action_replenish(self):
now = datetime.now()
try:
self._procure_orderpoint_confirm(company_id=self.env.company)
except UserError as e:
if len(self) != 1:
raise e
raise RedirectWarning(e, {
'name': self.product_id.display_name,
'type': 'ir.actions.act_window',
'res_model': 'product.product',
'res_id': self.product_id.id,
'views': [(self.env.ref('product.product_normal_form_view').id, 'form')],
'context': {'form_view_initial_mode': 'edit'}
}, _('Edit Product'))
notification = False
if len(self) == 1:
notification = self.with_context(written_after=now)._get_replenishment_order_notification()
# Forced to call compute quantity because we don't have a link.
self._compute_qty()
self.filtered(lambda o: o.create_uid.id == SUPERUSER_ID and o.qty_to_order <= 0.0 and o.trigger == 'manual').unlink()
return notification
def action_replenish_auto(self):
self.trigger = 'auto'
return self.action_replenish()
@api.depends('product_id', 'location_id', 'product_id.stock_move_ids', 'product_id.stock_move_ids.state',
'product_id.stock_move_ids.date', 'product_id.stock_move_ids.product_uom_qty')
def _compute_qty(self):
orderpoints_contexts = defaultdict(lambda: self.env['stock.warehouse.orderpoint'])
for orderpoint in self:
if not orderpoint.product_id or not orderpoint.location_id:
orderpoint.qty_on_hand = False
orderpoint.qty_forecast = False
continue
orderpoint_context = orderpoint._get_product_context()
product_context = frozendict({**orderpoint_context})
orderpoints_contexts[product_context] |= orderpoint
for orderpoint_context, orderpoints_by_context in orderpoints_contexts.items():
products_qty = {
p['id']: p for p in orderpoints_by_context.product_id.with_context(orderpoint_context).read(['qty_available', 'virtual_available'])
}
products_qty_in_progress = orderpoints_by_context._quantity_in_progress()
for orderpoint in orderpoints_by_context:
orderpoint.qty_on_hand = products_qty[orderpoint.product_id.id]['qty_available']
orderpoint.qty_forecast = products_qty[orderpoint.product_id.id]['virtual_available'] + products_qty_in_progress[orderpoint.id]
@api.depends('qty_multiple', 'qty_forecast', 'product_min_qty', 'product_max_qty')
def _compute_qty_to_order(self):
for orderpoint in self:
if not orderpoint.product_id or not orderpoint.location_id:
orderpoint.qty_to_order = False
continue
qty_to_order = 0.0
rounding = orderpoint.product_uom.rounding
if float_compare(orderpoint.qty_forecast, orderpoint.product_min_qty, precision_rounding=rounding) < 0:
qty_to_order = max(orderpoint.product_min_qty, orderpoint.product_max_qty) - orderpoint.qty_forecast
remainder = orderpoint.qty_multiple > 0 and qty_to_order % orderpoint.qty_multiple or 0.0
if float_compare(remainder, 0.0, precision_rounding=rounding) > 0:
qty_to_order += orderpoint.qty_multiple - remainder
orderpoint.qty_to_order = qty_to_order
def _get_qty_multiple_to_order(self):
""" Calculates the minimum quantity that can be ordered according to the PO UoM or BoM
"""
self.ensure_one()
return 0
def _set_default_route_id(self):
""" Write the `route_id` field on `self`. This method is intendend to be called on the
orderpoints generated when openning the replenish report.
"""
self = self.filtered(lambda o: not o.route_id)
rules_groups = self.env['stock.rule'].read_group([
('route_id.product_selectable', '!=', False),
('location_id', 'in', self.location_id.ids),
('action', 'in', ['pull_push', 'pull'])
], ['location_id', 'route_id'], ['location_id', 'route_id'], lazy=False)
for g in rules_groups:
if not g.get('route_id'):
continue
orderpoints = self.filtered(lambda o: o.location_id.id == g['location_id'][0])
orderpoints.route_id = g['route_id']
def _get_lead_days_values(self):
self.ensure_one()
return dict()
def _get_product_context(self):
"""Used to call `virtual_available` when running an orderpoint."""
self.ensure_one()
return {
'location': self.location_id.id,
'to_date': datetime.combine(self.lead_days_date, time.max)
}
def _product_exclude_list(self):
# added to be overwitten in mrp
return []
def _get_orderpoint_action(self):
"""Create manual orderpoints for missing product in each warehouses. It also removes
orderpoints that have been replenish. In order to do it:
- It uses the report.stock.quantity to find missing quantity per product/warehouse
- It checks if orderpoint already exist to refill this location.
- It checks if it exists other sources (e.g RFQ) tha refill the warehouse.
- It creates the orderpoints for missing quantity that were not refill by an upper option.
return replenish report ir.actions.act_window
"""
action = self.env["ir.actions.actions"]._for_xml_id("stock.action_orderpoint_replenish")
action['context'] = self.env.context
# Search also with archived ones to avoid to trigger product_location_check SQL constraints later
# It means that when there will be a archived orderpoint on a location + product, the replenishment
# report won't take in account this location + product and it won't create any manual orderpoint
# In master: the active field should be remove
orderpoints = self.env['stock.warehouse.orderpoint'].with_context(active_test=False).search([])
# Remove previous automatically created orderpoint that has been refilled.
orderpoints_removed = orderpoints._unlink_processed_orderpoints()
orderpoints = orderpoints - orderpoints_removed
to_refill = defaultdict(float)
all_product_ids = []
all_warehouse_ids = []
# Take 3 months since it's the max for the forecast report
to_date = add(fields.date.today(), months=3)
qty_by_product_warehouse = self.env['report.stock.quantity'].read_group(
[('date', '=', to_date), ('state', '=', 'forecast'), ('product_qty', '<', 0.0), ('warehouse_id', '!=', False), ('product_id', 'not in', self._product_exclude_list())],
['product_id', 'product_qty', 'warehouse_id'],
['product_id', 'warehouse_id'], orderby="id", lazy=False)
for group in qty_by_product_warehouse:
all_product_ids.append(group['product_id'][0])
all_warehouse_ids.append(group['warehouse_id'][0])
to_refill[(group['product_id'][0], group['warehouse_id'][0])] = group['product_qty']
if not to_refill:
return action
# Recompute the forecasted quantity for missing product today but at this time
# with their real lead days.
key_to_remove = []
pwh_per_day = defaultdict(list)
for (product, warehouse) in to_refill.keys():
product = self.env['product.product'].browse(product).with_prefetch(all_product_ids)
warehouse = self.env['stock.warehouse'].browse(warehouse).with_prefetch(all_warehouse_ids)
rules = product._get_rules_from_location(warehouse.lot_stock_id)
lead_days = rules.with_context(bypass_delay_description=True)._get_lead_days(product)[0]
pwh_per_day[(lead_days, warehouse)].append(product.id)
# group product by lead_days and warehouse in order to read virtual_available
# in batch
for (days, warehouse), p_ids in pwh_per_day.items():
products = self.env['product.product'].browse(p_ids)
qties = products.with_context(
warehouse=warehouse.id,
to_date=fields.datetime.now() + relativedelta.relativedelta(days=days)
).read(['virtual_available'])
for (product, qty) in zip(products, qties):
if float_compare(qty['virtual_available'], 0, precision_rounding=product.uom_id.rounding) >= 0:
key_to_remove.append((qty['id'], warehouse.id))
else:
to_refill[(qty['id'], warehouse.id)] = qty['virtual_available']
for key in key_to_remove:
del to_refill[key]
if not to_refill:
return action
# Remove incoming quantity from other origin than moves (e.g RFQ)
product_ids, warehouse_ids = zip(*to_refill)
dummy, qty_by_product_wh = self.env['product.product'].browse(product_ids)._get_quantity_in_progress(warehouse_ids=warehouse_ids)
rounding = self.env['decimal.precision'].precision_get('Product Unit of Measure')
# Group orderpoint by product-warehouse
orderpoint_by_product_warehouse = self.env['stock.warehouse.orderpoint'].read_group(
[('id', 'in', orderpoints.ids)],
['product_id', 'warehouse_id', 'qty_to_order:sum'],
['product_id', 'warehouse_id'], lazy=False)
orderpoint_by_product_warehouse = {
(record.get('product_id')[0], record.get('warehouse_id')[0]): record.get('qty_to_order')
for record in orderpoint_by_product_warehouse
}
for (product, warehouse), product_qty in to_refill.items():
qty_in_progress = qty_by_product_wh.get((product, warehouse)) or 0.0
qty_in_progress += orderpoint_by_product_warehouse.get((product, warehouse), 0.0)
# Add qty to order for other orderpoint under this warehouse.
if not qty_in_progress:
continue
to_refill[(product, warehouse)] = product_qty + qty_in_progress
to_refill = {k: v for k, v in to_refill.items() if float_compare(
v, 0.0, precision_digits=rounding) < 0.0}
lot_stock_id_by_warehouse = self.env['stock.warehouse'].with_context(active_test=False).search_read([
('id', 'in', [g[1] for g in to_refill.keys()])
], ['lot_stock_id'])
lot_stock_id_by_warehouse = {w['id']: w['lot_stock_id'][0] for w in lot_stock_id_by_warehouse}
# With archived ones to avoid `product_location_check` SQL constraints
orderpoint_by_product_location = self.env['stock.warehouse.orderpoint'].with_context(active_test=False).read_group(
[('id', 'in', orderpoints.ids)],
['product_id', 'location_id', 'ids:array_agg(id)'],
['product_id', 'location_id'], lazy=False)
orderpoint_by_product_location = {
(record.get('product_id')[0], record.get('location_id')[0]): record.get('ids')[0]
for record in orderpoint_by_product_location
}
orderpoint_values_list = []
for (product, warehouse), product_qty in to_refill.items():
lot_stock_id = lot_stock_id_by_warehouse[warehouse]
orderpoint_id = orderpoint_by_product_location.get((product, lot_stock_id))
if orderpoint_id:
self.env['stock.warehouse.orderpoint'].browse(orderpoint_id).qty_forecast += product_qty
else:
orderpoint_values = self.env['stock.warehouse.orderpoint']._get_orderpoint_values(product, lot_stock_id)
orderpoint_values.update({
'name': _('Replenishment Report'),
'warehouse_id': warehouse,
'company_id': self.env['stock.warehouse'].browse(warehouse).company_id.id,
})
orderpoint_values_list.append(orderpoint_values)
orderpoints = self.env['stock.warehouse.orderpoint'].with_user(SUPERUSER_ID).create(orderpoint_values_list)
for orderpoint in orderpoints:
orderpoint_wh = orderpoint.location_id.warehouse_id
orderpoint.route_id = next((r for r in orderpoint.product_id.route_ids if not r.supplied_wh_id or r.supplied_wh_id == orderpoint_wh), orderpoint.route_id)
if not orderpoint.route_id:
orderpoint._set_default_route_id()
orderpoint.qty_multiple = orderpoint._get_qty_multiple_to_order()
return action
@api.model
def _get_orderpoint_values(self, product, location):
return {
'product_id': product,
'location_id': location,
'product_max_qty': 0.0,
'product_min_qty': 0.0,
'trigger': 'manual',
}
def _get_replenishment_order_notification(self):
self.ensure_one()
domain = [('orderpoint_id', 'in', self.ids)]
if self.env.context.get('written_after'):
domain = expression.AND([domain, [('write_date', '>', self.env.context.get('written_after'))]])
move = self.env['stock.move'].search(domain, limit=1)
if move.picking_id:
return {
'type': 'ir.actions.client',
'tag': 'display_notification',
'params': {
'title': _('The inter-warehouse transfers have been generated'),
'sticky': False,
}
}
return False
def _quantity_in_progress(self):
"""Return Quantities that are not yet in virtual stock but should be deduced from orderpoint rule
(example: purchases created from orderpoints)"""
return dict(self.mapped(lambda x: (x.id, 0.0)))
@api.autovacuum
def _unlink_processed_orderpoints(self):
domain = [
('create_uid', '=', SUPERUSER_ID),
('trigger', '=', 'manual'),
('qty_to_order', '<=', 0)
]
if self.ids:
expression.AND([domain, [('ids', 'in', self.ids)]])
orderpoints_to_remove = self.env['stock.warehouse.orderpoint'].with_context(active_test=False).search(domain)
# Remove previous automatically created orderpoint that has been refilled.
orderpoints_to_remove.unlink()
return orderpoints_to_remove
def _prepare_procurement_values(self, date=False, group=False):
""" Prepare specific key for moves or other components that will be created from a stock rule
comming from an orderpoint. This method could be override in order to add other custom key that could
be used in move/po creation.
"""
date_planned = date or fields.Date.today()
return {
'route_ids': self.route_id,
'date_planned': date_planned,
'date_deadline': date or False,
'warehouse_id': self.warehouse_id,
'orderpoint_id': self,
'group_id': group or self.group_id,
}
def _procure_orderpoint_confirm(self, use_new_cursor=False, company_id=None, raise_user_error=True):
""" Create procurements based on orderpoints.
:param bool use_new_cursor: if set, use a dedicated cursor and auto-commit after processing
1000 orderpoints.
This is appropriate for batch jobs only.
"""
self = self.with_company(company_id)
for orderpoints_batch_ids in split_every(1000, self.ids):
if use_new_cursor:
cr = registry(self._cr.dbname).cursor()
self = self.with_env(self.env(cr=cr))
try:
orderpoints_batch = self.env['stock.warehouse.orderpoint'].browse(orderpoints_batch_ids)
all_orderpoints_exceptions = []
while orderpoints_batch:
procurements = []
for orderpoint in orderpoints_batch:
origins = orderpoint.env.context.get('origins', {}).get(orderpoint.id, False)
if origins:
origin = '%s - %s' % (orderpoint.display_name, ','.join(origins))
else:
origin = orderpoint.name
if float_compare(orderpoint.qty_to_order, 0.0, precision_rounding=orderpoint.product_uom.rounding) == 1:
date = orderpoint._get_orderpoint_procurement_date()
global_visibility_days = self.env['ir.config_parameter'].sudo().get_param('stock.visibility_days')
if global_visibility_days:
date -= relativedelta.relativedelta(days=int(global_visibility_days))
values = orderpoint._prepare_procurement_values(date=date)
procurements.append(self.env['procurement.group'].Procurement(
orderpoint.product_id, orderpoint.qty_to_order, orderpoint.product_uom,
orderpoint.location_id, orderpoint.name, origin,
orderpoint.company_id, values))
try:
with self.env.cr.savepoint():
self.env['procurement.group'].with_context(from_orderpoint=True).run(procurements, raise_user_error=raise_user_error)
except ProcurementException as errors:
orderpoints_exceptions = []
for procurement, error_msg in errors.procurement_exceptions:
orderpoints_exceptions += [(procurement.values.get('orderpoint_id'), error_msg)]
all_orderpoints_exceptions += orderpoints_exceptions
failed_orderpoints = self.env['stock.warehouse.orderpoint'].concat(*[o[0] for o in orderpoints_exceptions])
if not failed_orderpoints:
_logger.error('Unable to process orderpoints')
break
orderpoints_batch -= failed_orderpoints
except OperationalError:
if use_new_cursor:
cr.rollback()
continue
else:
raise
else:
orderpoints_batch._post_process_scheduler()
break
# Log an activity on product template for failed orderpoints.
for orderpoint, error_msg in all_orderpoints_exceptions:
existing_activity = self.env['mail.activity'].search([
('res_id', '=', orderpoint.product_id.product_tmpl_id.id),
('res_model_id', '=', self.env.ref('product.model_product_template').id),
('note', '=', error_msg)])
if not existing_activity:
orderpoint.product_id.product_tmpl_id.sudo().activity_schedule(
'mail.mail_activity_data_warning',
note=error_msg,
user_id=orderpoint.product_id.responsible_id.id or SUPERUSER_ID,
)
finally:
if use_new_cursor:
try:
cr.commit()
finally:
cr.close()
_logger.info("A batch of %d orderpoints is processed and committed", len(orderpoints_batch_ids))
return {}
def _post_process_scheduler(self):
return True
def _get_orderpoint_procurement_date(self):
return datetime.combine(self.lead_days_date, time.min)
| 52.106346
| 30,378
|
11,465
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from re import findall as regex_findall
from re import split as regex_split
from odoo.tools.misc import attrgetter
from odoo import _, api, fields, models
from odoo.exceptions import UserError, ValidationError
class ProductionLot(models.Model):
_name = 'stock.production.lot'
_inherit = ['mail.thread', 'mail.activity.mixin']
_description = 'Lot/Serial'
_check_company_auto = True
_order = 'name, id'
name = fields.Char(
'Lot/Serial Number', default=lambda self: self.env['ir.sequence'].next_by_code('stock.lot.serial'),
required=True, help="Unique Lot/Serial Number", index=True)
ref = fields.Char('Internal Reference', help="Internal reference number in case it differs from the manufacturer's lot/serial number")
product_id = fields.Many2one(
'product.product', 'Product', index=True,
domain=lambda self: self._domain_product_id(), required=True, check_company=True)
product_uom_id = fields.Many2one(
'uom.uom', 'Unit of Measure',
related='product_id.uom_id', store=True)
quant_ids = fields.One2many('stock.quant', 'lot_id', 'Quants', readonly=True)
product_qty = fields.Float('Quantity', compute='_product_qty')
note = fields.Html(string='Description')
display_complete = fields.Boolean(compute='_compute_display_complete')
company_id = fields.Many2one('res.company', 'Company', required=True, store=True, index=True)
delivery_ids = fields.Many2many('stock.picking', compute='_compute_delivery_ids', string='Transfers')
delivery_count = fields.Integer('Delivery order count', compute='_compute_delivery_ids')
last_delivery_partner_id = fields.Many2one('res.partner', compute='_compute_delivery_ids')
@api.model
def generate_lot_names(self, first_lot, count):
"""Generate `lot_names` from a string."""
# We look if the first lot contains at least one digit.
caught_initial_number = regex_findall(r"\d+", first_lot)
if not caught_initial_number:
return self.generate_lot_names(first_lot + "0", count)
# We base the series on the last number found in the base lot.
initial_number = caught_initial_number[-1]
padding = len(initial_number)
# We split the lot name to get the prefix and suffix.
splitted = regex_split(initial_number, first_lot)
# initial_number could appear several times, e.g. BAV023B00001S00001
prefix = initial_number.join(splitted[:-1])
suffix = splitted[-1]
initial_number = int(initial_number)
lot_names = []
for i in range(0, count):
lot_names.append('%s%s%s' % (
prefix,
str(initial_number + i).zfill(padding),
suffix
))
return lot_names
@api.model
def _get_next_serial(self, company, product):
"""Return the next serial number to be attributed to the product."""
if product.tracking != "none":
last_serial = self.env['stock.production.lot'].search(
[('company_id', '=', company.id), ('product_id', '=', product.id)],
limit=1, order='id DESC')
if last_serial:
return self.env['stock.production.lot'].generate_lot_names(last_serial.name, 2)[1]
return False
@api.constrains('name', 'product_id', 'company_id')
def _check_unique_lot(self):
domain = [('product_id', 'in', self.product_id.ids),
('company_id', 'in', self.company_id.ids),
('name', 'in', self.mapped('name'))]
fields = ['company_id', 'product_id', 'name']
groupby = ['company_id', 'product_id', 'name']
records = self.read_group(domain, fields, groupby, lazy=False)
error_message_lines = []
for rec in records:
if rec['__count'] != 1:
product_name = self.env['product.product'].browse(rec['product_id'][0]).display_name
error_message_lines.append(_(" - Product: %s, Serial Number: %s", product_name, rec['name']))
if error_message_lines:
raise ValidationError(_('The combination of serial number and product must be unique across a company.\nFollowing combination contains duplicates:\n') + '\n'.join(error_message_lines))
def _domain_product_id(self):
domain = [
"('tracking', '!=', 'none')",
"('type', '=', 'product')",
"'|'",
"('company_id', '=', False)",
"('company_id', '=', company_id)"
]
if self.env.context.get('default_product_tmpl_id'):
domain.insert(0,
("('product_tmpl_id', '=', %s)" % self.env.context['default_product_tmpl_id'])
)
return '[' + ', '.join(domain) + ']'
def _check_create(self):
active_picking_id = self.env.context.get('active_picking_id', False)
if active_picking_id:
picking_id = self.env['stock.picking'].browse(active_picking_id)
if picking_id and not picking_id.picking_type_id.use_create_lots:
raise UserError(_('You are not allowed to create a lot or serial number with this operation type. To change this, go on the operation type and tick the box "Create New Lots/Serial Numbers".'))
@api.depends('name')
def _compute_display_complete(self):
""" Defines if we want to display all fields in the stock.production.lot form view.
It will if the record exists (`id` set) or if we precised it into the context.
This compute depends on field `name` because as it has always a default value, it'll be
always triggered.
"""
for prod_lot in self:
prod_lot.display_complete = prod_lot.id or self._context.get('display_complete')
def _compute_delivery_ids(self):
delivery_ids_by_lot = self._find_delivery_ids_by_lot()
for lot in self:
lot.delivery_ids = delivery_ids_by_lot[lot.id]
lot.delivery_count = len(lot.delivery_ids)
lot.last_delivery_partner_id = False
# If lot is serial, keep track of the latest delivery's partner
if lot.product_id.tracking == 'serial' and lot.delivery_count > 0:
lot.last_delivery_partner_id = lot.delivery_ids.sorted(key=attrgetter('date_done'), reverse=True)[0].partner_id
@api.model_create_multi
def create(self, vals_list):
self._check_create()
return super(ProductionLot, self.with_context(mail_create_nosubscribe=True)).create(vals_list)
def write(self, vals):
if 'company_id' in vals:
for lot in self:
if lot.company_id.id != vals['company_id']:
raise UserError(_("Changing the company of this record is forbidden at this point, you should rather archive it and create a new one."))
if 'product_id' in vals and any(vals['product_id'] != lot.product_id.id for lot in self):
move_lines = self.env['stock.move.line'].search([('lot_id', 'in', self.ids), ('product_id', '!=', vals['product_id'])])
if move_lines:
raise UserError(_(
'You are not allowed to change the product linked to a serial or lot number '
'if some stock moves have already been created with that number. '
'This would lead to inconsistencies in your stock.'
))
return super(ProductionLot, self).write(vals)
def copy(self, default=None):
if default is None:
default = {}
if 'name' not in default:
default['name'] = _("(copy of) %s", self.name)
return super().copy(default)
@api.depends('quant_ids', 'quant_ids.quantity')
def _product_qty(self):
for lot in self:
# We only care for the quants in internal or transit locations.
quants = lot.quant_ids.filtered(lambda q: q.location_id.usage == 'internal' or (q.location_id.usage == 'transit' and q.location_id.company_id))
lot.product_qty = sum(quants.mapped('quantity'))
def action_lot_open_quants(self):
self = self.with_context(search_default_lot_id=self.id, create=False)
if self.user_has_groups('stock.group_stock_manager'):
self = self.with_context(inventory_mode=True)
return self.env['stock.quant']._get_quants_action()
def action_lot_open_transfers(self):
self.ensure_one()
action = {
'res_model': 'stock.picking',
'type': 'ir.actions.act_window'
}
if len(self.delivery_ids) == 1:
action.update({
'view_mode': 'form',
'res_id': self.delivery_ids[0].id
})
else:
action.update({
'name': _("Delivery orders of %s", self.display_name),
'domain': [('id', 'in', self.delivery_ids.ids)],
'view_mode': 'tree,form'
})
return action
def _find_delivery_ids_by_lot(self, lot_path=None, delivery_by_lot=None):
if lot_path is None:
lot_path = set()
domain = [
('lot_id', 'in', self.ids),
('state', '=', 'done'),
'|', ('picking_code', '=', 'outgoing'), ('produce_line_ids', '!=', False)
]
move_lines = self.env['stock.move.line'].search(domain)
moves_by_lot = {
lot_id: {'producing_lines': set(), 'barren_lines': set()}
for lot_id in move_lines.lot_id.ids
}
for line in move_lines:
if line.produce_line_ids:
moves_by_lot[line.lot_id.id]['producing_lines'].add(line.id)
else:
moves_by_lot[line.lot_id.id]['barren_lines'].add(line.id)
if delivery_by_lot is None:
delivery_by_lot = dict()
for lot in self:
delivery_ids = set()
if moves_by_lot.get(lot.id):
producing_move_lines = self.env['stock.move.line'].browse(moves_by_lot[lot.id]['producing_lines'])
barren_move_lines = self.env['stock.move.line'].browse(moves_by_lot[lot.id]['barren_lines'])
if producing_move_lines:
lot_path.add(lot.id)
next_lots = producing_move_lines.produce_line_ids.lot_id.filtered(lambda l: l.id not in lot_path)
next_lots_ids = set(next_lots.ids)
# If some producing lots are in lot_path, it means that they have been previously processed.
# Their results are therefore already in delivery_by_lot and we add them to delivery_ids directly.
delivery_ids.update(*(delivery_by_lot.get(lot_id, []) for lot_id in (producing_move_lines.produce_line_ids.lot_id - next_lots).ids))
for lot_id, delivery_ids_set in next_lots._find_delivery_ids_by_lot(lot_path=lot_path, delivery_by_lot=delivery_by_lot).items():
if lot_id in next_lots_ids:
delivery_ids.update(delivery_ids_set)
delivery_ids.update(barren_move_lines.picking_id.ids)
# delivery_ids = self._find_delivery_ids(moves_by_lot[lot.id])
delivery_by_lot[lot.id] = list(delivery_ids)
return delivery_by_lot
| 48.995726
| 11,465
|
82,967
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import json
import time
from ast import literal_eval
from datetime import date, timedelta
from itertools import groupby
from operator import attrgetter, itemgetter
from collections import defaultdict
from odoo import SUPERUSER_ID, _, api, fields, models
from odoo.addons.stock.models.stock_move import PROCUREMENT_PRIORITIES
from odoo.exceptions import UserError
from odoo.osv import expression
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT, format_datetime
from odoo.tools.float_utils import float_compare, float_is_zero, float_round
from odoo.tools.misc import format_date
class PickingType(models.Model):
_name = "stock.picking.type"
_description = "Picking Type"
_order = 'sequence, id'
_check_company_auto = True
def _default_show_operations(self):
return self.user_has_groups('stock.group_production_lot,'
'stock.group_stock_multi_locations,'
'stock.group_tracking_lot')
name = fields.Char('Operation Type', required=True, translate=True)
color = fields.Integer('Color')
sequence = fields.Integer('Sequence', help="Used to order the 'All Operations' kanban view")
sequence_id = fields.Many2one(
'ir.sequence', 'Reference Sequence',
check_company=True, copy=False)
sequence_code = fields.Char('Code', required=True)
default_location_src_id = fields.Many2one(
'stock.location', 'Default Source Location',
check_company=True,
help="This is the default source location when you create a picking manually with this operation type. It is possible however to change it or that the routes put another location. If it is empty, it will check for the supplier location on the partner. ")
default_location_dest_id = fields.Many2one(
'stock.location', 'Default Destination Location',
check_company=True,
help="This is the default destination location when you create a picking manually with this operation type. It is possible however to change it or that the routes put another location. If it is empty, it will check for the customer location on the partner. ")
code = fields.Selection([('incoming', 'Receipt'), ('outgoing', 'Delivery'), ('internal', 'Internal Transfer')], 'Type of Operation', required=True)
return_picking_type_id = fields.Many2one(
'stock.picking.type', 'Operation Type for Returns',
check_company=True)
show_entire_packs = fields.Boolean('Move Entire Packages', help="If ticked, you will be able to select entire packages to move")
warehouse_id = fields.Many2one(
'stock.warehouse', 'Warehouse', ondelete='cascade',
check_company=True)
active = fields.Boolean('Active', default=True)
use_create_lots = fields.Boolean(
'Create New Lots/Serial Numbers', default=True,
help="If this is checked only, it will suppose you want to create new Lots/Serial Numbers, so you can provide them in a text field. ")
use_existing_lots = fields.Boolean(
'Use Existing Lots/Serial Numbers', default=True,
help="If this is checked, you will be able to choose the Lots/Serial Numbers. You can also decide to not put lots in this operation type. This means it will create stock with no lot or not put a restriction on the lot taken. ")
print_label = fields.Boolean(
'Print Label',
help="If this checkbox is ticked, label will be print in this operation.")
show_operations = fields.Boolean(
'Show Detailed Operations', default=_default_show_operations,
help="If this checkbox is ticked, the pickings lines will represent detailed stock operations. If not, the picking lines will represent an aggregate of detailed stock operations.")
show_reserved = fields.Boolean(
'Pre-fill Detailed Operations', default=True,
help="If this checkbox is ticked, Odoo will automatically pre-fill the detailed "
"operations with the corresponding products, locations and lot/serial numbers.")
reservation_method = fields.Selection(
[('at_confirm', 'At Confirmation'), ('manual', 'Manually'), ('by_date', 'Before scheduled date')],
'Reservation Method', required=True, default='at_confirm',
help="How products in transfers of this operation type should be reserved.")
reservation_days_before = fields.Integer('Days', help="Maximum number of days before scheduled date that products should be reserved.")
reservation_days_before_priority = fields.Integer('Days when starred', help="Maximum number of days before scheduled date that priority picking products should be reserved.")
count_picking_draft = fields.Integer(compute='_compute_picking_count')
count_picking_ready = fields.Integer(compute='_compute_picking_count')
count_picking = fields.Integer(compute='_compute_picking_count')
count_picking_waiting = fields.Integer(compute='_compute_picking_count')
count_picking_late = fields.Integer(compute='_compute_picking_count')
count_picking_backorders = fields.Integer(compute='_compute_picking_count')
barcode = fields.Char('Barcode', copy=False)
company_id = fields.Many2one(
'res.company', 'Company', required=True,
default=lambda s: s.env.company.id, index=True)
@api.model
def create(self, vals):
if not vals.get('sequence_id') and vals.get('sequence_code'):
if vals.get('warehouse_id'):
wh = self.env['stock.warehouse'].browse(vals['warehouse_id'])
vals['sequence_id'] = self.env['ir.sequence'].sudo().create({
'name': wh.name + ' ' + _('Sequence') + ' ' + vals['sequence_code'],
'prefix': wh.code + '/' + vals['sequence_code'] + '/', 'padding': 5,
'company_id': wh.company_id.id,
}).id
else:
vals['sequence_id'] = self.env['ir.sequence'].sudo().create({
'name': _('Sequence') + ' ' + vals['sequence_code'],
'prefix': vals['sequence_code'], 'padding': 5,
'company_id': vals.get('company_id') or self.env.company.id,
}).id
picking_type = super(PickingType, self).create(vals)
return picking_type
def write(self, vals):
if 'company_id' in vals:
for picking_type in self:
if picking_type.company_id.id != vals['company_id']:
raise UserError(_("Changing the company of this record is forbidden at this point, you should rather archive it and create a new one."))
if 'sequence_code' in vals:
for picking_type in self:
if picking_type.warehouse_id:
picking_type.sequence_id.sudo().write({
'name': picking_type.warehouse_id.name + ' ' + _('Sequence') + ' ' + vals['sequence_code'],
'prefix': picking_type.warehouse_id.code + '/' + vals['sequence_code'] + '/', 'padding': 5,
'company_id': picking_type.warehouse_id.company_id.id,
})
else:
picking_type.sequence_id.sudo().write({
'name': _('Sequence') + ' ' + vals['sequence_code'],
'prefix': vals['sequence_code'], 'padding': 5,
'company_id': picking_type.env.company.id,
})
return super(PickingType, self).write(vals)
def _compute_picking_count(self):
domains = {
'count_picking_draft': [('state', '=', 'draft')],
'count_picking_waiting': [('state', 'in', ('confirmed', 'waiting'))],
'count_picking_ready': [('state', '=', 'assigned')],
'count_picking': [('state', 'in', ('assigned', 'waiting', 'confirmed'))],
'count_picking_late': [('scheduled_date', '<', time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)), ('state', 'in', ('assigned', 'waiting', 'confirmed'))],
'count_picking_backorders': [('backorder_id', '!=', False), ('state', 'in', ('confirmed', 'assigned', 'waiting'))],
}
for field in domains:
data = self.env['stock.picking'].read_group(domains[field] +
[('state', 'not in', ('done', 'cancel')), ('picking_type_id', 'in', self.ids)],
['picking_type_id'], ['picking_type_id'])
count = {
x['picking_type_id'][0]: x['picking_type_id_count']
for x in data if x['picking_type_id']
}
for record in self:
record[field] = count.get(record.id, 0)
def name_get(self):
""" Display 'Warehouse_name: PickingType_name' """
res = []
for picking_type in self:
if picking_type.warehouse_id:
name = picking_type.warehouse_id.name + ': ' + picking_type.name
else:
name = picking_type.name
res.append((picking_type.id, name))
return res
@api.model
def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None):
args = args or []
domain = []
if name:
# Try to reverse the `name_get` structure
parts = name.split(': ')
if len(parts) == 2:
domain = [('warehouse_id.name', operator, parts[0]), ('name', operator, parts[1])]
else:
domain = ['|', ('name', operator, name), ('warehouse_id.name', operator, name)]
return self._search(expression.AND([domain, args]), limit=limit, access_rights_uid=name_get_uid)
@api.onchange('code')
def _onchange_picking_code(self):
warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.company_id.id)], limit=1)
stock_location = warehouse.lot_stock_id
self.show_operations = self.code != 'incoming' and self.user_has_groups(
'stock.group_production_lot,'
'stock.group_stock_multi_locations,'
'stock.group_tracking_lot'
)
if self.code == 'incoming':
self.default_location_src_id = self.env.ref('stock.stock_location_suppliers').id
self.default_location_dest_id = stock_location.id
self.print_label = False
elif self.code == 'outgoing':
self.default_location_src_id = stock_location.id
self.default_location_dest_id = self.env.ref('stock.stock_location_customers').id
self.print_label = True
elif self.code == 'internal':
self.print_label = False
if not self.user_has_groups('stock.group_stock_multi_locations'):
return {
'warning': {
'message': _('You need to activate storage locations to be able to do internal operation types.')
}
}
@api.onchange('company_id')
def _onchange_company_id(self):
if self.company_id:
warehouse = self.env['stock.warehouse'].search([('company_id', '=', self.company_id.id)], limit=1)
self.warehouse_id = warehouse
else:
self.warehouse_id = False
@api.onchange('show_operations')
def _onchange_show_operations(self):
if self.show_operations and self.code != 'incoming':
self.show_reserved = True
def _get_action(self, action_xmlid):
action = self.env["ir.actions.actions"]._for_xml_id(action_xmlid)
if self:
action['display_name'] = self.display_name
default_immediate_tranfer = True
if self.env['ir.config_parameter'].sudo().get_param('stock.no_default_immediate_tranfer'):
default_immediate_tranfer = False
context = {
'search_default_picking_type_id': [self.id],
'default_picking_type_id': self.id,
'default_immediate_transfer': default_immediate_tranfer,
'default_company_id': self.company_id.id,
}
action_context = literal_eval(action['context'])
context = {**action_context, **context}
action['context'] = context
return action
def get_action_picking_tree_late(self):
return self._get_action('stock.action_picking_tree_late')
def get_action_picking_tree_backorder(self):
return self._get_action('stock.action_picking_tree_backorder')
def get_action_picking_tree_waiting(self):
return self._get_action('stock.action_picking_tree_waiting')
def get_action_picking_tree_ready(self):
return self._get_action('stock.action_picking_tree_ready')
def get_action_picking_type_operations(self):
return self._get_action('stock.action_get_picking_type_operations')
def get_stock_picking_action_picking_type(self):
return self._get_action('stock.stock_picking_action_picking_type')
class Picking(models.Model):
_name = "stock.picking"
_inherit = ['mail.thread', 'mail.activity.mixin']
_description = "Transfer"
_order = "priority desc, scheduled_date asc, id desc"
name = fields.Char(
'Reference', default='/',
copy=False, index=True, readonly=True)
origin = fields.Char(
'Source Document', index=True,
states={'done': [('readonly', True)], 'cancel': [('readonly', True)]},
help="Reference of the document")
note = fields.Html('Notes')
backorder_id = fields.Many2one(
'stock.picking', 'Back Order of',
copy=False, index=True, readonly=True,
check_company=True,
help="If this shipment was split, then this field links to the shipment which contains the already processed part.")
backorder_ids = fields.One2many('stock.picking', 'backorder_id', 'Back Orders')
move_type = fields.Selection([
('direct', 'As soon as possible'), ('one', 'When all products are ready')], 'Shipping Policy',
default='direct', required=True,
states={'done': [('readonly', True)], 'cancel': [('readonly', True)]},
help="It specifies goods to be deliver partially or all at once")
state = fields.Selection([
('draft', 'Draft'),
('waiting', 'Waiting Another Operation'),
('confirmed', 'Waiting'),
('assigned', 'Ready'),
('done', 'Done'),
('cancel', 'Cancelled'),
], string='Status', compute='_compute_state',
copy=False, index=True, readonly=True, store=True, tracking=True,
help=" * Draft: The transfer is not confirmed yet. Reservation doesn't apply.\n"
" * Waiting another operation: This transfer is waiting for another operation before being ready.\n"
" * Waiting: The transfer is waiting for the availability of some products.\n(a) The shipping policy is \"As soon as possible\": no product could be reserved.\n(b) The shipping policy is \"When all products are ready\": not all the products could be reserved.\n"
" * Ready: The transfer is ready to be processed.\n(a) The shipping policy is \"As soon as possible\": at least one product has been reserved.\n(b) The shipping policy is \"When all products are ready\": all product have been reserved.\n"
" * Done: The transfer has been processed.\n"
" * Cancelled: The transfer has been cancelled.")
group_id = fields.Many2one(
'procurement.group', 'Procurement Group',
readonly=True, related='move_lines.group_id', store=True)
priority = fields.Selection(
PROCUREMENT_PRIORITIES, string='Priority', default='0',
help="Products will be reserved first for the transfers with the highest priorities.")
scheduled_date = fields.Datetime(
'Scheduled Date', compute='_compute_scheduled_date', inverse='_set_scheduled_date', store=True,
index=True, default=fields.Datetime.now, tracking=True,
states={'done': [('readonly', True)], 'cancel': [('readonly', True)]},
help="Scheduled time for the first part of the shipment to be processed. Setting manually a value here would set it as expected date for all the stock moves.")
date_deadline = fields.Datetime(
"Deadline", compute='_compute_date_deadline', store=True,
help="Date Promise to the customer on the top level document (SO/PO)")
has_deadline_issue = fields.Boolean(
"Is late", compute='_compute_has_deadline_issue', store=True, default=False,
help="Is late or will be late depending on the deadline and scheduled date")
date = fields.Datetime(
'Creation Date',
default=fields.Datetime.now, tracking=True,
states={'done': [('readonly', True)], 'cancel': [('readonly', True)]},
help="Creation Date, usually the time of the order")
date_done = fields.Datetime('Date of Transfer', copy=False, readonly=True, help="Date at which the transfer has been processed or cancelled.")
delay_alert_date = fields.Datetime('Delay Alert Date', compute='_compute_delay_alert_date', search='_search_delay_alert_date')
json_popover = fields.Char('JSON data for the popover widget', compute='_compute_json_popover')
location_id = fields.Many2one(
'stock.location', "Source Location",
default=lambda self: self.env['stock.picking.type'].browse(self._context.get('default_picking_type_id')).default_location_src_id,
check_company=True, readonly=True, required=True,
states={'draft': [('readonly', False)]})
location_dest_id = fields.Many2one(
'stock.location', "Destination Location",
default=lambda self: self.env['stock.picking.type'].browse(self._context.get('default_picking_type_id')).default_location_dest_id,
check_company=True, readonly=True, required=True,
states={'draft': [('readonly', False)]})
move_lines = fields.One2many('stock.move', 'picking_id', string="Stock Moves", copy=True)
move_ids_without_package = fields.One2many('stock.move', 'picking_id', string="Stock moves not in package", compute='_compute_move_without_package', inverse='_set_move_without_package')
has_scrap_move = fields.Boolean(
'Has Scrap Moves', compute='_has_scrap_move')
picking_type_id = fields.Many2one(
'stock.picking.type', 'Operation Type',
required=True, readonly=True,
states={'draft': [('readonly', False)]})
picking_type_code = fields.Selection(
related='picking_type_id.code',
readonly=True)
picking_type_entire_packs = fields.Boolean(related='picking_type_id.show_entire_packs')
use_create_lots = fields.Boolean(related='picking_type_id.use_create_lots')
use_existing_lots = fields.Boolean(related='picking_type_id.use_existing_lots')
hide_picking_type = fields.Boolean(compute='_compute_hide_pickign_type')
partner_id = fields.Many2one(
'res.partner', 'Contact',
check_company=True,
states={'done': [('readonly', True)], 'cancel': [('readonly', True)]})
company_id = fields.Many2one(
'res.company', string='Company', related='picking_type_id.company_id',
readonly=True, store=True, index=True)
user_id = fields.Many2one(
'res.users', 'Responsible', tracking=True,
domain=lambda self: [('groups_id', 'in', self.env.ref('stock.group_stock_user').id)],
states={'done': [('readonly', True)], 'cancel': [('readonly', True)]},
default=lambda self: self.env.user)
move_line_ids = fields.One2many('stock.move.line', 'picking_id', 'Operations')
move_line_ids_without_package = fields.One2many('stock.move.line', 'picking_id', 'Operations without package', domain=['|',('package_level_id', '=', False), ('picking_type_entire_packs', '=', False)])
move_line_nosuggest_ids = fields.One2many(
'stock.move.line', 'picking_id',
domain=['|', ('product_qty', '=', 0.0), '&', ('product_qty', '!=', 0.0), ('qty_done', '!=', 0.0)])
move_line_exist = fields.Boolean(
'Has Pack Operations', compute='_compute_move_line_exist',
help='Check the existence of pack operation on the picking')
has_packages = fields.Boolean(
'Has Packages', compute='_compute_has_packages',
help='Check the existence of destination packages on move lines')
show_check_availability = fields.Boolean(
compute='_compute_show_check_availability',
help='Technical field used to compute whether the button "Check Availability" should be displayed.')
show_mark_as_todo = fields.Boolean(
compute='_compute_show_mark_as_todo',
help='Technical field used to compute whether the button "Mark as Todo" should be displayed.')
show_validate = fields.Boolean(
compute='_compute_show_validate',
help='Technical field used to decide whether the button "Validate" should be displayed.')
show_allocation = fields.Boolean(
compute='_compute_show_allocation',
help='Technical Field used to decide whether the button "Allocation" should be displayed.')
owner_id = fields.Many2one(
'res.partner', 'Assign Owner',
states={'done': [('readonly', True)], 'cancel': [('readonly', True)]},
check_company=True,
help="When validating the transfer, the products will be assigned to this owner.")
printed = fields.Boolean('Printed', copy=False)
signature = fields.Image('Signature', help='Signature', copy=False, attachment=True)
is_signed = fields.Boolean('Is Signed', compute="_compute_is_signed")
is_locked = fields.Boolean(default=True, help='When the picking is not done this allows changing the '
'initial demand. When the picking is done this allows '
'changing the done quantities.')
# Used to search on pickings
product_id = fields.Many2one('product.product', 'Product', related='move_lines.product_id', readonly=True)
show_operations = fields.Boolean(compute='_compute_show_operations')
show_reserved = fields.Boolean(related='picking_type_id.show_reserved')
show_lots_text = fields.Boolean(compute='_compute_show_lots_text')
has_tracking = fields.Boolean(compute='_compute_has_tracking')
immediate_transfer = fields.Boolean(default=False)
package_level_ids = fields.One2many('stock.package_level', 'picking_id')
package_level_ids_details = fields.One2many('stock.package_level', 'picking_id')
products_availability = fields.Char(
string="Product Availability", compute='_compute_products_availability',
help="Latest product availability status of the picking")
products_availability_state = fields.Selection([
('available', 'Available'),
('expected', 'Expected'),
('late', 'Late')], compute='_compute_products_availability')
_sql_constraints = [
('name_uniq', 'unique(name, company_id)', 'Reference must be unique per company!'),
]
def _compute_has_tracking(self):
for picking in self:
picking.has_tracking = any(m.has_tracking != 'none' for m in picking.move_lines)
@api.depends('date_deadline', 'scheduled_date')
def _compute_has_deadline_issue(self):
for picking in self:
picking.has_deadline_issue = picking.date_deadline and picking.date_deadline < picking.scheduled_date or False
def _compute_hide_pickign_type(self):
self.hide_picking_type = self.env.context.get('default_picking_type_id', False)
@api.depends('move_lines.delay_alert_date')
def _compute_delay_alert_date(self):
delay_alert_date_data = self.env['stock.move'].read_group([('id', 'in', self.move_lines.ids), ('delay_alert_date', '!=', False)], ['delay_alert_date:max'], 'picking_id')
delay_alert_date_data = {data['picking_id'][0]: data['delay_alert_date'] for data in delay_alert_date_data}
for picking in self:
picking.delay_alert_date = delay_alert_date_data.get(picking.id, False)
@api.depends('signature')
def _compute_is_signed(self):
for picking in self:
picking.is_signed = picking.signature
@api.depends('state', 'picking_type_code', 'scheduled_date', 'move_lines', 'move_lines.forecast_availability', 'move_lines.forecast_expected_date')
def _compute_products_availability(self):
pickings = self.filtered(lambda picking: picking.state in ('waiting', 'confirmed', 'assigned') and picking.picking_type_code == 'outgoing')
pickings.products_availability_state = 'available'
pickings.products_availability = _('Available')
other_pickings = self - pickings
other_pickings.products_availability = False
other_pickings.products_availability_state = False
all_moves = pickings.move_lines
# Force to prefetch more than 1000 by 1000
all_moves._fields['forecast_availability'].compute_value(all_moves)
for picking in pickings:
# In case of draft the behavior of forecast_availability is different : if forecast_availability < 0 then there is a issue else not.
if any(float_compare(move.forecast_availability, 0 if move.state == 'draft' else move.product_qty, precision_rounding=move.product_id.uom_id.rounding) == -1 for move in picking.move_lines):
picking.products_availability = _('Not Available')
picking.products_availability_state = 'late'
else:
forecast_date = max(picking.move_lines.filtered('forecast_expected_date').mapped('forecast_expected_date'), default=False)
if forecast_date:
picking.products_availability = _('Exp %s', format_date(self.env, forecast_date))
picking.products_availability_state = 'late' if picking.scheduled_date and picking.scheduled_date < forecast_date else 'expected'
@api.depends('picking_type_id.show_operations')
def _compute_show_operations(self):
for picking in self:
if self.env.context.get('force_detailed_view'):
picking.show_operations = True
continue
if picking.picking_type_id.show_operations:
if (picking.state == 'draft' and picking.immediate_transfer) or picking.state != 'draft':
picking.show_operations = True
else:
picking.show_operations = False
else:
picking.show_operations = False
@api.depends('move_line_ids', 'picking_type_id.use_create_lots', 'picking_type_id.use_existing_lots', 'state')
def _compute_show_lots_text(self):
group_production_lot_enabled = self.user_has_groups('stock.group_production_lot')
for picking in self:
if not picking.move_line_ids and not picking.picking_type_id.use_create_lots:
picking.show_lots_text = False
elif group_production_lot_enabled and picking.picking_type_id.use_create_lots \
and not picking.picking_type_id.use_existing_lots and picking.state != 'done':
picking.show_lots_text = True
else:
picking.show_lots_text = False
def _compute_json_popover(self):
picking_no_alert = self.filtered(lambda p: p.state in ('done', 'cancel') or not p.delay_alert_date)
picking_no_alert.json_popover = False
for picking in (self - picking_no_alert):
picking.json_popover = json.dumps({
'popoverTemplate': 'stock.PopoverStockRescheduling',
'delay_alert_date': format_datetime(self.env, picking.delay_alert_date, dt_format=False),
'late_elements': [{
'id': late_move.id,
'name': late_move.display_name,
'model': late_move._name,
} for late_move in picking.move_lines.filtered(lambda m: m.delay_alert_date).move_orig_ids._delay_alert_get_documents()
]
})
@api.depends('move_type', 'immediate_transfer', 'move_lines.state', 'move_lines.picking_id')
def _compute_state(self):
''' State of a picking depends on the state of its related stock.move
- Draft: only used for "planned pickings"
- Waiting: if the picking is not ready to be sent so if
- (a) no quantity could be reserved at all or if
- (b) some quantities could be reserved and the shipping policy is "deliver all at once"
- Waiting another move: if the picking is waiting for another move
- Ready: if the picking is ready to be sent so if:
- (a) all quantities are reserved or if
- (b) some quantities could be reserved and the shipping policy is "as soon as possible"
- Done: if the picking is done.
- Cancelled: if the picking is cancelled
'''
picking_moves_state_map = defaultdict(dict)
picking_move_lines = defaultdict(set)
for move in self.env['stock.move'].search([('picking_id', 'in', self.ids)]):
picking_id = move.picking_id
move_state = move.state
picking_moves_state_map[picking_id.id].update({
'any_draft': picking_moves_state_map[picking_id.id].get('any_draft', False) or move_state == 'draft',
'all_cancel': picking_moves_state_map[picking_id.id].get('all_cancel', True) and move_state == 'cancel',
'all_cancel_done': picking_moves_state_map[picking_id.id].get('all_cancel_done', True) and move_state in ('cancel', 'done'),
'all_done_are_scrapped': picking_moves_state_map[picking_id.id].get('all_done_are_scrapped', True) and (move.scrapped if move_state == 'done' else True),
'any_cancel_and_not_scrapped': picking_moves_state_map[picking_id.id].get('any_cancel_and_not_scrapped', False) or (move_state == 'cancel' and not move.scrapped),
})
picking_move_lines[picking_id.id].add(move.id)
for picking in self:
picking_id = (picking.ids and picking.ids[0]) or picking.id
if not picking_moves_state_map[picking_id]:
picking.state = 'draft'
elif picking_moves_state_map[picking_id]['any_draft']:
picking.state = 'draft'
elif picking_moves_state_map[picking_id]['all_cancel']:
picking.state = 'cancel'
elif picking_moves_state_map[picking_id]['all_cancel_done']:
if picking_moves_state_map[picking_id]['all_done_are_scrapped'] and picking_moves_state_map[picking_id]['any_cancel_and_not_scrapped']:
picking.state = 'cancel'
else:
picking.state = 'done'
else:
relevant_move_state = self.env['stock.move'].browse(picking_move_lines[picking_id])._get_relevant_state_among_moves()
if picking.immediate_transfer and relevant_move_state not in ('draft', 'cancel', 'done'):
picking.state = 'assigned'
elif relevant_move_state == 'partially_available':
picking.state = 'assigned'
else:
picking.state = relevant_move_state
@api.depends('move_lines.state', 'move_lines.date', 'move_type')
def _compute_scheduled_date(self):
for picking in self:
moves_dates = picking.move_lines.filtered(lambda move: move.state not in ('done', 'cancel')).mapped('date')
if picking.move_type == 'direct':
picking.scheduled_date = min(moves_dates, default=picking.scheduled_date or fields.Datetime.now())
else:
picking.scheduled_date = max(moves_dates, default=picking.scheduled_date or fields.Datetime.now())
@api.depends('move_lines.date_deadline', 'move_type')
def _compute_date_deadline(self):
for picking in self:
if picking.move_type == 'direct':
picking.date_deadline = min(picking.move_lines.filtered('date_deadline').mapped('date_deadline'), default=False)
else:
picking.date_deadline = max(picking.move_lines.filtered('date_deadline').mapped('date_deadline'), default=False)
def _set_scheduled_date(self):
for picking in self:
if picking.state in ('done', 'cancel'):
raise UserError(_("You cannot change the Scheduled Date on a done or cancelled transfer."))
picking.move_lines.write({'date': picking.scheduled_date})
def _has_scrap_move(self):
for picking in self:
# TDE FIXME: better implementation
picking.has_scrap_move = bool(self.env['stock.move'].search_count([('picking_id', '=', picking.id), ('scrapped', '=', True)]))
def _compute_move_line_exist(self):
for picking in self:
picking.move_line_exist = bool(picking.move_line_ids)
def _compute_has_packages(self):
domain = [('picking_id', 'in', self.ids), ('result_package_id', '!=', False)]
cnt_by_picking = self.env['stock.move.line'].read_group(domain, ['picking_id'], ['picking_id'])
cnt_by_picking = {d['picking_id'][0]: d['picking_id_count'] for d in cnt_by_picking}
for picking in self:
picking.has_packages = bool(cnt_by_picking.get(picking.id, False))
@api.depends('immediate_transfer', 'state')
def _compute_show_check_availability(self):
""" According to `picking.show_check_availability`, the "check availability" button will be
displayed in the form view of a picking.
"""
for picking in self:
if picking.immediate_transfer or picking.state not in ('confirmed', 'waiting', 'assigned'):
picking.show_check_availability = False
continue
picking.show_check_availability = any(
move.state in ('waiting', 'confirmed', 'partially_available') and
float_compare(move.product_uom_qty, 0, precision_rounding=move.product_uom.rounding)
for move in picking.move_lines
)
@api.depends('state', 'move_lines')
def _compute_show_mark_as_todo(self):
for picking in self:
if not picking.move_lines and not picking.package_level_ids:
picking.show_mark_as_todo = False
elif not picking.immediate_transfer and picking.state == 'draft':
picking.show_mark_as_todo = True
elif picking.state != 'draft' or not picking.id:
picking.show_mark_as_todo = False
else:
picking.show_mark_as_todo = True
@api.depends('state')
def _compute_show_validate(self):
for picking in self:
if not (picking.immediate_transfer) and picking.state == 'draft':
picking.show_validate = False
elif picking.state not in ('draft', 'waiting', 'confirmed', 'assigned'):
picking.show_validate = False
else:
picking.show_validate = True
@api.depends('state', 'move_lines', 'picking_type_id')
def _compute_show_allocation(self):
self.show_allocation = False
if not self.user_has_groups('stock.group_reception_report'):
return
for picking in self:
picking.show_allocation = picking._get_show_allocation(picking.picking_type_id)
def _get_show_allocation(self, picking_type_id):
""" Helper method for computing "show_allocation" value.
Separated out from _compute function so it can be reused in other models (e.g. batch).
"""
if not picking_type_id or picking_type_id.code == 'outgoing':
return False
lines = self.move_lines.filtered(lambda m: m.product_id.type == 'product' and m.state != 'cancel')
if lines:
allowed_states = ['confirmed', 'partially_available', 'waiting']
if self[0].state == 'done':
allowed_states += ['assigned']
wh_location_ids = self.env['stock.location']._search([('id', 'child_of', picking_type_id.warehouse_id.view_location_id.id), ('usage', '!=', 'supplier')])
if self.env['stock.move'].search([
('state', 'in', allowed_states),
('product_qty', '>', 0),
('location_id', 'in', wh_location_ids),
('picking_id', 'not in', self.ids),
('product_id', 'in', lines.product_id.ids),
'|', ('move_orig_ids', '=', False),
('move_orig_ids', 'in', lines.ids)], limit=1):
return True
@api.model
def _search_delay_alert_date(self, operator, value):
late_stock_moves = self.env['stock.move'].search([('delay_alert_date', operator, value)])
return [('move_lines', 'in', late_stock_moves.ids)]
@api.onchange('partner_id')
def onchange_partner_id(self):
for picking in self:
picking_id = isinstance(picking.id, int) and picking.id or getattr(picking, '_origin', False) and picking._origin.id
if picking_id:
moves = self.env['stock.move'].search([('picking_id', '=', picking_id)])
for move in moves:
move.write({'partner_id': picking.partner_id.id})
@api.onchange('picking_type_id', 'partner_id')
def _onchange_picking_type(self):
if self.picking_type_id and self.state == 'draft':
self = self.with_company(self.company_id)
if self.picking_type_id.default_location_src_id:
location_id = self.picking_type_id.default_location_src_id.id
elif self.partner_id:
location_id = self.partner_id.property_stock_supplier.id
else:
customerloc, location_id = self.env['stock.warehouse']._get_partner_locations()
if self.picking_type_id.default_location_dest_id:
location_dest_id = self.picking_type_id.default_location_dest_id.id
elif self.partner_id:
location_dest_id = self.partner_id.property_stock_customer.id
else:
location_dest_id, supplierloc = self.env['stock.warehouse']._get_partner_locations()
self.location_id = location_id
self.location_dest_id = location_dest_id
(self.move_lines | self.move_ids_without_package).update({
"picking_type_id": self.picking_type_id, # The compute store doesn't work in case of One2many inverse (move_ids_without_package)
"company_id": self.company_id,
})
for move in (self.move_lines | self.move_ids_without_package):
move.description_picking = move.product_id._get_description(move.picking_type_id)
if self.partner_id and self.partner_id.picking_warn:
if self.partner_id.picking_warn == 'no-message' and self.partner_id.parent_id:
partner = self.partner_id.parent_id
elif self.partner_id.picking_warn not in ('no-message', 'block') and self.partner_id.parent_id.picking_warn == 'block':
partner = self.partner_id.parent_id
else:
partner = self.partner_id
if partner.picking_warn != 'no-message':
if partner.picking_warn == 'block':
self.partner_id = False
return {'warning': {
'title': ("Warning for %s") % partner.name,
'message': partner.picking_warn_msg
}}
@api.onchange('location_id', 'location_dest_id', 'picking_type_id')
def _onchange_locations(self):
(self.move_lines | self.move_ids_without_package).update({
"location_id": self.location_id,
"location_dest_id": self.location_dest_id
})
@api.model
def create(self, vals):
defaults = self.default_get(['name', 'picking_type_id'])
picking_type = self.env['stock.picking.type'].browse(vals.get('picking_type_id', defaults.get('picking_type_id')))
if vals.get('name', '/') == '/' and defaults.get('name', '/') == '/' and vals.get('picking_type_id', defaults.get('picking_type_id')):
if picking_type.sequence_id:
vals['name'] = picking_type.sequence_id.next_by_id()
# make sure to write `schedule_date` *after* the `stock.move` creation in
# order to get a determinist execution of `_set_scheduled_date`
scheduled_date = vals.pop('scheduled_date', False)
res = super(Picking, self).create(vals)
if scheduled_date:
res.with_context(mail_notrack=True).write({'scheduled_date': scheduled_date})
res._autoconfirm_picking()
# set partner as follower
if vals.get('partner_id'):
for picking in res.filtered(lambda p: p.location_id.usage == 'supplier' or p.location_dest_id.usage == 'customer'):
picking.message_subscribe([vals.get('partner_id')])
if vals.get('picking_type_id'):
for move in res.move_lines:
if not move.description_picking:
move.description_picking = move.product_id.with_context(lang=move._get_lang())._get_description(move.picking_id.picking_type_id)
return res
def write(self, vals):
if vals.get('picking_type_id') and any(picking.state != 'draft' for picking in self):
raise UserError(_("Changing the operation type of this record is forbidden at this point."))
# set partner as a follower and unfollow old partner
if vals.get('partner_id'):
for picking in self:
if picking.location_id.usage == 'supplier' or picking.location_dest_id.usage == 'customer':
if picking.partner_id:
picking.message_unsubscribe(picking.partner_id.ids)
picking.message_subscribe([vals.get('partner_id')])
res = super(Picking, self).write(vals)
if vals.get('signature'):
for picking in self:
picking._attach_sign()
# Change locations of moves if those of the picking change
after_vals = {}
if vals.get('location_id'):
after_vals['location_id'] = vals['location_id']
if vals.get('location_dest_id'):
after_vals['location_dest_id'] = vals['location_dest_id']
if 'partner_id' in vals:
after_vals['partner_id'] = vals['partner_id']
if after_vals:
self.mapped('move_lines').filtered(lambda move: not move.scrapped).write(after_vals)
if vals.get('move_lines'):
self._autoconfirm_picking()
return res
def unlink(self):
self.mapped('move_lines')._action_cancel()
self.with_context(prefetch_fields=False).mapped('move_lines').unlink() # Checks if moves are not done
return super(Picking, self).unlink()
def do_print_picking(self):
self.write({'printed': True})
return self.env.ref('stock.action_report_picking').report_action(self)
def should_print_delivery_address(self):
self.ensure_one()
return self.move_lines and self.move_lines[0].partner_id and self._is_to_external_location()
def _is_to_external_location(self):
self.ensure_one()
return self.picking_type_code == 'outgoing'
def action_confirm(self):
self._check_company()
self.mapped('package_level_ids').filtered(lambda pl: pl.state == 'draft' and not pl.move_ids)._generate_moves()
# call `_action_confirm` on every draft move
self.mapped('move_lines')\
.filtered(lambda move: move.state == 'draft')\
._action_confirm()
# run scheduler for moves forecasted to not have enough in stock
self.mapped('move_lines').filtered(lambda move: move.state not in ('draft', 'cancel', 'done'))._trigger_scheduler()
return True
def action_assign(self):
""" Check availability of picking moves.
This has the effect of changing the state and reserve quants on available moves, and may
also impact the state of the picking as it is computed based on move's states.
@return: True
"""
self.filtered(lambda picking: picking.state == 'draft').action_confirm()
moves = self.mapped('move_lines').filtered(lambda move: move.state not in ('draft', 'cancel', 'done')).sorted(
key=lambda move: (-int(move.priority), not bool(move.date_deadline), move.date_deadline, move.date, move.id)
)
if not moves:
raise UserError(_('Nothing to check the availability for.'))
# If a package level is done when confirmed its location can be different than where it will be reserved.
# So we remove the move lines created when confirmed to set quantity done to the new reserved ones.
package_level_done = self.mapped('package_level_ids').filtered(lambda pl: pl.is_done and pl.state == 'confirmed')
package_level_done.write({'is_done': False})
moves._action_assign()
package_level_done.write({'is_done': True})
return True
def action_cancel(self):
self.mapped('move_lines')._action_cancel()
self.write({'is_locked': True})
self.filtered(lambda x: not x.move_lines).state = 'cancel'
return True
def _action_done(self):
"""Call `_action_done` on the `stock.move` of the `stock.picking` in `self`.
This method makes sure every `stock.move.line` is linked to a `stock.move` by either
linking them to an existing one or a newly created one.
If the context key `cancel_backorder` is present, backorders won't be created.
:return: True
:rtype: bool
"""
self._check_company()
todo_moves = self.mapped('move_lines').filtered(lambda self: self.state in ['draft', 'waiting', 'partially_available', 'assigned', 'confirmed'])
for picking in self:
if picking.owner_id:
picking.move_lines.write({'restrict_partner_id': picking.owner_id.id})
picking.move_line_ids.write({'owner_id': picking.owner_id.id})
todo_moves._action_done(cancel_backorder=self.env.context.get('cancel_backorder'))
self.write({'date_done': fields.Datetime.now(), 'priority': '0'})
# if incoming moves make other confirmed/partially_available moves available, assign them
done_incoming_moves = self.filtered(lambda p: p.picking_type_id.code == 'incoming').move_lines.filtered(lambda m: m.state == 'done')
done_incoming_moves._trigger_assign()
self._send_confirmation_email()
return True
def _send_confirmation_email(self):
for stock_pick in self.filtered(lambda p: p.company_id.stock_move_email_validation and p.picking_type_id.code == 'outgoing'):
delivery_template_id = stock_pick.company_id.stock_mail_confirmation_template_id.id
stock_pick.with_context(force_send=True).message_post_with_template(delivery_template_id, email_layout_xmlid='mail.mail_notification_light')
@api.depends('state', 'move_lines', 'move_lines.state', 'move_lines.package_level_id', 'move_lines.move_line_ids.package_level_id')
def _compute_move_without_package(self):
for picking in self:
picking.move_ids_without_package = picking._get_move_ids_without_package()
def _set_move_without_package(self):
new_mwp = self[0].move_ids_without_package
for picking in self:
old_mwp = picking._get_move_ids_without_package()
picking.move_lines = (picking.move_lines - old_mwp) | new_mwp
moves_to_unlink = old_mwp - new_mwp
if moves_to_unlink:
moves_to_unlink.unlink()
def _get_move_ids_without_package(self):
self.ensure_one()
move_ids_without_package = self.env['stock.move']
if not self.picking_type_entire_packs:
move_ids_without_package = self.move_lines
else:
for move in self.move_lines:
if not move.package_level_id:
if move.state == 'assigned' and move.picking_id and not move.picking_id.immediate_transfer or move.state == 'done':
if any(not ml.package_level_id for ml in move.move_line_ids):
move_ids_without_package |= move
else:
move_ids_without_package |= move
return move_ids_without_package.filtered(lambda move: not move.scrap_ids)
def _check_move_lines_map_quant_package(self, package):
""" This method checks that all product of the package (quant) are well present in the move_line_ids of the picking. """
all_in = True
pack_move_lines = self.move_line_ids.filtered(lambda ml: ml.package_id == package)
keys = ['product_id', 'lot_id']
keys_ids = ["{}.id".format(fname) for fname in keys]
precision_digits = self.env['decimal.precision'].precision_get('Product Unit of Measure')
grouped_quants = {}
for k, g in groupby(sorted(package.quant_ids, key=attrgetter(*keys_ids)), key=itemgetter(*keys)):
grouped_quants[k] = sum(self.env['stock.quant'].concat(*list(g)).mapped('quantity'))
grouped_ops = {}
for k, g in groupby(sorted(pack_move_lines, key=attrgetter(*keys_ids)), key=itemgetter(*keys)):
grouped_ops[k] = sum(self.env['stock.move.line'].concat(*list(g)).mapped('product_qty'))
if any(not float_is_zero(grouped_quants.get(key, 0) - grouped_ops.get(key, 0), precision_digits=precision_digits) for key in grouped_quants) \
or any(not float_is_zero(grouped_ops.get(key, 0) - grouped_quants.get(key, 0), precision_digits=precision_digits) for key in grouped_ops):
all_in = False
return all_in
def _get_entire_pack_location_dest(self, move_line_ids):
location_dest_ids = move_line_ids.mapped('location_dest_id')
if len(location_dest_ids) > 1:
return False
return location_dest_ids.id
def _check_entire_pack(self):
""" This function check if entire packs are moved in the picking"""
for picking in self:
origin_packages = picking.move_line_ids.mapped("package_id")
for pack in origin_packages:
if picking._check_move_lines_map_quant_package(pack):
package_level_ids = picking.package_level_ids.filtered(lambda pl: pl.package_id == pack)
move_lines_to_pack = picking.move_line_ids.filtered(lambda ml: ml.package_id == pack and not ml.result_package_id and ml.state not in ('done', 'cancel'))
if not package_level_ids:
self.env['stock.package_level'].create({
'picking_id': picking.id,
'package_id': pack.id,
'location_id': pack.location_id.id,
'location_dest_id': self._get_entire_pack_location_dest(move_lines_to_pack) or picking.location_dest_id.id,
'move_line_ids': [(6, 0, move_lines_to_pack.ids)],
'company_id': picking.company_id.id,
})
# Propagate the result package in the next move for disposable packages only.
if pack.package_use == 'disposable':
move_lines_to_pack.write({
'result_package_id': pack.id,
})
else:
move_lines_in_package_level = move_lines_to_pack.filtered(lambda ml: ml.move_id.package_level_id)
move_lines_without_package_level = move_lines_to_pack - move_lines_in_package_level
for ml in move_lines_in_package_level:
ml.write({
'result_package_id': pack.id,
'package_level_id': ml.move_id.package_level_id.id,
})
move_lines_without_package_level.write({
'result_package_id': pack.id,
'package_level_id': package_level_ids[0].id,
})
for pl in package_level_ids:
pl.location_dest_id = self._get_entire_pack_location_dest(pl.move_line_ids) or picking.location_dest_id.id
def do_unreserve(self):
self.move_lines._do_unreserve()
self.package_level_ids.filtered(lambda p: not p.move_ids).unlink()
def button_validate(self):
# Clean-up the context key at validation to avoid forcing the creation of immediate
# transfers.
ctx = dict(self.env.context)
ctx.pop('default_immediate_transfer', None)
self = self.with_context(ctx)
# Sanity checks.
pickings_without_moves = self.browse()
pickings_without_quantities = self.browse()
pickings_without_lots = self.browse()
products_without_lots = self.env['product.product']
for picking in self:
if not picking.move_lines and not picking.move_line_ids:
pickings_without_moves |= picking
picking.message_subscribe([self.env.user.partner_id.id])
picking_type = picking.picking_type_id
precision_digits = self.env['decimal.precision'].precision_get('Product Unit of Measure')
no_quantities_done = all(float_is_zero(move_line.qty_done, precision_digits=precision_digits) for move_line in picking.move_line_ids.filtered(lambda m: m.state not in ('done', 'cancel')))
no_reserved_quantities = all(float_is_zero(move_line.product_qty, precision_rounding=move_line.product_uom_id.rounding) for move_line in picking.move_line_ids)
if no_reserved_quantities and no_quantities_done:
pickings_without_quantities |= picking
if picking_type.use_create_lots or picking_type.use_existing_lots:
lines_to_check = picking.move_line_ids
if not no_quantities_done:
lines_to_check = lines_to_check.filtered(lambda line: float_compare(line.qty_done, 0, precision_rounding=line.product_uom_id.rounding))
for line in lines_to_check:
product = line.product_id
if product and product.tracking != 'none':
if not line.lot_name and not line.lot_id:
pickings_without_lots |= picking
products_without_lots |= product
if not self._should_show_transfers():
if pickings_without_moves:
raise UserError(_('Please add some items to move.'))
if pickings_without_quantities:
raise UserError(self._get_without_quantities_error_message())
if pickings_without_lots:
raise UserError(_('You need to supply a Lot/Serial number for products %s.') % ', '.join(products_without_lots.mapped('display_name')))
else:
message = ""
if pickings_without_moves:
message += _('Transfers %s: Please add some items to move.') % ', '.join(pickings_without_moves.mapped('name'))
if pickings_without_quantities:
message += _('\n\nTransfers %s: You cannot validate these transfers if no quantities are reserved nor done. To force these transfers, switch in edit more and encode the done quantities.') % ', '.join(pickings_without_quantities.mapped('name'))
if pickings_without_lots:
message += _('\n\nTransfers %s: You need to supply a Lot/Serial number for products %s.') % (', '.join(pickings_without_lots.mapped('name')), ', '.join(products_without_lots.mapped('display_name')))
if message:
raise UserError(message.lstrip())
# Run the pre-validation wizards. Processing a pre-validation wizard should work on the
# moves and/or the context and never call `_action_done`.
if not self.env.context.get('button_validate_picking_ids'):
self = self.with_context(button_validate_picking_ids=self.ids)
res = self._pre_action_done_hook()
if res is not True:
return res
# Call `_action_done`.
if self.env.context.get('picking_ids_not_to_backorder'):
pickings_not_to_backorder = self.browse(self.env.context['picking_ids_not_to_backorder'])
pickings_to_backorder = self - pickings_not_to_backorder
else:
pickings_not_to_backorder = self.env['stock.picking']
pickings_to_backorder = self
pickings_not_to_backorder.with_context(cancel_backorder=True)._action_done()
pickings_to_backorder.with_context(cancel_backorder=False)._action_done()
if self.user_has_groups('stock.group_reception_report') \
and self.user_has_groups('stock.group_auto_reception_report') \
and self.filtered(lambda p: p.picking_type_id.code != 'outgoing'):
lines = self.move_lines.filtered(lambda m: m.product_id.type == 'product' and m.state != 'cancel' and m.quantity_done and not m.move_dest_ids)
if lines:
# don't show reception report if all already assigned/nothing to assign
wh_location_ids = self.env['stock.location']._search([('id', 'child_of', self.picking_type_id.warehouse_id.view_location_id.ids), ('usage', '!=', 'supplier')])
if self.env['stock.move'].search([
('state', 'in', ['confirmed', 'partially_available', 'waiting', 'assigned']),
('product_qty', '>', 0),
('location_id', 'in', wh_location_ids),
('move_orig_ids', '=', False),
('picking_id', 'not in', self.ids),
('product_id', 'in', lines.product_id.ids)], limit=1):
action = self.action_view_reception_report()
action['context'] = {'default_picking_ids': self.ids}
return action
return True
def action_set_quantities_to_reservation(self):
self.move_lines._set_quantities_to_reservation()
def _pre_action_done_hook(self):
if not self.env.context.get('skip_immediate'):
pickings_to_immediate = self._check_immediate()
if pickings_to_immediate:
return pickings_to_immediate._action_generate_immediate_wizard(show_transfers=self._should_show_transfers())
if not self.env.context.get('skip_backorder'):
pickings_to_backorder = self._check_backorder()
if pickings_to_backorder:
return pickings_to_backorder._action_generate_backorder_wizard(show_transfers=self._should_show_transfers())
return True
def _should_show_transfers(self):
"""Whether the different transfers should be displayed on the pre action done wizards."""
return len(self) > 1
def _get_without_quantities_error_message(self):
""" Returns the error message raised in validation if no quantities are reserved or done.
The purpose of this method is to be overridden in case we want to adapt this message.
:return: Translated error message
:rtype: str
"""
return _(
'You cannot validate a transfer if no quantities are reserved nor done. '
'To force the transfer, switch in edit mode and encode the done quantities.'
)
def _action_generate_backorder_wizard(self, show_transfers=False):
view = self.env.ref('stock.view_backorder_confirmation')
return {
'name': _('Create Backorder?'),
'type': 'ir.actions.act_window',
'view_mode': 'form',
'res_model': 'stock.backorder.confirmation',
'views': [(view.id, 'form')],
'view_id': view.id,
'target': 'new',
'context': dict(self.env.context, default_show_transfers=show_transfers, default_pick_ids=[(4, p.id) for p in self]),
}
def _action_generate_immediate_wizard(self, show_transfers=False):
view = self.env.ref('stock.view_immediate_transfer')
return {
'name': _('Immediate Transfer?'),
'type': 'ir.actions.act_window',
'view_mode': 'form',
'res_model': 'stock.immediate.transfer',
'views': [(view.id, 'form')],
'view_id': view.id,
'target': 'new',
'context': dict(self.env.context, default_show_transfers=show_transfers, default_pick_ids=[(4, p.id) for p in self]),
}
def action_toggle_is_locked(self):
self.ensure_one()
self.is_locked = not self.is_locked
return True
def _check_backorder(self):
prec = self.env["decimal.precision"].precision_get("Product Unit of Measure")
backorder_pickings = self.browse()
for picking in self:
quantity_todo = {}
quantity_done = {}
for move in picking.mapped('move_lines').filtered(lambda m: m.state != "cancel"):
quantity_todo.setdefault(move.product_id.id, 0)
quantity_done.setdefault(move.product_id.id, 0)
quantity_todo[move.product_id.id] += move.product_uom._compute_quantity(move.product_uom_qty, move.product_id.uom_id, rounding_method='HALF-UP')
quantity_done[move.product_id.id] += move.product_uom._compute_quantity(move.quantity_done, move.product_id.uom_id, rounding_method='HALF-UP')
# FIXME: the next block doesn't seem nor should be used.
for ops in picking.mapped('move_line_ids').filtered(lambda x: x.package_id and not x.product_id and not x.move_id):
for quant in ops.package_id.quant_ids:
quantity_done.setdefault(quant.product_id.id, 0)
quantity_done[quant.product_id.id] += quant.qty
for pack in picking.mapped('move_line_ids').filtered(lambda x: x.product_id and not x.move_id):
quantity_done.setdefault(pack.product_id.id, 0)
quantity_done[pack.product_id.id] += pack.product_uom_id._compute_quantity(pack.qty_done, pack.product_id.uom_id)
if any(
float_compare(quantity_done[x], quantity_todo.get(x, 0), precision_digits=prec,) == -1
for x in quantity_done
):
backorder_pickings |= picking
return backorder_pickings
def _check_immediate(self):
immediate_pickings = self.browse()
precision_digits = self.env['decimal.precision'].precision_get('Product Unit of Measure')
for picking in self:
if all(float_is_zero(move_line.qty_done, precision_digits=precision_digits) for move_line in picking.move_line_ids.filtered(lambda m: m.state not in ('done', 'cancel'))):
immediate_pickings |= picking
return immediate_pickings
def _autoconfirm_picking(self):
""" Automatically run `action_confirm` on `self` if the picking is an immediate transfer or
if the picking is a planned transfer and one of its move was added after the initial
call to `action_confirm`. Note that `action_confirm` will only work on draft moves.
"""
# Clean-up the context key to avoid forcing the creation of immediate transfers.
ctx = dict(self.env.context)
ctx.pop('default_immediate_transfer', None)
self = self.with_context(ctx)
for picking in self:
if picking.state in ('done', 'cancel'):
continue
if not picking.move_lines and not picking.package_level_ids:
continue
if picking.immediate_transfer or any(move.additional for move in picking.move_lines):
picking.action_confirm()
# Make sure the reservation is bypassed in immediate transfer mode.
if picking.immediate_transfer:
picking.move_lines.write({'state': 'assigned'})
def _create_backorder(self):
""" This method is called when the user chose to create a backorder. It will create a new
picking, the backorder, and move the stock.moves that are not `done` or `cancel` into it.
"""
backorders = self.env['stock.picking']
bo_to_assign = self.env['stock.picking']
for picking in self:
moves_to_backorder = picking.move_lines.filtered(lambda x: x.state not in ('done', 'cancel'))
if moves_to_backorder:
backorder_picking = picking.copy({
'name': '/',
'move_lines': [],
'move_line_ids': [],
'backorder_id': picking.id
})
picking.message_post(
body=_('The backorder <a href=# data-oe-model=stock.picking data-oe-id=%d>%s</a> has been created.') % (
backorder_picking.id, backorder_picking.name))
moves_to_backorder.write({'picking_id': backorder_picking.id})
moves_to_backorder.move_line_ids.package_level_id.write({'picking_id':backorder_picking.id})
moves_to_backorder.mapped('move_line_ids').write({'picking_id': backorder_picking.id})
backorders |= backorder_picking
if backorder_picking.picking_type_id.reservation_method == 'at_confirm':
bo_to_assign |= backorder_picking
if bo_to_assign:
bo_to_assign.action_assign()
return backorders
def _log_activity_get_documents(self, orig_obj_changes, stream_field, stream, sorted_method=False, groupby_method=False):
""" Generic method to log activity. To use with
_log_activity method. It either log on uppermost
ongoing documents or following documents. This method
find all the documents and responsible for which a note
has to be log. It also generate a rendering_context in
order to render a specific note by documents containing
only the information relative to the document it. For example
we don't want to notify a picking on move that it doesn't
contain.
:param orig_obj_changes dict: contain a record as key and the
change on this record as value.
eg: {'move_id': (new product_uom_qty, old product_uom_qty)}
:param stream_field string: It has to be a field of the
records that are register in the key of 'orig_obj_changes'
eg: 'move_dest_ids' if we use move as record (previous example)
- 'UP' if we want to log on the upper most ongoing
documents.
- 'DOWN' if we want to log on following documents.
:param sorted_method method, groupby_method: Only need when
stream is 'DOWN', it should sort/group by tuple(object on
which the activity is log, the responsible for this object)
"""
if self.env.context.get('skip_activity'):
return {}
move_to_orig_object_rel = {co: ooc for ooc in orig_obj_changes.keys() for co in ooc[stream_field]}
origin_objects = self.env[list(orig_obj_changes.keys())[0]._name].concat(*list(orig_obj_changes.keys()))
# The purpose here is to group each destination object by
# (document to log, responsible) no matter the stream direction.
# example:
# {'(delivery_picking_1, admin)': stock.move(1, 2)
# '(delivery_picking_2, admin)': stock.move(3)}
visited_documents = {}
if stream == 'DOWN':
if sorted_method and groupby_method:
grouped_moves = groupby(sorted(origin_objects.mapped(stream_field), key=sorted_method), key=groupby_method)
else:
raise UserError(_('You have to define a groupby and sorted method and pass them as arguments.'))
elif stream == 'UP':
# When using upstream document it is required to define
# _get_upstream_documents_and_responsibles on
# destination objects in order to ascend documents.
grouped_moves = {}
for visited_move in origin_objects.mapped(stream_field):
for document, responsible, visited in visited_move._get_upstream_documents_and_responsibles(self.env[visited_move._name]):
if grouped_moves.get((document, responsible)):
grouped_moves[(document, responsible)] |= visited_move
visited_documents[(document, responsible)] |= visited
else:
grouped_moves[(document, responsible)] = visited_move
visited_documents[(document, responsible)] = visited
grouped_moves = grouped_moves.items()
else:
raise UserError(_('Unknown stream.'))
documents = {}
for (parent, responsible), moves in grouped_moves:
if not parent:
continue
moves = list(moves)
moves = self.env[moves[0]._name].concat(*moves)
# Get the note
rendering_context = {move: (orig_object, orig_obj_changes[orig_object]) for move in moves for orig_object in move_to_orig_object_rel[move]}
if visited_documents:
documents[(parent, responsible)] = rendering_context, visited_documents.values()
else:
documents[(parent, responsible)] = rendering_context
return documents
def _log_activity(self, render_method, documents):
""" Log a note for each documents, responsible pair in
documents passed as argument. The render_method is then
call in order to use a template and render it with a
rendering_context.
:param documents dict: A tuple (document, responsible) as key.
An activity will be log by key. A rendering_context as value.
If used with _log_activity_get_documents. In 'DOWN' stream
cases the rendering_context will be a dict with format:
{'stream_object': ('orig_object', new_qty, old_qty)}
'UP' stream will add all the documents browsed in order to
get the final/upstream document present in the key.
:param render_method method: a static function that will generate
the html note to log on the activity. The render_method should
use the args:
- rendering_context dict: value of the documents argument
the render_method should return a string with an html format
:param stream string:
"""
for (parent, responsible), rendering_context in documents.items():
note = render_method(rendering_context)
parent.activity_schedule(
'mail.mail_activity_data_warning',
date.today(),
note=note,
user_id=responsible.id or SUPERUSER_ID
)
def _log_less_quantities_than_expected(self, moves):
""" Log an activity on picking that follow moves. The note
contains the moves changes and all the impacted picking.
:param dict moves: a dict with a move as key and tuple with
new and old quantity as value. eg: {move_1 : (4, 5)}
"""
def _keys_in_sorted(move):
""" sort by picking and the responsible for the product the
move.
"""
return (move.picking_id.id, move.product_id.responsible_id.id)
def _keys_in_groupby(move):
""" group by picking and the responsible for the product the
move.
"""
return (move.picking_id, move.product_id.responsible_id)
def _render_note_exception_quantity(rendering_context):
""" :param rendering_context:
{'move_dest': (move_orig, (new_qty, old_qty))}
"""
origin_moves = self.env['stock.move'].browse([move.id for move_orig in rendering_context.values() for move in move_orig[0]])
origin_picking = origin_moves.mapped('picking_id')
move_dest_ids = self.env['stock.move'].concat(*rendering_context.keys())
impacted_pickings = origin_picking._get_impacted_pickings(move_dest_ids) - move_dest_ids.mapped('picking_id')
values = {
'origin_picking': origin_picking,
'moves_information': rendering_context.values(),
'impacted_pickings': impacted_pickings,
}
return self.env.ref('stock.exception_on_picking')._render(values=values)
documents = self._log_activity_get_documents(moves, 'move_dest_ids', 'DOWN', _keys_in_sorted, _keys_in_groupby)
documents = self._less_quantities_than_expected_add_documents(moves, documents)
self._log_activity(_render_note_exception_quantity, documents)
def _less_quantities_than_expected_add_documents(self, moves, documents):
return documents
def _get_impacted_pickings(self, moves):
""" This function is used in _log_less_quantities_than_expected
the purpose is to notify a user with all the pickings that are
impacted by an action on a chained move.
param: 'moves' contain moves that belong to a common picking.
return: all the pickings that contain a destination moves
(direct and indirect) from the moves given as arguments.
"""
def _explore(impacted_pickings, explored_moves, moves_to_explore):
for move in moves_to_explore:
if move not in explored_moves:
impacted_pickings |= move.picking_id
explored_moves |= move
moves_to_explore |= move.move_dest_ids
moves_to_explore = moves_to_explore - explored_moves
if moves_to_explore:
return _explore(impacted_pickings, explored_moves, moves_to_explore)
else:
return impacted_pickings
return _explore(self.env['stock.picking'], self.env['stock.move'], moves)
def _pre_put_in_pack_hook(self, move_line_ids):
return self._check_destinations(move_line_ids)
def _check_destinations(self, move_line_ids):
if len(move_line_ids.mapped('location_dest_id')) > 1:
view_id = self.env.ref('stock.stock_package_destination_form_view').id
wiz = self.env['stock.package.destination'].create({
'picking_id': self.id,
'location_dest_id': move_line_ids[0].location_dest_id.id,
})
return {
'name': _('Choose destination location'),
'view_mode': 'form',
'res_model': 'stock.package.destination',
'view_id': view_id,
'views': [(view_id, 'form')],
'type': 'ir.actions.act_window',
'res_id': wiz.id,
'target': 'new'
}
else:
return {}
def _put_in_pack(self, move_line_ids, create_package_level=True):
package = False
for pick in self:
move_lines_to_pack = self.env['stock.move.line']
package = self.env['stock.quant.package'].create({})
precision_digits = self.env['decimal.precision'].precision_get('Product Unit of Measure')
if float_is_zero(move_line_ids[0].qty_done, precision_digits=precision_digits):
for line in move_line_ids:
line.qty_done = line.product_uom_qty
for ml in move_line_ids:
if float_compare(ml.qty_done, ml.product_uom_qty,
precision_rounding=ml.product_uom_id.rounding) >= 0:
move_lines_to_pack |= ml
else:
quantity_left_todo = float_round(
ml.product_uom_qty - ml.qty_done,
precision_rounding=ml.product_uom_id.rounding,
rounding_method='HALF-UP')
done_to_keep = ml.qty_done
new_move_line = ml.copy(
default={'product_uom_qty': 0, 'qty_done': ml.qty_done})
vals = {'product_uom_qty': quantity_left_todo, 'qty_done': 0.0}
if pick.picking_type_id.code == 'incoming':
if ml.lot_id:
vals['lot_id'] = False
if ml.lot_name:
vals['lot_name'] = False
ml.write(vals)
new_move_line.write({'product_uom_qty': done_to_keep})
move_lines_to_pack |= new_move_line
if not package.package_type_id:
package_type = move_lines_to_pack.move_id.product_packaging_id.package_type_id
if len(package_type) == 1:
package.package_type_id = package_type
if len(move_lines_to_pack) == 1:
default_dest_location = move_lines_to_pack._get_default_dest_location()
move_lines_to_pack.location_dest_id = default_dest_location._get_putaway_strategy(
product=move_lines_to_pack.product_id,
quantity=move_lines_to_pack.product_uom_qty,
package=package)
move_lines_to_pack.write({
'result_package_id': package.id,
})
if create_package_level:
package_level = self.env['stock.package_level'].create({
'package_id': package.id,
'picking_id': pick.id,
'location_id': False,
'location_dest_id': move_lines_to_pack.mapped('location_dest_id').id,
'move_line_ids': [(6, 0, move_lines_to_pack.ids)],
'company_id': pick.company_id.id,
})
return package
def action_put_in_pack(self):
self.ensure_one()
if self.state not in ('done', 'cancel'):
picking_move_lines = self.move_line_ids
if (
not self.picking_type_id.show_reserved
and not self.immediate_transfer
and not self.env.context.get('barcode_view')
):
picking_move_lines = self.move_line_nosuggest_ids
move_line_ids = picking_move_lines.filtered(lambda ml:
float_compare(ml.qty_done, 0.0, precision_rounding=ml.product_uom_id.rounding) > 0
and not ml.result_package_id
)
if not move_line_ids:
move_line_ids = picking_move_lines.filtered(lambda ml: float_compare(ml.product_uom_qty, 0.0,
precision_rounding=ml.product_uom_id.rounding) > 0 and float_compare(ml.qty_done, 0.0,
precision_rounding=ml.product_uom_id.rounding) == 0)
if move_line_ids:
res = self._pre_put_in_pack_hook(move_line_ids)
if not res:
res = self._put_in_pack(move_line_ids)
return res
else:
raise UserError(_("Please add 'Done' quantities to the picking to create a new pack."))
def button_scrap(self):
self.ensure_one()
view = self.env.ref('stock.stock_scrap_form_view2')
products = self.env['product.product']
for move in self.move_lines:
if move.state not in ('draft', 'cancel') and move.product_id.type in ('product', 'consu'):
products |= move.product_id
return {
'name': _('Scrap'),
'view_mode': 'form',
'res_model': 'stock.scrap',
'view_id': view.id,
'views': [(view.id, 'form')],
'type': 'ir.actions.act_window',
'context': {'default_picking_id': self.id, 'product_ids': products.ids, 'default_company_id': self.company_id.id},
'target': 'new',
}
def action_see_move_scrap(self):
self.ensure_one()
action = self.env["ir.actions.actions"]._for_xml_id("stock.action_stock_scrap")
scraps = self.env['stock.scrap'].search([('picking_id', '=', self.id)])
action['domain'] = [('id', 'in', scraps.ids)]
action['context'] = dict(self._context, create=False)
return action
def action_see_packages(self):
self.ensure_one()
action = self.env["ir.actions.actions"]._for_xml_id("stock.action_package_view")
packages = self.move_line_ids.mapped('result_package_id')
action['domain'] = [('id', 'in', packages.ids)]
action['context'] = {'picking_id': self.id}
return action
def action_picking_move_tree(self):
action = self.env["ir.actions.actions"]._for_xml_id("stock.stock_move_action")
action['views'] = [
(self.env.ref('stock.view_picking_move_tree').id, 'tree'),
]
action['context'] = self.env.context
action['domain'] = [('picking_id', 'in', self.ids)]
return action
def action_view_reception_report(self):
return self.env["ir.actions.actions"]._for_xml_id("stock.stock_reception_action")
def action_open_label_layout(self):
view = self.env.ref('stock.product_label_layout_form_picking')
return {
'name': _('Choose Labels Layout'),
'type': 'ir.actions.act_window',
'res_model': 'product.label.layout',
'views': [(view.id, 'form')],
'target': 'new',
'context': {
'default_product_ids': self.move_lines.product_id.ids,
'default_move_line_ids': self.move_line_ids.ids,
'default_picking_quantity': 'picking'},
}
def _attach_sign(self):
""" Render the delivery report in pdf and attach it to the picking in `self`. """
self.ensure_one()
report = self.env.ref('stock.action_report_delivery')._render_qweb_pdf(self.id)
filename = "%s_signed_delivery_slip" % self.name
if self.partner_id:
message = _('Order signed by %s') % (self.partner_id.name)
else:
message = _('Order signed')
self.message_post(
attachments=[('%s.pdf' % filename, report[0])],
body=message,
)
return True
def _get_report_lang(self):
return self.move_lines and self.move_lines[0].partner_id.lang or self.partner_id.lang or self.env.lang
| 54.014974
| 82,967
|
7,761
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, api, fields, models
from odoo.exceptions import UserError
from odoo.tools.float_utils import float_compare
class RemovalStrategy(models.Model):
_name = 'product.removal'
_description = 'Removal Strategy'
name = fields.Char('Name', required=True)
method = fields.Char("Method", required=True, help="FIFO, LIFO...")
class StockPutawayRule(models.Model):
_name = 'stock.putaway.rule'
_order = 'sequence,product_id'
_description = 'Putaway Rule'
_check_company_auto = True
def _default_category_id(self):
if self.env.context.get('active_model') == 'product.category':
return self.env.context.get('active_id')
def _default_location_id(self):
if self.env.context.get('active_model') == 'stock.location':
return self.env.context.get('active_id')
if not self.env.user.has_group('stock.group_stock_multi_warehouses'):
wh = self.env['stock.warehouse'].search([('company_id', '=', self.env.company.id)], limit=1)
input_loc, _ = wh._get_input_output_locations(wh.reception_steps, wh.delivery_steps)
return input_loc
def _default_product_id(self):
if self.env.context.get('active_model') == 'product.template' and self.env.context.get('active_id'):
product_template = self.env['product.template'].browse(self.env.context.get('active_id'))
product_template = product_template.exists()
if product_template.product_variant_count == 1:
return product_template.product_variant_id
elif self.env.context.get('active_model') == 'product.product':
return self.env.context.get('active_id')
def _domain_category_id(self):
active_model = self.env.context.get('active_model')
if active_model in ('product.template', 'product.product') and self.env.context.get('active_id'):
product = self.env[active_model].browse(self.env.context.get('active_id'))
product = product.exists()
if product:
return [('id', '=', product.categ_id.id)]
return []
def _domain_product_id(self):
domain = "[('type', '!=', 'service'), '|', ('company_id', '=', False), ('company_id', '=', company_id)]"
if self.env.context.get('active_model') == 'product.template':
return [('product_tmpl_id', '=', self.env.context.get('active_id'))]
return domain
product_id = fields.Many2one(
'product.product', 'Product', check_company=True,
default=_default_product_id, domain=_domain_product_id, ondelete='cascade')
category_id = fields.Many2one('product.category', 'Product Category',
default=_default_category_id, domain=_domain_category_id, ondelete='cascade')
location_in_id = fields.Many2one(
'stock.location', 'When product arrives in', check_company=True,
domain="[('child_ids', '!=', False), '|', ('company_id', '=', False), ('company_id', '=', company_id)]",
default=_default_location_id, required=True, ondelete='cascade', index=True)
location_out_id = fields.Many2one(
'stock.location', 'Store to sublocation', check_company=True,
domain="[('id', 'child_of', location_in_id), '|', ('company_id', '=', False), ('company_id', '=', company_id)]",
required=True, ondelete='cascade')
sequence = fields.Integer('Priority', help="Give to the more specialized category, a higher priority to have them in top of the list.")
company_id = fields.Many2one(
'res.company', 'Company', required=True,
default=lambda s: s.env.company.id, index=True)
package_type_ids = fields.Many2many('stock.package.type', string='Package Type', check_company=True)
storage_category_id = fields.Many2one('stock.storage.category', 'Storage Category', ondelete='cascade', check_company=True)
active = fields.Boolean('Active', default=True)
@api.onchange('location_in_id')
def _onchange_location_in(self):
child_location_count = 0
if self.location_out_id:
child_location_count = self.env['stock.location'].search_count([
('id', '=', self.location_out_id.id),
('id', 'child_of', self.location_in_id.id),
('id', '!=', self.location_in_id.id),
])
if not child_location_count or not self.location_out_id:
self.location_out_id = self.location_in_id
@api.model_create_multi
def create(self, vals_list):
rules = super().create(vals_list)
rules._enable_show_reserved()
return rules
def write(self, vals):
if 'company_id' in vals:
for rule in self:
if rule.company_id.id != vals['company_id']:
raise UserError(_("Changing the company of this record is forbidden at this point, you should rather archive it and create a new one."))
self._enable_show_reserved()
return super(StockPutawayRule, self).write(vals)
def _enable_show_reserved(self):
out_locations = self.location_out_id
if out_locations:
self.env['stock.picking.type'].with_context(active_test=False)\
.search([('default_location_dest_id', 'in', out_locations.ids)])\
.write({'show_reserved': True})
def _get_putaway_location(self, product, quantity=0, package=None, packaging=None, qty_by_location=None):
# find package type on package or packaging
package_type = self.env['stock.package.type']
if package:
package_type = package.package_type_id
elif packaging:
package_type = packaging.package_type_id
checked_locations = set()
for putaway_rule in self:
location_out = putaway_rule.location_out_id
if not putaway_rule.storage_category_id:
if location_out in checked_locations:
continue
if location_out._check_can_be_used(product, quantity, package, qty_by_location[location_out.id]):
return location_out
continue
child_locations = location_out.child_internal_location_ids
# check if already have the product/package type stored
for location in child_locations:
if location in checked_locations:
continue
if package_type:
if location.quant_ids.filtered(lambda q: q.package_id and q.package_id.package_type_id == package_type):
if location._check_can_be_used(product, quantity, package=package, location_qty=qty_by_location[location.id]):
return location
else:
checked_locations.add(location)
elif float_compare(qty_by_location[location.id], 0, precision_rounding=product.uom_id.rounding) > 0:
if location._check_can_be_used(product, quantity, location_qty=qty_by_location[location.id]):
return location
else:
checked_locations.add(location)
# check locations with matched storage category
for location in child_locations.filtered(lambda l: l.storage_category_id == putaway_rule.storage_category_id):
if location in checked_locations:
continue
if location._check_can_be_used(product, quantity, package, qty_by_location[location.id]):
return location
checked_locations.add(location)
return None
| 49.433121
| 7,761
|
528
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class BarcodeRule(models.Model):
_inherit = 'barcode.rule'
type = fields.Selection(selection_add=[
('weight', 'Weighted Product'),
('location', 'Location'),
('lot', 'Lot'),
('package', 'Package')
], ondelete={
'weight': 'set default',
'location': 'set default',
'lot': 'set default',
'package': 'set default',
})
| 26.4
| 528
|
59,412
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import operator as py_operator
from ast import literal_eval
from collections import defaultdict
from dateutil.relativedelta import relativedelta
from odoo import _, api, fields, models
from odoo.exceptions import UserError
from odoo.osv import expression
from odoo.tools import float_is_zero
from odoo.tools.float_utils import float_round
from odoo.tools.mail import html2plaintext, is_html_empty
OPERATORS = {
'<': py_operator.lt,
'>': py_operator.gt,
'<=': py_operator.le,
'>=': py_operator.ge,
'=': py_operator.eq,
'!=': py_operator.ne
}
class Product(models.Model):
_inherit = "product.product"
stock_quant_ids = fields.One2many('stock.quant', 'product_id', help='Technical: used to compute quantities.')
stock_move_ids = fields.One2many('stock.move', 'product_id', help='Technical: used to compute quantities.')
qty_available = fields.Float(
'Quantity On Hand', compute='_compute_quantities', search='_search_qty_available',
digits='Product Unit of Measure', compute_sudo=False,
help="Current quantity of products.\n"
"In a context with a single Stock Location, this includes "
"goods stored at this Location, or any of its children.\n"
"In a context with a single Warehouse, this includes "
"goods stored in the Stock Location of this Warehouse, or any "
"of its children.\n"
"stored in the Stock Location of the Warehouse of this Shop, "
"or any of its children.\n"
"Otherwise, this includes goods stored in any Stock Location "
"with 'internal' type.")
virtual_available = fields.Float(
'Forecasted Quantity', compute='_compute_quantities', search='_search_virtual_available',
digits='Product Unit of Measure', compute_sudo=False,
help="Forecast quantity (computed as Quantity On Hand "
"- Outgoing + Incoming)\n"
"In a context with a single Stock Location, this includes "
"goods stored in this location, or any of its children.\n"
"In a context with a single Warehouse, this includes "
"goods stored in the Stock Location of this Warehouse, or any "
"of its children.\n"
"Otherwise, this includes goods stored in any Stock Location "
"with 'internal' type.")
free_qty = fields.Float(
'Free To Use Quantity ', compute='_compute_quantities', search='_search_free_qty',
digits='Product Unit of Measure', compute_sudo=False,
help="Forecast quantity (computed as Quantity On Hand "
"- reserved quantity)\n"
"In a context with a single Stock Location, this includes "
"goods stored in this location, or any of its children.\n"
"In a context with a single Warehouse, this includes "
"goods stored in the Stock Location of this Warehouse, or any "
"of its children.\n"
"Otherwise, this includes goods stored in any Stock Location "
"with 'internal' type.")
incoming_qty = fields.Float(
'Incoming', compute='_compute_quantities', search='_search_incoming_qty',
digits='Product Unit of Measure', compute_sudo=False,
help="Quantity of planned incoming products.\n"
"In a context with a single Stock Location, this includes "
"goods arriving to this Location, or any of its children.\n"
"In a context with a single Warehouse, this includes "
"goods arriving to the Stock Location of this Warehouse, or "
"any of its children.\n"
"Otherwise, this includes goods arriving to any Stock "
"Location with 'internal' type.")
outgoing_qty = fields.Float(
'Outgoing', compute='_compute_quantities', search='_search_outgoing_qty',
digits='Product Unit of Measure', compute_sudo=False,
help="Quantity of planned outgoing products.\n"
"In a context with a single Stock Location, this includes "
"goods leaving this Location, or any of its children.\n"
"In a context with a single Warehouse, this includes "
"goods leaving the Stock Location of this Warehouse, or "
"any of its children.\n"
"Otherwise, this includes goods leaving any Stock "
"Location with 'internal' type.")
orderpoint_ids = fields.One2many('stock.warehouse.orderpoint', 'product_id', 'Minimum Stock Rules')
nbr_moves_in = fields.Integer(compute='_compute_nbr_moves', compute_sudo=False, help="Number of incoming stock moves in the past 12 months")
nbr_moves_out = fields.Integer(compute='_compute_nbr_moves', compute_sudo=False, help="Number of outgoing stock moves in the past 12 months")
nbr_reordering_rules = fields.Integer('Reordering Rules',
compute='_compute_nbr_reordering_rules', compute_sudo=False)
reordering_min_qty = fields.Float(
compute='_compute_nbr_reordering_rules', compute_sudo=False)
reordering_max_qty = fields.Float(
compute='_compute_nbr_reordering_rules', compute_sudo=False)
putaway_rule_ids = fields.One2many('stock.putaway.rule', 'product_id', 'Putaway Rules')
storage_category_capacity_ids = fields.One2many('stock.storage.category.capacity', 'product_id', 'Storage Category Capacity')
show_on_hand_qty_status_button = fields.Boolean(compute='_compute_show_qty_status_button')
show_forecasted_qty_status_button = fields.Boolean(compute='_compute_show_qty_status_button')
def _compute_show_qty_status_button(self):
for product in self:
product.show_on_hand_qty_status_button = product.product_tmpl_id.show_on_hand_qty_status_button
product.show_forecasted_qty_status_button = product.product_tmpl_id.show_forecasted_qty_status_button
@api.depends('stock_move_ids.product_qty', 'stock_move_ids.state')
@api.depends_context(
'lot_id', 'owner_id', 'package_id', 'from_date', 'to_date',
'location', 'warehouse',
)
def _compute_quantities(self):
products = self.filtered(lambda p: p.type != 'service')
res = products._compute_quantities_dict(self._context.get('lot_id'), self._context.get('owner_id'), self._context.get('package_id'), self._context.get('from_date'), self._context.get('to_date'))
for product in products:
product.qty_available = res[product.id]['qty_available']
product.incoming_qty = res[product.id]['incoming_qty']
product.outgoing_qty = res[product.id]['outgoing_qty']
product.virtual_available = res[product.id]['virtual_available']
product.free_qty = res[product.id]['free_qty']
# Services need to be set with 0.0 for all quantities
services = self - products
services.qty_available = 0.0
services.incoming_qty = 0.0
services.outgoing_qty = 0.0
services.virtual_available = 0.0
services.free_qty = 0.0
def _compute_quantities_dict(self, lot_id, owner_id, package_id, from_date=False, to_date=False):
domain_quant_loc, domain_move_in_loc, domain_move_out_loc = self._get_domain_locations()
domain_quant = [('product_id', 'in', self.ids)] + domain_quant_loc
dates_in_the_past = False
# only to_date as to_date will correspond to qty_available
to_date = fields.Datetime.to_datetime(to_date)
if to_date and to_date < fields.Datetime.now():
dates_in_the_past = True
domain_move_in = [('product_id', 'in', self.ids)] + domain_move_in_loc
domain_move_out = [('product_id', 'in', self.ids)] + domain_move_out_loc
if lot_id is not None:
domain_quant += [('lot_id', '=', lot_id)]
if owner_id is not None:
domain_quant += [('owner_id', '=', owner_id)]
domain_move_in += [('restrict_partner_id', '=', owner_id)]
domain_move_out += [('restrict_partner_id', '=', owner_id)]
if package_id is not None:
domain_quant += [('package_id', '=', package_id)]
if dates_in_the_past:
domain_move_in_done = list(domain_move_in)
domain_move_out_done = list(domain_move_out)
if from_date:
date_date_expected_domain_from = [('date', '>=', from_date)]
domain_move_in += date_date_expected_domain_from
domain_move_out += date_date_expected_domain_from
if to_date:
date_date_expected_domain_to = [('date', '<=', to_date)]
domain_move_in += date_date_expected_domain_to
domain_move_out += date_date_expected_domain_to
Move = self.env['stock.move'].with_context(active_test=False)
Quant = self.env['stock.quant'].with_context(active_test=False)
domain_move_in_todo = [('state', 'in', ('waiting', 'confirmed', 'assigned', 'partially_available'))] + domain_move_in
domain_move_out_todo = [('state', 'in', ('waiting', 'confirmed', 'assigned', 'partially_available'))] + domain_move_out
moves_in_res = dict((item['product_id'][0], item['product_qty']) for item in Move.read_group(domain_move_in_todo, ['product_id', 'product_qty'], ['product_id'], orderby='id'))
moves_out_res = dict((item['product_id'][0], item['product_qty']) for item in Move.read_group(domain_move_out_todo, ['product_id', 'product_qty'], ['product_id'], orderby='id'))
quants_res = dict((item['product_id'][0], (item['quantity'], item['reserved_quantity'])) for item in Quant.read_group(domain_quant, ['product_id', 'quantity', 'reserved_quantity'], ['product_id'], orderby='id'))
if dates_in_the_past:
# Calculate the moves that were done before now to calculate back in time (as most questions will be recent ones)
domain_move_in_done = [('state', '=', 'done'), ('date', '>', to_date)] + domain_move_in_done
domain_move_out_done = [('state', '=', 'done'), ('date', '>', to_date)] + domain_move_out_done
moves_in_res_past = dict((item['product_id'][0], item['product_qty']) for item in Move.read_group(domain_move_in_done, ['product_id', 'product_qty'], ['product_id'], orderby='id'))
moves_out_res_past = dict((item['product_id'][0], item['product_qty']) for item in Move.read_group(domain_move_out_done, ['product_id', 'product_qty'], ['product_id'], orderby='id'))
res = dict()
for product in self.with_context(prefetch_fields=False):
origin_product_id = product._origin.id
product_id = product.id
if not origin_product_id:
res[product_id] = dict.fromkeys(
['qty_available', 'free_qty', 'incoming_qty', 'outgoing_qty', 'virtual_available'],
0.0,
)
continue
rounding = product.uom_id.rounding
res[product_id] = {}
if dates_in_the_past:
qty_available = quants_res.get(origin_product_id, [0.0])[0] - moves_in_res_past.get(origin_product_id, 0.0) + moves_out_res_past.get(origin_product_id, 0.0)
else:
qty_available = quants_res.get(origin_product_id, [0.0])[0]
reserved_quantity = quants_res.get(origin_product_id, [False, 0.0])[1]
res[product_id]['qty_available'] = float_round(qty_available, precision_rounding=rounding)
res[product_id]['free_qty'] = float_round(qty_available - reserved_quantity, precision_rounding=rounding)
res[product_id]['incoming_qty'] = float_round(moves_in_res.get(origin_product_id, 0.0), precision_rounding=rounding)
res[product_id]['outgoing_qty'] = float_round(moves_out_res.get(origin_product_id, 0.0), precision_rounding=rounding)
res[product_id]['virtual_available'] = float_round(
qty_available + res[product_id]['incoming_qty'] - res[product_id]['outgoing_qty'],
precision_rounding=rounding)
return res
def _compute_nbr_moves(self):
res = defaultdict(dict)
incoming_moves = self.env['stock.move.line'].read_group([
('product_id', 'in', self.ids),
('state', '=', 'done'),
('picking_code', '=', 'incoming'),
('date', '>=', fields.Datetime.now() - relativedelta(years=1))
], ['product_id'], ['product_id'])
outgoing_moves = self.env['stock.move.line'].read_group([
('product_id', 'in', self.ids),
('state', '=', 'done'),
('picking_code', '=', 'outgoing'),
('date', '>=', fields.Datetime.now() - relativedelta(years=1))
], ['product_id'], ['product_id'])
for move in incoming_moves:
res[move['product_id'][0]]['moves_in'] = int(move['product_id_count'])
for move in outgoing_moves:
res[move['product_id'][0]]['moves_out'] = int(move['product_id_count'])
for product in self:
product_res = res.get(product.id) or {}
product.nbr_moves_in = product_res.get('moves_in', 0)
product.nbr_moves_out = product_res.get('moves_out', 0)
def get_components(self):
self.ensure_one()
return self.ids
def _get_description(self, picking_type_id):
""" return product receipt/delivery/picking description depending on
picking type passed as argument.
"""
self.ensure_one()
picking_code = picking_type_id.code
description = html2plaintext(self.description) if not is_html_empty(self.description) else self.name
if picking_code == 'incoming':
return self.description_pickingin or description
if picking_code == 'outgoing':
return self.description_pickingout or self.name
if picking_code == 'internal':
return self.description_picking or description
return description
def _get_domain_locations(self):
'''
Parses the context and returns a list of location_ids based on it.
It will return all stock locations when no parameters are given
Possible parameters are shop, warehouse, location, compute_child
'''
Warehouse = self.env['stock.warehouse']
def _search_ids(model, values):
ids = set()
domain = []
for item in values:
if isinstance(item, int):
ids.add(item)
else:
domain = expression.OR([[(self.env[model]._rec_name, 'ilike', item)], domain])
if domain:
ids |= set(self.env[model].search(domain).ids)
return ids
# We may receive a location or warehouse from the context, either by explicit
# python code or by the use of dummy fields in the search view.
# Normalize them into a list.
location = self.env.context.get('location')
if location and not isinstance(location, list):
location = [location]
warehouse = self.env.context.get('warehouse')
if warehouse and not isinstance(warehouse, list):
warehouse = [warehouse]
# filter by location and/or warehouse
if warehouse:
w_ids = set(Warehouse.browse(_search_ids('stock.warehouse', warehouse)).mapped('view_location_id').ids)
if location:
l_ids = _search_ids('stock.location', location)
location_ids = w_ids & l_ids
else:
location_ids = w_ids
else:
if location:
location_ids = _search_ids('stock.location', location)
else:
location_ids = set(Warehouse.search([]).mapped('view_location_id').ids)
return self._get_domain_locations_new(location_ids, compute_child=self.env.context.get('compute_child', True))
def _get_domain_locations_new(self, location_ids, company_id=False, compute_child=True):
operator = compute_child and 'child_of' or 'in'
domain = company_id and ['&', ('company_id', '=', company_id)] or []
locations = self.env['stock.location'].browse(location_ids)
# TDE FIXME: should move the support of child_of + auto_join directly in expression
hierarchical_locations = locations if operator == 'child_of' else locations.browse()
other_locations = locations - hierarchical_locations
loc_domain = []
dest_loc_domain = []
# this optimizes [('location_id', 'child_of', hierarchical_locations.ids)]
# by avoiding the ORM to search for children locations and injecting a
# lot of location ids into the main query
for location in hierarchical_locations:
loc_domain = loc_domain and ['|'] + loc_domain or loc_domain
loc_domain.append(('location_id.parent_path', '=like', location.parent_path + '%'))
dest_loc_domain = dest_loc_domain and ['|'] + dest_loc_domain or dest_loc_domain
dest_loc_domain.append(('location_dest_id.parent_path', '=like', location.parent_path + '%'))
if other_locations:
loc_domain = loc_domain and ['|'] + loc_domain or loc_domain
loc_domain = loc_domain + [('location_id', operator, other_locations.ids)]
dest_loc_domain = dest_loc_domain and ['|'] + dest_loc_domain or dest_loc_domain
dest_loc_domain = dest_loc_domain + [('location_dest_id', operator, other_locations.ids)]
return (
domain + loc_domain,
domain + dest_loc_domain + ['!'] + loc_domain if loc_domain else domain + dest_loc_domain,
domain + loc_domain + ['!'] + dest_loc_domain if dest_loc_domain else domain + loc_domain
)
def _search_qty_available(self, operator, value):
# In the very specific case we want to retrieve products with stock available, we only need
# to use the quants, not the stock moves. Therefore, we bypass the usual
# '_search_product_quantity' method and call '_search_qty_available_new' instead. This
# allows better performances.
if not ({'from_date', 'to_date'} & set(self.env.context.keys())):
product_ids = self._search_qty_available_new(
operator, value, self.env.context.get('lot_id'), self.env.context.get('owner_id'),
self.env.context.get('package_id')
)
return [('id', 'in', product_ids)]
return self._search_product_quantity(operator, value, 'qty_available')
def _search_virtual_available(self, operator, value):
# TDE FIXME: should probably clean the search methods
return self._search_product_quantity(operator, value, 'virtual_available')
def _search_incoming_qty(self, operator, value):
# TDE FIXME: should probably clean the search methods
return self._search_product_quantity(operator, value, 'incoming_qty')
def _search_outgoing_qty(self, operator, value):
# TDE FIXME: should probably clean the search methods
return self._search_product_quantity(operator, value, 'outgoing_qty')
def _search_free_qty(self, operator, value):
return self._search_product_quantity(operator, value, 'free_qty')
def _search_product_quantity(self, operator, value, field):
# TDE FIXME: should probably clean the search methods
# to prevent sql injections
if field not in ('qty_available', 'virtual_available', 'incoming_qty', 'outgoing_qty', 'free_qty'):
raise UserError(_('Invalid domain left operand %s', field))
if operator not in ('<', '>', '=', '!=', '<=', '>='):
raise UserError(_('Invalid domain operator %s', operator))
if not isinstance(value, (float, int)):
raise UserError(_('Invalid domain right operand %s', value))
# TODO: Still optimization possible when searching virtual quantities
ids = []
# Order the search on `id` to prevent the default order on the product name which slows
# down the search because of the join on the translation table to get the translated names.
for product in self.with_context(prefetch_fields=False).search([], order='id'):
if OPERATORS[operator](product[field], value):
ids.append(product.id)
return [('id', 'in', ids)]
def _search_qty_available_new(self, operator, value, lot_id=False, owner_id=False, package_id=False):
''' Optimized method which doesn't search on stock.moves, only on stock.quants. '''
product_ids = set()
domain_quant = self._get_domain_locations()[0]
if lot_id:
domain_quant.append(('lot_id', '=', lot_id))
if owner_id:
domain_quant.append(('owner_id', '=', owner_id))
if package_id:
domain_quant.append(('package_id', '=', package_id))
quants_groupby = self.env['stock.quant'].read_group(domain_quant, ['product_id', 'quantity'], ['product_id'], orderby='id')
# check if we need include zero values in result
include_zero = (
value < 0.0 and operator in ('>', '>=') or
value > 0.0 and operator in ('<', '<=') or
value == 0.0 and operator in ('>=', '<=', '=')
)
processed_product_ids = set()
for quant in quants_groupby:
product_id = quant['product_id'][0]
if include_zero:
processed_product_ids.add(product_id)
if OPERATORS[operator](quant['quantity'], value):
product_ids.add(product_id)
if include_zero:
products_without_quants_in_domain = self.env['product.product'].search([
('type', '=', 'product'),
('id', 'not in', list(processed_product_ids))],
order='id'
)
product_ids |= set(products_without_quants_in_domain.ids)
return list(product_ids)
def _compute_nbr_reordering_rules(self):
read_group_res = self.env['stock.warehouse.orderpoint'].read_group(
[('product_id', 'in', self.ids)],
['product_id', 'product_min_qty', 'product_max_qty'],
['product_id'])
res = {i: {} for i in self.ids}
for data in read_group_res:
res[data['product_id'][0]]['nbr_reordering_rules'] = int(data['product_id_count'])
res[data['product_id'][0]]['reordering_min_qty'] = data['product_min_qty']
res[data['product_id'][0]]['reordering_max_qty'] = data['product_max_qty']
for product in self:
product_res = res.get(product.id) or {}
product.nbr_reordering_rules = product_res.get('nbr_reordering_rules', 0)
product.reordering_min_qty = product_res.get('reordering_min_qty', 0)
product.reordering_max_qty = product_res.get('reordering_max_qty', 0)
@api.onchange('tracking')
def onchange_tracking(self):
if any(product.tracking != 'none' and product.qty_available > 0 for product in self):
return {
'warning': {
'title': _('Warning!'),
'message': _("You have product(s) in stock that have no lot/serial number. You can assign lot/serial numbers by doing an inventory adjustment.")}}
@api.model
def view_header_get(self, view_id, view_type):
res = super(Product, self).view_header_get(view_id, view_type)
if not res and self._context.get('active_id') and self._context.get('active_model') == 'stock.location':
return _(
'Products: %(location)s',
location=self.env['stock.location'].browse(self._context['active_id']).name,
)
return res
@api.model
def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
res = super(Product, self).fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu)
if self._context.get('location') and isinstance(self._context['location'], int):
location = self.env['stock.location'].browse(self._context['location'])
fields = res.get('fields')
if fields:
if location.usage == 'supplier':
if fields.get('virtual_available'):
res['fields']['virtual_available']['string'] = _('Future Receipts')
if fields.get('qty_available'):
res['fields']['qty_available']['string'] = _('Received Qty')
elif location.usage == 'internal':
if fields.get('virtual_available'):
res['fields']['virtual_available']['string'] = _('Forecasted Quantity')
elif location.usage == 'customer':
if fields.get('virtual_available'):
res['fields']['virtual_available']['string'] = _('Future Deliveries')
if fields.get('qty_available'):
res['fields']['qty_available']['string'] = _('Delivered Qty')
elif location.usage == 'inventory':
if fields.get('virtual_available'):
res['fields']['virtual_available']['string'] = _('Future P&L')
if fields.get('qty_available'):
res['fields']['qty_available']['string'] = _('P&L Qty')
elif location.usage == 'production':
if fields.get('virtual_available'):
res['fields']['virtual_available']['string'] = _('Future Productions')
if fields.get('qty_available'):
res['fields']['qty_available']['string'] = _('Produced Qty')
return res
def action_view_orderpoints(self):
action = self.env["ir.actions.actions"]._for_xml_id("stock.action_orderpoint")
action['context'] = literal_eval(action.get('context'))
action['context'].pop('search_default_trigger', False)
action['context'].update({
'search_default_filter_not_snoozed': True,
})
if self and len(self) == 1:
action['context'].update({
'default_product_id': self.ids[0],
'search_default_product_id': self.ids[0]
})
else:
action['domain'] = expression.AND([action.get('domain', []), [('product_id', 'in', self.ids)]])
return action
def action_view_routes(self):
return self.mapped('product_tmpl_id').action_view_routes()
def action_view_stock_move_lines(self):
self.ensure_one()
action = self.env["ir.actions.actions"]._for_xml_id("stock.stock_move_line_action")
action['domain'] = [('product_id', '=', self.id)]
return action
def action_view_related_putaway_rules(self):
self.ensure_one()
domain = [
'|',
('product_id', '=', self.id),
('category_id', '=', self.product_tmpl_id.categ_id.id),
]
return self.env['product.template']._get_action_view_related_putaway_rules(domain)
def action_view_storage_category_capacity(self):
action = self.env["ir.actions.actions"]._for_xml_id("stock.action_storage_category_capacity")
action['context'] = {
'hide_package_type': True,
}
if len(self) == 1:
action['context'].update({
'default_product_id': self.id,
})
action['domain'] = [('product_id', 'in', self.ids)]
return action
def action_open_product_lot(self):
self.ensure_one()
action = self.env["ir.actions.actions"]._for_xml_id("stock.action_production_lot_form")
action['domain'] = [('product_id', '=', self.id)]
action['context'] = {
'default_product_id': self.id,
'set_product_readonly': True,
'default_company_id': (self.company_id or self.env.company).id,
}
return action
# Be aware that the exact same function exists in product.template
def action_open_quants(self):
domain = [('product_id', 'in', self.ids)]
hide_location = not self.user_has_groups('stock.group_stock_multi_locations')
hide_lot = all(product.tracking == 'none' for product in self)
self = self.with_context(
hide_location=hide_location, hide_lot=hide_lot,
no_at_date=True, search_default_on_hand=True,
)
# If user have rights to write on quant, we define the view as editable.
if self.user_has_groups('stock.group_stock_manager'):
self = self.with_context(inventory_mode=True)
# Set default location id if multilocations is inactive
if not self.user_has_groups('stock.group_stock_multi_locations'):
user_company = self.env.company
warehouse = self.env['stock.warehouse'].search(
[('company_id', '=', user_company.id)], limit=1
)
if warehouse:
self = self.with_context(default_location_id=warehouse.lot_stock_id.id)
# Set default product id if quants concern only one product
if len(self) == 1:
self = self.with_context(
default_product_id=self.id,
single_product=True
)
else:
self = self.with_context(product_tmpl_ids=self.product_tmpl_id.ids)
action = self.env['stock.quant'].action_view_inventory()
action['domain'] = domain
action["name"] = _('Update Quantity')
return action
def action_update_quantity_on_hand(self):
return self.product_tmpl_id.with_context(default_product_id=self.id, create=True).action_update_quantity_on_hand()
def action_product_forecast_report(self):
self.ensure_one()
action = self.env["ir.actions.actions"]._for_xml_id("stock.stock_replenishment_product_product_action")
return action
@api.model
def get_theoretical_quantity(self, product_id, location_id, lot_id=None, package_id=None, owner_id=None, to_uom=None):
product_id = self.env['product.product'].browse(product_id)
product_id.check_access_rights('read')
product_id.check_access_rule('read')
location_id = self.env['stock.location'].browse(location_id)
lot_id = self.env['stock.production.lot'].browse(lot_id)
package_id = self.env['stock.quant.package'].browse(package_id)
owner_id = self.env['res.partner'].browse(owner_id)
to_uom = self.env['uom.uom'].browse(to_uom)
quants = self.env['stock.quant']._gather(product_id, location_id, lot_id=lot_id, package_id=package_id, owner_id=owner_id, strict=True)
if lot_id:
quants = quants.filtered(lambda q: q.lot_id == lot_id)
theoretical_quantity = sum([quant.quantity for quant in quants])
if to_uom and product_id.uom_id != to_uom:
theoretical_quantity = product_id.uom_id._compute_quantity(theoretical_quantity, to_uom)
return theoretical_quantity
def write(self, values):
if 'active' in values:
self.filtered(lambda p: p.active != values['active']).with_context(active_test=False).orderpoint_ids.write({
'active': values['active']
})
return super().write(values)
def _get_quantity_in_progress(self, location_ids=False, warehouse_ids=False):
return defaultdict(float), defaultdict(float)
def _get_rules_from_location(self, location, route_ids=False, seen_rules=False):
if not seen_rules:
seen_rules = self.env['stock.rule']
rule = self.env['procurement.group']._get_rule(self, location, {
'route_ids': route_ids,
'warehouse_id': location.warehouse_id
})
if rule in seen_rules:
raise UserError(_("Invalid rule's configuration, the following rule causes an endless loop: %s", rule.display_name))
if not rule:
return seen_rules
if rule.procure_method == 'make_to_stock' or rule.action not in ('pull_push', 'pull'):
return seen_rules | rule
else:
return self._get_rules_from_location(rule.location_src_id, seen_rules=seen_rules | rule)
def _get_only_qty_available(self):
""" Get only quantities available, it is equivalent to read qty_available
but avoid fetching other qty fields (avoid costly read group on moves)
:rtype: defaultdict(float)
"""
domain_quant = expression.AND([self._get_domain_locations()[0], [('product_id', 'in', self.ids)]])
quants_groupby = self.env['stock.quant'].read_group(domain_quant, ['product_id', 'quantity'], ['product_id'], orderby='id')
currents = defaultdict(float)
for c in quants_groupby:
currents[c['product_id'][0]] = c['quantity']
return currents
def _filter_to_unlink(self):
domain = [('product_id', 'in', self.ids)]
lines = self.env['stock.production.lot'].read_group(domain, ['product_id'], ['product_id'])
linked_product_ids = [group['product_id'][0] for group in lines]
return super(Product, self - self.browse(linked_product_ids))._filter_to_unlink()
@api.model
def _count_returned_sn_products(self, sn_lot):
return 0
class ProductTemplate(models.Model):
_inherit = 'product.template'
_check_company_auto = True
responsible_id = fields.Many2one(
'res.users', string='Responsible', default=lambda self: self.env.uid, company_dependent=True, check_company=True,
help="This user will be responsible of the next activities related to logistic operations for this product.")
detailed_type = fields.Selection(selection_add=[
('product', 'Storable Product')
], tracking=True, ondelete={'product': 'set consu'})
type = fields.Selection(selection_add=[
('product', 'Storable Product')
], ondelete={'product': 'set consu'})
property_stock_production = fields.Many2one(
'stock.location', "Production Location",
company_dependent=True, check_company=True, domain="[('usage', '=', 'production'), '|', ('company_id', '=', False), ('company_id', '=', allowed_company_ids[0])]",
help="This stock location will be used, instead of the default one, as the source location for stock moves generated by manufacturing orders.")
property_stock_inventory = fields.Many2one(
'stock.location', "Inventory Location",
company_dependent=True, check_company=True, domain="[('usage', '=', 'inventory'), '|', ('company_id', '=', False), ('company_id', '=', allowed_company_ids[0])]",
help="This stock location will be used, instead of the default one, as the source location for stock moves generated when you do an inventory.")
sale_delay = fields.Float(
'Customer Lead Time', default=0,
help="Delivery lead time, in days. It's the number of days, promised to the customer, between the confirmation of the sales order and the delivery.")
tracking = fields.Selection([
('serial', 'By Unique Serial Number'),
('lot', 'By Lots'),
('none', 'No Tracking')], string="Tracking", help="Ensure the traceability of a storable product in your warehouse.", default='none', required=True)
description_picking = fields.Text('Description on Picking', translate=True)
description_pickingout = fields.Text('Description on Delivery Orders', translate=True)
description_pickingin = fields.Text('Description on Receptions', translate=True)
qty_available = fields.Float(
'Quantity On Hand', compute='_compute_quantities', search='_search_qty_available',
compute_sudo=False, digits='Product Unit of Measure')
virtual_available = fields.Float(
'Forecasted Quantity', compute='_compute_quantities', search='_search_virtual_available',
compute_sudo=False, digits='Product Unit of Measure')
incoming_qty = fields.Float(
'Incoming', compute='_compute_quantities', search='_search_incoming_qty',
compute_sudo=False, digits='Product Unit of Measure')
outgoing_qty = fields.Float(
'Outgoing', compute='_compute_quantities', search='_search_outgoing_qty',
compute_sudo=False, digits='Product Unit of Measure')
# The goal of these fields is to be able to put some keys in context from search view in order
# to influence computed field.
location_id = fields.Many2one('stock.location', 'Location', store=False)
warehouse_id = fields.Many2one('stock.warehouse', 'Warehouse', store=False)
has_available_route_ids = fields.Boolean(
'Routes can be selected on this product', compute='_compute_has_available_route_ids',
default=lambda self: self.env['stock.location.route'].search_count([('product_selectable', '=', True)]))
route_ids = fields.Many2many(
'stock.location.route', 'stock_route_product', 'product_id', 'route_id', 'Routes',
domain=[('product_selectable', '=', True)],
help="Depending on the modules installed, this will allow you to define the route of the product: whether it will be bought, manufactured, replenished on order, etc.")
nbr_moves_in = fields.Integer(compute='_compute_nbr_moves', compute_sudo=False, help="Number of incoming stock moves in the past 12 months")
nbr_moves_out = fields.Integer(compute='_compute_nbr_moves', compute_sudo=False, help="Number of outgoing stock moves in the past 12 months")
nbr_reordering_rules = fields.Integer('Reordering Rules',
compute='_compute_nbr_reordering_rules', compute_sudo=False)
reordering_min_qty = fields.Float(
compute='_compute_nbr_reordering_rules', compute_sudo=False)
reordering_max_qty = fields.Float(
compute='_compute_nbr_reordering_rules', compute_sudo=False)
# TDE FIXME: seems only visible in a view - remove me ?
route_from_categ_ids = fields.Many2many(
relation="stock.location.route", string="Category Routes",
related='categ_id.total_route_ids', related_sudo=False)
show_on_hand_qty_status_button = fields.Boolean(compute='_compute_show_qty_status_button')
show_forecasted_qty_status_button = fields.Boolean(compute='_compute_show_qty_status_button')
def _compute_show_qty_status_button(self):
for template in self:
template.show_on_hand_qty_status_button = template.type == 'product'
template.show_forecasted_qty_status_button = template.type == 'product'
@api.depends('type')
def _compute_has_available_route_ids(self):
self.has_available_route_ids = self.env['stock.location.route'].search_count([('product_selectable', '=', True)])
@api.depends(
'product_variant_ids.qty_available',
'product_variant_ids.virtual_available',
'product_variant_ids.incoming_qty',
'product_variant_ids.outgoing_qty',
)
def _compute_quantities(self):
res = self._compute_quantities_dict()
for template in self:
template.qty_available = res[template.id]['qty_available']
template.virtual_available = res[template.id]['virtual_available']
template.incoming_qty = res[template.id]['incoming_qty']
template.outgoing_qty = res[template.id]['outgoing_qty']
def _compute_quantities_dict(self):
variants_available = {
p['id']: p for p in self.product_variant_ids._origin.read(['qty_available', 'virtual_available', 'incoming_qty', 'outgoing_qty'])
}
prod_available = {}
for template in self:
qty_available = 0
virtual_available = 0
incoming_qty = 0
outgoing_qty = 0
for p in template.product_variant_ids._origin:
qty_available += variants_available[p.id]["qty_available"]
virtual_available += variants_available[p.id]["virtual_available"]
incoming_qty += variants_available[p.id]["incoming_qty"]
outgoing_qty += variants_available[p.id]["outgoing_qty"]
prod_available[template.id] = {
"qty_available": qty_available,
"virtual_available": virtual_available,
"incoming_qty": incoming_qty,
"outgoing_qty": outgoing_qty,
}
return prod_available
def _compute_nbr_moves(self):
res = defaultdict(lambda: {'moves_in': 0, 'moves_out': 0})
incoming_moves = self.env['stock.move.line'].read_group([
('product_id.product_tmpl_id', 'in', self.ids),
('state', '=', 'done'),
('picking_code', '=', 'incoming'),
('date', '>=', fields.Datetime.now() - relativedelta(years=1))
], ['product_id'], ['product_id'])
outgoing_moves = self.env['stock.move.line'].read_group([
('product_id.product_tmpl_id', 'in', self.ids),
('state', '=', 'done'),
('picking_code', '=', 'outgoing'),
('date', '>=', fields.Datetime.now() - relativedelta(years=1))
], ['product_id'], ['product_id'])
for move in incoming_moves:
product = self.env['product.product'].browse([move['product_id'][0]])
product_tmpl_id = product.product_tmpl_id.id
res[product_tmpl_id]['moves_in'] += int(move['product_id_count'])
for move in outgoing_moves:
product = self.env['product.product'].browse([move['product_id'][0]])
product_tmpl_id = product.product_tmpl_id.id
res[product_tmpl_id]['moves_out'] += int(move['product_id_count'])
for template in self:
template.nbr_moves_in = int(res[template.id]['moves_in'])
template.nbr_moves_out = int(res[template.id]['moves_out'])
@api.model
def _get_action_view_related_putaway_rules(self, domain):
return {
'name': _('Putaway Rules'),
'type': 'ir.actions.act_window',
'res_model': 'stock.putaway.rule',
'view_mode': 'list',
'domain': domain,
}
def _search_qty_available(self, operator, value):
domain = [('qty_available', operator, value)]
product_variant_query = self.env['product.product']._search(domain)
return [('product_variant_ids', 'in', product_variant_query)]
def _search_virtual_available(self, operator, value):
domain = [('virtual_available', operator, value)]
product_variant_query = self.env['product.product']._search(domain)
return [('product_variant_ids', 'in', product_variant_query)]
def _search_incoming_qty(self, operator, value):
domain = [('incoming_qty', operator, value)]
product_variant_query = self.env['product.product']._search(domain)
return [('product_variant_ids', 'in', product_variant_query)]
def _search_outgoing_qty(self, operator, value):
domain = [('outgoing_qty', operator, value)]
product_variant_query = self.env['product.product']._search(domain)
return [('product_variant_ids', 'in', product_variant_query)]
def _compute_nbr_reordering_rules(self):
res = {k: {'nbr_reordering_rules': 0, 'reordering_min_qty': 0, 'reordering_max_qty': 0} for k in self.ids}
product_data = self.env['stock.warehouse.orderpoint'].read_group([('product_id.product_tmpl_id', 'in', self.ids)], ['product_id', 'product_min_qty', 'product_max_qty'], ['product_id'])
for data in product_data:
product = self.env['product.product'].browse([data['product_id'][0]])
product_tmpl_id = product.product_tmpl_id.id
res[product_tmpl_id]['nbr_reordering_rules'] += int(data['product_id_count'])
res[product_tmpl_id]['reordering_min_qty'] = data['product_min_qty']
res[product_tmpl_id]['reordering_max_qty'] = data['product_max_qty']
for template in self:
if not template.id:
template.nbr_reordering_rules = 0
template.reordering_min_qty = 0
template.reordering_max_qty = 0
continue
template.nbr_reordering_rules = res[template.id]['nbr_reordering_rules']
template.reordering_min_qty = res[template.id]['reordering_min_qty']
template.reordering_max_qty = res[template.id]['reordering_max_qty']
def _compute_product_tooltip(self):
super()._compute_product_tooltip()
for record in self:
if record.type == 'product':
record.product_tooltip += _(
"Storable products are physical items for which you manage the inventory level."
)
@api.onchange('tracking')
def onchange_tracking(self):
return self.mapped('product_variant_ids').onchange_tracking()
@api.onchange('type')
def _onchange_type(self):
res = super(ProductTemplate, self)._onchange_type() or {}
if self.type == 'consu' and self.tracking != 'none':
self.tracking = 'none'
# Return a warning when trying to change the product type
if self.ids and self.product_variant_ids.ids and self.env['stock.move.line'].sudo().search_count([
('product_id', 'in', self.product_variant_ids.ids), ('state', '!=', 'cancel')
]):
res['warning'] = {
'title': _('Warning!'),
'message': _(
'This product has been used in at least one inventory movement. '
'It is not advised to change the Product Type since it can lead to inconsistencies. '
'A better solution could be to archive the product and create a new one instead.'
)
}
return res
def write(self, vals):
self._sanitize_vals(vals)
if 'company_id' in vals and vals['company_id']:
products_changing_company = self.filtered(lambda product: product.company_id.id != vals['company_id'])
if products_changing_company:
move = self.env['stock.move'].sudo().search([
('product_id', 'in', products_changing_company.product_variant_ids.ids),
('company_id', 'not in', [vals['company_id'], False]),
], order=None, limit=1)
if move:
raise UserError(_("This product's company cannot be changed as long as there are stock moves of it belonging to another company."))
# Forbid changing a product's company when quant(s) exist in another company.
quant = self.env['stock.quant'].sudo().search([
('product_id', 'in', products_changing_company.product_variant_ids.ids),
('company_id', 'not in', [vals['company_id'], False]),
('quantity', '!=', 0),
], order=None, limit=1)
if quant:
raise UserError(_("This product's company cannot be changed as long as there are quantities of it belonging to another company."))
if 'uom_id' in vals:
new_uom = self.env['uom.uom'].browse(vals['uom_id'])
updated = self.filtered(lambda template: template.uom_id != new_uom)
done_moves = self.env['stock.move'].search([('product_id', 'in', updated.with_context(active_test=False).mapped('product_variant_ids').ids)], limit=1)
if done_moves:
raise UserError(_("You cannot change the unit of measure as there are already stock moves for this product. If you want to change the unit of measure, you should rather archive this product and create a new one."))
if 'type' in vals and vals['type'] != 'product' and sum(self.mapped('nbr_reordering_rules')) != 0:
raise UserError(_('You still have some active reordering rules on this product. Please archive or delete them first.'))
if any('type' in vals and vals['type'] != prod_tmpl.type for prod_tmpl in self):
existing_done_move_lines = self.env['stock.move.line'].sudo().search([
('product_id', 'in', self.mapped('product_variant_ids').ids),
('state', '=', 'done'),
], limit=1)
if existing_done_move_lines:
raise UserError(_("You can not change the type of a product that was already used."))
existing_reserved_move_lines = self.env['stock.move.line'].search([
('product_id', 'in', self.mapped('product_variant_ids').ids),
('state', 'in', ['partially_available', 'assigned']),
])
if existing_reserved_move_lines:
raise UserError(_("You can not change the type of a product that is currently reserved on a stock move. If you need to change the type, you should first unreserve the stock move."))
if 'type' in vals and vals['type'] != 'product' and any(p.type == 'product' and not float_is_zero(p.qty_available, precision_rounding=p.uom_id.rounding) for p in self):
raise UserError(_("Available quantity should be set to zero before changing type"))
return super(ProductTemplate, self).write(vals)
def copy(self, default=None):
res = super().copy(default=default)
# Since we don't copy product variants directly, we need to match the newly
# created product variants with the old one, and copy the storage category
# capacity from them.
new_product_dict = {}
for product in res.product_variant_ids:
product_attribute_value = product.product_template_attribute_value_ids.product_attribute_value_id
new_product_dict[product_attribute_value] = product.id
storage_category_capacity_vals = []
for storage_category_capacity in self.product_variant_ids.storage_category_capacity_ids:
product_attribute_value = storage_category_capacity.product_id.product_template_attribute_value_ids.product_attribute_value_id
storage_category_capacity_vals.append(storage_category_capacity.copy_data({'product_id': new_product_dict[product_attribute_value]})[0])
self.env['stock.storage.category.capacity'].create(storage_category_capacity_vals)
return res
# Be aware that the exact same function exists in product.product
def action_open_quants(self):
return self.product_variant_ids.filtered(lambda p: p.active or p.qty_available != 0).action_open_quants()
def action_update_quantity_on_hand(self):
advanced_option_groups = [
'stock.group_stock_multi_locations',
'stock.group_production_lot',
'stock.group_tracking_owner',
'product.group_tracking_lot'
]
if (self.env.user.user_has_groups(','.join(advanced_option_groups))):
return self.action_open_quants()
else:
default_product_id = self.env.context.get('default_product_id', len(self.product_variant_ids) == 1 and self.product_variant_id.id)
action = self.env["ir.actions.actions"]._for_xml_id("stock.action_change_product_quantity")
action['context'] = dict(
self.env.context,
default_product_id=default_product_id,
default_product_tmpl_id=self.id
)
return action
def action_view_related_putaway_rules(self):
self.ensure_one()
domain = [
'|',
('product_id.product_tmpl_id', '=', self.id),
('category_id', '=', self.categ_id.id),
]
return self._get_action_view_related_putaway_rules(domain)
def action_view_storage_category_capacity(self):
self.ensure_one()
return self.product_variant_ids.action_view_storage_category_capacity()
def action_view_orderpoints(self):
return self.product_variant_ids.action_view_orderpoints()
def action_view_stock_move_lines(self):
self.ensure_one()
action = self.env["ir.actions.actions"]._for_xml_id("stock.stock_move_line_action")
action['domain'] = [('product_id.product_tmpl_id', 'in', self.ids)]
return action
def action_open_product_lot(self):
self.ensure_one()
action = self.env["ir.actions.actions"]._for_xml_id("stock.action_production_lot_form")
action['domain'] = [('product_id.product_tmpl_id', '=', self.id)]
action['context'] = {
'default_product_tmpl_id': self.id,
'default_company_id': (self.company_id or self.env.company).id,
}
if self.product_variant_count == 1:
action['context'].update({
'default_product_id': self.product_variant_id.id,
})
return action
def action_open_routes_diagram(self):
products = False
if self.env.context.get('default_product_id'):
products = self.env['product.product'].browse(self.env.context['default_product_id'])
if not products and self.env.context.get('default_product_tmpl_id'):
products = self.env['product.template'].browse(self.env.context['default_product_tmpl_id']).product_variant_ids
if not self.user_has_groups('stock.group_stock_multi_warehouses') and len(products) == 1:
company = products.company_id or self.env.company
warehouse = self.env['stock.warehouse'].search([('company_id', '=', company.id)], limit=1)
return self.env.ref('stock.action_report_stock_rule').report_action(None, data={
'product_id': products.id,
'warehouse_ids': warehouse.ids,
}, config=False)
action = self.env["ir.actions.actions"]._for_xml_id("stock.action_stock_rules_report")
action['context'] = self.env.context
return action
def action_product_tmpl_forecast_report(self):
self.ensure_one()
action = self.env["ir.actions.actions"]._for_xml_id('stock.stock_replenishment_product_product_action')
return action
class ProductCategory(models.Model):
_inherit = 'product.category'
route_ids = fields.Many2many(
'stock.location.route', 'stock_location_route_categ', 'categ_id', 'route_id', 'Routes',
domain=[('product_categ_selectable', '=', True)])
removal_strategy_id = fields.Many2one(
'product.removal', 'Force Removal Strategy',
help="Set a specific removal strategy that will be used regardless of the source location for this product category.\n\n"
"FIFO: products/lots that were stocked first will be moved out first.\n"
"LIFO: products/lots that were stocked last will be moved out first.\n"
"Closet location: products/lots closest to the target location will be moved out first.\n"
"FEFO: products/lots with the closest removal date will be moved out first "
"(the availability of this method depends on the \"Expiration Dates\" setting)."
)
total_route_ids = fields.Many2many(
'stock.location.route', string='Total routes', compute='_compute_total_route_ids',
readonly=True)
putaway_rule_ids = fields.One2many('stock.putaway.rule', 'category_id', 'Putaway Rules')
packaging_reserve_method = fields.Selection([
('full', 'Reserve Only Full Packagings'),
('partial', 'Reserve Partial Packagings'),], string="Reserve Packagings", default='partial',
help="Reserve Only Full Packagings: will not reserve partial packagings. If customer orders 2 pallets of 1000 units each and you only have 1600 in stock, then only 1000 will be reserved\n"
"Reserve Partial Packagings: allow reserving partial packagings. If customer orders 2 pallets of 1000 units each and you only have 1600 in stock, then 1600 will be reserved")
def _compute_total_route_ids(self):
for category in self:
base_cat = category
routes = category.route_ids
while base_cat.parent_id:
base_cat = base_cat.parent_id
routes |= base_cat.route_ids
category.total_route_ids = routes
class ProductPackaging(models.Model):
_inherit = "product.packaging"
package_type_id = fields.Many2one('stock.package.type', 'Package Type')
route_ids = fields.Many2many(
'stock.location.route', 'stock_location_route_packaging', 'packaging_id', 'route_id', 'Routes',
domain=[('packaging_selectable', '=', True)],
help="Depending on the modules installed, this will allow you to define the route of the product in this packaging: whether it will be bought, manufactured, replenished on order, etc.")
class UoM(models.Model):
_inherit = 'uom.uom'
def write(self, values):
# Users can not update the factor if open stock moves are based on it
if 'factor' in values or 'factor_inv' in values or 'category_id' in values:
changed = self.filtered(
lambda u: any(u[f] != values[f] if f in values else False
for f in {'factor', 'factor_inv'})) + self.filtered(
lambda u: any(u[f].id != int(values[f]) if f in values else False
for f in {'category_id'}))
if changed:
error_msg = _(
"You cannot change the ratio of this unit of measure"
" as some products with this UoM have already been moved"
" or are currently reserved."
)
if self.env['stock.move'].sudo().search_count([
('product_uom', 'in', changed.ids),
('state', 'not in', ('cancel', 'done'))
]):
raise UserError(error_msg)
if self.env['stock.move.line'].sudo().search_count([
('product_uom_id', 'in', changed.ids),
('state', 'not in', ('cancel', 'done')),
]):
raise UserError(error_msg)
if self.env['stock.quant'].sudo().search_count([
('product_id.product_tmpl_id.uom_id', 'in', changed.ids),
('quantity', '!=', 0),
]):
raise UserError(error_msg)
return super(UoM, self).write(values)
def _adjust_uom_quantities(self, qty, quant_uom):
""" This method adjust the quantities of a procurement if its UoM isn't the same
as the one of the quant and the parameter 'propagate_uom' is not set.
"""
procurement_uom = self
computed_qty = qty
get_param = self.env['ir.config_parameter'].sudo().get_param
if get_param('stock.propagate_uom') != '1':
computed_qty = self._compute_quantity(qty, quant_uom, rounding_method='HALF-UP')
procurement_uom = quant_uom
else:
computed_qty = self._compute_quantity(qty, procurement_uom, rounding_method='HALF-UP')
return (computed_qty, procurement_uom)
| 54.356816
| 59,412
|
31,328
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from collections import defaultdict, namedtuple
from dateutil.relativedelta import relativedelta
from odoo import SUPERUSER_ID, _, api, fields, models, registry
from odoo.exceptions import UserError
from odoo.osv import expression
from odoo.tools import float_compare, float_is_zero, html_escape
from odoo.tools.misc import split_every
_logger = logging.getLogger(__name__)
class ProcurementException(Exception):
"""An exception raised by ProcurementGroup `run` containing all the faulty
procurements.
"""
def __init__(self, procurement_exceptions):
""":param procurement_exceptions: a list of tuples containing the faulty
procurement and their error messages
:type procurement_exceptions: list
"""
self.procurement_exceptions = procurement_exceptions
class StockRule(models.Model):
""" A rule describe what a procurement should do; produce, buy, move, ... """
_name = 'stock.rule'
_description = "Stock Rule"
_order = "sequence, id"
_check_company_auto = True
@api.model
def default_get(self, fields_list):
res = super().default_get(fields_list)
if 'company_id' in fields_list and not res['company_id']:
res['company_id'] = self.env.company.id
return res
name = fields.Char(
'Name', required=True, translate=True,
help="This field will fill the packing origin and the name of its moves")
active = fields.Boolean(
'Active', default=True,
help="If unchecked, it will allow you to hide the rule without removing it.")
group_propagation_option = fields.Selection([
('none', 'Leave Empty'),
('propagate', 'Propagate'),
('fixed', 'Fixed')], string="Propagation of Procurement Group", default='propagate')
group_id = fields.Many2one('procurement.group', 'Fixed Procurement Group')
action = fields.Selection(
selection=[('pull', 'Pull From'), ('push', 'Push To'), ('pull_push', 'Pull & Push')], string='Action',
required=True, index=True)
sequence = fields.Integer('Sequence', default=20)
company_id = fields.Many2one('res.company', 'Company',
default=lambda self: self.env.company,
domain="[('id', '=?', route_company_id)]", index=True)
location_id = fields.Many2one('stock.location', 'Destination Location', required=True, check_company=True, index=True)
location_src_id = fields.Many2one('stock.location', 'Source Location', check_company=True)
route_id = fields.Many2one('stock.location.route', 'Route', required=True, ondelete='cascade', index=True)
route_company_id = fields.Many2one(related='route_id.company_id', string='Route Company')
procure_method = fields.Selection([
('make_to_stock', 'Take From Stock'),
('make_to_order', 'Trigger Another Rule'),
('mts_else_mto', 'Take From Stock, if unavailable, Trigger Another Rule')], string='Supply Method', default='make_to_stock', required=True,
help="Take From Stock: the products will be taken from the available stock of the source location.\n"
"Trigger Another Rule: the system will try to find a stock rule to bring the products in the source location. The available stock will be ignored.\n"
"Take From Stock, if Unavailable, Trigger Another Rule: the products will be taken from the available stock of the source location."
"If there is no stock available, the system will try to find a rule to bring the products in the source location.")
route_sequence = fields.Integer('Route Sequence', related='route_id.sequence', store=True, compute_sudo=True)
picking_type_id = fields.Many2one(
'stock.picking.type', 'Operation Type',
required=True, check_company=True,
domain="[('code', '=?', picking_type_code_domain)]")
picking_type_code_domain = fields.Char(compute='_compute_picking_type_code_domain')
delay = fields.Integer('Lead Time', default=0, help="The expected date of the created transfer will be computed based on this lead time.")
partner_address_id = fields.Many2one(
'res.partner', 'Partner Address',
check_company=True,
help="Address where goods should be delivered. Optional.")
propagate_cancel = fields.Boolean(
'Cancel Next Move', default=False,
help="When ticked, if the move created by this rule is cancelled, the next move will be cancelled too.")
propagate_carrier = fields.Boolean(
'Propagation of carrier', default=False,
help="When ticked, carrier of shipment will be propgated.")
warehouse_id = fields.Many2one('stock.warehouse', 'Warehouse', check_company=True, index=True)
propagate_warehouse_id = fields.Many2one(
'stock.warehouse', 'Warehouse to Propagate',
help="The warehouse to propagate on the created move/procurement, which can be different of the warehouse this rule is for (e.g for resupplying rules from another warehouse)")
auto = fields.Selection([
('manual', 'Manual Operation'),
('transparent', 'Automatic No Step Added')], string='Automatic Move',
default='manual', required=True,
help="The 'Manual Operation' value will create a stock move after the current one. "
"With 'Automatic No Step Added', the location is replaced in the original move.")
rule_message = fields.Html(compute='_compute_action_message')
@api.onchange('picking_type_id')
def _onchange_picking_type(self):
""" Modify locations to the default picking type's locations source and
destination.
Enable the delay alert if the picking type is a delivery
"""
self.location_src_id = self.picking_type_id.default_location_src_id.id
self.location_id = self.picking_type_id.default_location_dest_id.id
@api.onchange('route_id', 'company_id')
def _onchange_route(self):
""" Ensure that the rule's company is the same than the route's company. """
if self.route_id.company_id:
self.company_id = self.route_id.company_id
if self.picking_type_id.warehouse_id.company_id != self.route_id.company_id:
self.picking_type_id = False
def _get_message_values(self):
""" Return the source, destination and picking_type applied on a stock
rule. The purpose of this function is to avoid code duplication in
_get_message_dict functions since it often requires those data.
"""
source = self.location_src_id and self.location_src_id.display_name or _('Source Location')
destination = self.location_id and self.location_id.display_name or _('Destination Location')
operation = self.picking_type_id and self.picking_type_id.name or _('Operation Type')
return source, destination, operation
def _get_message_dict(self):
""" Return a dict with the different possible message used for the
rule message. It should return one message for each stock.rule action
(except push and pull). This function is override in mrp and
purchase_stock in order to complete the dictionary.
"""
message_dict = {}
source, destination, operation = self._get_message_values()
if self.action in ('push', 'pull', 'pull_push'):
suffix = ""
if self.procure_method == 'make_to_order' and self.location_src_id:
suffix = _("<br>A need is created in <b>%s</b> and a rule will be triggered to fulfill it.", source)
if self.procure_method == 'mts_else_mto' and self.location_src_id:
suffix = _("<br>If the products are not available in <b>%s</b>, a rule will be triggered to bring products in this location.", source)
message_dict = {
'pull': _('When products are needed in <b>%s</b>, <br/> <b>%s</b> are created from <b>%s</b> to fulfill the need.', destination, operation, source) + suffix,
'push': _('When products arrive in <b>%s</b>, <br/> <b>%s</b> are created to send them in <b>%s</b>.', source, operation, destination)
}
return message_dict
@api.depends('action', 'location_id', 'location_src_id', 'picking_type_id', 'procure_method')
def _compute_action_message(self):
""" Generate dynamicaly a message that describe the rule purpose to the
end user.
"""
action_rules = self.filtered(lambda rule: rule.action)
for rule in action_rules:
message_dict = rule._get_message_dict()
message = message_dict.get(rule.action) and message_dict[rule.action] or ""
if rule.action == 'pull_push':
message = message_dict['pull'] + "<br/><br/>" + message_dict['push']
rule.rule_message = message
(self - action_rules).rule_message = None
@api.depends('action')
def _compute_picking_type_code_domain(self):
self.picking_type_code_domain = False
def _run_push(self, move):
""" Apply a push rule on a move.
If the rule is 'no step added' it will modify the destination location
on the move.
If the rule is 'manual operation' it will generate a new move in order
to complete the section define by the rule.
Care this function is not call by method run. It is called explicitely
in stock_move.py inside the method _push_apply
"""
self.ensure_one()
new_date = fields.Datetime.to_string(move.date + relativedelta(days=self.delay))
if self.auto == 'transparent':
old_dest_location = move.location_dest_id
move.write({'date': new_date, 'location_dest_id': self.location_id.id})
# make sure the location_dest_id is consistent with the move line location dest
if move.move_line_ids:
move.move_line_ids.location_dest_id = move.location_dest_id._get_putaway_strategy(move.product_id) or move.location_dest_id
# avoid looping if a push rule is not well configured; otherwise call again push_apply to see if a next step is defined
if self.location_id != old_dest_location:
# TDE FIXME: should probably be done in the move model IMO
return move._push_apply()[:1]
else:
new_move_vals = self._push_prepare_move_copy_values(move, new_date)
new_move = move.sudo().copy(new_move_vals)
if new_move._should_bypass_reservation():
new_move.write({'procure_method': 'make_to_stock'})
if not new_move.location_id.should_bypass_reservation():
move.write({'move_dest_ids': [(4, new_move.id)]})
return new_move
def _push_prepare_move_copy_values(self, move_to_copy, new_date):
company_id = self.company_id.id
if not company_id:
company_id = self.sudo().warehouse_id and self.sudo().warehouse_id.company_id.id or self.sudo().picking_type_id.warehouse_id.company_id.id
new_move_vals = {
'origin': move_to_copy.origin or move_to_copy.picking_id.name or "/",
'location_id': move_to_copy.location_dest_id.id,
'location_dest_id': self.location_id.id,
'date': new_date,
'company_id': company_id,
'picking_id': False,
'picking_type_id': self.picking_type_id.id,
'propagate_cancel': self.propagate_cancel,
'warehouse_id': self.warehouse_id.id,
'procure_method': 'make_to_order',
}
return new_move_vals
@api.model
def _run_pull(self, procurements):
moves_values_by_company = defaultdict(list)
mtso_products_by_locations = defaultdict(list)
# To handle the `mts_else_mto` procure method, we do a preliminary loop to
# isolate the products we would need to read the forecasted quantity,
# in order to to batch the read. We also make a sanitary check on the
# `location_src_id` field.
for procurement, rule in procurements:
if not rule.location_src_id:
msg = _('No source location defined on stock rule: %s!') % (rule.name, )
raise ProcurementException([(procurement, msg)])
if rule.procure_method == 'mts_else_mto':
mtso_products_by_locations[rule.location_src_id].append(procurement.product_id.id)
# Get the forecasted quantity for the `mts_else_mto` procurement.
forecasted_qties_by_loc = {}
for location, product_ids in mtso_products_by_locations.items():
products = self.env['product.product'].browse(product_ids).with_context(location=location.id)
forecasted_qties_by_loc[location] = {product.id: product.free_qty for product in products}
# Prepare the move values, adapt the `procure_method` if needed.
procurements = sorted(procurements, key=lambda proc: float_compare(proc[0].product_qty, 0.0, precision_rounding=proc[0].product_uom.rounding) > 0)
for procurement, rule in procurements:
procure_method = rule.procure_method
if rule.procure_method == 'mts_else_mto':
qty_needed = procurement.product_uom._compute_quantity(procurement.product_qty, procurement.product_id.uom_id)
if float_compare(qty_needed, 0, precision_rounding=procurement.product_id.uom_id.rounding) <= 0:
procure_method = 'make_to_order'
for move in procurement.values.get('group_id', self.env['procurement.group']).stock_move_ids:
if move.rule_id == rule and float_compare(move.product_uom_qty, 0, precision_rounding=move.product_uom.rounding) > 0:
procure_method = move.procure_method
break
forecasted_qties_by_loc[rule.location_src_id][procurement.product_id.id] -= qty_needed
elif float_compare(qty_needed, forecasted_qties_by_loc[rule.location_src_id][procurement.product_id.id],
precision_rounding=procurement.product_id.uom_id.rounding) > 0:
procure_method = 'make_to_order'
else:
forecasted_qties_by_loc[rule.location_src_id][procurement.product_id.id] -= qty_needed
procure_method = 'make_to_stock'
move_values = rule._get_stock_move_values(*procurement)
move_values['procure_method'] = procure_method
moves_values_by_company[procurement.company_id.id].append(move_values)
for company_id, moves_values in moves_values_by_company.items():
# create the move as SUPERUSER because the current user may not have the rights to do it (mto product launched by a sale for example)
moves = self.env['stock.move'].with_user(SUPERUSER_ID).sudo().with_company(company_id).create(moves_values)
# Since action_confirm launch following procurement_group we should activate it.
moves._action_confirm()
return True
def _get_custom_move_fields(self):
""" The purpose of this method is to be override in order to easily add
fields from procurement 'values' argument to move data.
"""
return []
def _get_stock_move_values(self, product_id, product_qty, product_uom, location_id, name, origin, company_id, values):
''' Returns a dictionary of values that will be used to create a stock move from a procurement.
This function assumes that the given procurement has a rule (action == 'pull' or 'pull_push') set on it.
:param procurement: browse record
:rtype: dictionary
'''
group_id = False
if self.group_propagation_option == 'propagate':
group_id = values.get('group_id', False) and values['group_id'].id
elif self.group_propagation_option == 'fixed':
group_id = self.group_id.id
date_scheduled = fields.Datetime.to_string(
fields.Datetime.from_string(values['date_planned']) - relativedelta(days=self.delay or 0)
)
date_deadline = values.get('date_deadline') and (fields.Datetime.to_datetime(values['date_deadline']) - relativedelta(days=self.delay or 0)) or False
partner = self.partner_address_id or (values.get('group_id', False) and values['group_id'].partner_id)
if partner:
product_id = product_id.with_context(lang=partner.lang or self.env.user.lang)
picking_description = product_id._get_description(self.picking_type_id)
if values.get('product_description_variants'):
picking_description += values['product_description_variants']
# it is possible that we've already got some move done, so check for the done qty and create
# a new move with the correct qty
qty_left = product_qty
move_dest_ids = []
if not self.location_id.should_bypass_reservation():
move_dest_ids = values.get('move_dest_ids', False) and [(4, x.id) for x in values['move_dest_ids']] or []
# when create chained moves for inter-warehouse transfers, set the warehouses as partners
if not partner and move_dest_ids:
move_dest = values['move_dest_ids']
if location_id == company_id.internal_transit_location_id:
partners = move_dest.location_dest_id.warehouse_id.partner_id
if len(partners) == 1:
partner = partners
move_dest.partner_id = self.location_src_id.warehouse_id.partner_id or self.company_id.partner_id
move_values = {
'name': name[:2000],
'company_id': self.company_id.id or self.location_src_id.company_id.id or self.location_id.company_id.id or company_id.id,
'product_id': product_id.id,
'product_uom': product_uom.id,
'product_uom_qty': qty_left,
'partner_id': partner.id if partner else False,
'location_id': self.location_src_id.id,
'location_dest_id': location_id.id,
'move_dest_ids': move_dest_ids,
'rule_id': self.id,
'procure_method': self.procure_method,
'origin': origin,
'picking_type_id': self.picking_type_id.id,
'group_id': group_id,
'route_ids': [(4, route.id) for route in values.get('route_ids', [])],
'warehouse_id': self.propagate_warehouse_id.id or self.warehouse_id.id,
'date': date_scheduled,
'date_deadline': False if self.group_propagation_option == 'fixed' else date_deadline,
'propagate_cancel': self.propagate_cancel,
'description_picking': picking_description,
'priority': values.get('priority', "0"),
'orderpoint_id': values.get('orderpoint_id') and values['orderpoint_id'].id,
'product_packaging_id': values.get('product_packaging_id') and values['product_packaging_id'].id,
}
for field in self._get_custom_move_fields():
if field in values:
move_values[field] = values.get(field)
return move_values
def _get_lead_days(self, product, **values):
"""Returns the cumulative delay and its description encountered by a
procurement going through the rules in `self`.
:param product: the product of the procurement
:type product: :class:`~odoo.addons.product.models.product.ProductProduct`
:return: the cumulative delay and cumulative delay's description
:rtype: tuple[int, list[str, str]]
"""
delay = sum(self.filtered(lambda r: r.action in ['pull', 'pull_push']).mapped('delay'))
global_visibility_days = self.env['ir.config_parameter'].sudo().get_param('stock.visibility_days')
if global_visibility_days:
delay += int(global_visibility_days)
if self.env.context.get('bypass_delay_description'):
delay_description = []
else:
delay_description = [
(_('Delay on %s', rule.name), _('+ %d day(s)', rule.delay))
for rule in self
if rule.action in ['pull', 'pull_push'] and rule.delay
]
if global_visibility_days:
delay_description.append((_('Global Visibility Days'), _('+ %d day(s)') % int(global_visibility_days)))
return delay, delay_description
class ProcurementGroup(models.Model):
"""
The procurement group class is used to group products together
when computing procurements. (tasks, physical products, ...)
The goal is that when you have one sales order of several products
and the products are pulled from the same or several location(s), to keep
having the moves grouped into pickings that represent the sales order.
Used in: sales order (to group delivery order lines like the so), pull/push
rules (to pack like the delivery order), on orderpoints (e.g. for wave picking
all the similar products together).
Grouping is made only if the source and the destination is the same.
Suppose you have 4 lines on a picking from Output where 2 lines will need
to come from Input (crossdock) and 2 lines coming from Stock -> Output As
the four will have the same group ids from the SO, the move from input will
have a stock.picking with 2 grouped lines and the move from stock will have
2 grouped lines also.
The name is usually the name of the original document (sales order) or a
sequence computed if created manually.
"""
_name = 'procurement.group'
_description = 'Procurement Group'
_order = "id desc"
Procurement = namedtuple('Procurement', ['product_id', 'product_qty',
'product_uom', 'location_id', 'name', 'origin', 'company_id', 'values'])
partner_id = fields.Many2one('res.partner', 'Partner')
name = fields.Char(
'Reference',
default=lambda self: self.env['ir.sequence'].next_by_code('procurement.group') or '',
required=True)
move_type = fields.Selection([
('direct', 'Partial'),
('one', 'All at once')], string='Delivery Type', default='direct',
required=True)
stock_move_ids = fields.One2many('stock.move', 'group_id', string="Related Stock Moves")
@api.model
def run(self, procurements, raise_user_error=True):
"""Fulfil `procurements` with the help of stock rules.
Procurements are needs of products at a certain location. To fulfil
these needs, we need to create some sort of documents (`stock.move`
by default, but extensions of `_run_` methods allow to create every
type of documents).
:param procurements: the description of the procurement
:type list: list of `~odoo.addons.stock.models.stock_rule.ProcurementGroup.Procurement`
:param raise_user_error: will raise either an UserError or a ProcurementException
:type raise_user_error: boolan, optional
:raises UserError: if `raise_user_error` is True and a procurement isn't fulfillable
:raises ProcurementException: if `raise_user_error` is False and a procurement isn't fulfillable
"""
def raise_exception(procurement_errors):
if raise_user_error:
dummy, errors = zip(*procurement_errors)
raise UserError('\n'.join(errors))
else:
raise ProcurementException(procurement_errors)
actions_to_run = defaultdict(list)
procurement_errors = []
for procurement in procurements:
procurement.values.setdefault('company_id', procurement.location_id.company_id)
procurement.values.setdefault('priority', '0')
procurement.values.setdefault('date_planned', fields.Datetime.now())
if (
procurement.product_id.type not in ('consu', 'product') or
float_is_zero(procurement.product_qty, precision_rounding=procurement.product_uom.rounding)
):
continue
rule = self._get_rule(procurement.product_id, procurement.location_id, procurement.values)
if not rule:
error = _('No rule has been found to replenish "%s" in "%s".\nVerify the routes configuration on the product.') %\
(procurement.product_id.display_name, procurement.location_id.display_name)
procurement_errors.append((procurement, error))
else:
action = 'pull' if rule.action == 'pull_push' else rule.action
actions_to_run[action].append((procurement, rule))
if procurement_errors:
raise_exception(procurement_errors)
for action, procurements in actions_to_run.items():
if hasattr(self.env['stock.rule'], '_run_%s' % action):
try:
getattr(self.env['stock.rule'], '_run_%s' % action)(procurements)
except ProcurementException as e:
procurement_errors += e.procurement_exceptions
else:
_logger.error("The method _run_%s doesn't exist on the procurement rules" % action)
if procurement_errors:
raise_exception(procurement_errors)
return True
@api.model
def _search_rule(self, route_ids, packaging_id, product_id, warehouse_id, domain):
""" First find a rule among the ones defined on the procurement
group, then try on the routes defined for the product, finally fallback
on the default behavior
"""
if warehouse_id:
domain = expression.AND([['|', ('warehouse_id', '=', warehouse_id.id), ('warehouse_id', '=', False)], domain])
Rule = self.env['stock.rule']
res = self.env['stock.rule']
if route_ids:
res = Rule.search(expression.AND([[('route_id', 'in', route_ids.ids)], domain]), order='route_sequence, sequence', limit=1)
if not res and packaging_id:
packaging_routes = packaging_id.route_ids
if packaging_routes:
res = Rule.search(expression.AND([[('route_id', 'in', packaging_routes.ids)], domain]), order='route_sequence, sequence', limit=1)
if not res:
product_routes = product_id.route_ids | product_id.categ_id.total_route_ids
if product_routes:
res = Rule.search(expression.AND([[('route_id', 'in', product_routes.ids)], domain]), order='route_sequence, sequence', limit=1)
if not res and warehouse_id:
warehouse_routes = warehouse_id.route_ids
if warehouse_routes:
res = Rule.search(expression.AND([[('route_id', 'in', warehouse_routes.ids)], domain]), order='route_sequence, sequence', limit=1)
return res
@api.model
def _get_rule(self, product_id, location_id, values):
""" Find a pull rule for the location_id, fallback on the parent
locations if it could not be found.
"""
result = self.env['stock.rule']
location = location_id
while (not result) and location:
domain = self._get_rule_domain(location, values)
result = self._search_rule(values.get('route_ids', False), values.get('product_packaging_id', False), product_id, values.get('warehouse_id', False), domain)
location = location.location_id
return result
@api.model
def _get_rule_domain(self, location, values):
domain = ['&', ('location_id', '=', location.id), ('action', '!=', 'push')]
# In case the method is called by the superuser, we need to restrict the rules to the
# ones of the company. This is not useful as a regular user since there is a record
# rule to filter out the rules based on the company.
if self.env.su and values.get('company_id'):
domain_company = ['|', ('company_id', '=', False), ('company_id', 'child_of', values['company_id'].ids)]
domain = expression.AND([domain, domain_company])
return domain
@api.model
def _get_moves_to_assign_domain(self, company_id):
moves_domain = [
('state', 'in', ['confirmed', 'partially_available']),
('product_uom_qty', '!=', 0.0),
('reservation_date', '<=', fields.Date.today())
]
if company_id:
moves_domain = expression.AND([[('company_id', '=', company_id)], moves_domain])
return moves_domain
@api.model
def _run_scheduler_tasks(self, use_new_cursor=False, company_id=False):
# Minimum stock rules
domain = self._get_orderpoint_domain(company_id=company_id)
orderpoints = self.env['stock.warehouse.orderpoint'].search(domain)
# ensure that qty_* which depends on datetime.now() are correctly
# recomputed
orderpoints.sudo()._compute_qty_to_order()
if use_new_cursor:
self._cr.commit()
orderpoints.sudo()._procure_orderpoint_confirm(use_new_cursor=use_new_cursor, company_id=company_id, raise_user_error=False)
# Search all confirmed stock_moves and try to assign them
domain = self._get_moves_to_assign_domain(company_id)
moves_to_assign = self.env['stock.move'].search(domain, limit=None,
order='reservation_date, priority desc, date asc, id asc')
for moves_chunk in split_every(1000, moves_to_assign.ids):
self.env['stock.move'].browse(moves_chunk).sudo()._action_assign()
if use_new_cursor:
self._cr.commit()
_logger.info("A batch of %d moves are assigned and committed", len(moves_chunk))
# Merge duplicated quants
self.env['stock.quant']._quant_tasks()
if use_new_cursor:
self._cr.commit()
_logger.info("_run_scheduler_tasks is finished and committed")
@api.model
def run_scheduler(self, use_new_cursor=False, company_id=False):
""" Call the scheduler in order to check the running procurements (super method), to check the minimum stock rules
and the availability of moves. This function is intended to be run for all the companies at the same time, so
we run functions as SUPERUSER to avoid intercompanies and access rights issues. """
try:
if use_new_cursor:
cr = registry(self._cr.dbname).cursor()
self = self.with_env(self.env(cr=cr)) # TDE FIXME
self._run_scheduler_tasks(use_new_cursor=use_new_cursor, company_id=company_id)
except Exception:
_logger.error("Error during stock scheduler", exc_info=True)
raise
finally:
if use_new_cursor:
try:
self._cr.close()
except Exception:
pass
return {}
@api.model
def _get_orderpoint_domain(self, company_id=False):
domain = [('trigger', '=', 'auto'), ('product_id.active', '=', True)]
if company_id:
domain += [('company_id', '=', company_id)]
return domain
| 53.098305
| 31,328
|
7,568
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, SUPERUSER_ID, _
from odoo.exceptions import UserError
class ResConfigSettings(models.TransientModel):
_inherit = 'res.config.settings'
module_product_expiry = fields.Boolean("Expiration Dates",
help="Track following dates on lots & serial numbers: best before, removal, end of life, alert. \n Such dates are set automatically at lot/serial number creation based on values set on the product (in days).")
group_stock_production_lot = fields.Boolean("Lots & Serial Numbers",
implied_group='stock.group_production_lot')
group_lot_on_delivery_slip = fields.Boolean("Display Lots & Serial Numbers on Delivery Slips",
implied_group='stock.group_lot_on_delivery_slip', group="base.group_user,base.group_portal")
group_stock_tracking_lot = fields.Boolean("Packages",
implied_group='stock.group_tracking_lot')
group_stock_tracking_owner = fields.Boolean("Consignment",
implied_group='stock.group_tracking_owner')
group_stock_adv_location = fields.Boolean("Multi-Step Routes",
implied_group='stock.group_adv_location',
help="Add and customize route operations to process product moves in your warehouse(s): e.g. unload > quality control > stock for incoming products, pick > pack > ship for outgoing products. \n You can also set putaway strategies on warehouse locations in order to send incoming products into specific child locations straight away (e.g. specific bins, racks).")
group_warning_stock = fields.Boolean("Warnings for Stock", implied_group='stock.group_warning_stock')
group_stock_sign_delivery = fields.Boolean("Signature", implied_group='stock.group_stock_sign_delivery')
module_stock_picking_batch = fields.Boolean("Batch Transfers")
group_stock_picking_wave = fields.Boolean('Wave Transfers', implied_group='stock.group_stock_picking_wave',
help="Group your move operations in wave transfer to process them together")
module_stock_barcode = fields.Boolean("Barcode Scanner")
stock_move_email_validation = fields.Boolean(related='company_id.stock_move_email_validation', readonly=False)
stock_mail_confirmation_template_id = fields.Many2one(related='company_id.stock_mail_confirmation_template_id', readonly=False)
module_stock_sms = fields.Boolean("SMS Confirmation")
module_delivery = fields.Boolean("Delivery Methods")
module_delivery_dhl = fields.Boolean("DHL Express Connector")
module_delivery_fedex = fields.Boolean("FedEx Connector")
module_delivery_ups = fields.Boolean("UPS Connector")
module_delivery_usps = fields.Boolean("USPS Connector")
module_delivery_bpost = fields.Boolean("bpost Connector")
module_delivery_easypost = fields.Boolean("Easypost Connector")
module_quality_control = fields.Boolean("Quality")
module_quality_control_worksheet = fields.Boolean("Quality Worksheet")
group_stock_multi_locations = fields.Boolean('Storage Locations', implied_group='stock.group_stock_multi_locations',
help="Store products in specific locations of your warehouse (e.g. bins, racks) and to track inventory accordingly.")
group_stock_storage_categories = fields.Boolean(
'Storage Categories', implied_group='stock.group_stock_storage_categories')
annual_inventory_month = fields.Selection(related='company_id.annual_inventory_month', readonly=False)
annual_inventory_day = fields.Integer(related='company_id.annual_inventory_day', readonly=False)
group_stock_reception_report = fields.Boolean("Reception Report", implied_group='stock.group_reception_report')
group_stock_auto_reception_report = fields.Boolean("Show Reception Report at Validation", implied_group='stock.group_auto_reception_report')
@api.onchange('group_stock_multi_locations')
def _onchange_group_stock_multi_locations(self):
if not self.group_stock_multi_locations:
self.group_stock_adv_location = False
self.group_stock_storage_categories = False
@api.onchange('group_stock_production_lot')
def _onchange_group_stock_production_lot(self):
if not self.group_stock_production_lot:
self.group_lot_on_delivery_slip = False
@api.onchange('group_stock_adv_location')
def onchange_adv_location(self):
if self.group_stock_adv_location and not self.group_stock_multi_locations:
self.group_stock_multi_locations = True
def set_values(self):
warehouse_grp = self.env.ref('stock.group_stock_multi_warehouses')
location_grp = self.env.ref('stock.group_stock_multi_locations')
base_user = self.env.ref('base.group_user')
if not self.group_stock_multi_locations and location_grp in base_user.implied_ids and warehouse_grp in base_user.implied_ids:
raise UserError(_("You can't desactivate the multi-location if you have more than once warehouse by company"))
# Deactivate putaway rules with storage category when not in storage category
# group. Otherwise, active them.
storage_cate_grp = self.env.ref('stock.group_stock_storage_categories')
PutawayRule = self.env['stock.putaway.rule']
if self.group_stock_storage_categories and storage_cate_grp not in base_user.implied_ids:
putaway_rules = PutawayRule.search([
('active', '=', False),
('storage_category_id', '!=', False)
])
putaway_rules.write({'active': True})
elif not self.group_stock_storage_categories and storage_cate_grp in base_user.implied_ids:
putaway_rules = PutawayRule.search([('storage_category_id', '!=', False)])
putaway_rules.write({'active': False})
previous_group = self.default_get(['group_stock_multi_locations', 'group_stock_production_lot', 'group_stock_tracking_lot'])
was_operations_showed = self.env['stock.picking.type'].with_user(SUPERUSER_ID)._default_show_operations()
res = super(ResConfigSettings, self).set_values()
if not self.user_has_groups('stock.group_stock_manager'):
return
# If we just enabled multiple locations with this settings change, we can deactivate
# the internal operation types of the warehouses, so they won't appear in the dashboard.
# Otherwise (if we just disabled multiple locations with this settings change), activate them
warehouse_obj = self.env['stock.warehouse']
if self.group_stock_multi_locations and not previous_group.get('group_stock_multi_locations'):
# override active_test that is false in set_values
warehouse_obj.with_context(active_test=True).search([]).mapped('int_type_id').write({'active': True})
elif not self.group_stock_multi_locations and previous_group.get('group_stock_multi_locations'):
warehouse_obj.search([
('reception_steps', '=', 'one_step'),
('delivery_steps', '=', 'ship_only')]
).mapped('int_type_id').write({'active': False})
if not was_operations_showed and self.env['stock.picking.type'].with_user(SUPERUSER_ID)._default_show_operations():
picking_types = self.env['stock.picking.type'].with_context(active_test=False).search([
('code', '!=', 'incoming'),
('show_operations', '=', False)
])
picking_types.sudo().write({'show_operations': True})
return res
| 65.808696
| 7,568
|
3,220
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, fields, _
class PackageType(models.Model):
_name = 'stock.package.type'
_description = "Stock package type"
def _get_default_length_uom(self):
return self.env['product.template']._get_length_uom_name_from_ir_config_parameter()
def _get_default_weight_uom(self):
return self.env['product.template']._get_weight_uom_name_from_ir_config_parameter()
name = fields.Char('Package Type', required=True)
sequence = fields.Integer('Sequence', default=1, help="The first in the sequence is the default one.")
height = fields.Integer('Height', help="Packaging Height")
width = fields.Integer('Width', help="Packaging Width")
packaging_length = fields.Integer('Length', help="Packaging Length")
max_weight = fields.Float('Max Weight', help='Maximum weight shippable in this packaging')
barcode = fields.Char('Barcode', copy=False)
weight_uom_name = fields.Char(string='Weight unit of measure label', compute='_compute_weight_uom_name', default=_get_default_weight_uom)
length_uom_name = fields.Char(string='Length unit of measure label', compute='_compute_length_uom_name', default=_get_default_length_uom)
company_id = fields.Many2one('res.company', 'Company', index=True)
storage_category_capacity_ids = fields.One2many('stock.storage.category.capacity', 'package_type_id', 'Storage Category Capacity', copy=True)
_sql_constraints = [
('barcode_uniq', 'unique(barcode)', "A barcode can only be assigned to one package type !"),
('positive_height', 'CHECK(height>=0)', 'Height must be positive'),
('positive_width', 'CHECK(width>=0)', 'Width must be positive'),
('positive_length', 'CHECK(packaging_length>=0)', 'Length must be positive'),
('positive_max_weight', 'CHECK(max_weight>=0.0)', 'Max Weight must be positive'),
]
def _compute_length_uom_name(self):
# FIXME This variable does not impact any logic, it is only used for the packaging display on the form view.
# However, it generates some confusion for the users since this UoM will be ignored when sending the requests
# to the carrier server: the dimensions will be expressed with another UoM and there won't be any conversion.
# For instance, with Fedex, the UoM used with the package dimensions will depend on the UoM of
# `fedex_weight_unit`. With UPS, we will use the UoM defined on `ups_package_dimension_unit`
# This is also confusing when length UoM of the database is `ft`. The dimensions are integers (not floats) and
# the UoM is not small enough (for instance, the user will not be able to define a package with a length
# of 10 in)
self.length_uom_name = ""
def _compute_weight_uom_name(self):
for package_type in self:
package_type.weight_uom_name = self.env['product.template']._get_weight_uom_name_from_ir_config_parameter()
def copy(self, default=None):
default = dict(default or {})
default.update(name=_("%s (copy)") % self.name)
return super().copy(default)
| 58.545455
| 3,220
|
1,140
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
from odoo.addons.base.models.res_partner import WARNING_HELP, WARNING_MESSAGE
class Partner(models.Model):
_inherit = 'res.partner'
_check_company_auto = True
property_stock_customer = fields.Many2one(
'stock.location', string="Customer Location", company_dependent=True, check_company=True,
domain="['|', ('company_id', '=', False), ('company_id', '=', allowed_company_ids[0])]",
help="The stock location used as destination when sending goods to this contact.")
property_stock_supplier = fields.Many2one(
'stock.location', string="Vendor Location", company_dependent=True, check_company=True,
domain="['|', ('company_id', '=', False), ('company_id', '=', allowed_company_ids[0])]",
help="The stock location used as source when receiving goods from this contact.")
picking_warn = fields.Selection(WARNING_MESSAGE, 'Stock Picking', help=WARNING_HELP, default='no-message')
picking_warn_msg = fields.Text('Message for Stock Picking')
| 54.285714
| 1,140
|
7,792
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models, _
from odoo.exceptions import UserError
class ReportStockRule(models.AbstractModel):
_name = 'report.stock.report_stock_rule'
_description = 'Stock rule report'
@api.model
def _get_report_values(self, docids, data=None):
# Overriding data values here since used also in _get_routes.
data['product_id'] = data.get('product_id', docids)
data['warehouse_ids'] = data.get('warehouse_ids', [])
product = self.env['product.product'].browse(data['product_id'])
warehouses = self.env['stock.warehouse'].browse(data['warehouse_ids'])
routes = self._get_routes(data)
# Some routes don't have a warehouse_id but contain rules of different warehouses,
# we filter here the ones we want to display and build for each one a dict containing the rule,
# their source and destination location.
relevant_rules = routes.mapped('rule_ids').filtered(lambda r: not r.warehouse_id or r.warehouse_id in warehouses)
rules_and_loc = []
for rule in relevant_rules:
rules_and_loc.append(self._get_rule_loc(rule, product))
locations = self._sort_locations(rules_and_loc, warehouses)
reordering_rules = self.env['stock.warehouse.orderpoint'].search([('product_id', '=', product.id)])
locations |= reordering_rules.mapped('location_id').filtered(lambda l: l not in locations)
locations_names = locations.mapped('display_name')
# Here we handle reordering rules and putaway strategies by creating the header_lines dict. This dict is indexed
# by location_id and contains itself another dict with the relevant reordering rules and putaway strategies.
header_lines = {}
for location in locations:
# TODO: group the RR by location_id to avoid a filtered at each loop
rr = reordering_rules.filtered(lambda r: r.location_id.id == location.id)
putaways = product.putaway_rule_ids.filtered(lambda p: p.location_in_id.id == location.id)
if putaways or rr:
header_lines[location.id] = {'putaway': [], 'orderpoint': []}
for putaway in putaways:
header_lines[location.id]['putaway'].append(putaway)
for r in rr:
header_lines[location.id]['orderpoint'].append(r)
route_lines = []
colors = self._get_route_colors()
for color_index, route in enumerate(routes):
rules_to_display = route.rule_ids & relevant_rules
if rules_to_display:
route_color = colors[color_index % len(colors)]
color_index = color_index + 1
for rule in rules_to_display:
rule_loc = [r for r in rules_and_loc if r['rule'] == rule][0]
res = []
for x in range(len(locations_names)):
res.append([])
idx = locations_names.index(rule_loc['destination'].display_name)
tpl = (rule, 'destination', route_color, )
res[idx] = tpl
idx = locations_names.index(rule_loc['source'].display_name)
tpl = (rule, 'origin', route_color, )
res[idx] = tpl
route_lines.append(res)
return {
'docs': product,
'locations': locations,
'header_lines': header_lines,
'route_lines': route_lines,
}
@api.model
def _get_route_colors(self):
return ['#FFA500', '#800080', '#228B22', '#008B8B', '#4682B4', '#FF0000', '#32CD32']
@api.model
def _get_routes(self, data):
""" Extract the routes to display from the wizard's content.
"""
product = self.env['product.product'].browse(data['product_id'])
warehouse_ids = self.env['stock.warehouse'].browse(data['warehouse_ids'])
return product.route_ids | product.categ_id.total_route_ids | warehouse_ids.mapped('route_ids')
@api.model
def _get_rule_loc(self, rule, product):
rule.ensure_one()
return {'rule': rule, 'source': rule.location_src_id, 'destination': rule.location_id}
@api.model
def _sort_locations(self, rules_and_loc, warehouses):
""" We order the locations by setting first the locations of type supplier and manufacture,
then we add the locations grouped by warehouse and we finish by the locations of type
customer and the ones that were not added by the sort.
"""
all_src = self.env['stock.location'].concat(*([r['source'] for r in rules_and_loc]))
all_dest = self.env['stock.location'].concat(*([r['destination'] for r in rules_and_loc]))
all_locations = all_src | all_dest
ordered_locations = self.env['stock.location']
locations = all_locations.filtered(lambda l: l.usage in ('supplier', 'production'))
for warehouse_id in warehouses:
all_warehouse_locations = all_locations.filtered(lambda l: l.warehouse_id == warehouse_id)
starting_rules = [d for d in rules_and_loc if d['source'] not in all_warehouse_locations]
if starting_rules:
start_locations = self.env['stock.location'].concat(*([r['destination'] for r in starting_rules]))
else:
starting_rules = [d for d in rules_and_loc if d['source'] not in all_dest]
start_locations = self.env['stock.location'].concat(*([r['source'] for r in starting_rules]))
used_rules = self.env['stock.rule']
locations |= self._sort_locations_by_warehouse(rules_and_loc, used_rules, start_locations, ordered_locations, warehouse_id)
if any(location not in locations for location in all_warehouse_locations):
remaining_locations = self.env['stock.location'].concat(*([r['source'] for r in rules_and_loc])).filtered(lambda l: l not in locations)
locations |= self._sort_locations_by_warehouse(rules_and_loc, used_rules, remaining_locations, ordered_locations, warehouse_id)
locations |= all_locations.filtered(lambda l: l.usage in ('customer'))
locations |= all_locations.filtered(lambda l: l not in locations)
return locations
@api.model
def _sort_locations_by_warehouse(self, rules_and_loc, used_rules, start_locations, ordered_locations, warehouse_id):
""" We order locations by putting first the locations that are not the destination of others and do it recursively.
"""
start_locations = start_locations.filtered(lambda l: l.warehouse_id == warehouse_id)
ordered_locations |= start_locations
rules_start = []
for rule in rules_and_loc:
if rule['source'] in start_locations:
rules_start.append(rule)
used_rules |= rule['rule']
if rules_start:
rules_start_dest_locations = self.env['stock.location'].concat(*([r['destination'] for r in rules_start]))
remaining_rules = self.env['stock.rule'].concat(*([r['rule'] for r in rules_and_loc])) - used_rules
remaining_rules_location = self.env['stock.location']
for r in rules_and_loc:
if r['rule'] in remaining_rules:
remaining_rules_location |= r['destination']
start_locations = rules_start_dest_locations - ordered_locations - remaining_rules_location
ordered_locations = self._sort_locations_by_warehouse(rules_and_loc, used_rules, start_locations, ordered_locations, warehouse_id)
return ordered_locations
| 56.057554
| 7,792
|
10,710
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models, _
from odoo.tools import config
from odoo.tools import format_datetime
from markupsafe import Markup
rec = 0
def autoIncrement():
global rec
pStart = 1
pInterval = 1
if rec == 0:
rec = pStart
else:
rec += pInterval
return rec
class MrpStockReport(models.TransientModel):
_name = 'stock.traceability.report'
_description = 'Traceability Report'
@api.model
def _get_move_lines(self, move_lines, line_id=None):
lines_seen = move_lines
lines_todo = list(move_lines)
while lines_todo:
move_line = lines_todo.pop(0)
# if MTO
if move_line.move_id.move_orig_ids:
lines = move_line.move_id.move_orig_ids.mapped('move_line_ids').filtered(
lambda m: m.lot_id == move_line.lot_id and m.state == 'done'
) - lines_seen
# if MTS
elif move_line.location_id.usage == 'internal':
lines = self.env['stock.move.line'].search([
('product_id', '=', move_line.product_id.id),
('lot_id', '=', move_line.lot_id.id),
('location_dest_id', '=', move_line.location_id.id),
('id', 'not in', lines_seen.ids),
('date', '<=', move_line.date),
('state', '=', 'done')
])
else:
continue
if line_id is None or line_id in lines.ids:
lines_todo += list(lines)
lines_seen |= lines
return lines_seen - move_lines
@api.model
def get_lines(self, line_id=None, **kw):
context = dict(self.env.context)
model = kw and kw['model_name'] or context.get('model')
rec_id = kw and kw['model_id'] or context.get('active_id')
level = kw and kw['level'] or 1
lines = self.env['stock.move.line']
move_line = self.env['stock.move.line']
if rec_id and model == 'stock.production.lot':
lines = move_line.search([
('lot_id', '=', context.get('lot_name') or rec_id),
('state', '=', 'done'),
])
elif rec_id and model == 'stock.move.line' and context.get('lot_name'):
record = self.env[model].browse(rec_id)
dummy, is_used = self._get_linked_move_lines(record)
if is_used:
lines = is_used
elif rec_id and model in ('stock.picking', 'mrp.production'):
record = self.env[model].browse(rec_id)
if model == 'stock.picking':
lines = record.move_lines.mapped('move_line_ids').filtered(lambda m: m.lot_id and m.state == 'done')
else:
lines = record.move_finished_ids.mapped('move_line_ids').filtered(lambda m: m.state == 'done')
move_line_vals = self._lines(line_id, model_id=rec_id, model=model, level=level, move_lines=lines)
final_vals = sorted(move_line_vals, key=lambda v: v['date'], reverse=True)
lines = self._final_vals_to_lines(final_vals, level)
return lines
@api.model
def _get_reference(self, move_line):
res_model = ''
ref = ''
res_id = False
picking_id = move_line.picking_id or move_line.move_id.picking_id
if picking_id:
res_model = 'stock.picking'
res_id = picking_id.id
ref = picking_id.name
elif move_line.move_id.is_inventory:
res_model = 'stock.move'
res_id = move_line.move_id.id
ref = 'Inventory Adjustment'
elif move_line.move_id.scrapped and move_line.move_id.scrap_ids:
res_model = 'stock.scrap'
res_id = move_line.move_id.scrap_ids[0].id
ref = move_line.move_id.scrap_ids[0].name
return res_model, res_id, ref
@api.model
def _quantity_to_str(self, from_uom, to_uom, qty):
""" workaround to apply the float rounding logic of t-esc on data prepared server side """
qty = from_uom._compute_quantity(qty, to_uom, rounding_method='HALF-UP')
return self.env['ir.qweb.field.float'].value_to_html(qty, {'decimal_precision': 'Product Unit of Measure'})
def _get_usage(self, move_line):
usage = ''
if (move_line.location_id.usage == 'internal') and (move_line.location_dest_id.usage == 'internal'):
usage = 'internal'
elif (move_line.location_id.usage != 'internal') and (move_line.location_dest_id.usage == 'internal'):
usage = 'in'
else:
usage = 'out'
return usage
def _make_dict_move(self, level, parent_id, move_line, unfoldable=False):
res_model, res_id, ref = self._get_reference(move_line)
dummy, is_used = self._get_linked_move_lines(move_line)
data = [{
'level': level,
'unfoldable': unfoldable,
'date': move_line.move_id.date,
'parent_id': parent_id,
'is_used': bool(is_used),
'usage': self._get_usage(move_line),
'model_id': move_line.id,
'model': 'stock.move.line',
'product_id': move_line.product_id.display_name,
'product_qty_uom': "%s %s" % (self._quantity_to_str(move_line.product_uom_id, move_line.product_id.uom_id, move_line.qty_done), move_line.product_id.uom_id.name),
'lot_name': move_line.lot_id.name,
'lot_id': move_line.lot_id.id,
'location_source': move_line.location_id.name,
'location_destination': move_line.location_dest_id.name,
'reference_id': ref,
'res_id': res_id,
'res_model': res_model}]
return data
@api.model
def _final_vals_to_lines(self, final_vals, level):
lines = []
for data in final_vals:
lines.append({
'id': autoIncrement(),
'model': data['model'],
'model_id': data['model_id'],
'parent_id': data['parent_id'],
'usage': data.get('usage', False),
'is_used': data.get('is_used', False),
'lot_name': data.get('lot_name', False),
'lot_id': data.get('lot_id', False),
'reference': data.get('reference_id', False),
'res_id': data.get('res_id', False),
'res_model': data.get('res_model', False),
'columns': [data.get('reference_id', False),
data.get('product_id', False),
format_datetime(self.env, data.get('date', False), tz=False, dt_format=False),
data.get('lot_name', False),
data.get('location_source', False),
data.get('location_destination', False),
data.get('product_qty_uom', 0)],
'level': level,
'unfoldable': data['unfoldable'],
})
return lines
def _get_linked_move_lines(self, move_line):
""" This method will return the consumed line or produced line for this operation."""
return False, False
@api.model
def _lines(self, line_id=None, model_id=False, model=False, level=0, move_lines=[], **kw):
final_vals = []
lines = move_lines or []
if model and line_id:
move_line = self.env[model].browse(model_id)
move_lines, is_used = self._get_linked_move_lines(move_line)
if move_lines:
lines = move_lines
else:
# Traceability in case of consumed in.
lines = self._get_move_lines(move_line, line_id=line_id)
for line in lines:
unfoldable = False
if line.consume_line_ids or (model != "stock.production.lot" and line.lot_id and self._get_move_lines(line)):
unfoldable = True
final_vals += self._make_dict_move(level, parent_id=line_id, move_line=line, unfoldable=unfoldable)
return final_vals
def get_pdf_lines(self, line_data=[]):
lines = []
for line in line_data:
model = self.env[line['model_name']].browse(line['model_id'])
unfoldable = False
if line.get('unfoldable'):
unfoldable = True
final_vals = self._make_dict_move(line['level'], parent_id=line['id'], move_line=model, unfoldable=unfoldable)
lines.append(self._final_vals_to_lines(final_vals, line['level'])[0])
return lines
def get_pdf(self, line_data=None):
line_data = [] if line_data is None else line_data
lines = self.with_context(print_mode=True).get_pdf_lines(line_data)
base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url')
rcontext = {
'mode': 'print',
'base_url': base_url,
}
context = dict(self.env.context)
if not config['test_enable']:
context['commit_assetsbundle'] = True
if context.get('active_id') and context.get('active_model'):
rcontext['reference'] = self.env[context.get('active_model')].browse(int(context.get('active_id'))).display_name
body = self.env['ir.ui.view'].with_context(context)._render_template(
"stock.report_stock_inventory_print",
values=dict(rcontext, lines=lines, report=self, context=self),
)
header = self.env['ir.actions.report']._render_template("web.internal_layout", values=rcontext)
header = self.env['ir.actions.report']._render_template("web.minimal_layout", values=dict(rcontext, subst=True, body=Markup(header.decode())))
return self.env['ir.actions.report']._run_wkhtmltopdf(
[body],
header=header.decode(),
landscape=True,
specific_paperformat_args={'data-report-margin-top': 17, 'data-report-header-spacing': 12}
)
def _get_html(self):
result = {}
rcontext = {}
context = dict(self.env.context)
rcontext['lines'] = self.with_context(context).get_lines()
result['html'] = self.env.ref('stock.report_stock_inventory')._render(rcontext)
return result
@api.model
def get_html(self, given_context=None):
res = self.search([('create_uid', '=', self.env.uid)], limit=1)
if not res:
return self.create({}).with_context(given_context)._get_html()
return res.with_context(given_context)._get_html()
| 43.360324
| 10,710
|
7,019
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, tools
class ReportStockQuantity(models.Model):
_name = 'report.stock.quantity'
_auto = False
_description = 'Stock Quantity Report'
date = fields.Date(string='Date', readonly=True)
product_tmpl_id = fields.Many2one('product.template', readonly=True)
product_id = fields.Many2one('product.product', string='Product', readonly=True)
state = fields.Selection([
('forecast', 'Forecasted Stock'),
('in', 'Forecasted Receipts'),
('out', 'Forecasted Deliveries'),
], string='State', readonly=True)
product_qty = fields.Float(string='Quantity', readonly=True)
company_id = fields.Many2one('res.company', readonly=True)
warehouse_id = fields.Many2one('stock.warehouse', readonly=True)
def init(self):
"""
Because we can transfer a product from a warehouse to another one thanks to a stock move, we need to
generate some fake stock moves before processing all of them. That way, in case of an interwarehouse
transfer, we will have an outgoing stock move for the source warehouse and an incoming stock move
for the destination one. To do so, we select all relevant SM (incoming, outgoing and interwarehouse),
then we duplicate all these SM and edit the values:
- product_qty is kept if the SM is not the duplicated one or if the SM is an interwarehouse one
otherwise, we set the value to 0 (this allows us to filter it out during the SM processing)
- the source warehouse is kept if the SM is not the duplicated one
- the dest warehouse is kept if the SM is not the duplicated one and is not an interwarehouse
OR the SM is the duplicated one and is an interwarehouse
"""
tools.drop_view_if_exists(self._cr, 'report_stock_quantity')
query = """
CREATE or REPLACE VIEW report_stock_quantity AS (
WITH
existing_sm (id, product_id, tmpl_id, product_qty, date, state, company_id, whs_id, whd_id) AS (
SELECT m.id, m.product_id, pt.id, m.product_qty, m.date, m.state, m.company_id, whs.id, whd.id
FROM stock_move m
LEFT JOIN stock_location ls on (ls.id=m.location_id)
LEFT JOIN stock_location ld on (ld.id=m.location_dest_id)
LEFT JOIN stock_warehouse whs ON ls.parent_path like concat('%/', whs.view_location_id, '/%')
LEFT JOIN stock_warehouse whd ON ld.parent_path like concat('%/', whd.view_location_id, '/%')
LEFT JOIN product_product pp on pp.id=m.product_id
LEFT JOIN product_template pt on pt.id=pp.product_tmpl_id
WHERE pt.type = 'product' AND
(whs.id IS NOT NULL OR whd.id IS NOT NULL) AND
(whs.id IS NULL OR whd.id IS NULL OR whs.id != whd.id) AND
m.product_qty != 0 AND
m.state NOT IN ('draft', 'cancel') AND
(m.state IN ('draft', 'waiting', 'confirmed', 'partially_available', 'assigned') or m.date >= ((now() at time zone 'utc')::date - interval '3month'))
),
all_sm (id, product_id, tmpl_id, product_qty, date, state, company_id, whs_id, whd_id) AS (
SELECT sm.id, sm.product_id, sm.tmpl_id,
CASE
WHEN is_duplicated = 0 THEN sm.product_qty
WHEN sm.whs_id IS NOT NULL AND sm.whd_id IS NOT NULL AND sm.whs_id != sm.whd_id THEN sm.product_qty
ELSE 0
END,
sm.date, sm.state, sm.company_id,
CASE WHEN is_duplicated = 0 THEN sm.whs_id END,
CASE
WHEN is_duplicated = 0 AND NOT (sm.whs_id IS NOT NULL AND sm.whd_id IS NOT NULL AND sm.whs_id != sm.whd_id) THEN sm.whd_id
WHEN is_duplicated = 1 AND (sm.whs_id IS NOT NULL AND sm.whd_id IS NOT NULL AND sm.whs_id != sm.whd_id) THEN sm.whd_id
END
FROM
GENERATE_SERIES(0, 1, 1) is_duplicated,
existing_sm sm
)
SELECT
MIN(id) as id,
product_id,
product_tmpl_id,
state,
date,
sum(product_qty) as product_qty,
company_id,
warehouse_id
FROM (SELECT
m.id,
m.product_id,
m.tmpl_id as product_tmpl_id,
CASE
WHEN m.whs_id IS NOT NULL AND m.whd_id IS NULL THEN 'out'
WHEN m.whd_id IS NOT NULL AND m.whs_id IS NULL THEN 'in'
END AS state,
m.date::date AS date,
CASE
WHEN m.whs_id IS NOT NULL AND m.whd_id IS NULL THEN -m.product_qty
WHEN m.whd_id IS NOT NULL AND m.whs_id IS NULL THEN m.product_qty
END AS product_qty,
m.company_id,
CASE
WHEN m.whs_id IS NOT NULL AND m.whd_id IS NULL THEN m.whs_id
WHEN m.whd_id IS NOT NULL AND m.whs_id IS NULL THEN m.whd_id
END AS warehouse_id
FROM
all_sm m
WHERE
m.product_qty != 0 AND
m.state != 'done'
UNION ALL
SELECT
-q.id as id,
q.product_id,
pp.product_tmpl_id,
'forecast' as state,
date.*::date,
q.quantity as product_qty,
q.company_id,
wh.id as warehouse_id
FROM
GENERATE_SERIES((now() at time zone 'utc')::date - interval '3month',
(now() at time zone 'utc')::date + interval '3 month', '1 day'::interval) date,
stock_quant q
LEFT JOIN stock_location l on (l.id=q.location_id)
LEFT JOIN stock_warehouse wh ON l.parent_path like concat('%/', wh.view_location_id, '/%')
LEFT JOIN product_product pp on pp.id=q.product_id
WHERE
(l.usage = 'internal' AND wh.id IS NOT NULL) OR
l.usage = 'transit'
UNION ALL
SELECT
m.id,
m.product_id,
m.tmpl_id as product_tmpl_id,
'forecast' as state,
GENERATE_SERIES(
CASE
WHEN m.state = 'done' THEN (now() at time zone 'utc')::date - interval '3month'
ELSE m.date::date
END,
CASE
WHEN m.state != 'done' THEN (now() at time zone 'utc')::date + interval '3 month'
ELSE m.date::date - interval '1 day'
END, '1 day'::interval)::date date,
CASE
WHEN m.whs_id IS NOT NULL AND m.whd_id IS NULL AND m.state = 'done' THEN m.product_qty
WHEN m.whd_id IS NOT NULL AND m.whs_id IS NULL AND m.state = 'done' THEN -m.product_qty
WHEN m.whs_id IS NOT NULL AND m.whd_id IS NULL THEN -m.product_qty
WHEN m.whd_id IS NOT NULL AND m.whs_id IS NULL THEN m.product_qty
END AS product_qty,
m.company_id,
CASE
WHEN m.whs_id IS NOT NULL AND m.whd_id IS NULL THEN m.whs_id
WHEN m.whd_id IS NOT NULL AND m.whs_id IS NULL THEN m.whd_id
END AS warehouse_id
FROM
all_sm m
WHERE
m.product_qty != 0) AS forecast_qty
GROUP BY product_id, product_tmpl_id, state, date, company_id, warehouse_id
);
"""
self.env.cr.execute(query)
| 44.144654
| 7,019
|
17,394
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import defaultdict, OrderedDict
from odoo import _, api, models
from odoo.tools import float_compare, float_is_zero, format_date
class ReceptionReport(models.AbstractModel):
_name = 'report.stock.report_reception'
_description = "Stock Reception Report"
@api.model
def _get_report_values(self, docids, data=None):
''' This report is flexibly designed to work with both individual and batch pickings.
'''
docids = self.env.context.get('default_picking_ids', docids)
pickings = self.env['stock.picking'].search([('id', 'in', docids), ('picking_type_code', '!=', 'outgoing'), ('state', '!=', 'cancel')])
picking_states = pickings.mapped('state')
# unsupported cases
if not pickings:
msg = _("No transfers selected or a delivery order selected")
elif 'done' in picking_states and len(set(picking_states)) > 1:
pickings = False
msg = _("This report cannot be used for done and not done transfers at the same time")
if not pickings:
return {'pickings': False, 'reason': msg}
# incoming move qtys
product_to_qty_draft = defaultdict(float)
product_to_qty_to_assign = defaultdict(list)
product_to_total_assigned = defaultdict(lambda: [0.0, []])
# to support batch pickings we need to track the total already assigned
move_lines = pickings.move_lines.filtered(lambda m: m.product_id.type == 'product' and m.state != 'cancel')
assigned_moves = move_lines.mapped('move_dest_ids')
product_to_assigned_qty = defaultdict(float)
for assigned in assigned_moves:
product_to_assigned_qty[assigned.product_id] += assigned.product_qty
for move in move_lines:
qty_already_assigned = 0
if move.move_dest_ids:
qty_already_assigned = min(product_to_assigned_qty[move.product_id], move.product_qty)
product_to_assigned_qty[move.product_id] -= qty_already_assigned
if qty_already_assigned:
product_to_total_assigned[move.product_id][0] += qty_already_assigned
product_to_total_assigned[move.product_id][1].append(move.id)
if move.product_qty != qty_already_assigned:
if move.state == 'draft':
product_to_qty_draft[move.product_id] += move.product_qty - qty_already_assigned
else:
quantity_to_assign = move.product_qty
if move.picking_id.immediate_transfer:
# if immediate transfer is not Done and quantity_done hasn't been edited, then move.product_qty will incorrectly = 1 (due to default)
quantity_to_assign = move.product_uom._compute_quantity(move.quantity_done, move.product_id.uom_id, rounding_method='HALF-UP')
product_to_qty_to_assign[move.product_id].append((quantity_to_assign - qty_already_assigned, move))
# only match for non-mto moves in same warehouse
warehouse = pickings[0].picking_type_id.warehouse_id
wh_location_ids = self.env['stock.location']._search([('id', 'child_of', warehouse.view_location_id.id), ('usage', '!=', 'supplier')])
allowed_states = ['confirmed', 'partially_available', 'waiting']
if 'done' in picking_states:
# only done moves are allowed to be assigned to already reserved moves
allowed_states += ['assigned']
outs = self.env['stock.move'].search(
[
('state', 'in', allowed_states),
('product_qty', '>', 0),
('location_id', 'in', wh_location_ids),
('move_orig_ids', '=', False),
('picking_id', 'not in', pickings.ids),
('product_id', 'in',
[p.id for p in list(product_to_qty_to_assign.keys()) + list(product_to_qty_draft.keys())]),
],
order='reservation_date, priority desc, date, id')
products_to_outs = defaultdict(list)
for out in outs:
products_to_outs[out.product_id].append(out)
sources_to_lines = defaultdict(list) # group by source so we can print them together
# show potential moves that can be assigned
for product_id, outs in products_to_outs.items():
for out in outs:
# we expect len(source) = 2 when picking + origin [e.g. SO] and len() = 1 otherwise [e.g. MO]
source = (out._get_source_document(),)
if not source:
continue
if out.picking_id and source[0] != out.picking_id:
source = (out.picking_id, source[0])
qty_to_reserve = out.product_qty
product_uom = out.product_id.uom_id
if 'done' not in picking_states and out.state == 'partially_available':
qty_to_reserve -= out.product_uom._compute_quantity(out.reserved_availability, product_uom)
moves_in_ids = []
qty_done = 0
for move_in_qty, move_in in product_to_qty_to_assign[out.product_id]:
moves_in_ids.append(move_in.id)
if float_compare(qty_done + move_in_qty, qty_to_reserve, precision_rounding=product_uom.rounding) <= 0:
qty_to_add = move_in_qty
move_in_qty = 0
else:
qty_to_add = qty_to_reserve - qty_done
move_in_qty -= qty_to_add
qty_done += qty_to_add
if move_in_qty:
product_to_qty_to_assign[out.product_id][0] = (move_in_qty, move_in)
else:
product_to_qty_to_assign[out.product_id] = product_to_qty_to_assign[out.product_id][1:]
if float_compare(qty_to_reserve, qty_done, precision_rounding=product_uom.rounding) == 0:
break
if not float_is_zero(qty_done, precision_rounding=product_uom.rounding):
sources_to_lines[source].append(self._prepare_report_line(qty_done, product_id, out, source[0], move_ins=self.env['stock.move'].browse(moves_in_ids)))
# draft qtys can be shown but not assigned
qty_expected = product_to_qty_draft.get(product_id, 0)
if float_compare(qty_to_reserve, qty_done, precision_rounding=product_uom.rounding) > 0 and\
not float_is_zero(qty_expected, precision_rounding=product_uom.rounding):
to_expect = min(qty_expected, qty_to_reserve - qty_done)
sources_to_lines[source].append(self._prepare_report_line(to_expect, product_id, out, source[0], is_qty_assignable=False))
product_to_qty_draft[product_id] -= to_expect
# show already assigned moves
for product_id, qty_and_ins in product_to_total_assigned.items():
total_assigned = qty_and_ins[0]
moves_in = self.env['stock.move'].browse(qty_and_ins[1])
out_moves = moves_in.move_dest_ids
for out_move in out_moves:
if float_is_zero(total_assigned, precision_rounding=out_move.product_id.uom_id.rounding):
# it is possible there are different in moves linked to the same out moves due to batch
# => we guess as to which outs correspond to this report...
continue
source = (out_move._get_source_document(),)
if not source:
continue
if out_move.picking_id and source[0] != out_move.picking_id:
source = (out_move.picking_id, source[0])
qty_assigned = min(total_assigned, out_move.product_qty)
sources_to_lines[source].append(
self._prepare_report_line(qty_assigned, product_id, out_move, source[0], is_assigned=True, move_ins=moves_in))
# dates aren't auto-formatted when printed in report :(
sources_to_formatted_scheduled_date = defaultdict(list)
for source, dummy in sources_to_lines.items():
sources_to_formatted_scheduled_date[source] = self._get_formatted_scheduled_date(source[0])
return {
'data': data,
'doc_ids': docids,
'doc_model': 'stock.picking',
'sources_to_lines': sources_to_lines,
'precision': self.env['decimal.precision'].precision_get('Product Unit of Measure'),
'pickings': pickings,
'sources_to_formatted_scheduled_date': sources_to_formatted_scheduled_date,
}
def _prepare_report_line(self, quantity, product, move_out, source=False, is_assigned=False, is_qty_assignable=True, move_ins=False):
return {
'source': source,
'product': {
'id': product.id,
'display_name': product.display_name
},
'uom': product.uom_id.display_name,
'quantity': quantity,
'is_qty_assignable': is_qty_assignable,
'move_out': move_out,
'is_assigned': is_assigned,
'move_ins': move_ins and move_ins.ids or False,
}
def _get_formatted_scheduled_date(self, source):
""" Unfortunately different source record types have different field names for their "Scheduled Date"
Therefore an extendable method is needed.
"""
if source._name == 'stock.picking':
return format_date(self.env, source.scheduled_date)
return False
def action_assign(self, move_ids, qtys, in_ids):
""" Assign picking move(s) [i.e. link] to other moves (i.e. make them MTO)
:param move_id ids: the ids of the moves to make MTO
:param qtys list: the quantities that are being assigned to the move_ids (in same order as move_ids)
:param in_ids ids: the ids of the moves that are to be assigned to move_ids
"""
outs = self.env['stock.move'].browse(move_ids)
# Split outs with only part of demand assigned to prevent reservation problems later on.
# We do this first so we can create their split moves in batch
out_to_new_out = OrderedDict()
new_move_vals = []
for out, qty_to_link in zip(outs, qtys):
if float_compare(out.product_qty, qty_to_link, precision_rounding=out.product_id.uom_id.rounding) == 1:
new_move_vals += out._split(out.product_qty - qty_to_link)
out_to_new_out[out.id] = self.env['stock.move']
new_outs = self.env['stock.move'].create(new_move_vals)
# don't do action confirm to avoid creating additional unintentional reservations
new_outs.write({'state': 'confirmed'})
for i, k in enumerate(out_to_new_out.keys()):
out_to_new_out[k] = new_outs[i]
for out, qty_to_link, ins in zip(outs, qtys, in_ids):
potential_ins = self.env['stock.move'].browse(ins)
if out.id in out_to_new_out:
new_out = out_to_new_out[out.id]
if potential_ins[0].state != 'done' and out.reserved_availability:
# let's assume if 1 of the potential_ins isn't done, then none of them are => we are only assigning the not-reserved
# qty and the new move should have all existing reserved quants (i.e. move lines) assigned to it
out.move_line_ids.move_id = new_out
elif potential_ins[0].state == 'done' and out.reserved_availability > qty_to_link:
# let's assume if 1 of the potential_ins is done, then all of them are => we can link them to already reserved moves, but we
# need to make sure the reserved qtys still match the demand amount the move (we're assigning).
out.move_line_ids.move_id = new_out
assigned_amount = 0
for move_line_id in new_out.move_line_ids:
if assigned_amount + move_line_id.product_qty > qty_to_link:
new_move_line = move_line_id.copy({'product_uom_qty': 0, 'qty_done': 0})
new_move_line.product_uom_qty = move_line_id.product_uom_qty
move_line_id.product_uom_qty = out.product_id.uom_id._compute_quantity(qty_to_link - assigned_amount, out.product_uom, rounding_method='HALF-UP')
new_move_line.product_uom_qty -= out.product_id.uom_id._compute_quantity(move_line_id.product_qty, out.product_uom, rounding_method='HALF-UP')
move_line_id.move_id = out
assigned_amount += move_line_id.product_qty
if float_compare(assigned_amount, qty_to_link, precision_rounding=out.product_id.uom_id.rounding) == 0:
break
for in_move in reversed(potential_ins):
quantity_remaining = in_move.product_qty - sum(in_move.move_dest_ids.mapped('product_qty'))
if in_move.product_id != out.product_id or float_compare(0, quantity_remaining, precision_rounding=in_move.product_id.uom_id.rounding) >= 0:
# in move is already completely linked (e.g. during another assign click) => don't count it again
potential_ins = potential_ins[1:]
continue
linked_qty = min(in_move.product_qty, qty_to_link)
in_move.move_dest_ids |= out
out.procure_method = 'make_to_order'
quantity_remaining -= linked_qty
qty_to_link -= linked_qty
if float_is_zero(qty_to_link, precision_rounding=out.product_id.uom_id.rounding):
break # we have satistfied the qty_to_link
(outs | new_outs)._recompute_state()
# always try to auto-assign to prevent another move from reserving the quant if incoming move is done
self.env['stock.move'].browse(move_ids)._action_assign()
def action_unassign(self, move_id, qty, in_ids):
""" Unassign moves [i.e. unlink] from a move (i.e. make non-MTO)
:param move_id id: the id of the move to make non-MTO
:param qty float: the total quantity that is being unassigned from move_id
:param in_ids ids: the ids of the moves that are to be unassigned from move_id
"""
out = self.env['stock.move'].browse(move_id)
ins = self.env['stock.move'].browse(in_ids)
amount_unassigned = 0
for in_move in ins:
if out.id not in in_move.move_dest_ids.ids:
continue
in_move.move_dest_ids -= out
amount_unassigned += min(qty, in_move.product_qty)
if float_compare(qty, amount_unassigned, precision_rounding=out.product_id.uom_id.rounding) <= 0:
break
if out.move_orig_ids and out.state != 'done':
# annoying use cases where we need to split the out move:
# 1. batch reserved + individual picking unreserved
# 2. moves linked from backorder generation
total_still_linked = sum(out.move_orig_ids.mapped('product_qty'))
new_move_vals = out._split(out.product_qty - total_still_linked)
if new_move_vals:
new_move_vals[0]['procure_method'] = 'make_to_order'
new_out = self.env['stock.move'].create(new_move_vals)
# don't do action confirm to avoid creating additional unintentional reservations
new_out.write({'state': 'confirmed'})
out.move_line_ids.move_id = new_out
(out | new_out)._compute_reserved_availability()
if new_out.reserved_availability > new_out.product_qty:
# extra reserved amount goes to no longer linked out
reserved_amount_to_remain = new_out.reserved_availability - new_out.product_qty
for move_line_id in new_out.move_line_ids:
if reserved_amount_to_remain <= 0:
break
if move_line_id.product_qty > reserved_amount_to_remain:
new_move_line = move_line_id.copy({'product_uom_qty': 0, 'qty_done': 0})
new_move_line.product_uom_qty = out.product_id.uom_id._compute_quantity(move_line_id.product_qty - reserved_amount_to_remain, move_line_id.product_uom_id, rounding_method='HALF-UP')
move_line_id.product_uom_qty -= new_move_line.product_uom_qty
new_move_line.move_id = out
break
else:
move_line_id.move_id = out
reserved_amount_to_remain -= move_line_id.product_qty
(out | new_out)._compute_reserved_availability()
out.move_orig_ids = False
new_out._recompute_state()
out.procure_method = 'make_to_stock'
out._recompute_state()
return True
| 57.596026
| 17,394
|
13,866
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import defaultdict
from odoo import api, models
from odoo.tools import float_compare, float_is_zero, format_date, float_round
class ReplenishmentReport(models.AbstractModel):
_name = 'report.stock.report_product_product_replenishment'
_description = "Stock Replenishment Report"
def _product_domain(self, product_template_ids, product_variant_ids):
if product_template_ids:
return [('product_tmpl_id', 'in', product_template_ids)]
return [('product_id', 'in', product_variant_ids)]
def _move_domain(self, product_template_ids, product_variant_ids, wh_location_ids):
move_domain = self._product_domain(product_template_ids, product_variant_ids)
move_domain += [('product_uom_qty', '!=', 0)]
out_domain = move_domain + [
'&',
('location_id', 'in', wh_location_ids),
('location_dest_id', 'not in', wh_location_ids),
]
in_domain = move_domain + [
'&',
('location_id', 'not in', wh_location_ids),
('location_dest_id', 'in', wh_location_ids),
]
return in_domain, out_domain
def _move_draft_domain(self, product_template_ids, product_variant_ids, wh_location_ids):
in_domain, out_domain = self._move_domain(product_template_ids, product_variant_ids, wh_location_ids)
in_domain += [('state', '=', 'draft')]
out_domain += [('state', '=', 'draft')]
return in_domain, out_domain
def _move_confirmed_domain(self, product_template_ids, product_variant_ids, wh_location_ids):
in_domain, out_domain = self._move_domain(product_template_ids, product_variant_ids, wh_location_ids)
out_domain += [('state', 'in', ['waiting', 'assigned', 'confirmed', 'partially_available'])]
in_domain += [('state', 'in', ['waiting', 'assigned', 'confirmed', 'partially_available'])]
return in_domain, out_domain
def _compute_draft_quantity_count(self, product_template_ids, product_variant_ids, wh_location_ids):
in_domain, out_domain = self._move_draft_domain(product_template_ids, product_variant_ids, wh_location_ids)
incoming_moves = self.env['stock.move'].read_group(in_domain, ['product_qty:sum'], 'product_id')
outgoing_moves = self.env['stock.move'].read_group(out_domain, ['product_qty:sum'], 'product_id')
in_sum = sum(move['product_qty'] for move in incoming_moves)
out_sum = sum(move['product_qty'] for move in outgoing_moves)
return {
'draft_picking_qty': {
'in': in_sum,
'out': out_sum
},
'qty': {
'in': in_sum,
'out': out_sum
}
}
@api.model
def _get_report_values(self, docids, data=None):
return {
'data': data,
'doc_ids': docids,
'doc_model': 'product.product',
'docs': self._get_report_data(product_variant_ids=docids),
'precision': self.env['decimal.precision'].precision_get('Product Unit of Measure'),
}
def _get_report_data(self, product_template_ids=False, product_variant_ids=False):
assert product_template_ids or product_variant_ids
res = {}
if self.env.context.get('warehouse'):
warehouse = self.env['stock.warehouse'].browse(self.env.context.get('warehouse'))
else:
warehouse = self.env['stock.warehouse'].browse(self.get_warehouses()[0]['id'])
wh_location_ids = [loc['id'] for loc in self.env['stock.location'].search_read(
[('id', 'child_of', warehouse.view_location_id.id)],
['id'],
)]
# Get the products we're working, fill the rendering context with some of their attributes.
if product_template_ids:
product_templates = self.env['product.template'].browse(product_template_ids)
res['product_templates'] = product_templates
res['product_variants'] = product_templates.product_variant_ids
res['multiple_product'] = len(product_templates.product_variant_ids) > 1
res['uom'] = product_templates[:1].uom_id.display_name
res['quantity_on_hand'] = sum(product_templates.mapped('qty_available'))
res['virtual_available'] = sum(product_templates.mapped('virtual_available'))
elif product_variant_ids:
product_variants = self.env['product.product'].browse(product_variant_ids)
res['product_templates'] = False
res['product_variants'] = product_variants
res['multiple_product'] = len(product_variants) > 1
res['uom'] = product_variants[:1].uom_id.display_name
res['quantity_on_hand'] = sum(product_variants.mapped('qty_available'))
res['virtual_available'] = sum(product_variants.mapped('virtual_available'))
res.update(self._compute_draft_quantity_count(product_template_ids, product_variant_ids, wh_location_ids))
res['lines'] = self._get_report_lines(product_template_ids, product_variant_ids, wh_location_ids)
return res
def _prepare_report_line(self, quantity, move_out=None, move_in=None, replenishment_filled=True, product=False, reservation=False):
product = product or (move_out.product_id if move_out else move_in.product_id)
is_late = move_out.date < move_in.date if (move_out and move_in) else False
move_to_match_ids = self.env.context.get('move_to_match_ids') or []
move_in_id = move_in.id if move_in else None
move_out_id = move_out.id if move_out else None
return {
'document_in': move_in._get_source_document() if move_in else False,
'document_out': move_out._get_source_document() if move_out else False,
'product': {
'id': product.id,
'display_name': product.display_name
},
'replenishment_filled': replenishment_filled,
'uom_id': product.uom_id,
'receipt_date': format_date(self.env, move_in.date) if move_in else False,
'delivery_date': format_date(self.env, move_out.date) if move_out else False,
'is_late': is_late,
'quantity': float_round(quantity, precision_rounding=product.uom_id.rounding),
'move_out': move_out,
'move_in': move_in,
'reservation': reservation,
'is_matched': any(move_id in [move_in_id, move_out_id] for move_id in move_to_match_ids),
}
def _get_report_lines(self, product_template_ids, product_variant_ids, wh_location_ids):
def _reconcile_out_with_ins(lines, out, ins, demand, product_rounding, only_matching_move_dest=True):
index_to_remove = []
for index, in_ in enumerate(ins):
if float_is_zero(in_['qty'], precision_rounding=product_rounding):
index_to_remove.append(index)
continue
if only_matching_move_dest and in_['move_dests'] and out.id not in in_['move_dests']:
continue
taken_from_in = min(demand, in_['qty'])
demand -= taken_from_in
lines.append(self._prepare_report_line(taken_from_in, move_in=in_['move'], move_out=out))
in_['qty'] -= taken_from_in
if in_['qty'] <= 0:
index_to_remove.append(index)
if float_is_zero(demand, precision_rounding=product_rounding):
break
for index in reversed(index_to_remove):
del ins[index]
return demand
in_domain, out_domain = self._move_confirmed_domain(
product_template_ids, product_variant_ids, wh_location_ids
)
outs = self.env['stock.move'].search(out_domain, order='reservation_date, priority desc, date, id')
outs_per_product = defaultdict(list)
reserved_outs = self.env['stock.move']
reserved_outs_quantitites = defaultdict(float)
reserved_outs_per_product = defaultdict(list)
outs_reservation = {}
for out in outs:
outs_per_product[out.product_id.id].append(out)
out_qty_reserved = 0
moves_orig = out._get_moves_orig()
for move in moves_orig:
rounding = move.product_id.uom_id.rounding
move_qty_reserved = sum(move.move_line_ids.mapped('product_qty'))
if float_is_zero(move_qty_reserved, precision_rounding=rounding):
continue
already_used_qty = reserved_outs_quantitites.get(move, 0)
remaining_qty = move_qty_reserved - already_used_qty
if float_compare(remaining_qty, 0, precision_rounding=rounding) <= 0:
continue
qty_reserved = min(remaining_qty, out.product_qty - out_qty_reserved)
out_qty_reserved += qty_reserved
reserved_outs_quantitites[move] += qty_reserved
if float_compare(out_qty_reserved, out.product_qty, precision_rounding=rounding) >= 0:
break
if not float_is_zero(out_qty_reserved, out.product_id.uom_id.rounding):
reserved_outs |= out
reserved_outs_per_product[out.product_id.id].append(out)
outs_reservation[out.id] = out_qty_reserved
# Different sort than unreserved outs
reserved_outs = self.env['stock.move'].search([('id', 'in', reserved_outs.ids)], order="priority desc, date, id")
ins = self.env['stock.move'].search(in_domain, order='priority desc, date, id')
ins_per_product = defaultdict(list)
for in_ in ins:
ins_per_product[in_.product_id.id].append({
'qty': in_.product_qty,
'move': in_,
'move_dests': in_._rollup_move_dests(set())
})
currents = outs.product_id._get_only_qty_available()
lines = []
for product in (ins | outs).product_id:
product_rounding = product.uom_id.rounding
for out in reserved_outs_per_product[product.id]:
# Reconcile with reserved stock.
reserved = outs_reservation[out.id]
current = currents[product.id]
currents[product.id] -= reserved
lines.append(self._prepare_report_line(reserved, move_out=out, reservation=True))
unreconciled_outs = []
for out in outs_per_product[product.id]:
reserved_availability = outs_reservation.get(out.id, 0)
# Reconcile with the current stock.
reserved = 0.0
if not float_is_zero(reserved_availability, precision_rounding=product_rounding):
reserved = reserved_availability
demand = out.product_qty - reserved
if float_is_zero(demand, precision_rounding=product_rounding):
continue
current = currents[product.id]
taken_from_stock = min(demand, current)
if not float_is_zero(taken_from_stock, precision_rounding=product_rounding):
currents[product.id] -= taken_from_stock
demand -= taken_from_stock
lines.append(self._prepare_report_line(taken_from_stock, move_out=out))
# Reconcile with the ins.
if not float_is_zero(demand, precision_rounding=product_rounding):
demand = _reconcile_out_with_ins(lines, out, ins_per_product[product.id], demand, product_rounding, only_matching_move_dest=True)
if not float_is_zero(demand, precision_rounding=product_rounding):
unreconciled_outs.append((demand, out))
# Another pass, in case there are some ins linked to a dest move but that still have some quantity available
for (demand, out) in unreconciled_outs:
demand = _reconcile_out_with_ins(lines, out, ins_per_product[product.id], demand, product_rounding, only_matching_move_dest=False)
if not float_is_zero(demand, precision_rounding=product_rounding):
# Not reconciled
lines.append(self._prepare_report_line(demand, move_out=out, replenishment_filled=False))
# Unused remaining stock.
free_stock = currents.get(product.id, 0)
if not float_is_zero(free_stock, precision_rounding=product_rounding):
lines.append(self._prepare_report_line(free_stock, product=product))
# In moves not used.
for in_ in ins_per_product[product.id]:
if float_is_zero(in_['qty'], precision_rounding=product_rounding):
continue
lines.append(self._prepare_report_line(in_['qty'], move_in=in_['move']))
return lines
@api.model
def get_warehouses(self):
return self.env['stock.warehouse'].search_read(fields=['id', 'name', 'code'])
class ReplenishmentTemplateReport(models.AbstractModel):
_name = 'report.stock.report_product_template_replenishment'
_description = "Stock Replenishment Report"
_inherit = 'report.stock.report_product_product_replenishment'
@api.model
def _get_report_values(self, docids, data=None):
return {
'data': data,
'doc_ids': docids,
'doc_model': 'product.product',
'docs': self._get_report_data(product_template_ids=docids),
'precision': self.env['decimal.precision'].precision_get('Product Unit of Measure'),
}
| 51.546468
| 13,866
|
1,310
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import defaultdict
from odoo import _, models
from odoo.exceptions import UserError
class ReportProductLabel(models.AbstractModel):
_name = 'report.stock.label_product_product_view'
_description = 'Product Label Report'
def _get_report_values(self, docids, data):
if data.get('active_model') == 'product.template':
Product = self.env['product.template']
elif data.get('active_model') == 'product.product':
Product = self.env['product.product']
else:
raise UserError(_('Product model not defined, Please contact your administrator.'))
quantity_by_product = defaultdict(list)
for p, q in data.get('quantity_by_product').items():
product = Product.browse(int(p))
quantity_by_product[product].append((product.barcode, q))
if data.get('custom_barcodes'):
# we expect custom barcodes to be: {product: [(barcode, qty_of_barcode)]}
for product, barcodes_qtys in data.get('custom_barcodes').items():
quantity_by_product[Product.browse(int(product))] += (barcodes_qtys)
data['quantity'] = quantity_by_product
return data
| 40.9375
| 1,310
|
1,547
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
import werkzeug
from werkzeug.exceptions import InternalServerError
from odoo import http
from odoo.http import request
from odoo.addons.web.controllers.main import _serialize_exception
from odoo.tools.misc import html_escape
import json
class StockReportController(http.Controller):
@http.route('/stock/<string:output_format>/<string:report_name>', type='http', auth='user')
def report(self, output_format, report_name=False, **kw):
uid = request.session.uid
domain = [('create_uid', '=', uid)]
stock_traceability = request.env['stock.traceability.report'].with_user(uid).search(domain, limit=1)
line_data = json.loads(kw['data'])
try:
if output_format == 'pdf':
response = request.make_response(
stock_traceability.with_context(active_id=kw['active_id'], active_model=kw['active_model']).get_pdf(line_data),
headers=[
('Content-Type', 'application/pdf'),
('Content-Disposition', 'attachment; filename=' + 'stock_traceability' + '.pdf;')
]
)
return response
except Exception as e:
se = _serialize_exception(e)
error = {
'code': 200,
'message': 'Odoo Server Error',
'data': se
}
res = request.make_response(html_escape(json.dumps(error)))
raise InternalServerError(response=res) from e
| 39.666667
| 1,547
|
865
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Resource',
'version': '1.1',
'category': 'Hidden',
'description': """
Module for resource management.
===============================
A resource represent something that can be scheduled (a developer on a task or a
work center on manufacturing orders). This module manages a resource calendar
associated to every resource. It also manages the leaves of every resource.
""",
'depends': ['base', 'web'],
'data': [
'data/resource_data.xml',
'security/ir.model.access.csv',
'security/resource_security.xml',
'views/resource_views.xml',
],
'demo': [
],
'assets': {
'web.assets_backend': [
'resource/static/**/*',
],
},
'license': 'LGPL-3',
}
| 27.903226
| 865
|
55,091
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import date, datetime
from freezegun import freeze_time
from pytz import timezone, utc
from odoo import fields
from odoo.exceptions import ValidationError
from odoo.addons.resource.models.resource import Intervals
from odoo.addons.resource.tests.common import TestResourceCommon
from odoo.tests.common import TransactionCase
def datetime_tz(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None):
""" Return a `datetime` object with a given timezone (if given). """
dt = datetime(year, month, day, hour, minute, second, microsecond)
return timezone(tzinfo).localize(dt) if tzinfo else dt
def datetime_str(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None):
""" Return a fields.Datetime value with the given timezone. """
dt = datetime(year, month, day, hour, minute, second, microsecond)
if tzinfo:
dt = timezone(tzinfo).localize(dt).astimezone(utc)
return fields.Datetime.to_string(dt)
class TestIntervals(TransactionCase):
def ints(self, pairs):
recs = self.env['base']
return [(a, b, recs) for a, b in pairs]
def test_union(self):
def check(a, b):
a, b = self.ints(a), self.ints(b)
self.assertEqual(list(Intervals(a)), b)
check([(1, 2), (3, 4)], [(1, 2), (3, 4)])
check([(1, 2), (2, 4)], [(1, 4)])
check([(1, 3), (2, 4)], [(1, 4)])
check([(1, 4), (2, 3)], [(1, 4)])
check([(3, 4), (1, 2)], [(1, 2), (3, 4)])
check([(2, 4), (1, 2)], [(1, 4)])
check([(2, 4), (1, 3)], [(1, 4)])
check([(2, 3), (1, 4)], [(1, 4)])
def test_intersection(self):
def check(a, b, c):
a, b, c = self.ints(a), self.ints(b), self.ints(c)
self.assertEqual(list(Intervals(a) & Intervals(b)), c)
check([(10, 20)], [(5, 8)], [])
check([(10, 20)], [(5, 10)], [])
check([(10, 20)], [(5, 15)], [(10, 15)])
check([(10, 20)], [(5, 20)], [(10, 20)])
check([(10, 20)], [(5, 25)], [(10, 20)])
check([(10, 20)], [(10, 15)], [(10, 15)])
check([(10, 20)], [(10, 20)], [(10, 20)])
check([(10, 20)], [(10, 25)], [(10, 20)])
check([(10, 20)], [(15, 18)], [(15, 18)])
check([(10, 20)], [(15, 20)], [(15, 20)])
check([(10, 20)], [(15, 25)], [(15, 20)])
check([(10, 20)], [(20, 25)], [])
check(
[(0, 5), (10, 15), (20, 25), (30, 35)],
[(6, 7), (9, 12), (13, 17), (22, 23), (24, 40)],
[(10, 12), (13, 15), (22, 23), (24, 25), (30, 35)],
)
def test_difference(self):
def check(a, b, c):
a, b, c = self.ints(a), self.ints(b), self.ints(c)
self.assertEqual(list(Intervals(a) - Intervals(b)), c)
check([(10, 20)], [(5, 8)], [(10, 20)])
check([(10, 20)], [(5, 10)], [(10, 20)])
check([(10, 20)], [(5, 15)], [(15, 20)])
check([(10, 20)], [(5, 20)], [])
check([(10, 20)], [(5, 25)], [])
check([(10, 20)], [(10, 15)], [(15, 20)])
check([(10, 20)], [(10, 20)], [])
check([(10, 20)], [(10, 25)], [])
check([(10, 20)], [(15, 18)], [(10, 15), (18, 20)])
check([(10, 20)], [(15, 20)], [(10, 15)])
check([(10, 20)], [(15, 25)], [(10, 15)])
check([(10, 20)], [(20, 25)], [(10, 20)])
check(
[(0, 5), (10, 15), (20, 25), (30, 35)],
[(6, 7), (9, 12), (13, 17), (22, 23), (24, 40)],
[(0, 5), (12, 13), (20, 22), (23, 24)],
)
class TestErrors(TestResourceCommon):
def setUp(self):
super(TestErrors, self).setUp()
def test_create_negative_leave(self):
# from > to
with self.assertRaises(ValidationError):
self.env['resource.calendar.leaves'].create({
'name': 'error cannot return in the past',
'resource_id': False,
'calendar_id': self.calendar_jean.id,
'date_from': datetime_str(2018, 4, 3, 20, 0, 0, tzinfo=self.jean.tz),
'date_to': datetime_str(2018, 4, 3, 0, 0, 0, tzinfo=self.jean.tz),
})
with self.assertRaises(ValidationError):
self.env['resource.calendar.leaves'].create({
'name': 'error caused by timezones',
'resource_id': False,
'calendar_id': self.calendar_jean.id,
'date_from': datetime_str(2018, 4, 3, 10, 0, 0, tzinfo='UTC'),
'date_to': datetime_str(2018, 4, 3, 12, 0, 0, tzinfo='Etc/GMT-6')
})
class TestCalendar(TestResourceCommon):
def setUp(self):
super(TestCalendar, self).setUp()
def test_get_work_hours_count(self):
self.env['resource.calendar.leaves'].create({
'name': 'Global Leave',
'resource_id': False,
'calendar_id': self.calendar_jean.id,
'date_from': datetime_str(2018, 4, 3, 0, 0, 0, tzinfo=self.jean.tz),
'date_to': datetime_str(2018, 4, 3, 23, 59, 59, tzinfo=self.jean.tz),
})
self.env['resource.calendar.leaves'].create({
'name': 'leave for Jean',
'calendar_id': self.calendar_jean.id,
'resource_id': self.jean.resource_id.id,
'date_from': datetime_str(2018, 4, 5, 0, 0, 0, tzinfo=self.jean.tz),
'date_to': datetime_str(2018, 4, 5, 23, 59, 59, tzinfo=self.jean.tz),
})
hours = self.calendar_jean.get_work_hours_count(
datetime_tz(2018, 4, 2, 0, 0, 0, tzinfo=self.jean.tz),
datetime_tz(2018, 4, 6, 23, 59, 59, tzinfo=self.jean.tz),
)
self.assertEqual(hours, 32)
hours = self.calendar_jean.get_work_hours_count(
datetime_tz(2018, 4, 2, 0, 0, 0, tzinfo=self.jean.tz),
datetime_tz(2018, 4, 6, 23, 59, 59, tzinfo=self.jean.tz),
compute_leaves=False,
)
self.assertEqual(hours, 40)
# leave of size 0
self.env['resource.calendar.leaves'].create({
'name': 'zero_length',
'calendar_id': self.calendar_patel.id,
'resource_id': False,
'date_from': datetime_str(2018, 4, 3, 0, 0, 0, tzinfo=self.patel.tz),
'date_to': datetime_str(2018, 4, 3, 0, 0, 0, tzinfo=self.patel.tz),
})
hours = self.calendar_patel.get_work_hours_count(
datetime_tz(2018, 4, 2, 0, 0, 0, tzinfo=self.patel.tz),
datetime_tz(2018, 4, 6, 23, 59, 59, tzinfo=self.patel.tz),
)
self.assertEqual(hours, 35)
# leave of medium size
leave = self.env['resource.calendar.leaves'].create({
'name': 'zero_length',
'calendar_id': self.calendar_patel.id,
'resource_id': False,
'date_from': datetime_str(2018, 4, 3, 9, 0, 0, tzinfo=self.patel.tz),
'date_to': datetime_str(2018, 4, 3, 12, 0, 0, tzinfo=self.patel.tz),
})
hours = self.calendar_patel.get_work_hours_count(
datetime_tz(2018, 4, 2, 0, 0, 0, tzinfo=self.patel.tz),
datetime_tz(2018, 4, 6, 23, 59, 59, tzinfo=self.patel.tz),
)
self.assertEqual(hours, 32)
leave.unlink()
# leave of very small size
leave = self.env['resource.calendar.leaves'].create({
'name': 'zero_length',
'calendar_id': self.calendar_patel.id,
'resource_id': False,
'date_from': datetime_str(2018, 4, 3, 0, 0, 0, tzinfo=self.patel.tz),
'date_to': datetime_str(2018, 4, 3, 0, 0, 10, tzinfo=self.patel.tz),
})
hours = self.calendar_patel.get_work_hours_count(
datetime_tz(2018, 4, 2, 0, 0, 0, tzinfo=self.patel.tz),
datetime_tz(2018, 4, 6, 23, 59, 59, tzinfo=self.patel.tz),
)
self.assertEqual(hours, 35)
leave.unlink()
# no timezone given should be converted to UTC
# Should equal to a leave between 2018/04/03 10:00:00 and 2018/04/04 10:00:00
leave = self.env['resource.calendar.leaves'].create({
'name': 'no timezone',
'calendar_id': self.calendar_patel.id,
'resource_id': False,
'date_from': datetime_str(2018, 4, 3, 4, 0, 0),
'date_to': datetime_str(2018, 4, 4, 4, 0, 0),
})
hours = self.calendar_patel.get_work_hours_count(
datetime_tz(2018, 4, 2, 0, 0, 0, tzinfo=self.patel.tz),
datetime_tz(2018, 4, 6, 23, 59, 59, tzinfo=self.patel.tz),
)
self.assertEqual(hours, 28)
hours = self.calendar_patel.get_work_hours_count(
datetime_tz(2018, 4, 2, 23, 59, 59, tzinfo=self.patel.tz),
datetime_tz(2018, 4, 2, 0, 0, 0, tzinfo=self.patel.tz),
)
self.assertEqual(hours, 0)
leave.unlink()
# 2 weeks calendar week 1
hours = self.calendar_jules.get_work_hours_count(
datetime_tz(2018, 4, 2, 0, 0, 0, tzinfo=self.jules.tz),
datetime_tz(2018, 4, 6, 23, 59, 59, tzinfo=self.jules.tz),
)
self.assertEqual(hours, 30)
# 2 weeks calendar week 1
hours = self.calendar_jules.get_work_hours_count(
datetime_tz(2018, 4, 16, 0, 0, 0, tzinfo=self.jules.tz),
datetime_tz(2018, 4, 20, 23, 59, 59, tzinfo=self.jules.tz),
)
self.assertEqual(hours, 30)
# 2 weeks calendar week 2
hours = self.calendar_jules.get_work_hours_count(
datetime_tz(2018, 4, 9, 0, 0, 0, tzinfo=self.jules.tz),
datetime_tz(2018, 4, 13, 23, 59, 59, tzinfo=self.jules.tz),
)
self.assertEqual(hours, 16)
# 2 weeks calendar week 2, leave during a day where he doesn't work this week
leave = self.env['resource.calendar.leaves'].create({
'name': 'Leave Jules week 2',
'calendar_id': self.calendar_jules.id,
'resource_id': False,
'date_from': datetime_str(2018, 4, 11, 4, 0, 0, tzinfo=self.jules.tz),
'date_to': datetime_str(2018, 4, 13, 4, 0, 0, tzinfo=self.jules.tz),
})
hours = self.calendar_jules.get_work_hours_count(
datetime_tz(2018, 4, 9, 0, 0, 0, tzinfo=self.jules.tz),
datetime_tz(2018, 4, 13, 23, 59, 59, tzinfo=self.jules.tz),
)
self.assertEqual(hours, 16)
leave.unlink()
# 2 weeks calendar week 2, leave during a day where he works this week
leave = self.env['resource.calendar.leaves'].create({
'name': 'Leave Jules week 2',
'calendar_id': self.calendar_jules.id,
'resource_id': False,
'date_from': datetime_str(2018, 4, 9, 0, 0, 0, tzinfo=self.jules.tz),
'date_to': datetime_str(2018, 4, 9, 23, 59, 0, tzinfo=self.jules.tz),
})
hours = self.calendar_jules.get_work_hours_count(
datetime_tz(2018, 4, 9, 0, 0, 0, tzinfo=self.jules.tz),
datetime_tz(2018, 4, 13, 23, 59, 59, tzinfo=self.jules.tz),
)
self.assertEqual(hours, 8)
leave.unlink()
# leave without calendar, should count for anyone in the company
leave = self.env['resource.calendar.leaves'].create({
'name': 'small leave',
'resource_id': False,
'date_from': datetime_str(2018, 4, 3, 9, 0, 0, tzinfo=self.patel.tz),
'date_to': datetime_str(2018, 4, 3, 12, 0, 0, tzinfo=self.patel.tz),
})
hours = self.calendar_patel.get_work_hours_count(
datetime_tz(2018, 4, 2, 0, 0, 0, tzinfo=self.patel.tz),
datetime_tz(2018, 4, 6, 23, 59, 59, tzinfo=self.patel.tz),
)
self.assertEqual(hours, 32)
# 2 weeks calendar with date_from and date_to to check work_hours
self.calendar_jules.write({
"attendance_ids": [
(5, 0, 0),
(0, 0, {
"name": "Monday (morning)",
"day_period": "morning",
"dayofweek": "0",
"week_type": "0",
"hour_from": 8.0,
"hour_to": 12.0,
"date_from": "2022-01-01",
"date_to": "2022-01-16"}),
(0, 0, {
"name": "Monday (morning)",
"day_period": "morning",
"dayofweek": "0",
"week_type": "0",
"hour_from": 8.0,
"hour_to": 12.0,
"date_from": "2022-01-17"}),
(0, 0, {
"name": "Monday (afternoon)",
"day_period": "afternoon",
"dayofweek": "0",
"week_type": "0",
"hour_from": 16.0,
"hour_to": 20.0,
"date_from": "2022-01-17"}),
(0, 0, {
"name": "Monday (morning)",
"day_period": "morning",
"dayofweek": "0",
"week_type": "1",
"hour_from": 8.0,
"hour_to": 12.0,
"date_from": "2022-01-01",
"date_to": "2022-01-16"}),
(0, 0, {
"name": "Monday (afternoon)",
"day_period": "afternoon",
"dayofweek": "0",
"week_type": "1",
"hour_from": 16.0,
"hour_to": 20.0,
"date_from": "2022-01-01",
"date_to": "2022-01-16"}),
(0, 0, {
"name": "Monday (morning)",
"day_period": "morning",
"dayofweek": "0",
"week_type": "1",
"hour_from": 8.0,
"hour_to": 12.0,
"date_from": "2022-01-17"}),
(0, 0, {
"name": "Monday (afternoon)",
"day_period": "afternoon",
"dayofweek": "0",
"week_type": "1",
"hour_from": 16.0,
"hour_to": 20.0,
"date_from": "2022-01-17"})]})
hours = self.calendar_jules.get_work_hours_count(
datetime_tz(2022, 1, 10, 0, 0, 0, tzinfo=self.jules.tz),
datetime_tz(2022, 1, 10, 23, 59, 59, tzinfo=self.jules.tz),
)
self.assertEqual(hours, 4)
hours = self.calendar_jules.get_work_hours_count(
datetime_tz(2022, 1, 17, 0, 0, 0, tzinfo=self.jules.tz),
datetime_tz(2022, 1, 17, 23, 59, 59, tzinfo=self.jules.tz),
)
self.assertEqual(hours, 8)
def test_calendar_working_hours_count(self):
calendar = self.env.ref('resource.resource_calendar_std_35h')
calendar.tz = 'UTC'
res = calendar.get_work_hours_count(
fields.Datetime.from_string('2017-05-03 14:03:00'), # Wednesday (8:00-12:00, 13:00-16:00)
fields.Datetime.from_string('2017-05-04 11:03:00'), # Thursday (8:00-12:00, 13:00-16:00)
compute_leaves=False)
self.assertEqual(res, 5.0)
def test_calendar_working_hours_24(self):
self.att_4 = self.env['resource.calendar.attendance'].create({
'name': 'Att4',
'calendar_id': self.calendar_jean.id,
'dayofweek': '2',
'hour_from': 0,
'hour_to': 24
})
res = self.calendar_jean.get_work_hours_count(
datetime_tz(2018, 6, 19, 23, 0, 0, tzinfo=self.jean.tz),
datetime_tz(2018, 6, 21, 1, 0, 0, tzinfo=self.jean.tz),
compute_leaves=True)
self.assertAlmostEqual(res, 24.0)
def test_plan_hours(self):
self.env['resource.calendar.leaves'].create({
'name': 'global',
'calendar_id': self.calendar_jean.id,
'resource_id': False,
'date_from': datetime_str(2018, 4, 11, 0, 0, 0, tzinfo=self.jean.tz),
'date_to': datetime_str(2018, 4, 11, 23, 59, 59, tzinfo=self.jean.tz),
})
time = self.calendar_jean.plan_hours(2, datetime_tz(2018, 4, 10, 0, 0, 0, tzinfo=self.jean.tz), compute_leaves=False)
self.assertEqual(time, datetime_tz(2018, 4, 10, 10, 0, 0, tzinfo=self.jean.tz))
time = self.calendar_jean.plan_hours(20, datetime_tz(2018, 4, 10, 0, 0, 0, tzinfo=self.jean.tz), compute_leaves=False)
self.assertEqual(time, datetime_tz(2018, 4, 12, 12, 0, 0, tzinfo=self.jean.tz))
time = self.calendar_jean.plan_hours(5, datetime_tz(2018, 4, 10, 15, 0, 0, tzinfo=self.jean.tz), compute_leaves=True)
self.assertEqual(time, datetime_tz(2018, 4, 12, 12, 0, 0, tzinfo=self.jean.tz))
# negative planning
time = self.calendar_jean.plan_hours(-10, datetime_tz(2018, 4, 10, 0, 0, 0, tzinfo=self.jean.tz), compute_leaves=True)
self.assertEqual(time, datetime_tz(2018, 4, 6, 14, 0, 0, tzinfo=self.jean.tz))
# zero planning with holidays
time = self.calendar_jean.plan_hours(0, datetime_tz(2018, 4, 11, 0, 0, 0, tzinfo=self.jean.tz), compute_leaves=True)
self.assertEqual(time, datetime_tz(2018, 4, 12, 8, 0, 0, tzinfo=self.jean.tz))
time = self.calendar_jean.plan_hours(0, datetime_tz(2018, 4, 10, 0, 0, 0, tzinfo=self.jean.tz), compute_leaves=False)
self.assertEqual(time, datetime_tz(2018, 4, 10, 8, 0, 0, tzinfo=self.jean.tz))
# very small planning
time = self.calendar_jean.plan_hours(0.0002, datetime_tz(2018, 4, 10, 0, 0, 0, tzinfo=self.jean.tz), compute_leaves=True)
self.assertEqual(time, datetime_tz(2018, 4, 10, 8, 0, 0, 720000, tzinfo=self.jean.tz))
# huge planning
time = self.calendar_jean.plan_hours(3000, datetime_tz(2018, 4, 10, 0, 0, 0, tzinfo=self.jean.tz), compute_leaves=False)
self.assertEqual(time, datetime_tz(2019, 9, 16, 16, 0, 0, tzinfo=self.jean.tz))
def test_plan_days(self):
self.env['resource.calendar.leaves'].create({
'name': 'global',
'calendar_id': self.calendar_jean.id,
'resource_id': False,
'date_from': datetime_str(2018, 4, 11, 0, 0, 0, tzinfo=self.jean.tz),
'date_to': datetime_str(2018, 4, 11, 23, 59, 59, tzinfo=self.jean.tz),
})
time = self.calendar_jean.plan_days(1, datetime_tz(2018, 4, 10, 0, 0, 0, tzinfo=self.jean.tz), compute_leaves=False)
self.assertEqual(time, datetime_tz(2018, 4, 10, 16, 0, 0, tzinfo=self.jean.tz))
time = self.calendar_jean.plan_days(3, datetime_tz(2018, 4, 10, 0, 0, 0, tzinfo=self.jean.tz), compute_leaves=False)
self.assertEqual(time, datetime_tz(2018, 4, 12, 16, 0, 0, tzinfo=self.jean.tz))
time = self.calendar_jean.plan_days(4, datetime_tz(2018, 4, 10, 16, 0, 0, tzinfo=self.jean.tz), compute_leaves=True)
self.assertEqual(time, datetime_tz(2018, 4, 17, 16, 0, 0, tzinfo=self.jean.tz))
# negative planning
time = self.calendar_jean.plan_days(-10, datetime_tz(2018, 4, 10, 0, 0, 0, tzinfo=self.jean.tz), compute_leaves=True)
self.assertEqual(time, datetime_tz(2018, 3, 27, 8, 0, 0, tzinfo=self.jean.tz))
# zero planning
time = self.calendar_jean.plan_days(0, datetime_tz(2018, 4, 10, 0, 0, 0, tzinfo=self.jean.tz), compute_leaves=True)
self.assertEqual(time, datetime_tz(2018, 4, 10, 0, 0, 0, tzinfo=self.jean.tz))
# very small planning returns False in this case
# TODO: decide if this behaviour is alright
time = self.calendar_jean.plan_days(0.0002, datetime_tz(2018, 4, 10, 0, 0, 0, tzinfo=self.jean.tz), compute_leaves=True)
self.assertEqual(time, False)
# huge planning
# TODO: Same as above
# NOTE: Maybe allow to set a max limit to the method
time = self.calendar_jean.plan_days(3000, datetime_tz(2018, 4, 10, 0, 0, 0, tzinfo=self.jean.tz), compute_leaves=False)
self.assertEqual(time, False)
def test_closest_time(self):
# Calendar:
# Tuesdays 8-16
# Fridays 8-13 and 16-23
dt = datetime_tz(2020, 4, 2, 7, 0, 0, tzinfo=self.john.tz)
calendar_dt = self.calendar_john._get_closest_work_time(dt)
self.assertFalse(calendar_dt, "It should not return any value for unattended days")
dt = datetime_tz(2020, 4, 3, 7, 0, 0, tzinfo=self.john.tz)
range_start = datetime_tz(2020, 4, 3, 8, 0, 0, tzinfo=self.john.tz)
range_end = datetime_tz(2020, 4, 3, 19, 0, 0, tzinfo=self.john.tz)
calendar_dt = self.calendar_john._get_closest_work_time(dt, search_range=(range_start, range_end))
self.assertFalse(calendar_dt, "It should not return any value if dt outside of range")
dt = datetime_tz(2020, 4, 3, 7, 0, 0, tzinfo=self.john.tz) # before
start = datetime_tz(2020, 4, 3, 8, 0, 0, tzinfo=self.john.tz)
calendar_dt = self.calendar_john._get_closest_work_time(dt)
self.assertEqual(calendar_dt, start, "It should return the start of the day")
dt = datetime_tz(2020, 4, 3, 10, 0, 0, tzinfo=self.john.tz) # after
start = datetime_tz(2020, 4, 3, 8, 0, 0, tzinfo=self.john.tz)
calendar_dt = self.calendar_john._get_closest_work_time(dt)
self.assertEqual(calendar_dt, start, "It should return the start of the closest attendance")
dt = datetime_tz(2020, 4, 3, 7, 0, 0, tzinfo=self.john.tz) # before
end = datetime_tz(2020, 4, 3, 13, 0, 0, tzinfo=self.john.tz)
calendar_dt = self.calendar_john._get_closest_work_time(dt, match_end=True)
self.assertEqual(calendar_dt, end, "It should return the end of the closest attendance")
dt = datetime_tz(2020, 4, 3, 14, 0, 0, tzinfo=self.john.tz) # after
end = datetime_tz(2020, 4, 3, 13, 0, 0, tzinfo=self.john.tz)
calendar_dt = self.calendar_john._get_closest_work_time(dt, match_end=True)
self.assertEqual(calendar_dt, end, "It should return the end of the closest attendance")
dt = datetime_tz(2020, 4, 3, 0, 0, 0, tzinfo=self.john.tz)
start = datetime_tz(2020, 4, 3, 8, 0, 0, tzinfo=self.john.tz)
calendar_dt = self.calendar_john._get_closest_work_time(dt)
self.assertEqual(calendar_dt, start, "It should return the start of the closest attendance")
dt = datetime_tz(2020, 4, 3, 23, 59, 59, tzinfo=self.john.tz)
end = datetime_tz(2020, 4, 3, 23, 0, 0, tzinfo=self.john.tz)
calendar_dt = self.calendar_john._get_closest_work_time(dt, match_end=True)
self.assertEqual(calendar_dt, end, "It should return the end of the closest attendance")
# with a resource specific attendance
self.env['resource.calendar.attendance'].create({
'name': 'Att4',
'calendar_id': self.calendar_john.id,
'dayofweek': '4',
'hour_from': 5,
'hour_to': 6,
'resource_id': self.john.resource_id.id,
})
dt = datetime_tz(2020, 4, 3, 5, 0, 0, tzinfo=self.john.tz)
start = datetime_tz(2020, 4, 3, 8, 0, 0, tzinfo=self.john.tz)
calendar_dt = self.calendar_john._get_closest_work_time(dt)
self.assertEqual(calendar_dt, start, "It should not take into account resouce specific attendances")
dt = datetime_tz(2020, 4, 3, 5, 0, 0, tzinfo=self.john.tz)
start = datetime_tz(2020, 4, 3, 5, 0, 0, tzinfo=self.john.tz)
calendar_dt = self.calendar_john._get_closest_work_time(dt, resource=self.john.resource_id)
self.assertEqual(calendar_dt, start, "It should have taken john's specific attendances")
dt = datetime_tz(2020, 4, 4, 1, 0, 0, tzinfo='UTC') # The next day in UTC, but still the 3rd in john's timezone (America/Los_Angeles)
start = datetime_tz(2020, 4, 3, 16, 0, 0, tzinfo=self.john.tz)
calendar_dt = self.calendar_john._get_closest_work_time(dt, resource=self.john.resource_id)
self.assertEqual(calendar_dt, start, "It should have found the attendance on the 3rd April")
def test_attendance_intervals_batch_tz(self):
# Calendar for Jean and Pierre:
# Europe/Brussels, Monday to Friday, 8->16
# resource TZ : Pierre in UTC, Jean in Europe/Brussels (from calendar)
pierre = self.env['resource.test'].create({
'name': 'Pierre',
'resource_calendar_id': self.calendar_jean.id,
'tz': 'UTC'
})
# Friday (summer): 7->15 UTC / 9->17 Europe/Brussels
start_dt = datetime_tz(2020, 4, 3, 7, 0, 0, tzinfo='UTC')
end_dt = datetime_tz(2020, 4, 3, 15, 0, 0, tzinfo='UTC')
resources = [self.jean.resource_id, pierre.resource_id]
common_calendar = pierre.resource_calendar_id
attendance_intervals = common_calendar._attendance_intervals_batch(start_dt, end_dt, resources)
jean_intervals = list(attendance_intervals[self.jean.resource_id.id])
pierre_intervals = list(attendance_intervals[pierre.resource_id.id])
# Intervals should take each resource tz into account separately
self.assertEqual(len(jean_intervals), 1)
self.assertEqual(jean_intervals[0][0], datetime_tz(2020, 4, 3, 9, 0, 0, tzinfo=self.jean.tz))
self.assertEqual(jean_intervals[0][1], datetime_tz(2020, 4, 3, 16, 0, 0, tzinfo=self.jean.tz))
self.assertEqual(len(pierre_intervals), 1)
self.assertEqual(pierre_intervals[0][0], datetime_tz(2020, 4, 3, 8, 0, 0, tzinfo=pierre.tz))
self.assertEqual(pierre_intervals[0][1], datetime_tz(2020, 4, 3, 15, 0, 0, tzinfo=pierre.tz))
class TestResMixin(TestResourceCommon):
def test_adjust_calendar(self):
# Calendar:
# Tuesdays 8-16
# Fridays 8-13 and 16-23
result = self.john._adjust_to_calendar(
datetime_tz(2020, 4, 3, 9, 0, 0, tzinfo=self.john.tz),
datetime_tz(2020, 4, 3, 14, 0, 0, tzinfo=self.john.tz),
)
self.assertEqual(result[self.john],(
datetime_tz(2020, 4, 3, 8, 0, 0, tzinfo=self.john.tz),
datetime_tz(2020, 4, 3, 13, 0, 0, tzinfo=self.john.tz),
))
result = self.john._adjust_to_calendar(
datetime_tz(2020, 4, 3, 13, 1, 0, tzinfo=self.john.tz),
datetime_tz(2020, 4, 3, 14, 0, 0, tzinfo=self.john.tz),
)
self.assertEqual(result[self.john],(
datetime_tz(2020, 4, 3, 16, 0, 0, tzinfo=self.john.tz),
datetime_tz(2020, 4, 3, 23, 0, 0, tzinfo=self.john.tz),
))
result = self.john._adjust_to_calendar(
datetime_tz(2020, 4, 4, 9, 0, 0, tzinfo=self.john.tz), # both a day without attendance
datetime_tz(2020, 4, 4, 14, 0, 0, tzinfo=self.john.tz),
)
self.assertEqual(result[self.john], (None, None))
result = self.john._adjust_to_calendar(
datetime_tz(2020, 4, 3, 8, 0, 0, tzinfo=self.john.tz),
datetime_tz(2020, 4, 4, 14, 0, 0, tzinfo=self.john.tz), # day without attendance
)
self.assertEqual(result[self.john], (
datetime_tz(2020, 4, 3, 8, 0, 0, tzinfo=self.john.tz),
None,
))
result = self.john._adjust_to_calendar(
datetime_tz(2020, 4, 2, 8, 0, 0, tzinfo=self.john.tz), # day without attendance
datetime_tz(2020, 4, 3, 14, 0, 0, tzinfo=self.john.tz),
)
self.assertEqual(result[self.john], (
None,
datetime_tz(2020, 4, 3, 13, 0, 0, tzinfo=self.john.tz),
))
# It should find the start and end within the search range
result = self.paul._adjust_to_calendar(
datetime_tz(2020, 4, 2, 2, 0, 0, tzinfo='UTC'),
datetime_tz(2020, 4, 3, 1, 59, 59, tzinfo='UTC'),
)
self.assertEqual(result[self.paul], (
datetime_tz(2020, 4, 2, 4, 0, tzinfo='UTC'),
datetime_tz(2020, 4, 2, 18, 0, tzinfo='UTC')
), "It should have found the start and end of the shift on the same day on April 2nd, 2020")
def test_adjust_calendar_timezone_before(self):
# Calendar:
# Every day 8-16
self.jean.tz = 'Japan'
self.calendar_jean.tz = 'Europe/Brussels'
result = self.jean._adjust_to_calendar(
datetime_tz(2020, 4, 1, 0, 0, 0, tzinfo='Japan'),
datetime_tz(2020, 4, 1, 23, 59, 59, tzinfo='Japan'),
)
self.assertEqual(result[self.jean], (
datetime_tz(2020, 4, 1, 8, 0, 0, tzinfo='Japan'),
datetime_tz(2020, 4, 1, 16, 0, 0, tzinfo='Japan'),
), "It should have found a starting time the 1st")
def test_adjust_calendar_timezone_after(self):
# Calendar:
# Tuesdays 8-16
# Fridays 8-13 and 16-23
tz = 'Europe/Brussels'
self.john.tz = tz
result = self.john._adjust_to_calendar(
datetime(2020, 4, 2, 23, 0, 0), # The previous day in UTC, but the 3rd in Europe/Brussels
datetime(2020, 4, 3, 20, 0, 0),
)
self.assertEqual(result[self.john], (
datetime(2020, 4, 3, 6, 0, 0),
datetime(2020, 4, 3, 21, 0, 0),
), "It should have found a starting time the 3rd")
def test_work_days_data(self):
# Looking at Jean's calendar
# Viewing it as Jean
data = self.jean._get_work_days_data_batch(
datetime_tz(2018, 4, 2, 0, 0, 0, tzinfo=self.jean.tz),
datetime_tz(2018, 4, 6, 16, 0, 0, tzinfo=self.jean.tz),
)[self.jean.id]
self.assertEqual(data, {'days': 5, 'hours': 40})
# Viewing it as Patel
# Views from 2018/04/01 20:00:00 to 2018/04/06 12:00:00
data = self.jean._get_work_days_data_batch(
datetime_tz(2018, 4, 2, 0, 0, 0, tzinfo=self.patel.tz),
datetime_tz(2018, 4, 6, 16, 0, 0, tzinfo=self.patel.tz),
)[self.jean.id]
self.assertEqual(data, {'days': 4.5, 'hours': 36}) # We see only 36 hours
# Viewing it as John
# Views from 2018/04/02 09:00:00 to 2018/04/07 02:00:00
data = self.jean._get_work_days_data_batch(
datetime_tz(2018, 4, 2, 0, 0, 0, tzinfo=self.john.tz),
datetime_tz(2018, 4, 6, 16, 0, 0, tzinfo=self.john.tz),
)[self.jean.id]
# still showing as 5 days because of rounding, but we see only 39 hours
self.assertEqual(data, {'days': 4.875, 'hours': 39})
# Looking at John's calendar
# Viewing it as Jean
# Views from 2018/04/01 15:00:00 to 2018/04/06 14:00:00
data = self.john._get_work_days_data_batch(
datetime_tz(2018, 4, 2, 0, 0, 0, tzinfo=self.jean.tz),
datetime_tz(2018, 4, 6, 23, 0, 0, tzinfo=self.jean.tz),
)[self.john.id]
self.assertEqual(data, {'days': 1.4375, 'hours': 13})
# Viewing it as Patel
# Views from 2018/04/01 11:00:00 to 2018/04/06 10:00:00
data = self.john._get_work_days_data_batch(
datetime_tz(2018, 4, 2, 0, 0, 0, tzinfo=self.patel.tz),
datetime_tz(2018, 4, 6, 23, 0, 0, tzinfo=self.patel.tz),
)[self.john.id]
self.assertEqual(data, {'days': 1.1875, 'hours': 10})
# Viewing it as John
data = self.john._get_work_days_data_batch(
datetime_tz(2018, 4, 2, 0, 0, 0, tzinfo=self.john.tz),
datetime_tz(2018, 4, 6, 23, 0, 0, tzinfo=self.john.tz),
)[self.john.id]
self.assertEqual(data, {'days': 2, 'hours': 20})
# using Jean as a timezone reference
data = self.john._get_work_days_data_batch(
datetime_tz(2018, 4, 2, 0, 0, 0, tzinfo=self.john.tz),
datetime_tz(2018, 4, 6, 23, 0, 0, tzinfo=self.john.tz),
calendar=self.calendar_jean,
)[self.john.id]
self.assertEqual(data, {'days': 5, 'hours': 40})
# half days
leave = self.env['resource.calendar.leaves'].create({
'name': 'half',
'calendar_id': self.calendar_jean.id,
'resource_id': self.jean.resource_id.id,
'date_from': datetime_str(2018, 4, 2, 10, 0, 0, tzinfo=self.jean.tz),
'date_to': datetime_str(2018, 4, 2, 14, 0, 0, tzinfo=self.jean.tz),
})
data = self.jean._get_work_days_data_batch(
datetime_tz(2018, 4, 2, 0, 0, 0, tzinfo=self.jean.tz),
datetime_tz(2018, 4, 6, 23, 0, 0, tzinfo=self.jean.tz),
)[self.jean.id]
self.assertEqual(data, {'days': 4.5, 'hours': 36})
# using John as a timezone reference, leaves are outside attendances
data = self.john._get_work_days_data_batch(
datetime_tz(2018, 4, 2, 0, 0, 0, tzinfo=self.john.tz),
datetime_tz(2018, 4, 6, 23, 0, 0, tzinfo=self.john.tz),
calendar=self.calendar_jean,
)[self.john.id]
self.assertEqual(data, {'days': 5, 'hours': 40})
leave.unlink()
# leave size 0
leave = self.env['resource.calendar.leaves'].create({
'name': 'zero',
'calendar_id': self.calendar_jean.id,
'resource_id': False,
'date_from': datetime_str(2018, 4, 2, 10, 0, 0, tzinfo=self.jean.tz),
'date_to': datetime_str(2018, 4, 2, 10, 0, 0, tzinfo=self.jean.tz),
})
data = self.jean._get_work_days_data_batch(
datetime_tz(2018, 4, 2, 0, 0, 0, tzinfo=self.jean.tz),
datetime_tz(2018, 4, 6, 23, 0, 0, tzinfo=self.jean.tz),
)[self.jean.id]
self.assertEqual(data, {'days': 5, 'hours': 40})
leave.unlink()
# leave very small size
leave = self.env['resource.calendar.leaves'].create({
'name': 'small',
'calendar_id': self.calendar_jean.id,
'resource_id': False,
'date_from': datetime_str(2018, 4, 2, 10, 0, 0, tzinfo=self.jean.tz),
'date_to': datetime_str(2018, 4, 2, 10, 0, 1, tzinfo=self.jean.tz),
})
data = self.jean._get_work_days_data_batch(
datetime_tz(2018, 4, 2, 0, 0, 0, tzinfo=self.jean.tz),
datetime_tz(2018, 4, 6, 23, 0, 0, tzinfo=self.jean.tz),
)[self.jean.id]
self.assertEqual(data['days'], 5)
self.assertAlmostEqual(data['hours'], 40, 2)
def test_leaves_days_data(self):
# Jean takes a leave
self.env['resource.calendar.leaves'].create({
'name': 'Jean is visiting India',
'calendar_id': self.jean.resource_calendar_id.id,
'resource_id': self.jean.resource_id.id,
'date_from': datetime_str(2018, 4, 10, 8, 0, 0, tzinfo=self.jean.tz),
'date_to': datetime_str(2018, 4, 10, 16, 0, 0, tzinfo=self.jean.tz),
})
# John takes a leave for Jean
self.env['resource.calendar.leaves'].create({
'name': 'Jean is comming in USA',
'calendar_id': self.jean.resource_calendar_id.id,
'resource_id': self.jean.resource_id.id,
'date_from': datetime_str(2018, 4, 12, 8, 0, 0, tzinfo=self.john.tz),
'date_to': datetime_str(2018, 4, 12, 16, 0, 0, tzinfo=self.john.tz),
})
# Jean asks to see how much leave he has taken
data = self.jean._get_leave_days_data_batch(
datetime_tz(2018, 4, 9, 0, 0, 0, tzinfo=self.jean.tz),
datetime_tz(2018, 4, 13, 23, 59, 59, tzinfo=self.jean.tz),
)[self.jean.id]
# Sees only 1 day and 8 hours because, as john is in UTC-7 the second leave is not in
# the attendances of Jean
self.assertEqual(data, {'days': 1, 'hours': 8})
# Patel Asks to see when Jean has taken some leaves
# Patel should see the same
data = self.jean._get_leave_days_data_batch(
datetime_tz(2018, 4, 9, 0, 0, 0, tzinfo=self.patel.tz),
datetime_tz(2018, 4, 13, 23, 59, 59, tzinfo=self.patel.tz),
)[self.jean.id]
self.assertEqual(data, {'days': 1, 'hours': 8})
# use Patel as a resource, jean's leaves are not visible
datas = self.patel._get_leave_days_data_batch(
datetime_tz(2018, 4, 9, 0, 0, 0, tzinfo=self.patel.tz),
datetime_tz(2018, 4, 13, 23, 59, 59, tzinfo=self.patel.tz),
calendar=self.calendar_jean,
)[self.patel.id]
self.assertEqual(datas['days'], 0)
self.assertEqual(datas['hours'], 0)
# Jean takes a leave for John
# Gives 3 hours (3/8 of a day)
self.env['resource.calendar.leaves'].create({
'name': 'John is sick',
'calendar_id': self.john.resource_calendar_id.id,
'resource_id': self.john.resource_id.id,
'date_from': datetime_str(2018, 4, 10, 0, 0, 0, tzinfo=self.jean.tz),
'date_to': datetime_str(2018, 4, 10, 20, 0, 0, tzinfo=self.jean.tz),
})
# John takes a leave
# Gives all day (12 hours)
self.env['resource.calendar.leaves'].create({
'name': 'John goes to holywood',
'calendar_id': self.john.resource_calendar_id.id,
'resource_id': self.john.resource_id.id,
'date_from': datetime_str(2018, 4, 13, 7, 0, 0, tzinfo=self.john.tz),
'date_to': datetime_str(2018, 4, 13, 18, 0, 0, tzinfo=self.john.tz),
})
# John asks how much leaves he has
# He sees that he has only 15 hours of leave in his attendances
data = self.john._get_leave_days_data_batch(
datetime_tz(2018, 4, 9, 0, 0, 0, tzinfo=self.john.tz),
datetime_tz(2018, 4, 13, 23, 59, 59, tzinfo=self.john.tz),
)[self.john.id]
self.assertEqual(data, {'days': 0.9375, 'hours': 10})
# half days
leave = self.env['resource.calendar.leaves'].create({
'name': 'half',
'calendar_id': self.calendar_jean.id,
'resource_id': self.jean.resource_id.id,
'date_from': datetime_str(2018, 4, 2, 10, 0, 0, tzinfo=self.jean.tz),
'date_to': datetime_str(2018, 4, 2, 14, 0, 0, tzinfo=self.jean.tz),
})
data = self.jean._get_leave_days_data_batch(
datetime_tz(2018, 4, 2, 0, 0, 0, tzinfo=self.jean.tz),
datetime_tz(2018, 4, 6, 23, 0, 0, tzinfo=self.jean.tz),
)[self.jean.id]
self.assertEqual(data, {'days': 0.5, 'hours': 4})
leave.unlink()
# leave size 0
leave = self.env['resource.calendar.leaves'].create({
'name': 'zero',
'calendar_id': self.calendar_jean.id,
'resource_id': False,
'date_from': datetime_str(2018, 4, 2, 10, 0, 0, tzinfo=self.jean.tz),
'date_to': datetime_str(2018, 4, 2, 10, 0, 0, tzinfo=self.jean.tz),
})
data = self.jean._get_leave_days_data_batch(
datetime_tz(2018, 4, 2, 0, 0, 0, tzinfo=self.jean.tz),
datetime_tz(2018, 4, 6, 23, 0, 0, tzinfo=self.jean.tz),
)[self.jean.id]
self.assertEqual(data, {'days': 0, 'hours': 0})
leave.unlink()
# leave very small size
leave = self.env['resource.calendar.leaves'].create({
'name': 'small',
'calendar_id': self.calendar_jean.id,
'resource_id': False,
'date_from': datetime_str(2018, 4, 2, 10, 0, 0, tzinfo=self.jean.tz),
'date_to': datetime_str(2018, 4, 2, 10, 0, 1, tzinfo=self.jean.tz),
})
data = self.jean._get_leave_days_data_batch(
datetime_tz(2018, 4, 2, 0, 0, 0, tzinfo=self.jean.tz),
datetime_tz(2018, 4, 6, 23, 0, 0, tzinfo=self.jean.tz),
)[self.jean.id]
self.assertEqual(data['days'], 0)
self.assertAlmostEqual(data['hours'], 0, 2)
leave.unlink()
def test_list_leaves(self):
jean_leave = self.env['resource.calendar.leaves'].create({
'name': "Jean's son is sick",
'calendar_id': self.jean.resource_calendar_id.id,
'resource_id': False,
'date_from': datetime_str(2018, 4, 10, 0, 0, 0, tzinfo=self.jean.tz),
'date_to': datetime_str(2018, 4, 10, 23, 59, 59, tzinfo=self.jean.tz),
})
leaves = self.jean.list_leaves(
datetime_tz(2018, 4, 9, 0, 0, 0, tzinfo=self.jean.tz),
datetime_tz(2018, 4, 13, 23, 59, 59, tzinfo=self.jean.tz),
)
self.assertEqual(leaves, [(date(2018, 4, 10), 8, jean_leave)])
# half days
leave = self.env['resource.calendar.leaves'].create({
'name': 'half',
'calendar_id': self.jean.resource_calendar_id.id,
'resource_id': self.jean.resource_id.id,
'date_from': datetime_str(2018, 4, 2, 10, 0, 0, tzinfo=self.jean.tz),
'date_to': datetime_str(2018, 4, 2, 14, 0, 0, tzinfo=self.jean.tz),
})
leaves = self.jean.list_leaves(
datetime_tz(2018, 4, 2, 0, 0, 0, tzinfo=self.jean.tz),
datetime_tz(2018, 4, 6, 23, 0, 0, tzinfo=self.jean.tz),
)
self.assertEqual(leaves, [(date(2018, 4, 2), 4, leave)])
leave.unlink()
# very small size
leave = self.env['resource.calendar.leaves'].create({
'name': 'small',
'calendar_id': self.jean.resource_calendar_id.id,
'resource_id': self.jean.resource_id.id,
'date_from': datetime_str(2018, 4, 2, 10, 0, 0, tzinfo=self.jean.tz),
'date_to': datetime_str(2018, 4, 2, 10, 0, 1, tzinfo=self.jean.tz),
})
leaves = self.jean.list_leaves(
datetime_tz(2018, 4, 2, 0, 0, 0, tzinfo=self.jean.tz),
datetime_tz(2018, 4, 6, 23, 0, 0, tzinfo=self.jean.tz),
)
self.assertEqual(len(leaves), 1)
self.assertEqual(leaves[0][0], date(2018, 4, 2))
self.assertAlmostEqual(leaves[0][1], 0, 2)
self.assertEqual(leaves[0][2].id, leave.id)
leave.unlink()
# size 0
leave = self.env['resource.calendar.leaves'].create({
'name': 'zero',
'calendar_id': self.jean.resource_calendar_id.id,
'resource_id': self.jean.resource_id.id,
'date_from': datetime_str(2018, 4, 2, 10, 0, 0, tzinfo=self.jean.tz),
'date_to': datetime_str(2018, 4, 2, 10, 0, 0, tzinfo=self.jean.tz),
})
leaves = self.jean.list_leaves(
datetime_tz(2018, 4, 2, 0, 0, 0, tzinfo=self.jean.tz),
datetime_tz(2018, 4, 6, 23, 0, 0, tzinfo=self.jean.tz),
)
self.assertEqual(leaves, [])
leave.unlink()
def test_list_work_time_per_day(self):
working_time = self.john.list_work_time_per_day(
datetime_tz(2018, 4, 9, 0, 0, 0, tzinfo=self.john.tz),
datetime_tz(2018, 4, 13, 23, 59, 59, tzinfo=self.john.tz),
)
self.assertEqual(working_time, [
(date(2018, 4, 10), 8),
(date(2018, 4, 13), 12),
])
# change john's resource's timezone
self.john.resource_id.tz = 'Europe/Brussels'
self.assertEqual(self.john.tz, 'Europe/Brussels')
self.assertEqual(self.calendar_john.tz, 'America/Los_Angeles')
working_time = self.john.list_work_time_per_day(
datetime_tz(2018, 4, 9, 0, 0, 0, tzinfo=self.john.tz),
datetime_tz(2018, 4, 13, 23, 59, 59, tzinfo=self.john.tz),
)
self.assertEqual(working_time, [
(date(2018, 4, 10), 8),
(date(2018, 4, 13), 12),
])
# half days
leave = self.env['resource.calendar.leaves'].create({
'name': 'small',
'calendar_id': self.jean.resource_calendar_id.id,
'resource_id': self.jean.resource_id.id,
'date_from': datetime_str(2018, 4, 2, 10, 0, 0, tzinfo=self.jean.tz),
'date_to': datetime_str(2018, 4, 2, 14, 0, 0, tzinfo=self.jean.tz),
})
working_time = self.jean.list_work_time_per_day(
datetime_tz(2018, 4, 2, 0, 0, 0, tzinfo=self.jean.tz),
datetime_tz(2018, 4, 6, 23, 0, 0, tzinfo=self.jean.tz),
)
self.assertEqual(working_time, [
(date(2018, 4, 2), 4),
(date(2018, 4, 3), 8),
(date(2018, 4, 4), 8),
(date(2018, 4, 5), 8),
(date(2018, 4, 6), 8),
])
leave.unlink()
# very small size
leave = self.env['resource.calendar.leaves'].create({
'name': 'small',
'calendar_id': self.jean.resource_calendar_id.id,
'resource_id': self.jean.resource_id.id,
'date_from': datetime_str(2018, 4, 2, 10, 0, 0, tzinfo=self.jean.tz),
'date_to': datetime_str(2018, 4, 2, 10, 0, 1, tzinfo=self.jean.tz),
})
working_time = self.jean.list_work_time_per_day(
datetime_tz(2018, 4, 2, 0, 0, 0, tzinfo=self.jean.tz),
datetime_tz(2018, 4, 6, 23, 0, 0, tzinfo=self.jean.tz),
)
self.assertEqual(len(working_time), 5)
self.assertEqual(working_time[0][0], date(2018, 4, 2))
self.assertAlmostEqual(working_time[0][1], 8, 2)
leave.unlink()
# size 0
leave = self.env['resource.calendar.leaves'].create({
'name': 'zero',
'calendar_id': self.jean.resource_calendar_id.id,
'resource_id': self.jean.resource_id.id,
'date_from': datetime_str(2018, 4, 2, 10, 0, 0, tzinfo=self.jean.tz),
'date_to': datetime_str(2018, 4, 2, 10, 0, 0, tzinfo=self.jean.tz),
})
working_time = self.jean.list_work_time_per_day(
datetime_tz(2018, 4, 2, 0, 0, 0, tzinfo=self.jean.tz),
datetime_tz(2018, 4, 6, 23, 0, 0, tzinfo=self.jean.tz),
)
self.assertEqual(working_time, [
(date(2018, 4, 2), 8),
(date(2018, 4, 3), 8),
(date(2018, 4, 4), 8),
(date(2018, 4, 5), 8),
(date(2018, 4, 6), 8),
])
leave.unlink()
class TestTimezones(TestResourceCommon):
def setUp(self):
super(TestTimezones, self).setUp()
self.tz1 = 'Etc/GMT+6'
self.tz2 = 'Europe/Brussels'
self.tz3 = 'Etc/GMT-10'
self.tz4 = 'Etc/GMT+10'
def test_work_hours_count(self):
# When no timezone => UTC
count = self.calendar_jean.get_work_hours_count(
datetime_tz(2018, 4, 10, 8, 0, 0),
datetime_tz(2018, 4, 10, 12, 0, 0),
)
self.assertEqual(count, 4)
# This timezone is not the same as the calendar's one
count = self.calendar_jean.get_work_hours_count(
datetime_tz(2018, 4, 10, 8, 0, 0, tzinfo=self.tz1),
datetime_tz(2018, 4, 10, 12, 0, 0, tzinfo=self.tz1),
)
self.assertEqual(count, 0)
# Using two different timezones
# 10-04-2018 06:00:00 - 10-04-2018 02:00:00
count = self.calendar_jean.get_work_hours_count(
datetime_tz(2018, 4, 10, 8, 0, 0, tzinfo=self.tz2),
datetime_tz(2018, 4, 10, 12, 0, 0, tzinfo=self.tz3),
)
self.assertEqual(count, 0)
# Using two different timezones
# 2018-4-10 06:00:00 - 2018-4-10 22:00:00
count = self.calendar_jean.get_work_hours_count(
datetime_tz(2018, 4, 10, 8, 0, 0, tzinfo=self.tz2),
datetime_tz(2018, 4, 10, 12, 0, 0, tzinfo=self.tz4),
)
self.assertEqual(count, 8)
def test_plan_hours(self):
dt = self.calendar_jean.plan_hours(10, datetime_tz(2018, 4, 10, 8, 0, 0))
self.assertEqual(dt, datetime_tz(2018, 4, 11, 10, 0, 0))
dt = self.calendar_jean.plan_hours(10, datetime_tz(2018, 4, 10, 8, 0, 0, tzinfo=self.tz4))
self.assertEqual(dt, datetime_tz(2018, 4, 11, 22, 0, 0, tzinfo=self.tz4))
def test_plan_days(self):
dt = self.calendar_jean.plan_days(2, datetime_tz(2018, 4, 10, 8, 0, 0))
self.assertEqual(dt, datetime_tz(2018, 4, 11, 14, 0, 0))
# We lose one day because of timezone
dt = self.calendar_jean.plan_days(2, datetime_tz(2018, 4, 10, 8, 0, 0, tzinfo=self.tz4))
self.assertEqual(dt, datetime_tz(2018, 4, 12, 4, 0, 0, tzinfo=self.tz4))
def test_work_data(self):
# 09-04-2018 10:00:00 - 13-04-2018 18:00:00
data = self.jean._get_work_days_data_batch(
datetime_tz(2018, 4, 9, 8, 0, 0),
datetime_tz(2018, 4, 13, 16, 0, 0),
)[self.jean.id]
self.assertEqual(data, {'days': 4.75, 'hours': 38})
# 09-04-2018 00:00:00 - 13-04-2018 08:00:00
data = self.jean._get_work_days_data_batch(
datetime_tz(2018, 4, 9, 8, 0, 0, tzinfo=self.tz3),
datetime_tz(2018, 4, 13, 16, 0, 0, tzinfo=self.tz3),
)[self.jean.id]
self.assertEqual(data, {'days': 4, 'hours': 32})
# 09-04-2018 08:00:00 - 14-04-2018 12:00:00
data = self.jean._get_work_days_data_batch(
datetime_tz(2018, 4, 9, 8, 0, 0, tzinfo=self.tz2),
datetime_tz(2018, 4, 13, 16, 0, 0, tzinfo=self.tz4),
)[self.jean.id]
self.assertEqual(data, {'days': 5, 'hours': 40})
# Jules with 2 weeks calendar
# 02-04-2018 00:00:00 - 6-04-2018 23:59:59
data = self.jules._get_work_days_data_batch(
datetime_tz(2018, 4, 2, 0, 0, 0, tzinfo=self.jules.tz),
datetime_tz(2018, 4, 6, 23, 59, 59, tzinfo=self.jules.tz),
)[self.jules.id]
self.assertEqual(data, {'days': 4, 'hours': 30})
# Jules with 2 weeks calendar
# 02-04-2018 00:00:00 - 14-04-2018 23:59:59
data = self.jules._get_work_days_data_batch(
datetime_tz(2018, 4, 2, 0, 0, 0, tzinfo=self.jules.tz),
datetime_tz(2018, 4, 14, 23, 59, 59, tzinfo=self.jules.tz),
)[self.jules.id]
self.assertEqual(data, {'days': 6, 'hours': 46})
# Jules with 2 weeks calendar
# 12-29-2014 00:00:00 - 27-12-2019 23:59:59 => 261 weeks
# 130 weeks type 1: 131*4 = 524 days and 131*30 = 3930 hours
# 131 weeks type 2: 130*2 = 260 days and 130*16 = 2080 hours
data = self.jules._get_work_days_data_batch(
datetime_tz(2014, 12, 29, 0, 0, 0, tzinfo=self.jules.tz),
datetime_tz(2019, 12, 27, 23, 59, 59, tzinfo=self.jules.tz),
)[self.jules.id]
self.assertEqual(data, {'days': 784, 'hours': 6010})
def test_leave_data(self):
self.env['resource.calendar.leaves'].create({
'name': '',
'calendar_id': self.jean.resource_calendar_id.id,
'resource_id': self.jean.resource_id.id,
'date_from': datetime_str(2018, 4, 9, 8, 0, 0, tzinfo=self.tz2),
'date_to': datetime_str(2018, 4, 9, 14, 0, 0, tzinfo=self.tz2),
})
# 09-04-2018 10:00:00 - 13-04-2018 18:00:00
data = self.jean._get_leave_days_data_batch(
datetime_tz(2018, 4, 9, 8, 0, 0),
datetime_tz(2018, 4, 13, 16, 0, 0),
)[self.jean.id]
self.assertEqual(data, {'days': 0.5, 'hours': 4})
# 09-04-2018 00:00:00 - 13-04-2018 08:00:00
data = self.jean._get_leave_days_data_batch(
datetime_tz(2018, 4, 9, 8, 0, 0, tzinfo=self.tz3),
datetime_tz(2018, 4, 13, 16, 0, 0, tzinfo=self.tz3),
)[self.jean.id]
self.assertEqual(data, {'days': 0.75, 'hours': 6})
# 09-04-2018 08:00:00 - 14-04-2018 12:00:00
data = self.jean._get_leave_days_data_batch(
datetime_tz(2018, 4, 9, 8, 0, 0, tzinfo=self.tz2),
datetime_tz(2018, 4, 13, 16, 0, 0, tzinfo=self.tz4),
)[self.jean.id]
self.assertEqual(data, {'days': 0.75, 'hours': 6})
def test_leaves(self):
leave = self.env['resource.calendar.leaves'].create({
'name': '',
'calendar_id': self.jean.resource_calendar_id.id,
'resource_id': self.jean.resource_id.id,
'date_from': datetime_str(2018, 4, 9, 8, 0, 0, tzinfo=self.tz2),
'date_to': datetime_str(2018, 4, 9, 14, 0, 0, tzinfo=self.tz2),
})
# 09-04-2018 10:00:00 - 13-04-2018 18:00:00
leaves = self.jean.list_leaves(
datetime_tz(2018, 4, 9, 8, 0, 0),
datetime_tz(2018, 4, 13, 16, 0, 0),
)
self.assertEqual(leaves, [(date(2018, 4, 9), 4, leave)])
# 09-04-2018 00:00:00 - 13-04-2018 08:00:00
leaves = self.jean.list_leaves(
datetime_tz(2018, 4, 9, 8, 0, 0, tzinfo=self.tz3),
datetime_tz(2018, 4, 13, 16, 0, 0, tzinfo=self.tz3),
)
self.assertEqual(leaves, [(date(2018, 4, 9), 6, leave)])
# 09-04-2018 08:00:00 - 14-04-2018 12:00:00
leaves = self.jean.list_leaves(
datetime_tz(2018, 4, 9, 8, 0, 0, tzinfo=self.tz2),
datetime_tz(2018, 4, 13, 16, 0, 0, tzinfo=self.tz4),
)
self.assertEqual(leaves, [(date(2018, 4, 9), 6, leave)])
def test_works(self):
work = self.jean.list_work_time_per_day(
datetime_tz(2018, 4, 9, 8, 0, 0),
datetime_tz(2018, 4, 13, 16, 0, 0),
)
self.assertEqual(work, [
(date(2018, 4, 9), 6),
(date(2018, 4, 10), 8),
(date(2018, 4, 11), 8),
(date(2018, 4, 12), 8),
(date(2018, 4, 13), 8),
])
work = self.jean.list_work_time_per_day(
datetime_tz(2018, 4, 9, 8, 0, 0, tzinfo=self.tz3),
datetime_tz(2018, 4, 13, 16, 0, 0, tzinfo=self.tz3),
)
self.assertEqual(len(work), 4)
self.assertEqual(work, [
(date(2018, 4, 9), 8),
(date(2018, 4, 10), 8),
(date(2018, 4, 11), 8),
(date(2018, 4, 12), 8),
])
work = self.jean.list_work_time_per_day(
datetime_tz(2018, 4, 9, 8, 0, 0, tzinfo=self.tz2),
datetime_tz(2018, 4, 13, 16, 0, 0, tzinfo=self.tz4),
)
self.assertEqual(work, [
(date(2018, 4, 9), 8),
(date(2018, 4, 10), 8),
(date(2018, 4, 11), 8),
(date(2018, 4, 12), 8),
(date(2018, 4, 13), 8),
])
@freeze_time("2022-09-21 15:30:00", tz_offset=-10)
def test_unavailable_intervals(self):
resource = self.env['resource.resource'].create({
'name': 'resource',
'tz': self.tz3,
})
intervals = resource._get_unavailable_intervals(datetime(2022, 9, 21), datetime(2022, 9, 22))
self.assertEqual(list(intervals.values())[0], [
(datetime(2022, 9, 21, 0, 0, tzinfo=utc), datetime(2022, 9, 21, 6, 0, tzinfo=utc)),
(datetime(2022, 9, 21, 10, 0, tzinfo=utc), datetime(2022, 9, 21, 11, 0, tzinfo=utc)),
(datetime(2022, 9, 21, 15, 0, tzinfo=utc), datetime(2022, 9, 22, 0, 0, tzinfo=utc)),
])
| 43.550198
| 55,091
|
3,323
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests.common import TransactionCase
class TestResourceCommon(TransactionCase):
def _define_calendar(self, name, attendances, tz):
return self.env['resource.calendar'].create({
'name': name,
'tz': tz,
'attendance_ids': [
(0, 0, {
'name': '%s_%d' % (name, index),
'hour_from': att[0],
'hour_to': att[1],
'dayofweek': str(att[2]),
})
for index, att in enumerate(attendances)
],
})
def _define_calendar_2_weeks(self, name, attendances, tz):
return self.env['resource.calendar'].create({
'name': name,
'tz': tz,
'two_weeks_calendar': True,
'attendance_ids': [
(0, 0, {
'name': '%s_%d' % (name, index),
'hour_from': att[0],
'hour_to': att[1],
'dayofweek': str(att[2]),
'week_type': att[3],
'display_type': att[4],
'sequence': att[5],
})
for index, att in enumerate(attendances)
],
})
def setUp(self):
super(TestResourceCommon, self).setUp()
# UTC+1 winter, UTC+2 summer
self.calendar_jean = self._define_calendar('40 Hours', [(8, 16, i) for i in range(5)], 'Europe/Brussels')
# UTC+6
self.calendar_patel = self._define_calendar('38 Hours', sum([((9, 12, i), (13, 17, i)) for i in range(5)], ()), 'Etc/GMT-6')
# UTC-8 winter, UTC-7 summer
self.calendar_john = self._define_calendar('8+12 Hours', [(8, 16, 1), (8, 13, 4), (16, 23, 4)], 'America/Los_Angeles')
# UTC+1 winter, UTC+2 summer
self.calendar_jules = self._define_calendar_2_weeks('Week 1: 30 Hours - Week 2: 16 Hours', [
(0, 0, 0, '0', 'line_section', 0), (8, 16, 0, '0', False, 1), (9, 17, 1, '0', False, 2),
(0, 0, 0, '1', 'line_section', 10), (8, 16, 0, '1', False, 11), (7, 15, 2, '1', False, 12),
(8, 16, 3, '1', False, 13), (10, 16, 4, '1', False, 14)], 'Europe/Brussels')
self.calendar_paul = self._define_calendar('Morning and evening shifts', sum([((2, 7, i), (10, 16, i)) for i in range(5)], ()), 'Brazil/DeNoronha')
# Employee is linked to a resource.resource via resource.mixin
self.jean = self.env['resource.test'].create({
'name': 'Jean',
'resource_calendar_id': self.calendar_jean.id,
})
self.patel = self.env['resource.test'].create({
'name': 'Patel',
'resource_calendar_id': self.calendar_patel.id,
})
self.john = self.env['resource.test'].create({
'name': 'John',
'resource_calendar_id': self.calendar_john.id,
})
self.jules = self.env['resource.test'].create({
'name': 'Jules',
'resource_calendar_id': self.calendar_jules.id,
})
self.paul = self.env['resource.test'].create({
'name': 'Paul',
'resource_calendar_id': self.calendar_paul.id,
})
| 41.5375
| 3,323
|
297
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class ResourceTest(models.Model):
_description = 'Test Resource Model'
_name = 'resource.test'
_inherit = ['resource.mixin']
name = fields.Char()
| 24.75
| 297
|
49,201
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import defaultdict
import math
from datetime import datetime, time, timedelta
from dateutil.relativedelta import relativedelta
from dateutil.rrule import rrule, DAILY, WEEKLY
from functools import partial
from itertools import chain
from pytz import timezone, utc
from odoo import api, fields, models, _
from odoo.addons.base.models.res_partner import _tz_get
from odoo.exceptions import ValidationError, UserError
from odoo.osv import expression
from odoo.tools.float_utils import float_round
from odoo.tools import date_utils, float_utils
from .resource_mixin import timezone_datetime
# Default hour per day value. The one should
# only be used when the one from the calendar
# is not available.
HOURS_PER_DAY = 8
# This will generate 16th of days
ROUNDING_FACTOR = 16
def make_aware(dt):
""" Return ``dt`` with an explicit timezone, together with a function to
convert a datetime to the same (naive or aware) timezone as ``dt``.
"""
if dt.tzinfo:
return dt, lambda val: val.astimezone(dt.tzinfo)
else:
return dt.replace(tzinfo=utc), lambda val: val.astimezone(utc).replace(tzinfo=None)
def string_to_datetime(value):
""" Convert the given string value to a datetime in UTC. """
return utc.localize(fields.Datetime.from_string(value))
def datetime_to_string(dt):
""" Convert the given datetime (converted in UTC) to a string value. """
return fields.Datetime.to_string(dt.astimezone(utc))
def float_to_time(hours):
""" Convert a number of hours into a time object. """
if hours == 24.0:
return time.max
fractional, integral = math.modf(hours)
return time(int(integral), int(float_round(60 * fractional, precision_digits=0)), 0)
def _boundaries(intervals, opening, closing):
""" Iterate on the boundaries of intervals. """
for start, stop, recs in intervals:
if start < stop:
yield (start, opening, recs)
yield (stop, closing, recs)
class Intervals(object):
""" Collection of ordered disjoint intervals with some associated records.
Each interval is a triple ``(start, stop, records)``, where ``records``
is a recordset.
"""
def __init__(self, intervals=()):
self._items = []
if intervals:
# normalize the representation of intervals
append = self._items.append
starts = []
recses = []
for value, flag, recs in sorted(_boundaries(intervals, 'start', 'stop')):
if flag == 'start':
starts.append(value)
recses.append(recs)
else:
start = starts.pop()
if not starts:
append((start, value, recses[0].union(*recses)))
recses.clear()
def __bool__(self):
return bool(self._items)
def __len__(self):
return len(self._items)
def __iter__(self):
return iter(self._items)
def __reversed__(self):
return reversed(self._items)
def __or__(self, other):
""" Return the union of two sets of intervals. """
return Intervals(chain(self._items, other._items))
def __and__(self, other):
""" Return the intersection of two sets of intervals. """
return self._merge(other, False)
def __sub__(self, other):
""" Return the difference of two sets of intervals. """
return self._merge(other, True)
def _merge(self, other, difference):
""" Return the difference or intersection of two sets of intervals. """
result = Intervals()
append = result._items.append
# using 'self' and 'other' below forces normalization
bounds1 = _boundaries(self, 'start', 'stop')
bounds2 = _boundaries(other, 'switch', 'switch')
start = None # set by start/stop
recs1 = None # set by start
enabled = difference # changed by switch
for value, flag, recs in sorted(chain(bounds1, bounds2)):
if flag == 'start':
start = value
recs1 = recs
elif flag == 'stop':
if enabled and start < value:
append((start, value, recs1))
start = None
else:
if not enabled and start is not None:
start = value
if enabled and start is not None and start < value:
append((start, value, recs1))
enabled = not enabled
return result
class ResourceCalendar(models.Model):
""" Calendar model for a resource. It has
- attendance_ids: list of resource.calendar.attendance that are a working
interval in a given weekday.
- leave_ids: list of leaves linked to this calendar. A leave can be general
or linked to a specific resource, depending on its resource_id.
All methods in this class use intervals. An interval is a tuple holding
(begin_datetime, end_datetime). A list of intervals is therefore a list of
tuples, holding several intervals of work or leaves. """
_name = "resource.calendar"
_description = "Resource Working Time"
@api.model
def default_get(self, fields):
res = super(ResourceCalendar, self).default_get(fields)
if not res.get('name') and res.get('company_id'):
res['name'] = _('Working Hours of %s', self.env['res.company'].browse(res['company_id']).name)
if 'attendance_ids' in fields and not res.get('attendance_ids'):
company_id = res.get('company_id', self.env.company.id)
company = self.env['res.company'].browse(company_id)
company_attendance_ids = company.resource_calendar_id.attendance_ids
if company_attendance_ids:
res['attendance_ids'] = [
(0, 0, {
'name': attendance.name,
'dayofweek': attendance.dayofweek,
'hour_from': attendance.hour_from,
'hour_to': attendance.hour_to,
'day_period': attendance.day_period,
})
for attendance in company_attendance_ids
]
else:
res['attendance_ids'] = [
(0, 0, {'name': _('Monday Morning'), 'dayofweek': '0', 'hour_from': 8, 'hour_to': 12, 'day_period': 'morning'}),
(0, 0, {'name': _('Monday Afternoon'), 'dayofweek': '0', 'hour_from': 13, 'hour_to': 17, 'day_period': 'afternoon'}),
(0, 0, {'name': _('Tuesday Morning'), 'dayofweek': '1', 'hour_from': 8, 'hour_to': 12, 'day_period': 'morning'}),
(0, 0, {'name': _('Tuesday Afternoon'), 'dayofweek': '1', 'hour_from': 13, 'hour_to': 17, 'day_period': 'afternoon'}),
(0, 0, {'name': _('Wednesday Morning'), 'dayofweek': '2', 'hour_from': 8, 'hour_to': 12, 'day_period': 'morning'}),
(0, 0, {'name': _('Wednesday Afternoon'), 'dayofweek': '2', 'hour_from': 13, 'hour_to': 17, 'day_period': 'afternoon'}),
(0, 0, {'name': _('Thursday Morning'), 'dayofweek': '3', 'hour_from': 8, 'hour_to': 12, 'day_period': 'morning'}),
(0, 0, {'name': _('Thursday Afternoon'), 'dayofweek': '3', 'hour_from': 13, 'hour_to': 17, 'day_period': 'afternoon'}),
(0, 0, {'name': _('Friday Morning'), 'dayofweek': '4', 'hour_from': 8, 'hour_to': 12, 'day_period': 'morning'}),
(0, 0, {'name': _('Friday Afternoon'), 'dayofweek': '4', 'hour_from': 13, 'hour_to': 17, 'day_period': 'afternoon'})
]
return res
name = fields.Char(required=True)
active = fields.Boolean("Active", default=True,
help="If the active field is set to false, it will allow you to hide the Working Time without removing it.")
company_id = fields.Many2one(
'res.company', 'Company',
default=lambda self: self.env.company)
attendance_ids = fields.One2many(
'resource.calendar.attendance', 'calendar_id', 'Working Time',
compute='_compute_attendance_ids', store=True, readonly=False, copy=True)
leave_ids = fields.One2many(
'resource.calendar.leaves', 'calendar_id', 'Time Off')
global_leave_ids = fields.One2many(
'resource.calendar.leaves', 'calendar_id', 'Global Time Off',
compute='_compute_global_leave_ids', store=True, readonly=False,
domain=[('resource_id', '=', False)], copy=True,
)
hours_per_day = fields.Float("Average Hour per Day", default=HOURS_PER_DAY,
help="Average hours per day a resource is supposed to work with this calendar.")
tz = fields.Selection(
_tz_get, string='Timezone', required=True,
default=lambda self: self._context.get('tz') or self.env.user.tz or self.env.ref('base.user_admin').tz or 'UTC',
help="This field is used in order to define in which timezone the resources will work.")
tz_offset = fields.Char(compute='_compute_tz_offset', string='Timezone offset', invisible=True)
two_weeks_calendar = fields.Boolean(string="Calendar in 2 weeks mode")
two_weeks_explanation = fields.Char('Explanation', compute="_compute_two_weeks_explanation")
@api.depends('company_id')
def _compute_attendance_ids(self):
for calendar in self.filtered(lambda c: not c._origin or c._origin.company_id != c.company_id):
company_calendar = calendar.company_id.resource_calendar_id
calendar.write({
'two_weeks_calendar': company_calendar.two_weeks_calendar,
'hours_per_day': company_calendar.hours_per_day,
'tz': company_calendar.tz,
'attendance_ids': [(5, 0, 0)] + [
(0, 0, attendance._copy_attendance_vals()) for attendance in company_calendar.attendance_ids if not attendance.resource_id]
})
@api.depends('company_id')
def _compute_global_leave_ids(self):
for calendar in self.filtered(lambda c: not c._origin or c._origin.company_id != c.company_id):
calendar.write({
'global_leave_ids': [(5, 0, 0)] + [
(0, 0, leave._copy_leave_vals()) for leave in calendar.company_id.resource_calendar_id.global_leave_ids]
})
@api.depends('tz')
def _compute_tz_offset(self):
for calendar in self:
calendar.tz_offset = datetime.now(timezone(calendar.tz or 'GMT')).strftime('%z')
@api.returns('self', lambda value: value.id)
def copy(self, default=None):
self.ensure_one()
if default is None:
default = {}
if not default.get('name'):
default.update(name=_('%s (copy)') % (self.name))
return super(ResourceCalendar, self).copy(default)
@api.constrains('attendance_ids')
def _check_attendance_ids(self):
for resource in self:
if (resource.two_weeks_calendar and
resource.attendance_ids.filtered(lambda a: a.display_type == 'line_section') and
not resource.attendance_ids.sorted('sequence')[0].display_type):
raise ValidationError(_("In a calendar with 2 weeks mode, all periods need to be in the sections."))
@api.depends('two_weeks_calendar')
def _compute_two_weeks_explanation(self):
today = fields.Date.today()
week_type = self.env['resource.calendar.attendance'].get_week_type(today)
week_type_str = _("second") if week_type else _("first")
first_day = date_utils.start_of(today, 'week')
last_day = date_utils.end_of(today, 'week')
self.two_weeks_explanation = _("The current week (from %s to %s) correspond to the %s one.", first_day,
last_day, week_type_str)
def _get_global_attendances(self):
return self.attendance_ids.filtered(lambda attendance:
not attendance.date_from and not attendance.date_to
and not attendance.resource_id and not attendance.display_type)
def _compute_hours_per_day(self, attendances):
if not attendances:
return 0
hour_count = 0.0
for attendance in attendances:
hour_count += attendance.hour_to - attendance.hour_from
if self.two_weeks_calendar:
number_of_days = len(set(attendances.filtered(lambda cal: cal.week_type == '1').mapped('dayofweek')))
number_of_days += len(set(attendances.filtered(lambda cal: cal.week_type == '0').mapped('dayofweek')))
else:
number_of_days = len(set(attendances.mapped('dayofweek')))
return float_round(hour_count / float(number_of_days), precision_digits=2)
@api.onchange('attendance_ids', 'two_weeks_calendar')
def _onchange_hours_per_day(self):
attendances = self._get_global_attendances()
self.hours_per_day = self._compute_hours_per_day(attendances)
def switch_calendar_type(self):
if self == self.env.company.resource_calendar_id:
raise UserError(_('Impossible to switch calendar type for the default company schedule.'))
if not self.two_weeks_calendar:
self.attendance_ids.unlink()
self.attendance_ids = [
(0, 0, {
'name': 'First week',
'dayofweek': '0',
'sequence': '0',
'hour_from': 0,
'day_period': 'morning',
'week_type': '0',
'hour_to': 0,
'display_type':
'line_section'}),
(0, 0, {
'name': 'Second week',
'dayofweek': '0',
'sequence': '25',
'hour_from': 0,
'day_period': 'morning',
'week_type': '1',
'hour_to': 0,
'display_type': 'line_section'}),
]
self.two_weeks_calendar = True
default_attendance = self.default_get('attendance_ids')['attendance_ids']
for idx, att in enumerate(default_attendance):
att[2]["week_type"] = '0'
att[2]["sequence"] = idx + 1
self.attendance_ids = default_attendance
for idx, att in enumerate(default_attendance):
att[2]["week_type"] = '1'
att[2]["sequence"] = idx + 26
self.attendance_ids = default_attendance
else:
self.two_weeks_calendar = False
self.attendance_ids.unlink()
self.attendance_ids = self.default_get('attendance_ids')['attendance_ids']
self._onchange_hours_per_day()
@api.onchange('attendance_ids')
def _onchange_attendance_ids(self):
if not self.two_weeks_calendar:
return
even_week_seq = self.attendance_ids.filtered(lambda att: att.display_type == 'line_section' and att.week_type == '0')
odd_week_seq = self.attendance_ids.filtered(lambda att: att.display_type == 'line_section' and att.week_type == '1')
if len(even_week_seq) != 1 or len(odd_week_seq) != 1:
raise ValidationError(_("You can't delete section between weeks."))
even_week_seq = even_week_seq.sequence
odd_week_seq = odd_week_seq.sequence
for line in self.attendance_ids.filtered(lambda att: att.display_type is False):
if even_week_seq > odd_week_seq:
line.week_type = '1' if even_week_seq > line.sequence else '0'
else:
line.week_type = '0' if odd_week_seq > line.sequence else '1'
def _check_overlap(self, attendance_ids):
""" attendance_ids correspond to attendance of a week,
will check for each day of week that there are no superimpose. """
result = []
for attendance in attendance_ids.filtered(lambda att: not att.date_from and not att.date_to):
# 0.000001 is added to each start hour to avoid to detect two contiguous intervals as superimposing.
# Indeed Intervals function will join 2 intervals with the start and stop hour corresponding.
result.append((int(attendance.dayofweek) * 24 + attendance.hour_from + 0.000001, int(attendance.dayofweek) * 24 + attendance.hour_to, attendance))
if len(Intervals(result)) != len(result):
raise ValidationError(_("Attendances can't overlap."))
@api.constrains('attendance_ids')
def _check_attendance(self):
# Avoid superimpose in attendance
for calendar in self:
attendance_ids = calendar.attendance_ids.filtered(lambda attendance: not attendance.resource_id and attendance.display_type is False)
if calendar.two_weeks_calendar:
calendar._check_overlap(attendance_ids.filtered(lambda attendance: attendance.week_type == '0'))
calendar._check_overlap(attendance_ids.filtered(lambda attendance: attendance.week_type == '1'))
else:
calendar._check_overlap(attendance_ids)
# --------------------------------------------------
# Computation API
# --------------------------------------------------
def _attendance_intervals_batch(self, start_dt, end_dt, resources=None, domain=None, tz=None):
""" Return the attendance intervals in the given datetime range.
The returned intervals are expressed in specified tz or in the resource's timezone.
"""
self.ensure_one()
resources = self.env['resource.resource'] if not resources else resources
assert start_dt.tzinfo and end_dt.tzinfo
self.ensure_one()
combine = datetime.combine
required_tz = tz
resources_list = list(resources) + [self.env['resource.resource']]
resource_ids = [r.id for r in resources_list]
domain = domain if domain is not None else []
domain = expression.AND([domain, [
('calendar_id', '=', self.id),
('resource_id', 'in', resource_ids),
('display_type', '=', False),
]])
# for each attendance spec, generate the intervals in the date range
cache_dates = defaultdict(dict)
cache_deltas = defaultdict(dict)
result = defaultdict(list)
for attendance in self.env['resource.calendar.attendance'].search(domain):
for resource in resources_list:
# express all dates and times in specified tz or in the resource's timezone
tz = required_tz if required_tz else timezone((resource or self).tz)
if (tz, start_dt) in cache_dates:
start = cache_dates[(tz, start_dt)]
else:
start = start_dt.astimezone(tz)
cache_dates[(tz, start_dt)] = start
if (tz, end_dt) in cache_dates:
end = cache_dates[(tz, end_dt)]
else:
end = end_dt.astimezone(tz)
cache_dates[(tz, end_dt)] = end
start = start.date()
if attendance.date_from:
start = max(start, attendance.date_from)
until = end.date()
if attendance.date_to:
until = min(until, attendance.date_to)
if attendance.week_type:
start_week_type = self.env['resource.calendar.attendance'].get_week_type(start)
if start_week_type != int(attendance.week_type):
# start must be the week of the attendance
# if it's not the case, we must remove one week
start = start + relativedelta(weeks=-1)
weekday = int(attendance.dayofweek)
if self.two_weeks_calendar and attendance.week_type:
days = rrule(WEEKLY, start, interval=2, until=until, byweekday=weekday)
else:
days = rrule(DAILY, start, until=until, byweekday=weekday)
for day in days:
# We need to exclude incorrect days according to re-defined start previously
# with weeks=-1 (Note: until is correctly handled)
if (self.two_weeks_calendar and attendance.date_from and attendance.date_from > day.date()):
continue
# attendance hours are interpreted in the resource's timezone
hour_from = attendance.hour_from
if (tz, day, hour_from) in cache_deltas:
dt0 = cache_deltas[(tz, day, hour_from)]
else:
dt0 = tz.localize(combine(day, float_to_time(hour_from)))
cache_deltas[(tz, day, hour_from)] = dt0
hour_to = attendance.hour_to
if (tz, day, hour_to) in cache_deltas:
dt1 = cache_deltas[(tz, day, hour_to)]
else:
dt1 = tz.localize(combine(day, float_to_time(hour_to)))
cache_deltas[(tz, day, hour_to)] = dt1
result[resource.id].append((max(cache_dates[(tz, start_dt)], dt0), min(cache_dates[(tz, end_dt)], dt1), attendance))
return {r.id: Intervals(result[r.id]) for r in resources_list}
def _leave_intervals(self, start_dt, end_dt, resource=None, domain=None, tz=None):
if resource is None:
resource = self.env['resource.resource']
return self._leave_intervals_batch(
start_dt, end_dt, resources=resource, domain=domain, tz=tz
)[resource.id]
def _leave_intervals_batch(self, start_dt, end_dt, resources=None, domain=None, tz=None):
""" Return the leave intervals in the given datetime range.
The returned intervals are expressed in specified tz or in the calendar's timezone.
"""
resources = self.env['resource.resource'] if not resources else resources
assert start_dt.tzinfo and end_dt.tzinfo
self.ensure_one()
# for the computation, express all datetimes in UTC
resources_list = list(resources) + [self.env['resource.resource']]
resource_ids = [r.id for r in resources_list]
if domain is None:
domain = [('time_type', '=', 'leave')]
domain = domain + [
('calendar_id', 'in', [False, self.id]),
('resource_id', 'in', resource_ids),
('date_from', '<=', datetime_to_string(end_dt)),
('date_to', '>=', datetime_to_string(start_dt)),
]
# retrieve leave intervals in (start_dt, end_dt)
result = defaultdict(lambda: [])
tz_dates = {}
for leave in self.env['resource.calendar.leaves'].search(domain):
for resource in resources_list:
if leave.resource_id.id not in [False, resource.id]:
continue
tz = tz if tz else timezone((resource or self).tz)
if (tz, start_dt) in tz_dates:
start = tz_dates[(tz, start_dt)]
else:
start = start_dt.astimezone(tz)
tz_dates[(tz, start_dt)] = start
if (tz, end_dt) in tz_dates:
end = tz_dates[(tz, end_dt)]
else:
end = end_dt.astimezone(tz)
tz_dates[(tz, end_dt)] = end
dt0 = string_to_datetime(leave.date_from).astimezone(tz)
dt1 = string_to_datetime(leave.date_to).astimezone(tz)
result[resource.id].append((max(start, dt0), min(end, dt1), leave))
return {r.id: Intervals(result[r.id]) for r in resources_list}
def _work_intervals_batch(self, start_dt, end_dt, resources=None, domain=None, tz=None):
""" Return the effective work intervals between the given datetimes. """
if not resources:
resources = self.env['resource.resource']
resources_list = [resources]
else:
resources_list = list(resources)
attendance_intervals = self._attendance_intervals_batch(start_dt, end_dt, resources, tz=tz)
leave_intervals = self._leave_intervals_batch(start_dt, end_dt, resources, domain, tz=tz)
return {
r.id: (attendance_intervals[r.id] - leave_intervals[r.id]) for r in resources_list
}
def _unavailable_intervals(self, start_dt, end_dt, resource=None, domain=None, tz=None):
if resource is None:
resource = self.env['resource.resource']
return self._unavailable_intervals_batch(
start_dt, end_dt, resources=resource, domain=domain, tz=tz
)[resource.id]
def _unavailable_intervals_batch(self, start_dt, end_dt, resources=None, domain=None, tz=None):
""" Return the unavailable intervals between the given datetimes. """
if not resources:
resources = self.env['resource.resource']
resources_list = [resources]
else:
resources_list = list(resources)
resources_work_intervals = self._work_intervals_batch(start_dt, end_dt, resources, domain, tz)
result = {}
for resource in resources_list:
work_intervals = [(start, stop) for start, stop, meta in resources_work_intervals[resource.id]]
# start + flatten(intervals) + end
work_intervals = [start_dt] + list(chain.from_iterable(work_intervals)) + [end_dt]
# put it back to UTC
work_intervals = list(map(lambda dt: dt.astimezone(utc), work_intervals))
# pick groups of two
work_intervals = list(zip(work_intervals[0::2], work_intervals[1::2]))
result[resource.id] = work_intervals
return result
# --------------------------------------------------
# Private Methods / Helpers
# --------------------------------------------------
def _get_days_data(self, intervals, day_total):
"""
helper function to compute duration of `intervals`
expressed in days and hours.
`day_total` is a dict {date: n_hours} with the number of hours for each day.
"""
day_hours = defaultdict(float)
for start, stop, meta in intervals:
day_hours[start.date()] += (stop - start).total_seconds() / 3600
# compute number of days as quarters
days = sum(
float_utils.round(ROUNDING_FACTOR * day_hours[day] / day_total[day]) / ROUNDING_FACTOR if day_total[day] else 0
for day in day_hours
)
return {
'days': days,
'hours': sum(day_hours.values()),
}
def _get_resources_day_total(self, from_datetime, to_datetime, resources=None):
"""
@return dict with hours of attendance in each day between `from_datetime` and `to_datetime`
"""
self.ensure_one()
resources = self.env['resource.resource'] if not resources else resources
resources_list = list(resources) + [self.env['resource.resource']]
# total hours per day: retrieve attendances with one extra day margin,
# in order to compute the total hours on the first and last days
from_full = from_datetime - timedelta(days=1)
to_full = to_datetime + timedelta(days=1)
intervals = self._attendance_intervals_batch(from_full, to_full, resources=resources)
result = defaultdict(lambda: defaultdict(float))
for resource in resources_list:
day_total = result[resource.id]
for start, stop, meta in intervals[resource.id]:
day_total[start.date()] += (stop - start).total_seconds() / 3600
return result
def _get_closest_work_time(self, dt, match_end=False, resource=None, search_range=None):
"""Return the closest work interval boundary within the search range.
Consider only starts of intervals unless `match_end` is True. It will then only consider
ends of intervals.
:param dt: reference datetime
:param match_end: wether to search for the begining of an interval or the end.
:param search_range: time interval considered. Defaults to the entire day of `dt`
:rtype: datetime | None
"""
def interval_dt(interval):
return interval[1 if match_end else 0]
tz = resource.tz if resource else self.tz
if resource is None:
resource = self.env['resource.resource']
if not dt.tzinfo or search_range and not (search_range[0].tzinfo and search_range[1].tzinfo):
raise ValueError('Provided datetimes needs to be timezoned')
dt = dt.astimezone(timezone(tz))
if not search_range:
range_start = dt + relativedelta(hour=0, minute=0, second=0)
range_end = dt + relativedelta(days=1, hour=0, minute=0, second=0)
else:
range_start, range_end = search_range
if not range_start <= dt <= range_end:
return None
work_intervals = sorted(
self._work_intervals_batch(range_start, range_end, resource)[resource.id],
key=lambda i: abs(interval_dt(i) - dt),
)
return interval_dt(work_intervals[0]) if work_intervals else None
# --------------------------------------------------
# External API
# --------------------------------------------------
def get_work_hours_count(self, start_dt, end_dt, compute_leaves=True, domain=None):
"""
`compute_leaves` controls whether or not this method is taking into
account the global leaves.
`domain` controls the way leaves are recognized.
None means default value ('time_type', '=', 'leave')
Counts the number of work hours between two datetimes.
"""
self.ensure_one()
# Set timezone in UTC if no timezone is explicitly given
if not start_dt.tzinfo:
start_dt = start_dt.replace(tzinfo=utc)
if not end_dt.tzinfo:
end_dt = end_dt.replace(tzinfo=utc)
if compute_leaves:
intervals = self._work_intervals_batch(start_dt, end_dt, domain=domain)[False]
else:
intervals = self._attendance_intervals_batch(start_dt, end_dt)[False]
return sum(
(stop - start).total_seconds() / 3600
for start, stop, meta in intervals
)
def get_work_duration_data(self, from_datetime, to_datetime, compute_leaves=True, domain=None):
"""
Get the working duration (in days and hours) for a given period, only
based on the current calendar. This method does not use resource to
compute it.
`domain` is used in order to recognise the leaves to take,
None means default value ('time_type', '=', 'leave')
Returns a dict {'days': n, 'hours': h} containing the
quantity of working time expressed as days and as hours.
"""
# naive datetimes are made explicit in UTC
from_datetime, dummy = make_aware(from_datetime)
to_datetime, dummy = make_aware(to_datetime)
day_total = self._get_resources_day_total(from_datetime, to_datetime)[False]
# actual hours per day
if compute_leaves:
intervals = self._work_intervals_batch(from_datetime, to_datetime, domain=domain)[False]
else:
intervals = self._attendance_intervals_batch(from_datetime, to_datetime, domain=domain)[False]
return self._get_days_data(intervals, day_total)
def plan_hours(self, hours, day_dt, compute_leaves=False, domain=None, resource=None):
"""
`compute_leaves` controls whether or not this method is taking into
account the global leaves.
`domain` controls the way leaves are recognized.
None means default value ('time_type', '=', 'leave')
Return datetime after having planned hours
"""
day_dt, revert = make_aware(day_dt)
if resource is None:
resource = self.env['resource.resource']
# which method to use for retrieving intervals
if compute_leaves:
get_intervals = partial(self._work_intervals_batch, domain=domain, resources=resource)
resource_id = resource.id
else:
get_intervals = self._attendance_intervals_batch
resource_id = False
if hours >= 0:
delta = timedelta(days=14)
for n in range(100):
dt = day_dt + delta * n
for start, stop, meta in get_intervals(dt, dt + delta)[resource_id]:
interval_hours = (stop - start).total_seconds() / 3600
if hours <= interval_hours:
return revert(start + timedelta(hours=hours))
hours -= interval_hours
return False
else:
hours = abs(hours)
delta = timedelta(days=14)
for n in range(100):
dt = day_dt - delta * n
for start, stop, meta in reversed(get_intervals(dt - delta, dt)[resource_id]):
interval_hours = (stop - start).total_seconds() / 3600
if hours <= interval_hours:
return revert(stop - timedelta(hours=hours))
hours -= interval_hours
return False
def plan_days(self, days, day_dt, compute_leaves=False, domain=None):
"""
`compute_leaves` controls whether or not this method is taking into
account the global leaves.
`domain` controls the way leaves are recognized.
None means default value ('time_type', '=', 'leave')
Returns the datetime of a days scheduling.
"""
day_dt, revert = make_aware(day_dt)
# which method to use for retrieving intervals
if compute_leaves:
get_intervals = partial(self._work_intervals_batch, domain=domain)
else:
get_intervals = self._attendance_intervals_batch
if days > 0:
found = set()
delta = timedelta(days=14)
for n in range(100):
dt = day_dt + delta * n
for start, stop, meta in get_intervals(dt, dt + delta)[False]:
found.add(start.date())
if len(found) == days:
return revert(stop)
return False
elif days < 0:
days = abs(days)
found = set()
delta = timedelta(days=14)
for n in range(100):
dt = day_dt - delta * n
for start, stop, meta in reversed(get_intervals(dt - delta, dt)[False]):
found.add(start.date())
if len(found) == days:
return revert(start)
return False
else:
return revert(day_dt)
def _get_max_number_of_hours(self, start, end):
self.ensure_one()
if not self.attendance_ids:
return 0
mapped_data = defaultdict(lambda: 0)
for attendance in self.attendance_ids.filtered(lambda a: (not a.date_from or not a.date_to) or (a.date_from <= end.date() and a.date_to >= start.date())):
mapped_data[(attendance.week_type, attendance.dayofweek)] += attendance.hour_to - attendance.hour_from
return max(mapped_data.values())
class ResourceCalendarAttendance(models.Model):
_name = "resource.calendar.attendance"
_description = "Work Detail"
_order = 'week_type, dayofweek, hour_from'
name = fields.Char(required=True)
dayofweek = fields.Selection([
('0', 'Monday'),
('1', 'Tuesday'),
('2', 'Wednesday'),
('3', 'Thursday'),
('4', 'Friday'),
('5', 'Saturday'),
('6', 'Sunday')
], 'Day of Week', required=True, index=True, default='0')
date_from = fields.Date(string='Starting Date')
date_to = fields.Date(string='End Date')
hour_from = fields.Float(string='Work from', required=True, index=True,
help="Start and End time of working.\n"
"A specific value of 24:00 is interpreted as 23:59:59.999999.")
hour_to = fields.Float(string='Work to', required=True)
calendar_id = fields.Many2one("resource.calendar", string="Resource's Calendar", required=True, ondelete='cascade')
day_period = fields.Selection([('morning', 'Morning'), ('afternoon', 'Afternoon')], required=True, default='morning')
resource_id = fields.Many2one('resource.resource', 'Resource')
week_type = fields.Selection([
('1', 'Second'),
('0', 'First')
], 'Week Number', default=False)
two_weeks_calendar = fields.Boolean("Calendar in 2 weeks mode", related='calendar_id.two_weeks_calendar')
display_type = fields.Selection([
('line_section', "Section")], default=False, help="Technical field for UX purpose.")
sequence = fields.Integer(default=10,
help="Gives the sequence of this line when displaying the resource calendar.")
@api.onchange('hour_from', 'hour_to')
def _onchange_hours(self):
# avoid negative or after midnight
self.hour_from = min(self.hour_from, 23.99)
self.hour_from = max(self.hour_from, 0.0)
self.hour_to = min(self.hour_to, 24)
self.hour_to = max(self.hour_to, 0.0)
# avoid wrong order
self.hour_to = max(self.hour_to, self.hour_from)
@api.model
def get_week_type(self, date):
# week_type is defined by
# * counting the number of days from January 1 of year 1
# (extrapolated to dates prior to the first adoption of the Gregorian calendar)
# * converted to week numbers and then the parity of this number is asserted.
# It ensures that an even week number always follows an odd week number. With classical week number,
# some years have 53 weeks. Therefore, two consecutive odd week number follow each other (53 --> 1).
return int(math.floor((date.toordinal() - 1) / 7) % 2)
def _compute_display_name(self):
super()._compute_display_name()
this_week_type = str(self.get_week_type(fields.Date.context_today(self)))
section_names = {'0': _('First week'), '1': _('Second week')}
section_info = {True: _('this week'), False: _('other week')}
for record in self.filtered(lambda l: l.display_type == 'line_section'):
section_name = "%s (%s)" % (section_names[record.week_type], section_info[this_week_type == record.week_type])
record.display_name = section_name
def _copy_attendance_vals(self):
self.ensure_one()
return {
'name': self.name,
'dayofweek': self.dayofweek,
'date_from': self.date_from,
'date_to': self.date_to,
'hour_from': self.hour_from,
'hour_to': self.hour_to,
'day_period': self.day_period,
'week_type': self.week_type,
'display_type': self.display_type,
'sequence': self.sequence,
}
class ResourceResource(models.Model):
_name = "resource.resource"
_description = "Resources"
_order = "name"
@api.model
def default_get(self, fields):
res = super(ResourceResource, self).default_get(fields)
if not res.get('calendar_id') and res.get('company_id'):
company = self.env['res.company'].browse(res['company_id'])
res['calendar_id'] = company.resource_calendar_id.id
return res
name = fields.Char(required=True)
active = fields.Boolean(
'Active', default=True,
help="If the active field is set to False, it will allow you to hide the resource record without removing it.")
company_id = fields.Many2one('res.company', string='Company', default=lambda self: self.env.company)
resource_type = fields.Selection([
('user', 'Human'),
('material', 'Material')], string='Type',
default='user', required=True)
user_id = fields.Many2one('res.users', string='User', help='Related user name for the resource to manage its access.')
time_efficiency = fields.Float(
'Efficiency Factor', default=100, required=True,
help="This field is used to calculate the expected duration of a work order at this work center. For example, if a work order takes one hour and the efficiency factor is 100%, then the expected duration will be one hour. If the efficiency factor is 200%, however the expected duration will be 30 minutes.")
calendar_id = fields.Many2one(
"resource.calendar", string='Working Time',
default=lambda self: self.env.company.resource_calendar_id,
required=True, domain="[('company_id', '=', company_id)]",
help="Define the schedule of resource")
tz = fields.Selection(
_tz_get, string='Timezone', required=True,
default=lambda self: self._context.get('tz') or self.env.user.tz or 'UTC',
help="This field is used in order to define in which timezone the resources will work.")
_sql_constraints = [
('check_time_efficiency', 'CHECK(time_efficiency>0)', 'Time efficiency must be strictly positive'),
]
@api.model_create_multi
def create(self, vals_list):
for values in vals_list:
if values.get('company_id') and not values.get('calendar_id'):
values['calendar_id'] = self.env['res.company'].browse(values['company_id']).resource_calendar_id.id
if not values.get('tz'):
# retrieve timezone on user or calendar
tz = (self.env['res.users'].browse(values.get('user_id')).tz or
self.env['resource.calendar'].browse(values.get('calendar_id')).tz)
if tz:
values['tz'] = tz
return super(ResourceResource, self).create(vals_list)
@api.returns('self', lambda value: value.id)
def copy(self, default=None):
self.ensure_one()
if default is None:
default = {}
if not default.get('name'):
default.update(name=_('%s (copy)') % (self.name))
return super(ResourceResource, self).copy(default)
@api.onchange('company_id')
def _onchange_company_id(self):
if self.company_id:
self.calendar_id = self.company_id.resource_calendar_id.id
@api.onchange('user_id')
def _onchange_user_id(self):
if self.user_id:
self.tz = self.user_id.tz
def _get_work_interval(self, start, end):
# Deprecated method. Use `_adjust_to_calendar` instead
return self._adjust_to_calendar(start, end)
def _adjust_to_calendar(self, start, end):
"""Adjust the given start and end datetimes to the closest effective hours encoded
in the resource calendar. Only attendances in the same day as `start` and `end` are
considered (respectively). If no attendance is found during that day, the closest hour
is None.
e.g. simplified example:
given two attendances: 8am-1pm and 2pm-5pm, given start=9am and end=6pm
resource._adjust_to_calendar(start, end)
>>> {resource: (8am, 5pm)}
:return: Closest matching start and end of working periods for each resource
:rtype: dict(resource, tuple(datetime | None, datetime | None))
"""
start, revert_start_tz = make_aware(start)
end, revert_end_tz = make_aware(end)
result = {}
for resource in self:
calendar_start = resource.calendar_id._get_closest_work_time(start, resource=resource)
search_range = None
tz = timezone(resource.tz)
if calendar_start and start.astimezone(tz).date() == end.astimezone(tz).date():
end = end.astimezone(tz)
# Make sure to only search end after start
search_range = (
start,
end + relativedelta(days=1, hour=0, minute=0, second=0),
)
calendar_end = resource.calendar_id._get_closest_work_time(end, match_end=True, resource=resource, search_range=search_range)
result[resource] = (
calendar_start and revert_start_tz(calendar_start),
calendar_end and revert_end_tz(calendar_end),
)
return result
def _get_unavailable_intervals(self, start, end):
""" Compute the intervals during which employee is unavailable with hour granularity between start and end
Note: this method is used in enterprise (forecast and planning)
"""
start_datetime = timezone_datetime(start)
end_datetime = timezone_datetime(end)
resource_mapping = {}
calendar_mapping = defaultdict(lambda: self.env['resource.resource'])
for resource in self:
calendar_mapping[resource.calendar_id] |= resource
for calendar, resources in calendar_mapping.items():
resources_unavailable_intervals = calendar._unavailable_intervals_batch(start_datetime, end_datetime, resources, tz=timezone(calendar.tz))
resource_mapping.update(resources_unavailable_intervals)
return resource_mapping
class ResourceCalendarLeaves(models.Model):
_name = "resource.calendar.leaves"
_description = "Resource Time Off Detail"
_order = "date_from"
def default_get(self, fields_list):
res = super().default_get(fields_list)
if 'date_from' in fields_list and 'date_to' in fields_list and not res.get('date_from') and not res.get('date_to'):
# Then we give the current day and we search the begin and end hours for this day in resource.calendar of the current company
today = fields.Datetime.now()
user_tz = timezone(self.env.user.tz or self._context.get('tz') or self.company_id.resource_calendar_id.tz or 'UTC')
date_from = user_tz.localize(datetime.combine(today, time.min))
date_to = user_tz.localize(datetime.combine(today, time.max))
intervals = self.env.company.resource_calendar_id._work_intervals_batch(date_from.replace(tzinfo=utc), date_to.replace(tzinfo=utc))[False]
if intervals: # Then we stop and return the dates given in parameter
list_intervals = [(start, stop) for start, stop, records in intervals] # Convert intervals in interval list
date_from = list_intervals[0][0] # We take the first date in the interval list
date_to = list_intervals[-1][1] # We take the last date in the interval list
res.update(
date_from=date_from.astimezone(utc).replace(tzinfo=None),
date_to=date_to.astimezone(utc).replace(tzinfo=None)
)
return res
name = fields.Char('Reason')
company_id = fields.Many2one(
'res.company', string="Company", readonly=True, store=True,
default=lambda self: self.env.company, compute='_compute_company_id')
calendar_id = fields.Many2one('resource.calendar', 'Working Hours', domain="[('company_id', 'in', [company_id, False])]", check_company=True, index=True)
date_from = fields.Datetime('Start Date', required=True)
date_to = fields.Datetime('End Date', required=True)
resource_id = fields.Many2one(
"resource.resource", 'Resource', index=True,
help="If empty, this is a generic time off for the company. If a resource is set, the time off is only for this resource")
time_type = fields.Selection([('leave', 'Time Off'), ('other', 'Other')], default='leave',
help="Whether this should be computed as a time off or as work time (eg: formation)")
@api.depends('calendar_id')
def _compute_company_id(self):
for leave in self:
leave.company_id = leave.calendar_id.company_id or self.env.company
@api.constrains('date_from', 'date_to')
def check_dates(self):
if self.filtered(lambda leave: leave.date_from > leave.date_to):
raise ValidationError(_('The start date of the time off must be earlier than the end date.'))
@api.onchange('resource_id')
def onchange_resource(self):
if self.resource_id:
self.calendar_id = self.resource_id.calendar_id
def _copy_leave_vals(self):
self.ensure_one()
return {
'name': self.name,
'date_from': self.date_from,
'date_to': self.date_to,
'time_type': self.time_type,
}
| 46.459868
| 49,201
|
1,286
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
class ResCompany(models.Model):
_inherit = 'res.company'
resource_calendar_ids = fields.One2many(
'resource.calendar', 'company_id', 'Working Hours')
resource_calendar_id = fields.Many2one(
'resource.calendar', 'Default Working Hours', ondelete='restrict')
@api.model
def _init_data_resource_calendar(self):
self.search([('resource_calendar_id', '=', False)])._create_resource_calendar()
def _create_resource_calendar(self):
for company in self:
company.resource_calendar_id = self.env['resource.calendar'].create({
'name': _('Standard 40 hours/week'),
'company_id': company.id
}).id
@api.model
def create(self, values):
company = super(ResCompany, self).create(values)
if not company.resource_calendar_id:
company.sudo()._create_resource_calendar()
# calendar created from form view: no company_id set because record was still not created
if not company.resource_calendar_id.company_id:
company.resource_calendar_id.company_id = company.id
return company
| 37.823529
| 1,286
|
890
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class ResUsers(models.Model):
_inherit = 'res.users'
resource_ids = fields.One2many(
'resource.resource', 'user_id', 'Resources')
resource_calendar_id = fields.Many2one(
'resource.calendar', 'Default Working Hours',
related='resource_ids.calendar_id', readonly=False)
def write(self, vals):
rslt = super().write(vals)
# If the timezone of the admin user gets set on their first login, also update the timezone of the default working calendar
if (vals.get('tz') and len(self) == 1 and not self.env.user.login_date
and self.env.user == self.env.ref('base.user_admin', False) and self == self.env.user):
self.resource_calendar_id.tz = vals['tz']
return rslt
| 37.083333
| 890
|
8,729
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import defaultdict
from dateutil.relativedelta import relativedelta
from pytz import utc
from odoo import api, fields, models
def timezone_datetime(time):
if not time.tzinfo:
time = time.replace(tzinfo=utc)
return time
class ResourceMixin(models.AbstractModel):
_name = "resource.mixin"
_description = 'Resource Mixin'
resource_id = fields.Many2one(
'resource.resource', 'Resource',
auto_join=True, index=True, ondelete='restrict', required=True)
company_id = fields.Many2one(
'res.company', 'Company',
default=lambda self: self.env.company,
index=True, related='resource_id.company_id', store=True, readonly=False)
resource_calendar_id = fields.Many2one(
'resource.calendar', 'Working Hours',
default=lambda self: self.env.company.resource_calendar_id,
index=True, related='resource_id.calendar_id', store=True, readonly=False)
tz = fields.Selection(
string='Timezone', related='resource_id.tz', readonly=False,
help="This field is used in order to define in which timezone the resources will work.")
@api.model
def create(self, values):
if not values.get('resource_id'):
resource_vals = {'name': values.get(self._rec_name)}
tz = (values.pop('tz', False) or
self.env['resource.calendar'].browse(values.get('resource_calendar_id')).tz)
if tz:
resource_vals['tz'] = tz
resource = self.env['resource.resource'].create(resource_vals)
values['resource_id'] = resource.id
return super(ResourceMixin, self).create(values)
def copy_data(self, default=None):
if default is None:
default = {}
resource = self.resource_id.copy()
default['resource_id'] = resource.id
default['company_id'] = resource.company_id.id
default['resource_calendar_id'] = resource.calendar_id.id
return super(ResourceMixin, self).copy_data(default)
def _get_work_days_data_batch(self, from_datetime, to_datetime, compute_leaves=True, calendar=None, domain=None):
"""
By default the resource calendar is used, but it can be
changed using the `calendar` argument.
`domain` is used in order to recognise the leaves to take,
None means default value ('time_type', '=', 'leave')
Returns a dict {'days': n, 'hours': h} containing the
quantity of working time expressed as days and as hours.
"""
resources = self.mapped('resource_id')
mapped_employees = {e.resource_id.id: e.id for e in self}
result = {}
# naive datetimes are made explicit in UTC
from_datetime = timezone_datetime(from_datetime)
to_datetime = timezone_datetime(to_datetime)
mapped_resources = defaultdict(lambda: self.env['resource.resource'])
for record in self:
mapped_resources[calendar or record.resource_calendar_id] |= record.resource_id
for calendar, calendar_resources in mapped_resources.items():
if not calendar:
for calendar_resource in calendar_resources:
result[calendar_resource.id] = {'days': 0, 'hours': 0}
continue
day_total = calendar._get_resources_day_total(from_datetime, to_datetime, calendar_resources)
# actual hours per day
if compute_leaves:
intervals = calendar._work_intervals_batch(from_datetime, to_datetime, calendar_resources, domain)
else:
intervals = calendar._attendance_intervals_batch(from_datetime, to_datetime, calendar_resources)
for calendar_resource in calendar_resources:
result[calendar_resource.id] = calendar._get_days_data(intervals[calendar_resource.id], day_total[calendar_resource.id])
# convert "resource: result" into "employee: result"
return {mapped_employees[r.id]: result[r.id] for r in resources}
def _get_leave_days_data_batch(self, from_datetime, to_datetime, calendar=None, domain=None):
"""
By default the resource calendar is used, but it can be
changed using the `calendar` argument.
`domain` is used in order to recognise the leaves to take,
None means default value ('time_type', '=', 'leave')
Returns a dict {'days': n, 'hours': h} containing the number of leaves
expressed as days and as hours.
"""
resources = self.mapped('resource_id')
mapped_employees = {e.resource_id.id: e.id for e in self}
result = {}
# naive datetimes are made explicit in UTC
from_datetime = timezone_datetime(from_datetime)
to_datetime = timezone_datetime(to_datetime)
mapped_resources = defaultdict(lambda: self.env['resource.resource'])
for record in self:
mapped_resources[calendar or record.resource_calendar_id] |= record.resource_id
for calendar, calendar_resources in mapped_resources.items():
day_total = calendar._get_resources_day_total(from_datetime, to_datetime, calendar_resources)
# compute actual hours per day
attendances = calendar._attendance_intervals_batch(from_datetime, to_datetime, calendar_resources)
leaves = calendar._leave_intervals_batch(from_datetime, to_datetime, calendar_resources, domain)
for calendar_resource in calendar_resources:
result[calendar_resource.id] = calendar._get_days_data(
attendances[calendar_resource.id] & leaves[calendar_resource.id],
day_total[calendar_resource.id]
)
# convert "resource: result" into "employee: result"
return {mapped_employees[r.id]: result[r.id] for r in resources}
def _adjust_to_calendar(self, start, end):
resource_results = self.resource_id._adjust_to_calendar(start, end)
# change dict keys from resources to associated records.
return {
record: resource_results[record.resource_id]
for record in self
}
def list_work_time_per_day(self, from_datetime, to_datetime, calendar=None, domain=None):
"""
By default the resource calendar is used, but it can be
changed using the `calendar` argument.
`domain` is used in order to recognise the leaves to take,
None means default value ('time_type', '=', 'leave')
Returns a list of tuples (day, hours) for each day
containing at least an attendance.
"""
resource = self.resource_id
calendar = calendar or self.resource_calendar_id
# naive datetimes are made explicit in UTC
if not from_datetime.tzinfo:
from_datetime = from_datetime.replace(tzinfo=utc)
if not to_datetime.tzinfo:
to_datetime = to_datetime.replace(tzinfo=utc)
intervals = calendar._work_intervals_batch(from_datetime, to_datetime, resource, domain)[resource.id]
result = defaultdict(float)
for start, stop, meta in intervals:
result[start.date()] += (stop - start).total_seconds() / 3600
return sorted(result.items())
def list_leaves(self, from_datetime, to_datetime, calendar=None, domain=None):
"""
By default the resource calendar is used, but it can be
changed using the `calendar` argument.
`domain` is used in order to recognise the leaves to take,
None means default value ('time_type', '=', 'leave')
Returns a list of tuples (day, hours, resource.calendar.leaves)
for each leave in the calendar.
"""
resource = self.resource_id
calendar = calendar or self.resource_calendar_id
# naive datetimes are made explicit in UTC
if not from_datetime.tzinfo:
from_datetime = from_datetime.replace(tzinfo=utc)
if not to_datetime.tzinfo:
to_datetime = to_datetime.replace(tzinfo=utc)
attendances = calendar._attendance_intervals_batch(from_datetime, to_datetime, resource)[resource.id]
leaves = calendar._leave_intervals_batch(from_datetime, to_datetime, resource, domain)[resource.id]
result = []
for start, stop, leave in (leaves & attendances):
hours = (stop - start).total_seconds() / 3600
result.append((start.date(), hours, leave))
return result
| 44.085859
| 8,729
|
791
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Sale Purchase',
'summary': 'Sale based on service outsourcing.',
'description': """
Allows the outsourcing of services. This module allows one to sell services provided
by external providers and will automatically generate purchase orders directed to the service seller.
""",
'version': '1.0',
'website': 'https://www.odoo.com/',
'category': 'Hidden',
'depends': [
'sale',
'purchase',
],
'data': [
'data/mail_data.xml',
'views/product_views.xml',
'views/sale_order_views.xml',
'views/purchase_order_views.xml',
],
'demo': [
],
'auto_install': True,
'license': 'LGPL-3',
}
| 28.25
| 791
|
2,997
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.exceptions import AccessError
from odoo.addons.sale_purchase.tests.common import TestCommonSalePurchaseNoChart
from odoo.tests import tagged
@tagged('-at_install', 'post_install')
class TestAccessRights(TestCommonSalePurchaseNoChart):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
# Create a users
group_sale_user = cls.env.ref('sales_team.group_sale_salesman')
group_purchase_user = cls.env.ref('purchase.group_purchase_user')
cls.user_salesperson = cls.env['res.users'].with_context(no_reset_password=True).create({
'name': 'Le Grand Jojo User',
'login': 'grand.jojo',
'email': 'grand.jojo@chansonbelge.com',
'groups_id': [(6, 0, [group_sale_user.id])]
})
cls.user_purchaseperson = cls.env['res.users'].with_context(no_reset_password=True).create({
'name': 'Jean-Luc Fonck',
'login': 'jl.fonck',
'email': 'jl.fonck@chansonbelge.com',
'groups_id': [(6, 0, [group_purchase_user.id])]
})
def test_access_saleperson(self):
""" Check a saleperson (only) can generate a PO and a PO user can not confirm a SO """
SaleOrder = self.env['sale.order'].with_context(tracking_disable=True)
sale_order = SaleOrder.with_user(self.user_salesperson).create({
'partner_id': self.partner_a.id,
'user_id': self.user_salesperson.id
})
sol_service_purchase = self.env['sale.order.line'].with_user(self.user_salesperson).create({
'name': self.service_purchase_1.name,
'product_id': self.service_purchase_1.id,
'product_uom_qty': 4,
'product_uom': self.service_purchase_1.uom_id.id,
'price_unit': self.service_purchase_1.list_price,
'order_id': sale_order.id,
'tax_id': False,
})
# confirming SO will create the PO even if you don't have the rights
sale_order.action_confirm()
sale_order.action_cancel()
self.assertTrue(sale_order.name, "Saleperson can read its own SO")
action = sale_order.sudo().action_view_purchase_orders()
# try to access PO as sale person
with self.assertRaises(AccessError):
purchase_orders = self.env['purchase.order'].with_user(self.user_salesperson).browse(action['res_id'])
purchase_orders.read()
# try to access PO as purchase person
purchase_orders = self.env['purchase.order'].with_user(self.user_purchaseperson).browse(action['res_id'])
purchase_orders.read()
# try to access the PO lines from the SO, as sale person
with self.assertRaises(AccessError):
sol_service_purchase.with_user(self.user_salesperson).purchase_line_ids.read()
| 42.814286
| 2,997
|
2,605
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.sale.tests.common import TestSaleCommon
class TestCommonSalePurchaseNoChart(TestSaleCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
uom_unit = cls.env.ref('uom.product_uom_unit')
uom_dozen = cls.env.ref('uom.product_uom_dozen')
# Create category
cls.product_category_purchase = cls.env['product.category'].create({
'name': 'Product Category with Income account',
'property_account_income_categ_id': cls.company_data['default_account_expense'].id
})
cls.partner_vendor_service = cls.env['res.partner'].create({
'name': 'Super Service Supplier',
'email': 'supplier.serv@supercompany.com',
})
cls.service_purchase_1 = cls.env['product.product'].create({
'name': "Out-sourced Service 1",
'standard_price': 200.0,
'list_price': 180.0,
'type': 'service',
'uom_id': uom_unit.id,
'uom_po_id': uom_unit.id,
'invoice_policy': 'delivery',
'expense_policy': 'no',
'default_code': 'SERV_DEL',
'service_type': 'manual',
'taxes_id': False,
'categ_id': cls.product_category_purchase.id,
'service_to_purchase': True,
})
cls.service_purchase_2 = cls.env['product.product'].create({
'name': "Out-sourced Service 2",
'standard_price': 20.0,
'list_price': 15.0,
'type': 'service',
'uom_id': uom_dozen.id, # different UoM
'uom_po_id': uom_unit.id,
'invoice_policy': 'order',
'expense_policy': 'no',
'default_code': 'SERV_ORD',
'service_type': 'manual',
'taxes_id': False,
'categ_id': cls.product_category_purchase.id,
'service_to_purchase': True,
})
cls.supplierinfo1 = cls.env['product.supplierinfo'].create({
'name': cls.partner_vendor_service.id,
'price': 100,
'product_tmpl_id': cls.service_purchase_1.product_tmpl_id.id,
'delay': 1,
})
cls.supplierinfo2 = cls.env['product.supplierinfo'].create({
'name': cls.partner_vendor_service.id,
'price': 10,
'product_tmpl_id': cls.service_purchase_2.product_tmpl_id.id,
'delay': 5,
})
| 37.753623
| 2,605
|
17,751
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.exceptions import UserError, AccessError
from odoo.tests import tagged
from odoo.addons.sale_purchase.tests.common import TestCommonSalePurchaseNoChart
@tagged('-at_install', 'post_install')
class TestSalePurchase(TestCommonSalePurchaseNoChart):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
# create a generic Sale Order with 2 classical products and a purchase service
SaleOrder = cls.env['sale.order'].with_context(tracking_disable=True)
cls.sale_order_1 = SaleOrder.create({
'partner_id': cls.partner_a.id,
'partner_invoice_id': cls.partner_a.id,
'partner_shipping_id': cls.partner_a.id,
'pricelist_id': cls.company_data['default_pricelist'].id,
})
cls.sol1_service_deliver = cls.env['sale.order.line'].create({
'name': cls.company_data['product_service_delivery'].name,
'product_id': cls.company_data['product_service_delivery'].id,
'product_uom_qty': 1,
'product_uom': cls.company_data['product_service_delivery'].uom_id.id,
'price_unit': cls.company_data['product_service_delivery'].list_price,
'order_id': cls.sale_order_1.id,
'tax_id': False,
})
cls.sol1_product_order = cls.env['sale.order.line'].create({
'name': cls.company_data['product_order_no'].name,
'product_id': cls.company_data['product_order_no'].id,
'product_uom_qty': 2,
'product_uom': cls.company_data['product_order_no'].uom_id.id,
'price_unit': cls.company_data['product_order_no'].list_price,
'order_id': cls.sale_order_1.id,
'tax_id': False,
})
cls.sol1_service_purchase_1 = cls.env['sale.order.line'].create({
'name': cls.service_purchase_1.name,
'product_id': cls.service_purchase_1.id,
'product_uom_qty': 4,
'product_uom': cls.service_purchase_1.uom_id.id,
'price_unit': cls.service_purchase_1.list_price,
'order_id': cls.sale_order_1.id,
'tax_id': False,
})
cls.sale_order_2 = SaleOrder.create({
'partner_id': cls.partner_a.id,
'partner_invoice_id': cls.partner_a.id,
'partner_shipping_id': cls.partner_a.id,
'pricelist_id': cls.company_data['default_pricelist'].id,
})
cls.sol2_product_deliver = cls.env['sale.order.line'].create({
'name': cls.company_data['product_delivery_no'].name,
'product_id': cls.company_data['product_delivery_no'].id,
'product_uom_qty': 5,
'product_uom': cls.company_data['product_delivery_no'].uom_id.id,
'price_unit': cls.company_data['product_delivery_no'].list_price,
'order_id': cls.sale_order_2.id,
'tax_id': False,
})
cls.sol2_service_order = cls.env['sale.order.line'].create({
'name': cls.company_data['product_service_order'].name,
'product_id': cls.company_data['product_service_order'].id,
'product_uom_qty': 6,
'product_uom': cls.company_data['product_service_order'].uom_id.id,
'price_unit': cls.company_data['product_service_order'].list_price,
'order_id': cls.sale_order_2.id,
'tax_id': False,
})
cls.sol2_service_purchase_2 = cls.env['sale.order.line'].create({
'name': cls.service_purchase_2.name,
'product_id': cls.service_purchase_2.id,
'product_uom_qty': 7,
'product_uom': cls.service_purchase_2.uom_id.id,
'price_unit': cls.service_purchase_2.list_price,
'order_id': cls.sale_order_2.id,
'tax_id': False,
})
def test_sale_create_purchase(self):
""" Confirming 2 sales orders with a service that should create a PO, then cancelling the PO should shedule 1 next activity per SO """
self.sale_order_1.action_confirm()
self.sale_order_2.action_confirm()
purchase_order = self.env['purchase.order'].search([('partner_id', '=', self.supplierinfo1.name.id), ('state', '=', 'draft')])
purchase_lines_so1 = self.env['purchase.order.line'].search([('sale_line_id', 'in', self.sale_order_1.order_line.ids)])
purchase_line1 = purchase_lines_so1[0]
purchase_lines_so2 = self.env['purchase.order.line'].search([('sale_line_id', 'in', self.sale_order_2.order_line.ids)])
purchase_line2 = purchase_lines_so2[0]
self.assertEqual(len(purchase_order), 1, "Only one PO should have been created, from the 2 Sales orders")
self.assertEqual(len(purchase_order.order_line), 2, "The purchase order should have 2 lines")
self.assertEqual(len(purchase_lines_so1), 1, "Only one SO line from SO 1 should have create a PO line")
self.assertEqual(len(purchase_lines_so2), 1, "Only one SO line from SO 2 should have create a PO line")
self.assertEqual(len(purchase_order.activity_ids), 0, "No activity should be scheduled on the PO")
self.assertEqual(purchase_order.state, 'draft', "The created PO should be in draft state")
self.assertNotEqual(purchase_line1.product_id, purchase_line2.product_id, "The 2 PO line should have different products")
self.assertEqual(purchase_line1.product_id, self.sol1_service_purchase_1.product_id, "The create PO line must have the same product as its mother SO line")
self.assertEqual(purchase_line2.product_id, self.sol2_service_purchase_2.product_id, "The create PO line must have the same product as its mother SO line")
purchase_order.button_cancel()
self.assertEqual(len(self.sale_order_1.activity_ids), 1, "One activity should be scheduled on the SO 1 since the PO has been cancelled")
self.assertEqual(self.sale_order_1.user_id, self.sale_order_1.activity_ids[0].user_id, "The activity should be assigned to the SO responsible")
self.assertEqual(len(self.sale_order_2.activity_ids), 1, "One activity should be scheduled on the SO 2 since the PO has been cancelled")
self.assertEqual(self.sale_order_2.user_id, self.sale_order_2.activity_ids[0].user_id, "The activity should be assigned to the SO responsible")
def test_uom_conversion(self):
""" Test generated PO use the right UoM according to product configuration """
self.sale_order_2.action_confirm()
purchase_line = self.env['purchase.order.line'].search([('sale_line_id', '=', self.sol2_service_purchase_2.id)]) # only one line
self.assertTrue(purchase_line, "The SO line should generate a PO line")
self.assertEqual(purchase_line.product_uom, self.service_purchase_2.uom_po_id, "The UoM on the purchase line should be the one from the product configuration")
self.assertNotEqual(purchase_line.product_uom, self.sol2_service_purchase_2.product_uom, "As the product configuration, the UoM on the SO line should still be different from the one on the PO line")
self.assertEqual(purchase_line.product_qty, self.sol2_service_purchase_2.product_uom_qty * 12, "The quantity from the SO should be converted with th UoM factor on the PO line")
def test_no_supplier(self):
""" Test confirming SO with product with no supplier raise Error """
# delete the suppliers
self.supplierinfo1.unlink()
# confirm the SO should raise UserError
with self.assertRaises(UserError):
self.sale_order_1.action_confirm()
def test_reconfirm_sale_order(self):
""" Confirm SO, cancel it, then re-confirm it should not regenerate a purchase line """
self.sale_order_1.action_confirm()
purchase_order = self.env['purchase.order'].search([('partner_id', '=', self.supplierinfo1.name.id), ('state', '=', 'draft')])
purchase_lines = self.env['purchase.order.line'].search([('sale_line_id', 'in', self.sale_order_1.order_line.ids)])
purchase_line = purchase_lines[0]
self.assertEqual(len(purchase_lines), 1, "Only one purchase line should be created on SO confirmation")
self.assertEqual(len(purchase_order), 1, "One purchase order should have been created on SO confirmation")
self.assertEqual(len(purchase_order.order_line), 1, "Only one line on PO, after SO confirmation")
self.assertEqual(purchase_order, purchase_lines.order_id, "The generated purchase line should be in the generated purchase order")
self.assertEqual(purchase_order.state, 'draft', "Generated purchase should be in draft state")
self.assertEqual(purchase_line.price_unit, self.supplierinfo1.price, "Purchase line price is the one from the supplier")
self.assertEqual(purchase_line.product_qty, self.sol1_service_purchase_1.product_uom_qty, "Quantity on SO line is not the same on the purchase line (same UoM)")
self.sale_order_1.action_cancel()
self.assertEqual(len(purchase_order.activity_ids), 1, "One activity should be scheduled on the PO since a SO has been cancelled")
purchase_order = self.env['purchase.order'].search([('partner_id', '=', self.supplierinfo1.name.id), ('state', '=', 'draft')])
purchase_lines = self.env['purchase.order.line'].search([('sale_line_id', 'in', self.sale_order_1.order_line.ids)])
purchase_line = purchase_lines[0]
self.assertEqual(len(purchase_lines), 1, "Always one purchase line even after SO cancellation")
self.assertTrue(purchase_order, "Always one purchase order even after SO cancellation")
self.assertEqual(len(purchase_order.order_line), 1, "Still one line on PO, even after SO cancellation")
self.assertEqual(purchase_order, purchase_lines.order_id, "The generated purchase line should still be in the generated purchase order")
self.assertEqual(purchase_order.state, 'draft', "Generated purchase should still be in draft state")
self.assertEqual(purchase_line.price_unit, self.supplierinfo1.price, "Purchase line price is still the one from the supplier")
self.assertEqual(purchase_line.product_qty, self.sol1_service_purchase_1.product_uom_qty, "Quantity on SO line should still be the same on the purchase line (same UoM)")
self.sale_order_1.action_draft()
self.sale_order_1.action_confirm()
purchase_order = self.env['purchase.order'].search([('partner_id', '=', self.supplierinfo1.name.id), ('state', '=', 'draft')])
purchase_lines = self.env['purchase.order.line'].search([('sale_line_id', 'in', self.sale_order_1.order_line.ids)])
purchase_line = purchase_lines[0]
self.assertEqual(len(purchase_lines), 1, "Still only one purchase line should be created even after SO reconfirmation")
self.assertEqual(len(purchase_order), 1, "Still one purchase order should be after SO reconfirmation")
self.assertEqual(len(purchase_order.order_line), 1, "Only one line on PO, even after SO reconfirmation")
self.assertEqual(purchase_order, purchase_lines.order_id, "The generated purchase line should be in the generated purchase order")
self.assertEqual(purchase_order.state, 'draft', "Generated purchase should be in draft state")
self.assertEqual(purchase_line.price_unit, self.supplierinfo1.price, "Purchase line price is the one from the supplier")
self.assertEqual(purchase_line.product_qty, self.sol1_service_purchase_1.product_uom_qty, "Quantity on SO line is not the same on the purchase line (same UoM)")
def test_update_ordered_sale_quantity(self):
""" Test the purchase order behovior when changing the ordered quantity on the sale order line.
Increase of qty on the SO
- If PO is draft ['draft', 'sent', 'to approve'] : increase the quantity on the PO
- If PO is confirmed ['purchase', 'done', 'cancel'] : create a new PO
Decrease of qty on the SO
- If PO is draft ['draft', 'sent', 'to approve'] : next activity on the PO
- If PO is confirmed ['purchase', 'done', 'cancel'] : next activity on the PO
"""
self.sale_order_1.action_confirm()
purchase_order = self.env['purchase.order'].search([('partner_id', '=', self.supplierinfo1.name.id), ('state', '=', 'draft')])
purchase_lines = self.env['purchase.order.line'].search([('sale_line_id', 'in', self.sale_order_1.order_line.ids)])
purchase_line = purchase_lines[0]
self.assertEqual(purchase_order.state, 'draft', "The created purchase should be in draft state")
self.assertFalse(purchase_order.activity_ids, "There is no activities on the PO")
self.assertEqual(purchase_line.product_qty, self.sol1_service_purchase_1.product_uom_qty, "Quantity on SO line is not the same on the purchase line (same UoM)")
# increase the ordered quantity on sale line
self.sol1_service_purchase_1.write({'product_uom_qty': self.sol1_service_purchase_1.product_uom_qty + 12}) # product_uom_qty = 16
self.assertEqual(purchase_line.product_qty, self.sol1_service_purchase_1.product_uom_qty, "The quantity of draft PO line should be increased as the one from the sale line changed")
sale_line_old_quantity = self.sol1_service_purchase_1.product_uom_qty
# decrease the ordered quantity on sale line
self.sol1_service_purchase_1.write({'product_uom_qty': self.sol1_service_purchase_1.product_uom_qty - 3}) # product_uom_qty = 13
self.assertEqual(len(purchase_order.activity_ids), 1, "One activity should have been created on the PO")
self.assertEqual(purchase_order.activity_ids.user_id, purchase_order.user_id, "Activity assigned to PO responsible")
self.assertEqual(purchase_order.activity_ids.state, 'today', "Activity is for today, as it is urgent")
# confirm the PO
purchase_order.button_confirm()
# decrease the ordered quantity on sale line
self.sol1_service_purchase_1.write({'product_uom_qty': self.sol1_service_purchase_1.product_uom_qty - 5}) # product_uom_qty = 8
purchase_order.invalidate_cache() # Note: creating a second activity will not refresh the cache
self.assertEqual(purchase_line.product_qty, sale_line_old_quantity, "The quantity on the PO line should not have changed.")
self.assertEqual(len(purchase_order.activity_ids), 2, "a second activity should have been created on the PO")
self.assertEqual(purchase_order.activity_ids.mapped('user_id'), purchase_order.user_id, "Activities assigned to PO responsible")
self.assertEqual(purchase_order.activity_ids.mapped('state'), ['today', 'today'], "Activities are for today, as it is urgent")
# increase the ordered quantity on sale line
delta = 8
self.sol1_service_purchase_1.write({'product_uom_qty': self.sol1_service_purchase_1.product_uom_qty + delta}) # product_uom_qty = 16
self.assertEqual(purchase_line.product_qty, sale_line_old_quantity, "The quantity on the PO line should not have changed.")
self.assertEqual(len(purchase_order.activity_ids), 2, "Always 2 activity on confirmed the PO")
purchase_order2 = self.env['purchase.order'].search([('partner_id', '=', self.supplierinfo1.name.id), ('state', '=', 'draft')])
purchase_lines = self.env['purchase.order.line'].search([('sale_line_id', 'in', self.sale_order_1.order_line.ids)])
purchase_lines2 = purchase_lines.filtered(lambda pol: pol.order_id == purchase_order2)
purchase_line2 = purchase_lines2[0]
self.assertTrue(purchase_order2, "A second PO is created by increasing sale quantity when first PO is confirmed")
self.assertEqual(purchase_order2.state, 'draft', "The second PO is in draft state")
self.assertNotEqual(purchase_order, purchase_order2, "The 2 PO are different")
self.assertEqual(len(purchase_lines), 2, "The same Sale Line has created 2 purchase lines")
self.assertEqual(len(purchase_order2.order_line), 1, "The 2nd PO has only one line")
self.assertEqual(purchase_line2.sale_line_id, self.sol1_service_purchase_1, "The 2nd PO line came from the SO line sol1_service_purchase_1")
self.assertEqual(purchase_line2.product_qty, delta, "The quantity of the new PO line is the quantity added on the Sale Line, after first PO confirmation")
def test_pol_description(self):
"""
test cases when product names are different from how the vendor refers to, which is allowed
"""
service = self.env['product.product'].create({
'name': 'Super Product',
'type': 'service',
'service_to_purchase': True,
'seller_ids': [(0, 0, {
'name': self.partner_vendor_service.id,
'min_qty': 1,
'price': 10,
'product_code': 'C01',
'product_name': 'Name01',
'sequence': 1,
})]
})
so = self.env['sale.order'].create({
'partner_id': self.partner_a.id,
'order_line': [
(0, 0, {
'name': service.name,
'product_id': service.id,
'product_uom_qty': 1,
})
],
})
so.action_confirm()
po = self.env['purchase.order'].search([('partner_id', '=', self.partner_vendor_service.id)], order='id desc', limit=1)
self.assertEqual(po.order_line.name, "[C01] Name01")
| 63.852518
| 17,751
|
17,054
|
py
|
PYTHON
|
15.0
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models, _
from odoo.exceptions import UserError
from odoo.tools import float_compare
from odoo.tools.misc import get_lang
class SaleOrder(models.Model):
_inherit = 'sale.order'
purchase_order_count = fields.Integer(
"Number of Purchase Order Generated",
compute='_compute_purchase_order_count',
groups='purchase.group_purchase_user')
@api.depends('order_line.purchase_line_ids.order_id')
def _compute_purchase_order_count(self):
for order in self:
order.purchase_order_count = len(order._get_purchase_orders())
def _action_confirm(self):
result = super(SaleOrder, self)._action_confirm()
for order in self:
order.order_line.sudo()._purchase_service_generation()
return result
def _action_cancel(self):
result = super()._action_cancel()
# When a sale person cancel a SO, he might not have the rights to write
# on PO. But we need the system to create an activity on the PO (so 'write'
# access), hence the `sudo`.
self.sudo()._activity_cancel_on_purchase()
return result
def action_view_purchase_orders(self):
self.ensure_one()
purchase_order_ids = self._get_purchase_orders().ids
action = {
'res_model': 'purchase.order',
'type': 'ir.actions.act_window',
}
if len(purchase_order_ids) == 1:
action.update({
'view_mode': 'form',
'res_id': purchase_order_ids[0],
})
else:
action.update({
'name': _("Purchase Order generated from %s", self.name),
'domain': [('id', 'in', purchase_order_ids)],
'view_mode': 'tree,form',
})
return action
def _get_purchase_orders(self):
return self.order_line.purchase_line_ids.order_id
def _activity_cancel_on_purchase(self):
""" If some SO are cancelled, we need to put an activity on their generated purchase. If sale lines of
different sale orders impact different purchase, we only want one activity to be attached.
"""
purchase_to_notify_map = {} # map PO -> recordset of SOL as {purchase.order: set(sale.orde.liner)}
purchase_order_lines = self.env['purchase.order.line'].search([('sale_line_id', 'in', self.mapped('order_line').ids), ('state', '!=', 'cancel')])
for purchase_line in purchase_order_lines:
purchase_to_notify_map.setdefault(purchase_line.order_id, self.env['sale.order.line'])
purchase_to_notify_map[purchase_line.order_id] |= purchase_line.sale_line_id
for purchase_order, sale_order_lines in purchase_to_notify_map.items():
purchase_order._activity_schedule_with_view('mail.mail_activity_data_warning',
user_id=purchase_order.user_id.id or self.env.uid,
views_or_xmlid='sale_purchase.exception_purchase_on_sale_cancellation',
render_context={
'sale_orders': sale_order_lines.mapped('order_id'),
'sale_order_lines': sale_order_lines,
})
class SaleOrderLine(models.Model):
_inherit = 'sale.order.line'
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.")
purchase_line_count = fields.Integer("Number of generated purchase items", compute='_compute_purchase_count')
@api.depends('purchase_line_ids')
def _compute_purchase_count(self):
database_data = self.env['purchase.order.line'].sudo().read_group([('sale_line_id', 'in', self.ids)], ['sale_line_id'], ['sale_line_id'])
mapped_data = dict([(db['sale_line_id'][0], db['sale_line_id_count']) for db in database_data])
for line in self:
line.purchase_line_count = mapped_data.get(line.id, 0)
@api.onchange('product_uom_qty')
def _onchange_service_product_uom_qty(self):
if self.state == 'sale' and self.product_id.type == 'service' and self.product_id.service_to_purchase:
if self.product_uom_qty < self._origin.product_uom_qty:
if self.product_uom_qty < self.qty_delivered:
return {}
warning_mess = {
'title': _('Ordered quantity decreased!'),
'message': _('You are decreasing the ordered quantity! Do not forget to manually update the purchase order if needed.'),
}
return {'warning': warning_mess}
return {}
# --------------------------
# CRUD
# --------------------------
@api.model_create_multi
def create(self, values):
lines = super(SaleOrderLine, self).create(values)
# Do not generate purchase when expense SO line since the product is already delivered
lines.filtered(
lambda line: line.state == 'sale' and not line.is_expense
)._purchase_service_generation()
return lines
def write(self, values):
increased_lines = None
decreased_lines = None
increased_values = {}
decreased_values = {}
if 'product_uom_qty' in values:
precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')
increased_lines = self.sudo().filtered(lambda r: r.product_id.service_to_purchase and r.purchase_line_count and float_compare(r.product_uom_qty, values['product_uom_qty'], precision_digits=precision) == -1)
decreased_lines = self.sudo().filtered(lambda r: r.product_id.service_to_purchase and r.purchase_line_count and float_compare(r.product_uom_qty, values['product_uom_qty'], precision_digits=precision) == 1)
increased_values = {line.id: line.product_uom_qty for line in increased_lines}
decreased_values = {line.id: line.product_uom_qty for line in decreased_lines}
result = super(SaleOrderLine, self).write(values)
if increased_lines:
increased_lines._purchase_increase_ordered_qty(values['product_uom_qty'], increased_values)
if decreased_lines:
decreased_lines._purchase_decrease_ordered_qty(values['product_uom_qty'], decreased_values)
return result
# --------------------------
# Business Methods
# --------------------------
def _purchase_decrease_ordered_qty(self, new_qty, origin_values):
""" Decrease the quantity from SO line will add a next acitivities on the related purchase order
:param new_qty: new quantity (lower than the current one on SO line), expressed
in UoM of SO line.
:param origin_values: map from sale line id to old value for the ordered quantity (dict)
"""
purchase_to_notify_map = {} # map PO -> set(SOL)
last_purchase_lines = self.env['purchase.order.line'].search([('sale_line_id', 'in', self.ids)])
for purchase_line in last_purchase_lines:
purchase_to_notify_map.setdefault(purchase_line.order_id, self.env['sale.order.line'])
purchase_to_notify_map[purchase_line.order_id] |= purchase_line.sale_line_id
# create next activity
for purchase_order, sale_lines in purchase_to_notify_map.items():
render_context = {
'sale_lines': sale_lines,
'sale_orders': sale_lines.mapped('order_id'),
'origin_values': origin_values,
}
purchase_order._activity_schedule_with_view('mail.mail_activity_data_warning',
user_id=purchase_order.user_id.id or self.env.uid,
views_or_xmlid='sale_purchase.exception_purchase_on_sale_quantity_decreased',
render_context=render_context)
def _purchase_increase_ordered_qty(self, new_qty, origin_values):
""" Increase the quantity on the related purchase lines
:param new_qty: new quantity (higher than the current one on SO line), expressed
in UoM of SO line.
:param origin_values: map from sale line id to old value for the ordered quantity (dict)
"""
for line in self:
last_purchase_line = self.env['purchase.order.line'].search([('sale_line_id', '=', line.id)], order='create_date DESC', limit=1)
if last_purchase_line.state in ['draft', 'sent', 'to approve']: # update qty for draft PO lines
quantity = line.product_uom._compute_quantity(new_qty, last_purchase_line.product_uom)
last_purchase_line.write({'product_qty': quantity})
elif last_purchase_line.state in ['purchase', 'done', 'cancel']: # create new PO, by forcing the quantity as the difference from SO line
quantity = line.product_uom._compute_quantity(new_qty - origin_values.get(line.id, 0.0), last_purchase_line.product_uom)
line._purchase_service_create(quantity=quantity)
def _purchase_get_date_order(self, supplierinfo):
""" return the ordered date for the purchase order, computed as : SO commitment date - supplier delay """
commitment_date = fields.Datetime.from_string(self.order_id.commitment_date or fields.Datetime.now())
return commitment_date - relativedelta(days=int(supplierinfo.delay))
def _purchase_service_prepare_order_values(self, supplierinfo):
""" Returns the values to create the purchase order from the current SO line.
:param supplierinfo: record of product.supplierinfo
:rtype: dict
"""
self.ensure_one()
partner_supplier = supplierinfo.name
fpos = self.env['account.fiscal.position'].sudo().get_fiscal_position(partner_supplier.id)
date_order = self._purchase_get_date_order(supplierinfo)
return {
'partner_id': partner_supplier.id,
'partner_ref': partner_supplier.ref,
'company_id': self.company_id.id,
'currency_id': partner_supplier.property_purchase_currency_id.id or self.env.company.currency_id.id,
'dest_address_id': False, # False since only supported in stock
'origin': self.order_id.name,
'payment_term_id': partner_supplier.property_supplier_payment_term_id.id,
'date_order': date_order,
'fiscal_position_id': fpos.id,
}
def _purchase_service_prepare_line_values(self, purchase_order, quantity=False):
""" Returns the values to create the purchase order line from the current SO line.
:param purchase_order: record of purchase.order
:rtype: dict
:param quantity: the quantity to force on the PO line, expressed in SO line UoM
"""
self.ensure_one()
# compute quantity from SO line UoM
product_quantity = self.product_uom_qty
if quantity:
product_quantity = quantity
purchase_qty_uom = self.product_uom._compute_quantity(product_quantity, self.product_id.uom_po_id)
# determine vendor (real supplier, sharing the same partner as the one from the PO, but with more accurate informations like validity, quantity, ...)
# Note: one partner can have multiple supplier info for the same product
supplierinfo = self.product_id._select_seller(
partner_id=purchase_order.partner_id,
quantity=purchase_qty_uom,
date=purchase_order.date_order and purchase_order.date_order.date(), # and purchase_order.date_order[:10],
uom_id=self.product_id.uom_po_id
)
supplier_taxes = self.product_id.supplier_taxes_id.filtered(lambda t: t.company_id.id == self.company_id.id)
taxes = purchase_order.fiscal_position_id.map_tax(supplier_taxes)
# compute unit price
price_unit = 0.0
product_ctx = {
'lang': get_lang(self.env, purchase_order.partner_id.lang).code,
'company_id': purchase_order.company_id,
}
if supplierinfo:
price_unit = self.env['account.tax'].sudo()._fix_tax_included_price_company(
supplierinfo.price, supplier_taxes, taxes, self.company_id)
if purchase_order.currency_id and supplierinfo.currency_id != purchase_order.currency_id:
price_unit = supplierinfo.currency_id._convert(price_unit, purchase_order.currency_id, purchase_order.company_id, fields.Date.context_today(self))
product_ctx.update({'seller_id': supplierinfo.id})
else:
product_ctx.update({'partner_id': purchase_order.partner_id.id})
product = self.product_id.with_context(**product_ctx)
name = product.display_name
if product.description_purchase:
name += '\n' + product.description_purchase
return {
'name': name,
'product_qty': purchase_qty_uom,
'product_id': self.product_id.id,
'product_uom': self.product_id.uom_po_id.id,
'price_unit': price_unit,
'date_planned': fields.Date.from_string(purchase_order.date_order) + relativedelta(days=int(supplierinfo.delay)),
'taxes_id': [(6, 0, taxes.ids)],
'order_id': purchase_order.id,
'sale_line_id': self.id,
}
def _purchase_service_create(self, quantity=False):
""" On Sales Order confirmation, some lines (services ones) can create a purchase order line and maybe a purchase order.
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
a new PO line. The created purchase order line will be linked to the SO line.
:param quantity: the quantity to force on the PO line, expressed in SO line UoM
"""
PurchaseOrder = self.env['purchase.order']
supplier_po_map = {}
sale_line_purchase_map = {}
for line in self:
line = line.with_company(line.company_id)
# determine vendor of the order (take the first matching company and product)
suppliers = line.product_id._select_seller(quantity=line.product_uom_qty, uom_id=line.product_uom)
if not suppliers:
raise UserError(_("There is no vendor associated to the product %s. Please define a vendor for this product.") % (line.product_id.display_name,))
supplierinfo = suppliers[0]
partner_supplier = supplierinfo.name # yes, this field is not explicit .... it is a res.partner !
# determine (or create) PO
purchase_order = supplier_po_map.get(partner_supplier.id)
if not purchase_order:
purchase_order = PurchaseOrder.search([
('partner_id', '=', partner_supplier.id),
('state', '=', 'draft'),
('company_id', '=', line.company_id.id),
], limit=1)
if not purchase_order:
values = line._purchase_service_prepare_order_values(supplierinfo)
purchase_order = PurchaseOrder.with_context(mail_create_nosubscribe=True).create(values)
else: # update origin of existing PO
so_name = line.order_id.name
origins = []
if purchase_order.origin:
origins = purchase_order.origin.split(', ') + origins
if so_name not in origins:
origins += [so_name]
purchase_order.write({
'origin': ', '.join(origins)
})
supplier_po_map[partner_supplier.id] = purchase_order
# add a PO line to the PO
values = line._purchase_service_prepare_line_values(purchase_order, quantity=quantity)
purchase_line = line.env['purchase.order.line'].create(values)
# link the generated purchase to the SO line
sale_line_purchase_map.setdefault(line, line.env['purchase.order.line'])
sale_line_purchase_map[line] |= purchase_line
return sale_line_purchase_map
def _purchase_service_generation(self):
""" Create a Purchase for the first time from the sale line. If the SO line already created a PO, it
will not create a second one.
"""
sale_line_purchase_map = {}
for line in self:
# Do not regenerate PO line if the SO line has already created one in the past (SO cancel/reconfirmation case)
if line.product_id.service_to_purchase and not line.purchase_line_count:
result = line._purchase_service_create()
sale_line_purchase_map.update(result)
return sale_line_purchase_map
| 51.993902
| 17,054
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.