Repository navigation
Expand file tree
/
Copy pathdatabase.py
More file actions
2195 lines (1773 loc) · 84.4 KB
/
Copy pathdatabase.py
File metadata and controls
2195 lines (1773 loc) · 84.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
from supabase import create_client, Client
from supabase.client import AsyncClient, create_async_client
from pydantic import BaseModel, validator
from typing import Any, Dict, List, Optional, Union
import uuid
from process_definition import ProcessDefinition, load_process_definition, UIDefinition
import psycopg2
from psycopg2.extras import RealDictCursor
from fastapi import HTTPException
from decimal import Decimal
from datetime import datetime, timedelta, timezone
import pytz
from contextvars import ContextVar
from dotenv import load_dotenv
import socket
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from supabase_config import get_supabase_key, get_supabase_url
db_config_var = ContextVar('db_config', default={})
supabase_client_var = ContextVar('supabase', default=None)
DEFAULT_TENANT_ID = (os.getenv("DEFAULT_TENANT_ID") or "skt").strip()
subdomain_var = ContextVar('subdomain', default=DEFAULT_TENANT_ID)
DEFAULT_DB_CONFIG = {
"dbname": "postgres",
"user": "supabase_admin",
"password": "pi-system-supabase",
"host": "pi-system-supabase-supabase-db",
"port": "5432",
}
def setting_database():
try:
if os.getenv("ENV") != "production":
# Don't override env vars provided by runtime (Docker/K8s).
# Local dev still works because .env fills missing values.
load_dotenv(override=False)
supabase_url = get_supabase_url()
supabase_key = get_supabase_key()
supabase: Client = create_client(supabase_url, supabase_key)
supabase_client_var.set(supabase)
db_config = {
"dbname": os.getenv("DB_NAME") or DEFAULT_DB_CONFIG["dbname"],
"user": os.getenv("DB_USER") or DEFAULT_DB_CONFIG["user"],
"password": os.getenv("DB_PASSWORD") or DEFAULT_DB_CONFIG["password"],
"host": os.getenv("DB_HOST") or DEFAULT_DB_CONFIG["host"],
"port": os.getenv("DB_PORT") or DEFAULT_DB_CONFIG["port"]
}
db_config_var.set(db_config)
except Exception as e:
print(f"Database configuration error: {e}")
setting_database()
async def update_tenant_id(subdomain):
try:
if not subdomain:
raise Exception("Unable to configure Tenant ID.")
subdomain_var.set(subdomain)
except Exception as e:
print(f"An error occurred: {e}")
def load_sql_from_file(file_path):
"""Load SQL commands from a text file."""
with open(file_path, 'r', encoding='utf-8') as file: # UTF-8 인코딩으로 파일을 열기
return file.read()
# def update_db():
# try:
# db_config = db_config_var.get()
# # Establish a connection to the database
# connection = psycopg2.connect(**db_config)
# cursor = connection.cursor(cursor_factory=RealDictCursor)
# # Load SQL from file
# sql_query = load_sql_from_file('update_db_sql.txt')
# cursor.execute(sql_query)
# connection.commit()
# return "Tables created successfully."
# except Exception as e:
# print(f"An error occurred: {e}")
# finally:
# if connection:
# connection.close()
def insert_usage(usage_data: dict):
try:
supabase = supabase_client_var.get()
if supabase is None:
raise HTTPException(status_code=500, detail="Supabase 클라이언트가 요청에 대해 구성되지 않았습니다.")
if not usage_data:
raise HTTPException(status_code=400, detail="사용량 데이터가 제공되지 않았습니다.")
if not usage_data.get('serviceId'):
raise HTTPException(status_code=400, detail="서비스 ID가 제공되지 않았습니다.")
if not usage_data.get('userId'):
raise HTTPException(status_code=400, detail="사용자 ID가 제공되지 않았습니다.")
if not usage_data.get('startAt'):
raise HTTPException(status_code=400, detail="사용 시작 시점이 제공되지 않았습니다.")
if not usage_data.get('usage'):
raise HTTPException(status_code=400, detail="메타데이터 제공되지 않았습니다.")
if not usage_data.get('tenantId'):
usage_data['tenantId'] = subdomain_var.get()
# Procedure 호출
# return supabase.rpc("insert_usage_from_payload", usage_data).execute()
return supabase.rpc("insert_usage_from_payload", {"p_payload": usage_data}).execute()
except Exception as e:
raise HTTPException(status_code=500, detail=f"사용량 삽입 중 오류가 발생했습니다: {e}")
def db_client_signin(user_info: dict):
try:
supabase = supabase_client_var.get()
if supabase is None:
raise Exception("Supabase client is not configured for this request")
response = supabase.auth.sign_in_with_password({ "email": user_info.get('email'), "password": user_info.get('password') })
supabase.auth.set_session(response.session.access_token, response.session.refresh_token)
return response
except Exception as e:
raise HTTPException(status_code=500, detail=f"An error occurred while signing in: {e}")
def execute_sql(sql_query):
"""
Connects to a PostgreSQL database and executes the given SQL query.
Args:
sql_query (str): The SQL query to execute.
Returns:
list: A list of dictionaries representing the rows returned by the query.
"""
try:
db_config = db_config_var.get()
# Establish a connection to the database
connection = psycopg2.connect(**db_config)
cursor = connection.cursor(cursor_factory=RealDictCursor)
# Execute the SQL query
cursor.execute(sql_query)
# If the query was a SELECT statement, fetch the results
if sql_query.strip().upper().startswith("SELECT"):
result = cursor.fetchall()
else:
# Commit the transaction if the query modified the database
connection.commit()
result = "Table Created"
return result
except Exception as e:
return(f"An error occurred while executing the SQL query: {e}")
finally:
# Close the cursor and connection to clean up
if connection:
connection.close()
def fetch_all_process_definitions():
try:
supabase = supabase_client_var.get()
if supabase is None:
raise Exception("Supabase client is not configured for this request")
subdomain = subdomain_var.get()
response = supabase.table('proc_def').select('*').eq('tenant_id', subdomain).execute()
return response.data
except Exception as e:
raise HTTPException(status_code=500, detail=f"An error occurred while fetching process definitions: {e}")
def fetch_all_process_definition_ids():
try:
supabase = supabase_client_var.get()
if supabase is None:
raise Exception("Supabase client is not configured for this request")
subdomain = subdomain_var.get()
response = supabase.table('proc_def').select('id').eq('tenant_id', subdomain).execute()
return response.data
except Exception as e:
raise HTTPException(status_code=500, detail=f"An error occurred while fetching process definition ids: {e}")
def generate_create_statement_for_table(table_name):
"""
Generates a CREATE TABLE statement for the given table name by fetching its current schema.
Args:
table_name (str): The name of the table for which to generate the CREATE statement.
Returns:
str: A CREATE TABLE statement as a string, or an error message if the operation fails.
"""
try:
db_config = db_config_var.get()
# Establish a connection to the database
connection = psycopg2.connect(**db_config)
cursor = connection.cursor()
# Fetch the table schema
cursor.execute("SELECT column_name, data_type, character_maximum_length FROM information_schema.columns WHERE table_name = %s", (table_name,))
columns = cursor.fetchall()
if not columns:
return f"No existing table"
# Generate the CREATE TABLE statement
create_statement = f"CREATE TABLE {table_name} (\n"
for column in columns:
column_name, data_type, max_length = column
column_def = f"{column_name} {data_type}"
if max_length:
column_def += f"({max_length})"
create_statement += f" {column_def},\n"
# Remove the last comma and add the closing parenthesis
create_statement = create_statement.rstrip(',\n') + "\n);"
return create_statement
except Exception as e:
return(f"An error occurred while generating CREATE statement for table {table_name}: {e}")
finally:
# Close the cursor and connection to clean up
if connection:
connection.close()
def fetch_process_definition(def_id, tenant_id: Optional[str] = None):
"""
Fetches the process definition from the 'proc_def' table based on the given definition ID.
Args:
def_id (str): The ID of the process definition to fetch.
Returns:
dict: The process definition as a JSON object if found, else None.
"""
try:
supabase = supabase_client_var.get()
if supabase is None:
raise Exception("Supabase client is not configured for this request")
subdomain = subdomain_var.get()
if not tenant_id:
tenant_id = subdomain
# definition 만 사용 — tobe/executable 등 분리 컬럼(대용량 To-Be 작업본)을 끌어오지 않는다
response = supabase.table('proc_def').select('definition').eq('id', def_id.lower()).eq('tenant_id', tenant_id).execute()
# Check if the response contains data
if response.data:
# Assuming the first match is the desired one since ID should be unique
process_definition = response.data[0].get('definition', None)
return process_definition
else:
return None
except Exception as e:
raise HTTPException(status_code=404, detail=f"No process definition found with ID {def_id}: {e}")
def fetch_process_definition_by_version(
def_id: str,
version_tag: Optional[str] = None,
version: Optional[Union[str, int]] = None,
tenant_id: Optional[str] = None,
arcv_id: Optional[str] = None,
):
"""
실행 정의(프로세스 definition)를 버전 규칙에 따라 조회합니다.
호환/명시 우선순위:
- arcv_id 가 주어지면: 해당 proc_def_arcv 버전을 최우선으로 조회 (기존 동작 유지)
- version_tag + version 이 주어지면: proc_def_version에서 해당 tag/version을 우선 조회
기본(명시 버전이 없을 때) 동작은 TS 방식으로 통일:
1) proc_def.prod_version 이 있으면 해당 버전을 우선 조회
- prod_version은 기존 운영상 arcv_id로 저장되는 경우가 있어 proc_def_arcv로 먼저 시도하고,
실패 시 proc_def_version.version 매칭도 시도
2) 최신 major(version_tag='major')
3) 최신 minor(version_tag='minor')
4) proc_def.definition (현재 정의)
"""
# 공통 모듈로 로직을 위임하여 중복 제거
from proc_def_versioning import fetch_process_definition_by_version_ts_style
if not def_id:
return None
supabase = supabase_client_var.get()
if supabase is None:
raise Exception("Supabase client is not configured for this request")
subdomain = subdomain_var.get()
if not tenant_id:
tenant_id = subdomain
def fetch_arcv_rows(arcv: str) -> List[dict]:
return fetch_process_definition_version_by_arcv_id(def_id, arcv, tenant_id) or []
return fetch_process_definition_by_version_ts_style(
supabase=supabase,
def_id=def_id,
tenant_id=tenant_id,
version_tag=version_tag,
version=version,
arcv_id=arcv_id,
fetch_arcv_rows=fetch_arcv_rows,
)
def upsert_process_definition(definition: dict, tenant_id: Optional[str] = None):
try:
supabase = supabase_client_var.get()
if supabase is None:
raise Exception("Supabase client is not configured for this request")
if not tenant_id:
tenant_id = subdomain_var.get()
process_definition_id = definition.get('id')
definition['tenant_id'] = tenant_id
# 기존 행 보존 필드만 조회 (uuid/bpmn/isdeleted) — 분리 컬럼(tobe/executable)은 upsert 페이로드에 없어 보존됨
process_definition = supabase.table('proc_def').select('uuid, bpmn, isdeleted').eq('id', process_definition_id).eq('tenant_id', tenant_id).execute()
if process_definition.data:
existing_data = process_definition.data[0]
definition['uuid'] = existing_data.get('uuid')
definition['bpmn'] = existing_data.get('bpmn')
definition['isdeleted'] = existing_data.get('isdeleted', False)
return supabase.table('proc_def').upsert(definition).execute()
else:
definition.pop('uuid', None)
return supabase.table('proc_def').insert(definition).execute()
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error upserting process definition with ID {process_definition_id}: {e}")
def fetch_process_definition_versions(def_id, tenant_id: Optional[str] = None):
try:
supabase = supabase_client_var.get()
if supabase is None:
raise Exception("Supabase client is not configured for this request")
subdomain = subdomain_var.get()
if not tenant_id:
tenant_id = subdomain
response = supabase.table('proc_def_version').select('*').eq('proc_def_id', def_id.lower()).eq('tenant_id', tenant_id).execute()
return response.data
except Exception as e:
raise HTTPException(status_code=404, detail=f"No process definition version found with ID {def_id}: {e}")
def fetch_process_definition_version_by_arcv_id(def_id, arcv_id, tenant_id: Optional[str] = None):
try:
supabase = supabase_client_var.get()
if supabase is None:
raise Exception("Supabase client is not configured for this request")
subdomain = subdomain_var.get()
if not tenant_id:
tenant_id = subdomain
response = supabase.table('proc_def_arcv').select('*').eq('proc_def_id', def_id.lower()).eq('arcv_id', arcv_id).eq('tenant_id', tenant_id).execute()
# versions are saved in proc_def_version (process-gpt's save path); proc_def_arcv is legacy
return response.data or _pinned_version_rows(supabase, def_id, arcv_id, tenant_id)
except Exception as e:
raise HTTPException(status_code=404, detail=f"No process definition version found with ID {def_id} and version {arcv_id}: {e}")
def _pinned_version_rows(supabase, def_id, arcv_id, tenant_id) -> List[dict]:
"""A saved version (proc_def_version.arcv_id) an instance was pinned to when it started.
The instance keeps running on that version once a newer version has been saved; while it is
still the newest saved version, nothing is returned and the current definition
(proc_def.definition) is used as before. Drafts (e.g. a mining proposal) never pin.
"""
if not arcv_id or not def_id:
return []
rows = (
supabase.table("proc_def_version").select("*")
.eq("proc_def_id", def_id.lower()).eq("arcv_id", arcv_id).eq("tenant_id", tenant_id)
.execute().data
or []
)
rows = [r for r in rows if not r.get("is_draft") and r.get("definition")]
if not rows or not rows[0].get("timeStamp"):
return []
newer = (
supabase.table("proc_def_version").select("arcv_id,is_draft")
.eq("proc_def_id", def_id.lower()).eq("tenant_id", tenant_id)
.gt("timeStamp", rows[0]["timeStamp"])
.execute().data
or []
)
return rows[:1] if any(not r.get("is_draft") for r in newer) else []
def _instance_version(process_instance, supabase, tenant_id) -> Optional[str]:
"""The version an instance runs on: stamped once, when it starts, and kept after that.
Re-stamping the latest version on every save moved running instances onto a version saved
after they started (their next steps then followed the new definition).
"""
pinned = getattr(process_instance, "proc_def_version", None)
if pinned:
return pinned
try:
cur = (
supabase.table("bpm_proc_inst").select("proc_def_version")
.eq("proc_inst_id", process_instance.proc_inst_id).eq("tenant_id", tenant_id)
.limit(1).execute().data
or []
)
if cur and cur[0].get("proc_def_version"):
return cur[0]["proc_def_version"]
except Exception as e:
print(f"[WARN] instance version lookup failed for {process_instance.proc_inst_id}: {e}")
rows = (
supabase.table("proc_def_version").select("arcv_id,is_draft")
.eq("proc_def_id", process_instance.get_def_id().lower()).eq("tenant_id", tenant_id)
# newest = saved last; version is text ('9.0' > '10.0'), so ordering by it pinned new instances to 9.0
.order("timeStamp", desc=True).execute().data
or []
)
released = [r for r in rows if not r.get("is_draft")]
return released[0].get("arcv_id") if released else None
def fetch_process_definition_latest_version(def_id, tenant_id: Optional[str] = None):
try:
supabase = supabase_client_var.get()
if supabase is None:
raise Exception("Supabase client is not configured for this request")
subdomain = subdomain_var.get()
if not tenant_id:
tenant_id = subdomain
response = supabase.table('proc_def_version').select('*').eq('proc_def_id', def_id.lower()).eq('tenant_id', tenant_id).order('timeStamp', desc=True).execute() # newest saved, not text-max version
if response.data:
return response.data[0]
else:
return None
except Exception as e:
raise HTTPException(status_code=404, detail=f"No process definition latest version found with ID {def_id}: {e}")
def fetch_all_ui_definition():
try:
supabase = supabase_client_var.get()
if supabase is None:
raise Exception("Supabase client is not configured for this request")
subdomain = subdomain_var.get()
response = supabase.table('form_def').select('*').eq('tenant_id', subdomain).execute()
if response.data:
return response.data
else:
return []
except Exception as e:
raise HTTPException(status_code=500, detail=f"An error occurred while fetching UI definitions: {e}")
def fetch_ui_definition(def_id):
try:
supabase = supabase_client_var.get()
if supabase is None:
raise Exception("Supabase client is not configured for this request")
subdomain = subdomain_var.get()
response = supabase.table('form_def').select('*').eq('id', def_id.lower()).eq('tenant_id', subdomain).execute()
if response.data:
# Assuming the first match is the desired one since ID should be unique
ui_definition = UIDefinition(**response.data[0])
return ui_definition
else:
return None
except Exception as e:
raise HTTPException(status_code=404, detail=f"No UI definition found with ID {def_id}: {e}")
def fetch_ui_definition_by_activity_id(proc_def_id, activity_id, tenant_id: Optional[str] = None):
try:
supabase = supabase_client_var.get()
if supabase is None:
raise Exception("Supabase client is not configured for this request")
subdomain = subdomain_var.get()
if not tenant_id:
tenant_id = subdomain
response = supabase.table('form_def').select('*').eq('proc_def_id', proc_def_id).eq('activity_id', activity_id).eq('tenant_id', tenant_id).execute()
if response.data:
# Assuming the first match is the desired one since ID should be unique
ui_definition = UIDefinition(**response.data[0])
return ui_definition
else:
return None
except Exception as e:
raise HTTPException(status_code=404, detail=f"No UI definition found with ID {proc_def_id}: {e}")
class ProcessInstance(BaseModel):
proc_inst_id: str
proc_inst_name: Optional[str] = None
role_bindings: Optional[List[Dict[str, Any]]] = []
current_activity_ids: Optional[List[str]] = []
participants: Optional[List[str]] = []
variables_data: Optional[List[Dict[str, Any]]] = []
process_definition: ProcessDefinition = None # Add a reference to ProcessDefinition
status: str = None
tenant_id: str
proc_def_version: Optional[str] = None
execution_scope: Optional[str] = None
class Config:
extra = "allow"
def __init__(self, **data):
super().__init__(**data)
def_id = self.get_def_id()
tenant_id = self.tenant_id
# proc_def_version(arcv_id)가 있으면 해당 버전 정의를 우선 사용하되,
# 레거시 데이터(예: "xxx_2.0")처럼 arcv_id가 아닌 값이 들어올 수 있어 폴백을 둡니다.
definition_json = None
if getattr(self, "proc_def_version", None):
definition_json = fetch_process_definition_by_version(
def_id,
tenant_id=tenant_id,
arcv_id=self.proc_def_version,
)
# arcv_id 기반 조회 실패 시, instance에 버전 태그/버전이 있으면 그걸로 재시도
if not definition_json and getattr(self, "version_tag", None) and getattr(self, "version", None):
definition_json = fetch_process_definition_by_version(
def_id,
tenant_id=tenant_id,
version_tag=self.version_tag,
version=self.version,
)
# 최종 폴백: 최신/프로덕션 규칙 기반 조회
if not definition_json:
definition_json = fetch_process_definition_by_version(def_id, tenant_id=tenant_id)
if not definition_json:
raise ValueError(
f"Process definition not found for def_id={def_id}, tenant_id={tenant_id}, "
f"proc_def_version={getattr(self, 'proc_def_version', None)}, "
f"version_tag={getattr(self, 'version_tag', None)}, version={getattr(self, 'version', None)}"
)
self.process_definition = load_process_definition(definition_json) # Load ProcessDefinition
def get_def_id(self):
# inst_id 예시: "company_entrance.123e4567-e89b-12d3-a456-426614174000"
# 여기서 "company_entrance"가 프로세스 정의 ID입니다.
return self.proc_inst_id.split(".")[0]
def get_data(self):
# Return all process variable values as a map
variable_map = {}
for variable in self.process_definition.data:
variable_name = variable.name
variable_map[variable_name] = getattr(self, variable_name, None)
return variable_map
class WorkItem(BaseModel):
id: str
user_id: Optional[str]
username: Optional[str] = None
proc_inst_id: Optional[str] = None
proc_def_id: Optional[str] = None
activity_id: str
activity_name: str
start_date: Optional[datetime] = None
end_date: Optional[datetime] = None
due_date: Optional[datetime] = None
status: str
description: Optional[str] = None
tool: Optional[str] = None
tenant_id: str
reference_ids: Optional[List[str]] = []
assignees: Optional[List[Dict[str, Any]]] = []
duration: Optional[int] = None
output: Optional[Dict[str, Any]] = {}
retry: Optional[int] = 0
consumer: Optional[str] = None
log: Optional[str] = None
agent_mode: Optional[str] = None
agent_orch: Optional[str] = None
feedback: Optional[List[Dict[str, Any]]] = []
temp_feedback: Optional[str] = None
execution_scope: Optional[str] = None
rework_count: Optional[int] = 0
project_id: Optional[str] = None
root_proc_inst_id: Optional[str] = None
query: Optional[str] = None
@validator('start_date', 'end_date', 'due_date', pre=True)
def parse_datetime(cls, value):
if isinstance(value, str):
try:
return datetime.fromisoformat(value).replace(tzinfo=None)
except ValueError:
return datetime.strptime(value, "%Y-%m-%d %H:%M:%S")
return value
class Config:
json_encoders = {
datetime: lambda dt: dt.strftime("%Y-%m-%d %H:%M:%S")
}
def fetch_process_instance(full_id: str, tenant_id: Optional[str] = None) -> Optional[ProcessInstance]:
try:
if full_id == "new" or '.' not in full_id:
return None
if not full_id:
raise HTTPException(status_code=404, detail="Instance Id should be provided")
supabase = supabase_client_var.get()
if supabase is None:
raise Exception("Supabase client is not configured for this request")
subdomain = subdomain_var.get()
if not tenant_id:
tenant_id = subdomain
response = supabase.table('bpm_proc_inst').select("*").eq('proc_inst_id', full_id).eq('tenant_id', tenant_id).execute()
if response.data:
process_instance_data = response.data[0]
process_instance = ProcessInstance(**process_instance_data)
return process_instance
else:
return None
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)) from e
def insert_process_instance(process_instance_data: dict, tenant_id: Optional[str] = None):
try:
supabase = supabase_client_var.get()
if supabase is None:
raise Exception("Supabase client is not configured for this request")
if not tenant_id:
tenant_id = subdomain_var.get()
process_instance_data['tenant_id'] = tenant_id
return supabase.table('bpm_proc_inst').upsert(process_instance_data).execute()
except Exception as e:
raise HTTPException(status_code=404, detail=str(e)) from e
def upsert_process_instance(process_instance: ProcessInstance, tenant_id: Optional[str] = None) -> (bool, ProcessInstance):
if 'END_PROCESS' in process_instance.current_activity_ids or 'endEvent' in process_instance.current_activity_ids or 'end_event' in process_instance.current_activity_ids or process_instance.status == 'COMPLETED':
process_instance.current_activity_ids = []
status = 'COMPLETED'
else:
status = 'RUNNING'
process_instance_data = process_instance.dict(exclude={'process_definition'}) # Convert Pydantic model to dict
process_instance_data = convert_decimal(process_instance_data)
try:
supabase = supabase_client_var.get()
if supabase is None:
raise Exception("Supabase client is not configured for this request")
if not tenant_id:
tenant_id = subdomain_var.get()
# pinned at start: a running instance keeps its version, a new one gets the latest
arcv_id = _instance_version(process_instance, supabase, tenant_id)
response = supabase.table('bpm_proc_inst').upsert({
'proc_inst_id': process_instance.proc_inst_id,
'proc_inst_name': process_instance.proc_inst_name,
'current_activity_ids': process_instance.current_activity_ids,
'participants': process_instance.participants,
'role_bindings': process_instance.role_bindings,
'variables_data': process_instance.variables_data,
'status': status,
'proc_def_id': process_instance.get_def_id(),
'proc_def_version': arcv_id,
'tenant_id': tenant_id
}).execute()
success = bool(response.data)
return success, process_instance
except Exception as e:
raise HTTPException(status_code=404, detail=str(e)) from e
def fetch_table_columns(table_name: str) -> List[str]:
"""
Fetches the column names of a given table from the database.
Args:
table_name (str): The name of the table to fetch columns from.
Returns:
List[str]: A list of column names.
"""
try:
db_config = db_config_var.get()
connection = psycopg2.connect(**db_config)
cursor = connection.cursor()
cursor.execute("SELECT column_name FROM information_schema.columns WHERE table_name = %s", (table_name,))
columns = cursor.fetchall()
return [column[0] for column in columns]
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to fetch columns for table {table_name}: {e}")
finally:
if connection:
connection.close()
def convert_decimal(data):
for key, value in data.items():
if isinstance(value, Decimal):
data[key] = float(value)
return data
def fetch_organization_chart(tenant_id: Optional[str] = None):
try:
supabase = supabase_client_var.get()
if supabase is None:
raise Exception("Supabase client is not configured for this request")
subdomain = subdomain_var.get()
if not tenant_id:
tenant_id = subdomain
response = supabase.table("configuration").select("*").eq('key', 'organization').eq('tenant_id', tenant_id).execute()
# Check if the response contains data
if response.data:
# Assuming the first match is the desired one since ID should be unique
value = response.data[0].get('value', None)
organization_chart = value.get('chart', None)
return organization_chart
else:
return None
except Exception as e:
raise HTTPException(status_code=404, detail=f"Failed to fetch organization chart: {e}")
def fetch_process_instance_list(user_id: str, process_definition_id: Optional[str] = None) -> Optional[List[ProcessInstance]]:
try:
supabase = supabase_client_var.get()
if supabase is None:
raise Exception("Supabase client is not configured for this request")
subdomain = subdomain_var.get()
if process_definition_id:
response = supabase.table('bpm_proc_inst').select("*").eq('tenant_id', subdomain).eq('proc_def_id', process_definition_id).filter('participants', 'cs', '{' + user_id + '}').execute()
else:
response = supabase.table('bpm_proc_inst').select("*").eq('tenant_id', subdomain).filter('participants', 'cs', '{' + user_id + '}').execute()
if response.data:
return [ProcessInstance(**item) for item in response.data]
else:
return None
except Exception as e:
raise HTTPException(status_code=404, detail=str(e)) from e
def fetch_todolist_by_user_id(user_id: str) -> Optional[List[WorkItem]]:
try:
supabase = supabase_client_var.get()
if supabase is None:
raise Exception("Supabase client is not configured for this request")
subdomain = subdomain_var.get()
response = supabase.table('todolist').select("*").eq('user_id', user_id).eq('tenant_id', subdomain).execute()
if response.data:
return [WorkItem(**item) for item in response.data]
else:
return None
except Exception as e:
raise HTTPException(status_code=404, detail=str(e)) from e
def fetch_todolist_by_proc_inst_id(proc_inst_id: str, tenant_id: Optional[str] = None) -> Optional[List[WorkItem]]:
try:
supabase = supabase_client_var.get()
if supabase is None:
raise Exception("Supabase client is not configured for this request")
subdomain = subdomain_var.get()
if not tenant_id:
tenant_id = subdomain
response = supabase.table('todolist').select("*").eq('proc_inst_id', proc_inst_id).eq('tenant_id', tenant_id).execute()
if response.data:
return [WorkItem(**item) for item in response.data]
else:
return None
except Exception as e:
raise HTTPException(status_code=404, detail=str(e)) from e
def fetch_workitem_by_proc_inst_and_activity(
proc_inst_id: str,
activity_id: str,
tenant_id: Optional[str] = None,
recent_only: Optional[bool] = True
) -> Union[WorkItem, List[WorkItem], None]:
try:
supabase = supabase_client_var.get()
if supabase is None:
raise Exception("Supabase client is not configured for this request")
subdomain = subdomain_var.get()
if not tenant_id:
tenant_id = subdomain
response = supabase.table('todolist').select("*").eq('proc_inst_id', proc_inst_id).eq('activity_id', activity_id).eq('tenant_id', tenant_id).execute()
if response.data:
if len(response.data) > 1 and recent_only:
# updated_at이 가장 최근이거나, updated_at이 같으면 rework_count가 가장 큰 항목을 최근 워크아이템으로 간주
def get_recent_key(item):
updated_at = item.get('updated_at')
rework_count = item.get('rework_count', 0)
if updated_at:
try:
if isinstance(updated_at, str):
updated_at = datetime.fromisoformat(updated_at.replace('Z', '+00:00')).replace(tzinfo=None)
elif hasattr(updated_at, 'replace'):
updated_at = updated_at.replace(tzinfo=None)
except (ValueError, TypeError, AttributeError):
updated_at = None
return (updated_at or datetime.min, rework_count)
most_recent_item = max(response.data, key=get_recent_key)
return WorkItem(**most_recent_item)
elif len(response.data) > 1 and not recent_only:
return [WorkItem(**item) for item in response.data]
elif len(response.data) == 1:
return WorkItem(**response.data[0])
else:
return None
except Exception as e:
raise HTTPException(status_code=404, detail=str(e)) from e
def fetch_workitem_by_id(workitem_id: str, tenant_id: Optional[str] = None) -> Optional[WorkItem]:
try:
supabase = supabase_client_var.get()
if supabase is None:
raise Exception("Supabase client is not configured for this request")
subdomain = subdomain_var.get()
if not tenant_id:
tenant_id = subdomain
response = supabase.table('todolist').select("*").eq('id', workitem_id).eq('tenant_id', tenant_id).execute()
if response.data and len(response.data) > 0:
return WorkItem(**response.data[0])
else:
return None
except Exception as e:
raise HTTPException(status_code=404, detail=str(e)) from e
def fetch_prev_task_ids(process_definition, current_activity_id: str, proc_inst_id: str) -> List[str]:
"""
현재 테스크의 시퀀스 정보를 이용해 바로 직전 테스크의 ID 목록을 반환합니다.
Args:
process_definition: 프로세스 정의 객체
current_activity_id: 현재 테스크의 ID
proc_inst_id: 프로세스 인스턴스 ID
Returns:
List[str]: 직전 테스크의 activity ID 목록
"""
prev_task_ids = []
prev_activities = process_definition.find_immediate_prev_activities(current_activity_id)
if prev_activities:
# 이전 액티비티들의 activity_id를 수집
for prev_activity in prev_activities:
prev_task_ids.append(prev_activity.id)
return prev_task_ids
def upsert_todo_workitems(process_instance_data, process_result_data, process_definition, tenant_id: Optional[str] = None):
try:
if not tenant_id:
tenant_id = subdomain_var.get()
initial_activity = next((activity for activity in process_definition.activities if process_definition.is_starting_activity(activity.id)), None)
if not initial_activity:
initial_activity = process_definition.find_initial_activity()
next_activities = [activity for activity in process_definition.activities if activity.id != initial_activity.id]
for activity in next_activities:
prev_activities = process_definition.find_prev_activities(activity.id, [])
start_date = datetime.now(pytz.timezone('Asia/Seoul'))
if prev_activities:
# 동일한 srcTrg를 가진 액티비티들 중 duration이 가장 큰 것만 남기기
srcTrg_groups = {}
for prev_activity in prev_activities:
if prev_activity.srcTrg not in srcTrg_groups:
srcTrg_groups[prev_activity.srcTrg] = []
srcTrg_groups[prev_activity.srcTrg].append(prev_activity)
# duration이 가장 큰 액티비티만 선택
filtered_activities = []
for activities in srcTrg_groups.values():
max_duration_activity = max(activities, key=lambda x: x.duration if x.duration is not None else 0)
filtered_activities.append(max_duration_activity)
reference_ids = fetch_prev_task_ids(process_definition, activity.id, process_instance_data['proc_inst_id'])
for prev_activity in filtered_activities:
start_date = start_date + timedelta(days=prev_activity.duration)
due_date = start_date + timedelta(days=activity.duration) if activity.duration else None
workitem = fetch_workitem_by_proc_inst_and_activity(process_instance_data['proc_inst_id'], activity.id, tenant_id)
if not workitem:
user_id = ""
assignees = []
if process_result_data['roleBindings']:
role_bindings = process_result_data['roleBindings']