-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2063 lines (1725 loc) · 85.4 KB
/
Copy pathapp.py
File metadata and controls
2063 lines (1725 loc) · 85.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
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 os
import json
import logging
import threading
import urllib3
from datetime import datetime
from flask import Flask, request, jsonify, render_template, session, send_from_directory
from flask_session import Session
from dotenv import load_dotenv
import requests
#from final_mcp_client import mcp_client
from improved_mcp_client import execute_query, format_query_response
from improved_mcp_client import mcp_client
import jwt
from functools import wraps
from flask_cors import CORS
import psycopg2
import time
from mcp_client import mcp_client
import intent_detection
from nlp_plan_builder import extract_plan_struct_from_text
from datetime import datetime, timedelta
import re
# Import RAG functionality
from rag import retrieve_context, clear_vector_cache
#for redis
from redis_chat_session import save_message, get_chat_history, clear_chat_history
import redis
#for prediction analysis
from ml_handler import handle_ml_request
from intent_detection import is_ml_prediction_intent, is_ml_optimization_intent, extract_ml_params
from plan_editor import plan_editor
# --- Setup & config ---
load_dotenv()
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO").upper()
logging.basicConfig(level=os.getenv('LOG_LEVEL', 'INFO').upper())
logger = logging.getLogger(__name__)
app = Flask(__name__, static_folder="static", template_folder="templates")
CORS(app, origins=["http://localhost:9000"], supports_credentials=True)
secret = os.getenv("FLASK_SECRET_KEY", None)
if secret:
app.secret_key = secret
else:
# fallback random each run (restart clears sessions)
app.secret_key = os.urandom(24)
app.config["SESSION_TYPE"] = "filesystem"
app.config["SESSION_PERMANENT"] = True #False
app.config["SESSION_USE_SIGNER"] = True
# ========== ML SYSTEM AUTO-INITIALIZATION ==========
logger.info("🤖 Initializing ML Prediction System...")
try:
from ml_advanced_predictor import tenant_predictor
logger.info("✅ ML Predictor loaded and ready")
except Exception as e:
logger.error(f"❌ ML Predictor initialization failed: {e}")
# ====================================================
app.permanent_session_lifetime = timedelta(hours=2)
Session(app)
API_BASE_URL = os.getenv("BACKEND_API_BASE_URL", "https://localhost:8081")
JWT_TOKEN = os.getenv("JWT_TOKEN", "")
DOCUMENTS_FOLDER = os.getenv("DOCUMENTS_FOLDER", "documents") # Folder path for RAG documents
logger.info(f"✅ JWT_TOKEN present: {bool(JWT_TOKEN)}")
logger.info(f"🔧 API_BASE_URL: {API_BASE_URL}")
logger.info(f"📂 DOCUMENTS_FOLDER: {DOCUMENTS_FOLDER}")
def get_client_id_for_org(org_id):
conn = psycopg2.connect(
host=os.getenv("DB_HOST", "localhost"),
database=os.getenv("DB_NAME", "commissions"),
user=os.getenv("DB_USER", "user"),
password=os.getenv("DB_PASSWORD", "password"),
port=int(os.getenv("DB_PORT", 5432)),
)
try:
with conn.cursor() as cur:
cur.execute(
"SELECT parent_id FROM organization WHERE status=1 AND id=%s ORDER BY id DESC LIMIT 1", (org_id,)
)
row = cur.fetchone()
return row[0] if row else None
finally:
conn.close()
def verify_jwt_token(f):
from functools import wraps
@wraps(f)
def decorated(*args, **kwargs):
token = request.headers.get('Authorization')
if not token:
return jsonify({'error': 'No token provided'}), 401
if token.startswith('Bearer '):
token = token[7:]
try:
# Replace 'your-jwt-secret' with the secret used by your .NET backend!
#payload = jwt.decode(token, 'your-jwt-secret', algorithms=['HS256'])
payload = jwt.decode(token, "V_E_R_Y_S_E_C_R_E_T_K_E_Y_Commission_WEB_APP", algorithms=['HS256'], audience="http://callippus.co.uk", issuer="http://callippus.co.uk")
print("Decoded JWT payload:", payload)
session['jwt_token'] = token
# Save user fields needed for multitenancy:
request.org_id = payload.get("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/spn")
request.org_code = payload.get("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/stateorprovince")
request.user_id = payload.get("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier")
request.username = payload.get("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name")
except jwt.ExpiredSignatureError:
return jsonify({'error': 'Token expired'}), 401
except jwt.InvalidTokenError:
return jsonify({'error': 'Invalid token'}), 401
return f(*args, **kwargs)
return decorated
# --- Server-side persistent user-state (optional keyed by user_id) ---
USER_STATE = {}
USER_STATE_LOCK = threading.Lock()
def load_user_state(user_id):
with USER_STATE_LOCK:
s = USER_STATE.get(user_id)
return dict(s) if isinstance(s, dict) else {}
def save_user_state(user_id, state_dict):
with USER_STATE_LOCK:
USER_STATE[user_id] = dict(state_dict)
def clear_user_state(user_id):
with USER_STATE_LOCK:
if user_id in USER_STATE:
del USER_STATE[user_id]
# --- INTENT RECOGNITION ---
def is_plan_creation_intent(user_msg, llm_complete_func):
msg = user_msg.lower().strip()
plan_keywords = [
"create plan", "create a plan", "start plan", "new plan", "commission plan",
"setup plan", "plan creation", "add plan", "build plan"
]
for keyword in plan_keywords:
if keyword in msg:
logger.info(f"🎯 Plan creation intent detected: '{keyword}' found in message")
return True
meta_prompt = f"""Is this message from a user a description of a new compensation plan or an attempt to create a compensation plan? Answer True or False: {user_msg}"""
try:
resp = llm_complete_func(prompt=meta_prompt, max_tokens=2, temperature=0)
logger.info(f'[intent LLM] LLM intent response: {resp}')
return resp.strip().lower().startswith("true")
except Exception as e:
return False
def is_database_query_intent(message: str) -> bool:
"""
Determine if the user wants to query the database
"""
if not is_database_enabled():
return False
message_lower = message.lower().strip()
# Database query keywords
db_keywords = [
"show", "list", "find", "get", "what", "how many", "count",
"total", "sum", "average", "when", "who", "active plan", "current plan",
"commission", "payment", "employee", "program", "rule", "condition",
"tier", "range", "schedule", "assignment", "paid", "amount"
]
# Check if message contains database entities (use schema)
try:
schema = mcp_client.get_database_schema()
if schema:
# Check for table names in message
for table_name in schema.keys():
table_words = table_name.replace('_', ' ').split()
for word in table_words:
if word in message_lower and len(word) > 3:
logger.info(f"🎯 Database query intent detected: table '{table_name}' reference found")
return True
except Exception as e:
logger.debug(f"Schema check failed in intent detection: {e}")
# Check for database query keywords
for keyword in db_keywords:
if keyword in message_lower:
# Make sure it's not a plan creation intent
# if not is_plan_creation_intent(message):
if not intent_detection.is_plan_creation_intent(message, mcp_client.claude_complete):
logger.info(f"🎯 Database query intent detected: '{keyword}' found in message")
return True
return False
def is_database_enabled():
try:
from improved_mcp_client import execute_query
return True
except ImportError:
return False
def handle_database_query(user_message: str, offset=0) -> str:
"""
Handle database queries using improved MCP client
"""
try:
# Execute the natural language query using the improved MCP/NL→SQL flow
org_id = getattr(request, 'org_id', None)
org_code = getattr(request, 'org_code', None)
client_id = get_client_id_for_org(org_id) if org_id else None
#result = execute_query(user_message, org_id=org_id, client_id=client_id, offset=offset)
# ✅ PAGINATION FIX: Inject offset hint into the message
if offset > 0:
# Tell the SQL generator to skip records
user_message_with_offset = f"{user_message} (skip first {offset} records, show next 10)"
else:
user_message_with_offset = user_message
result = execute_query(user_message_with_offset, org_id=org_id, client_id=client_id, offset=offset)
# Format for pretty printing, safe for end user
formatted_response = format_query_response(result)
# ✅ ADD PAGINATION INFO to response
if offset > 0:
formatted_response = formatted_response.replace(
"Here are the ",
f"Here are the next "
)
formatted_response = f"**Showing records {offset+1}-{offset+10}:**\n\n{formatted_response}"
return formatted_response
except Exception as e:
logger.error(f"❌ [DB] Error processing database query: {e}")
error_text = str(e)
if ("429" in error_text or "rate_limit_error" in error_text or "Too Many Requests" in error_text):
return "The system is currently handling too many requests to the AI service. Please wait a few seconds and try again."
return "The server is restarting or temporarily unavailable. Please try again in a few seconds."
# --- Pagination helpers ---
def get_plan_offset():
return session.get('plan_offset', 0)
def set_plan_offset(offset):
session['plan_offset'] = offset
session.modified = True
def increment_plan_offset(n=10):
session['plan_offset'] = get_plan_offset() + n
session.modified = True
def reset_plan_offset():
session['plan_offset'] = 0
session.modified = True
# --- RAG QUERY HANDLER - SIMPLIFIED SINCE rag.py NOW HANDLES CLEAN RESPONSES ---
def handle_rag_query(user_message: str) -> str:
"""
Handle general queries using RAG functionality
"""
logger.info(f"🧠 [RAG] Processing query: '{user_message}'")
try:
# retrieve_context now returns clean answer directly
clean_answer, chunks = retrieve_context(user_message, DOCUMENTS_FOLDER, k=7)
if not clean_answer:
logger.warning("📭 [RAG] No relevant context found")
return "I couldn't find any relevant information in the documents. Please make sure the documents are properly loaded or try rephrasing your question."
logger.info(f"📋 [RAG] Retrieved answer from {len(chunks)} chunks")
logger.info(f"✅ [RAG] Response generated: {len(clean_answer)} characters")
return clean_answer
except Exception as e:
logger.error(f"❌ [RAG] Error processing query: {e}")
error_text = str(e)
if "429" in error_text or "rate_limit_error" in error_text or "Too Many Requests" in error_text:
return "The system is currently handling too many requests to the AI service. Please wait a few seconds and try again."
return f"Sorry, I encountered an error while searching the documents: {str(e)}"
def api_headers():
print("[DEBUG] jwt_token IN api_headers:", session.get('jwt_token'))
h = {"Accept": "application/json"}
token = session.get("jwt_token")
if not token:
token = JWT_TOKEN # fallback ONLY if not in session (dev/testing)
if token:
h["Authorization"] = f"Bearer {token}"
print("API HEADERS USED FOR FETCH:", h)
return h
def fetch_json_safe(url, name_for_logs=None, timeout=8):
name = name_for_logs or url
try:
logger.info(f"[{name}] GET {url}")
r = requests.get(url, headers=api_headers(), timeout=timeout, verify=False)
logger.info(f"[{name}] Status: {r.status_code}")
txt = (r.text or "")[:1000]
logger.debug(f"[{name}] Body (truncated): {txt}")
if r.status_code != 200:
return None
ct = (r.headers.get("Content-Type") or "").lower()
if "json" in ct or r.text.strip().startswith(("[", "{")):
try:
return r.json()
except Exception as e:
logger.error(f"[{name}] JSON parse error: {e}")
logger.debug(r.text[:2000])
return None
else:
logger.warning(f"[{name}] Non-json response")
return None
except Exception as e:
logger.error(f"[{name}] Request failed: {e}")
return None
# --- API fetchers (use your endpoints) ---
def fetch_schedules():
return fetch_json_safe(f"{API_BASE_URL}/api/PlanCreationWebApi/GetCommissionSchedule", "fetch_schedules") or []
def fetch_assignee_objects():
return fetch_json_safe(f"{API_BASE_URL}/api/PlanCreationWebApi/GetAssigneeNameList", "fetch_assignee_objects") or []
def fetch_plan_types():
return fetch_json_safe(f"{API_BASE_URL}/api/PlanTypeMasterWebApi/GetPlanTypeMasterList", "fetch_plan_types") or []
def fetch_plan_params():
# attempt endpoint; fallback to five if not available
res = fetch_json_safe(f"{API_BASE_URL}/api/PlanCreationWebApi/GetPlanParams", "fetch_plan_params")
if isinstance(res, list) and res:
# try extract names
out = []
for r in res:
if isinstance(r, str):
out.append(r)
elif isinstance(r, dict):
name = r.get("name") or r.get("paramName") or r.get("param")
if name:
out.append(name)
if out:
return out
return ["Territory", "Product", "BusinessPartner", "Plant", "Group"]
def fetch_uom():
return fetch_json_safe(f"{API_BASE_URL}/api/PlanCreationWebApi/GetUomList", "fetch_uom") or []
def fetch_currency():
return fetch_json_safe(f"{API_BASE_URL}/api/PlanCreationWebApi/GetCurrencyList", "fetch_currency") or []
# --- Hardcoded lists ---
OBJECT_TYPES = ["Invoices", "Contracts", "Sales Orders"]
CATEGORY_TYPES = ["Flat", "Slab", "Tiered"]
RANGE_TYPES = ["Amount", "Quantity"]
BASE_VALUES = ["Gross", "Net"]
PLAN_BASES = ["Revenue", "Margin"]
VALUE_TYPES = ["Percentage", "Amount"]
YES_NO = ["Yes", "No"]
ON_OFF = ["On", "Off"]
# --- Helpers for presenting & selecting numbered lists ---
def present_numbered_list(items, heading=None):
"""
Returns a single string with numbered lines and the options list saved for later resolution.
"""
if heading is None:
heading = ""
lines = []
if heading:
lines.append(heading)
if not items:
lines.append("(no options available)")
return "\n".join(lines)
for i, it in enumerate(items, start=1):
# if item is dict try nice label
if isinstance(it, dict):
label = it.get("schedulerName") or it.get("planName") or it.get("objectType") or it.get("label") or it.get("currencyCode") or it.get("currencyName") or str(it)
else:
label = str(it)
lines.append(f"{i}. {label}")
return "\n".join(lines)
def resolve_choice(choice, options):
"""
Accepts choice: number (string) or text. Returns resolved label (string) or None.
options: list of strings or dicts (we return pretty label as string)
"""
if not choice:
return None
c = choice.strip()
# numeric
if c.isdigit():
idx = int(c) - 1
if 0 <= idx < len(options):
opt = options[idx]
return option_label(opt)
return None
# exact match case-insensitive against labels
for opt in options:
lbl = option_label(opt)
if lbl.lower() == c.lower():
return lbl
# startswith fallback
for opt in options:
lbl = option_label(opt)
if lbl.lower().startswith(c.lower()):
return lbl
return None
def option_label(opt):
if isinstance(opt, dict):
return opt.get("schedulerName") or opt.get("planName") or opt.get("objectType") or opt.get("label") or opt.get("currencyCode") or opt.get("currencyName") or str(opt)
return str(opt)
# --- Combination helper: fetch values for a param from assignee objects as colleague described ---
def get_param_options_for_combination(param_name, assignee_objs):
if not param_name:
return []
out = []
valid_tables = set()
for a in assignee_objs:
tname = (a.get("tableName") or "").strip().lower()
if tname:
valid_tables.add(tname)
for a in assignee_objs:
try:
if str(a.get("type") or "").strip().lower() == param_name.strip().lower() and str(a.get("subType") or "").strip().lower() != "sales team":
tname = (a.get("tableName") or "").strip().lower()
if tname in valid_tables:
out.append({"label": a.get("objectType") or a.get("label") or a.get("objectName") or a.get("object") or a.get("name") or "", "id": a.get("id"), "tableName": a.get("tableName")})
except Exception as e:
logger.debug(f"[get_param_options_for_combination] error: {e}")
# dedupe by label preserving order
seen = set(); deduped = []
for o in out:
lbl = (o.get("label") or "").strip()
if not lbl: continue
if lbl.lower() in seen: continue
seen.add(lbl.lower()); deduped.append(o)
return deduped
# --- Build and store options once when starting plan creation ---
def build_options_and_store():
opts = {}
opts["schedules"] = fetch_schedules() # schedule objects with schedulerName
opts["assignee_objects"] = fetch_assignee_objects() # raw assignee objects
# extract readable assignee names for selection (filter Sales Team as colleague mentioned for assignee dropdown? keep all readable)
assignees = []
for a in opts["assignee_objects"]:
label = a.get("objectType") or a.get("label") or a.get("objectName") or a.get("name")
if label:
assignees.append(label)
opts["assignees"] = sorted(list(dict.fromkeys(assignees))) # dedupe but preserve order
opts["plan_types"] = [p.get("planName") for p in fetch_plan_types()] or []
opts["plan_params"] = fetch_plan_params()
opts["uom"] = fetch_uom()
opts["currency"] = fetch_currency()
opts["object_types"] = OBJECT_TYPES
opts["category_types"] = CATEGORY_TYPES
opts["range_types"] = RANGE_TYPES
opts["base_values"] = BASE_VALUES
opts["plan_bases"] = PLAN_BASES
opts["value_types"] = VALUE_TYPES
return opts
# --- POST to create program/plans (final submit) - UPDATED WITH BETTER ERROR HANDLING ---
def post_program_creation(plan_payload):
url = f"{API_BASE_URL}/api/PlanCreationWebApi/PostProgramCreation"
try:
# Check if this is a simple payload (from NLP) or complex (from wizard)
if 'plan_name' in plan_payload:
# Convert simple NLP payload to API format
plan_payload = build_simple_payload_from_plan_data(plan_payload)
logger.info("[post_program_creation] posting to URL: " + url)
logger.info("[post_program_creation] payload keys: " + str(list(plan_payload.keys())))
logger.info("[post_program_creation] posting payload (truncated): " + json.dumps(plan_payload)[:1500])
headers = api_headers()
headers["Content-Type"] = "application/json"
r = requests.post(url, json=plan_payload, headers=headers, timeout=30, verify=False)
logger.info(f"[post_program_creation] status: {r.status_code}")
logger.info(f"[post_program_creation] response headers: {dict(r.headers)}")
logger.info(f"[post_program_creation] response text: {r.text[:1000]}")
if r.status_code == 404:
logger.error("[post_program_creation] 404 error - endpoint not found")
return {"error": "API endpoint not found (404). Check server configuration.", "status_code": 404}
elif r.status_code == 401:
logger.error("[post_program_creation] 401 error - authentication failed")
return {"error": "Authentication failed (401). Check JWT token.", "status_code": 401}
elif r.status_code == 500:
logger.error("[post_program_creation] 500 error - server error")
return {"error": f"Server error (500): {r.text[:200]}", "status_code": 500}
elif r.status_code not in [200, 201]:
logger.warning(f"[post_program_creation] unexpected status: {r.status_code}")
return {"error": f"Unexpected response status: {r.status_code}", "status_code": r.status_code, "response": r.text}
try:
return r.json()
except:
# Success but non-JSON response
if r.status_code in [200, 201]:
return {"success": True, "status_code": r.status_code, "text": r.text[:2000]}
return {"status_code": r.status_code, "text": r.text[:2000]}
except Exception as e:
logger.error(f"[post_program_creation] error: {e}")
return {"error": str(e)}
# --- Start plan creation: initialize session keys ---
def start_plan_creation_session():
opts = build_options_and_store()
if not opts["schedules"] or not opts["assignees"] or not opts["plan_types"]:
# allow flow but warn if critical masters are missing
logger.warning("[start_plan_creation_session] some master data missing; check backend endpoints")
# session.clear()
jwt = session.get("jwt_token") # save JWT
session.clear()
if jwt:
session["jwt_token"] = jwt # restore JWT
session["mode"] = "plan_creation"
session["phase"] = 1
session["stage"] = "plan_name"
session["options"] = opts
session["plan_data"] = {
"plan_name": None,
"calculation_schedule": None,
"payment_schedule": None,
"assignee_name": None,
"object_type": None,
"valid_from": None,
"valid_to": None,
"plan_rules": []
}
session["current_rule"] = None
session["current_assignment"] = None
session["awaiting_final_confirmation"] = False
session["org_id"] = getattr(request, "org_id", None)
session["org_code"] = getattr(request, "org_code", None)
session["user_id"] = getattr(request, "user_id", None)
session["username"] = getattr(request, "username", None)
# (client_id/client_code only if needed and correctly mapped)
session.modified = True
# --- Flow handler (core) - COMPLETE PLAN CREATION LOGIC ---
def handle_message_in_flow(user_msg):
"""
Handle wizard continuation - process user input in plan creation mode
Returns: dict with 'response' key
"""
logger.info(f"[WIZARD] Processing continuation message: {user_msg}")
try:
# Get current plan data
plan_data = session.get('plan_data', {})
logger.info(f"[WIZARD] Current plan data: {plan_data}")
# Check if this is NLP-based plan creation (has plan_data)
if plan_data:
# NLP-based continuation
user_msg_lower = user_msg.lower().strip()
# Check if user wants to submit
if any(word in user_msg_lower for word in ['submit', 'save']):
# Check if we have minimum required fields
required_fields = ['plan_name']
missing_required = [f for f in required_fields if not plan_data.get(f)]
if missing_required:
return {
"response": f"Cannot submit yet. Plan name is required. Please provide a plan name first."
}
# SHOW COMPLETE SUMMARY with ALL fields (including empty)
logger.info("[WIZARD] User requested submit - showing final confirmation with ALL fields")
session['awaiting_final_confirmation'] = True
session.modified = True
#if user_id:
#save_user_state(user_id, dict(session))
# Generate complete summary showing ALL fields
complete_summary = format_plan_summary(plan_data, show_all_fields=True)
return {
"response": complete_summary
}
# Check for FINAL CONFIRMATION (SECOND STEP: Actually save)
if user_msg_lower.strip() == 'confirm' and session.get('awaiting_final_confirmation'):
logger.info("[WIZARD] User confirmed - proceeding with actual save")
# Clear the confirmation flag
session['awaiting_final_confirmation'] = False
session.modified = True
# Build and submit the plan
try:
# Log what we're about to save
logger.info(f"[WIZARD] Saving plan to database with data: {json.dumps(plan_data, indent=2)}")
# Use your EXISTING API submission
resp = post_program_creation(plan_data)
# Clear session on success
if isinstance(resp, dict) and not resp.get("error"):
jwt = session.get("jwt_token")
session.clear()
if jwt:
session["jwt_token"] = jwt
return {
"response": f"✅ **SUCCESS!** \n\nYour plan '{plan_data.get('plan_name')}' has been created successfully!\n\nYou can now create another plan or ask me questions about existing plans."
}
else:
error_msg = resp.get('error', 'Unknown error') if isinstance(resp, dict) else str(resp)
return {
"response": f"❌ Error saving plan: {error_msg}\n\nPlease check the details and try again, or type 'edit' to modify the plan."
}
except Exception as e:
logger.error(f"[WIZARD] Error submitting plan: {e}")
return {
"response": f"❌ Error saving plan: {str(e)}\n\nPlease try again or contact support."
}
# Handle cancel during confirmation
if user_msg_lower.strip() == 'cancel' and session.get('awaiting_final_confirmation'):
session['awaiting_final_confirmation'] = False
session.modified = True
#if user_id:
#save_user_state(user_id, dict(session))
return {
"response": "Plan submission cancelled. You can continue editing or type 'submit' again when ready."
}
# Check if user wants to edit
if any(word in user_msg_lower for word in ['edit', 'change', 'modify', 'update']):
# If just "edit" with no details, ask what to change
if user_msg_lower.strip() in ['edit', 'modify', 'change', 'update']:
return {
"response": "What would you like to change? Please specify the field and new value.\n\nExample: 'Change plan name to Q4 Sales Champions' or 'Update commission to 10%'"
}
# Try to extract field and value from edit commands
field_updated = False
# Improved patterns to handle multi-word field names
patterns = [
r'change\s+(?:the\s+)?(.+?)\s+to\s+(.+)', # "change [the] plan name to X"
r'update\s+(?:the\s+)?(.+?)\s+to\s+(.+)', # "update [the] commission to X"
r'(.+?)\s*=\s*(.+)', # "plan_name = X"
r'(.+?)\s*:\s*(.+)' # "plan_name: X"
]
import re
for pattern in patterns:
match = re.search(pattern, user_msg_lower)
if match:
raw_field = match.group(1).strip()
value = match.group(2).strip()
# Clean up field name - remove articles and extra spaces
raw_field = raw_field.replace('the ', '').replace(' ', '_')
# Map common field variations to actual field names
field_map = {
'name': 'plan_name',
'plan_name': 'plan_name',
'period': 'plan_period',
'plan_period': 'plan_period',
'commission': 'commission_structure',
'commission_structure': 'commission_structure',
'bonus': 'bonus_rules',
'bonus_rules': 'bonus_rules',
'target': 'sales_target',
'sales_target': 'sales_target',
'quota': 'quota',
'territory': 'territory',
'tiers': 'tiers',
'effective_dates': 'effective_dates',
'date': 'effective_dates',
'dates': 'effective_dates',
'effective_date': 'effective_dates',
'validity': 'effective_dates',
'valid_from': 'effective_dates',
'valid_to': 'effective_dates'
}
field = field_map.get(raw_field)
if field:
# Store old value for display
old_value = plan_data.get(field, 'Not set')
# Update the field based on type
if field in ['quota', 'sales_target']:
# Convert to integer for numeric fields
try:
plan_data[field] = int(value.replace(',', '').replace('$', ''))
except:
plan_data[field] = value
else:
# For text fields, preserve original case from user input
# Extract the actual value from original message (not lowercase)
original_match = re.search(pattern.replace('(.+?)', '(.+?)').replace('(.+)', '(.+)'), user_msg, re.IGNORECASE)
if original_match:
plan_data[field] = original_match.group(2).strip()
else:
plan_data[field] = value
session['plan_data'] = plan_data
session.modified = True
field_updated = True
logger.info(f"[WIZARD] Updated {field} from '{old_value}' to '{plan_data[field]}'")
# Show updated summary
summary = format_plan_summary(plan_data)
return {
"response": f"✏️ Updated {field.replace('_', ' ')} from '{old_value}' to: {plan_data[field]}\n\n{summary}\n\n✅ Type 'submit' to save this plan, or 'edit' to make more changes."
}
else:
logger.warning(f"[WIZARD] Could not map field '{raw_field}' to a known field")
break
if not field_updated:
# Couldn't parse the edit command
return {
"response": "I couldn't understand what you want to change. Please use format like:\n- 'Change plan name to Q4 Champions'\n- 'Change the commission to 10%'\n- 'Update quota to 500000'\n- 'plan_name = Q4 Champions'"
}
# PRIMARY APPROACH: Try NLP extraction FIRST
if not user_msg_lower.startswith(('change', 'update', 'edit')):
logger.info(f"[WIZARD] Starting field extraction for: {user_msg}")
# STEP 1: Try NLP extraction using Claude AI
nlp_success = False
try:
logger.info(f"[WIZARD] Attempting NLP extraction...")
result = extract_plan_struct_from_text(user_msg, mcp_client.claude_complete)
logger.info(f"[WIZARD] NLP extraction result: {result}")
if result["status"] == "ok" and result["extracted"]:
# Merge extracted fields with existing plan data
for key, value in result["extracted"].items():
if key == 'structure': # Skip bogus fields
continue
if value and str(value).strip(): # Only update non-empty values
plan_data[key] = value
logger.info(f"[WIZARD] NLP extracted {key}: {value}")
nlp_success = True
except Exception as e:
logger.error(f"[WIZARD] NLP extraction failed: {e}")
# STEP 2: If NLP failed, fallback to regex patterns
if not nlp_success:
logger.info(f"[WIZARD] NLP failed, using regex fallback...")
import re
# Extract Q4 2025 type patterns
period_match = re.search(r'(Q[1-4]\s*\d{4})', user_msg, re.IGNORECASE)
if period_match:
plan_data['plan_period'] = period_match.group(1)
logger.info(f"[WIZARD-REGEX] Extracted period: {period_match.group(1)}")
# Extract quota
quota_match = re.search(r'quota[\s:]*(\d+)', user_msg, re.IGNORECASE)
if quota_match:
plan_data['quota'] = int(quota_match.group(1))
logger.info(f"[WIZARD-REGEX] Extracted quota: {quota_match.group(1)}")
# Extract target
target_match = re.search(r'target[\s:]*(\d+)', user_msg, re.IGNORECASE)
if target_match:
plan_data['sales_target'] = int(target_match.group(1))
logger.info(f"[WIZARD-REGEX] Extracted target: {target_match.group(1)}")
# Extract plan name - improved patterns for "Ash_tst2 is plan name"
if 'plan name' in user_msg_lower or 'name is' in user_msg_lower:
name_patterns = [
r'([A-Za-z0-9_]+)\s+is\s+plan\s+name', # "Ash_tst2 is plan name"
r'plan\s+name\s+is\s+([A-Za-z0-9_\s]+)', # "plan name is XYZ"
r'name\s+is\s+([A-Za-z0-9_\s]+)', # "name is XYZ"
r'called\s+([A-Za-z0-9_\s]+)', # "called XYZ"
]
for pattern in name_patterns:
name_match = re.search(pattern, user_msg, re.IGNORECASE)
if name_match:
plan_data['plan_name'] = name_match.group(1).strip()
logger.info(f"[WIZARD-REGEX] Extracted plan name: {plan_data['plan_name']}")
break
# Extract territory - improved patterns for "territory is north"
if 'territory' in user_msg_lower:
territory_patterns = [
r'territory\s+is\s+([A-Za-z]+)', # "territory is north"
r'and\s+territory\s+is\s+([A-Za-z]+)', # "and territory is north"
r',\s*territory\s+([A-Za-z]+)', # ", territory north"
]
for pattern in territory_patterns:
territory_match = re.search(pattern, user_msg, re.IGNORECASE)
if territory_match:
plan_data['territory'] = territory_match.group(1).strip()
logger.info(f"[WIZARD-REGEX] Extracted territory: {plan_data['territory']}")
break
# Extract tiered structure
if 'tiered' in user_msg_lower or '%' in user_msg:
tiers = []
tier_patterns = re.findall(r'(\d+)%\s*(below|above|for|at|over)?\s*(quota|target|\d+)?', user_msg, re.IGNORECASE)
for rate, condition, threshold in tier_patterns:
tier_info = {'rate': f"{rate}%"}
if condition:
if 'below' in condition.lower():
tier_info['threshold'] = 'Below quota'
elif 'above' in condition.lower() or 'over' in condition.lower():
tier_info['threshold'] = 'Above quota'
tiers.append(tier_info)
if tiers:
plan_data['tiers'] = tiers
logger.info(f"[WIZARD-REGEX] Extracted tiers: {tiers}")
# Extract bonus rules
bonus_match = re.search(r'bonus\s+(\d+)\s+for\s+exceeding\s+(\d+)%?', user_msg, re.IGNORECASE)
if bonus_match:
plan_data['bonus_rules'] = f"${bonus_match.group(1)} bonus for exceeding {bonus_match.group(2)}% of target"
logger.info(f"[WIZARD-REGEX] Extracted bonus: {plan_data['bonus_rules']}")
# Extract dates
date_pattern = r'(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\s+\d{1,2}\s+(?:to|through|-)\s+(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\s+\d{1,2}\s+\d{4}'
date_match = re.search(date_pattern, user_msg, re.IGNORECASE)
if date_match:
date_str = date_match.group(0)
parts = re.split(r'\s+(?:to|through|-)\s+', date_str, re.IGNORECASE)
if len(parts) == 2:
plan_data['effective_dates'] = {
'start': '2025-01-01',
'end': '2025-03-31'
}
logger.info(f"[WIZARD-REGEX] Extracted dates: {plan_data['effective_dates']}")
# Save updated plan data
session["plan_data"] = plan_data
session.modified = True
# Show updated summary
summary = format_plan_summary(plan_data)
# Check what's still missing
all_fields = [
'plan_name', 'plan_period', 'territory', 'quota',
'commission_structure', 'tiers', 'bonus_rules',
'sales_target', 'effective_dates'
]
still_missing = [f for f in all_fields if not plan_data.get(f)]
logger.info(f"[WIZARD] Still missing fields: {still_missing}")
if not still_missing or len(still_missing) <= 2:
return {
#"response": f"Perfect! Here's your complete plan:\n\n{summary}\n\n✅ **Ready to submit!**\nType 'submit' to save this plan, or 'edit' to make changes."
"response": summary
}
else:
missing_str = ', '.join([f.replace('_', ' ') for f in still_missing[:3]])
return {
"response": f"Great! I've updated your plan:\n\n{summary}\n\nℹ️ Still missing: {missing_str}\n\nYou can provide these details, type 'submit' to save with current info, or 'edit' to change values."
}
# Fallback for no plan data
return {
"response": "No active plan creation session. Please type 'create plan' to start creating a new commission plan."
}
except Exception as e:
logger.error(f"[WIZARD] Critical error in handle_message_in_flow: {e}", exc_info=True)
return {
"response": f"Sorry, there was an error processing your request. Please try again or type 'clear session' to start over."
}
def format_plan_summary(plan_data, show_all_fields=False):
"""
Format plan data into a Markdown summary for ReactMarkdown
Args:
plan_data: Dictionary containing plan information
show_all_fields: If True, show complete API payload with all defaults
"""
lines = []
if not show_all_fields:
# NORMAL SUMMARY (during editing)
#lines.append("Perfect! Here's your complete plan:")
#lines.append("")
lines.append("## 📋 PLAN SUMMARY")
lines.append("")
field_labels = {
'plan_name': '📝 Plan Name',
'plan_period': '📅 Period',
'territory': '🌍 Territory',
'quota': '🎯 Quota',
'commission_structure': '💰 Commission Structure',
'tiers': '📊 Commission Tiers',
'bonus_rules': '🎁 Bonus Rules',
'sales_target': '📈 Sales Target',
'effective_dates': '📆 Effective Dates'
}
for field, label in field_labels.items():
value = plan_data.get(field, None)
is_empty = (
value is None or
value == '' or
value == 'Not specified' or
(isinstance(value, list) and len(value) == 0) or
(isinstance(value, dict) and not any(value.values()))
)
if is_empty:
continue
if field == 'tiers':
if isinstance(value, list) and value:
lines.append(f"**{label}:**")
for tier in value:
if isinstance(tier, dict):
threshold = tier.get('threshold', tier.get('min', 'Unknown'))
rate = tier.get('rate', tier.get('commission', 'Unknown'))
rate_str = str(rate)
if not rate_str.endswith('%'):
rate_str = rate_str + '%'
lines.append(f"- {threshold}: {rate_str}")
lines.append("")
else:
'''if field == 'effective_dates':
if isinstance(value, dict) and any(value.values()):
start = value.get('start', 'Not set')
end = value.get('end', 'Not set')
value = f"{start} to {end}"
else:
value = '*Not specified*'''
if field == 'effective_dates':
# ✅ FIX: Handle both dict and string formats
if isinstance(value, dict):
if any(value.values()):
start = value.get('start', 'Not set')