trytond-stock_party_warehouse/model.py

100 lines
3.2 KiB
Python

# The COPYRIGHT file at the top level of this repository contains the full
# copyright notices and license terms.
from trytond.pool import Pool
from trytond.model import fields
from trytond.pyson import Eval
from trytond.transaction import Transaction
class PartyWarehouseMixin(object):
def _get_party_warehouse_pattern(self):
return {}
@property
def party_with_warehouse(self):
return self.party
def get_party_warehouse_used(self, **pattern):
party = self.party_with_warehouse
if party:
wh = party.get_multivalue('warehouse', **pattern)
if not wh:
# leave only party match pattern value
pattern = {key: None if key != 'party' else value
for key, value in pattern.items()
}
wh = party.get_multivalue('warehouse', **pattern)
return wh
class ReturnableMoveMixin(PartyWarehouseMixin):
returnables_moves = fields.Function(
fields.One2Many('stock.move', None, 'Returnables moves',
states={
'invisible': ~Eval('returnables_moves')
}),
'get_returnables_moves')
def get_returnables_moves(self, name):
moves = []
from_loc, to_loc = self.get_returnables_locations()
if from_loc and to_loc:
for move in self.moves:
if (move.from_location == from_loc
and move.to_location == to_loc):
moves.append(move.id)
return moves
def is_returnable(self, move):
return self.get_party_warehouse_used(
**self._get_party_warehouse_pattern())
@classmethod
def create_returnables_moves(cls, records):
pool = Pool()
Move = pool.get('stock.move')
returnables_moves = []
key2moves = {}
for record in records:
if record.returnables_moves:
returnables_moves.extend([
m for m in record.returnables_moves
if m.state != 'done'])
else:
for move in getattr(record, cls._to_return_moves):
if not record.is_returnable(move):
continue
key = record._get_returnable_move_values(move)
key2moves.setdefault(key, []).append(move)
for key, moves in key2moves.items():
returnables_moves.extend(Move.copy(moves, default=dict(key)))
if returnables_moves:
Move.do(returnables_moves)
def _get_returnable_move_values(self, move):
from_loc, to_loc = self.get_returnables_locations()
return (
('from_location', from_loc),
('to_location', to_loc),
)
@classmethod
def delete_returnables_moves(cls, records):
pool = Pool()
Move = pool.get('stock.move')
to_delete = []
for record in records:
if not record.returnables_moves:
continue
to_delete.extend(list(record.returnables_moves))
if to_delete:
with Transaction().set_context(
check_origin=False, check_shipment=False):
Move.cancel(to_delete)
Move.delete(to_delete)