-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathonly_cleanup_script.py
More file actions
1485 lines (1215 loc) · 67.5 KB
/
only_cleanup_script.py
File metadata and controls
1485 lines (1215 loc) · 67.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
#!/usr/bin/env python3
"""
step 1 - export dump file manually
step 2 - restore database mannually
step 3 - run odoo server with version same as db_version at any port
step 4 - run below command to run cleanup script with arguments
python3 only_cleanup_script.py --module_name="members_name" --category="category_name" --studio_path="/path/to/studio_customization" --destination_path="/home/odoo/Download" --db_name="restore_db_name" --port=port_number
"""
import os
import requests
import logging
import shutil
import argparse
import sys
from pathlib import Path
import re
from ast import literal_eval
from lxml import etree
# Setup logger
# Create a Logger instance directly
_logger = logging.Logger("logging")
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
_logger.addHandler(handler)
BASE_URL = "http://localhost:"
LOGIN = "admin"
PASSWORD = "admin"
# ====================================================
# CleanUp logic
# ====================================================
class CleanModule:
def __init__(self, ind_name, ind_category, db_name, module_path, destination_base_path, port):
self.ind_name = ind_name
self.ind_category = ind_category
self.db_name = db_name
self.module_path = module_path
self.port = port
self.destination_base_path = destination_base_path
self.automated = {
'author': 'Odoo S.A.',
'category': '',
'images': ['images/main.png'],
'license': 'OPL-1',
'version': '1.0',
}
self.mandatory_files = {
"/static/src/js/my_tour.js": """import {{ _t }} from "@web/core/l10n/translation";
import {{ registry }} from "@web/core/registry";
registry.category("web_tour.tours").add("{ind_name}_knowledge_tour", {{
url: "/odoo",
steps: () => [
{{
trigger: '.o_app[data-menu-xmlid="knowledge.knowledge_menu_root"]',
content: _t("Get on track and explore our recommendations for your Odoo usage here!"),
run: "click",
}},
],
}});
""",
"/data/mail_message.xml": """<?xml version='1.0' encoding='UTF-8'?>
<odoo noupdate="1">
<record model="mail.message" id="notification_knowledge">
<field name="model">discuss.channel</field>
<field name="res_id" ref="mail.channel_all_employees"/>
<field name="message_type">email</field>
<field name="author_id" ref="base.partner_root"/>
<field name="subtype_id" ref="mail.mt_comment"/>
<field name="subject">🚀 Get started with Odoo {Ind_name} Shop</field>
<field name="body" model="knowledge.article" eval="
'<span>👋 Hi! Follow this <a href=\\''
+ obj().env.ref('{ind_name}.welcome_article').article_url
+ '\\'>onboarding guide</a>. You can find it anytime in the Knowledge app.</span>'"/>
</record>
</odoo>
""",
"/data/knowledge_article_favorite.xml": """<?xml version='1.0' encoding='UTF-8'?>
<odoo noupdate="1">
<record id="knowledge_favorite" model="knowledge.article.favorite">
<field name="article_id" ref="welcome_article"/>
<field name="user_id" ref="base.user_admin"/>
</record>
</odoo>
""",
"/data/knowledge_tour.xml": """<?xml version="1.0" encoding="UTF-8"?>
<odoo noupdate="1">
<record id="knowledge_tour" model="web_tour.tour">
<field name="name">{ind_name}_knowledge_tour</field>
<field name="sequence">2</field>
<field name="rainbow_man_message">Welcome! Happy exploring.</field>
</record>
</odoo>
""",
}
def get_dependency_chains(self, directory):
warning_txt_path = Path(directory + '/warnings.txt')
if warning_txt_path.exists():
with open(warning_txt_path, 'r', encoding='utf-8') as f:
content = f.read()
count_match = re.search(r"Found (\d+) circular dependencies", content)
if not count_match:
return []
# Capture lines starting with either (data) or (demo)
chains = re.findall(r"\((data|demo)\) (.+)", content)
result = [{"type": dir, "chain": chain.split(" -> ")} for dir, chain in chains]
return result
def process_dependencies(self, directory, dependency_chains, dependencies_collection):
"""
Processes dependency chains to detect and eliminate circular dependencies in XML data files.
Steps:
1. Iterates through each dependency chain and constructs XML file paths.
2. Parses XML files in reverse order to track previously loaded records.
3. Identifies fields using 'ref' or 'eval' attributes that reference earlier records.
4. Removes problematic fields from XML structure and stores metadata for reporting.
5. Updates the XML files after modification and accumulates dependency info.
Args:
directory (str): Path to the base directory containing XML files.
dependency_chains (list): List of dependency chain dictionaries with file references.
dependencies_collection (list): Collection to accumulate field metadata causing circular dependencies.
Returns:
list: Updated collection of dependency metadata entries for circular references.
"""
for depend in dependency_chains:
dependency_info = {}
dir = depend.get('type')
files =[file.replace('.', '_') + '.xml' for file in depend.get('chain')]
old_record_ids = []
for file in reversed(files):
file_path = Path(directory + '/' + dir + '/' + file)
if file_path.exists():
etree_file_content = self.get_etree_content(file_path)
records = etree_file_content.xpath("//record")
record_ids = [record.get("id") for record in records]
for record in records:
record_id = record.get('id')
model = record.get('model')
for field in record.xpath(".//field"):
dependency_info = {
'dir': dir,
'id': record_id,
'model': model,
'ref': None,
'eval': None,
'field_name': None
}
removed = False
ref = field.get("ref")
eval_attr = field.get("eval")
if ref and ref in old_record_ids:
dependency_info['field_name'] = field.get("name")
dependency_info['ref'] = field.get("ref")
record.remove(field)
removed = True
elif eval_attr:
refs_found = re.findall(r"ref\(['\"]([\w\.]+)['\"]\)", eval_attr)
if any(ref in old_record_ids for ref in refs_found):
dependency_info['field_name'] = field.get("name")
dependency_info['eval'] = field.get("eval")
record.remove(field)
removed = True
if removed:
dependencies_collection.append(dependency_info)
self.write_etree_content(file_path, etree_file_content)
old_record_ids = record_ids
return dependencies_collection
def map_dependencies_files(self, destination_module_path, dependencies_collection):
"""
Generates XML files that map fields causing circular dependencies for both 'data' and 'demo' directories.
Steps:
1. Iterates through the dependencies collection, grouping records by their directory type ('data' or 'demo').
2. Constructs XML <record> entries with appropriate <field> elements reflecting 'eval' or 'ref' attributes.
3. Writes two separate XML files:
- map_circular_dependencies.xml in the 'data' folder if applicable.
- map_circular_dependencies.xml in the 'demo' folder if applicable.
4. Returns flags indicating the presence of mapped circular dependency entries in each directory.
Args:
destination_module_path (str): Base path of the module directory where XML files will be written.
dependencies_collection (list): List of dictionaries representing fields involved in circular dependencies.
Returns:
tuple: Two booleans indicating whether data and demo mapping files were created (data_file_flag, demo_file_flag).
"""
demo_file = ""
data_file = ""
for depend_list in dependencies_collection:
if depend_list['dir'] == 'data':
field_xml = ""
if depend_list.get('eval'):
field_xml += f"""<field name="{depend_list['field_name']}" eval="{depend_list['eval']}"/>"""
elif depend_list.get('ref'):
field_xml += f"""<field name="{depend_list['field_name']}" ref="{depend_list['ref']}"/>"""
else:
field_xml += f"""<field name="{depend_list['field_name']}"/>"""
data_file += f"""
<record id="{depend_list['id']}" model="{depend_list['model']}">
{field_xml}
</record>
"""
elif depend_list['dir'] == 'demo':
field_xml = ""
if depend_list.get('eval'):
field_xml += f"""<field name="{depend_list['field_name']}" eval="{depend_list['eval']}"/>"""
elif depend_list.get('ref'):
field_xml += f"""<field name="{depend_list['field_name']}" ref="{depend_list['ref']}"/>"""
else:
field_xml += f"""<field name="{depend_list['field_name']}"/>"""
demo_file += f"""
<record id="{depend_list['id']}" model="{depend_list['model']}">
{field_xml}
</record>
"""
if data_file:
content = f"""<?xml version='1.0' encoding='UTF-8'?>
<odoo>
{data_file}
</odoo>
"""
with open(destination_module_path + "/data/record_creation_post.xml", 'w') as f:
f.write(content)
if demo_file:
content = f"""<?xml version='1.0' encoding='UTF-8'?>
<odoo>
{demo_file}
</odoo>
"""
with open(destination_module_path + "/demo/record_creation_post.xml", 'w') as f:
f.write(content)
return bool(data_file), bool(demo_file)
def clean(self):
# Format the industry name and category by replacing underscores/hyphens with spaces and capitalizing
Ind_name = re.sub(r'[_-]', ' ', self.ind_name).title()
Ind_category = re.sub(r'[_-]', ' ', self.ind_category).title()
self.automated['category'] = Ind_category
os.system(f"psql {self.db_name} -c \"UPDATE res_users SET login='{LOGIN}', password='{PASSWORD}' WHERE id=2;\"")
# Construct the destination path for the cleaned module
destination_module_path = self.destination_base_path + '/' + self.ind_name
directory = self.module_path
# Fetch field metadata of fields
fields_info_dict = {}
scss_content_list = []
manifest_demo_file_list = []
# Getting circular dependency chain from warnings.txt file
dependency_chains = []
dependency_chains = self.get_dependency_chains(directory)
# store old_id --> new_id (for thode records whose ids are generated in rendom hexadecimal)
old_to_new_id_map = self.prepare_old_to_new_id_map()
# get default pricelist id for remove ref
default_pricelist_id = self.get_default_pricelist_id(self.module_path)
# Traverse the module directory recursively
for root, dirs, files in os.walk(directory):
current_dir = root.split(directory)[1] + '/'
# Recreate directory structure at the destination
for d in dirs:
os.makedirs(destination_module_path + current_dir + d, exist_ok=True)
for file_name in files:
ext = file_name.rsplit('.')[1] if '.' in file_name else ''
# Process XML files
if ext == 'xml':
content = Path(root + '/' + file_name).read_text(encoding="utf-8")
# replace old_id to new_id in xml file
content = self.replace_old_id_to_new_id(content, old_to_new_id_map)
# remove field with default pricelist reference
content = self.remove_default_pricelist_ref(default_pricelist_id, content)
# Apply module-specific modifications to XML content
content = self.edit_xml_content(content)
# Remove predefined unwanted fields from the XML
unwanted_fields = ['color', 'inherited_permission', 'access_token', 'document_token', 'peppol_verification_state', 'uuid']
content = self.remove_unwanted_fields(content, unwanted_fields)
# Remove sequence field and add auto_sequence = "1" in <odoo>
content = self.process_sequence_field(content)
xml_root = etree.fromstring(content.encode("utf-8"))
# Collect reference names from the XML records
ref_name_list = list(set([
field.get('ref')
for record in xml_root.xpath("//record")
for field in record
if field.get('ref') and '.' not in field.get('ref')
]))
# Store metadata of demo files without records for later use
if current_dir.endswith('/demo/') and not xml_root.xpath("//record"):
manifest_demo_file_dict = {
'file_name': file_name,
'ref_name': ref_name_list
}
manifest_demo_file_list.append(manifest_demo_file_dict)
for record in xml_root.xpath("//record"):
# Store metadata of demo files with records for later use
self.unorder_manifest_demo_files(manifest_demo_file_list, current_dir, file_name, ref_name_list, record)
model_name = record.get('model')
if not model_name:
continue
# Remove fields based on model-specific rules
content = self.remove_model_based_fields(model_name, content)
# Clean computed fields without inverse methods
content = self.remove_computed_fields(fields_info_dict, model_name, record, content)
# Special case handling for certain XML files
if file_name == 'ir_default.xml':
content = re.sub(r"<odoo>", '<odoo noupdate="1">', content)
# Write the processed XML content to the destination
Path(destination_module_path + current_dir + file_name).write_text(content, encoding='utf-8')
# Handle manifest file separately
elif ext in ['py', 'txt']:
if file_name != '__manifest__.py':
continue
manifest = literal_eval(Path(root + '/' + file_name).read_text(encoding="utf-8"))
with open(destination_module_path + '/__manifest__.py', 'w', encoding="utf-8") as f:
f.write('{\n')
for k, v in manifest.items():
if k == 'name':
f.write(f" '{k}': '{Ind_name}',\n")
elif k == 'description':
continue
elif k not in self.automated:
if isinstance(v, list):
f.write(f" '{k}': [\n")
for item in v:
# Skip unwanted dependencies
unwanted_depends = [
'base_module',
'__import__',
'account_invoice_extract',
'account_online_synchronization',
'account_peppol',
'auth_totp_mail',
'base_install_request',
'crm_iap_enrich',
'crm_iap_mine',
'partner_autocomplete',
'pos_epson_printer',
'sale_async_emails',
'snailmail_account',
'web_grid',
'web_studio',
'social_push_notifications',
'appointment_sms',
'website_knowledge',
'base_vat',
'product_barcodelookup',
'snailmail_account_followup',
'base_geolocalize',
'gamification',
'l10n_be_pos_sale',
'pos_sms',
'pos_settle_due',
'website_partner',
'website_project',
'project_sms',
]
if k == 'depends' and (item in unwanted_depends or item.startswith('theme_')):
continue
f.write(f" '{item}',\n")
if k == 'data':
f.write(" 'data/mail_message.xml',\n")
f.write(" 'data/knowledge_article_favorite.xml',\n")
f.write(" 'data/knowledge_tour.xml',\n")
f.write(" ],\n")
else:
f.write(f" '{k}': '{v}',\n")
else:
f.write(f" '{k}': '{self.automated[k]}',\n")
f.write('}\n')
# Copy other files without an extension or as specific assets
elif not ext or (current_dir.endswith('/ir_attachment/') and ext != "scss"):
shutil.copy(root + '/' + file_name, destination_module_path + current_dir + file_name)
# Extract relevant SCSS customization data
elif current_dir.endswith('/ir_attachment/') and ext == "scss":
self.get_relevant_scss_data(scss_content_list, root, file_name)
# Generate SCSS function from collected theme data
self.write_scss_function(destination_module_path, scss_content_list)
# Remove fields explicitly marked with ondelete=False
self.remove_ondelete_false_field(destination_module_path)
# Clean up specific non-user created records
remove_file_names = ['ir_attachment_pre.xml', 'knowledge_cover.xml', 'mail_template.xml']
for remove_file_name in remove_file_names:
self.remove_record_not_created_by_user(destination_module_path, remove_file_name)
# Clean up default pricelists from data files
self.remove_default_pricelist(destination_module_path)
# Organize records in a standard format
self.remove_unused_ir_attachment_post(destination_module_path)
self.order_ir_attachment_post(destination_module_path)
# Retain only welcome article in the knowledge article
self.clean_knowledge_article(destination_module_path)
# Add demo payment provider if relevant module is present
self.add_demo_payment_provider(destination_module_path, manifest_demo_file_list)
# Add immediate install function for the theme module in demo XML files
self.add_theme_immediate_install_function(destination_module_path)
self.clean_sale_order_line_record(destination_module_path)
# Update manifest file
self.arrange_manifest_files(destination_module_path, manifest_demo_file_list, dependency_chains)
# Write mandatory files such as templates or init scripts
for file, content in self.mandatory_files.items():
directory, _ = os.path.split(file)
os.makedirs(destination_module_path + directory, exist_ok=True)
Path(destination_module_path + file).write_text(content.format(ind_name=self.ind_name, Ind_name=Ind_name), encoding='UTF-8')
print("clean up successful")
def get_etree_content(self, file_path):
try:
# Read the xml file and parse the XML string into an ElementTree object
content = file_path.read_text(encoding='utf-8')
etree_content = etree.fromstring(content.encode("utf-8"))
return etree_content
except Exception as e:
raise Exception(f"Error while getting etree content of file ({file_path}): {e}")
def write_etree_content(self, file_path, etree_content):
try:
# Convert the ElementTree content to a pretty-printed XML string
content = etree.tostring(
etree_content,
pretty_print = True,
encoding="UTF-8",
xml_declaration = True
).decode("utf-8")
file_path.write_text(content, encoding="utf-8")
except Exception as e:
raise Exception(f"Error while writing etree content to file ({file_path}): {e}")
def session_authentication(self):
session = requests.Session()
# Authenticates the user via Odoo's /web/session/authenticate endpoint and returns a session with an active login and the user ID.
auth_payload = {
"jsonrpc": "2.0",
"method": "call",
"params": {
"db": self.db_name,
"login": LOGIN,
"password": PASSWORD,
},
"id": 1
}
response = session.post(f"{BASE_URL}{self.port}/web/session/authenticate", json=auth_payload)
response.raise_for_status()
result = response.json().get("result")
if not result or not result.get("uid"):
raise Exception("Login failed in cleanup script.")
return session, result['uid']
def get_fields_info(self, model_name):
session, uid = self.session_authentication()
# Retrieves metadata (model, name, store, readonly, depends) for all fields from the Odoo model using JSON-RPC.
payload = {
"jsonrpc": "2.0",
"method": "call",
"params": {
"service": "object",
"method": "execute_kw",
"args": [
self.db_name,
uid,
PASSWORD,
model_name, # the model whose fields you're querying
"fields_get",
[], # optional list of fields (empty means all)
{
"attributes": ["model", "name", "store", "readonly", "depends"]
}
]
},
"id": 1
}
resp = session.post(f"{BASE_URL}{self.port}/jsonrpc", json=payload)
resp.raise_for_status()
if not resp.json()["result"]:
raise Exception("Error in getting model and field name")
return resp.json()["result"]
def edit_xml_content(self, content):
# Replace references to the "studio_customization" module with the new industry module name
env_ref = re.compile("(env\.ref\('studio_customization\.)(.*)'")
content = env_ref.sub(lambda m: f"env.ref('{self.ind_name}.{m.group(2)}'", content)
# Normalize custom field names by replacing "x_studio_" with "x_"
x_studio = re.compile("x_studio_")
content = x_studio.sub('x_', content)
# Remove studio-specific context attribute
context_studio = re.compile(" context=\"{'studio': True}\"")
content = context_studio.sub('', content)
# Remove the "studio_customization." prefix from field values or references
studio_mod = re.compile("studio_customization\.")
content = studio_mod.sub('', content)
# Replace directory references from "studio_customization/" to the new module directory
studio_link = re.compile("studio_customization/")
content = studio_link.sub(self.ind_name + '/', content)
# Remove forcecreate="1" attribute from <record> tags where the id starts with "base_module."
pattern_base_module_forcecreate = re.compile(r'(<record\s+[^>]*id="base_module\.[^"]*"[^>]*?")\s+forcecreate="1"')
content = pattern_base_module_forcecreate.sub(r"\1", content)
# Remove "base_module." prefix from record IDs or references
pattern_base_module = re.compile(r"base_module.")
content = pattern_base_module.sub("", content)
# Normalize user references by replacing "res_users_*" with "base.user_admin"
pattern_res_users = re.compile("res_users_\w+")
content = pattern_res_users.sub("base.user_admin", content)
# Add the industry module prefix to ir_ui_view references in Python-style expressions
pattern_ir_ui_view = re.compile(r"obj\(\)\.env\.ref\(\'ir_ui_view_")
content = pattern_ir_ui_view.sub(f"obj().env.ref('{self.ind_name}.ir_ui_view_", content)
# Replace default homepage key with a namespaced one under the new module
pattern_ir_ui_view_key = re.compile(r'(<field name="key">)website.homepage(</field>)')
content = pattern_ir_ui_view_key.sub(rf'\1{self.ind_name}.homepage\2', content)
# Update subdomain links to match the industry subdomain (replace underscores with hyphens)
pattern_href_url = re.compile(r'https://(?!www\.)([^/]+)\.odoo\.com')
content = pattern_href_url.sub(f'https://{self.ind_name.replace("_", "-")}.odoo.com', content)
# Remove full URLs in <field name="url"> when a hardcoded domain is present
pattern_url = re.compile(r'(<field name="url">)https://[^/]+(.*?</field>)')
content = pattern_url.sub(r'\1\2', content)
# Remove any field referencing UOM (unit of measure) records to avoid data coupling
pattern_product_uom_unit = re.compile(r'\s*<field[^>]*ref="uom.[^"]*"[^>]*\s*/>')
content = pattern_product_uom_unit.sub('', content)
# Replace any version segment in a '/documentation/{version}/' URL with '/documentation/latest/'
pattern_documention_version_link= re.compile(r'(/documentation/)[^/]+')
content = pattern_documention_version_link.sub(r'\1latest', content)
# Obfuscate all odoo.com emails by replacing with ****@example.com
pattern_email = re.compile(r'([a-zA-Z0-9._%+-]+)@odoo\.com')
content = pattern_email.sub(lambda m: f'{"*" * len(m.group(1))}@example.com', content)
return content
def remove_unwanted_fields(self, content, unwanted_fields):
"""
Removes XML field elements (both standard and self-closing) based on a list of unwanted field names.
Args:
content (str): The XML content as a string.
unwanted_fields (list): A list of field names to remove from the XML.
Returns:
str: The cleaned XML content with unwanted fields removed.
"""
for unwanted_field in unwanted_fields:
pattern_regular = rf'\s*<field name="{unwanted_field}">.*?</field>'
pattern_self_closing = rf'\s*<field name="{unwanted_field}"[^>]*\s*/>'
content = re.sub(pattern_regular, "", content, flags=re.DOTALL)
content = re.sub(pattern_self_closing, "", content)
return content
def process_sequence_field(self, content):
"""
Process XML content to detect numeric 'sequence' fields and conditionally modify the root tag.
Parses the given XML content to check for any <field name="sequence"> elements
with numeric text values. If found, it adds the attribute `auto_sequence="1"` to
the root <odoo> element. Also removes all 'sequence' fields from the content using
`remove_unwanted_fields`.
Args:
content (str): XML content as a UTF-8 encoded string.
Returns:
str: Modified XML content with 'sequence' fields removed and possibly
updated root <odoo> tag with `auto_sequence="1"`.
"""
etree_content = etree.fromstring(content.encode('utf-8'))
found_numeric_sequence = False
for record in etree_content.xpath("//record"):
for field in record.xpath(".//field[@name='sequence']"):
# Check if the field has a numeric value (not eval="False")
if field.text and field.text.strip().isdigit():
found_numeric_sequence = True
content = self.remove_unwanted_fields(content, ['sequence'])
# Add auto_sequence="1" if any numeric sequence was found
if found_numeric_sequence:
content = re.sub(r'<odoo', '<odoo auto_sequence="1"', content)
return content
def unorder_manifest_demo_files(self, manifest_demo_file_list, current_dir, file_name, ref_name_list, record):
"""
Inserts a demo file entry into the manifest_demo_file_list in an ordered manner.
Logic:
- If the record's ID appears in any ref_name of an existing entry, insert before that entry.
- If ref_name_list is empty, insert the entry at the beginning of the list.
- Otherwise, append the entry at the end.
Args:
manifest_demo_file_list (list): The current list of demo file metadata dictionaries.
current_dir (str): The current directory being processed (used to check if in '/demo/').
file_name (str): The name of the XML file being processed.
ref_name_list (list): A list of references extracted from the file.
record (etree.Element): The current <record> element from the XML.
"""
# Only process files within the 'demo' directory
if current_dir.endswith('/demo/'):
# Prepare a dictionary for the current demo file and its references
manifest_demo_file_dict = {
'file_name': file_name,
'ref_name': ref_name_list
}
# Get the ID of the current record
file_record_id = record.get('id')
if manifest_demo_file_dict['ref_name']:
inserted = False
# Try to insert before any existing file that references this record ID
for idx, existing in enumerate(manifest_demo_file_list):
if file_record_id in existing['ref_name']:
manifest_demo_file_list.insert(idx, manifest_demo_file_dict)
inserted = True
break
# If not inserted in loop, append to the end
if not inserted:
manifest_demo_file_list.append(manifest_demo_file_dict)
# If no references, insert at the beginning
else:
manifest_demo_file_list.insert(0, manifest_demo_file_dict)
return
def remove_model_based_fields(self, model_name, content):
"""
Removes specific XML fields from the content based on the model name.
Args:
model_name (str): The technical name of the model (e.g., 'sale.order').
content (str): The XML content as a string.
Returns:
str: The XML content with model-specific unwanted fields removed.
"""
# Define a dictionary mapping models to their corresponding unwanted field names
model_field_map = {
'calendar.event': ['start', 'stop'],
'crm.lead': ['email_from', 'company_id', 'country_id', 'city', 'street', 'partner_name', 'contact_name', 'zip', 'reveal_id', 'medium_id', 'date_closed', 'email_state', 'date_open', 'email_domain_criterion', 'iap_enrich_done', 'won_status', 'street2', 'phone', 'state_id'],
'event.event': ['kanban_state_label'],
'hr.department': ['complete_name', 'master_department_id'],
'pos.config': ['last_data_change'],
'pos.order': ['date_order', 'state', 'last_order_preparation_change', 'pos_reference', 'ticket_code', 'email', 'company_id'],
'pos.order.line': ['full_product_name', 'qty_delivered', 'price_unit', 'total_cost'],
'pos.payment.method': ['is_cash_count'],
'pos.session': ['name', 'start_at', 'stop_at', 'state'],
'product.pricelist.item': ['date_start', 'date_end'],
'product.template': ['base_unit_count'],
'purchase.order': ['date_order', 'date_approve', 'state', 'date_planned'],
'purchase.order.line': ['date_planned', 'name'],
'res.partner': ['supplier_rank', 'partner_gid', 'partner_weight'],
'sale.order': ['date_order', 'prepayment_percent', 'delivery_status', 'amount_unpaid', 'warehouse_id', 'origin'],
'sale.order.line': ['technical_price_unit', 'warehouse_id'],
'sale.order.template': ['prepayment_percent'],
'sign.item': ['transaction_id'],
}
# Retrieve the list of unwanted fields for the given model
unwanted_fields = model_field_map.get(model_name, [])
# Remove those fields using the previously defined helper
content = self.remove_unwanted_fields(content, unwanted_fields)
return content
def remove_computed_fields(self, fields_info_dict, model_name, record, content):
# Retrieve and cache the fields information for the current model if not already done; otherwise, use the cached info
if model_name not in fields_info_dict:
field_info = self.get_fields_info(model_name)
fields_info_dict[model_name] = field_info
else:
field_info = fields_info_dict[model_name]
# Extract all field names defined in the given XML <record> tag
fields_set_in_record = {
field.get('name') for field in record.xpath('.//field')
}
# Iterate through each field name in the record
for field_name in fields_set_in_record:
field_obj = None
field_obj = field_info.get(field_name)
# Remove the field from the XML content if it's computed (not stored) and readonly
if field_obj and (field_obj["depends"] and field_obj["readonly"] and not field_obj['store']):
# Match standard field tags (e.g., <field name="foo">bar</field>)
pattern_standard = re.compile(
rf'\s*<field name="{field_name}">.*?</field>',
re.DOTALL
)
# Match self-closing field tags (e.g., <field name="foo" />)
pattern_self_closing = re.compile(
rf'\s*<field name="{field_name}"[^>]*\s*/>'
)
# Remove matched fields from the content
content = pattern_standard.sub('', content)
content = pattern_self_closing.sub('', content)
return content
def get_relevant_scss_data(self, scss_content_list, root, file_name):
"""
Parses the given SCSS file to extract relevant customization data.
This function reads the content of a specified SCSS file and searches for
a customization block defined by the 'o-map-omit((...))' pattern. If found,
it extracts the inner content and appends a dictionary containing the content
and a corresponding URL to the provided list.
Parameters:
scss_content_list (list): A list to which the extracted SCSS data dictionaries will be appended.
root (str): The root directory path where the SCSS file is located.
file_name (str): The name of the SCSS file to be processed.
Returns:
None
"""
scss_content_dict = {}
scss_content = Path(root + '/' + file_name).read_text(encoding="utf-8")
# Extract SCSS variable customization block
scss_pattern = re.compile(r'o-map-omit\(\(\s*(.*?)\s*\)\)', re.DOTALL)
scss_match = scss_pattern.search(scss_content)
if scss_match:
inner_scss_content = scss_match.group(1) # Extract inner contents
scss_content_dict['inner_scss_content'] = inner_scss_content
if 'color' in file_name:
scss_content_dict['url'] = "/website/static/src/scss/options/colors/" + file_name
else:
scss_content_dict['url'] = "/website/static/src/scss/options/" + file_name
scss_content_list.append(scss_content_dict)
return
def write_scss_function(self, destination_module_path, scss_content_list):
"""
Generates and writes SCSS customization functions into the website_theme_apply.xml file.
For each SCSS customization, this function generates a <function> block, embedding the SCSS
content and target URL. It appends these blocks to the existing XML file or creates
a new one if it does not exist.
Args:
destination_module_path (str): Path to the module directory.
scss_content_list (list): A list of dictionaries with keys 'url' and 'inner_scss_content'.
"""
if scss_content_list:
target_path = Path(destination_module_path + '/demo/' + 'website_theme_apply.xml')
target_path.parent.mkdir(parents=True, exist_ok=True)
# Build new <function> entries for each SCSS customization
new_function = ""
for item in scss_content_list:
new_function += f"""
<function model="web_editor.assets" name="make_scss_customization">
<value eval="{item['url']}" />
<value eval="{{'
{item['inner_scss_content']}'
}}" />
</function>
"""
# Base structure if file does not exist
base_xml = f"""<?xml version='1.0' encoding='UTF-8'?>
<odoo>{new_function}
</odoo>
"""
# Update existing file or create new one
if target_path.exists():
content = target_path.read_text(encoding='utf-8')
if "</odoo>" in content:
updated_content = content.replace("</odoo>", f"{new_function}\n</odoo>")
else:
updated_content = content + "\n" + new_function + "\n</odoo>"
else:
updated_content = base_xml
try:
target_path.write_text(updated_content, encoding='utf-8')
except Exception as e:
raise Exception(f"Unable to write website_theme_apply.xml file: {e}")
return
def remove_ondelete_false_field(self, destination_module_path):
"""
From ir_model_fields.xml, remove <field name="on_delete" eval="False"/>
if field type (ttype) is NOT 'many2one' or 'one2many'.
Also wrap the 'compute' field text in CDATA.
"""
path_ir_model_fields = Path(destination_module_path + '/data/' + 'ir_model_fields.xml')
if path_ir_model_fields.exists():
root_ir_model_field = self.get_etree_content(path_ir_model_fields)
records = root_ir_model_field.xpath("//record")
for record in records:
field_type_elem = record.xpath(".//field[@name='ttype']")
if not field_type_elem:
continue
field_type = field_type_elem[0].text.strip()
# Remove on_delete fields if ttype is not many2one or one2many and on_delete eval is False
if field_type not in ['many2one', 'one2many']:
for field in record.xpath(".//field[@name='on_delete']"):
if field.get('eval') == 'False':
record.remove(field)
# Wrap compute field text in CDATA if exists
for field in record.xpath(".//field[@name='compute']"):
original_text = field.text
if original_text:
field.text = etree.CDATA(original_text)
self.write_etree_content(path_ir_model_fields, root_ir_model_field)
return
def remove_record_not_created_by_user(self, destination_module_path, file_name):
"""
Remove XML records from the given file if their ID contains a dot ('.'),
which indicates they are not user-created records.
Args:
destination_module_path (str or Path): The base path to the module directory.
file_name (str): The XML data file name to process.
Returns:
None
"""
path_file = Path(destination_module_path + '/data/' + file_name)
if path_file.exists():
root_file = self.get_etree_content(path_file)
records = root_file.xpath("//record")
for record in records:
record_id = record.get('id')
if '.' in record_id:
root_file.remove(record)
self.write_etree_content(path_file, root_file)
return
def remove_default_pricelist(self, destination_module_path):
"""
Remove records from product_pricelist.xml where the 'name' field is 'Default' or 'default'.
Args:
destination_module_path (str or Path): The path to the module directory.
Returns:
None
"""
path_product_pricelist = Path(destination_module_path + '/data/' + 'product_pricelist.xml')
if path_product_pricelist.exists():
root_product_pricelist = self.get_etree_content(path_product_pricelist)
records = root_product_pricelist.xpath("//record")
default_id = None
for record in records:
name_key = record.xpath(".//field[@name='name']")
if name_key and (name_key[0].text == 'Default' or name_key[0].text == 'default'):
default_id = record.get('id')
root_product_pricelist.remove(record)
self.write_etree_content(path_product_pricelist, root_product_pricelist)
return default_id
def get_default_pricelist_id(self, extrsct_module_path):
path_product_pricelist = Path(extrsct_module_path + '/data/' + 'product_pricelist.xml')
if path_product_pricelist.exists():
root_product_pricelist = self.get_etree_content(path_product_pricelist)
records = root_product_pricelist.xpath("//record")
for record in records:
name_key = record.xpath(".//field[@name='name']")
if name_key and (name_key[0].text == 'Default' or name_key[0].text == 'default'):
return record.get('id')
def remove_unused_ir_attachment_post(self, destination_module_path):
"""
Remove unused <record> elements from 'ir_attachment_post.xml' whose 'key' or 'name' fields
are not referenced in 'ir_ui_view.xml'. Also deletes corresponding files from disk.
Args:
destination_module_path (str): Module directory path.
"""
path_ir_attachment_post = Path(destination_module_path + '/demo/' + 'ir_attachment_post.xml')
path_ir_ui_view = Path(destination_module_path + '/demo/' + 'ir_ui_view.xml')
# Only proceed if both files exist
if path_ir_attachment_post.exists() and path_ir_ui_view.exists():
root_ir_attachment_post = self.get_etree_content(path_ir_attachment_post)
content_ir_ui_view = path_ir_ui_view.read_text(encoding="utf-8")
records = root_ir_attachment_post.xpath("//record")
unused_ir_attachment_post_ids = []
unused_files = []
for record in records:
key_field = record.xpath(".//field[@name='key']")
name_field = record.xpath(".//field[@name='name']")
datas_field = record.xpath(".//field[@name='datas']")
url_field = record.xpath(".//field[@name='url']")
res_model = record.xpath(".//field[@name='res_model']")
website_id = record.xpath(".//field[@name='website_id']")
if res_model: