-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathGeneral_BOM_Functions.py
1316 lines (1163 loc) · 54 KB
/
General_BOM_Functions.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 (c) 2023 Paul Ebbers paul.ebbers@gmail.com *
# * *
# * This file is part of the FreeCAD CAx development system. *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * FreeCAD is distributed in the hope that it will be useful, *
# * but WITHOUT ANY WARRANTY; without even the implied warranty of *
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
# * GNU Lesser General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with FreeCAD; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ***************************************************************************/
import FreeCAD as App
import Standard_Functions_BOM_WB as Standard_Functions
from Settings_BoM import CUSTOM_HEADERS
from Settings_BoM import DEBUG_HEADERS
from datetime import datetime
import os
import Settings_BoM
import getpass
# Define the translation
translate = App.Qt.translate
class General_BOM:
customHeaders = CUSTOM_HEADERS
if customHeaders[:1] == ";":
customHeaders = customHeaders[1:]
currentScheme = App.Units.getSchema()
# Function to create BoM. standard, a raw BoM will befrom the main list.
# If a modified list is created, this function can be used to write it the a spreadsheet.
# You can add a dict for the headers of this list
@classmethod
def createBoMSpreadsheet(
self, mainList: list, Headers: dict = None, Summary: bool = False, IFCData=None
):
# If the Mainlist is empty, return.
if mainList is None:
Text = translate("BoM Workbench", "No list available!!")
Standard_Functions.Print(Input=Text, Type="Warning")
return
# Get the active document
doc = App.ActiveDocument
# Get or create the spreadsheet.
IsNewSheet = False
sheet = doc.getObject("BoM")
if sheet is not None:
for i in range(
1, 16384
): # 16384 is the maximum rows of the spreadsheet module
doc.BoM.splitCell("A" + str(i))
sheet.clearAll()
if sheet is None:
sheet = doc.addObject("Spreadsheet::Sheet", "BoM")
IsNewSheet = True
# Define CopyMainList and Header
CopyMainList = []
# Copy the main list
CopyMainList = mainList
# Set the colors for the table
HeaderColorRGB = [243, 202, 98]
FirstColorRGB = [169, 169, 169]
SecondColorRGB = [128, 128, 128]
# region - Set the headers in the spreadsheet
# If Headers is None, Set the default headers
if Headers is None:
Headers = Settings_BoM.ReturnHeaders()
# Create a empty dict for the aditional headers
DebugHeadersDict = {}
CustomHeadersDict = {}
# Go through the debug headers
if DEBUG_HEADERS != "":
DebugHeaderList = DEBUG_HEADERS.split(";")
for i in range(len(DebugHeaderList)):
# Set the header
Header = DebugHeaderList[i]
# Set the column
Column = Standard_Functions.GetLetterFromNumber(len(Headers) + i + 1)
# Set the cell
Cell = f"{Column}1"
# Add the cell and header as a dict item to the dict AdditionalHeaders
DebugHeadersDict[Cell] = Header
# Get the headers with additional headers
Headers = Settings_BoM.ReturnHeaders(
Headers=Headers, AdditionalHeaders=DebugHeadersDict
)
# Go through the custom headers
if CustomHeadersDict is not None or bool(CustomHeadersDict) is True:
if IFCData is None:
CustomHeaderList = self.customHeaders.split(";")
for i in range(len(CustomHeaderList)):
# Set the header
Header = CustomHeaderList[i]
# Set the column
Column = Standard_Functions.GetLetterFromNumber(
len(Headers) + i + 1
)
# Set the cell
Cell = f"{Column}1"
# Add the cell and header as a dict item to the dict AdditionalHeaders
CustomHeadersDict[Cell] = Header
# Set the headers with additional headers
Headers = Settings_BoM.ReturnHeaders(
Headers=Headers, AdditionalHeaders=CustomHeadersDict
)
# Define the header range based on Headers
HeaderRange = f"A1:{Standard_Functions.GetLetterFromNumber(len(Headers))}1"
# Create the headers and set the width
for key, value in Headers.items():
sheet.set(key, value)
# set the width based on the headers
Standard_Functions.SetColumnWidth_SpreadSheet(
sheet=sheet, column=key[:1], cellValue=value
)
# Style the Top row
sheet.setStyle(HeaderRange, "bold") # \bold|italic|underline'
# Go through the main list and add every rowList to the spreadsheet.
# Define a row counter
Row = 0
Column = ""
Value = ""
ValuePrevious = ""
TotalNoItems = 0
# Go through the CopyMainlist
for i in range(len(CopyMainList)):
rowList = CopyMainList[i]
# Set the row offset to 2. otherwise the headers will be overwritten
rowOffset = 2
# Increase the row
Row = i + rowOffset
# Fill the spreadsheet
# The standard headers
sheet.set(
"A" + str(Row), "'" + str(rowList["ItemNumber"])
) # add ' at the beginning to make sure it is text.
sheet.set("B" + str(Row), str(rowList["Qty"]))
sheet.set("C" + str(Row), rowList["ObjectLabel"])
sheet.set(
"D" + str(Row),
self.ReturnDocProperty(rowList["DocumentObject"], "Label2"),
) # This will be the description
# The debug headers
for i in range(4, len(Headers) + 1):
Column = Standard_Functions.GetLetterFromNumber(i)
if Headers[Column + "1"] == "Type":
sheet.set(Column + str(Row), rowList["Type"])
elif Headers[Column + "1"].lower() == "label":
sheet.set(
Column + str(Row),
self.ReturnDocProperty(rowList["DocumentObject"], "Label"),
)
elif Headers[Column + "1"].lower() == "name":
sheet.set(
Column + str(Row),
self.ReturnDocProperty(rowList["DocumentObject"], "Name"),
)
elif Headers[Column + "1"].lower() == "fullname":
sheet.set(
Column + str(Row),
self.ReturnDocProperty(rowList["DocumentObject"], "FullName"),
)
elif Headers[Column + "1"].lower() == "typeid":
sheet.set(
Column + str(Row),
self.ReturnDocProperty(rowList["DocumentObject"], "TypeId"),
)
else:
try:
sheet.set(
Column + str(Row),
self.ReturnViewProperty(
rowList["DocumentObject"], Headers[Column + "1"]
)[0],
)
# NewHeader = ""
# Unit = self.ReturnViewProperty(rowList["DocumentObject"], Headers[Column + "1"])[1]
# # if Unit != "":
# # NewHeader = Headers[Column + "1"] + " [" + Unit + "]"
# # if sheet.getContents(Column + "1") != NewHeader:
# # sheet.set(Column + "1", NewHeader)
except Exception as e:
# print(e)
pass
# Create the total number of items for the summary
TotalNoItems = TotalNoItems + int(rowList["Qty"])
# Set the column widht
for key in Headers:
Column = key[:1]
Value = str(sheet.getContents(Column + str(Row)))
ValuePrevious = str(sheet.getContents(Column + str(Row - 1)))
if len(Value) > len(ValuePrevious) and len(Value) > len(Headers[key]):
Standard_Functions.SetColumnWidth_SpreadSheet(
sheet=sheet, column=Column, cellValue=Value
)
# Allign the columns
if Row > 1:
sheet.setAlignment(
"A1:"
+ str(Standard_Functions.GetLetterFromNumber(len(Headers)))
+ str(Row),
"center",
"keep",
)
# Style the table
RangeStyleHeader = HeaderRange
RangeStyleTable = (
"A2:" + str(Standard_Functions.GetLetterFromNumber(len(Headers))) + str(Row)
)
self.FormatTableColors(
sheet=sheet,
HeaderRange=RangeStyleHeader,
TableRange=RangeStyleTable,
HeaderColorRGB=HeaderColorRGB,
FirstColorRGB=FirstColorRGB,
SecondColorRGB=SecondColorRGB,
)
# Define NoRows. This is needed for the next functions
NoRows = 0
# If a summary is requested, create a summary
if Summary is True:
# Define the counters
AssemblyCounter = 0
PartCounter = 0
TotalCounter = 0
# Go through the list. If it is an assembly, increase the AssemblyCounter by 1.
# If it is an Part, increase the PartCounter by 1. Always increase the TotalCounter.
for i in range(len(CopyMainList)):
rowList = CopyMainList[i]
isAssembly = False
AssemblyTypes = [
"A2plus",
"Assembly4",
"Assembly3",
"Internal",
"AppLink",
"AppPart",
"Assembly",
]
for j in range(len(AssemblyTypes)):
if rowList["Type"] == AssemblyTypes[j]:
isAssembly = True
if isAssembly is True:
AssemblyCounter = AssemblyCounter + 1
TotalCounter = TotalCounter + 1
if isAssembly is False:
PartCounter = PartCounter + 1
TotalCounter = TotalCounter + 1
# Define the row above which extra rows will be added.
RowNumber = "1"
# Set the number of rows to be added.
NoRows = 6
# Insert the rows and merge for each row the first three cells
for i in range(NoRows):
sheet.insertRows(RowNumber, 1)
sheet.mergeCells("A1:C1")
sheet.mergeCells("A1:D1")
# Fill in the cells
sheet.set("A1", translate("BoM Workbench", "Summary"))
sheet.set("A2", translate("BoM Workbench", "The total number of items:"))
sheet.set("A3", translate("BoM Workbench", "Number of unique parts:"))
sheet.set("A4", translate("BoM Workbench", "Number of unique assemblies:"))
sheet.set(
"A5", translate("BoM Workbench", "The total number of unique items:")
)
sheet.set("D2", str(TotalNoItems))
sheet.set("D3", str(PartCounter))
sheet.set("D4", str(AssemblyCounter))
sheet.set("D5", str(TotalCounter))
# Align the cells
sheet.setAlignment("A1:C5", "left", "keep")
sheet.setAlignment("D1:D5", "center", "keep")
# Style the table
RangeStyleHeader = "A1:D1"
RangeStyleTable = "A2:D5"
self.FormatTableColors(
sheet=sheet,
HeaderRange=RangeStyleHeader,
TableRange=RangeStyleTable,
HeaderColorRGB=HeaderColorRGB,
FirstColorRGB=FirstColorRGB,
SecondColorRGB=SecondColorRGB,
)
# Add the end of the BoM add indentifaction data
# Set the row to start from
Row = Row + NoRows + 2
# Merge cells for the next four rows
sheet.mergeCells(f"A{str(Row)}:D{str(Row)}")
sheet.mergeCells(f"A{str(Row+1)}:D{str(Row+1)}")
sheet.mergeCells(f"A{str(Row+2)}:D{str(Row+2)}")
sheet.mergeCells(f"A{str(Row+3)}:D{str(Row+3)}")
# Define the created by value. If no document information is available, use the OS account info.
CreatedBy = doc.LastModifiedBy
if CreatedBy == "":
try:
CreatedBy = getpass.getuser()
except Exception:
pass
# Fill in the cells with Date, time, created by and for which file.
sheet.set("A" + str(Row), translate("BoM Workbench", "File information"))
sheet.set(
"A" + str(Row + 1),
f"{translate('BoM Workbench', 'BoM created at')}: {datetime.today().strftime('%Y-%m-%d %H:%M:%S')}",
)
sheet.set(
"A" + str(Row + 2),
f"{translate('BoM Workbench', 'BoM created by')}: {CreatedBy}",
)
sheet.set(
"A" + str(Row + 3),
f"{translate('BoM Workbench', 'BoM created for file')}: ../{os.path.basename(doc.FileName)}",
)
# Align the cells
sheet.setAlignment(f"A{str(Row)}:C{str(Row + 3)}", "left", "keep")
# Style the table
RangeStyleHeader = f"A{str(Row)}:D{str(Row)}"
RangeStyleTable = f"A{str(Row+1)}:D{str(Row+3)}"
self.FormatTableColors(
sheet=sheet,
HeaderRange=RangeStyleHeader,
TableRange=RangeStyleTable,
HeaderColorRGB=HeaderColorRGB,
FirstColorRGB=FirstColorRGB,
SecondColorRGB=SecondColorRGB,
)
# Recompute the document
doc.recompute(None, True, True)
if IsNewSheet is False:
Standard_Functions.Mbox(
text="Bill of Materials is replaced with a new version!",
title="Bill of Materials",
style=0,
)
if IsNewSheet is True:
Standard_Functions.Mbox(
text="Bill of Materials is created!",
title="Bill of Materials",
style=0,
)
return
@classmethod
def FormatTableColors(
self,
sheet,
HeaderRange,
TableRange,
HeaderColorRGB,
FirstColorRGB,
SecondColorRGB,
ForeGroundHeaderRGB=[0, 0, 0],
ForeGroundTable=[0, 0, 0],
HeaderStyle="bold",
TableStyle="",
):
"""_summary_
Args:
sheet (object): FreeCAD sheet object
HeaderRange (string): Range for the header.
TableRange (string): Range for the table
HeaderColorRGB (List): RGB color for the header. (e.g. [255, 255, 255])
FirstColorRGB (list): RGB color for every 1st row. (e.g. [255, 255, 255])
SecondColorRGB (list): RGB color for every 2nd row. (e.g. [255, 255, 255])
ForeGroundHeaderRGB (list, optional): _description_. Defaults to [0, 0, 0].
ForeGroundTable (list, optional): _description_. Defaults to [0, 0, 0].
HeaderStyle (str, optional): Font style for the header. (bold|italic|underline) Defaults to "bold".
TableStyle (str, optional): Font style for the table. (bold|italic|underline) Defaults to "".
"""
# Format the header ------------------------------------------------------------------------------------------------
# Set the font style for the header
if HeaderStyle != "":
sheet.setStyle(HeaderRange, HeaderStyle) # \bold|italic|underline'
# Set the colors for the header
sheet.setBackground(
HeaderRange, Standard_Functions.ColorConvertor(HeaderColorRGB)
)
sheet.setForeground(
HeaderRange, Standard_Functions.ColorConvertor(ForeGroundHeaderRGB)
) # RGBA
# ------------------------------------------------------------------------------------------------------------------
# Format the table -------------------------------------------------------------------------------------------------
# Get the first column and first row
TableRangeColumnStart = Standard_Functions.RemoveNumbersFromString(
TableRange.split(":")[0]
)
TableRangeRowStart = int(
Standard_Functions.RemoveLettersFromString(TableRange.split(":")[0])
)
# Get the last column and last row
TableRangeColumnEnd = Standard_Functions.RemoveNumbersFromString(
TableRange.split(":")[1]
)
TableRangeRowEnd = int(
Standard_Functions.RemoveLettersFromString(TableRange.split(":")[1])
)
# Calculate the delta between the start and end of the table in vertical direction (Rows).
DeltaRange = TableRangeRowEnd - TableRangeRowStart + 1
# Go through the range
for i in range(1, DeltaRange + 2, 2):
# Correct the position
j = i - 1
# Define the first row
FirstRow = f"{TableRangeColumnStart}{str(j+TableRangeRowStart)}:{TableRangeColumnEnd}{str(j+TableRangeRowStart)}"
# Define the second row
SecondRow = f"{TableRangeColumnStart}{str(j+TableRangeRowStart+1)}:{TableRangeColumnEnd}{str(j+TableRangeRowStart+1)}"
# if the first and second rows are within the range, set the colors
if i <= DeltaRange:
sheet.setBackground(
FirstRow, Standard_Functions.ColorConvertor(FirstColorRGB)
)
sheet.setForeground(
FirstRow, Standard_Functions.ColorConvertor(ForeGroundTable)
)
if i + 1 <= DeltaRange:
sheet.setBackground(
SecondRow, Standard_Functions.ColorConvertor(SecondColorRGB)
)
sheet.setForeground(
SecondRow, Standard_Functions.ColorConvertor(ForeGroundTable)
)
# Set the font style for the table
if TableStyle != "":
sheet.setStyle(TableRange, TableStyle) # \bold|italic|underline'
# ------------------------------------------------------------------------------------------------------------------
return
# Functions to count document objects in a list based on the itemnumber of their parent.
@classmethod
def ObjectCounter_ItemNumber(
self,
ListItem,
ItemNumber: str,
BomList: list,
ObjectBasedPart: bool = True,
ObjectBasedAssy: bool = False,
) -> int:
"""_summary_
Args:
ListItem (dict): Item from main list.
ItemNumber (str): Item number of document object.
BomList (list): complete main list.
ObjectBasedPart (bool, optional): Compare objects (True) or object.labels (False) Defaults to True.
ObjectBasedAssy (bool, optional): Compare objects when they are an assembly.(ObjectBased must be False)) Defaults to False.
Returns:
int: number of document number in item number range.
"""
ObjectNameValuePart = "Object"
if ObjectBasedPart is False:
ObjectNameValuePart = "ObjectLabel"
ObjectNameValueAssy = "Object"
if ObjectBasedAssy is False:
ObjectNameValueAssy = "ObjectLabel"
# Set the counter
counter = 0
# Go Through the objectList
for i in range(len(BomList)):
# The parent number is the itemnumber without the last digit. if both ItemNumber and item in numberlist are the same, continue.
# If the itemnumber is more than one level deep:
if len(ItemNumber.split(".")) > 1:
if (
BomList[i]["ItemNumber"].rsplit(".", 1)[0]
== ItemNumber.rsplit(".", 1)[0]
):
if ListItem["Type"] == "Part":
if ObjectNameValuePart == "Object":
if (
BomList[i]["DocumentObject"]
== ListItem["DocumentObject"]
):
counter = counter + 1
if ObjectNameValuePart == "ObjectLabel":
if BomList[i]["ObjectLabel"] == ListItem["ObjectLabel"]:
counter = counter + 1
if ListItem["Type"] == "Assembly":
if ObjectNameValueAssy == "Object":
if (
BomList[i]["DocumentObject"]
== ListItem["DocumentObject"]
):
counter = counter + 1
if ObjectNameValueAssy == "ObjectLabel":
if BomList[i]["ObjectLabel"] == ListItem["ObjectLabel"]:
counter = counter + 1
# If the itemnumber is one level deep:
if (
len(ItemNumber.split(".")) == 1
and len(BomList[i]["ItemNumber"].split(".")) == 1
):
if ListItem["Type"] == "Part":
if ObjectNameValuePart == "Object":
if BomList[i]["DocumentObject"] == ListItem["DocumentObject"]:
counter = counter + 1
if ObjectNameValuePart == "ObjectLabel":
if BomList[i]["ObjectLabel"] == ListItem["ObjectLabel"]:
counter = counter + 1
if ListItem["Type"] == "Assembly":
if ObjectNameValueAssy == "Object":
if BomList[i]["DocumentObject"] == ListItem["DocumentObject"]:
counter = counter + 1
if ObjectNameValueAssy == "ObjectLabel":
if BomList[i]["ObjectLabel"] == ListItem["ObjectLabel"]:
counter = counter + 1
# Return the counter
return counter
@classmethod
def ListContainsCheck(self, List: list, Item1, Item2, Item3) -> bool:
for i in range(len(List)):
rowItem = List[i]
ListItem1 = rowItem["Item1"]
ListItem2 = rowItem["Item2"]
ListItem3 = rowItem["Item3"]
if ListItem1 == Item1 and ListItem2 == Item2 and ListItem3 == Item3:
return True
return False
# Functions to count document objects in a list. Can be object based or List row based comparison.
@classmethod
def ObjectCounter(
self,
DocObject=None,
RowItem: dict = None,
mainList: list = None,
ObjectNameBased: bool = True,
) -> int:
"""_summary_
Use this function only two ways:\n
1. Enter an DocumentObject (DocObject) and a BoM list with a tuples as items (mainList). RowItem must be None.
2. Enter an RowItem from a BoM List (RowItem), a BoM list with tuples as items (mainList) and set ObjectNameBased to True or False.\n
DocObject must be None.\n
Args:
DocObject (FreeCAD.DocumentObject, optional): DocumentObject to search for. Defaults to None.
RowItem (dict, optional): List item to search for. Defaults to None.
ItemList (list, optional): The item or Document object list. Defaults to None.
ObjectNameType (bool, optional): Set to true if the counter must be Name based or False if the counter must be Label based.
Returns:
int: _description_
"""
ObjectBased = False
ListRowBased = False
if DocObject is not None and RowItem is None:
ObjectBased = True
if DocObject is None and RowItem is not None:
ListRowBased = True
else:
return 0
ObjectNameValue = "ObjectName"
if ObjectNameBased is False:
ObjectNameValue = "ObjectLabel"
# Set the counter
counter = 0
# Go Through the mainList
# If ObjectBased is True, compare the objects
if ObjectBased is True:
for i in range(len(mainList)):
# If the document object in the list is equal to DocObject, increase the counter by one.
if mainList[i]["DocumentObject"] == DocObject:
counter = counter + 1
# If ListRowBased is True, compare the name and type of the objects. These are stored in the list items.
if ListRowBased is True:
for i in range(len(mainList)):
ObjectName = mainList[i][ObjectNameValue]
ObjectType = mainList[i]["DocumentObject"].TypeId
# If the object name and type of the object in the list are equal to that of the DocObject,
# increase the counter by one
if (
RowItem[ObjectNameValue] == ObjectName
and RowItem["DocumentObject"].TypeId == ObjectType
):
counter = counter + 1
# Return the counter
return counter
# Function to correct the items of the BoM after filtering has taken place.
@classmethod
def CorrectItemNumbers(self, BoMList: list, DebugMode: bool = False) -> list:
"""_summary_
Args:
BoMList (list): The list that needs correction.
DebugMode (bool, optional): If set to True, all itemnumber will be reported. Defaults to False.
Returns:
list: The corrected list.
"""
TemporaryList = []
# Go throug the list
for i in range(len(BoMList)):
TemporaryList.append(BoMList[i])
if i > 1:
# Get the list item from the new temporary list
rowItem = TemporaryList[i]
# Get the item and define the current itemnumber from the original list
rowItemOriginal = BoMList[i]
ItemNumberOriginal = str(rowItemOriginal["ItemNumber"])
# Get the previous item from the new temporary list and define the itemnumber
RowItemPrevious = TemporaryList[i - 1]
ItemNumberPrevious = str(RowItemPrevious["ItemNumber"])
# create a new empty itemnumber as a placeholder
NewItemNumber = ""
# Get the previous item from the original list and define the itemnumber
RowItemPreviousOriginal = BoMList[i - 1]
ItemNumberPreviousOriginal = str(RowItemPreviousOriginal["ItemNumber"])
# Create a new row item for the temporary row.
# The comparison is done with the items from the original list.
# This way you are certain the comparison is not done on a changing list.
# The term longer, shorter, equal means the times the splitter "." is present.
# ----------------------------------------------------------------------------------------------------------
#
# If the previous itemnumber is shorter than the current itemnumber,
# you have the first item in a subassembly.
# Add ".1" and you have the itemnumber for this first item. (e.g. 1.1 -> 1.1.1)
if len(ItemNumberPreviousOriginal.split(".")) < len(
ItemNumberOriginal.split(".")
):
# Define the new itemnumber.
NewItemNumber = str(ItemNumberPrevious) + ".1"
# If the previous itemnumber is as long as the current itemnumber,
# you have an item of a subassembly that is not the first item.
if len(ItemNumberPreviousOriginal.split(".")) == len(
ItemNumberOriginal.split(".")
):
# If the current item is a first level item, increase the number by 1.
if len(ItemNumberOriginal.split(".")) == 1:
NewItemNumber = str(int(ItemNumberPrevious) + 1)
# If the current item is a level deeper then one, split the itemnumber in two parts.
# The first part is the number without the last digit. This won't change.
# The second part is the last digit. Increase this by one.
# The new itemnumber is the combined string of part 1 and modified part 2.
if len(ItemNumberOriginal.split(".")) > 1:
Part1 = str(ItemNumberPrevious.rsplit(".", 1)[0])
Part2 = str(int(ItemNumberPrevious.rsplit(".", 1)[1]) + 1)
NewItemNumber = Part1 + "." + Part2
# If the previous itemnumber is longer than the current itemnumber, you have a new subassembly.
if len(ItemNumberPreviousOriginal.split(".")) > len(
ItemNumberOriginal.split(".")
):
# if the new subassembly is at the first level, split the previous itemnumber in two
# to get the first digit and increase this by one.
if len(ItemNumberOriginal.split(".")) == 1:
NewItemNumber = str(int(ItemNumberPrevious.split(".")[0]) + 1)
# If the current item is a level deeper then one, determine the length of the current item.
# Use this to create a new itemnumber from the previous itemnumber but based on the current number.
# Simply removing the last digit won't always work because it is not garuanteed that the new subassembly
# is just one level higher in the order. (e.g., you can go from 1.2.4.5 to the next assembly at 1.3)
if len(ItemNumberOriginal.split(".")) > 1:
# Get the length for the new itemnumber
Length = len(ItemNumberOriginal.split("."))
# Create a list of all the numbers from the previous itemnumber.
ItemNumberSplit = ItemNumberPrevious.split(".")
# Define a temporary itemnumber. Then add the next part from the list to it.
# Do this until the temporary itemnumber has correct length.
Part0 = str(ItemNumberSplit[0])
for j in range(1, len(ItemNumberSplit) - 1):
if j <= Length:
Part0 = Part0 + "." + str(ItemNumberSplit[j])
# Split the temporary itemnumber into two parts.
# The first part is the number without the last digit. This won't change.
# The second part is the last digit. Increase this by one.
# The new itemnumber is the combined string of part 1 and modified part 2.
Part1 = str(Part0.rsplit(".", 1)[0])
Part2 = str(int(Part0.rsplit(".", 1)[1]) + 1)
NewItemNumber = Part1 + "." + Part2
# ----------------------------------------------------------------------------------------------------------
# Define the new rowList item.
rowListNew = {
"ItemNumber": NewItemNumber,
"DocumentObject": rowItem["DocumentObject"],
"ObjectLabel": rowItem["ObjectLabel"],
"ObjectName": rowItem["ObjectName"],
"Qty": rowItem["Qty"],
"Type": rowItem["Type"],
}
# Replace the last item in the temporary list with this new one.
TemporaryList.pop()
TemporaryList.append(rowListNew)
# If in debug mode, print the resulting list of numbers
if DebugMode is True:
for i in range(len(TemporaryList)):
Standard_Functions.Print(TemporaryList[i]["ItemNumber"], "Log")
# Return the result.
return TemporaryList
# Function to check the type of workbench
@classmethod
def CheckAssemblyType(self, DocObject):
"""_summary_
Args:
DocObject (App.DocumentObject): The DocumentObject
Returns:
string: The assembly type as a string
"""
result = ""
# Get the list with rootobjects
RootObjects = DocObject.RootObjects
# Check if there are groups with items. create a list from it and add it to the docObjects.
for RootObject in RootObjects:
if RootObject.TypeId == "App::DocumentObjectGroup":
RootObjects.extend(General_BOM.GetObjectsFromGroups(RootObject))
# Define the result list.
resultList = []
# Go through the root objects. If there is an object type "a2pPart", this is an A2plus assembly.
# If not, continue.
# In the A2plus WB, you have to go through the Objects instead of the RootObjects
for Object in DocObject.Objects:
try:
if Object.objectType == "a2pPart":
return "A2plus"
except Exception:
pass
# In the other workbenches go through the RootObjects
for Object in RootObjects:
try:
if Object.AssemblyType == "Part::Link" and Object.Type == "Assembly":
resultList.append("Assembly4")
except Exception:
pass
try:
if Object.SolverType == "SolveSpace":
resultList.append("Assembly3")
except Exception:
pass
try:
if (
Object.Type == "Assembly"
and Object.TypeId == "Assembly::AssemblyObject"
):
resultList.append("Internal")
except Exception:
pass
try:
if Object.TypeId == "App::Link" or Object.TypeId == "App::LinkGroup":
resultList.append("AppLink")
except Exception:
pass
try:
if Object.Type == "" and Object.TypeId == "App::Part":
resultList.append("AppPart")
except Exception:
pass
# Check if the document is an arch or multibody document
try:
test = self.CheckMultiBodyType(DocObject)
if test != "":
resultList.append(test)
except Exception:
pass
check_AppPart = False
for result in resultList:
if result == "Assembly3":
return "Assembly3"
if result == "Assembly4":
return "Assembly4"
if result == "Internal":
return "Internal"
if result == "AppLink":
return "AppLink"
if result == "Arch":
return "Arch"
if result == "MultiBody":
return "MultiBody"
if result == "AppPart":
check_AppPart = True
if check_AppPart is True:
result = "AppPart"
return result
@classmethod
def CheckMultiBodyType(self, DocObject):
# Define the list with allowed types
ListObjecttypes = [
"Part::FeaturePython",
"Part::Feature",
"PartDesign::Body",
]
# Define the list with not allowed types. (aka all assembly types)
ListBlockedTypes = [
"App::Part",
"App::LinkGroup",
"App::Link",
"Part::Link",
]
# Define the result
result = ""
# Get the list with rootobjects
RootObjects = DocObject.RootObjects
# Check if there are groups with items. create a list from it and add it to the docObjects.
for RootObject in RootObjects:
if RootObject.TypeId == "App::DocumentObjectGroup":
RootObjects.extend(General_BOM.GetObjectsFromGroups(RootObject))
# define a boolan for the Arch item check
isArchItem = False
# Go through the rootobjects. If it is a blocked type, return.
for RootObject in RootObjects:
for type in ListBlockedTypes:
if type == RootObject.TypeId:
return
# not returned, go through the obects in rootobjects
for RootObject in RootObjects:
# go through the allowed types
for type in ListObjecttypes:
# If the type is allowed, check if the object has BIM properties.
# If so, it is an Arch document.
if type == RootObject.TypeId:
try:
PropertyList = RootObject.PropertiesList
for Property in PropertyList:
if Property == "IfcType":
isArchItem = True
if Property == "IfcData":
isArchItem = True
if Property == "IfcProperties":
isArchItem = True
except Exception:
pass
# set the result to the correct string.
if isArchItem is True:
result = "Arch"
if isArchItem is False:
result = "MultiBody"
return result
@classmethod
def GetObjectsFromGroups(self, Group):
resultList = []
try:
Objects = Group.Group
for Object in Objects:
if Object.TypeId != "App::DocumentObjectGroup":
resultList.append(Object)
if Object.TypeId == "App::DocumentObjectGroup":
resultList.extend(self.GetObjectsFromGroups(Object))
except Exception:
pass
return resultList
@classmethod
def ReturnDocProperty(self, DocObject, PropertyName) -> str:
result = ""
try:
if PropertyName == "FullName":
result = DocObject.Fullname
if PropertyName == "Label":
result = DocObject.Label
if PropertyName == "Label2":
result = DocObject.Label2
if PropertyName == "TypeId":
result = DocObject.TypeId
if PropertyName == "Name":
result = DocObject.Name
return result
except Exception:
return ""
@classmethod
def ReturnViewProperty(self, DocObject, PropertyName) -> list:
resultValue: object
resultUnit: str
result: list
# if there is a linked object, use that.
# Otherwise use the provided document.
try:
DocObject = DocObject.getLinkedObject()
except Exception:
pass
isShapeProperty = False
if PropertyName.startswith("Shape - ") is True:
isShapeProperty = True
if isShapeProperty is False:
try:
try:
resultValue = DocObject.getPropertyByName(PropertyName)
except Exception:
resultValue = None
if isinstance(resultValue, int):
resultValue = str(resultValue)
elif isinstance(resultValue, list):
resultString = ""
for item in resultValue:
resultString = resultString + self.ObjectToString(item) + ", "