All files / src/stores deployment.store.ts

0% Statements 0/247
0% Branches 0/1
0% Functions 0/1
0% Lines 0/247

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
import { defineStore } from 'pinia'
import { deploymentApi } from '@/api/deployment.api'
import { useAppStore } from './app.store'
import { useAuthStore } from './auth.store'
import { useKeycloak } from '@/composables/useKeycloak'
 
import type {
  Deployment,
  DeploymentWithRelations,
  DeploymentCreate,
  DeploymentStatus,
  DeploymentDraft,
  AppVariable
} from '@/types'
 
const defaultDraft: DeploymentDraft = {
  appId: null,
  name: '',
  releaseTag: '',
  courseIds: [],
  studentIds: [],
  groupMode: 'one',
  groupCount: 1,
  assignments: [],
 
  // --- WICHTIG: Diese müssen mit dem Interface übereinstimmen ---
  version: 'latest',
  variables: {},     // Behebt den TS-Fehler "Property variables missing"
  userInputVar: {},  // Behebt den TS-Fehler "Property userInputVar missing"
  groupNames: [],
  variableDefinitions: [] as AppVariable[], // speichert die API-Definitionen für die Variablen
  // ``fileUploads`` is the wizard-side staging area for files. Each
  // ``@openstack:file:<scope>``-marked variable contributes one entry
  // here, with inner-keys driven by the scope. ``submitDraft`` ships
  // the whole map under ``DeploymentCreate.files``.
  fileUploads: {}
}
 
