Files
tryton/forecast.py
T

623 lines
21 KiB
Python
Raw Normal View History

2014-12-02 12:56:06 +01:00
# This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
2018-06-26 19:11:55 +02:00
2010-08-10 11:58:52 -04:00
import datetime
import itertools
2021-12-11 17:58:44 +01:00
from dateutil.relativedelta import relativedelta
from sql import Null
2013-09-06 22:34:50 +02:00
from sql.aggregate import Sum
from sql.conditionals import Coalesce
2018-12-29 14:20:29 +01:00
from trytond.i18n import gettext
2021-12-11 17:58:44 +01:00
from trytond.model import ModelSQL, ModelView, Unique, Workflow, fields
2018-12-29 14:20:29 +01:00
from trytond.model.exceptions import AccessError
2011-07-03 13:19:15 +02:00
from trytond.pool import Pool
2021-12-11 17:58:44 +01:00
from trytond.pyson import Bool, Equal, Eval, If, Not, Or
from trytond.tools import grouped_slice, reduce_ids
from trytond.transaction import Transaction
from trytond.wizard import Button, StateTransition, StateView, Wizard
2008-11-10 21:44:37 +01:00
2018-12-29 14:20:29 +01:00
from .exceptions import ForecastValidationError
2008-11-10 21:44:37 +01:00
2012-03-25 00:18:20 +01:00
class Forecast(Workflow, ModelSQL, ModelView):
2008-11-10 21:44:37 +01:00
"Stock Forecast"
2012-09-24 22:18:18 +02:00
__name__ = "stock.forecast"
_states = {
'readonly': Not(Equal(Eval('state'), 'draft')),
}
_depends = ['state']
warehouse = fields.Many2One(
2008-11-10 21:44:37 +01:00
'stock.location', 'Location', required=True,
domain=[('type', '=', 'warehouse')], states={
2010-01-20 11:04:40 +01:00
'readonly': Or(Not(Equal(Eval('state'), 'draft')),
Bool(Eval('lines', [0]))),
2011-08-04 16:57:43 +02:00
},
depends=['state'])
2008-11-10 21:44:37 +01:00
destination = fields.Many2One(
'stock.location', 'Destination', required=True,
domain=[('type', 'in', ['customer', 'production'])], states=_states,
depends=_depends)
from_date = fields.Date(
"From Date", required=True,
domain=[('from_date', '<=', Eval('to_date'))],
states=_states, depends=_depends + ['to_date'])
to_date = fields.Date(
"To Date", required=True,
domain=[('to_date', '>=', Eval('from_date'))],
states=_states, depends=_depends + ['from_date'])
2008-11-10 21:44:37 +01:00
lines = fields.One2Many(
'stock.forecast.line', 'forecast', 'Lines', states=_states,
depends=_depends)
2008-11-10 21:44:37 +01:00
company = fields.Many2One(
'company.company', 'Company', required=True, states={
2010-01-20 11:04:40 +01:00
'readonly': Or(Not(Equal(Eval('state'), 'draft')),
Bool(Eval('lines', [0]))),
2011-08-04 16:57:43 +02:00
},
depends=['state'])
state = fields.Selection([
('draft', "Draft"),
('done', "Done"),
('cancelled', "Cancelled"),
], "State", readonly=True, select=True)
2015-01-15 23:55:50 +01:00
active = fields.Function(fields.Boolean('Active'),
'get_active', searcher='search_active')
2008-11-10 21:44:37 +01:00
del _states, _depends
2012-09-24 22:18:18 +02:00
@classmethod
def __setup__(cls):
super(Forecast, cls).__setup__()
cls._order.insert(0, ('from_date', 'DESC'))
cls._order.insert(1, ('warehouse', 'ASC'))
cls._transitions |= set((
2012-03-25 00:18:20 +01:00
('draft', 'done'),
('draft', 'cancelled'),
2012-03-25 00:18:20 +01:00
('done', 'draft'),
('cancelled', 'draft'),
2012-03-25 00:18:20 +01:00
))
2012-09-24 22:18:18 +02:00
cls._buttons.update({
2012-03-25 00:18:20 +01:00
'cancel': {
'invisible': Eval('state') != 'draft',
2018-02-19 11:42:01 +01:00
'depends': ['state'],
2012-03-25 00:18:20 +01:00
},
'draft': {
'invisible': Eval('state') == 'draft',
2018-02-19 11:42:01 +01:00
'depends': ['state'],
2012-03-25 00:18:20 +01:00
},
'confirm': {
'invisible': Eval('state') != 'draft',
2018-02-19 11:42:01 +01:00
'depends': ['state'],
2012-03-25 00:18:20 +01:00
},
2012-09-10 15:28:40 +02:00
'complete': {
'readonly': Eval('state') != 'draft',
2018-02-19 11:42:01 +01:00
'depends': ['state'],
2012-09-10 15:28:40 +02:00
},
2012-03-25 00:18:20 +01:00
})
2018-03-26 14:15:20 +02:00
cls._active_field = 'active'
2008-11-11 14:35:13 +01:00
2012-09-24 22:18:18 +02:00
@classmethod
def __register__(cls, module_name):
cursor = Transaction().connection.cursor()
sql_table = cls.__table__()
2012-09-24 22:18:18 +02:00
super(Forecast, cls).__register__(module_name)
2010-01-23 11:47:52 +01:00
# Add index on create_date
2018-07-24 22:01:08 +02:00
table = cls.__table_handler__(module_name)
2010-01-23 11:47:52 +01:00
table.index_action('create_date', action='add')
# Migration from 5.0: remove check_from_to_date
table.drop_constraint('check_from_to_date')
# Migration from 5.6: rename state cancel to cancelled
cursor.execute(*sql_table.update(
[sql_table.state], ['cancelled'],
where=sql_table.state == 'cancel'))
2012-09-24 22:18:18 +02:00
@staticmethod
def default_state():
2008-11-10 21:44:37 +01:00
return 'draft'
2012-09-24 22:18:18 +02:00
@classmethod
def default_destination(cls):
Location = Pool().get('stock.location')
locations = Location.search(cls.destination.domain)
if len(locations) == 1:
return locations[0].id
2008-11-11 14:35:13 +01:00
2012-09-24 22:18:18 +02:00
@staticmethod
def default_company():
2012-03-27 10:44:05 +02:00
return Transaction().context.get('company')
2008-11-10 21:44:37 +01:00
2015-01-15 23:55:50 +01:00
def get_active(self, name):
pool = Pool()
Date = pool.get('ir.date')
return self.to_date >= Date.today()
@classmethod
def search_active(cls, name, clause):
pool = Pool()
Date = pool.get('ir.date')
today = Date.today()
operators = {
'=': '>=',
'!=': '<',
}
reverse = {
'=': '!=',
'!=': '=',
}
if clause[1] in operators:
if clause[2]:
return [('to_date', operators[clause[1]], today)]
else:
return [('to_date', operators[reverse[clause[1]]], today)]
else:
return []
2017-07-26 23:43:27 +02:00
def get_rec_name(self, name):
return self.warehouse.rec_name
@classmethod
def search_rec_name(cls, name, clause):
2017-09-27 18:37:34 +02:00
return [('warehouse.rec_name',) + tuple(clause[1:])]
2017-07-26 23:43:27 +02:00
@classmethod
def validate(cls, forecasts):
super(Forecast, cls).validate(forecasts)
for forecast in forecasts:
forecast.check_date_overlap()
2012-09-24 22:18:18 +02:00
def check_date_overlap(self):
if self.state != 'done':
2013-10-15 15:09:22 +02:00
return
2016-07-07 10:07:33 +02:00
transaction = Transaction()
connection = transaction.connection
self.__class__.lock()
2013-09-06 22:34:50 +02:00
forcast = self.__table__()
2016-07-07 10:07:33 +02:00
cursor = connection.cursor()
2013-09-06 22:34:50 +02:00
cursor.execute(*forcast.select(forcast.id,
where=(((forcast.from_date <= self.from_date)
& (forcast.to_date >= self.from_date))
| ((forcast.from_date <= self.to_date)
& (forcast.to_date >= self.to_date))
| ((forcast.from_date >= self.from_date)
& (forcast.to_date <= self.to_date)))
& (forcast.warehouse == self.warehouse.id)
& (forcast.destination == self.destination.id)
& (forcast.company == self.company.id)
& (forcast.id != self.id)))
forecast_id = cursor.fetchone()
if forecast_id:
second = self.__class__(forecast_id[0])
2018-12-29 14:20:29 +01:00
raise ForecastValidationError(
gettext('stock_forecast.msg_forecast_date_overlap',
first=self.rec_name,
second=second.rec_name))
2008-11-11 17:51:55 +01:00
2012-09-24 22:18:18 +02:00
@classmethod
2018-09-19 00:15:59 +02:00
def delete(cls, forecasts):
# Cancel before delete
2018-09-19 00:15:59 +02:00
cls.cancel(forecasts)
2012-09-24 22:18:18 +02:00
for forecast in forecasts:
if forecast.state != 'cancelled':
2018-12-29 14:20:29 +01:00
raise AccessError(
gettext('stock_forecast.msg_forecast_delete_cancel',
forecast=forecast.rec_name))
2018-09-19 00:15:59 +02:00
super(Forecast, cls).delete(forecasts)
2012-09-24 22:18:18 +02:00
@classmethod
2012-03-25 00:18:20 +01:00
@ModelView.button
@Workflow.transition('draft')
2012-09-24 22:18:18 +02:00
def draft(cls, forecasts):
2012-03-25 00:18:20 +01:00
pass
2008-11-10 21:44:37 +01:00
2012-09-24 22:18:18 +02:00
@classmethod
2012-03-25 00:18:20 +01:00
@ModelView.button
@Workflow.transition('done')
2012-09-24 22:18:18 +02:00
def confirm(cls, forecasts):
2012-03-25 00:18:20 +01:00
pass
2008-11-10 21:44:37 +01:00
2012-09-24 22:18:18 +02:00
@classmethod
2012-03-25 00:18:20 +01:00
@ModelView.button
@Workflow.transition('cancelled')
2012-09-24 22:18:18 +02:00
def cancel(cls, forecasts):
2012-03-25 00:18:20 +01:00
pass
2012-09-24 22:18:18 +02:00
@classmethod
2012-09-10 15:28:40 +02:00
@ModelView.button_action('stock_forecast.wizard_forecast_complete')
2012-09-24 22:18:18 +02:00
def complete(cls, forecasts):
2012-09-10 15:28:40 +02:00
pass
2012-09-24 22:18:18 +02:00
@staticmethod
def create_moves(forecasts):
'Create stock moves for the forecast ids'
2016-06-20 10:51:02 +02:00
pool = Pool()
Line = pool.get('stock.forecast.line')
to_save = []
for forecast in forecasts:
if forecast.state == 'done':
for line in forecast.lines:
2016-06-20 10:51:02 +02:00
line.moves += tuple(line.get_moves())
to_save.append(line)
Line.save(to_save)
2012-09-24 22:18:18 +02:00
@staticmethod
def delete_moves(forecasts):
'Delete stock moves for the forecast ids'
2012-09-24 22:18:18 +02:00
Line = Pool().get('stock.forecast.line')
Line.delete_moves([l for f in forecasts for l in f.lines])
2009-07-16 18:52:56 +02:00
2009-02-28 17:04:59 +01:00
class ForecastLine(ModelSQL, ModelView):
2008-11-10 21:44:37 +01:00
'Stock Forecast Line'
2012-09-24 22:18:18 +02:00
__name__ = 'stock.forecast.line'
2016-06-30 18:56:34 +02:00
_states = {
'readonly': Eval('forecast_state') != 'draft',
}
_depends = ['forecast_state']
2008-11-10 21:44:37 +01:00
product = fields.Many2One('product.product', 'Product', required=True,
domain=[
('type', '=', 'goods'),
('consumable', '=', False),
2016-06-30 18:56:34 +02:00
],
states=_states, depends=_depends)
2012-03-25 15:39:12 +02:00
product_uom_category = fields.Function(
2014-01-26 14:29:38 +01:00
fields.Many2One('product.uom.category', 'Product Uom Category'),
2012-09-24 22:18:18 +02:00
'on_change_with_product_uom_category')
2011-08-04 16:57:43 +02:00
uom = fields.Many2One('product.uom', 'UOM', required=True,
2010-01-20 11:04:40 +01:00
domain=[
2012-03-25 15:39:12 +02:00
If(Bool(Eval('product_uom_category')),
('category', '=', Eval('product_uom_category')),
('category', '!=', -1)),
2016-06-30 18:56:34 +02:00
],
states=_states,
depends=['product', 'product_uom_category'] + _depends)
quantity = fields.Float(
2021-08-30 00:27:14 +02:00
"Quantity", digits='uom', required=True,
domain=[('quantity', '>=', 0)],
2021-08-30 00:27:14 +02:00
states=_states, depends=_depends)
minimal_quantity = fields.Float(
2021-08-30 00:27:14 +02:00
"Minimal Qty", digits='uom', required=True,
domain=[('minimal_quantity', '<=', Eval('quantity'))],
2021-08-30 00:27:14 +02:00
states=_states, depends=['quantity'] + _depends)
2009-03-05 14:54:34 +01:00
moves = fields.Many2Many('stock.forecast.line-stock.move',
2012-04-03 20:07:44 +02:00
'line', 'move', 'Moves', readonly=True)
2008-11-20 18:31:12 +01:00
forecast = fields.Many2One(
2016-06-30 18:56:34 +02:00
'stock.forecast', 'Forecast', required=True, ondelete='CASCADE',
states={
'readonly': ((Eval('forecast_state') != 'draft')
& Bool(Eval('forecast'))),
},
depends=['forecast_state'])
forecast_state = fields.Function(
fields.Selection('get_forecast_states', 'Forecast State'),
2016-06-30 18:56:34 +02:00
'on_change_with_forecast_state')
2021-08-30 00:27:14 +02:00
quantity_executed = fields.Function(fields.Float(
"Quantity Executed", digits='uom'), 'get_quantity_executed')
2008-11-10 21:44:37 +01:00
2016-06-30 18:56:34 +02:00
del _states, _depends
2012-09-24 22:18:18 +02:00
@classmethod
def __setup__(cls):
super(ForecastLine, cls).__setup__()
2021-03-07 11:13:53 +01:00
cls.__access__.add('forecast')
t = cls.__table__()
2012-09-24 22:18:18 +02:00
cls._sql_constraints += [
('forecast_product_uniq', Unique(t, t.forecast, t.product),
2018-12-29 14:20:29 +01:00
'stock_forecast.msg_forecast_line_product_unique'),
2012-09-24 22:18:18 +02:00
]
2008-11-10 21:44:37 +01:00
@classmethod
def __register__(cls, module_name):
super().__register__(module_name)
table_h = cls.__table_handler__(module_name)
# Migration from 5.0: remove check on quantity
table_h.drop_constraint('check_line_qty_pos')
table_h.drop_constraint('check_line_minimal_qty')
2012-09-24 22:18:18 +02:00
@staticmethod
def default_minimal_quantity():
2008-11-11 14:35:13 +01:00
return 1.0
2014-01-26 14:29:38 +01:00
@fields.depends('product')
2012-09-24 22:18:18 +02:00
def on_change_product(self):
if self.product:
2014-10-29 20:40:26 +01:00
self.uom = self.product.default_uom
2008-11-10 21:44:37 +01:00
2014-01-26 14:29:38 +01:00
@fields.depends('product')
2012-09-24 22:18:18 +02:00
def on_change_with_product_uom_category(self, name=None):
if self.product:
return self.product.default_uom_category.id
2012-03-25 15:39:12 +02:00
@classmethod
def get_forecast_states(cls):
pool = Pool()
Forecast = pool.get('stock.forecast')
return Forecast.fields_get(['state'])['state']['selection']
2016-06-30 18:56:34 +02:00
@fields.depends('forecast', '_parent_forecast.state')
def on_change_with_forecast_state(self, name=None):
if self.forecast:
return self.forecast.state
2017-07-26 23:43:27 +02:00
def get_rec_name(self, name):
return self.product.rec_name
@classmethod
def search_rec_name(cls, name, clause):
2017-09-27 18:37:34 +02:00
return [('product.rec_name',) + tuple(clause[1:])]
2017-07-26 23:43:27 +02:00
2012-09-24 22:18:18 +02:00
@classmethod
def get_quantity_executed(cls, lines, name):
cursor = Transaction().connection.cursor()
2012-09-24 22:18:18 +02:00
pool = Pool()
Move = pool.get('stock.move')
Location = pool.get('stock.location')
Uom = pool.get('product.uom')
Forecast = pool.get('stock.forecast')
LineMove = pool.get('stock.forecast.line-stock.move')
2013-09-06 22:34:50 +02:00
move = Move.__table__()
location_from = Location.__table__()
location_to = Location.__table__()
line_move = LineMove.__table__()
2012-09-24 22:18:18 +02:00
result = dict((x.id, 0) for x in lines)
2020-03-01 12:33:54 +01:00
def key(line):
return line.forecast.id
lines.sort(key=key)
for forecast_id, lines in itertools.groupby(lines, key):
2012-09-24 22:18:18 +02:00
forecast = Forecast(forecast_id)
product2line = dict((line.product.id, line) for line in lines)
product_ids = product2line.keys()
2014-07-17 19:01:16 +02:00
for sub_ids in grouped_slice(product_ids):
2013-09-06 22:34:50 +02:00
red_sql = reduce_ids(move.product, sub_ids)
cursor.execute(*move.join(location_from,
condition=move.from_location == location_from.id
).join(location_to,
condition=move.to_location == location_to.id
).join(line_move, 'LEFT',
condition=move.id == line_move.move
).select(move.product, Sum(move.internal_quantity),
where=red_sql
& (location_from.left >= forecast.warehouse.left)
& (location_from.right <= forecast.warehouse.right)
& (location_to.left >= forecast.destination.left)
& (location_to.right <= forecast.destination.right)
2020-06-06 10:30:12 +01:00
& (move.state != 'cancelled')
2013-09-06 22:34:50 +02:00
& (Coalesce(move.effective_date, move.planned_date)
>= forecast.from_date)
& (Coalesce(move.effective_date, move.planned_date)
<= forecast.to_date)
& (line_move.id == Null),
2013-09-06 22:34:50 +02:00
group_by=move.product))
for product_id, quantity in cursor:
line = product2line[product_id]
2012-09-24 22:18:18 +02:00
result[line.id] = Uom.compute_qty(line.product.default_uom,
quantity, line.uom)
return result
2012-09-24 22:18:18 +02:00
@classmethod
def copy(cls, lines, default=None):
if default is None:
default = {}
2018-09-01 01:02:04 +02:00
else:
default = default.copy()
default.setdefault('moves', None)
2012-09-24 22:18:18 +02:00
return super(ForecastLine, cls).copy(lines, default=default)
2016-06-20 10:51:02 +02:00
def get_moves(self):
'Get stock moves for the forecast line'
2012-09-24 22:18:18 +02:00
pool = Pool()
Move = pool.get('stock.move')
Uom = pool.get('product.uom')
Date = pool.get('ir.date')
2012-09-24 22:18:18 +02:00
assert not self.moves
2012-09-24 22:18:18 +02:00
today = Date.today()
from_date = self.forecast.from_date
if from_date < today:
from_date = today
2012-09-24 22:18:18 +02:00
to_date = self.forecast.to_date
if to_date < today:
return []
delta = to_date - from_date
2008-11-11 23:59:08 +01:00
delta = delta.days + 1
2016-03-01 21:48:31 +01:00
nb_packet = ((self.quantity - self.quantity_executed)
// self.minimal_quantity)
2010-08-10 11:58:52 -04:00
distribution = self.distribute(delta, nb_packet)
2012-03-27 10:44:05 +02:00
unit_price = None
2012-09-24 22:18:18 +02:00
if self.forecast.destination.type == 'customer':
unit_price = self.product.list_price or 0
2012-09-24 22:18:18 +02:00
unit_price = Uom.compute_price(self.product.default_uom,
unit_price, self.uom)
2008-11-10 21:44:37 +01:00
2016-06-20 10:51:02 +02:00
moves = []
2018-06-26 19:11:55 +02:00
for day, qty in distribution.items():
2008-11-10 21:44:37 +01:00
if qty == 0.0:
continue
2016-06-20 10:51:02 +02:00
move = Move()
move.from_location = self.forecast.warehouse.storage_location
move.to_location = self.forecast.destination
move.product = self.product
move.uom = self.uom
move.quantity = qty * self.minimal_quantity
move.planned_date = from_date + datetime.timedelta(day)
2016-06-20 10:51:02 +02:00
move.company = self.forecast.company
move.currency = self.forecast.company.currency
move.unit_price = unit_price
moves.append(move)
return moves
2008-11-10 21:44:37 +01:00
2012-09-24 22:18:18 +02:00
@classmethod
def delete_moves(cls, lines):
'Delete stock moves of the forecast line'
2012-09-24 22:18:18 +02:00
Move = Pool().get('stock.move')
Move.delete([m for l in lines for m in l.moves])
2008-11-10 21:44:37 +01:00
2015-05-08 12:47:33 +02:00
def distribute(self, delta, qty):
'Distribute qty over delta'
2018-06-26 19:11:55 +02:00
range_delta = list(range(delta))
2008-11-11 14:35:13 +01:00
a = {}.fromkeys(range_delta, 0)
while qty > 0:
if qty > delta:
for i in range_delta:
2012-04-03 20:07:44 +02:00
a[i] += qty // delta
qty = qty % delta
elif delta // qty > 1:
2008-11-11 14:35:13 +01:00
i = 0
while i < qty:
2016-03-01 21:48:31 +01:00
a[i * delta // qty + (delta // qty // 2)] += 1
2008-11-11 14:35:13 +01:00
i += 1
qty = 0
else:
for i in range_delta:
a[i] += 1
2012-04-03 20:07:44 +02:00
qty = delta - qty
2008-11-11 14:35:13 +01:00
i = 0
while i < qty:
2016-03-01 21:48:31 +01:00
a[delta - ((i * delta // qty) + (delta // qty // 2)) - 1
2012-04-03 20:07:44 +02:00
] -= 1
2008-11-11 14:35:13 +01:00
i += 1
qty = 0
return a
2008-11-20 18:31:47 +01:00
2009-03-05 14:54:34 +01:00
class ForecastLineMove(ModelSQL):
'ForecastLine - Move'
2012-09-24 22:18:18 +02:00
__name__ = 'stock.forecast.line-stock.move'
2009-03-05 14:54:34 +01:00
_table = 'forecast_line_stock_move_rel'
line = fields.Many2One('stock.forecast.line', 'Forecast Line',
2012-03-05 10:53:08 +01:00
ondelete='CASCADE', select=True, required=True)
2009-03-05 14:54:34 +01:00
move = fields.Many2One('stock.move', 'Move', ondelete='CASCADE',
2012-03-05 10:53:08 +01:00
select=True, required=True)
2009-03-05 14:54:34 +01:00
2009-02-28 17:04:59 +01:00
class ForecastCompleteAsk(ModelView):
2012-01-02 18:08:18 +01:00
'Complete Forecast'
2012-09-24 22:18:18 +02:00
__name__ = 'stock.forecast.complete.ask'
2018-12-29 14:20:29 +01:00
from_date = fields.Date(
"From Date", required=True,
domain=[('from_date', '<', Eval('to_date'))],
depends=['to_date'])
to_date = fields.Date(
"To Date", required=True,
domain=[('to_date', '>', Eval('from_date'))],
depends=['from_date'])
2008-11-20 18:31:47 +01:00
2009-02-28 17:04:59 +01:00
class ForecastCompleteChoose(ModelView):
2012-01-02 18:08:18 +01:00
'Complete Forecast'
2012-09-24 22:18:18 +02:00
__name__ = 'stock.forecast.complete.choose'
2009-03-05 14:54:34 +01:00
products = fields.Many2Many('product.product', None, None, 'Products')
2008-11-20 18:31:47 +01:00
class ForecastComplete(Wizard):
'Complete Forecast'
2012-09-24 22:18:18 +02:00
__name__ = 'stock.forecast.complete'
2012-01-02 18:08:18 +01:00
start_state = 'ask'
ask = StateView('stock.forecast.complete.ask',
2013-03-14 00:25:59 +01:00
'stock_forecast.forecast_complete_ask_view_form', [
2012-01-02 18:08:18 +01:00
Button('Cancel', 'end', 'tryton-cancel'),
2018-08-19 20:02:58 +02:00
Button('Choose Products', 'choose', 'tryton-forward'),
2012-01-02 18:08:18 +01:00
Button('Complete', 'complete', 'tryton-ok', default=True),
])
choose = StateView('stock.forecast.complete.choose',
2013-03-14 00:25:59 +01:00
'stock_forecast.forecast_complete_choose_view_form', [
2012-01-02 18:08:18 +01:00
Button('Cancel', 'end', 'tryton-cancel'),
2018-08-19 20:02:58 +02:00
Button('Choose Dates', 'ask', 'tryton-back'),
2012-01-02 18:08:18 +01:00
Button('Complete', 'complete', 'tryton-ok', default=True),
])
complete = StateTransition()
2008-11-20 18:31:47 +01:00
2012-09-24 22:18:18 +02:00
def default_ask(self, fields):
2008-11-20 18:31:47 +01:00
"""
Forecast dates shifted by one year.
"""
default = {}
2009-03-17 15:56:52 +01:00
for field in ("to_date", "from_date"):
default[field] = (
getattr(self.record, field) - relativedelta(years=1))
return default
2008-11-20 18:31:47 +01:00
2012-09-24 22:18:18 +02:00
def _get_product_quantity(self):
pool = Pool()
Product = pool.get('product.product')
2008-11-20 18:31:47 +01:00
2010-08-10 11:58:52 -04:00
with Transaction().set_context(
stock_destinations=[self.record.destination.id],
2012-09-24 22:18:18 +02:00
stock_date_start=self.ask.from_date,
stock_date_end=self.ask.to_date):
return Product.products_by_location([self.record.warehouse.id],
2013-06-21 23:24:43 +02:00
with_childs=True)
2008-11-20 18:31:47 +01:00
2012-09-24 22:18:18 +02:00
def default_choose(self, fields):
2008-11-20 18:31:47 +01:00
"""
Collect products for which there is an outgoing stream between
the given location and the destination.
"""
if getattr(self.choose, 'products', None):
2012-09-24 22:18:18 +02:00
return {'products': [x.id for x in self.choose.products]}
pbl = self._get_product_quantity()
2008-11-20 18:31:47 +01:00
products = []
2018-06-26 19:11:55 +02:00
for (_, product), qty in pbl.items():
2008-11-20 18:31:47 +01:00
if qty < 0:
products.append(product)
2012-01-02 18:08:18 +01:00
return {'products': products}
2008-11-20 18:31:47 +01:00
2012-09-24 22:18:18 +02:00
def transition_complete(self):
2011-07-03 13:19:15 +02:00
pool = Pool()
2012-09-24 22:18:18 +02:00
ForecastLine = pool.get('stock.forecast.line')
Product = pool.get('product.product')
2008-11-20 18:31:47 +01:00
forecast = self.record
2008-11-20 18:31:47 +01:00
prod2line = {}
2012-09-24 22:18:18 +02:00
forecast_lines = ForecastLine.search([
2016-06-20 10:51:02 +02:00
('forecast', '=', forecast.id),
2012-01-02 18:08:18 +01:00
])
2012-09-24 22:18:18 +02:00
for forecast_line in forecast_lines:
prod2line[forecast_line.product.id] = forecast_line
2008-11-20 18:31:47 +01:00
2012-09-24 22:18:18 +02:00
pbl = self._get_product_quantity()
2008-11-20 18:31:47 +01:00
product_ids = [x[1] for x in pbl]
prod2uom = {}
2012-09-24 22:18:18 +02:00
for product in Product.browse(product_ids):
2008-11-20 18:31:47 +01:00
prod2uom[product.id] = product.default_uom.id
if getattr(self.choose, 'products', None):
2012-09-24 22:18:18 +02:00
products = [x.id for x in self.choose.products]
2008-11-20 18:31:47 +01:00
else:
products = None
2016-06-20 10:51:02 +02:00
to_save = []
2018-06-26 19:11:55 +02:00
for key, qty in pbl.items():
2011-07-31 17:23:49 +02:00
_, product = key
2008-11-20 18:31:47 +01:00
if products and product not in products:
continue
if -qty <= 0:
continue
if product in prod2line:
2016-06-20 10:51:02 +02:00
line = prod2line[product]
2008-11-20 18:31:47 +01:00
else:
2016-06-20 10:51:02 +02:00
line = ForecastLine()
line.product = product
line.quantity = -qty
line.uom = prod2uom[product]
line.forecast = forecast
line.minimal_quantity = min(1, -qty)
to_save.append(line)
ForecastLine.save(to_save)
2012-01-02 18:08:18 +01:00
return 'end'