-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathoutbound.py
More file actions
2125 lines (2007 loc) · 87.5 KB
/
outbound.py
File metadata and controls
2125 lines (2007 loc) · 87.5 KB
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
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014 by frePPLe bv
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
import json
import logging
import pytz
import xmlrpc.client
from xml.sax.saxutils import quoteattr
from datetime import datetime, timedelta
from pytz import timezone
import ssl
from .. import with_mrp
try:
import odoo
except ImportError:
pass
logger = logging.getLogger(__name__)
class Odoo_generator:
def __init__(self, env):
self.env = env
def setContext(self, **kwargs):
t = dict(self.env.context)
t.update(kwargs)
self.env = self.env(
user=self.env.user,
context=t,
)
def callMethod(self, model, id, method, args=[]):
for obj in self.env[model].browse(id):
return getattr(obj, method)(*args)
return None
def getData(self, model, search=[], order=None, fields=[], ids=None):
if ids is not None:
return self.env[model].browse(ids).read(fields) if ids else []
if order:
return self.env[model].search_read(
domain=search, order=order, fields=fields)
else:
return self.env[model].search_read(domain=search, fields=fields)
class XMLRPC_generator:
pagesize = 5000
def __init__(self, url, db, username, password):
self.db = db
self.password = password
self.env = xmlrpc.client.ServerProxy(
"{}/xmlrpc/2/common".format(url),
context=ssl._create_unverified_context(),
)
self.uid = self.env.authenticate(db, username, password, {})
self.env = xmlrpc.client.ServerProxy(
"{}/xmlrpc/2/object".format(url),
context=ssl._create_unverified_context(),
use_builtin_types=True,
headers={"Connection": "keep-alive"}.items(),
)
self.context = {}
def setContext(self, **kwargs):
self.context.update(kwargs)
def callMethod(self, model, id, method, args):
return self.env.execute_kw(
self.db, self.uid, self.password, model, method, [id], []
)
def getData(self, model, search=None, order="id asc", fields=[], ids=[]):
if ids:
page_ids = [ids]
else:
page_ids = []
offset = 0
msg = {
"limit": self.pagesize,
"offset": offset,
"context": self.context,
"order": order,
}
while True:
extra_ids = self.env.execute_kw(
self.db,
self.uid,
self.password,
model,
"search",
[search] if search else [[]],
msg,
)
if not extra_ids:
break
page_ids.append(extra_ids)
offset += self.pagesize
msg["offset"] = offset
if page_ids and page_ids != [[]]:
data = []
for page in page_ids:
data.extend(
self.env.execute_kw(
self.db,
self.uid,
self.password,
model,
"read",
[page],
{"fields": fields, "context": self.context},
)
)
return data
else:
return []
class exporter(object):
def __init__(
self,
generator,
req,
uid,
database=None,
company=None,
mode=1,
timezone=None,
singlecompany=False,
version="0.0.0.unknown",
delta=999,
):
self.database = database
self.company = company
self.generator = generator
self.version = version
self.timezone = timezone
if timezone:
if timezone not in pytz.all_timezones:
logger.warning("Invalid timezone URL argument: %s." % (timezone,))
self.timezone = None
else:
# Valid timezone override in the url
self.timezone = timezone
if not self.timezone:
# Default timezone: use the timezone of the connector user (or UTC if not set)
for i in self.generator.getData(
"res.users",
ids=[
uid,
],
fields=["tz"],
):
self.timezone = i["tz"] or "UTC"
self.timeformat = "%Y-%m-%dT%H:%M:%S"
self.singlecompany = singlecompany
self.delta = delta
# The mode argument defines different types of runs:
# - Mode 1:
# This mode returns all data that is loaded with every planning run.
# Currently this mode transfers all objects, except closed sales orders.
# - Mode 2:
# This mode returns data that is loaded that changes infrequently and
# can be transferred during automated scheduled runs at a quiet moment.
# Currently this mode transfers only closed sales orders.
#
# Normally an Odoo object should be exported by only a single mode.
# Exporting a certain object with BOTH modes 1 and 2 will only create extra
# processing time for the connector without adding any benefits. On the other
# hand it won't break things either.
#
# Which data elements belong to each mode can vary between implementations.
self.mode = mode
def run(self):
# Check if we manage by work orders or manufacturing orders.
self.manage_work_orders = False
for rec in self.generator.getData(
"ir.model", search=[("model", "=", "mrp.workorder")], fields=["name"]
):
self.manage_work_orders = True
# Load some auxiliary data in memory
self.load_company()
if self.mode == 0:
# This was only a connection test
yield '<?xml version="1.0" encoding="UTF-8" ?>\n'
yield '<plan xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" source="odoo_%s">' % self.mode
yield "connection ok"
yield "</plan>"
return
self.load_uom()
# Header.
# The source attribute is set to 'odoo_<mode>', such that all objects created or
# updated from the data are also marked as from originating from odoo.
yield '<?xml version="1.0" encoding="UTF-8" ?>\n'
yield '<plan xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" source="odoo_%s">\n' % self.mode
yield "<description>Generated by odoo %s</description>\n" % odoo.release.version
# Synchronize users
for i in self.export_users():
yield i
# Main content.
# The order of the entities is important. First one needs to create the
# objects before they are referenced by other objects.
# If multiple types of an entity exists (eg operation_time_per,
# operation_alternate, operation_alternate, etc) the reference would
# automatically create an object, potentially of the wrong type.
if with_mrp:
logger.debug("Exporting calendars.")
if self.mode == 1:
for i in self.export_calendar():
yield i
logger.debug("Exporting locations.")
for i in self.export_locations():
yield i
logger.debug("Exporting customers.")
for i in self.export_customers():
yield i
if self.mode == 1:
logger.debug("Exporting suppliers.")
for i in self.export_suppliers():
yield i
if with_mrp:
logger.debug("Exporting skills.")
for i in self.export_skills():
yield i
logger.debug("Exporting workcenters.")
for i in self.export_workcenters():
yield i
logger.debug("Exporting workcenterskills.")
for i in self.export_workcenterskills():
yield i
logger.debug("Exporting products.")
for i in self.export_items():
yield i
if with_mrp:
logger.debug("Exporting BOMs.")
if self.mode == 1:
for i in self.export_boms():
yield i
logger.debug("Exporting sales orders.")
for i in self.export_salesorders():
yield i
# Uncomment the following lines to create forecast models in frepple
# logger.debug("Exporting forecast.")
# for i in self.export_forecasts():
# yield i
if self.mode == 1:
logger.debug("Exporting purchase orders.")
for i in self.export_purchaseorders():
yield i
if with_mrp:
logger.debug("Exporting manufacturing orders.")
for i in self.export_manufacturingorders():
yield i
logger.debug("Exporting reordering rules.")
for i in self.export_orderpoints():
yield i
logger.debug("Exporting quantities on-hand.")
for i in self.export_onhand():
yield i
# Footer
yield "</plan>\n"
def load_company(self):
self.company_id = 0
for i in self.generator.getData(
"res.company",
search=[("name", "=", self.company)],
fields=[
"security_lead",
"po_lead",
"manufacturing_lead",
"calendar",
"manufacturing_warehouse",
"respect_reservations",
],
):
self.company_id = i["id"]
self.security_lead = int(
i["security_lead"]
) # TODO NOT USED RIGHT NOW - add parameter in frepple for this
self.po_lead = i["po_lead"]
self.manufacturing_lead = i["manufacturing_lead"]
self.respect_reservations = i["respect_reservations"]
try:
self.calendar = i["calendar"] and i["calendar"][1] or None
self.mfg_location = (
i["manufacturing_warehouse"]
and i["manufacturing_warehouse"][1]
or self.company
)
except Exception:
self.calendar = None
self.mfg_location = None
if self.singlecompany:
# Create a new context to limit the data to the selected company
self.generator.setContext(allowed_company_ids=[i["id"]])
if not self.company_id:
logger.warning("Can't find company '%s'" % self.company)
self.company_id = None
self.security_lead = 0
self.po_lead = 0
self.manufacturing_lead = 0
self.calendar = None
self.mfg_location = self.company
def load_uom(self):
"""
Loading units of measures into a dictionary for fast lookups.
All quantities are sent to frePPLe as numbers, expressed in the default
unit of measure of the uom dimension.
"""
self.uom = {}
self.uom_categories = {}
for i in self.generator.getData(
"uom.uom",
# We also need to load INactive UOMs, because there still might be records
# using the inactive UOM. Questionable practice, but can happen...
search=["|", ("active", "=", 1), ("active", "=", 0)],
fields=["factor", "uom_type", "category_id", "name"],
):
if i["uom_type"] == "reference":
self.uom_categories[i["category_id"][0]] = i["id"]
self.uom[i["id"]] = {
"factor": i["factor"],
"category": i["category_id"][0],
"name": i["name"],
}
def convert_qty_uom(self, qty, uom_id, product_template_id=None):
"""
Convert a quantity to the reference uom of the product template.
"""
try:
uom_id = uom_id[0]
except Exception as e:
pass
if not uom_id:
return qty
if not product_template_id:
return qty * self.uom[uom_id]["factor"]
try:
product_uom = self.product_templates[product_template_id]["uom_id"][0]
except Exception:
return qty * self.uom[uom_id]["factor"]
# check if default product uom is the one we received
if product_uom == uom_id:
return qty
# check if different uoms belong to the same category
if self.uom[product_uom]["category"] == self.uom[uom_id]["category"]:
return qty / self.uom[uom_id]["factor"] * self.uom[product_uom]["factor"]
else:
# UOM is from a different category as the reference uom of the product.
logger.warning(
"Can't convert from %s for product template %s"
% (self.uom[uom_id]["name"], product_template_id)
)
return qty * self.uom[uom_id]["factor"]
def convert_float_time(self, float_time, units="days"):
"""
Convert Odoo float time to ISO 8601 duration.
"""
d = timedelta(**{units: float_time})
return "P%dDT%dH%dM%dS" % (
d.days, # duration: days
int(d.seconds / 3600), # duration: hours
int((d.seconds % 3600) / 60), # duration: minutes
int(d.seconds % 60), # duration: seconds
)
def formatDateTime(self, d, tmzone=None):
if not isinstance(d, datetime):
d = datetime.fromisoformat(d)
return d.astimezone(timezone(tmzone or self.timezone)).strftime(self.timeformat)
def export_users(self):
users = []
for grp in self.generator.getData(
"res.groups",
search=[("name", "=", "frePPLe user")],
fields=[
"users",
],
):
for usr in self.generator.getData(
"res.users",
ids=grp["users"],
fields=["name", "login"],
):
users.append(
(
usr["name"],
usr["login"],
)
)
yield '<stringproperty name="users" value=%s/>\n' % quoteattr(json.dumps(users))
def export_calendar(self):
"""
Reads all calendars from resource.calendar model and creates a calendar in frePPLe.
Attendance times are read from resource.calendar.attendance
Leave times are read from resource.calendar.leaves
resource.calendar.name -> calendar.name (default value is 0)
resource.calendar.attendance.date_from -> calendar bucket start date (or 2020-01-01 if unspecified)
resource.calendar.attendance.date_to -> calendar bucket end date (or 2030-01-01 if unspecified)
resource.calendar.attendance.hour_from -> calendar bucket start time
resource.calendar.attendance.hour_to -> calendar bucket end time
resource.calendar.attendance.dayofweek -> calendar bucket day
resource.calendar.leaves.date_from -> calendar bucket start date
resource.calendar.leaves.date_to -> calendar bucket end date
For two-week calendars all weeks between the calendar start and
calendar end dates are added in frepple as calendar buckets.
The week number is using the iso standard (first week of the
year is the one containing the first Thursday of the year).
"""
yield "<!-- calendar -->\n"
yield "<calendars>\n"
calendars = {}
cal_tz = {}
cal_ids = set()
try:
# Read the timezone
for i in self.generator.getData(
"resource.calendar",
fields=[
"name",
"tz",
],
):
cal_tz[i["name"]] = i["tz"]
cal_ids.add(i["id"])
# Read the attendance for all calendars
for i in self.generator.getData(
"resource.calendar.attendance",
search=[("display_type", "=", False)],
fields=[
"dayofweek",
"date_from",
"date_to",
"hour_from",
"hour_to",
"calendar_id",
"week_type",
],
):
if i["calendar_id"] and i["calendar_id"][0] in cal_ids:
if i["calendar_id"][1] not in calendars:
calendars[i["calendar_id"][1]] = []
i["attendance"] = True
calendars[i["calendar_id"][1]].append(i)
# Read the leaves for all calendars
for i in self.generator.getData(
"resource.calendar.leaves",
search=[("time_type", "=", "leave")],
fields=[
"date_from",
"date_to",
"calendar_id",
],
):
if i["calendar_id"] and i["calendar_id"][0] in cal_ids:
if i["calendar_id"][1] not in calendars:
calendars[i["calendar_id"][1]] = []
i["attendance"] = False
calendars[i["calendar_id"][1]].append(i)
# Iterate over the results:
for i in calendars:
priority_attendance = 1000
priority_leave = 10
if cal_tz[i] != self.timezone:
logger.warning(
"timezone is different on workcenter %s and connector user. Working hours will not be synced correctly to frepple."
% i
)
yield '<calendar name=%s default="0"><buckets>\n' % quoteattr(i)
for j in calendars[i]:
if j.get("week_type", False) == False:
# ONE-WEEK CALENDAR
yield '<bucket start="%s" end="%s" value="%s" days="%s" priority="%s" starttime="%s" endtime="%s"/>\n' % (
self.formatDateTime(j["date_from"], cal_tz[i])
if not j["attendance"]
else (
j["date_from"].strftime("%Y-%m-%dT00:00:00")
if j["date_from"]
else "2020-01-01T00:00:00"
),
self.formatDateTime(j["date_to"], cal_tz[i])
if not j["attendance"]
else (
j["date_to"].strftime("%Y-%m-%dT00:00:00")
if j["date_to"]
else "2030-01-01T00:00:00"
),
"1" if j["attendance"] else "0",
(2 ** ((int(j["dayofweek"]) + 1) % 7))
if "dayofweek" in j
else (2**7) - 1,
priority_attendance if j["attendance"] else priority_leave,
# In odoo, monday = 0. In frePPLe, sunday = 0.
("PT%dM" % round(j["hour_from"] * 60))
if "hour_from" in j
else "PT0M",
("PT%dM" % round(j["hour_to"] * 60))
if "hour_to" in j
else "PT1440M",
)
if j["attendance"]:
priority_attendance += 1
else:
priority_leave += 1
else:
# TWO-WEEKS CALENDAR
start = j["date_from"] or datetime(2020, 1, 1)
end = j["date_to"] or datetime(2030, 1, 1)
t = start
while t < end:
if int(t.isocalendar()[1] % 2) == int(j["week_type"]):
if j["hour_to"] == 0:
logger.info(j)
yield '<bucket start="%s" end="%s" value="%s" days="%s" priority="%s" starttime="%s" endtime="%s"/>\n' % (
self.formatDateTime(t, cal_tz[i]),
self.formatDateTime(
min(t + timedelta(7 - t.weekday()), end),
cal_tz[i],
),
"1",
(2 ** ((int(j["dayofweek"]) + 1) % 7))
if "dayofweek" in j
else (2**7) - 1,
priority_attendance,
# In odoo, monday = 0. In frePPLe, sunday = 0.
("PT%dM" % round(j["hour_from"] * 60))
if "hour_from" in j
else "PT0M",
("PT%dM" % round(j["hour_to"] * 60))
if "hour_to" in j
else "PT1440M",
)
priority_attendance += 1
dow = t.weekday()
t += timedelta(7 - dow)
yield "</buckets></calendar>\n"
yield "</calendars>\n"
except Exception as e:
logger.info(e)
yield "</calendars>\n"
def export_locations(self):
"""
Generate a list of warehouse locations to frePPLe, based on the
stock.warehouse model.
We assume the location name to be unique. This is NOT guaranteed by Odoo.
The field subcategory is used to store the id of the warehouse. This makes
it easier for frePPLe to send back planning results directly with an
odoo location identifier.
FrePPLe is not interested in the locations odoo defines with a warehouse.
This methods also populates a map dictionary between these locations and
warehouse they belong to.
Mapping:
stock.warehouse.name -> location.name
stock.warehouse.id -> location.subcategory
"""
self.map_locations = {}
self.warehouses = {}
first = True
for i in self.generator.getData(
"stock.warehouse",
fields=["name"],
):
if first:
yield "<!-- warehouses -->\n"
yield "<locations>\n"
first = False
if self.calendar:
yield '<location name=%s subcategory="%s"><available name=%s/></location>\n' % (
quoteattr(i["name"]),
i["id"],
quoteattr(self.calendar),
)
else:
yield '<location name=%s subcategory="%s"></location>\n' % (
quoteattr(i["name"]),
i["id"],
)
self.warehouses[i["id"]] = i["name"]
if not first:
yield "</locations>\n"
# Populate a mapping location-to-warehouse name for later lookups
for loc in self.generator.getData(
"stock.location",
search=[("usage", "=", "internal")],
fields=["id"],
):
wh = self.generator.callMethod(
"stock.location", loc["id"], "get_warehouse", []
)
if hasattr(wh, "id"):
wh = wh.id
if wh in self.warehouses:
self.map_locations[loc["id"]] = self.warehouses[wh]
def export_customers(self):
"""
Generate a list of customers to frePPLe, based on the res.partner model.
We filter on res.partner where customer = True.
Mapping:
res.partner.id res.partner.name -> customer.name
"""
self.map_customers = {}
first = True
for i in self.generator.getData(
"res.partner",
search=[("customer_rank", ">", 0)],
fields=["name"],
):
if first:
yield "<!-- customers -->\n"
yield "<customers>\n"
first = False
name = "%s %s" % (i["name"], i["id"])
yield "<customer name=%s/>\n" % quoteattr(name)
self.map_customers[i["id"]] = name
if not first:
yield "</customers>\n"
def export_suppliers(self):
"""
Generate a list of suppliers for frePPLe, based on the res.partner model.
We filter on res.supplier where supplier = True.
Mapping:
res.partner.id res.partner.name -> supplier.name
"""
first = True
for i in self.generator.getData(
"res.partner",
search=[("supplier_rank", ">", "0")],
fields=["name"],
):
if first:
yield "<!-- suppliers -->\n"
yield "<suppliers>\n"
first = False
yield "<supplier name=%s/>\n" % quoteattr("%d %s" % (i["id"], i["name"]))
if not first:
yield "</suppliers>\n"
def export_skills(self):
first = True
for i in self.generator.getData(
"mrp.skill",
fields=["name"],
):
if first:
yield "<!-- skills -->\n"
yield "<skills>\n"
first = False
name = i["name"]
yield "<skill name=%s/>\n" % (quoteattr(name),)
if not first:
yield "</skills>\n"
def export_workcenterskills(self):
first = True
for i in self.generator.getData(
"mrp.workcenter.skill",
fields=["workcenter", "skill", "priority"],
):
if not i["workcenter"] or i["workcenter"][0] not in self.map_workcenters:
continue
if first:
yield "<!-- resourceskills -->\n"
yield "<skills>\n"
first = False
yield "<skill name=%s>\n" % quoteattr(i["skill"][1])
yield "<resourceskills>"
yield '<resourceskill priority="%d"><resource name=%s/></resourceskill>' % (
i["priority"],
quoteattr(self.map_workcenters[i["workcenter"][0]]),
)
yield "</resourceskills>"
yield "</skill>"
if not first:
yield "</skills>"
def export_workcenters(self):
"""
Send the workcenter list to frePPLe, based one the mrp.workcenter model.
We assume the workcenter name is unique. Odoo does NOT guarantuee that.
Mapping:
mrp.workcenter.name -> resource.name
mrp.workcenter.owner -> resource.owner
mrp.workcenter.resource_calendar_id -> resource.available
mrp.workcenter.capacity -> resource.maximum
mrp.workcenter.time_efficiency -> resource.efficiency
company.mfg_location -> resource.location
"""
self.map_workcenters = {}
first = True
for i in self.generator.getData(
"mrp.workcenter",
fields=[
"name",
"owner",
"resource_calendar_id",
"time_efficiency",
"capacity",
],
):
if first:
yield "<!-- workcenters -->\n"
yield "<resources>\n"
first = False
name = i["name"]
owner = i["owner"]
available = i["resource_calendar_id"]
self.map_workcenters[i["id"]] = name
yield '<resource name=%s maximum="%s" efficiency="%s"><location name=%s/>%s%s</resource>\n' % (
quoteattr(name),
i["capacity"],
i["time_efficiency"],
quoteattr(self.mfg_location),
("<owner name=%s/>" % quoteattr(owner[1])) if owner else "",
("<available name=%s/>" % quoteattr(available[1])) if available else "",
)
if not first:
yield "</resources>\n"
def export_items(self):
"""
Send the list of products to frePPLe, based on the product.product model.
For purchased items we also create a procurement buffer in each warehouse.
Mapping:
[product.product.code] product.product.name -> item.name
product.product.product_tmpl_id.list_price or standard_price -> item.cost
product.product.id , product.product.product_tmpl_id.uom_id -> item.subcategory
If product.product.product_tmpl_id.purchase_ok
and product.product.product_tmpl_id.routes contains the buy route
we collect the suppliers as product.product.product_tmpl_id.seller_ids
[product.product.code] product.product.name -> itemsupplier.item
res.partner.id res.partner.name -> itemsupplier.supplier.name
supplierinfo.delay -> itemsupplier.leadtime
supplierinfo.min_qty -> itemsupplier.size_minimum
supplierinfo.date_start -> itemsupplier.effective_start
supplierinfo.date_end -> itemsupplier.effective_end
product.product.product_tmpl_id.delay -> itemsupplier.leadtime
supplierinfo.sequence -> itemsupplier.priority
"""
# Read the product categories
self.category_parent = {}
for i in self.generator.getData(
"product.category",
fields=["name", "parent_id"],
):
if i["parent_id"]:
self.category_parent[i["name"]] = i["parent_id"]
# Read the product templates
self.product_product = {}
self.product_template_product = {}
self.product_templates = {}
for i in self.generator.getData(
"product.template",
search=[("type", "not in", ("service", "consu"))],
fields=[
"sale_ok",
"purchase_ok",
"produce_delay",
"list_price",
"standard_price",
"uom_id",
"categ_id",
"product_variant_ids",
],
):
self.product_templates[i["id"]] = i
# Read the products
supplierinfo_fields = [
"name",
"delay",
"min_qty",
"date_end",
"date_start",
"price",
"batching_window",
"sequence",
"is_subcontractor",
]
first = True
for i in self.generator.getData(
"product.product",
fields=[
"id",
"name",
"code",
"product_tmpl_id",
"volume",
"weight",
"product_template_attribute_value_ids",
"price_extra",
],
):
if first:
yield "<!-- products -->\n"
yield "<items>\n"
first = False
if i["product_tmpl_id"][0] not in self.product_templates:
continue
tmpl = self.product_templates[i["product_tmpl_id"][0]]
if i["code"]:
name = ("[%s] %s" % (i["code"], i["name"]))[:300]
else:
name = i["name"][:300]
prod_obj = {
"name": name,
"template": i["product_tmpl_id"][0],
"product_template_attribute_value_ids": i[
"product_template_attribute_value_ids"
],
}
self.product_product[i["id"]] = prod_obj
self.product_template_product[i["product_tmpl_id"][0]] = prod_obj
# For make-to-order items the next line needs to XML snippet ' type="item_mto"'.
yield '<item name=%s uom=%s volume="%f" weight="%f" cost="%f" category=%s subcategory="%s,%s">\n' % (
quoteattr(name),
quoteattr(tmpl["uom_id"][1]) if tmpl["uom_id"] else "",
i["volume"] or 0,
i["weight"] or 0,
max(
0, (tmpl["list_price"] + (i["price_extra"] or 0)) or 0
) # Option 1: Map "sales price" to frepple
# max(0, tmpl["standard_price"]) or 0) # Option 2: Map the "cost" to frepple
/ self.convert_qty_uom(1.0, tmpl["uom_id"], i["product_tmpl_id"][0]),
quoteattr(
"%s%s"
% (
("%s/" % self.category_parent(tmpl["categ_id"][1]))
if tmpl["categ_id"][1] in self.category_parent
else "",
tmpl["categ_id"][1],
)
)
if tmpl["categ_id"]
else '""',
self.uom_categories[self.uom[tmpl["uom_id"][0]]["category"]],
i["id"],
)
# Export suppliers for the item, if the item is allowed to be purchased
if tmpl["purchase_ok"]:
try:
# TODO it's inefficient to run a query per product template.
results = self.generator.getData(
"product.supplierinfo",
search=[("product_tmpl_id", "=", tmpl["id"])],
fields=supplierinfo_fields,
)
except Exception:
# subcontracting module not installed
supplierinfo_fields.remove("is_subcontractor")
results = self.generator.getData(
"product.supplierinfo",
search=[("product_tmpl_id", "=", tmpl["id"])],
fields=supplierinfo_fields,
)
suppliers = {}
for sup in results:
name = "%d %s" % (sup["name"][0], sup["name"][1])
if sup.get("is_subcontractor", False):
if not hasattr(tmpl, "subcontractors"):
tmpl["subcontractors"] = []
tmpl["subcontractors"].append(
{
"name": name,
"delay": sup["delay"],
"priority": sup["sequence"] or 1,
"size_minimum": sup["min_qty"],
}
)
elif (name, sup["date_start"]) in suppliers:
# If there are multiple records with the same supplier & start date
# we pass a single record to frepple with lowest-lead-time,
# lowest-quantity, lowest-sequence, greatest-end-date.
r = suppliers[(name, sup["date_start"])]
if sup["delay"] and (
not r["delay"] or sup["delay"] < r["delay"]
):
r["delay"] = sup["delay"]
if sup["sequence"] and (
not r["sequence"] or sup["sequence"] < r["sequence"]
):
r["sequence"] = sup["sequence"]
if sup["batching_window"] and (
not r["batching_window"]
or sup["batching_window"] > r["batching_window"]
):
r["batching_window"] = sup["batching_window"]
if sup["min_qty"] and (
not r["min_qty"] or sup["min_qty"] < r["min_qty"]
):
r["min_qty"] = sup["min_qty"]
if sup["price"] and (
not r["price"] or sup["price"] < r["price"]
):
r["price"] = sup["price"]
if sup["date_end"] and (
not r["date_end"] or sup["date_end"] > r["date_end"]
):
r["date_end"] = sup["date_end"]
else:
suppliers[(name, sup["date_start"])] = {
"delay": sup["delay"],
"sequence": sup["sequence"] or 1,
"batching_window": sup["batching_window"] or 0,
"min_qty": sup["min_qty"],
"price": max(0, sup["price"]),
"date_end": sup["date_end"],
}
if suppliers:
yield "<itemsuppliers>\n"
for k, v in suppliers.items():
yield '<itemsupplier leadtime="P%dD" priority="%s" batchwindow="P%dD" size_minimum="%f" cost="%f"%s%s><supplier name=%s/></itemsupplier>\n' % (
v["delay"],
v["sequence"] or 1,
v["batching_window"] or 0,
v["min_qty"],
max(0, v["price"]),
' effective_end="%sT00:00:00"'
% v["date_end"].strftime("%Y-%m-%d")
if v["date_end"]
else "",
' effective_start="%sT00:00:00"' % k[1].strftime("%Y-%m-%d")
if k[1]
else "",
quoteattr(k[0]),
)
yield "</itemsuppliers>\n"
yield "</item>\n"
if not first:
yield "</items>\n"
def export_boms(self):