export const useDeploymentStore = defineStore('deployment', {
  state: () => ({
    deployments: [] as Deployment[],
 
    deploymentTasks: {} as Record<string, any>,
 
    currentDeployment: null as DeploymentWithRelations | null,
    isLoading: false,
    error: null as string | null,
 
    // Der Wizard-Status (Draft)
    draft: JSON.parse(JSON.stringify(defaultDraft)) as DeploymentDraft,
 
    // Globaler Cache für Studenten und Kurse (userId/courseId → Objekt)
    studentCache: new Map<string, any>(),
    courseCache: new Map<string, any>(),
  }),
 
  getters: {
    myDeployments: (state) => {
      const authStore = useAuthStore()
      return state.deployments.filter((d) => d.userId === authStore.userId)
    },
 
    deploymentsByStatus: (state) => {
      return (status: DeploymentStatus) =>
        state.deployments.filter((d) => d.status === status)
    },
 
    draftAppDetails: (state) => {
      const appStore = useAppStore()
      if (!state.draft.appId) return null
      return appStore.apps.find(a => a.appId === state.draft.appId) || null
    }
  },
  actions: {
    async fetchDeployments(params?: { userId?: string; appId?: string; status?: DeploymentStatus }) {
      this.isLoading = true; this.error = null
      try {
        const response = await deploymentApi.list(params)
        this.deployments = response.data
      } catch (err: any) {
        this.error = err.response?.data?.detail || 'Failed to fetch deployments'
      } finally {
        this.isLoading = false
      }
    },
 
    async fetchDeploymentById(id: string) {
      this.isLoading = true; this.error = null
      try {
        const response = await deploymentApi.getById(id)
        this.currentDeployment = response.data
      } catch (err: any) {
        // 404 = Deployment wurde upstream soft-deleted (z.B. nach
        // erfolgreichem Destroy). Das ist KEIN Fehler-Zustand für
        // die UI — der ``streamConnectionState === 'ended'``-Watcher
        // im DetailView prüft anschließend ``currentDeployment ===
        // null`` als Soft-Delete-Signal und navigiert zur Liste mit
        // Success-Toast. Hätten wir hier ``state.error`` gesetzt,
        // würde der nächste Render einen Error-Banner zeigen, obwohl
        // das Backend exakt das tut, was der User wollte. Bei allen
        // anderen Status-Codes (5xx, Netzwerk-Timeout) bleibt der
        // Error-Pfad intakt.
        const status = err?.response?.status
        if (status === 404) {
          this.currentDeployment = null
        } else {
          this.error = err.response?.data?.detail || 'Failed to fetch deployment'
        }
      } finally {
        this.isLoading = false
      }
    },
 
    async createDeployment(data: DeploymentCreate) {
      this.isLoading = true; this.error = null
      try {
        const response = await deploymentApi.create(data)
        this.deployments.push(response.data)
        return response.data
      } catch (err: any) {
        this.error = err.response?.data?.detail || 'Failed to create deployment'
        throw err
      } finally {
        this.isLoading = false
      }
    },
 
    /**
     * Delete a deployment. Returns the raw HTTP response so the caller
     * can branch on status (202 = destroy task dispatched, watch the
     * SSE stream; 204 = soft-deleted immediately).
     *
     * Drops the row from the local list either way — the deployment
     * either disappears now (204) or shortly when the destroy task
     * completes and auto-soft-deletes it (202). Keeping it in the
     * sidebar list while it's running would only confuse the user;
     * the live progress lives in the detail view that issued the call.
     */
    async deleteDeployment(id: string) {
      this.isLoading = true; this.error = null
      try {
        const response = await deploymentApi.delete(id)
        this.deployments = this.deployments.filter((d: any) => d.deploymentId !== id)
        return response
      } catch (err: any) {
        this.error = err.response?.data?.detail || 'Failed to delete deployment'
        throw err
      } finally {
        this.isLoading = false
      }
    },
 
    /**
     * Pause a running deployment. Returns the raw HTTP response (202
     * with ``{task_id, status: "pausing"}``) so the detail view can
     * attach the SSE stream and switch into the live-progress UI.
     *
     * Unlike ``deleteDeployment``, the deployment row stays in the
     * list — pausing isn't a destruction, the user expects to find
     * it again under the new "paused" status. Status refresh comes
     * via the next list fetch or the SSE ``succeeded`` event.
     */
    async pauseDeployment(id: string) {
      this.isLoading = true; this.error = null
      try {
        return await deploymentApi.pause(id)
      } catch (err: any) {
        this.error = err.response?.data?.detail || 'Failed to pause deployment'
        throw err
      } finally {
        this.isLoading = false
      }
    },
 
    /**
     * Resume a paused deployment. Mirrors ``pauseDeployment`` —
     * returns the 202 ``{task_id, status: "resuming"}`` response so
     * the detail view can attach the live stream.
     */
    async resumeDeployment(id: string) {
      this.isLoading = true; this.error = null
      try {
        return await deploymentApi.resume(id)
      } catch (err: any) {
        this.error = err.response?.data?.detail || 'Failed to resume deployment'
        throw err
      } finally {
        this.isLoading = false
      }
    },
 
    resetDraft() {
      this.draft = JSON.parse(JSON.stringify(defaultDraft))
    },
 
    async submitDraft() {
      /**
       * Prepare and submit the current draft as a DeploymentCreate payload.
       * - Normalizes `releaseTag` which may come as string or object from UI
       * - Packs wizard selections (courses, groups, variables) into `userInputVar`
       * - Delegates creation to the API and returns the created deployment
       */
      if (!this.draft.appId || !this.draft.name) {
        throw new Error("App und Name sind Pflichtfelder")
      }
 
      const rawTag: any = this.draft.releaseTag
      let finalVersion = 'latest'
 
      if (rawTag && typeof rawTag === 'object') {
        finalVersion = rawTag.version || rawTag.name || 'latest'
      } else if (typeof rawTag === 'string' && rawTag.trim() !== '') {
        finalVersion = rawTag
      }
 
      // Teams: Array<{ name: string, userIds: string[] }>
      let teams: Array<{ name: string; userIds: string[] }> = []
      if (Array.isArray(this.draft.groupNames) && Array.isArray(this.draft.assignments)) {
        // assignments: Record<number, string[]>; groupNames: string[]
        teams = this.draft.groupNames.map((name: string, idx: number) => ({
          name,
          userIds: Array.isArray((this.draft.assignments as any)[idx]) ? (this.draft.assignments as any)[idx] : []
        }))
      }
 
      // Fallback: Wenn keine Teams definiert sind, erstelle automatisch Teams basierend auf studentIds
      if (teams.length === 0 && this.draft.studentIds.length > 0) {
        console.log('[submitDraft] Creating default teams from studentIds')
        // Erstelle Teams basierend auf groupCount
        const groupCount = this.draft.groupCount
        const studentsPerGroup = Math.floor(this.draft.studentIds.length / groupCount)
        const remainder = this.draft.studentIds.length % groupCount
        
        teams = []
        let currentIndex = 0
        for (let i = 0; i < groupCount; i++) {
          const groupSize = studentsPerGroup + (i < remainder ? 1 : 0)
          const groupStudents = this.draft.studentIds.slice(currentIndex, currentIndex + groupSize)
          teams.push({
            name: this.draft.groupNames[i] || `Team-${i + 1}`,
            userIds: groupStudents
          })
          currentIndex += groupSize
        }
      }
 
      // Stelle sicher, dass alle userIds als UUID-Strings formatiert sind
      teams = teams.map(team => ({
        name: team.name,
        userIds: team.userIds.map(id => typeof id === 'string' ? id : String(id))
      }))
 
      // userInputVar: { packer: {...}, terraform: {...} }
      let userInputVarObj: any = { packer: {}, terraform: {} }
      if (this.draft.variables && typeof this.draft.variables === 'object') {
        // VariableDefinitions enthält Info, ob packer/terraform
        if (Array.isArray(this.draft.variableDefinitions)) {
          for (const def of this.draft.variableDefinitions) {
            // File-typed variables travel through ``files`` instead of
            // ``userInputVar``. Skipping them here keeps the variables
            // dict free of accidental ``undefined`` entries that would
            // confuse the backend's terraform encoder.
            if (def.osType === 'file') continue
            const val = this.draft.variables[def.name]
            // Skip empty / undefined values — they would otherwise be
            // forwarded to Terraform as ``-var=name=null`` and bypass
            // the variable's HCL ``default = ...``. Critical for any
            // variable whose default is structurally non-trivial
            // (e.g. ``map(object(...))``) — the user not touching it
            // must mean "use the default", not "set to null". An
            // empty string is also treated as "no input".
            if (val === undefined || val === null) continue
            if (typeof val === 'string' && val.trim() === '') continue
            // Scoped variables (``varScope = team|user``) arrive as a
            // map. An empty map means no slot was filled — same logic
            // applies: ship nothing so the HCL default wins.
            if (
              typeof val === 'object'
              && !Array.isArray(val)
              && (def.varScope === 'team' || def.varScope === 'user')
              && Object.keys(val).length === 0
            ) {
              continue
            }
            if (def.source === 'packer') userInputVarObj.packer[def.name] = val
            else if (def.source === 'terraform') userInputVarObj.terraform[def.name] = val
          }
        } else {
          // Fallback: alles in terraform
          userInputVarObj.terraform = { ...this.draft.variables }
        }
      }
 
      // Drop empty file-variable entries — the wizard may have rendered
      // a slot that the user never filled (optional file with default
      // ``{}``). Sending it would still hit the backend's ``file_var_empty``
      // guard with a confusing error.
      const fileUploads: Record<string, Record<string, any>> = {}
      if (this.draft.fileUploads) {
        for (const [varName, slotMap] of Object.entries(this.draft.fileUploads)) {
          const filledSlots: Record<string, any> = {}
          for (const [slotKey, file] of Object.entries(slotMap || {})) {
            if (file && file.content_b64) {
              filledSlots[slotKey] = file
            }
          }
          if (Object.keys(filledSlots).length > 0) {
            fileUploads[varName] = filledSlots
          }
        }
      }
 
      const payload: any = {
        name: this.draft.name,
        appId: this.draft.appId,
        releaseTag: finalVersion,
        userInputVar: userInputVarObj,
        teams
      }
      if (Object.keys(fileUploads).length > 0) {
        payload.files = fileUploads
      }
 
      console.log('[submitDraft] Sending Payload:', payload)
 
      const response = await this.createDeployment(payload as DeploymentCreate)
      return response
    },
 
    async fetchStatusForDeployment(deploymentId: string) {
      /**
       * Load the latest task status for a given deployment.
       * Uses the Keycloak access token to call the tasks endpoint and keeps
       * only the most recent task of type 'deploy' for quick status rendering.
       */
      const { getAccessToken } = useKeycloak()
 
      try {
        const token = await getAccessToken()
 
        if (!token) {
          console.warn(`[Store] Kein Access Token verfügbar für Deployment ${deploymentId}`)
          return
        }
 
        const response = await fetch(`http://localhost:8000/tasks/deployment/${deploymentId}`, {
          headers: {
            'Authorization': `Bearer ${token}`,
            'Accept': 'application/json'
          }
        })
 
        if (!response.ok) {
          if (response.status === 401) console.error("Nicht autorisiert!")
          return
        }
 
        const tasks = await response.json()
 
        if (Array.isArray(tasks)) {
          const deployTasks = tasks.filter(t => t.type === 'deploy')
          if (deployTasks.length > 0) {
            this.deploymentTasks[deploymentId] = deployTasks[deployTasks.length - 1]
          }
        }
      } catch (err) {
        console.error(`Store: Fehler beim Laden des Status für ${deploymentId}`, err)
      }
    }
  }
})