/
stock_buffer.py
2105 lines (1966 loc) · 77.4 KB
/
stock_buffer.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
# Copyright 2019-20 ForgeFlow S.L. (http://www.forgeflow.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
import json
import logging
import operator as py_operator
import threading
from collections import defaultdict
from datetime import datetime, timedelta
from math import pi
from odoo import _, api, exceptions, fields, models
from odoo.exceptions import ValidationError
from odoo.tools import float_compare, float_round
from odoo.tools.misc import split_every
_logger = logging.getLogger(__name__)
try:
from bokeh.embed import components
from bokeh.models import (
ColumnDataSource,
DatetimeTickFormatter,
HoverTool,
LabelSet,
Legend,
)
from bokeh.plotting import figure
from bokeh.util.serialization import convert_datetime_type
except (ImportError, IOError) as err:
_logger.debug(err)
OPERATORS = {
"<": py_operator.lt,
">": py_operator.gt,
"<=": py_operator.le,
">=": py_operator.ge,
"==": py_operator.eq,
"=": py_operator.eq,
"!=": py_operator.ne,
}
_PRIORITY_LEVEL = [("1_red", "Red"), ("2_yellow", "Yellow"), ("3_green", "Green")]
DDMRP_COLOR = {
"0_dark_red": "#8B0000",
"1_red": "#ff0000",
"2_yellow": "#ffff00",
"3_green": "#33cc33",
}
class StockBuffer(models.Model):
_name = "stock.buffer"
_description = "Stock Buffer"
_order = "planning_priority_level asc, net_flow_position_percent asc"
CRON_DDMRP_CHUNKS = 50
@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
name = fields.Char(
copy=False,
required=True,
default=lambda self: self.env["ir.sequence"].next_by_code("stock.buffer"),
)
active = fields.Boolean(default=True)
warehouse_id = fields.Many2one(
comodel_name="stock.warehouse",
string="Warehouse",
ondelete="cascade",
required=True,
)
location_id = fields.Many2one(
comodel_name="stock.location",
string="Location",
ondelete="cascade",
required=True,
)
product_id = fields.Many2one(
comodel_name="product.product",
string="Product",
domain=[("type", "=", "product")],
ondelete="cascade",
required=True,
)
product_uom = fields.Many2one(
related="product_id.uom_id",
)
# TODO: fix in method _compute_procure_recommended_qty.
# not sure maybe they are useful for tweak batches like in multi level mrp
procure_min_qty = fields.Float(
string="Minimum Procure Batch",
digits="Product Unit of Measure",
help="Minimum qty for a single procurement",
)
procure_max_qty = fields.Float(
string="Maximum Procure Batch",
digits="Product Unit of Measure",
help="Maximum qty for a single procurement",
)
qty_multiple = fields.Float(
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(
comodel_name="procurement.group",
string="Procurement Group",
copy=False,
help="Moves created through this buffer 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(
comodel_name="res.company",
string="Company",
required=True,
default=lambda self: self.env.company,
)
# TODO: rename to manual LT ??
lead_days = fields.Integer(
"Lead Time (Distributed)",
default=1,
help="Lead time for distributed products.",
)
_sql_constraints = [
(
"qty_multiple_check",
"CHECK( qty_multiple >= 0 )",
"Qty Multiple must be greater than or equal to zero.",
),
(
"stock_buffer_uniq",
"unique(product_id, location_id)",
"The product/location combination must be unique."
"Remember that the buffer could be archived.",
),
]
def _quantity_in_progress(self):
"""Return Quantities that are not yet in virtual stock but should
be deduced from buffers (example: purchases created from buffers)"""
res = {}.fromkeys(self.ids, 0.0)
polines = self.env["purchase.order.line"].search(
[
("state", "in", ("draft", "sent", "to approve")),
("buffer_ids", "in", self.ids),
]
)
for poline in polines:
for buffer in poline.buffer_ids:
if buffer.id not in self.ids:
continue
res[buffer.id] += poline.product_uom._compute_quantity(
poline.product_qty, buffer.product_uom, round=False
)
return res
def action_view_purchase(self):
action = self.env["ir.actions.actions"]._for_xml_id("purchase.purchase_rfq")
# Remove the context since the action basically display RFQ and not PO.
action["context"] = {}
order_line_ids = self.env["purchase.order.line"].search(
[("buffer_ids", "in", self.ids)]
)
purchase_ids = order_line_ids.mapped("order_id")
action["domain"] = [("id", "in", purchase_ids.ids)]
return action
def action_view_yearly_consumption(self):
action = self.env["ir.actions.actions"]._for_xml_id(
"ddmrp.stock_move_year_consumption_action"
)
locations = self.env["stock.location"].search(
[("id", "child_of", [self.location_id.id])]
)
date_to = fields.Date.today()
# We take last five years, even though they will be initially
# filtered in the action to show only last year.
date_from = date_to - timedelta(days=5 * 365)
action["domain"] = self._past_moves_domain(date_from, date_to, locations)
return action
def _demand_estimate_domain(self, locations, date_from=False, date_to=False):
self.ensure_one()
domain = [
("location_id", "in", locations.ids),
("product_id", "=", self.product_id.id),
]
if date_to:
domain += [("date_from", "<=", date_to)]
if date_from:
domain += [("date_to", ">=", date_from)]
return domain
def action_view_stock_demand_estimates(self):
result = self.env["ir.actions.actions"]._for_xml_id(
"stock_demand_estimate.stock_demand_estimate_action"
)
locations = self.env["stock.location"].search(
[("id", "child_of", [self.location_id.id])]
)
domain = self._demand_estimate_domain(locations)
recs = self.env["stock.demand.estimate"].search(domain)
result["domain"] = [("id", "in", recs.ids)]
return result
def action_view_bom(self):
action = self.product_id.action_view_bom()
locations = self.env["stock.location"].search(
[("id", "child_of", [self.location_id.id])]
)
action["domain"] += [
"|",
("location_id", "in", locations.ids),
("location_id", "=", False),
]
return action
@api.constrains("product_id")
def _check_product_uom(self):
if any(
buffer.product_id.uom_id.category_id != buffer.product_uom.category_id
for buffer in self
):
raise ValidationError(
_(
"You have to select a product unit of measure that is in"
"the same category than the default unit of"
"measure of the product"
)
)
@api.onchange("warehouse_id")
def onchange_warehouse_id(self):
if self.warehouse_id:
self.location_id = self.warehouse_id.lot_stock_id.id
@api.onchange("product_id")
def onchange_product_id(self):
if self.product_id:
self.product_uom = self.product_id.uom_id.id
return {
"domain": {
"product_uom": [
("category_id", "=", self.product_id.uom_id.category_id.id)
]
}
}
return {"domain": {"product_uom": []}}
def _prepare_procurement_values(
self,
product_qty,
date=False,
group=False,
):
"""Prepare specific key for moves or other components that will be
created from a stock rule comming from a buffer. This method could
be override in order to add other custom key that could
be used in move/po creation.
"""
return {
"date_planned": date or self._get_date_planned(),
"warehouse_id": self.warehouse_id,
"buffer_id": self,
"company_id": self.company_id,
"group_id": group or self.group_id,
}
# MANUAL PROCUREMENT AND UOM
def _get_date_planned(self, force_lt=None):
self.ensure_one()
profile = self.buffer_profile_id
dlt = int(self.dlt)
if force_lt and isinstance(force_lt, (int, float)):
dlt = force_lt
if profile.item_type == "distributed":
max_proc_time = profile.distributed_reschedule_max_proc_time
else:
max_proc_time = 0
# For purchased items we always consider calendar days,
# not work days.
if profile.item_type == "purchased":
dt_planned = fields.datetime.today() + timedelta(days=dlt)
else:
if self.warehouse_id.calendar_id:
dt_planned = self.warehouse_id.wh_plan_days(fields.datetime.now(), dlt)
if max_proc_time:
calendar = self.warehouse_id.calendar_id
# We found the day with "wh_plan_day", now determine
# the first available hour in the day (wh_plan_day returns
# the stop hour), and add the procurement time.
dt_planned = calendar.plan_hours(
# expect hours
max_proc_time / 60,
# start from the first working hours available
dt_planned.replace(hour=0, minute=0, second=0),
)
else:
dt_planned = (
fields.datetime.now()
+ timedelta(days=dlt)
+ timedelta(minutes=max_proc_time)
)
return dt_planned
procure_recommended_qty = fields.Float(
string="Procure Recommendation",
compute="_compute_procure_recommended_qty",
store=True,
)
procure_uom_id = fields.Many2one(
comodel_name="uom.uom",
string="Procurement UoM",
compute="_compute_procure_uom_id",
readonly=False,
store=True,
)
@api.constrains("product_id", "procure_uom_id")
def _check_procure_uom(self):
if any(
buffer.product_uom
and buffer.procure_uom_id
and buffer.product_uom.category_id != buffer.procure_uom_id.category_id
for buffer in self
):
raise ValidationError(
_(
"Error: The product default Unit of Measure and the "
"procurement Unit of Measure must be in the same category."
)
)
# STOCK INFORMATION:
product_location_qty_available_not_res = fields.Float(
string="Quantity On Hand (Unreserved)",
help="Quantity available in this stock buffer, this is the total "
"quantity on hand minus the outgoing reservations.",
readonly=True,
)
def _get_outgoing_reservation_qty(self):
"""Return the qty reserved in operations that move products outside
of the buffer in the UoM of the product."""
domain = [
("product_id", "=", self.product_id.id),
("state", "in", ("partially_available", "assigned")),
]
lines = self.env["stock.move.line"].search(domain)
lines = lines.filtered(
lambda line: line.location_id.is_sublocation_of(self.location_id)
and not line.location_dest_id.is_sublocation_of(self.location_id)
)
return sum(lines.mapped("reserved_qty"))
def _update_quantities_dict(self, product):
self.ensure_one()
reserved_qty = self._get_outgoing_reservation_qty()
self.update(
{
"product_location_qty_available_not_res": product["qty_available"]
- reserved_qty,
}
)
def _calc_product_available_qty(self):
operation_by_location = defaultdict(lambda: self.browse())
for rec in self:
operation_by_location[rec.location_id] |= rec
for location_id, buffer_in_location in operation_by_location.items():
products = (
buffer_in_location.mapped("product_id")
.with_context(location=location_id.id)
._compute_quantities_dict(
lot_id=self.env.context.get("lot_id"),
owner_id=self.env.context.get("owner_id"),
package_id=self.env.context.get("package_id"),
)
)
for buffer in buffer_in_location:
product = products[buffer.product_id.id]
buffer._update_quantities_dict(product)
# PURCHASES LINK:
purchase_line_ids = fields.Many2many(
comodel_name="purchase.order.line",
string="Purchase Order Lines",
copy=False,
readonly=True,
)
# MRP LINK:
def action_view_mrp_productions(self):
result = self.env["ir.actions.actions"]._for_xml_id("mrp.mrp_production_action")
result["context"] = {}
mrp_production_ids = self.env["mrp.production"].search(
[("buffer_id", "=", self.id)]
)
result["domain"] = [("id", "in", mrp_production_ids.ids)]
return result
product_type = fields.Selection(related="product_id.type", readonly=True)
used_in_bom_count = fields.Integer(related="product_id.used_in_bom_count")
def action_used_in_bom(self):
self.ensure_one()
action = self.env["ir.actions.actions"]._for_xml_id("mrp.mrp_bom_form_action")
action["domain"] = [("bom_line_ids.product_id", "=", self.product_id.id)]
return action
# DDMRP SPECIFIC:
@api.depends(
"dlt",
"extra_lead_time",
"adu",
"buffer_profile_id.lead_time_id.factor",
"red_override",
"buffer_profile_id.variability_id.factor",
"product_uom.rounding",
"lead_days",
"product_id.seller_ids.delay",
)
def _compute_red_zone(self):
for rec in self:
if rec.product_id and rec.replenish_method in ["replenish", "min_max"]:
dlt = rec.dlt + rec.extra_lead_time
rec.red_base_qty = float_round(
dlt * rec.adu * rec.buffer_profile_id.lead_time_id.factor,
precision_rounding=rec.product_uom.rounding,
)
rec.red_safety_qty = float_round(
rec.red_base_qty * rec.buffer_profile_id.variability_id.factor,
precision_rounding=rec.product_uom.rounding,
)
rec.red_zone_qty = rec.red_base_qty + rec.red_safety_qty
elif rec.product_id and rec.replenish_method == "replenish_override":
rec.red_zone_qty = rec.red_override
else:
rec.red_zone_qty = 0.0
@api.depends(
"dlt",
"extra_lead_time",
"adu",
"buffer_profile_id.lead_time_id.factor",
"order_cycle",
"minimum_order_quantity",
"product_uom.rounding",
"green_override",
"top_of_yellow",
)
def _compute_green_zone(self):
for rec in self:
if rec.product_id and rec.replenish_method in ["replenish", "min_max"]:
# Using imposed or desired minimum order cycle
rec.green_zone_oc = float_round(
rec.order_cycle * rec.adu,
precision_rounding=rec.product_uom.rounding,
)
# Using lead time factor
dlt = rec.dlt + rec.extra_lead_time
rec.green_zone_lt_factor = float_round(
dlt * rec.adu * rec.buffer_profile_id.lead_time_id.factor,
precision_rounding=rec.product_uom.rounding,
)
# Using minimum order quantity
rec.green_zone_moq = float_round(
rec.minimum_order_quantity,
precision_rounding=rec.product_uom.rounding,
)
# The biggest option of the above will be used as the green
# zone value
rec.green_zone_qty = max(
rec.green_zone_oc, rec.green_zone_lt_factor, rec.green_zone_moq
)
elif rec.product_id and rec.replenish_method == "replenish_override":
rec.green_zone_qty = rec.green_override
else:
rec.green_zone_qty = 0.0
rec.top_of_green = rec.green_zone_qty + rec.top_of_yellow
@api.depends(
"dlt",
"extra_lead_time",
"adu",
"buffer_profile_id.lead_time_id.factor",
"buffer_profile_id.variability_id.factor",
"buffer_profile_id.replenish_method",
"order_cycle",
"minimum_order_quantity",
"product_uom.rounding",
"yellow_override",
"red_zone_qty",
)
def _compute_yellow_zone(self):
for rec in self:
if rec.product_id and rec.replenish_method == "min_max":
rec.yellow_zone_qty = 0
elif rec.product_id and rec.replenish_method == "replenish":
dlt = rec.dlt + rec.extra_lead_time
rec.yellow_zone_qty = float_round(
dlt * rec.adu, precision_rounding=rec.product_uom.rounding
)
elif rec.product_id and rec.replenish_method == "replenish_override":
rec.yellow_zone_qty = rec.yellow_override
else:
rec.yellow_zone_qty = 0.0
rec.top_of_yellow = rec.yellow_zone_qty + rec.red_zone_qty
@api.depends(
"net_flow_position",
"top_of_green",
"qty_multiple",
"product_uom",
"procure_uom_id",
"product_uom.rounding",
)
def _compute_procure_recommended_qty(self):
subtract_qty = self.sudo()._quantity_in_progress()
for rec in self:
procure_recommended_qty = 0.0
# uses _origin because onchange uses a NewId with the record wrapped
if rec._origin and rec.net_flow_position < rec.top_of_yellow:
qty = (
rec.top_of_green
- rec.net_flow_position
- subtract_qty[rec._origin.id]
)
if qty >= 0.0:
procure_recommended_qty = qty
elif rec._origin:
if subtract_qty[rec._origin.id] > 0.0:
procure_recommended_qty -= subtract_qty[rec._origin.id]
adjusted_qty = 0.0
if procure_recommended_qty > 0.0:
adjusted_qty = rec._adjust_procure_qty(procure_recommended_qty)
rec.procure_recommended_qty = adjusted_qty
@api.depends("product_uom")
def _compute_procure_uom_id(self):
for rec in self:
rec.procure_uom_id = rec.product_uom.id
def _adjust_procure_qty(self, qty):
self.ensure_one()
# If there is a procure UoM we apply it before anything.
# This means max, min and multiple quantities are relative to
# the procure UoM.
if self.procure_uom_id:
rounding = self.procure_uom_id.rounding
adjusted_qty = self.product_id.uom_id._compute_quantity(
qty, self.procure_uom_id
)
else:
rounding = self.product_uom.rounding
adjusted_qty = qty
# Apply qty multiple and minimum quantity (maximum quantity
# applies on the procure wizard)
remainder = self.qty_multiple > 0 and adjusted_qty % self.qty_multiple or 0.0
multiple_tolerance = self.qty_multiple * (
self.company_id.ddmrp_qty_multiple_tolerance / 100
)
if (
float_compare(remainder, multiple_tolerance, precision_rounding=rounding)
> 0
):
adjusted_qty += self.qty_multiple - remainder
elif float_compare(remainder, 0.0, precision_rounding=rounding) > 0:
adjusted_qty -= remainder
if (
float_compare(
adjusted_qty, self.procure_min_qty, precision_rounding=rounding
)
< 0
):
adjusted_qty = self.procure_min_qty
return adjusted_qty
def _compute_ddmrp_chart_planning(self):
"""This method use the Bokeh library to create a buffer depiction."""
for rec in self:
div, script = rec.get_ddmrp_chart_planning()
json_data = json.dumps(
{
"div": div,
"script": script,
}
)
rec.ddmrp_chart = json_data
def _compute_ddmrp_chart_execution(self):
for rec in self:
div, script = rec.get_ddmrp_chart_execution()
json_data = json.dumps(
{
"div": div,
"script": script,
}
)
rec.ddmrp_chart_execution = json_data
def _get_colors_hex_map(self, pallete="planning"):
return DDMRP_COLOR
def get_ddmrp_chart_planning(self):
p = figure(frame_width=300, frame_height=400, y_axis_label="Quantity")
p.xaxis.visible = False
p.toolbar.logo = None
hex_colors = self._get_colors_hex_map(pallete="planning")
red = p.vbar(
x=1,
bottom=0,
top=self.top_of_red,
width=1,
color=hex_colors.get("1_red", "red"),
)
yellow = p.vbar(
x=1,
bottom=self.top_of_red,
top=self.top_of_yellow,
width=1,
color=hex_colors.get("2_yellow", "yellow"),
)
green = p.vbar(
x=1,
bottom=self.top_of_yellow,
top=self.top_of_green,
width=1,
color=hex_colors.get("3_green", "green"),
)
net_flow = p.line(
[0, 2], [self.net_flow_position, self.net_flow_position], line_width=2
)
on_hand = p.line(
[0, 2],
[
self.product_location_qty_available_not_res,
self.product_location_qty_available_not_res,
],
line_width=2,
line_dash="dotted",
)
legend = Legend(
items=[
("Red zone", [red]),
("Yellow zone", [yellow]),
("Green zone", [green]),
("Net Flow Position", [net_flow]),
("On-Hand Position (Unreserved)", [on_hand]),
],
)
labels_source_data = {
"height": [
self.net_flow_position,
self.product_location_qty_available_not_res,
self.top_of_red,
self.top_of_yellow,
self.top_of_green,
],
"weight": [0.25, 1.75, 1, 1, 1],
"names": [
str(self.net_flow_position),
str(self.product_location_qty_available_not_res),
str(self.top_of_red),
str(self.top_of_yellow),
str(self.top_of_green),
],
}
source = ColumnDataSource(data=labels_source_data)
labels = LabelSet(
x="weight",
y="height",
text="names",
y_offset=1,
text_font_size="8pt",
source=source,
text_align="center",
)
p.add_layout(labels)
p.add_layout(legend, "below")
script, div = components(p, wrap_script=False)
return div, script
def get_ddmrp_chart_execution(self):
p = figure(frame_width=300, frame_height=400, y_axis_label="Quantity")
p.xaxis.visible = False
p.toolbar.logo = None
tor_exec = float_round(
self.top_of_red / 2,
precision_rounding=self.product_uom.rounding,
)
toy_exec = self.top_of_red
tog_exec = float_round(
self.top_of_red + self.green_zone_qty,
precision_rounding=self.product_uom.rounding,
)
toy2_exec = self.top_of_yellow
tor2_exec = self.top_of_green
hex_colors = self._get_colors_hex_map(pallete="execution")
red = p.vbar(
x=1,
bottom=0,
top=tor_exec,
width=1,
color=hex_colors.get("1_red", "red"),
)
yellow = p.vbar(
x=1,
bottom=tor_exec,
top=toy_exec,
width=1,
color=hex_colors.get("2_yellow", "yellow"),
)
green = p.vbar(
x=1,
bottom=toy_exec,
top=tog_exec,
width=1,
color=hex_colors.get("3_green", "green"),
)
yellow_2 = p.vbar(
x=1,
bottom=tog_exec,
top=toy2_exec,
width=1,
color=hex_colors.get("2_yellow", "yellow"),
)
red_2 = p.vbar(
x=1,
bottom=toy2_exec,
top=tor2_exec,
width=1,
color=hex_colors.get("1_red", "red"),
)
on_hand = p.line(
[0, 2],
[
self.product_location_qty_available_not_res,
self.product_location_qty_available_not_res,
],
line_width=2,
line_dash="dotted",
)
legend = Legend(
items=[
("Red zone (Execution)", [red, red_2]),
("Yellow zone (Execution)", [yellow, yellow_2]),
("Green zone (Execution)", [green]),
("On-Hand Position (Unreserved)", [on_hand]),
]
)
labels_source_data = {
"height": [
self.product_location_qty_available_not_res,
tor_exec,
toy_exec,
tog_exec,
toy2_exec,
],
"weight": [0.25, 1, 1, 1, 1],
"names": [
str(self.product_location_qty_available_not_res),
str(tor_exec),
str(toy_exec),
str(tog_exec),
str(toy2_exec),
],
}
source = ColumnDataSource(data=labels_source_data)
labels = LabelSet(
x="weight",
y="height",
text="names",
y_offset=1,
text_font_size="8pt",
source=source,
text_align="center",
)
p.add_layout(labels)
p.add_layout(legend, "below")
script, div = components(p, wrap_script=False)
return div, script
def _compute_ddmrp_demand_supply_chart(self):
for rec in self:
if not rec.buffer_profile_id:
# Not a buffer, skip.
rec.ddmrp_demand_chart = ""
rec.ddmrp_supply_chart = ""
continue
# Prepare data:
demand_data = rec._get_demand_by_days(rec.qualified_demand_stock_move_ids)
mrp_data = rec._get_qualified_mrp_moves(rec.qualified_demand_mrp_move_ids)
supply_data = rec._get_incoming_by_days()
width = timedelta(days=0.4)
date_format = (
self.env["res.lang"]._lang_get(self.env.lang or "en_US").date_format
)
# Plot demand data:
if demand_data or mrp_data:
x_demand = list(convert_datetime_type(x) for x in demand_data.keys())
y_demand = list(demand_data.values())
x_mrp = list(convert_datetime_type(x) for x in mrp_data.keys())
y_mrp = list(mrp_data.values())
p = figure(
frame_width=500,
frame_height=400,
y_axis_label="Quantity",
x_axis_type="datetime",
)
p.toolbar.logo = None
p.sizing_mode = "stretch_both"
# TODO: # p.xaxis.label_text_font = "helvetica"
p.xaxis.formatter = DatetimeTickFormatter(
hours=date_format,
days=date_format,
months=date_format,
years=date_format,
)
p.xaxis.major_label_orientation = pi / 4
if demand_data:
p.vbar(
x=x_demand,
width=width,
bottom=0,
top=y_demand,
color="firebrick",
)
if mrp_data:
p.vbar(
x=x_mrp, width=width, bottom=0, top=y_mrp, color="lightsalmon"
)
p.line(
[
datetime.today() - timedelta(days=1),
datetime.today() + timedelta(days=rec.order_spike_horizon),
],
[rec.order_spike_threshold, rec.order_spike_threshold],
line_width=2,
line_dash="dashed",
)
unit = rec.product_uom.name
hover = HoverTool(
tooltips=[("qty", "$y %s" % unit)], point_policy="follow_mouse"
)
p.add_tools(hover)
script, div = components(p, wrap_script=False)
json_data = json.dumps(
{
"div": div,
"script": script,
}
)
rec.ddmrp_demand_chart = json_data
else:
rec.ddmrp_demand_chart = json.dumps(
{
"div": _("No demand detected."),
"script": "",
}
)
# Plot supply data:
if supply_data:
x_supply = list(convert_datetime_type(x) for x in supply_data.keys())
y_supply = list(supply_data.values())
p = figure(
frame_width=500,
frame_height=400,
y_axis_label="Quantity",
x_axis_type="datetime",
)
p.toolbar.logo = None
p.sizing_mode = "stretch_both"
p.xaxis.formatter = DatetimeTickFormatter(
hours=date_format,
days=date_format,
months=date_format,
years=date_format,
)
p.xaxis.major_label_orientation = pi / 4
# White line to have similar proportion to demand chart.
p.line(
[
datetime.today() - timedelta(days=1),
datetime.today() + timedelta(days=rec.order_spike_horizon),
],
[rec.order_spike_threshold, rec.order_spike_threshold],
line_width=2,
line_dash="dashed",
color="white",
)
p.vbar(x=x_supply, width=width, bottom=0, top=y_supply, color="grey")
unit = rec.product_uom.name
hover = HoverTool(
tooltips=[("qty", "$y %s" % unit)], point_policy="follow_mouse"
)
p.add_tools(hover)
script, div = components(p, wrap_script=False)
json_data = json.dumps(
{
"div": div,
"script": script,
}
)
rec.ddmrp_supply_chart = json_data
else:
rec.ddmrp_supply_chart = json.dumps(
{
"div": _("No supply detected."),
"script": "",
}
)
@api.depends("red_zone_qty")
def _compute_order_spike_threshold(self):
for rec in self:
rec.order_spike_threshold = 0.5 * rec.red_zone_qty
def _get_manufactured_bom(self):
return self.env["mrp.bom"].search(
[
"|",
("product_id", "=", self.product_id.id),
("product_tmpl_id", "=", self.product_id.product_tmpl_id.id),
"|",
("location_id", "=", self.location_id.id),
("location_id", "=", False),
],
limit=1,
)
@api.depends("lead_days", "product_id.seller_ids.delay")
def _compute_dlt(self):
for rec in self:
if rec.buffer_profile_id.item_type == "manufactured":
bom = rec._get_manufactured_bom()
dlt = bom.dlt
elif rec.buffer_profile_id.item_type == "distributed":
dlt = rec.lead_days
else:
sellers = rec._get_product_sellers()
dlt = sellers and fields.first(sellers).delay or rec.lead_days
rec.dlt = dlt
def _get_product_sellers(self):
""":returns the default sellers for a single buffer."""
self.ensure_one()
all_sellers = self.product_id.seller_ids.filtered(
lambda r: not r.company_id or r.company_id == self.company_id
)
today = fields.Date.context_today(self)
sellers = all_sellers.filtered(
lambda s: (
(s.product_id == self.product_id or not s.product_id)
and (
(s.date_start <= today if s.date_start else True)
and (s.date_end >= today if s.date_end else True)