Files
tryton/modules/stock_forecast/forecast.py
T

622 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
from trytond.model import Index, 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')),
}
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]))),
})
2008-11-10 21:44:37 +01:00
destination = fields.Many2One(
'stock.location', 'Destination', required=True,
domain=[('type', 'in', ['customer', 'production'])], states=_states)
from_date = fields.Date(
"From Date", required=True,
domain=[('from_date', '<=', Eval('to_date'))],
states=_states)
to_date = fields.Date(
"To Date", required=True,
domain=[('to_date', '>=', Eval('from_date'))],
states=_states)
2008-11-10 21:44:37 +01:00
lines = fields.One2Many(
'stock.forecast.line', 'forecast', 'Lines', states=_states)
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]))),
})
state = fields.Selection([
('draft', "Draft"),
('done', "Done"),
('cancelled', "Cancelled"),
], "State", readonly=True, sort=False)
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
2012-09-24 22:18:18 +02:00
@classmethod
def __setup__(cls):
super(Forecast, cls).__setup__()
t = cls.__table__()
cls._sql_indexes.add(
Index(
t,
(t.state, Index.Equality()),
(t.to_date, Index.Range())))
2022-02-03 22:29:08 +01:00
cls.create_date.select = True
2012-09-24 22:18:18 +02:00
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
2018-07-24 22:01:08 +02:00
table = cls.__table_handler__(module_name)
2010-01-23 11:47:52 +01:00
# 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):
pool = Pool()
Lang = pool.get('ir.lang')
lang = Lang.get()
from_date = lang.strftime(self.from_date)
to_date = lang.strftime(self.to_date)
return (
f'{self.warehouse.rec_name} → {self.destination.rec_name} @ '
f'[{from_date} - {to_date}]')
2017-07-26 23:43:27 +02:00
@classmethod
def search_rec_name(cls, name, clause):
operator = clause[1]
if operator.startswith('!') or operator.startswith('not '):
bool_op = 'AND'
else:
bool_op = 'OR'
return [bool_op,
('warehouse.rec_name', *clause[1:]),
('destination.rec_name', *clause[1:]),
]
2017-07-26 23:43:27 +02:00
@classmethod
2022-04-11 23:24:21 +02:00
def validate_fields(cls, forecasts, field_names):
super().validate_fields(forecasts, field_names)
cls.check_date_overlap(forecasts, field_names)
2022-04-11 23:24:21 +02:00
@classmethod
def check_date_overlap(cls, forecasts, field_names=None):
if field_names and not (field_names & {
'from_date', 'to_date',
'warehouse', 'destination',
'company', 'state'}):
2013-10-15 15:09:22 +02:00
return
2016-07-07 10:07:33 +02:00
transaction = Transaction()
connection = transaction.connection
2022-04-11 23:24:21 +02:00
cls.lock()
table = cls.__table__()
2016-07-07 10:07:33 +02:00
cursor = connection.cursor()
2022-04-11 23:24:21 +02:00
for forecast in forecasts:
if forecast.state != 'done':
continue
cursor.execute(*table.select(table.id,
where=(((table.from_date <= forecast.from_date)
& (table.to_date >= forecast.from_date))
| ((table.from_date <= forecast.to_date)
& (table.to_date >= forecast.to_date))
| ((table.from_date >= forecast.from_date)
& (table.to_date <= forecast.to_date)))
& (table.warehouse == forecast.warehouse.id)
& (table.destination == forecast.destination.id)
& (table.company == forecast.company.id)
& (table.state == 'done')
2022-04-11 23:24:21 +02:00
& (table.id != forecast.id)))
forecast_id = cursor.fetchone()
if forecast_id:
second = cls(forecast_id[0])
raise ForecastValidationError(
gettext('stock_forecast.msg_forecast_date_overlap',
first=forecast.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',
}
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)
2012-03-25 15:39:12 +02:00
product_uom_category = fields.Function(
2023-08-20 12:17:27 +02:00
fields.Many2One(
'product.uom.category', "Product UoM Category",
help="The category of Unit of Measure for the product."),
2012-09-24 22:18:18 +02:00
'on_change_with_product_uom_category')
2023-08-20 01:24:32 +02:00
unit = fields.Many2One(
'product.uom', "Unit", 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'})
quantity = fields.Float(
2023-08-20 01:24:32 +02:00
"Quantity", digits='unit', required=True,
domain=[('quantity', '>=', 0)],
states=_states)
minimal_quantity = fields.Float(
2023-08-20 01:24:32 +02:00
"Minimal Qty", digits='unit', required=True,
domain=[('minimal_quantity', '<=', Eval('quantity'))],
states=_states)
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'))),
})
2016-06-30 18:56:34 +02:00
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(
2023-08-20 01:24:32 +02:00
"Quantity Executed", digits='unit'), 'get_quantity_executed')
2008-11-10 21:44:37 +01:00
del _states
2016-06-30 18:56:34 +02:00
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):
2023-08-20 01:24:32 +02:00
table_h = cls.__table_handler__(module_name)
# Migration from 6.8: rename uom to unit
if (table_h.column_exist('uom')
and not table_h.column_exist('unit')):
table_h.column_rename('uom', 'unit')
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:
2023-08-20 01:24:32 +02:00
self.unit = 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):
2023-03-26 09:49:00 +02:00
return self.product.default_uom_category if self.product else None
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]
2023-08-20 01:24:32 +02:00
result[line.id] = Uom.compute_qty(
line.product.default_uom, quantity, line.unit)
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')
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 []
2023-02-11 12:40:41 +01:00
if self.quantity_executed >= self.quantity:
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)
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
2023-08-20 01:24:32 +02:00
move.unit = self.unit
2016-06-20 10:51:02 +02:00
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 = (
0 if self.forecast.destination.type == 'customer' else None)
2016-06-20 10:51:02 +02:00
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",
ondelete='CASCADE', required=True)
move = fields.Many2One(
'stock.move', "Move", ondelete='CASCADE', 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'
2023-02-11 12:40:41 +01:00
company = fields.Many2One('company.company', "Company", readonly=True)
warehouse = fields.Many2One('stock.location', "Warehouse", readonly=True)
destination = fields.Many2One(
'stock.location', "Destination", readonly=True)
2018-12-29 14:20:29 +01:00
from_date = fields.Date(
"From Date", required=True,
2023-02-11 12:40:41 +01:00
domain=[('from_date', '<', Eval('to_date'))],
states={
'readonly': Bool(Eval('products')),
})
2018-12-29 14:20:29 +01:00
to_date = fields.Date(
"To Date", required=True,
2023-02-11 12:40:41 +01:00
domain=[('to_date', '>', Eval('from_date'))],
states={
'readonly': Bool(Eval('products')),
})
products = fields.Many2Many(
'product.product', None, None, "Products",
domain=[
('type', '=', 'goods'),
('consumable', '=', False),
2023-02-11 12:40:41 +01:00
],
context={
'company': Eval('company', -1),
'locations': [Eval('warehouse', -1)],
'stock_destinations': [Eval('destination', -1)],
'stock_date_start': Eval('from_date', None),
'stock_date_end': Eval('to_date', None),
'with_childs': True,
'stock_invert': True,
},
depends=[
'company', 'warehouse', 'destination', 'from_date', 'to_date'])
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', [
2023-02-11 12:40:41 +01:00
Button("Cancel", 'end', 'tryton-cancel'),
Button("Complete", 'complete', 'tryton-ok', default=True),
2012-01-02 18:08:18 +01:00
])
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 = {}
2023-02-11 12:40:41 +01:00
for field in ['company', 'warehouse', 'destination']:
if field in fields:
record = getattr(self.record, field)
default[field] = record.id
for field in ["to_date", "from_date"]:
if field in fields:
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 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')
2008-11-20 18:31:47 +01:00
2023-02-11 12:40:41 +01:00
product2line = {l.product: l for l in self.record.lines}
2016-06-20 10:51:02 +02:00
to_save = []
2023-02-11 12:40:41 +01:00
# Ensure context is set
self.ask.products = map(int, self.ask.products)
for product in self.ask.products:
line = product2line.get(product, ForecastLine())
self._fill_line(line, product)
2016-06-20 10:51:02 +02:00
to_save.append(line)
ForecastLine.save(to_save)
2012-01-02 18:08:18 +01:00
return 'end'
2023-02-11 12:40:41 +01:00
def _fill_line(self, line, product):
quantity = max(product.quantity, 0)
line.product = product
line.quantity = quantity
2023-08-20 01:24:32 +02:00
line.unit = product.default_uom
2023-02-11 12:40:41 +01:00
line.forecast = self.record
line.minimal_quantity = min(1, quantity)