-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_phase_c_tables_fixed.py
More file actions
250 lines (233 loc) · 11.4 KB
/
create_phase_c_tables_fixed.py
File metadata and controls
250 lines (233 loc) · 11.4 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
#!/usr/bin/env python3
"""
Create Phase C Rules tables with proper names to avoid conflicts
"""
import sqlite3
import uuid
import os
# Database file path
db_path = "icc_rules.db"
def create_phase_c_tables():
"""Create Phase C Rules tables"""
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
try:
# Check if approval columns exist in rules table first
cursor.execute("PRAGMA table_info(rules);")
columns = [col[1] for col in cursor.fetchall()]
# Add approval workflow columns to rules table if they don't exist
if 'approval_status' not in columns:
print("Adding approval workflow columns to rules table...")
cursor.execute("ALTER TABLE rules ADD COLUMN approval_status TEXT DEFAULT 'draft' NOT NULL;")
cursor.execute("ALTER TABLE rules ADD COLUMN approved_by TEXT;")
cursor.execute("ALTER TABLE rules ADD COLUMN approved_at DATETIME;")
cursor.execute("ALTER TABLE rules ADD COLUMN rejection_reason TEXT;")
conn.commit()
print("[OK] Added approval workflow columns to rules table")
else:
print("[OK] Approval workflow columns already exist in rules table")
# Create rule_change_history table (renamed from rule_versions to avoid conflict)
print("Creating rule_change_history table...")
cursor.execute('''
CREATE TABLE IF NOT EXISTS rule_change_history (
id TEXT PRIMARY KEY,
rule_db_id TEXT NOT NULL, -- references rules.id
rule_id TEXT NOT NULL, -- the rule's rule_id field
version_number INTEGER NOT NULL,
content TEXT NOT NULL, -- JSON stored as TEXT
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
created_by TEXT,
change_summary TEXT
);
''')
cursor.execute('CREATE INDEX IF NOT EXISTS ix_rule_change_history_rule_db_id ON rule_change_history (rule_db_id);')
cursor.execute('CREATE INDEX IF NOT EXISTS ix_rule_change_history_rule_id ON rule_change_history (rule_id);')
cursor.execute('CREATE INDEX IF NOT EXISTS ix_rule_change_history_created_at ON rule_change_history (created_at);')
print("[OK] Created rule_change_history table with indexes")
# Create rule_usage_analytics table
print("Creating rule_usage_analytics table...")
cursor.execute('''
CREATE TABLE IF NOT EXISTS rule_usage_analytics (
id TEXT PRIMARY KEY,
rule_db_id TEXT NOT NULL, -- references rules.id
rule_id TEXT NOT NULL, -- the rule's rule_id field
applied_count INTEGER DEFAULT 0 NOT NULL,
violation_count INTEGER DEFAULT 0 NOT NULL,
last_used DATETIME,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
);
''')
cursor.execute('CREATE UNIQUE INDEX IF NOT EXISTS ix_rule_usage_analytics_rule_db_id ON rule_usage_analytics (rule_db_id);')
cursor.execute('CREATE INDEX IF NOT EXISTS ix_rule_usage_analytics_rule_id ON rule_usage_analytics (rule_id);')
cursor.execute('CREATE INDEX IF NOT EXISTS ix_rule_usage_analytics_last_used ON rule_usage_analytics (last_used);')
print("[OK] Created rule_usage_analytics table with indexes")
# Create rule_templates table
print("Creating rule_templates table...")
cursor.execute('''
CREATE TABLE IF NOT EXISTS rule_templates (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
description TEXT,
category TEXT NOT NULL,
template_content TEXT NOT NULL, -- JSON stored as TEXT
usage_count INTEGER DEFAULT 0 NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
);
''')
cursor.execute('CREATE UNIQUE INDEX IF NOT EXISTS ix_rule_templates_name ON rule_templates (name);')
cursor.execute('CREATE INDEX IF NOT EXISTS ix_rule_templates_category ON rule_templates (category);')
print("[OK] Created rule_templates table with indexes")
# Create rule_audit_logs table
print("Creating rule_audit_logs table...")
cursor.execute('''
CREATE TABLE IF NOT EXISTS rule_audit_logs (
id TEXT PRIMARY KEY,
rule_db_id TEXT, -- references rules.id
rule_id TEXT NOT NULL, -- the rule's rule_id field
action TEXT NOT NULL, -- created, updated, deleted, approved, rejected, tested
user_id TEXT,
tenant_id TEXT,
before_state TEXT, -- JSON stored as TEXT
after_state TEXT, -- JSON stored as TEXT
diff_summary TEXT,
ip_address TEXT,
user_agent TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
);
''')
cursor.execute('CREATE INDEX IF NOT EXISTS ix_rule_audit_logs_rule_db_id ON rule_audit_logs (rule_db_id);')
cursor.execute('CREATE INDEX IF NOT EXISTS ix_rule_audit_logs_rule_id ON rule_audit_logs (rule_id);')
cursor.execute('CREATE INDEX IF NOT EXISTS ix_rule_audit_logs_action ON rule_audit_logs (action);')
cursor.execute('CREATE INDEX IF NOT EXISTS ix_rule_audit_logs_user_id ON rule_audit_logs (user_id);')
cursor.execute('CREATE INDEX IF NOT EXISTS ix_rule_audit_logs_created_at ON rule_audit_logs (created_at);')
print("[OK] Created rule_audit_logs table with indexes")
# Create rule_test_results table
print("Creating rule_test_results table...")
cursor.execute('''
CREATE TABLE IF NOT EXISTS rule_test_results (
id TEXT PRIMARY KEY,
rule_db_id TEXT, -- references rules.id
rule_id TEXT NOT NULL, -- the rule's rule_id field
test_input TEXT NOT NULL, -- JSON stored as TEXT
test_result TEXT NOT NULL, -- JSON stored as TEXT
passed INTEGER NOT NULL, -- Boolean as INTEGER (0/1)
execution_time_ms REAL,
tested_by TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
);
''')
cursor.execute('CREATE INDEX IF NOT EXISTS ix_rule_test_results_rule_db_id ON rule_test_results (rule_db_id);')
cursor.execute('CREATE INDEX IF NOT EXISTS ix_rule_test_results_rule_id ON rule_test_results (rule_id);')
cursor.execute('CREATE INDEX IF NOT EXISTS ix_rule_test_results_created_at ON rule_test_results (created_at);')
print("[OK] Created rule_test_results table with indexes")
# Insert sample rule templates
print("Inserting sample rule templates...")
sample_templates = [
{
'id': str(uuid.uuid4()),
'name': 'Document Amount Validation',
'description': 'Template for validating document amounts against limits',
'category': 'Financial',
'template_content': '''{
"conditions": [
{
"field": "amount",
"operator": "<=",
"value": "{{max_amount}}",
"error_message": "Amount exceeds maximum limit of {{max_amount}}"
}
],
"variables": {
"max_amount": {
"type": "number",
"description": "Maximum allowed amount",
"default": 100000
}
}
}'''
},
{
'id': str(uuid.uuid4()),
'name': 'Required Fields Check',
'description': 'Template for validating required document fields',
'category': 'Validation',
'template_content': '''{
"conditions": [
{
"field": "{{field_name}}",
"operator": "exists",
"error_message": "Required field {{field_name}} is missing"
}
],
"variables": {
"field_name": {
"type": "string",
"description": "Name of the required field",
"default": "beneficiary_name"
}
}
}'''
},
{
'id': str(uuid.uuid4()),
'name': 'Date Range Validation',
'description': 'Template for validating dates within acceptable ranges',
'category': 'Temporal',
'template_content': '''{
"conditions": [
{
"field": "{{date_field}}",
"operator": "date_between",
"value": ["{{start_date}}", "{{end_date}}"],
"error_message": "Date must be between {{start_date}} and {{end_date}}"
}
],
"variables": {
"date_field": {
"type": "string",
"description": "Date field to validate",
"default": "issue_date"
},
"start_date": {
"type": "date",
"description": "Start of valid date range",
"default": "2024-01-01"
},
"end_date": {
"type": "date",
"description": "End of valid date range",
"default": "2025-12-31"
}
}
}'''
}
]
for template in sample_templates:
cursor.execute('''
INSERT OR IGNORE INTO rule_templates (id, name, description, category, template_content, usage_count)
VALUES (?, ?, ?, ?, ?, 0)
''', (template['id'], template['name'], template['description'], template['category'], template['template_content']))
print(f"[OK] Inserted {len(sample_templates)} sample rule templates")
# Commit all changes
conn.commit()
print("\n[SUCCESS] All Phase C Rules tables created successfully!")
# Show new tables
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE '%rule_%' ORDER BY name;")
tables = cursor.fetchall()
print(f"\nRule-related tables:")
for table in tables:
print(f" - {table[0]}")
except Exception as e:
print(f"[ERROR] Error creating tables: {e}")
conn.rollback()
raise
finally:
conn.close()
if __name__ == "__main__":
if not os.path.exists(db_path):
print(f"[ERROR] Database file {db_path} not found!")
exit(1)
print("[INFO] Creating Phase C Rules tables...")
create_phase_c_tables()