-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathchange_request.py
More file actions
1654 lines (1438 loc) · 70.6 KB
/
change_request.py
File metadata and controls
1654 lines (1438 loc) · 70.6 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
import logging
from markupsafe import escape as html_escape
from odoo import _, api, fields, models
from odoo.exceptions import UserError, ValidationError
_logger = logging.getLogger(__name__)
class SPPChangeRequest(models.Model):
"""Change request - base model with approval workflow."""
_name = "spp.change.request"
_description = "Change Request"
_inherit = [
"mail.thread",
"mail.activity.mixin",
"spp.approval.mixin",
"spp.cr.conflict.mixin",
]
_order = "create_date desc"
# ══════════════════════════════════════════════════════════════════════════
# CORE FIELDS
# ══════════════════════════════════════════════════════════════════════════
name = fields.Char(
string="Reference",
required=True,
readonly=True,
copy=False,
default="New",
tracking=True,
)
request_type_id = fields.Many2one(
"spp.change.request.type",
string="Request Type",
required=True,
index=True,
ondelete="restrict",
tracking=True,
)
request_type_code = fields.Char(
related="request_type_id.code",
store=True,
index=True,
)
allow_document_download = fields.Boolean(
related="request_type_id.allow_document_download",
)
stage = fields.Selection(
[
("details", "Edit Details"),
("documents", "Upload Documents"),
("review", "Review & Submit"),
],
string="Stage",
default="details",
tracking=True,
)
is_cr_manager = fields.Boolean(
compute="_compute_is_cr_manager",
)
def _compute_is_cr_manager(self):
is_manager = self.env.user.has_group("spp_change_request_v2.group_cr_manager")
for rec in self:
rec.is_cr_manager = is_manager
# ══════════════════════════════════════════════════════════════════════════
# REGISTRANT & APPLICANT
# ══════════════════════════════════════════════════════════════════════════
registrant_id = fields.Many2one(
"res.partner",
string="Registrant",
index=True,
tracking=True,
)
registrant_domain = fields.Char(
compute="_compute_registrant_domain",
store=False,
)
applicant_id = fields.Many2one(
"res.partner",
string="Applicant",
help="Person submitting on behalf of registrant",
domain="[('is_registrant', '=', True), ('is_group', '=', False)]",
)
applicant_phone = fields.Char()
# ══════════════════════════════════════════════════════════════════════════
# DETAIL REFERENCE
# ══════════════════════════════════════════════════════════════════════════
detail_res_model = fields.Char(
related="request_type_id.detail_model",
store=True,
string="Detail Model",
)
detail_res_id = fields.Many2oneReference(
string="Detail Record",
model_field="detail_res_model",
)
# ══════════════════════════════════════════════════════════════════════════
# SOURCE TRACKING
# ══════════════════════════════════════════════════════════════════════════
source_type = fields.Selection(
[
("manual", "Manual Entry"),
("event", "Event Data"),
("api", "External API"),
("import", "Bulk Import"),
],
default="manual",
readonly=True,
)
source_event_id = fields.Many2one("spp.event.data", readonly=True)
source_reference = fields.Char(help="External reference ID")
# ══════════════════════════════════════════════════════════════════════════
# APPLICATION TRACKING
# ══════════════════════════════════════════════════════════════════════════
is_applied = fields.Boolean(default=False, readonly=True, tracking=True)
applied_date = fields.Datetime(readonly=True)
applied_by_id = fields.Many2one("res.users", readonly=True)
apply_error = fields.Text(readonly=True)
# ══════════════════════════════════════════════════════════════════════════
# DYNAMIC APPROVAL
# ══════════════════════════════════════════════════════════════════════════
selected_field_name = fields.Char(
string="Field Being Modified",
readonly=True,
help="The detail field selected for modification (set when detail is saved). "
"Used by CEL conditions to determine the approval workflow.",
)
selected_field_old_value = fields.Char(
string="Old Value",
readonly=True,
help="Human-readable old value of the selected field (from registrant). Stored for audit trail.",
)
selected_field_new_value = fields.Char(
string="New Value",
readonly=True,
help="Human-readable new value of the selected field (from detail). Stored for audit trail.",
)
# ══════════════════════════════════════════════════════════════════════════
# LOG
# ══════════════════════════════════════════════════════════════════════════
log_ids = fields.One2many(
"spp.change.request.log",
"change_request_id",
string="Change Request Log",
)
# ══════════════════════════════════════════════════════════════════════════
# DOCUMENTS & NOTES
# ══════════════════════════════════════════════════════════════════════════
dms_directory_id = fields.Many2one(
"spp.dms.directory",
string="Document Directory",
readonly=True,
ondelete="restrict",
help="Automatically created directory for this change request's documents",
)
document_ids = fields.Many2many("spp.dms.file", string="Documents")
description = fields.Text()
notes = fields.Text(string="Internal Notes")
# ══════════════════════════════════════════════════════════════════════════
# COMPUTED
# ══════════════════════════════════════════════════════════════════════════
display_state = fields.Selection(
[
("draft", "Draft"),
("pending", "Under Review"),
("revision", "Needs Changes"),
("approved", "Approved"),
("rejected", "Rejected"),
("applied", "Applied"),
],
compute="_compute_display_state",
store=True,
)
preview_html = fields.Html(
string="Preview of Changes",
compute="_compute_preview_html",
sanitize=False,
)
review_comparison_html = fields.Html(
string="Review Comparison",
compute="_compute_review_comparison_html",
sanitize=False,
)
preview_html_snapshot = fields.Html(
string="Preview Snapshot",
help="Stored snapshot of preview taken before applying changes",
sanitize=False,
)
review_comparison_html_snapshot = fields.Html(
string="Review Comparison Snapshot",
help="Stored snapshot of review comparison taken before applying changes",
sanitize=False,
)
preview_json_snapshot = fields.Text(
string="Preview JSON Snapshot",
help="Stored JSON snapshot of preview taken before applying changes",
)
review_documents_html = fields.Html(
string="Review Documents",
compute="_compute_review_documents_html",
sanitize=False,
)
registrant_summary_html = fields.Html(
string="Registrant Summary",
compute="_compute_registrant_summary_html",
sanitize=False,
)
is_creator = fields.Boolean(
string="Is Creator",
compute="_compute_is_creator",
help="True if current user created this change request",
)
has_proposed_changes = fields.Boolean(
string="Has Proposed Changes",
compute="_compute_has_proposed_changes",
help="True if there are proposed changes in the detail record",
)
multitier_approval_message = fields.Char(
string="Multi-tier Approval Message",
compute="_compute_multitier_approval_message",
help="Message shown when awaiting next level approval in multi-tier workflow",
)
target_type_message = fields.Char(
string="Target Type Message",
compute="_compute_target_type_message",
help="Message indicating what type of registrant this CR type applies to",
)
missing_required_document_ids = fields.Many2many(
"spp.vocabulary.code",
compute="_compute_missing_required_documents",
string="Missing Required Documents",
)
documents_complete = fields.Boolean(
compute="_compute_missing_required_documents",
string="All Required Documents Uploaded",
)
stage_banner_html = fields.Html(
compute="_compute_stage_banner_html",
sanitize=False,
string="Stage Banner",
)
required_documents_html = fields.Html(
compute="_compute_required_documents_html",
sanitize=False,
string="Required Documents Status",
)
def _compute_is_creator(self):
"""Check if current user is the creator of this CR."""
for rec in self:
rec.is_creator = rec.create_uid == self.env.user
@api.depends("detail_res_id", "detail_res_model")
def _compute_has_proposed_changes(self):
"""Check if there are actual proposed changes in the detail record."""
for rec in self:
rec.has_proposed_changes = False
if not rec.detail_res_id or not rec.detail_res_model or not rec.request_type_id:
continue
try:
# Use sudo to bypass record rules (e.g. global disabled-registrant
# rules on spp.group.membership) — this is read-only preview logic.
sudo_rec = rec.sudo() # nosemgrep: odoo-sudo-without-context
strategy = sudo_rec.request_type_id.get_apply_strategy()
changes = strategy.preview(sudo_rec) or {}
# Remove metadata keys that don't represent actual changes
changes.pop("_action", None)
changes.pop("_message", None)
# If there are remaining keys, there are actual changes
rec.has_proposed_changes = bool(changes)
except Exception:
# If preview fails, default to checking if detail exists
rec.has_proposed_changes = bool(rec.detail_res_id)
@api.depends(
"approval_state",
"approval_review_ids",
"approval_review_ids.status",
"approval_review_ids.tier_review_ids",
"approval_review_ids.tier_review_ids.status",
)
def _compute_multitier_approval_message(self):
"""Compute message showing approval status and pending approver."""
for rec in self:
rec.multitier_approval_message = ""
if rec.approval_state != "pending":
continue
# Get the active pending review
active_review = rec.approval_review_ids.filtered(lambda r: r.status == "pending")[:1]
if not active_review:
continue
if active_review.is_multitier:
# Multi-tier approval
tier_reviews = active_review.tier_review_ids
approved_tiers = tier_reviews.filtered(lambda t: t.status == "approved")
pending_tiers = tier_reviews.filtered(lambda t: t.status == "pending")
waiting_tiers = tier_reviews.filtered(lambda t: t.status == "waiting")
if pending_tiers:
current_tier = pending_tiers.sorted("sequence")[:1]
group_name = ""
if current_tier.tier_id and current_tier.tier_id.approval_group_id:
group_name = current_tier.tier_id.approval_group_id.name
if group_name:
total_tiers = len(tier_reviews)
completed = len(approved_tiers)
msg = _("Awaiting approval from: %s (Level %d of %d)") % (
group_name,
completed + 1,
total_tiers,
)
# Show next approver group if there are waiting tiers
if waiting_tiers:
next_tier = waiting_tiers.sorted("sequence")[:1]
if next_tier.tier_id and next_tier.tier_id.approval_group_id:
next_group = next_tier.tier_id.approval_group_id.name
msg += "\n" + _("Next: %s") % next_group
rec.multitier_approval_message = msg
else:
# Single-tier approval - get group from definition
definition = active_review.definition_id
if definition and definition.approval_group_id:
group_name = definition.approval_group_id.name
rec.multitier_approval_message = _("Awaiting approval from: %s") % group_name
@api.depends("request_type_id", "request_type_id.target_type")
def _compute_target_type_message(self):
"""Compute message indicating valid registrant types for this CR type."""
for rec in self:
rec.target_type_message = ""
if not rec.request_type_id or not rec.request_type_id.target_type:
continue
target_type = rec.request_type_id.target_type
if target_type == "individual":
rec.target_type_message = _("This request type applies to individuals only.")
elif target_type == "group":
rec.target_type_message = _("This request type applies to groups/households only.")
else:
rec.target_type_message = _("This request type applies to both individuals and groups/households.")
@api.depends("name", "request_type_id", "registrant_id")
def _compute_stage_banner_html(self):
for rec in self:
cr_ref = html_escape(rec.name or "")
cr_type = html_escape(rec.request_type_id.name) if rec.request_type_id else ""
html = f'<span class="fw-bold">{cr_ref}</span><span class="text-muted mx-2">|</span><span>{cr_type}</span>'
if rec.registrant_id:
registrant = html_escape(rec.registrant_id.name or "")
html += (
f'<span class="text-muted mx-2">|</span>'
f'<i class="fa fa-user me-1 text-muted"></i>'
f"<span>{registrant}</span>"
)
rec.stage_banner_html = html
@api.depends("document_ids", "document_ids.document_type_id", "request_type_id.required_document_ids")
def _compute_missing_required_documents(self):
for rec in self:
required = rec.request_type_id.required_document_ids if rec.request_type_id else None
if not required:
rec.missing_required_document_ids = self.env["spp.vocabulary.code"]
rec.documents_complete = True
continue
uploaded = rec.document_ids.mapped("document_type_id").filtered(lambda c: c)
missing = required - uploaded
rec.missing_required_document_ids = missing
rec.documents_complete = not bool(missing)
@api.depends("document_ids", "document_ids.document_type_id", "request_type_id.required_document_ids")
def _compute_required_documents_html(self):
for rec in self:
required = rec.request_type_id.required_document_ids if rec.request_type_id else None
if not required:
rec.required_documents_html = (
'<div class="alert alert-info mb-3 py-2">'
'<i class="fa fa-info-circle me-2"></i>'
"Documents are optional for this request type. "
"You may upload supporting documents or proceed to the next step."
"</div>"
)
continue
uploaded_types = rec.document_ids.mapped("document_type_id").filtered(lambda c: c)
items = []
for doc_type in required:
escaped_name = html_escape(doc_type.display_name)
if doc_type in uploaded_types:
items.append(f'<li class="text-success"><i class="fa fa-check-circle me-1"></i>{escaped_name}</li>')
else:
items.append(f'<li class="text-danger"><i class="fa fa-times-circle me-1"></i>{escaped_name}</li>')
rec.required_documents_html = (
'<div class="mb-3">'
"<strong>Required Documents:</strong>"
f'<ul class="list-unstyled mt-1 mb-0">{"".join(items)}</ul>'
"</div>"
)
@api.depends("approval_state", "is_applied")
def _compute_display_state(self):
for rec in self:
if rec.is_applied:
rec.display_state = "applied"
else:
rec.display_state = rec.approval_state
@api.depends("request_type_id.target_type")
def _compute_registrant_domain(self):
"""Compute dynamic domain for registrant based on CR type target."""
for rec in self:
base_domain = [("is_registrant", "=", True)]
if rec.request_type_id and rec.request_type_id.target_type:
target_type = rec.request_type_id.target_type
if target_type == "individual":
# Only individuals (not groups)
base_domain.append(("is_group", "=", False))
elif target_type == "group":
# Only groups
base_domain.append(("is_group", "=", True))
# else: target_type == "both" - no additional filter
rec.registrant_domain = str(base_domain)
def _compute_preview_html(self):
"""Compute HTML preview of changes for the review panel."""
for rec in self:
# If already applied, show the stored snapshot
if rec.is_applied and rec.preview_html_snapshot:
rec.preview_html = rec.preview_html_snapshot
else:
# Generate fresh preview
rec.preview_html = rec._generate_preview_html()
def _compute_review_comparison_html(self):
"""Compute side-by-side comparison HTML for the review stage.
For field-mapping CR types: shows a three-column table (Field | Current | Proposed).
For action CR types: shows a clean summary table of the action details.
Uses stored snapshot after apply (since current == proposed post-apply).
"""
for rec in self:
if rec.is_applied and rec.review_comparison_html_snapshot:
rec.review_comparison_html = rec.review_comparison_html_snapshot
else:
rec.review_comparison_html = rec._generate_review_comparison_html()
@api.depends("document_ids")
def _compute_review_documents_html(self):
"""Compute HTML table for documents matching the proposed changes table style."""
for rec in self:
if not rec.document_ids:
rec.review_documents_html = (
'<div class="text-muted"><i class="fa fa-info-circle me-2"></i>No documents attached.</div>'
)
continue
html = ['<table class="table table-sm table-bordered mb-0" style="width:100%;table-layout:fixed">']
html.append(
"<thead><tr>"
'<th class="bg-light" style="width:45%">File</th>'
'<th class="bg-light" style="width:35%">Document Type</th>'
'<th class="bg-light" style="width:20%">Uploaded</th>'
"</tr></thead>"
)
html.append("<tbody>")
for doc in rec.document_ids:
doc_name = html_escape(doc.name or "")
doc_type = html_escape(doc.document_type_id.display_name) if doc.document_type_id else ""
uploaded = doc.create_date.strftime("%Y-%m-%d") if doc.create_date else ""
html.append(
f"<tr>"
f'<td style="max-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">'
f'<a class="o_cr_doc_preview" data-doc-id="{doc.id}" '
f'style="cursor:pointer" title="{doc_name}">'
f'<i class="fa fa-eye text-primary me-2"></i></a>{doc_name}</td>'
f"<td>{doc_type}</td>"
f"<td>{uploaded}</td>"
f"</tr>"
)
html.append("</tbody></table>")
rec.review_documents_html = "".join(html)
def _compute_registrant_summary_html(self):
"""Compute HTML summary of the registrant for the review panel."""
for rec in self:
if not rec.registrant_id:
rec.registrant_summary_html = '<div class="text-muted">No registrant selected.</div>'
continue
reg = rec.registrant_id
html_parts = ['<div class="o_registrant_summary">']
# Header with name and ID
html_parts.append('<div class="d-flex align-items-center mb-2">')
if reg.is_group:
html_parts.append('<i class="fa fa-users fa-lg text-primary me-2"></i>')
else:
html_parts.append('<i class="fa fa-user fa-lg text-primary me-2"></i>')
html_parts.append(f"<strong>{html_escape(reg.name or '')}</strong>")
html_parts.append("</div>")
# ID badge
if hasattr(reg, "spp_id") and reg.spp_id:
escaped_id = html_escape(reg.spp_id)
html_parts.append(f'<div class="mb-2"><span class="badge bg-secondary">ID: {escaped_id}</span></div>')
# Address
address_parts = []
if reg.street:
address_parts.append(html_escape(reg.street))
if reg.city:
address_parts.append(html_escape(reg.city))
if address_parts:
html_parts.append(
f'<div class="text-muted small mb-2">'
f'<i class="fa fa-map-marker me-1"></i>'
f"{', '.join(address_parts)}"
f"</div>"
)
# Group member count
if reg.is_group and hasattr(reg, "group_membership_ids"):
member_count = len(reg.group_membership_ids or [])
html_parts.append(
f'<div class="badge bg-info"><i class="fa fa-users me-1"></i>{member_count} member(s)</div>'
)
html_parts.append("</div>")
rec.registrant_summary_html = "".join(html_parts)
@api.onchange("request_type_id")
def _onchange_request_type_id(self):
"""Clear registrant if it doesn't match the new target type."""
if self.request_type_id and self.registrant_id:
target_type = self.request_type_id.target_type
is_group = self.registrant_id.is_group
# Check if registrant conflicts with new target type
should_clear = False
if target_type == "individual" and is_group:
# Changed to individual type but registrant is a group
should_clear = True
elif target_type == "group" and not is_group:
# Changed to group type but registrant is an individual
should_clear = True
if should_clear:
self.registrant_id = False
return {
"warning": {
"title": _("Registrant Cleared"),
"message": _(
"The selected registrant was cleared because it doesn't match "
"the target type of the new request type. Please select a "
"compatible registrant."
),
}
}
# ══════════════════════════════════════════════════════════════════════════
# CRUD
# ══════════════════════════════════════════════════════════════════════════
@api.model_create_multi
def create(self, vals_list):
for vals in vals_list:
if vals.get("name", "New") == "New":
vals["name"] = self.env["ir.sequence"].next_by_code("spp.change.request") or "New"
records = super().create(vals_list)
for record in records:
# Auto-create DMS directory
record._create_dms_directory()
# Auto-create detail record
record._ensure_detail()
record._create_audit_event("created", None, "draft")
record._create_log("created")
# Run conflict detection after creation
# Skip for dynamic approval — field_to_modify isn't set yet at create time.
# Checks run when selected_field_name is written (see conflict model's write()).
if hasattr(record, "_run_conflict_checks") and not (
record.request_type_id and record.request_type_id.use_dynamic_approval
):
record._run_conflict_checks()
return records
def unlink(self):
"""Delete associated detail records and archive DMS directory."""
directories_to_archive = self.env["spp.dms.directory"]
for rec in self:
detail = rec.get_detail()
if detail:
detail.unlink()
# Collect directory for archiving (instead of deletion to avoid FK constraint violations)
if rec.dms_directory_id:
directories_to_archive |= rec.dms_directory_id
result = super().unlink()
# Archive directories after CR is deleted to preserve files and avoid constraint issues
if directories_to_archive:
directories_to_archive.write({"active": False})
_logger.info(
"Archived %d DMS directories after CR deletion",
len(directories_to_archive),
)
return result
# ══════════════════════════════════════════════════════════════════════════
# DMS DIRECTORY MANAGEMENT
# ══════════════════════════════════════════════════════════════════════════
def _get_parent_directory(self):
"""Get the parent 'Change Request' directory.
Returns:
spp.dms.directory: The parent Change Request directory
"""
parent_dir = self.env.ref(
"spp_change_request_v2.dms_directory_change_request_root",
raise_if_not_found=False,
)
if not parent_dir:
_logger.warning(
"Parent 'Change Request' directory not found. Please ensure data/dms_directories.xml is loaded."
)
return parent_dir
def _create_dms_directory(self):
"""Create a DMS directory for this change request.
Creates a subdirectory under the 'Change Request' parent directory
with the CR reference as the name.
"""
self.ensure_one()
if self.dms_directory_id:
# Directory already exists
return
if self.name == "New":
# Skip if name is still default (shouldn't happen after sequence)
_logger.warning("Skipping DMS directory creation for CR with name 'New'")
return
# Get parent directory
parent_dir = self._get_parent_directory()
if not parent_dir:
_logger.error(
"Cannot create DMS directory for CR %s: parent directory not found",
self.name,
)
return
# Create subdirectory for this CR
directory = self.env["spp.dms.directory"].create(
{
"name": self.name,
"parent_id": parent_dir.id,
"is_root_directory": False,
"change_request_id": self.id,
}
)
self.dms_directory_id = directory.id
_logger.info(
"Created DMS directory '%s' for change request %s",
directory.complete_name,
self.name,
)
# ══════════════════════════════════════════════════════════════════════════
# DETAIL HELPERS
# ══════════════════════════════════════════════════════════════════════════
def get_detail(self):
"""Get the detail record for this CR.
Uses with_prefetch() to isolate from _ensure_detail's sudo()
prefetch set — without this, non-stored computed fields can
trigger record-rule checks against the wrong user.
"""
self.ensure_one()
if self.detail_res_model and self.detail_res_id:
return self.env[self.detail_res_model].browse(self.detail_res_id).with_prefetch()
return None
def _ensure_detail(self):
"""Ensure detail record exists, create if needed.
Handles both Python-defined models (with change_request_id) and
Studio-created models (with x_change_request_id).
Uses sudo() for creation since users may not have create permission
on detail models (especially Studio-created ones where we disable
create permission to prevent the "New" button from appearing).
"""
self.ensure_one()
if not self.detail_res_id and self.detail_res_model:
# Determine the correct field name for the change request reference
# Studio-created models use x_change_request_id (Odoo naming convention)
# Python-defined models use change_request_id
detail_model = self.env[self.detail_res_model]
if "x_change_request_id" in detail_model._fields:
cr_field = "x_change_request_id"
else:
cr_field = "change_request_id"
# Use sudo() for creation - users don't need create permission
# Detail records are always created by the system automatically
detail = detail_model.sudo().create({cr_field: self.id}) # nosemgrep: odoo-sudo-without-context
self.detail_res_id = detail.id
# Pre-fill detail from registrant if the detail model supports it
if hasattr(detail, "prefill_from_registrant"):
detail.prefill_from_registrant()
return self.get_detail()
# ══════════════════════════════════════════════════════════════════════════
# APPROVAL ACTIONS
# ══════════════════════════════════════════════════════════════════════════
def action_approve(self, comment=None):
"""Override to log intermediate tier approvals in multi-tier workflow.
The base _on_approve hook only fires after ALL tiers are approved.
This captures each intermediate tier approval in the CR log.
"""
# Capture pre-approval state per record
pre_states = {}
for record in self:
if record.approval_state == "pending" and record.is_multitier_approval:
pre_states[record.id] = record.current_tier_name
result = super().action_approve(comment=comment)
# Log intermediate tier approvals
# (final approval is already logged by _on_approve)
for record in self:
if record.id in pre_states and record.approval_state == "pending":
record._create_log("approved")
return result
def action_submit_for_approval(self):
"""Submit for approval with document and required field validation.
Checks required detail fields and documents before submission.
"""
for record in self:
# Validate required detail fields first
if record.request_type_id.required_field_ids:
detail = record.get_detail()
if detail:
is_valid, missing_fields = record.request_type_id.validate_required_fields(detail)
if not is_valid:
missing_list = "\n".join(f"• {field}" for field in missing_fields)
raise ValidationError(
_(
"Cannot submit change request. The following required fields are missing:\n\n%s\n\n"
"Please fill in all required fields before submitting."
)
% missing_list
)
# Check document validation
doc_validation_result = record._validate_documents()
# Proceed with submission
super(SPPChangeRequest, record).action_submit_for_approval()
# Build success notification with redirect to CR list
list_action = {
"type": "ir.actions.client",
"tag": "navigate_cr_list",
}
type_name = record.request_type_id.name or ""
success_message = _("%s %s successfully submitted for approval.") % (
record.name,
type_name,
)
# If warning mode and documents missing, append doc warning to message
if doc_validation_result and doc_validation_result.get("notification"):
notification = doc_validation_result["notification"]
success_message += "\n" + notification["message"]
return {
"type": "ir.actions.client",
"tag": "display_notification",
"params": {
"message": success_message,
"type": "success",
"sticky": False,
"next": list_action,
},
}
return super().action_submit_for_approval()
# ══════════════════════════════════════════════════════════════════════════
# APPROVAL HOOKS (from spp.approval.mixin)
# ══════════════════════════════════════════════════════════════════════════
def _get_approval_definition(self):
self.ensure_one()
cr_type = self.request_type_id
# Dynamic approval: evaluate candidates using selected field + values
if cr_type.use_dynamic_approval and cr_type.candidate_definition_ids:
definition = self._resolve_dynamic_approval()
if definition:
return definition
# Fallback to static definition (existing behavior)
definition = cr_type.approval_definition_id
if not definition:
raise UserError(
_(
"No approval workflow configured for request type '%s'. "
"Please configure an approval definition in Change Request > "
"Configuration > CR Types."
)
% cr_type.name
)
return definition
def _resolve_dynamic_approval(self):
"""Evaluate candidate definitions against selected field and values.
Iterates candidates in sequence order; first match wins.
Returns spp.approval.definition record, or None if no candidate matches.
"""
self.ensure_one()
if not self.selected_field_name:
return None
extra_context = self._compute_field_values_for_cel()
evaluator = self.env["spp.cel.evaluator"]
for candidate in self.request_type_id.candidate_definition_ids.sorted("sequence"):
if not candidate.use_cel_condition or not candidate.cel_condition:
# No condition = catch-all (matches everything)
return candidate
try:
result = evaluator.evaluate(candidate.cel_condition, self, extra_context)
if result:
return candidate
except Exception:
_logger.warning(
"CEL evaluation failed for candidate definition '%s' on CR %s, skipping",
candidate.name,
self.name,
exc_info=True,
)
continue
return None
def _compute_field_values_for_cel(self):
"""Compute typed old and new values for CEL evaluation.
Returns a dict with old_value and new_value typed according to field type.
"""
self.ensure_one()
field_name = self.selected_field_name
cr_type = self.request_type_id
if not field_name:
return {"old_value": None, "new_value": None}
mapping = cr_type.apply_mapping_ids.filtered(lambda m: m.source_field == field_name)[:1]
detail = self.get_detail()
registrant = self.registrant_id
old_raw = None
new_raw = None
if mapping and registrant:
old_raw = getattr(registrant, mapping.target_field, None)
if detail:
new_raw = getattr(detail, field_name, None)
return {
"old_value": self._normalize_value_for_cel(old_raw, registrant, mapping.target_field if mapping else None),
"new_value": self._normalize_value_for_cel(new_raw, detail, field_name),
}
def _normalize_value_for_cel(self, value, record, field_name):
"""Normalize an Odoo field value for use in CEL expressions."""
if value is None or value is False:
if record and field_name and field_name in record._fields:
field = record._fields[field_name]
if field.type == "boolean":
return False
if field.type in ("integer", "float", "monetary"):
return 0
return None
if record and field_name and field_name in record._fields:
field = record._fields[field_name]
if field.type in ("char", "text", "selection", "html"):
return value or ""
if field.type in ("integer", "float", "monetary"):
return value or 0
if field.type == "boolean":
return bool(value)
if field.type in ("date", "datetime"):
return value
if field.type == "many2one":
# IDs are exposed for internal CEL evaluation only, not for external APIs.
result = {
"id": value.id if value else 0,
"name": value.display_name if value else "",
}
# Vocabulary models: expose machine-readable code for stable CEL matching
if value and "code" in value._fields:
result["code"] = value.code or ""
# Hierarchical vocabularies: expose parent category
if value and "parent_id" in value._fields and value.parent_id:
parent = value.parent_id
result["parent"] = {
"id": parent.id,
"name": parent.display_name,
"code": parent.code if "code" in parent._fields else "",
}
return result
if field.type in ("one2many", "many2many"):
return {
"ids": value.ids if value else [],
"count": len(value) if value else 0,
}
return value
def _on_approve(self):
super()._on_approve()
# Signal ORM that approval_state changed (set via raw SQL in _do_approve)
# so stored computed fields like display_state get recomputed
self.modified(["approval_state"])
self._create_audit_event("approved", "pending", "approved")
self._create_log("approved")
if self.request_type_id.auto_apply_on_approve:
self.action_apply()
def _on_reject(self, reason):
super()._on_reject(reason)
self._create_audit_event("rejected", "pending", "rejected")
self._create_log("rejected", notes=reason)
def _check_can_submit(self):
"""Override to allow resubmission and validate dynamic approval field selection."""
self.ensure_one()
if self.approval_state not in ("draft", "revision"):
raise UserError(_("Only draft or revision-requested records can be submitted for approval."))
cr_type = self.request_type_id
if cr_type.use_dynamic_approval and not self.selected_field_name:
raise ValidationError(
_(