File size: 7,277 Bytes
1b4b6d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9f689e
 
 
 
 
 
 
 
 
 
 
 
1b4b6d2
 
 
 
e9f689e
1b4b6d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
464123d
 
1b4b6d2
 
464123d
 
 
 
 
 
1b4b6d2
464123d
1b4b6d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
464123d
 
 
 
1b4b6d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import APIRouter, HTTPException, Depends
from pydantic import BaseModel
from typing import Optional, Dict, Any
from utils.db import safe_query, safe_execute
from api.auth import get_current_user
from engine.project_history import save_project, load_all_projects

router = APIRouter()

class SaveProjectReq(BaseModel):
    project_id: Optional[int] = None
    project_name: str
    state_data: Optional[Dict[str, Any]] = None
    boq_data: Optional[Dict[str, Any]] = None
    current_step: int = 1

@router.get("")
@router.get("/")
async def list_projects(current_user: dict = Depends(get_current_user)):
    projects = load_all_projects(current_user["id"])
    return projects

@router.get("/active")
async def get_active_project(project_id: Optional[int] = None, current_user: dict = Depends(get_current_user)):
    if project_id:
        df = safe_query("SELECT current_step, updated_at, state_data FROM qto_active_projects WHERE user_id=%s AND project_id=%s", (current_user["id"], project_id))
    else:
        df = safe_query("SELECT current_step, updated_at, state_data, project_id FROM qto_active_projects WHERE user_id=%s ORDER BY updated_at DESC LIMIT 1", (current_user["id"],))
    if df.empty:
        return {"has_active": False}
    row = df.iloc[0]

    import json as _json
    from api.routers.data_review import reconstruct_project_inputs
    raw = row["state_data"]
    state_data = _json.loads(raw) if isinstance(raw, str) else (raw or {})
    if state_data.get("current_step", 0) >= 3:
        reconstruct_project_inputs(state_data)
        safe_execute(
            "UPDATE qto_active_projects SET state_data=%s WHERE user_id=%s AND project_id=%s",
            (_json.dumps(state_data, ensure_ascii=False, default=str), current_user["id"], row.get("project_id") or project_id)
        )

    res = {
        "has_active": True,
        "current_step": int(row["current_step"]),
        "updated_at": row["updated_at"],
        "state_data": state_data
    }
    if "project_id" in row:
        res["project_id"] = int(row["project_id"])
    return res

@router.delete("/active")
async def clear_active_project(project_id: Optional[int] = None, current_user: dict = Depends(get_current_user)):
    if project_id:
        success, err = safe_execute("DELETE FROM qto_active_projects WHERE user_id = %s AND project_id = %s", (current_user["id"], project_id))
    else:
        success, err = safe_execute("DELETE FROM qto_active_projects WHERE user_id = %s", (current_user["id"],))
    if not success:
        raise HTTPException(status_code=500, detail=f"Database clear failed: {err}")
    return {"message": "Active project state cleared."}

@router.post("")
@router.post("/")
async def save_project_route(req: SaveProjectReq, current_user: dict = Depends(get_current_user)):
    # Load existing state to merge
    existing_state = {}
    project_id = req.project_id
    is_new_project = False
    
    if project_id:
        df_state = safe_query("SELECT state_data FROM qto_active_projects WHERE user_id=%s AND project_id=%s", (current_user["id"], project_id))
        if not df_state.empty and df_state.iloc[0]["state_data"]:
            try:
                import json as json_lib
                existing_state = json_lib.loads(df_state.iloc[0]["state_data"])
            except Exception as ex:
                print(f"Error parsing existing state: {ex}")
    else:
        is_new_project = True
            
    # Merge states
    def merge_states(existing: dict, incoming: dict) -> dict:
        if not existing:
            return incoming
        if not incoming:
            return existing
        merged = existing.copy()
        for k, v in incoming.items():
            if k == "confirmed_auto_data" and isinstance(v, dict):
                existing_confirmed = merged.get("confirmed_auto_data") or {}
                new_confirmed = v.copy()
                # If structured keys are empty/falsy in incoming, preserve existing database ones
                for struct_key in ["floors", "walls", "schedules", "openings"]:
                    if not new_confirmed.get(struct_key) and existing_confirmed.get(struct_key):
                        new_confirmed[struct_key] = existing_confirmed[struct_key]
                merged["confirmed_auto_data"] = new_confirmed
            else:
                merged[k] = v
        return merged
        
    state_to_save = merge_states(existing_state, req.state_data or {})

    pid = save_project(
        project_name=req.project_name,
        boq_data=req.boq_data or {},
        user_id=current_user["id"],
        state_data=state_to_save,
        current_step=req.current_step,
        project_id=req.project_id
    )
    if pid is None:
        raise HTTPException(status_code=500, detail="Failed to save project.")
    
    # Update active project state table as well
    import json
    state_json = json.dumps(state_to_save, ensure_ascii=False, default=str)
    from utils.db import is_sqlite
    if is_sqlite():
        safe_execute(
            """
            INSERT INTO qto_active_projects (user_id, project_id, current_step, state_data)
            VALUES (%s, %s, %s, %s)
            ON CONFLICT(user_id, project_id) DO UPDATE SET 
                current_step=excluded.current_step, 
                state_data=excluded.state_data, 
                updated_at=datetime('now', 'localtime')
            """,
            (current_user["id"], pid, req.current_step, state_json)
        )
    else:
        safe_execute(
            """
            INSERT INTO qto_active_projects (user_id, project_id, current_step, state_data)
            VALUES (%s, %s, %s, %s)
            ON DUPLICATE KEY UPDATE current_step=%s, state_data=%s, updated_at=CURRENT_TIMESTAMP
            """,
            (current_user["id"], pid, req.current_step, state_json, req.current_step, state_json)
        )
        
    if is_new_project:
        from utils.usage import EVENT_PROJECT, log_usage
        log_usage(current_user["id"], EVENT_PROJECT, metadata={"project_id": pid, "project_name": req.project_name})
    
    return {"message": "Project saved successfully.", "project_id": pid}

@router.get("/{project_id}")
async def get_project(project_id: int, current_user: dict = Depends(get_current_user)):
    df = safe_query(
        "SELECT id, name, date, boq_data, state_data, current_step FROM qto_projects WHERE id=%s AND user_id=%s",
        (project_id, current_user["id"])
    )
    if df.empty:
        raise HTTPException(status_code=404, detail="Project not found.")
    row = df.iloc[0]
    return {
        "id": int(row["id"]),
        "name": row["name"],
        "date": row["date"],
        "boq_data": row["boq_data"],
        "state_data": row["state_data"],
        "current_step": int(row["current_step"]) if row["current_step"] else 1
    }

@router.delete("/{project_id}")
async def delete_project(project_id: int, current_user: dict = Depends(get_current_user)):
    success, err = safe_execute(
        "DELETE FROM qto_projects WHERE id=%s AND user_id=%s",
        (project_id, current_user["id"])
    )
    if not success:
        raise HTTPException(status_code=500, detail=f"Database delete failed: {err}")
    return {"message": "Project deleted successfully."}