This repository has been archived by the owner on Dec 30, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathmove.py
1652 lines (1510 loc) · 65.6 KB
/
move.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
import copy
import datetime
import operator
from collections import OrderedDict, defaultdict
from decimal import Decimal
from itertools import groupby
from sql import Column, For, Literal, Null, Union
from sql.aggregate import Max, Sum
from sql.conditionals import Case, Coalesce
from sql.functions import Round
from trytond.i18n import gettext
from trytond.model import (
Check, Index, Model, ModelSQL, ModelView, Workflow, fields)
from trytond.model.exceptions import AccessError
from trytond.modules.product import price_digits, round_price
from trytond.pool import Pool
from trytond.pyson import Bool, Eval, If
from trytond.tools import grouped_slice, reduce_ids
from trytond.transaction import Transaction
from .exceptions import MoveFutureWarning, MoveOriginWarning
STATES = {
'readonly': Eval('state').in_(['cancelled', 'assigned', 'done']),
}
LOCATION_DOMAIN = [
If(Eval('state').in_(['staging', 'draft', 'cancelled']),
('type', 'not in', ['warehouse']),
('type', 'not in', ['warehouse', 'view'])),
If(~Eval('state').in_(['done', 'cancelled']),
('active', '=', True),
()),
]
class StockMixin(object):
'''Mixin class with helper to setup stock quantity field.'''
__slots__ = ()
@classmethod
def _quantity_context(cls, name):
pool = Pool()
Date = pool.get('ir.date')
today = Date.today()
context = Transaction().context
new_context = {}
stock_date_end = context.get('stock_date_end')
if name == 'quantity':
new_context['forecast'] = False
if (stock_date_end or datetime.date.max) > today:
new_context['stock_date_end'] = today
elif name == 'forecast_quantity':
new_context['forecast'] = True
if not stock_date_end:
new_context['stock_date_end'] = datetime.date.max
return new_context
@classmethod
def _get_quantity(cls, records, name, location_ids,
grouping=('product',), grouping_filter=None, position=-1):
"""
Compute for each record the stock quantity in the default uom of the
product.
location_ids is the list of IDs of locations to take account to compute
the stock.
grouping defines how stock moves are grouped.
grouping_filter is a tuple of values, for the Move's field at the same
position in grouping tuple, used to filter which moves are used to
compute quantities. If it is None all the products are used.
position defines which field of grouping corresponds to the record
whose quantity is computed.
Return a dictionary with records id as key and quantity as value.
"""
pool = Pool()
Product = pool.get('product.product')
record_ids = [r.id for r in records]
quantities = dict.fromkeys(record_ids, 0.0)
if not location_ids:
return quantities
with_childs = Transaction().context.get(
'with_childs', len(location_ids) == 1)
with Transaction().set_context(cls._quantity_context(name)):
pbl = Product.products_by_location(
location_ids,
with_childs=with_childs,
grouping=grouping,
grouping_filter=grouping_filter)
for key, quantity in pbl.items():
# pbl could return None in some keys
if (key[position] is not None
and key[position] in quantities):
quantities[key[position]] += quantity
return quantities
@classmethod
def _search_quantity(cls, name, location_ids, domain=None,
grouping=('product',), position=-1):
"""
Compute the domain to filter records which validates the domain over
quantity field.
location_ids is the list of IDs of locations to take account to compute
the stock.
grouping defines how stock moves are grouped.
position defines which field of grouping corresponds to the record
whose quantity is computed.
"""
pool = Pool()
Product = pool.get('product.product')
Move = pool.get('stock.move')
Uom = pool.get('product.uom')
uom = Uom.__table__()
if not location_ids or not domain:
return []
with_childs = Transaction().context.get(
'with_childs', len(location_ids) == 1)
_, operator_, operand = domain
with Transaction().set_context(cls._quantity_context(name)):
if (len(location_ids) == 1
and not Transaction().context.get('stock_skip_warehouse')):
# We can use the compute quantities query if the request is for
# a single location because all the locations are children and
# so we can do a SUM.
Operator = fields.SQL_OPERATORS[operator_]
query = Move.compute_quantities_query(
location_ids, with_childs, grouping=grouping)
col_id = Column(query, grouping[position])
# We need to round the result to have same result as
# products_by_location but as we do not have the unit, we use
# the biggest digits of all unit as best approximation.
quantity = Round(
fields.Numeric('quantity').sql_cast(Sum(query.quantity)),
uom.select(Max(uom.digits)))
group_by = [Column(query, key).as_(key) for key in grouping]
return [('id', 'in', query.select(
col_id,
group_by=group_by,
having=Operator(quantity, operand)))]
pbl = Product.products_by_location(
location_ids, with_childs=with_childs, grouping=grouping)
operator_ = {
'=': operator.eq,
'>=': operator.ge,
'>': operator.gt,
'<=': operator.le,
'<': operator.lt,
'!=': operator.ne,
'in': lambda v, l: v in l,
'not in': lambda v, l: v not in l,
}.get(operator_, lambda v, l: False)
record_ids = []
for key, quantity in pbl.items():
if (quantity is not None and operand is not None
and operator_(quantity, operand)):
# pbl could return None in some keys
if key[position] is not None:
record_ids.append(key[position])
return [('id', 'in', record_ids)]
class Move(Workflow, ModelSQL, ModelView):
"Stock Move"
__name__ = 'stock.move'
_order_name = 'product'
product = fields.Many2One(
'product.product', "Product", required=True, states=STATES,
context={
'company': Eval('company', -1),
},
depends={'company'},
help="The product that the move is associated with.")
product_uom_category = fields.Function(
fields.Many2One('product.uom.category', 'Product Uom Category'),
'on_change_with_product_uom_category')
uom = fields.Many2One("product.uom", "Uom", required=True,
states={
'readonly': (Eval('state').in_(['cancelled', 'assigned', 'done'])
| Eval('unit_price')),
},
domain=[
If(~Eval('state').in_(['done', 'cancelled']),
('category', '=', Eval('product_uom_category')),
()),
],
help="The unit in which the quantity is specified.")
quantity = fields.Float(
"Quantity", digits='uom', required=True,
states=STATES,
help="The amount of stock moved.")
internal_quantity = fields.Float('Internal Quantity', readonly=True,
required=True)
from_location = fields.Many2One(
'stock.location', "From Location",
required=True, states=STATES,
domain=LOCATION_DOMAIN,
help="Where the stock is moved from.")
to_location = fields.Many2One(
'stock.location', "To Location",
required=True, states=STATES,
domain=LOCATION_DOMAIN,
help="Where the stock is moved to.")
shipment = fields.Reference(
"Shipment", selection='get_shipment', readonly=True,
states={
'invisible': ~Eval('shipment'),
},
help="Used to group several stock moves together.")
origin = fields.Reference(
"Origin", selection='get_origin',
states={
'readonly': Eval('state') != 'draft',
},
help="The source of the stock move.")
planned_date = fields.Date(
"Planned Date",
states={
'readonly': (Eval('state').in_(['cancelled', 'assigned', 'done'])
| Eval('shipment'))
},
help="When the stock is expected to be moved.")
effective_date = fields.Date(
"Effective Date",
states={
'required': Eval('state') == 'done',
'readonly': (Eval('state').in_(['cancelled', 'done'])
| Eval('shipment')),
},
help="When the stock was actually moved.")
state = fields.Selection([
('staging', 'Staging'),
('draft', 'Draft'),
('assigned', 'Assigned'),
('done', 'Done'),
('cancelled', 'Cancelled'),
], "State", readonly=True, sort=False,
help="The current state of the stock move.")
company = fields.Many2One(
'company.company', "Company", required=True,
states={
'readonly': Eval('state') != 'draft',
},
help="The company the stock move is associated with.")
unit_price = fields.Numeric('Unit Price', digits=price_digits,
states={
'invisible': ~Eval('unit_price_required'),
'required': Bool(Eval('unit_price_required')),
'readonly': Eval('state') != 'draft',
})
unit_price_company = fields.Function(
fields.Numeric("Unit Price", digits=price_digits,
states={
'invisible': ~Eval('unit_price_required'),
},
help="Unit price in company currency."),
'get_unit_price_company')
unit_price_updated = fields.Boolean(
"Unit Price Updated", readonly=True,
states={
'invisible': Eval('state') != 'done',
})
cost_price = fields.Numeric(
"Cost Price", digits=price_digits, readonly=True,
states={
'invisible': ~Eval('cost_price_required'),
'required': (
(Eval('state') == 'done')
& Eval('cost_price_required', False)),
})
currency = fields.Many2One('currency.currency', 'Currency',
states={
'invisible': ~Eval('unit_price_required'),
'required': Bool(Eval('unit_price_required')),
'readonly': Eval('state') != 'draft',
},
help="The currency in which the unit price is specified.")
unit_price_required = fields.Function(
fields.Boolean('Unit Price Required'),
'on_change_with_unit_price_required')
cost_price_required = fields.Function(
fields.Boolean("Cost Price Required"),
'on_change_with_cost_price_required')
assignation_required = fields.Function(
fields.Boolean('Assignation Required'),
'on_change_with_assignation_required',
searcher='search_assignation_required')
@classmethod
def __setup__(cls):
super(Move, cls).__setup__()
cls.product.domain = [
If(Bool(Eval('product_uom_category'))
& ~Eval('state').in_(['done', 'cancelled']),
('default_uom_category', '=', Eval('product_uom_category')),
()),
('type', 'in', cls.get_product_types()),
]
cls._deny_modify_assigned = set(['product', 'uom', 'quantity',
'from_location', 'to_location', 'company'])
cls._deny_modify_done_cancel = (cls._deny_modify_assigned
| set(['planned_date', 'effective_date']))
cls._allow_modify_closed_period = {
'cost_price', 'unit_price', 'unit_price_updated', 'currency'}
t = cls.__table__()
cls._sql_constraints += [
('check_move_qty_pos', Check(t, t.quantity >= 0),
'stock.msg_move_quantity_positive'),
('check_move_internal_qty_pos',
Check(t, t.internal_quantity >= 0),
'stock.msg_move_internal_quantity_positive'),
('check_from_to_locations',
Check(t, t.from_location != t.to_location),
'stock.msg_move_from_to_location'),
]
cls._sql_indexes.update({
Index(
t,
(t.from_location, Index.Range()),
(t.product, Index.Range()),
(Coalesce(
t.effective_date,
t.planned_date,
datetime.date.max),
Index.Range())),
Index(
t,
(t.to_location, Index.Range()),
(t.product, Index.Range()),
(Coalesce(
t.effective_date,
t.planned_date,
datetime.date.max),
Index.Range())),
Index(
t,
(t.state, Index.Equality()),
where=t.state.in_(['staging', 'draft', 'assigned'])),
})
cls._order[0] = ('id', 'DESC')
cls._transitions |= set((
('staging', 'draft'),
('staging', 'cancelled'),
('draft', 'assigned'),
('draft', 'done'),
('draft', 'cancelled'),
('assigned', 'draft'),
('assigned', 'done'),
('assigned', 'cancelled'),
('done', 'cancelled'),
))
cls._buttons.update({
'cancel': {
'invisible': ~Eval('state').in_(['draft', 'assigned']),
'readonly': Eval('shipment'),
'depends': ['state', 'shipment'],
},
'draft': {
'invisible': ~Eval('state').in_(['assigned']),
'readonly': Eval('shipment'),
'depends': ['state', 'shipment'],
},
'do': {
'invisible': ~Eval('state').in_(['draft', 'assigned']),
'readonly': (Eval('shipment')
| (Eval('assignation_required', True)
& (Eval('state') == 'draft'))),
'depends': ['state', 'assignation_required', 'shipment'],
},
})
@classmethod
def __register__(cls, module_name):
cursor = Transaction().connection.cursor()
sql_table = cls.__table__()
super(Move, cls).__register__(module_name)
# Migration from 5.6: rename state cancel to cancelled
cursor.execute(*sql_table.update(
[sql_table.state], ['cancelled'],
where=sql_table.state == 'cancel'))
@classmethod
def get_product_types(cls):
return ['goods', 'assets']
@staticmethod
def default_planned_date():
return Transaction().context.get('planned_date')
@staticmethod
def default_state():
return 'draft'
@staticmethod
def default_company():
return Transaction().context.get('company')
@classmethod
def default_unit_price_updated(cls):
return True
@fields.depends('product', 'uom')
def on_change_product(self):
if self.product:
if (not self.uom
or self.uom.category != self.product.default_uom.category):
self.uom = self.product.default_uom
@fields.depends('product')
def on_change_with_product_uom_category(self, name=None):
if self.product:
return self.product.default_uom_category.id
@classmethod
def get_unit_price_company(cls, moves, name):
pool = Pool()
Currency = pool.get('currency.currency')
Uom = pool.get('product.uom')
Date = pool.get('ir.date')
prices = {}
for company, c_moves in groupby(moves, key=lambda m: m.company):
with Transaction().set_context(company=company.id):
today = Date.today()
for move in c_moves:
if move.unit_price is not None:
date = move.effective_date or move.planned_date or today
with Transaction().set_context(date=date):
unit_price = Currency.compute(
move.currency, move.unit_price,
move.company.currency, round=False)
unit_price = Uom.compute_price(
move.uom, unit_price, move.product.default_uom)
prices[move.id] = round_price(unit_price)
else:
prices[move.id] = None
return prices
@fields.depends('from_location', 'to_location')
def on_change_with_unit_price_required(self, name=None):
from_type = self.from_location.type if self.from_location else None
to_type = self.to_location.type if self.to_location else None
if from_type == 'supplier' and to_type in {'storage', 'drop', 'view'}:
return True
if from_type == 'production' and to_type != 'lost_found':
return True
if from_type in {'storage', 'drop', 'view'} and to_type == 'customer':
return True
if from_type in {'storage', 'drop', 'view'} and to_type == 'supplier':
return True
if from_type == 'customer' and to_type in {'storage', 'drop', 'view'}:
return True
return False
@fields.depends('from_location', 'to_location')
def on_change_with_cost_price_required(self, name=None):
from_type = self.from_location.type if self.from_location else None
to_type = self.to_location.type if self.to_location else None
return ((from_type != 'storage' and to_type == 'storage')
or (from_type == 'storage' and to_type != 'storage')
or (from_type != 'drop' and to_type == 'drop')
or (from_type == 'drop' and to_type != 'drop'))
@fields.depends('from_location', 'quantity')
def on_change_with_assignation_required(self, name=None):
if self.from_location:
return (
self.quantity
and self.from_location.type in {'storage', 'view'})
@classmethod
def search_assignation_required(cls, name, clause):
operators = {
'=': 'in',
'!=': 'not in',
}
reverse = {
'=': '!=',
'!=': '=',
}
if clause[1] in operators:
if not clause[2]:
operator = reverse[clause[1]]
else:
operator = clause[1]
return [
('quantity', '!=', 0),
('from_location.type', operators[operator], [
'storage', 'view']),
]
else:
return []
@staticmethod
def _get_shipment():
'Return list of Model names for shipment Reference'
return [
'stock.shipment.in',
'stock.shipment.out',
'stock.shipment.out.return',
'stock.shipment.in.return',
'stock.shipment.internal',
]
@classmethod
def get_shipment(cls):
IrModel = Pool().get('ir.model')
get_name = IrModel.get_name
models = cls._get_shipment()
return [(None, '')] + [(m, get_name(m)) for m in models]
@classmethod
def _get_origin(cls):
'Return list of Model names for origin Reference'
return [cls.__name__, 'stock.inventory.line']
@classmethod
def get_origin(cls):
IrModel = Pool().get('ir.model')
get_name = IrModel.get_name
models = cls._get_origin()
return [(None, '')] + [(m, get_name(m)) for m in models]
@property
def origin_name(self):
return self.origin.rec_name if self.origin else None
@classmethod
def check_period_closed(cls, moves):
Period = Pool().get('stock.period')
with Transaction().set_context(_check_access=False):
for company, moves in groupby(moves, lambda m: m.company):
periods = Period.search([
('state', '=', 'closed'),
('company', '=', company.id),
], order=[('date', 'DESC')], limit=1)
if periods:
period, = periods
for move in moves:
date = (move.effective_date if move.effective_date
else move.planned_date)
if date and date <= period.date:
raise AccessError(
gettext('stock.msg_move_modify_period_close',
move=move.rec_name,
period=period.rec_name))
def get_rec_name(self, name):
pool = Pool()
Lang = pool.get('ir.lang')
lang = Lang.get()
return (lang.format_number_symbol(
self.quantity, self.uom, digits=self.uom.digits)
+ ' %s' % self.product.rec_name)
@classmethod
def search_rec_name(cls, name, clause):
return [('product.rec_name',) + tuple(clause[1:])]
def _compute_product_cost_price(self, direction, product_cost_price=None):
"""
Update the cost price on the given product.
The direction must be "in" if incoming and "out" if outgoing.
"""
pool = Pool()
Uom = pool.get('product.uom')
if direction == 'in':
quantity = self.quantity
elif direction == 'out':
quantity = -self.quantity
qty = Uom.compute_qty(self.uom, quantity, self.product.default_uom)
qty = Decimal(str(qty))
product_qty = Decimal(str(self.product.quantity))
unit_price = self.get_cost_price(product_cost_price=product_cost_price)
cost_price = self.product.get_multivalue(
'cost_price', **self._cost_price_pattern)
if product_qty + qty > 0 and product_qty >= 0:
new_cost_price = (
(cost_price * product_qty) + (unit_price * qty)
) / (product_qty + qty)
elif direction == 'in':
new_cost_price = unit_price
elif direction == 'out':
new_cost_price = cost_price
return round_price(new_cost_price)
@staticmethod
def _get_internal_quantity(quantity, uom, product):
Uom = Pool().get('product.uom')
internal_quantity = Uom.compute_qty(uom, quantity,
product.default_uom, round=True)
return internal_quantity
def set_effective_date(self):
pool = Pool()
Date = pool.get('ir.date')
ShipmentInternal = pool.get('stock.shipment.internal')
if (not self.effective_date
and isinstance(self.shipment, ShipmentInternal)
and self.to_location == self.shipment.transit_location):
self.effective_date = self.shipment.effective_start_date
elif not self.effective_date and self.shipment:
self.effective_date = self.shipment.effective_date
if not self.effective_date:
with Transaction().set_context(company=self.company.id):
self.effective_date = Date.today()
@classmethod
def view_attributes(cls):
return super().view_attributes() + [
('/tree', 'visual', If(Eval('state') == 'cancelled', 'muted', '')),
]
@property
def from_warehouse(self):
return self.from_location.warehouse
@property
def to_warehouse(self):
return self.to_location.warehouse
@property
def warehouse(self):
return self.from_warehouse or self.to_warehouse
@classmethod
@ModelView.button
@Workflow.transition('draft')
def draft(cls, moves):
cls.write(moves, {
'effective_date': None,
})
@classmethod
@Workflow.transition('assigned')
def assign(cls, moves):
cls.check_origin(moves)
@classmethod
@ModelView.button
@Workflow.transition('done')
def do(cls, moves):
pool = Pool()
Product = pool.get('product.product')
Date = pool.get('ir.date')
Warning = pool.get('res.user.warning')
today_cache = {}
def in_future(move):
if move.company not in today_cache:
with Transaction().set_context(company=move.company.id):
today_cache[move.company] = Date.today()
today = today_cache[move.company]
if move.effective_date and move.effective_date > today:
return move
def set_cost_values(cost_values):
Value = Product.multivalue_model('cost_price')
values = []
for product, cost_price, pattern in cost_values:
values.extend(product.set_multivalue(
'cost_price', cost_price, save=False, **pattern))
Value.save(values)
cls.check_origin(moves)
for key, grouped_moves in groupby(moves, key=cls._cost_price_key):
to_save = []
cost_values = []
products = set()
grouped_moves = list(grouped_moves)
context = dict(key)
context.update(cls._cost_price_context(grouped_moves))
with Transaction().set_context(context):
grouped_moves = cls.browse(grouped_moves)
for move in grouped_moves:
move.set_effective_date()
previous_values = copy.copy(move._values)
cost_price, extra_to_save = move._do()
if cost_price is not None:
if move.product in products:
# The average computation of product cost price
# requires each previous move of the same product
# to be saved
cls.save(to_save)
set_cost_values(cost_values)
del to_save[:]
del cost_values[:]
products.clear()
# Recompute with unmodified move but including new
# saved moves
move._values = previous_values
cost_price, extra_to_save = move._do()
cost_values.append(
(move.product, cost_price,
move._cost_price_pattern))
to_save.extend(extra_to_save)
if move.cost_price_required and move.cost_price is None:
if cost_price is None:
cost_price = move.product.get_multivalue(
'cost_price', **move._cost_price_pattern)
move.cost_price = cost_price
move.state = 'done'
to_save.append(move)
products.add(move.product)
if to_save:
cls.save(to_save)
if cost_values:
set_cost_values(cost_values)
future_moves = sorted(filter(in_future, moves))
if future_moves:
names = ', '.join(m.rec_name for m in future_moves[:5])
if len(future_moves) > 5:
names += '...'
warning_name = Warning.format(
'effective_date_future', future_moves)
if Warning.check(warning_name):
raise MoveFutureWarning(warning_name,
gettext('stock.msg_move_effective_date_in_the_future',
moves=names))
@property
def _cost_price_pattern(self):
return {
'company': self.company.id,
}
def _cost_price_key(self):
return (
('company', self.company.id),
)
def get_cost_price(self, product_cost_price=None):
"Return the cost price of the move for computation"
with Transaction().set_context(date=self.effective_date):
if (self.from_location.type in {'supplier', 'production'}
or self.to_location.type == 'supplier'):
return self.unit_price_company
elif product_cost_price is not None:
return product_cost_price
elif self.cost_price is not None:
return self.cost_price
else:
return self.product.get_multivalue(
'cost_price', **self._cost_price_pattern)
@classmethod
def _cost_price_context(cls, moves):
pool = Pool()
Location = pool.get('stock.location')
Date = pool.get('ir.date')
context = {}
locations = Location.search([
('type', '=', 'storage'),
])
context['with_childs'] = False
context['locations'] = [l.id for l in locations]
with Transaction().set_context(company=moves[0].company.id):
context['stock_date_end'] = Date.today()
context['company'] = moves[0].company.id
return context
def _do(self):
"Return cost_price and a list of moves to save"
if (self.from_location.type in ('supplier', 'production')
and self.to_location.type == 'storage'
and self.product.cost_price_method == 'average'):
return self._compute_product_cost_price('in'), []
elif (self.to_location.type == 'supplier'
and self.from_location.type == 'storage'
and self.product.cost_price_method == 'average'):
return self._compute_product_cost_price('out'), []
return None, []
@classmethod
@ModelView.button
@Workflow.transition('cancelled')
def cancel(cls, moves):
pass
@classmethod
def create(cls, vlist):
pool = Pool()
Product = pool.get('product.product')
Uom = pool.get('product.uom')
vlist = [x.copy() for x in vlist]
# Use ordered dict to optimize cache alignment
products, uoms = OrderedDict(), OrderedDict()
for vals in vlist:
products[vals['product']] = None
uoms[vals['uom']] = None
id2product = {p.id: p for p in Product.browse(products.keys())}
id2uom = {u.id: u for u in Uom.browse(uoms.keys())}
for vals in vlist:
assert vals.get('state', cls.default_state()
) in ['draft', 'staging']
product = id2product[int(vals['product'])]
uom = id2uom[int(vals['uom'])]
internal_quantity = cls._get_internal_quantity(
vals['quantity'], uom, product)
vals['internal_quantity'] = internal_quantity
moves = super(Move, cls).create(vlist)
cls.check_period_closed(moves)
return moves
@classmethod
def write(cls, *args):
actions = iter(args)
for moves, values in zip(actions, actions):
vals_set = set(values)
if cls._deny_modify_assigned & vals_set:
for move in moves:
if move.state == 'assigned':
raise AccessError(
gettext('stock.msg_move_modify_assigned',
move=move.rec_name))
if cls._deny_modify_done_cancel & vals_set:
for move in moves:
if move.state in ('done', 'cancelled'):
raise AccessError(
gettext('stock.msg_move_modify_%s' % move.state,
move=move.rec_name))
super(Move, cls).write(*args)
to_write = []
unit_price_update = []
actions = iter(args)
for moves, values in zip(actions, actions):
if any(f not in cls._allow_modify_closed_period for f in values):
cls.check_period_closed(moves)
for move in moves:
internal_quantity = cls._get_internal_quantity(move.quantity,
move.uom, move.product)
if (internal_quantity != move.internal_quantity
and internal_quantity
!= values.get('internal_quantity')):
to_write.extend(([move], {
'internal_quantity': internal_quantity,
}))
if (move.state == 'done'
and ('unit_price' in values
or 'currency' in values)):
unit_price_update.append(move)
if to_write:
cls.write(*to_write)
if unit_price_update:
cls.write(unit_price_update, {'unit_price_updated': True})
@classmethod
def delete(cls, moves):
for move in moves:
if move.state not in {'staging', 'draft', 'cancelled'}:
raise AccessError(
gettext('stock.msg_move_delete_draft_cancel',
move=move.rec_name))
super(Move, cls).delete(moves)
@staticmethod
def check_origin_types():
"Location types to check for origin"
return set()
@classmethod
def check_origin(cls, moves, types=None):
pool = Pool()
Warning = pool.get('res.user.warning')
if types is None:
types = cls.check_origin_types()
if not types:
return
def no_origin(move):
return ((move.from_location.type in types)
^ (move.to_location.type in types)
and not move.origin)
moves = sorted(filter(no_origin, moves))
if moves:
names = ', '.join(m.rec_name for m in moves[:5])
if len(moves) > 5:
names += '...'
warning_name = Warning.format('done', moves)
if Warning.check(warning_name):
raise MoveOriginWarning(warning_name,
gettext('stock.msg_move_no_origin',
moves=names))
def sort_quantities(self, quantities, locations, grouping):
"""
Return the quantities ordered by pick preference which is the locations
order by default.
"""
locations = {l.id: i for i, l in enumerate(locations)}
quantities = filter(lambda x: x[0][0] in locations, quantities)
return sorted(quantities, key=lambda x: locations[x[0][0]])
def pick_product(self, quantities):
"""
Pick the product across the keys. Naive (fast) implementation.
Return a list of tuple (key, quantity) for quantities that can be
picked.
"""
to_pick = []
needed_qty = self.quantity
for key, available_qty in quantities:
# Ignore available_qty when too small
if available_qty < self.uom.rounding:
continue
if needed_qty <= available_qty:
to_pick.append((key, needed_qty))
return to_pick
else:
to_pick.append((key, available_qty))
needed_qty -= available_qty
# Force assignation for consumables:
if self.product.consumable and self.from_location.type != 'view':
to_pick.append(((self.from_location,), needed_qty))
return to_pick
return to_pick
@classmethod
def assign_try(cls, moves, with_childs=True, grouping=('product',)):
'''
Try to assign moves.
It will split the moves to assign as much possible.
Return True if succeed or False if not.
'''
pool = Pool()
Product = pool.get('product.product')
Uom = pool.get('product.uom')
Date = pool.get('ir.date')
Location = pool.get('stock.location')
moves = [m for m in moves if m.state in {'draft', 'staging'}]
if not moves:
return True
if with_childs:
locations = Location.search([
('parent', 'child_of',
[x.from_location.id for x in moves]),
])
else:
locations = list(set((m.from_location for m in moves)))
location_ids = [l.id for l in locations]
product_ids = list(set((m.product.id for m in moves)))
companies = {m.company for m in moves}
stock_date_end = Date.today()
pblc = {}
for company in companies:
with Transaction().set_context(company=company.id):
stock_date_end = Date.today()
cls._assign_try_lock(
product_ids, location_ids, [company.id],
stock_date_end, grouping)
with Transaction().set_context(
stock_date_end=stock_date_end,
stock_assign=True,
company=company.id):
pblc[company.id] = Product.products_by_location(
location_ids,
grouping=grouping,
grouping_filter=(product_ids,))
def get_key(move, location_id):
key = (location_id,)
for field in grouping:
value = getattr(move, field)
if isinstance(value, Model):
value = value.id
key += (value,)
return key
def get_values(key, location_name):