feat: 데이터 바인딩

main
jschoi 9 months ago
parent 6e41bb966b
commit a11ff9c1d3

6
components.d.ts vendored

@ -10,7 +10,10 @@ declare module 'vue' {
export interface GlobalComponents {
AppFooter: typeof import('./src/components/AppFooter.vue')['default']
CompareComponent: typeof import('./src/components/templates/run/executions/CompareComponent.vue')['default']
copy: typeof import('./src/components/atoms/organisms/TrainingScriptBaseDoalog copy.vue')['default']
DatasetBaseDoalog: typeof import('./src/components/atoms/organisms/DatasetBaseDoalog.vue')['default']
DatasetsBaseDoalog: typeof import('./src/components/atoms/organisms/DatasetsBaseDoalog.vue')['default']
DatesetBaseDoalog: typeof import('./src/components/atoms/organisms/DatesetBaseDoalog.vue')['default']
DeploymentDialog: typeof import('./src/components/atoms/organisms/DeploymentDialog.vue')['default']
DrawerComponent: typeof import('./src/components/common/DrawerComponent.vue')['default']
ExecutionBaseDialog: typeof import('./src/components/atoms/organisms/ExecutionBaseDialog.vue')['default']
@ -23,6 +26,7 @@ declare module 'vue' {
IconDownloadBtn: typeof import('./src/components/atoms/button/IconDownloadBtn.vue')['default']
IconInfoBtn: typeof import('./src/components/atoms/button/IconInfoBtn.vue')['default']
IconModifyBtn: typeof import('./src/components/atoms/button/IconModifyBtn.vue')['default']
IconRunBtn: typeof import('./src/components/atoms/button/IconRunBtn.vue')['default']
IconSettingBtn: typeof import('./src/components/atoms/button/IconSettingBtn.vue')['default']
LayoutComponent: typeof import('./src/components/common/LayoutComponent.vue')['default']
ListComponent: typeof import('./src/components/templates/Datasets/ListComponent.vue')['default']
@ -36,6 +40,8 @@ declare module 'vue' {
WorkflowDialog: typeof import('./src/components/atoms/organisms/WorkflowDialog.vue')['default']
WorkflowsBaseDialog: typeof import('./src/components/atoms/organisms/WorkflowsBaseDialog.vue')['default']
WorkflowsCreateDialog: typeof import('./src/components/atoms/organisms/WorkflowsCreateDialog.vue')['default']
WorkflowsRunDialog: typeof import('./src/components/atoms/organisms/WorkflowsRunDialog.vue')['default']
WorkflowsRunsDialog: typeof import('./src/components/atoms/organisms/WorkflowsRunsDialog.vue')['default']
WorkflowsUploadDialog: typeof import('./src/components/atoms/organisms/WorkflowsUploadDialog.vue')['default']
WorklfowStepBaseDialog: typeof import('./src/components/atoms/organisms/WorklfowStepBaseDialog.vue')['default']
}

@ -0,0 +1,198 @@
<script setup lang="ts">
import { computed, ref, watch, onMounted, onBeforeUnmount } from "vue";
import { storeToRefs } from "pinia";
import { useAutoflowStore } from "@/stores/autoflowStore";
import { AttachmentsService } from "@/components/service/management/attachmentsService";
import type { AxiosError } from "axios";
const props = defineProps<{ editData: any; mode: "create" | "edit" }>();
const emit = defineEmits<{
(e: "close-modal"): void;
(e: "saved", v: any): void;
}>();
const isEdit = computed(() => props.mode === "edit");
const { projectId } = storeToRefs(useAutoflowStore());
const saving = ref(false);
const errorMsg = ref("");
const form = ref({
name: "",
description: "",
file: null as any, // File | File[] | null
});
function hydrateFormFromEdit(d: any) {
if (!d) return;
form.value.name = (d?.name ?? d?.title ?? "") + "";
form.value.description = (d?.description ?? "") + "";
}
onMounted(() => {
if (isEdit.value) hydrateFormFromEdit(props.editData);
});
watch(
() => props.editData,
(v) => {
if (isEdit.value) hydrateFormFromEdit(v);
},
);
const dialogTitle = computed(() =>
isEdit.value ? "Edit Training Script" : "Create Training Script",
);
//
const regUserId = (() => {
try {
const raw = localStorage.getItem("autoflow-auth") || "{}";
const auth = JSON.parse(raw);
return (
auth?.userInfo?.username ??
auth?.userinfo?.username ??
auth?.username ??
auth?.userId ??
""
);
} catch {
return "";
}
})();
//
async function submit() {
errorMsg.value = "";
const title = (form.value.name || "").trim();
const desc = (form.value.description || "").trim();
const fileObj = Array.isArray(form.value.file)
? form.value.file[0]
: form.value.file;
if (!title) return (errorMsg.value = "Training Script Title은 필수입니다.");
if (!regUserId)
return (errorMsg.value = "로그인 사용자 정보를 찾을 수 없습니다.");
try {
saving.value = true;
if (isEdit.value) {
if (!fileObj) return (errorMsg.value = "수정할 새 파일을 선택해주세요.");
const fd = new FormData();
fd.append("title", title);
fd.append("description", desc);
fd.append("regUserId", regUserId);
fd.append("projectId", String(projectId.value));
fd.append("file", fileObj);
const id = props.editData?.id ?? props.editData?.deviceKey;
await AttachmentsService.update(id, fd as any);
} else {
if (!fileObj) return (errorMsg.value = "업로드할 파일을 선택해주세요.");
if (!projectId.value)
return (errorMsg.value = "프로젝트가 선택되지 않았습니다.");
const fd = new FormData();
fd.append("refId", "0");
fd.append("refType", "DATASET");
fd.append("title", title);
fd.append("description", desc);
fd.append("version", "1");
fd.append("regUserId", regUserId);
fd.append("projectId", String(projectId.value));
fd.append("file", fileObj);
await AttachmentsService.upload(fd as any);
}
emit("saved", { ok: true });
emit("close-modal");
} catch (e) {
console.error("[Dataset] 저장 실패:", e as AxiosError);
errorMsg.value = "저장에 실패했습니다. 잠시 후 다시 시도하세요.";
} finally {
saving.value = false;
}
}
function onEsc(e: KeyboardEvent) {
if (e.key === "Escape") emit("close-modal");
}
onMounted(() => window.addEventListener("keydown", onEsc));
onBeforeUnmount(() => window.removeEventListener("keydown", onEsc));
</script>
<template>
<v-card class="rounded-lg overflow-hidden">
<v-card-title
class="text-white font-weight-bold text-h6"
style="background-color: #1976d2"
>
{{ dialogTitle }}
</v-card-title>
<v-card-text class="pa-6">
<v-form @submit.prevent="submit">
<div class="mb-5">
<label class="text-subtitle-2 font-weight-medium mb-1 d-block"
>Training Script Title</label
>
<v-text-field
v-model="form.name"
variant="outlined"
:disabled="saving"
dense
hide-details
required
/>
</div>
<div class="mb-5">
<label class="text-subtitle-2 font-weight-medium mb-1 d-block"
>Description</label
>
<v-text-field
v-model="form.description"
variant="outlined"
:disabled="saving"
dense
hide-details
required
/>
</div>
<div class="mb-5">
<label class="text-subtitle-2 font-weight-medium mb-1 d-block"
>File</label
>
<v-file-input
v-model="form.file"
label="Upload File"
:disabled="saving"
outlined
dense
hide-details
:required="true"
/>
</div>
<div v-if="errorMsg" class="mt-3 text-error">{{ errorMsg }}</div>
</v-form>
</v-card-text>
<v-card-actions class="justify-end" style="padding: 16px 24px">
<v-btn color="success" :loading="saving" @click="submit">
{{ isEdit ? "Update" : "Save" }}
</v-btn>
<v-btn
text
class="white--text"
:disabled="saving"
@click="$emit('close-modal')"
>
Close
</v-btn>
</v-card-actions>
</v-card>
</template>

@ -1,110 +0,0 @@
<script setup lang="ts">
import { computed, ref, watch } from "vue";
const props = defineProps({
editData: Object,
mode: String,
userOption: Array,
});
const emit = defineEmits(["handle-data", "close-modal"]);
const visible = ref(true);
const fileInput = ref<HTMLInputElement | null>(null);
const form = ref({
name: "",
description: "",
file: "",
});
//
const dialogTitle = computed(() => {
if (props.mode === "create") return "Create Dataset";
if (props.mode === "edit") return "Edit Dataset";
return "Clone Execution";
});
const onChooseFile = () => {
fileInput.value?.click();
};
const submit = () => {
emit("handle-data", form.value);
};
</script>
<template>
<v-card class="rounded-lg overflow-hidden">
<!-- 타이틀 영역 -->
<v-card-title
class="text-white font-weight-bold text-h6"
style="background-color: #1976d2"
>
{{ dialogTitle }}
</v-card-title>
<v-card-text class="pa-6">
<v-form @submit.prevent="submit">
<v-row dense class="mb-6">
<v-col cols="6">
<v-subheader class="font-weight-medium white--text mb-2">
Dataset Title
</v-subheader>
<v-text-field
v-model="form.name"
variant="outlined"
dense
hide-details
outlined
style="background: #1e1e1e; color: #fff"
/>
</v-col>
<v-col cols="6">
<v-subheader class="font-weight-medium white--text mb-2">
Dataset Version
</v-subheader>
<v-text-field
variant="outlined"
dense
hide-details
outlined
style="background: #1e1e1e; color: #fff"
/>
</v-col>
</v-row>
<div class="mb-5">
<label class="text-subtitle-2 font-weight-medium mb-1 d-block"
>Description
</label>
<v-text-field
v-model="form.description"
variant="outlined"
dense
hide-details
required
/>
</div>
<div class="mb-5">
<label class="text-subtitle-2 font-weight-medium mb-1 d-block"
>Upload File
</label>
<v-file-input
v-model="form.file"
label="Upload File"
@click:append-outer="onChooseFile"
outlined
dense
hide-details
/>
</div>
</v-form>
</v-card-text>
<v-card-actions class="justify-end" style="padding: 16px 24px">
<v-btn color="success" @click="submit">Save</v-btn>
<v-btn text class="white--text" @click="$emit('close-modal')"
>Close</v-btn
>
</v-card-actions>
</v-card>
</template>

@ -1,29 +1,170 @@
<script setup lang="ts">
import { ref, watch } from "vue";
import { onBeforeUnmount, onMounted, ref, watch } from "vue";
import { ExperimentService } from "@/components/service/management/ExperimentService";
import { ExperimentCreateDto } from "@/components/models/management/Experiments";
import type { AxiosError } from "axios"; //
const props = defineProps({
editData: Object,
mode: String,
userOption: Array,
});
type SelectedData = {
name?: string;
description?: string;
username?: string;
projectId?: number | null;
};
const props = defineProps<{
editData: SelectedData | null;
mode: "create" | "edit";
}>();
const emit = defineEmits(["handle-data", "close-modal"]);
const emit = defineEmits<{
(e: "close-modal"): void;
(e: "saved", v: any): void;
}>();
const visible = ref(true);
const saving = ref(false);
const errorMsg = ref("");
const form = ref({
name: "",
description: "",
regUserId: "",
projectId: null as number | null,
});
const submit = () => {
emit("handle-data", form.value);
//
watch(
() => props.editData,
(v) => {
form.value.name = v?.name ?? "";
form.value.description = v?.description ?? "";
form.value.regUserId = v?.username ?? "";
form.value.projectId = v?.projectId ?? null;
},
{ immediate: true },
);
const nowIso = () => new Date().toISOString();
/** ✅ 에러를 사용자 친화적으로 변환 */
function parseApiError(err: unknown): string {
const ax = err as AxiosError<any>;
// /
if (!ax?.response) {
if ((ax as any)?.code === "ECONNABORTED")
return "요청 시간이 초과되었습니다. 잠시 후 다시 시도해 주세요.";
return "네트워크 오류가 발생했습니다. 연결 상태를 확인해 주세요.";
}
const { status, data } = ax.response;
const serverMsg = (
data?.message ||
data?.error ||
data?.detail ||
data?.msg ||
""
).toString();
// (409 )
if (status === 409 || /duplicate|exists|이미.*존재|중복/i.test(serverMsg)) {
return "동일한 이름의 Experiment가 이미 존재합니다. 다른 이름을 사용해 주세요.";
}
// (400/422) -
if (status === 400 || status === 422) {
const fieldErrors =
data?.errors || data?.fieldErrors || data?.validationErrors;
if (Array.isArray(fieldErrors) && fieldErrors.length) {
const f = fieldErrors[0];
if (typeof f === "string") return f;
if (f?.defaultMessage) return f.defaultMessage;
if (f?.message) return f.message;
if (f?.field && f?.error) return `${f.field}: ${f.error}`;
}
if (serverMsg) return serverMsg;
return "입력값이 올바르지 않습니다. 필수 항목을 확인해 주세요.";
}
// /
if (status === 401) return "로그인이 필요합니다.";
if (status === 403) return "이 작업에 대한 권한이 없습니다.";
//
if (status === 404) return "대상을 찾을 수 없습니다.";
// /
if (status === 413) return "요청 용량 제한을 초과했습니다.";
//
if (status >= 500)
return (
serverMsg || "서버 내부 오류가 발생했습니다. 관리자에게 문의해 주세요."
);
return serverMsg || "요청 처리 중 오류가 발생했습니다.";
}
async function submit() {
errorMsg.value = "";
const name = (form.value.name || "").trim();
const description = (form.value.description || "").trim();
const regUserId = (form.value.regUserId || "").trim();
const projectId = Number(form.value.projectId);
if (!name) {
errorMsg.value = "Experiment Name은 필수입니다.";
return;
}
if (!regUserId) {
errorMsg.value = "로그인 사용자(regUserId) 정보를 찾을 수 없습니다.";
return;
}
if (!Number.isFinite(projectId) || projectId <= 0) {
errorMsg.value = "프로젝트가 선택되지 않았습니다.";
return;
}
const now = nowIso();
const payload: ExperimentCreateDto = {
kubeFlowId: null,
mlFlowId: null,
name,
displayName: name,
description,
artifactLocation: null,
lifecycleStage: "active",
storageState: "available",
kubeflowCreatedAt: null,
mlflowCreatedAt: null,
lastUpdateTime: null,
lastRunCreatedAt: null,
regUserId,
projectId,
};
try {
saving.value = true;
const res = await ExperimentService.add(payload);
emit("saved", res?.data ?? { ok: true });
emit("close-modal");
} catch (e) {
console.error("[Experiment] 저장 실패:", e);
errorMsg.value = parseApiError(e); //
} finally {
saving.value = false;
}
}
function onEsc(e: KeyboardEvent) {
if (e.key === "Escape") emit("close-modal");
}
onMounted(() => window.addEventListener("keydown", onEsc));
onBeforeUnmount(() => window.removeEventListener("keydown", onEsc));
</script>
<template>
<v-card class="rounded-lg overflow-hidden">
<!-- 타이틀 영역 -->
<v-card-title
class="text-white font-weight-bold text-h6"
style="background-color: #1976d2"
@ -40,13 +181,14 @@ const submit = () => {
<v-text-field
v-model="form.name"
variant="outlined"
:disabled="saving"
dense
hide-details
required
/>
</div>
<div>
<div class="mb-5">
<label class="text-subtitle-2 font-weight-medium mb-1 d-block"
>Description</label
>
@ -54,16 +196,29 @@ const submit = () => {
v-model="form.description"
variant="outlined"
rows="3"
:disabled="saving"
dense
hide-details
/>
</div>
<div v-if="errorMsg" class="mt-3 text-error">{{ errorMsg }}</div>
</v-form>
</v-card-text>
<v-card-actions class="justify-end" style="padding: 16px 24px">
<v-btn color="success" @click="submit">Save</v-btn>
<v-btn text class="white--text" @click="$emit('close-modal')"
<v-btn
color="success"
:loading="saving"
:disabled="saving"
@click="submit"
>Save</v-btn
>
<v-btn
text
class="white--text"
:disabled="saving"
@click="$emit('close-modal')"
>Close</v-btn
>
</v-card-actions>

@ -1,40 +1,131 @@
<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { computed, ref, watch, onMounted, onBeforeUnmount } from "vue";
import { storeToRefs } from "pinia";
import { useAutoflowStore } from "@/stores/autoflowStore";
import { AttachmentsService } from "@/components/service/management/attachmentsService";
import type { AxiosError } from "axios";
const props = defineProps({
editData: Object,
mode: String,
userOption: Array,
});
const props = defineProps<{ editData: any; mode: "create" | "edit" }>();
const emit = defineEmits<{
(e: "close-modal"): void;
(e: "saved", v: any): void;
}>();
const emit = defineEmits(["handle-data", "close-modal"]);
const isEdit = computed(() => props.mode === "edit");
const { projectId } = storeToRefs(useAutoflowStore());
const saving = ref(false);
const errorMsg = ref("");
const visible = ref(true);
const fileInput = ref<HTMLInputElement | null>(null);
const form = ref({
name: "",
description: "",
file: "",
file: null as any,
});
//
const dialogTitle = computed(() => {
if (props.mode === "create") return "Create Training Script";
if (props.mode === "edit") return "Edit Training Script";
return "Clone Execution";
function hydrateFormFromEdit(d: any) {
if (!d) return;
form.value.name = (d?.name ?? d?.title ?? "") + "";
form.value.description = (d?.description ?? "") + "";
}
onMounted(() => {
if (isEdit.value) hydrateFormFromEdit(props.editData);
});
watch(
() => props.editData,
(v) => {
if (isEdit.value) hydrateFormFromEdit(v);
},
);
const dialogTitle = computed(() =>
isEdit.value ? "Edit Training Script" : "Create Training Script",
);
//
const regUserId = (() => {
try {
const raw = localStorage.getItem("autoflow-auth") || "{}";
const auth = JSON.parse(raw);
return (
auth?.userInfo?.username ??
auth?.userinfo?.username ??
auth?.username ??
auth?.userId ??
""
);
} catch {
return "";
}
})();
//
async function submit() {
errorMsg.value = "";
const title = (form.value.name || "").trim();
const desc = (form.value.description || "").trim();
const fileObj = Array.isArray(form.value.file)
? form.value.file[0]
: form.value.file;
if (!title) return (errorMsg.value = "Training Script Title은 필수입니다.");
if (!regUserId)
return (errorMsg.value = "로그인 사용자 정보를 찾을 수 없습니다.");
try {
saving.value = true;
if (isEdit.value) {
// : file required
if (!fileObj) return (errorMsg.value = "수정할 새 파일을 선택해주세요.");
const onChooseFile = () => {
fileInput.value?.click();
};
const submit = () => {
emit("handle-data", form.value);
};
const fd = new FormData();
fd.append("title", title);
fd.append("description", desc);
fd.append("regUserId", regUserId);
fd.append("projectId", String(projectId.value));
fd.append("file", fileObj);
const id = props.editData?.id ?? props.editData?.deviceKey;
await AttachmentsService.update(id, fd as any);
} else {
if (!fileObj) return (errorMsg.value = "업로드할 파일을 선택해주세요.");
if (!projectId.value)
return (errorMsg.value = "프로젝트가 선택되지 않았습니다.");
const fd = new FormData();
fd.append("refId", "0");
fd.append("refType", "TRAINING_SCRIPT");
fd.append("title", title);
fd.append("description", desc);
fd.append("version", "1");
fd.append("regUserId", regUserId);
fd.append("projectId", String(projectId.value));
fd.append("file", fileObj);
await AttachmentsService.upload(fd as any);
}
emit("saved", { ok: true });
emit("close-modal");
} catch (e) {
console.error("[Training Script] 저장 실패:", e as AxiosError);
errorMsg.value = "저장에 실패했습니다. 잠시 후 다시 시도하세요.";
} finally {
saving.value = false;
}
}
function onEsc(e: KeyboardEvent) {
if (e.key === "Escape") emit("close-modal");
}
onMounted(() => window.addEventListener("keydown", onEsc));
onBeforeUnmount(() => window.removeEventListener("keydown", onEsc));
</script>
<template>
<v-card class="rounded-lg overflow-hidden">
<!-- 타이틀 영역 -->
<v-card-title
class="text-white font-weight-bold text-h6"
style="background-color: #1976d2"
@ -46,49 +137,63 @@ const submit = () => {
<v-form @submit.prevent="submit">
<div class="mb-5">
<label class="text-subtitle-2 font-weight-medium mb-1 d-block"
>Training Script Title
</label>
>Training Script Title</label
>
<v-text-field
v-model="form.name"
variant="outlined"
:disabled="saving"
dense
hide-details
required
/>
</div>
<div class="mb-5">
<label class="text-subtitle-2 font-weight-medium mb-1 d-block"
>File
</label>
<v-file-input
v-model="form.file"
label="Upload File"
@click:append-outer="onChooseFile"
outlined
>Description</label
>
<v-text-field
v-model="form.description"
variant="outlined"
:disabled="saving"
dense
hide-details
required
/>
</div>
<div class="mb-5">
<label class="text-subtitle-2 font-weight-medium mb-1 d-block"
>Description
</label>
<v-text-field
v-model="form.description"
variant="outlined"
>File</label
>
<v-file-input
v-model="form.file"
label="Upload File"
:disabled="saving"
outlined
dense
hide-details
required
:required="true"
/>
</div>
<div v-if="errorMsg" class="mt-3 text-error">{{ errorMsg }}</div>
</v-form>
</v-card-text>
<v-card-actions class="justify-end" style="padding: 16px 24px">
<v-btn color="success" @click="submit">Save</v-btn>
<v-btn text class="white--text" @click="$emit('close-modal')"
>Close</v-btn
<v-btn color="success" :loading="saving" @click="submit">
{{ isEdit ? "Update" : "Save" }}
</v-btn>
<v-btn
text
class="white--text"
:disabled="saving"
@click="$emit('close-modal')"
>
Close
</v-btn>
</v-card-actions>
</v-card>
</template>

@ -34,7 +34,6 @@ const errorMsg = ref("");
// ====== KFP & ======
const KFP_NAME_REGEX = /^[a-z0-9]([-a-z0-9\.]*[a-z0-9])?$/; // //.-, /
const KOREAN_RX = /[ㄱ-ㅎㅏ-ㅣ가-힣]/g;
const sanitizeKfpName = (s: string) => {
let x = (s ?? "").toLowerCase();
@ -45,13 +44,11 @@ const sanitizeKfpName = (s: string) => {
x = x.replace(/[^a-z0-9]+$/, ""); //
return x;
};
const stripKorean = (s: string) => (s ?? "").replace(KOREAN_RX, "");
// /
const nameHint = ref(
"허용 문자: 소문자 az, 숫자 09, '-', '.' (시작/끝은 영숫자). 한글/공백/대문자/언더스코어 불가",
);
const descHint = ref("한글은 사용할 수 없습니다.");
const nameInvalid = computed(
() => !!form.value.name && !KFP_NAME_REGEX.test(form.value.name),
);
@ -72,10 +69,6 @@ function onNameInput(v: string) {
}
form.value.name = cleaned;
}
function onDescInput(v: string) {
const cleaned = stripKorean(v || "");
form.value.description = cleaned;
}
function extractApiErrorMessage(err: any): string {
const status = err?.response?.status;
@ -149,7 +142,9 @@ watch(
if (isEdit.value) hydrateFormFromEdit(v);
},
);
function onDescInput(v: string) {
form.value.description = v ?? "";
}
/** 시간 포맷 */
const nowLocalIso = (): string => {
const t = new Date(Date.now() - new Date().getTimezoneOffset() * 60000);
@ -161,7 +156,7 @@ async function submit() {
// &
form.value.name = sanitizeKfpName(form.value.name);
form.value.description = stripKorean(form.value.description);
form.value.description = (form.value.description ?? "").trim();
const name = form.value.name.trim();
if (!name || !KFP_NAME_REGEX.test(name)) {
@ -322,7 +317,6 @@ onBeforeUnmount(() => window.removeEventListener("keydown", onEsc));
dense
hide-details="auto"
persistent-hint
:hint="descHint"
@update:model-value="onDescInput"
/>
</div>

@ -0,0 +1,158 @@
<script setup lang="ts">
import { computed, onMounted, onBeforeUnmount, ref, watch } from "vue";
import { kubeflowService } from "@/components/service/management/kubeflowService";
type RunPayload = {
display_name: string;
description?: string;
pipeline_version_reference: { pipeline_id: string };
runtime_config?: { parameters?: Record<string, any> };
service_account?: string;
};
const props = defineProps<{
/** 테이블에서 선택된 파이프라인의 pipelineId */
pipelineId?: string | number | null;
}>();
const emit = defineEmits<{
(e: "close-modal"): void;
(e: "submitted", value: any): void;
}>();
const form = ref({
display_name: "", //
description: "", //
pipeline_id: "", // prop ( )
});
const loading = ref(false);
const errorMsg = ref("");
const isValid = computed(
() => !!form.value.display_name.trim() && !!form.value.pipeline_id.trim(),
);
function initForm() {
form.value.pipeline_id = props.pipelineId ? String(props.pipelineId) : "";
// display_name/description
}
onMounted(initForm);
watch(() => props.pipelineId, initForm);
function onEsc(e: KeyboardEvent) {
if (e.key === "Escape" && !loading.value) emit("close-modal");
}
onMounted(() => window.addEventListener("keydown", onEsc));
onBeforeUnmount(() => window.removeEventListener("keydown", onEsc));
async function submitRun() {
errorMsg.value = "";
if (!isValid.value) {
errorMsg.value = "Run 제목(display_name)과 pipeline_id는 필수입니다.";
return;
}
const payload: RunPayload = {
display_name: form.value.display_name.trim(),
description: form.value.description?.trim(),
pipeline_version_reference: { pipeline_id: form.value.pipeline_id.trim() },
runtime_config: { parameters: {} }, //
service_account: "pipeline-runner",
};
try {
loading.value = true;
const { data } = await kubeflowService.run(payload);
emit("submitted", data);
emit("close-modal");
} catch (e: any) {
console.error("Run 생성 실패:", e);
const msg =
e?.response?.data?.message ||
e?.response?.data?.error ||
e?.message ||
"Run 생성에 실패했습니다.";
errorMsg.value = String(msg);
} finally {
loading.value = false;
}
}
</script>
<template>
<v-card>
<v-card-title
class="text-white font-weight-bold text-h6"
style="background-color: #1976d2"
>
Run Pipeline
</v-card-title>
<v-card-text class="pa-6">
<v-form @submit.prevent="submitRun">
<!-- 제목 -->
<div class="mb-4">
<label class="text-subtitle-2 font-weight-medium mb-1 d-block">
Run Title (display_name)
</label>
<v-text-field
v-model="form.display_name"
variant="outlined"
:disabled="loading"
density="comfortable"
hide-details="auto"
persistent-hint
required
/>
</div>
<!-- 내용 -->
<div class="mb-4">
<label class="text-subtitle-2 font-weight-medium mb-1 d-block">
Run Description
</label>
<v-textarea
v-model="form.description"
variant="outlined"
:disabled="loading"
rows="3"
density="comfortable"
hide-details="auto"
/>
</div>
<!-- pipeline_id -->
<div class="mb-2">
<label class="text-subtitle-2 font-weight-medium mb-1 d-block">
pipeline_id
</label>
<v-text-field
v-model="form.pipeline_id"
variant="outlined"
:disabled="true"
density="comfortable"
hide-details="auto"
required
/>
</div>
<div v-if="errorMsg" class="mt-3 text-error">{{ errorMsg }}</div>
</v-form>
</v-card-text>
<v-card-actions class="justify-end" style="padding: 16px 24px">
<v-btn
color="success"
:loading="loading"
:disabled="!isValid"
@click="submitRun"
>
RUN
</v-btn>
<v-btn text :disabled="loading" @click="$emit('close-modal')"
>CLOSE</v-btn
>
</v-card-actions>
</v-card>
</template>

@ -0,0 +1,24 @@
export type AttachmentUpload = {
refId?: number | null;
refType: string;
title?: string;
description?: string;
version?: number;
regUserId: string;
projectId: number;
file: File | Blob;
path?: string;
};
export type AttachmentSearch = {
projectId: number;
page?: number;
size?: number;
keyword?: string;
searchType?: "전체" | "제목" | "작성자";
startDate?: string;
endDate?: string;
sortField?: string;
sortDirection?: "ASC" | "DESC";
refType?: "WORKFLOW_STEP" | "DATASET" | "TRAINING_SCRIPT";
};

@ -0,0 +1,29 @@
export interface ExperimentCreateDto {
kubeFlowId?: string;
mlFlowId?: string;
name: string;
displayName: string;
description?: string;
artifactLocation?: string;
lifecycleStage?: string;
storageState?: string;
kubeflowCreatedAt?: string;
mlflowCreatedAt?: string;
lastUpdateTime?: string;
lastRunCreatedAt?: string;
regUserId: string;
projectId: number;
}
export type ExperimentSearch = {
projectId: number;
page?: number;
size?: number;
keyword?: string;
searchType?: "전체" | "제목" | "작성자";
startDate?: string;
endDate?: string;
sortField?: string;
sortDirection?: "ASC" | "DESC";
refType?: "WORKFLOW_STEP" | "DATASET" | "TRAINING_SCRIPT";
};

@ -0,0 +1,23 @@
export type KubeflowUploadDto = {
name: string;
display_name?: string;
description?: string;
namespace?: string;
regUserId: string;
projectId: number | string;
uploadfile: File | Blob;
};
export type kubeflow = FormData;
export function toKubeflowForm(dto: KubeflowUploadDto): FormData {
const fd = new FormData();
fd.append("name", dto.name);
fd.append("display_name", dto.display_name || dto.name);
fd.append("description", dto.description || "");
fd.append("namespace", dto.namespace || "default");
fd.append("regUserId", String(dto.regUserId));
fd.append("projectId", String(dto.projectId));
fd.append("uploadfile", dto.uploadfile);
return fd;
}

@ -30,7 +30,7 @@ export interface ProjectAuthority {
permissions: Permission[];
}
export interface ProjectSearchParams {
export interface ProjectSearch {
page: number;
size: number;
keyword: string;

@ -20,6 +20,12 @@ export const request = {
put: (uri: string, param: any): any => {
return axios.put(`${API_URL}${uri}`, param);
},
getFile: (uri: string, param: any): any => {
return axios.get(`${API_URL}${uri}`, {
params: param,
responseType: "blob",
});
},
postFile: (uri: string, param: any, attachment: any, progress: any): any => {
const formData = new FormData();

@ -0,0 +1,36 @@
import {
AttachmentSearch,
AttachmentUpload,
} from "@/components/models/management/Attachments";
import { request } from "@/components/service/index";
export const AttachmentsService = {
upload: (payload: AttachmentUpload) => {
return request.post("/api/attachments/upload", payload);
},
delete: (id: Number) => {
return request.delete(`/api/attachments/${id}`, {});
},
view: (id: number) => {
return request.get(`/api/attachments/${id}`, {});
},
update: (id: number, payload: AttachmentUpload) => {
return request.put(`/api/attachments/${id}/update`, payload);
},
readTextByPath: (objectName: string) => {
return request.get(
`/api/attachments/readYamlText?objectName=${objectName}`,
{},
);
},
downloadFile: (objectName: string) => {
return request.getFile(
`/api/attachments/download?objectName=${objectName}`,
{},
);
},
search: (payload: AttachmentSearch) => {
return request.get("/api/attachments/search", payload);
},
};

@ -0,0 +1,22 @@
import {
ExperimentCreateDto,
ExperimentSearch,
} from "@/components/models/management/Experiments";
import { request } from "@/components/service/index";
export const ExperimentService = {
add: (payload: ExperimentCreateDto) => {
return request.post("/api/experiments", payload);
},
delete: (id: Number) => {
return request.delete(`/api/experiments/${id}`, {});
},
view: (id: number) => {
return request.get(`/api/experiments/${id}`, {});
},
// update: (id: number, payload: AttachmentUpload) => {
// return request.put(`/api/experiments/${id}`, payload);
// },
search: (payload: ExperimentSearch) => {
return request.get("/api/experiments/search", payload);
},
};

@ -0,0 +1,10 @@
import { kubeflow } from "@/components/models/management/Kubeflow";
import { request } from "@/components/service/index";
export const kubeflowService = {
upload: (payload: kubeflow) => {
return request.post("/pipelines/upload", payload);
},
run: (payload: kubeflow) => {
return request.post("/pipelines/runs", payload);
},
};

@ -26,4 +26,12 @@ export const UserManagerService = {
getUser: (userId: number) => {
return request.get(`/api/auth/users/${userId}`, {});
},
// 사용자 수정
update: (id: number, payload: User) => {
return request.put(`/api/auth/users/${id}`, payload);
},
// 사용자 삭제
delete: (id: Number) => {
return request.delete(`/api/auth/users/${id}`, {});
},
};

@ -2,7 +2,7 @@ import { request } from "@/components/service/index";
import {
ApiProject,
ProjectAuthority,
ProjectSearchParams,
ProjectSearch,
} from "@/components/models/project/Project";
export const ProjectService = {
@ -27,9 +27,9 @@ export const ProjectService = {
return request.post("/api/projects", payload);
},
// 검색 및 페이지네이션 프로젝트 목록 조회
searchProjects: (params: ProjectSearchParams) =>
request.get("/api/projects/search", params),
searchProjects: (params: ProjectSearch) => {
return request.get("/api/projects/search", params);
},
// ----------------------------------------------------------------------
// 프로젝트 권한
@ -43,4 +43,7 @@ export const ProjectService = {
{},
);
},
userProjectAuthority: (id: number) => {
return request.get(`/api/projects/users/${id}/projects`, {});
},
};

@ -2,340 +2,334 @@
import IconDeleteBtn from "@/components/atoms/button/IconDeleteBtn.vue";
import IconModifyBtn from "@/components/atoms/button/IconModifyBtn.vue";
import IconInfoBtn from "@/components/atoms/button/IconInfoBtn.vue";
// import FormComponent from "@/components/device/FormComponent.vue";
import { onMounted, ref, watch } from "vue";
import { onMounted, ref } from "vue";
import { storage } from "@/utils/storage";
import ViewComponent from "@/components/templates/Datasets/ViewComponent.vue";
import DatasetsBaseDoalog from "@/components/atoms/organisms/DatasetsBaseDoalog.vue";
import WorkflowsUploadDialog from "@/components/atoms/organisms/WorkflowsUploadDialog.vue";
// const store = commonStore();
import DatasetBaseDoalog from "@/components/atoms/organisms/DatasetBaseDoalog.vue";
import { AttachmentsService } from "@/components/service/management/attachmentsService";
import { commonStore } from "@/stores/commonStore";
const store = commonStore();
const openView = ref(false);
const openModify = ref(false);
const tableHeader = [
{
label: "Title",
width: "7%",
style: "word-break: keep-all;",
},
{
label: "File Name",
width: "7%",
style: "word-break: keep-all;",
},
{
label: "File Path",
width: "7%",
style: "word-break: keep-all;",
},
{
label: "Description",
width: "7%",
style: "word-break: keep-all;",
},
{
label: "Created Data",
width: "7%",
style: "word-break: keep-all;",
},
{
label: "Modified Data",
width: "7%",
style: "word-break: keep-all;",
},
{
label: "Action",
width: "7%",
style: "word-break: keep-all;",
},
];
const username = ref<string>("");
// ===== /( ) =====
type SearchType = "전체" | "제목" | "작성자";
const searchOptions = [
{
searchType: "전체",
searchText: "",
},
{
searchType: "디바이스 별칭",
searchText: "deviceAlias",
},
{
searchType: "디바이스 키",
searchText: "deviceKey",
},
{
searchType: "사용자",
searchText: "userId",
},
{
searchType: "디바이스 이름",
searchText: "deviceName",
},
{
searchType: "디바이스 모델",
searchText: "deviceModel",
},
{
searchType: "디바이스 OS",
searchText: "deviceOs",
},
{ label: "전체", value: "전체" as SearchType },
{ label: "제목", value: "제목" as SearchType },
{ label: "작성자", value: "작성자" as SearchType },
];
const SEARCH_TYPE_MAP: Record<SearchType | "", "ALL" | "TITLE" | "AUTHOR"> = {
"": "ALL",
전체: "ALL",
제목: "TITLE",
작성자: "AUTHOR",
};
const pageSizeOptions = [
{ text: "10 페이지", value: 10 },
{ text: "50 페이지", value: 50 },
{ text: "100 페이지", value: 100 },
];
//
const tableHeader = [
{ label: "Title", width: "7%", style: "word-break: keep-all;" },
{ label: "File Name", width: "7%", style: "word-break: keep-all;" },
{ label: "File Path", width: "7%", style: "word-break: keep-all;" },
{ label: "Description", width: "7%", style: "word-break: keep-all;" },
{ label: "Created Data", width: "7%", style: "word-break: keep-all;" },
{ label: "Modified Data", width: "7%", style: "word-break: keep-all;" },
{ label: "Action", width: "7%", style: "word-break: keep-all;" },
];
const data = ref({
params: {
pageNum: 1,
pageSize: 10,
searchType: "",
searchType: "전체" as SearchType,
searchText: "",
},
results: [],
totalDataLength: 0,
results: [] as any[],
totalElements: 0,
pageLength: 0,
modalMode: "",
selectedData: null,
modalMode: "" as "create" | "edit" | "setting" | "",
selectedData: null as any,
allSelected: false,
selected: [],
selected: [] as Array<{ deviceKey: number }>,
isCreateVisible: false,
isUploadVisible: false,
isModalVisible: false,
isConfirmDialogVisible: false,
userOption: [],
userOption: [] as any[],
});
const getCodeList = () => {
// UserService.search(data.value.params).then((d) => {
// if (d.status === 200) {
// data.value.userOption = d.data.userList;
// }
// });
//
function readUsernameFromStorage(): string {
try {
const raw =
storage?.get?.("autoflow-auth") ??
storage?.getAuth?.() ??
localStorage.getItem("autoflow-auth") ??
null;
const auth = typeof raw === "string" ? JSON.parse(raw) : raw;
const u1 = auth?.userInfo?.username;
const u2 = auth?.username;
const u3 = auth?.userInfo?.userName;
const u4 = auth?.userInfo?.email?.split("@")?.[0];
return (u1 || u2 || u3 || u4 || "").toString();
} catch {
return "";
}
}
// ID
const getProjectId = (): number => {
const v = Number(localStorage.getItem("projectId"));
return Number.isFinite(v) ? v : 0;
};
const getData = () => {
const params = { ...data.value.params };
if (params.searchType === "" || params.searchText === "") {
delete params.searchType;
delete params.searchText;
// ( )
const toRow = (a: any) => ({
deviceKey: a.id,
id: a.id,
title: a.title ?? "",
fileName: a.originalName ?? "",
filePath: a.storagePath ?? "",
description: a.description ?? "",
createdData: String(a.regDt ?? "")
.replace("T", " ")
.slice(0, 19),
modifiedData: "-",
});
const fetchList = async () => {
const projectId = getProjectId();
if (!projectId) {
console.warn("[TrainingScript] projectId 없음 — 프로젝트 먼저 선택");
data.value.results = [];
data.value.totalElements = 0;
data.value.pageLength = 0;
return;
}
data.value.results = [
{
title: "배터리 상태 예측 모델 프로젝트",
fileName: "train.py",
filePath: "/kubeflow-users/battery/train.py",
description: "배터리 상태 예측 스크립트",
createdData: "2025-04-28 12:01:00",
modifiedData: "2025-04-28 12:01:00",
},
{
title: "상태 추적 모델",
fileName: "detection.py",
filePath: "/kubeflow-users/status/detection.py",
description: "상태 추적 스크립트",
createdData: "2025-04-20 12:01:00",
modifiedData: "2025-04-28 12:01:00",
},
];
data.value.totalDataLength = 5;
// DeviceService.search(params).then((d) => {
// if (d.status === 200) {
// data.value.results = d.data.deviceList;
// data.value.totalDataLength = d.data.totalCount;
// setTimeout(() => {
// setPaginationLength();
// }, 200);
// } else {
// store.setSnackbarMsg({
// text: " ",
// color: "error",
// });
// }
// });
// DeviceService.search().then((d) => {
// data.value.totalDataLength = d.data.totalCount;
// setTimeout(() => {
// setPaginationLength();
// }, 200);
// });
const { pageNum, pageSize, searchType, searchText } = data.value.params;
const mapped = SEARCH_TYPE_MAP[searchType] || "ALL";
const keyword = (searchText || "").trim();
const needLocalFilter = mapped !== "ALL" && keyword.length > 0;
let reqPage = data.value.params.pageNum;
let reqSize = data.value.params.pageSize;
if (needLocalFilter) {
reqPage = 0;
reqSize = 1000;
}
const payload = {
projectId,
page: reqPage,
size: reqSize,
keyword,
searchType: mapped,
sortField: "id",
sortDirection: "DESC",
refType: "DATASET",
};
const setPaginationLength = () => {
if (data.value.totalDataLength % data.value.params.pageSize === 0) {
data.value.pageLength =
data.value.totalDataLength / data.value.params.pageSize;
} else {
data.value.pageLength = Math.ceil(
data.value.totalDataLength / data.value.params.pageSize,
try {
const res = await AttachmentsService.search(payload as any);
const result = res?.data ?? res;
let list = result?.content ?? [];
if (needLocalFilter) {
const kw = keyword.toLowerCase();
if (mapped === "TITLE") {
list = list.filter((x: any) =>
String(x?.title ?? "")
.toLowerCase()
.includes(kw),
);
} else if (mapped === "AUTHOR") {
list = list.filter((x: any) =>
String(x?.regUserId ?? "")
.toLowerCase()
.includes(kw),
);
}
};
const saveData = (formData) => {
if (data.value.modalMode === "create") {
// DeviceService.add(formData).then((d) => {
// if (d.status === 200) {
// data.value.isModalVisible = false;
// store.setSnackbarMsg({
// text: " .",
// result: 200,
// });
// changePageNum(1);
// } else {
// store.setSnackbarMsg({
// text: d,
// result: 500,
// });
// }
// });
} else {
// DeviceService.update(formData.deviceKey, formData).then((d) => {
// if (d.status === 200) {
// data.value.isModalVisible = false;
// store.setSnackbarMsg({
// text: " .",
// result: 200,
// });
// changePageNum();
// } else {
// store.setSnackbarMsg({
// text: d,
// result: 500,
// });
// }
// });
//
const uiSize = data.value.params.pageSize;
const totalElements = list.length;
const totalPages = Math.max(1, Math.ceil(totalElements / uiSize));
const safePage = Math.min(Math.max(1, pageNum), totalPages);
const start = (safePage - 1) * uiSize;
const pageSlice = list.slice(start, start + uiSize);
data.value.results = pageSlice.map(toRow);
data.value.totalElements = totalElements;
data.value.pageLength = totalPages;
return;
}
data.value.results = (list as any[]).map(toRow);
data.value.totalElements = result?.totalElements ?? list.length;
data.value.pageLength = result?.totalPages ?? 1;
} catch (err) {
console.error("[TrainingScript] 조회 에러:", err);
data.value.results = [];
data.value.totalElements = 0;
data.value.pageLength = 1;
}
};
const removeData = (value) => {
let removeList = value ? value : data.value.selected;
const remove = (code) => {
// return DeviceService.delete(code).then((d) => {
// if (d.status !== 200) {
// store.setSnackbarMsg({
// text: d,
// result: 500,
// });
// }
// });
/** 검색 실행 (페이지 1로 리셋) */
const doSearch = () => {
data.value.params.pageNum = 1;
fetchList();
};
if (removeList.length === 1) {
remove(removeList[0].deviceKey).then(() => {
// store.setSnackbarMsg({
// text: ".",
// result: 200,
// });
changePageNum();
data.value.isConfirmDialogVisible = false;
data.value.selected = [];
data.value.allSelected = false;
/** 페이지 이동 */
const changePageNum = (page: number) => {
data.value.params.pageNum = page;
fetchList();
};
/** 페이지 사이즈 변경 */
const changePageSize = (size: number) => {
data.value.params.pageSize = size;
data.value.params.pageNum = 1;
fetchList();
};
// / ( )
const removeData = (value?: Array<{ deviceKey: number }>) => {
const removeList = value ?? data.value.selected;
if (!removeList || removeList.length === 0) return;
const ids = removeList.map((x) => x.deviceKey);
const removeOne = (id: number) =>
AttachmentsService.delete(id).then((res) => {
if (res.status < 200 || res.status >= 300) return Promise.reject(res);
});
} else {
Promise.all(removeList.map((item) => remove(item.deviceKey))).finally(
() => {
// store.setSnackbarMsg({
// text: " .",
// result: 200,
// });
changePageNum();
const after = () => {
if (
ids.length >= data.value.results.length &&
data.value.params.pageNum > 1
) {
data.value.params.pageNum -= 1;
}
fetchList();
data.value.isConfirmDialogVisible = false;
data.value.selected = [];
data.value.allSelected = false;
},
);
}
};
const handleRemoveData = () => {
if (data.value.selected.length === 0) {
// store.setSnackbarMsg({
// text: " . ",
// result: 500,
// });
return;
}
if (data.value.allSelected || data.value.selected.length !== 1) {
data.value.isConfirmDialogVisible = true;
return;
// /
if (ids.length === 1) {
removeOne(ids[0])
.then(() => {
store.setSnackbarMsg({
color: "success",
text: "삭제되었습니다.",
result: 200,
});
after();
})
.catch((err) => {
console.error("삭제 실패:", err);
store.setSnackbarMsg({
color: "warning",
text: "삭제 실패",
result: 500,
});
});
} else {
Promise.all(ids.map(removeOne))
.then(() => {
store.setSnackbarMsg({
color: "success",
text: "모두 삭제되었습니다.",
result: 200,
});
})
.catch((err) => {
console.error("일부 삭제 실패:", err);
store.setSnackbarMsg({
color: "warning",
text: "일부 삭제 실패",
result: 500,
});
})
.finally(after);
}
//
removeData(undefined);
};
const closeDetail = () => {
openView.value = false;
};
const changePageNum = (page) => {
data.value.params.pageNum = page;
getData();
};
const openSettingModal = (selectedItem) => {
const openDetailModal = (selectedItem: any) => {
data.value.selectedData = selectedItem;
data.value.modalMode = "setting";
openView.value = true;
};
const openCreateModal = () => {
data.value.selectedData = null;
data.value.modalMode = "create";
data.value.selectedData = {
username: username.value,
projectId: getProjectId(),
};
data.value.isCreateVisible = true;
};
const openModifyModal = () => {
data.value.selectedData = null;
const openModifyModal = (item: any) => {
data.value.modalMode = "edit";
data.value.isUploadVisible = true;
data.value.selectedData = {
id: item.deviceKey,
title: item.title,
description: item.description,
};
data.value.isCreateVisible = true;
};
const closeCreateModal = () => {
data.value.isModalVisible = false;
data.value.isCreateVisible = null;
data.value.isCreateVisible = false;
data.value.selectedData = null;
};
const closeModifyModal = () => {
data.value.isModalVisible = false;
data.value.isUploadVisible = null;
data.value.isUploadVisible = false;
data.value.selectedData = null;
};
const getSelectedAllData = () => {
data.value.selected = data.value.allSelected
? data.value.results.map((item) => {
return {
deviceKey: item.deviceKey,
};
})
? data.value.results.map((item: any) => ({ deviceKey: item.deviceKey }))
: [];
};
onMounted(() => {
getData();
getCodeList();
username.value = readUsernameFromStorage();
fetchList();
});
</script>
<template>
<div class="w-100" v-if="!openView">
<!-- <v-dialog v-model="data.isModalVisible" max-width="600" persistent>-->
<!-- <FormComponent-->
<!-- :edit-data="data.selectedData"-->
<!-- :mode="data.modalMode"-->
<!-- @close-modal="closeModal"-->
<!-- @handle-data="saveData"-->
<!-- :user-option="data.userOption"-->
<!-- />-->
<!-- </v-dialog>-->
<!-- <v-dialog v-model="data.isConfirmDialogVisible" persistent max-width="300">-->
<!-- <ConfirmDialogComponent-->
<!-- @cancel="data.isConfirmDialogVisible = false"-->
<!-- @delete="removeData(undefined)"-->
<!-- @init="(data.selected = []), (data.allSelected = false)"-->
<!-- />-->
<!-- </v-dialog>-->
<v-container fluid class="h-100 pa-5 d-flex flex-column align-center">
<v-card
flat
class="bg-shades-transparent d-flex flex-column align-center justify-center w-100"
>
<!-- 헤더 -->
<v-card flat class="bg-shades-transparent w-100">
<v-card-item class="text-h5 font-weight-bold pt-0 pa-5 pl-0">
<div class="d-flex flex-row justify-start align-center">
@ -343,7 +337,9 @@ onMounted(() => {
</div>
</v-card-item>
</v-card>
<v-card flat class="bg-shades-transparent w-100">
<!-- 검색 영역 -->
<v-card flat class="bg-shades-transparent mb-4">
<div class="d-flex justify-center flex-wrap align-center">
<v-responsive
@ -356,11 +352,12 @@ onMounted(() => {
label="검색조건"
density="compact"
:items="searchOptions"
item-title="searchType"
item-value="searchText"
item-title="label"
item-value="value"
hide-details
></v-select>
/>
</v-responsive>
<v-responsive min-width="540" max-width="540">
<v-text-field
v-model="data.params.searchText"
@ -370,8 +367,8 @@ onMounted(() => {
required
class="mt-3 mb-3"
hide-details
@keyup.enter="changePageNum(1)"
></v-text-field>
@keyup.enter="doSearch"
/>
</v-responsive>
<div class="ml-3">
@ -379,7 +376,7 @@ onMounted(() => {
size="large"
color="primary"
:rounded="5"
@click="changePageNum(1)"
@click="doSearch"
>
<v-icon>mdi-magnify</v-icon>
</v-btn>
@ -387,6 +384,7 @@ onMounted(() => {
</div>
</v-card>
<!-- 상단 툴바 -->
<v-sheet
class="bg-shades-transparent d-flex flex-wrap align-center mb-2"
>
@ -394,10 +392,12 @@ onMounted(() => {
<v-sheet
class="d-flex align-center mr-3 mb-2 bg-shades-transparent"
>
<!-- 스크립트의 totalElements 사용 -->
<v-chip color="primary"
> {{ data.totalDataLength.toLocaleString() }}
</v-chip>
> {{ data.totalElements.toLocaleString() }}</v-chip
>
</v-sheet>
<v-sheet class="bg-shades-transparent">
<v-responsive max-width="140" min-width="140" class="mb-2">
<v-select
@ -409,18 +409,18 @@ onMounted(() => {
variant="outlined"
color="primary"
hide-details
@update:model-value="changePageNum(1)"
></v-select>
@update:model-value="changePageSize"
/>
</v-responsive>
</v-sheet>
</v-sheet>
<v-sheet class="justify-end mb-2">
<v-btn color="info" @click="openCreateModal"
>Create Dataset
</v-btn>
<v-btn color="info" @click="openCreateModal">Add Dataset</v-btn>
</v-sheet>
</v-sheet>
<!-- 목록 -->
<v-card class="rounded-lg pa-8">
<v-col cols="12">
<v-sheet>
@ -428,8 +428,6 @@ onMounted(() => {
density="comfortable"
fixed-header
height="625"
col-md-12
col-12
overflow-x-auto
>
<colgroup>
@ -439,18 +437,20 @@ onMounted(() => {
:style="`width:${item.width}`"
/>
</colgroup>
<thead>
<tr>
<th
v-for="(item, i) in tableHeader"
:key="i"
class="text-center font-weight-bold"
:style="`${item.style}`"
:style="item.style"
>
{{ item.label }}
</th>
</tr>
</thead>
<tbody class="text-body-2">
<tr
v-for="(item, i) in data.results"
@ -464,8 +464,8 @@ onMounted(() => {
<td>{{ item.createdData }}</td>
<td>{{ item.modifiedData }}</td>
<td style="white-space: nowrap">
<IconInfoBtn @on-click="openSettingModal(item)" />
<IconModifyBtn @on-click="openModifyModal()" />
<IconInfoBtn @on-click="openDetailModal(item)" />
<IconModifyBtn @on-click="openModifyModal(item)" />
<IconDeleteBtn
@on-click="
removeData([{ deviceKey: item.deviceKey }])
@ -476,6 +476,7 @@ onMounted(() => {
</tbody>
</v-table>
</v-sheet>
<v-card-actions class="text-center mt-8 justify-center">
<v-pagination
v-model="data.params.pageNum"
@ -483,36 +484,33 @@ onMounted(() => {
:total-visible="10"
color="primary"
rounded="circle"
@update:model-value="getData"
></v-pagination>
@update:model-value="changePageNum"
/>
</v-card-actions>
</v-col>
</v-card>
</v-card>
</v-card>
</v-container>
<!-- 등록 다이얼로그 -->
<v-dialog v-model="data.isCreateVisible" max-width="600" persistent>
<DatasetsBaseDoalog
<DatasetBaseDoalog
:edit-data="data.selectedData"
:mode="data.modalMode"
@close-modal="closeCreateModal"
@handle-data="saveData"
:user-option="data.userOption"
/>
</v-dialog>
<v-dialog v-model="data.isUploadVisible" max-width="600" persistent>
<DatasetsBaseDoalog
:edit-data="data.selectedData"
:mode="data.modalMode"
@close-modal="closeModifyModal"
@handle-data="saveData"
@saved="fetchList"
:user-option="data.userOption"
/>
</v-dialog>
</div>
<div class="w-100" v-else>
<ViewComponent @close="closeDetail" />
<ViewComponent
v-if="data.selectedData"
:id="data.selectedData.deviceKey"
@close="closeDetail"
/>
</div>
</template>

@ -1,147 +1,164 @@
<script setup lang="ts">
import IconDeleteBtn from "@/components/atoms/button/IconDeleteBtn.vue";
import IconModifyBtn from "@/components/atoms/button/IconModifyBtn.vue";
// import FormComponent from "@/components/device/FormComponent.vue";
import { onMounted, ref } from "vue";
// const store = commonStore();
import { ref, computed, onMounted, watch } from "vue";
import { AttachmentsService } from "@/components/service/management/attachmentsService";
import { ProjectService } from "@/components/service/project/projectService";
// id +
const props = defineProps<{ id: number | string }>();
const emit = defineEmits<{ (e: "close"): void }>();
// -------- state --------
const loading = ref(false);
const detailRaw = ref<any | null>(null);
const experimentInfo = ref({
datasetTitle: "자율주행차량 배터리 상태 예측 모델 구축",
projectName: "배터리 상태 예측 모델 프로젝트",
version: "2.0",
createdDate: "2025-02-06",
createdId: "ADMIN_001",
modifiedDate: "2025-04-30",
modifiedId: "USER_002",
description: "날씨, 조도, 도로 상태 등의 주행환경 데이터",
fileName: "environment_log.csv",
fileSize: "58KB",
datasetTitle: "-",
projectName: "-",
version: "-",
createdDate: "-",
createdId: "-",
modifiedDate: "-",
modifiedId: "-",
description: "-",
fileName: "-",
fileSize: "-",
});
const data = ref({
params: {
pageNum: 1,
pageSize: 10,
searchType: "",
searchText: "",
},
results: [],
totalDataLength: 0,
pageLength: 0,
modalMode: "",
selectedData: null,
allSelected: false,
selected: [],
isModalVisible: false,
isConfirmDialogVisible: false,
userOption: [],
});
const downloadObjectName = computed(() => detailRaw.value?.storagePath || "");
const canDownload = computed(() => !!downloadObjectName.value);
const getCodeList = () => {
// UserService.search(data.value.params).then((d) => {
// if (d.status === 200) {
// data.value.userOption = d.data.userList;
// }
// });
};
async function handleDownload() {
const key = downloadObjectName.value.trim();
if (!key) return;
const setPaginationLength = () => {
if (data.value.totalDataLength % data.value.params.pageSize === 0) {
data.value.pageLength =
data.value.totalDataLength / data.value.params.pageSize;
} else {
data.value.pageLength = Math.ceil(
data.value.totalDataLength / data.value.params.pageSize,
);
const res = await AttachmentsService.downloadFile(key);
const ct = String(res.headers["content-type"] || "").toLowerCase();
if (ct.includes("application/json")) {
const text = await (res.data as Blob).text();
try {
const json = JSON.parse(text);
throw new Error(json.message || text);
} catch {
throw new Error(text);
}
}
};
const saveData = (formData) => {
if (data.value.modalMode === "create") {
// DeviceService.add(formData).then((d) => {
// if (d.status === 200) {
// data.value.isModalVisible = false;
// store.setSnackbarMsg({
// text: " .",
// result: 200,
// });
// changePageNum(1);
// } else {
// store.setSnackbarMsg({
// text: d,
// result: 500,
// });
// }
// });
} else {
// DeviceService.update(formData.deviceKey, formData).then((d) => {
// if (d.status === 200) {
// data.value.isModalVisible = false;
// store.setSnackbarMsg({
// text: " .",
// result: 200,
// });
// changePageNum();
// } else {
// store.setSnackbarMsg({
// text: d,
// result: 500,
// });
// }
// });
const cd = res.headers["content-disposition"] || "";
let filename: string | undefined;
const mUtf8 = cd.match(/filename\*\s*=\s*UTF-8''([^;]+)/i);
const mStd = cd.match(/filename\s*=\s*(?:"([^"]+)"|([^;]+))/i);
if (mUtf8?.[1]) {
try {
filename = decodeURIComponent(mUtf8[1].trim());
} catch {
filename = mUtf8[1].trim();
}
} else if (mStd) {
filename = (mStd[1] || mStd[2])?.trim();
}
// 2) : objectName basename (fallback)
if (!filename) {
// key : "11fc4121-...-mlflow_pipeline.yaml" "dir/subdir/11fc...yaml"
const parts = key.split(/[\\/]/);
filename = parts[parts.length - 1] || "download.bin";
}
const blob = new Blob([res.data]);
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.setAttribute("download", filename);
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
}
// -------- utils --------
const formatIso = (s?: string) =>
s ? String(s).replace("T", " ").slice(0, 19) : "-";
const formatBytes = (b?: number) => {
const n = Number(b);
if (!Number.isFinite(n) || n < 0) return "-";
if (n < 1024) return `${n} B`;
const u = ["KB", "MB", "GB", "TB"];
let i = -1,
v = n;
do {
v /= 1024;
i++;
} while (v >= 1024 && i < u.length - 1);
return `${v.toFixed(1)} ${u[i]}`;
};
const removeData = (value) => {
let removeList = value ? value : data.value.selected;
const remove = (code) => {
// return DeviceService.delete(code).then((d) => {
// if (d.status !== 200) {
// store.setSnackbarMsg({
// text: d,
// result: 500,
// });
// }
// });
//
const mapToViewModel = (raw: any) => {
const projectName =
raw?.projectName ?? raw?.project?.name ?? raw?.prjNm ?? "-";
const size = raw?.fileSize ?? raw?.size ?? raw?.length ?? undefined;
return {
datasetTitle: raw?.title ?? "-",
projectName,
version: raw?.version ?? "-",
createdDate: formatIso(raw?.regDt),
createdId: raw?.regUserId ?? "-",
modifiedDate: formatIso(raw?.modDt),
modifiedId: raw?.modUserId ?? "-",
description: raw?.description ?? "-",
fileName: raw?.originalName ?? "-",
fileSize: formatBytes(size),
};
};
if (removeList.length === 1) {
remove(removeList[0].deviceKey).then(() => {
// store.setSnackbarMsg({
// text: ".",
// result: 200,
// });
async function fetchProjectName(projectId?: number) {
if (!projectId && projectId !== 0) return;
try {
const res = await ProjectService.fetchProjectById(projectId as number);
const prj = res?.data ?? res;
experimentInfo.value.projectName = prj?.prjNm ?? prj?.name ?? "-";
} catch (e) {
console.warn("[Experiment/View] project fetch fail:", e);
}
}
data.value.isConfirmDialogVisible = false;
data.value.selected = [];
data.value.allSelected = false;
});
} else {
Promise.all(removeList.map((item) => remove(item.deviceKey))).finally(
() => {
// store.setSnackbarMsg({
// text: " .",
// result: 200,
// });
const info = computed(() => mapToViewModel(detailRaw.value || {}));
data.value.isConfirmDialogVisible = false;
data.value.selected = [];
data.value.allSelected = false;
},
);
async function fetchDetail(id: number | string) {
const idNum = typeof id === "string" ? Number(id) : id;
if (!Number.isFinite(idNum as number)) {
console.warn("[Datasets/View] invalid id:", id);
return;
}
};
const changePageNum = (page) => {
data.value.params.pageNum = page;
};
loading.value = true;
try {
const res = await AttachmentsService.view(idNum as number);
detailRaw.value = res?.data ?? res;
const emit = defineEmits<{
(e: "close"): void;
}>();
experimentInfo.value = mapToViewModel(detailRaw.value);
await fetchProjectName(detailRaw.value?.projectId);
} catch (e) {
console.error("[Datasets/View] fetch detail error:", e);
} finally {
loading.value = false;
}
}
// -------- lifecycle --------
onMounted(() => {
getCodeList();
fetchDetail(props.id);
});
watch(
() => props.id,
(nv) => {
if (nv !== undefined && nv !== null && nv !== "") fetchDetail(nv);
},
);
</script>
<template>
@ -191,19 +208,6 @@ onMounted(() => {
<v-col cols="3" class="text-h6 font-weight-bold">Created ID </v-col>
<v-col cols="3" class="pa-2">{{ experimentInfo.createdId }}</v-col>
</v-row>
<VDivider class="my-2" />
<v-row align="center" class="py-2">
<v-col cols="3" class="text-h6 font-weight-bold"
>Modified Date
</v-col>
<v-col cols="3" class="pa-2">{{
experimentInfo.modifiedDate
}}</v-col>
<v-col cols="3" class="text-h6 font-weight-bold"
>Modified ID
</v-col>
<v-col cols="3" class="pa-2">{{ experimentInfo.modifiedId }}</v-col>
</v-row>
<VDivider class="my-2" />
@ -217,7 +221,20 @@ onMounted(() => {
<VDivider class="my-2" />
<v-row align="center" class="py-2">
<v-col cols="3" class="text-h6 font-weight-bold">File</v-col>
<v-col cols="9" class="pa-2">{{ experimentInfo.fileName }}</v-col>
<v-col cols="9" class="pa-2 d-flex align-center">
<span class="text-truncate">{{ experimentInfo.fileName }}</span>
<v-btn
icon
variant="text"
size="small"
class="ml-2"
:disabled="!canDownload"
@click="handleDownload"
aria-label="download"
>
<v-icon>mdi-download</v-icon>
</v-btn>
</v-col>
</v-row>
</v-card-text>
<v-sheet class="d-flex justify-end mb-2">

@ -1,30 +1,41 @@
<script setup lang="ts">
import { onMounted, ref, computed } from "vue";
import { onMounted, ref, computed, watch } from "vue";
import Plotly from "plotly.js-dist-min";
import { WorkflowService } from "@/components/service/management/workflowService";
import { useAutoflowStore } from "@/stores/autoflowStore";
const store = useAutoflowStore();
const currentProjectId = computed(() => store.projectId);
const pieChartRef = ref<HTMLElement | null>(null);
const workflows = ref<any[]>([]);
const recentLimit = 10;
onMounted(() => {
if (pieChartRef.value) {
Plotly.newPlot(
pieChartRef.value,
[
{
values: [40, 25, 20, 15],
labels: ["Success", "Pending", "Failed", "Cancelled"],
// ---- kubeflowStatus ( , ) ----
function renderStatusPie() {
if (!pieChartRef.value) return;
const counts = new Map<string, number>();
for (const wf of workflows.value ?? []) {
const status =
String(wf?.kubeflowStatus ?? wf?.kubeflow_status ?? "Unknown").trim() ||
"Unknown";
counts.set(status, (counts.get(status) || 0) + 1);
}
const labels = Array.from(counts.keys());
const values = Array.from(counts.values());
const trace: Partial<Plotly.PlotData> = {
values: values.length ? values : [1],
labels: labels.length ? labels : ["No Data"],
type: "pie",
marker: {
colors: ["#4caf50", "#ff9800", "#f44336", "#9e9e9e"],
},
textinfo: "label+percent",
textfont: { color: "#fff", size: 14 },
hole: 0.4,
},
],
{
};
const layout: Partial<Plotly.Layout> = {
paper_bgcolor: "#1e1e1e",
plot_bgcolor: "#1e1e1e",
showlegend: true,
@ -36,12 +47,12 @@ onMounted(() => {
y: -0.2,
},
margin: { t: 20, b: 40, l: 0, r: 0 },
},
{ displayModeBar: false },
);
};
Plotly.react(pieChartRef.value, [trace], layout, { displayModeBar: false });
}
});
// ---- ( ) ----
const recentRuns = [
{ name: "Model A - v1", status: "success", time: "2025-05-12 09:12" },
{ name: "Model B - tuning", status: "success", time: "2025-05-14 08:59" },
@ -55,12 +66,7 @@ const datasetUpdates = [
{ name: "Traffic_log", count: 2 },
{ name: "Traffic_log2", count: 2 },
];
const dummyWorkflow = [
{ title: "Volcano Test Pipeline", date: "2025-05-13 08:12" },
{ title: "Volcano Test Pipeline", date: "2025-05-13 08:12" },
{ title: "XGBoost Training", date: "2025-05-13 08:12" },
{ title: "Data Preprocess Flow", date: "2025-05-13 08:12" },
];
const tableHeader = [
{ label: "Model Name", width: "10%", style: "word-break: keep-all;" },
{ label: "Version", width: "10%", style: "word-break: keep-all;" },
@ -96,10 +102,10 @@ const data = ref({
download: "Failed",
},
],
allSelected: false,
selected: [],
});
const handleRefresh = () => {
alert("Refresh 작업 진행중...");
};
@ -109,26 +115,24 @@ const getSelectedAllData = () => {
: [];
};
const getLatestTimestamp = (wf: any): string =>
wf?.modDttm || wf?.modDt || wf?.regDttm || wf?.regDt || "";
const getLatestTimestamp = (wf: any): string => wf.modDt;
// "YYYY-MM-DD HH:mm"
const formatToYmdHm = (isoString: string): string => {
if (!isoString) return "-";
const dateObj = new Date(isoString);
const pad2 = (n: number) => String(n).padStart(2, "0");
return `${dateObj.getFullYear()}-${pad2(dateObj.getMonth() + 1)}-${pad2(dateObj.getDate())} ${pad2(dateObj.getHours())}:${pad2(dateObj.getMinutes())}`;
const d = new Date(isoString);
const pad = (n: number) => String(n).padStart(2, "0");
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
};
// ( + )
const recentWorkflowList = computed(() => {
return (workflows.value ?? [])
.map((wf: any) => ({
id: wf?.id,
title: wf?.workflowName ?? "Untitled",
id: wf.id,
title: wf.name,
timestamp: getLatestTimestamp(wf),
}))
.filter((item: { timestamp: string }) => item.timestamp) //
.filter((item) => item.title && item.timestamp)
.sort(
(a, b) =>
new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime(),
@ -136,15 +140,47 @@ const recentWorkflowList = computed(() => {
.slice(0, recentLimit);
});
onMounted(async () => {
// ---- & ----
async function loadWorkflows() {
try {
const res = await WorkflowService.getAll();
workflows.value = Array.isArray(res?.data) ? res.data : [];
const payload = {
page: 0,
size: 1000,
projectId: currentProjectId.value,
sortField: "id",
sortDirection: "DESC",
};
const res = await WorkflowService.search(payload);
const raw = Array.isArray(res?.data?.content)
? res.data.content
: Array.isArray(res?.data)
? res.data
: [];
workflows.value = raw.filter(
(wf: any) =>
String(
wf?.projectId ?? wf?.prjId ?? wf?.project_id ?? wf?.project?.id ?? "",
) === String(currentProjectId.value),
);
renderStatusPie();
} catch (err) {
console.error("GET /api/workflows failed:", err);
workflows.value = [];
renderStatusPie();
}
}
onMounted(async () => {
// ,
renderStatusPie();
await loadWorkflows();
});
//
watch(currentProjectId, () => loadWorkflows());
</script>
<template>

@ -2,20 +2,29 @@
import { ref, onMounted, watch, computed } from "vue";
import { commonStore } from "@/stores/commonStore";
import { storage } from "@/utils/storage.js";
import { ProjectService } from "@/components/service/project/projectService";
import { UserManagerService } from "@/components/service/management/userManagerService";
import type { Permission } from "@/components/models/project/Project";
import IconDeleteBtn from "@/components/atoms/button/IconDeleteBtn.vue";
import IconModifyBtn from "@/components/atoms/button/IconModifyBtn.vue";
import type {
Permission,
ApiProject,
} from "@/components/models/project/Project";
//
// /
//
const store = commonStore();
type SearchType = "전체" | "제목" | "작성자";
const searchOptions = [
{ label: "전체", value: "전체" as SearchType },
{ label: "제목", value: "제목" as SearchType },
{ label: "작성자", value: "작성자" as SearchType },
];
const SEARCH_TYPE_MAP: Record<SearchType | "", "ALL" | "TITLE" | "AUTHOR"> = {
"": "ALL",
전체: "ALL",
제목: "TITLE",
작성자: "AUTHOR",
};
const DEFAULT_PERMISSIONS: Permission[] = [
"CREATE",
"READ",
@ -31,9 +40,6 @@ const refreshRoles = () => {
};
const isAdmin = computed(() => roles.value.includes("ROLE_ADMIN"));
//
// / (UI )
//
const tableHeader = [
{ label: "No", width: "5%", style: "word-break: keep-all;" },
{ label: "Project Name", width: "20%", style: "word-break: keep-all;" },
@ -43,13 +49,6 @@ const tableHeader = [
{ label: "Action", width: "13%", style: "word-break: keep-all;" },
];
const searchOptions = [
{ searchType: "전체", searchText: "" },
{ searchType: "프로젝트명", searchText: "prjNm" },
{ searchType: "설명", searchText: "prjDesc" },
{ searchType: "생성자", searchText: "regUserId" },
];
const pageSizeOptions = [
{ text: "10 페이지", value: 10 },
{ text: "50 페이지", value: 50 },
@ -60,13 +59,23 @@ type Row = {
no: number;
name: string;
desc: string;
users: string[];
users: string[]; // (= mod_user_nm )
registDt: string;
deviceKey: number;
};
// reg ( )
const projectRegById = ref<Record<number, { regId?: string; regNm?: string }>>(
{},
);
const data = ref({
params: { pageNum: 1, pageSize: 10, searchType: "", searchText: "" },
params: {
pageNum: 1,
pageSize: 10,
searchType: "전체" as SearchType,
searchText: "",
},
results: [] as Row[],
totalDataLength: 0,
pageLength: 0,
@ -87,60 +96,157 @@ const splitCsv = (v?: string) =>
.map((s) => s.trim())
.filter(Boolean);
//
/** 사용자 목록 (v-select items) */
//
type UserOption = { id: number | string; username: string };
const userOptions = ref<UserOption[]>([]);
async function loadUsers() {
const { data } = await UserManagerService.getAll();
const raw = data as Array<{ id: number | string; username: string }>;
userOptions.value = raw.map((u) => ({ id: u.id, username: u.username }));
}
//
/** 목록 로드: 카드형 로직과 동일한 응답을 테이블 Row로 매핑 */
//
function toRow(p: any, index: number, offset: number): Row {
// UI (mod_user_nm )
function toRow(p: any, no: number): Row {
let displayNm = "";
if (typeof p.modUserNm === "string" && p.modUserNm.length > 0)
displayNm = p.modUserNm;
else if (typeof p.regUserNm === "string") displayNm = p.regUserNm;
// reg
projectRegById.value[p.id] = { regId: p.regUserId, regNm: p.regUserNm };
return {
no: offset + index + 1,
name: p.prjNm ?? "-",
desc: p.prjDesc ?? "-",
users: splitCsv(p.regUserId ?? p.regUserNm),
registDt: fmtDate(p.regDate ?? p.prjStartDt),
no,
name: p.prjNm,
desc: p.prjDesc,
users: splitCsv(displayNm),
registDt: fmtDate(p.prjStartDt), //
deviceKey: p.id,
};
}
/** ===== 목록 조회 (검색/페이지네이션 포함) ===== */
async function getData() {
const { pageNum, pageSize } = data.value.params;
const startIndex = (pageNum - 1) * pageSize;
const { pageNum, pageSize, searchType, searchText } = data.value.params;
const mapped = SEARCH_TYPE_MAP[searchType] || "ALL";
const keyword = (searchText || "").trim();
const res = await ProjectService.search();
const raw = Array.isArray(res.data) ? res.data : (res.data?.content ?? []);
const needLocalFilter = mapped !== "ALL" && keyword.length > 0;
data.value.totalDataLength = Array.isArray(res.data)
? raw.length
: (res.data?.totalElements ?? raw.length);
let reqPage = data.value.params.pageNum;
let reqSize = data.value.params.pageSize;
if (needLocalFilter) {
reqPage = 0;
reqSize = 1000;
}
const payload = {
page: reqPage,
size: reqSize,
keyword,
searchType: mapped,
sortField: "id",
sortDirection: "DESC",
};
try {
const res = await ProjectService.searchProjects(payload as any);
const result = res?.data ?? res;
let list: any[] = result?.content ?? (Array.isArray(result) ? result : []);
//
if (needLocalFilter) {
const kw = keyword.toLowerCase();
if (mapped === "TITLE") {
list = list.filter((x: any) =>
String(x?.prjNm ?? "")
.toLowerCase()
.includes(kw),
);
} else if (mapped === "AUTHOR") {
list = list.filter((x: any) => {
let authorStr = "";
if (typeof x.modUserNm === "string" && x.modUserNm.length > 0)
authorStr = x.modUserNm;
else if (typeof x.regUserNm === "string") authorStr = x.regUserNm;
return authorStr.toLowerCase().includes(kw);
});
}
const uiSize = data.value.params.pageSize;
const totalElements = list.length;
const totalPages = Math.max(1, Math.ceil(totalElements / uiSize));
const safePage = Math.min(Math.max(1, pageNum), totalPages);
const start = (safePage - 1) * uiSize;
const pageSlice = list.slice(start, start + uiSize);
const slice = Array.isArray(res.data)
? raw.slice(startIndex, startIndex + pageSize)
: raw;
data.value.results = slice.map((p: any, i: number) =>
toRow(p, i, startIndex),
const firstNo = totalElements - start;
// reg
projectRegById.value = {};
data.value.results = pageSlice.map((p: any, i: number) =>
toRow(p, Math.max(1, firstNo - i)),
);
data.value.totalDataLength = totalElements;
data.value.pageLength = totalPages;
return;
}
const total = data.value.totalDataLength || 0;
const totalElements =
typeof result?.totalElements === "number"
? result.totalElements
: (list.length ?? 0);
const serverPage = result?.pageable?.pageNumber;
const serverSize = result?.pageable?.pageSize;
const offset =
typeof result?.pageable?.offset === "number"
? result.pageable.offset
: typeof serverPage === "number" && typeof serverSize === "number"
? serverPage * serverSize
: (pageNum - 1) * pageSize;
const firstNo = totalElements - offset;
// reg
projectRegById.value = {};
data.value.results = list.map((p: any, i: number) =>
toRow(p, Math.max(1, firstNo - i)),
);
data.value.totalDataLength = totalElements;
data.value.pageLength =
total % data.value.params.pageSize === 0
? total / data.value.params.pageSize
: Math.ceil(total / data.value.params.pageSize);
typeof result?.totalPages === "number"
? result.totalPages
: Math.max(1, Math.ceil(totalElements / pageSize));
} catch (e) {
console.error("[Project] search error:", e);
data.value.results = [];
data.value.totalDataLength = 0;
data.value.pageLength = 1;
}
}
/** 트리거 */
function doSearch() {
data.value.params.pageNum = 1;
getData();
}
function changePageSize(size: number) {
data.value.params.pageSize = size;
data.value.params.pageNum = 1;
getData();
}
function changePageNum(page: number) {
data.value.params.pageNum = page;
getData();
}
watch(
() => data.value.params.searchType,
() => doSearch(),
);
//
/** 폼 & 권한 부여 & 저장 흐름 (카드형과 동일) */
//
/** ===== 생성/수정 다이얼로그 ===== */
const form = ref({
prjCd: "",
prjNm: "",
@ -156,12 +262,52 @@ const resetForm = () => {
form.value.selectedUsers = [];
};
const buildApiPayload = (): ApiProject => {
// payload (mod* )
type NewProjectPayload = {
id: null;
prjCd: string;
prjNm: string;
prjDesc: string;
prjStartDt: string;
prjEndDt: string;
delYn: string;
regDate: string;
regUserId?: string;
regUserNm?: string;
};
// payload (reg* , mod* )
type UpdateProjectPayload = {
id: number;
prjCd: string;
prjNm: string;
prjDesc: string;
prjStartDt: string;
prjEndDt: string;
delYn: string;
regDate: string;
regUserId?: string;
regUserNm?: string;
modDate: string;
modUserId?: string;
modUserNm?: string;
};
function buildCreatePayload(): NewProjectPayload {
const today = new Date().toISOString().slice(0, 10);
const nowIso = new Date().toISOString();
const namesCsv = form.value.selectedUsers.join(",");
const names = form.value.selectedUsers;
const namesCsv = names.join(",");
const idsCsv = names
.map((name) => userOptions.value.find((u) => u.username === name)?.id)
.filter(
(v): v is number | string => v !== undefined && v !== null && v !== "",
)
.map(String)
.join(",");
return {
id: data.value.modalMode === "edit" ? editingProjectId.value! : null,
id: null,
prjCd: form.value.prjCd,
prjNm: form.value.prjNm,
prjDesc: form.value.prjDesc,
@ -169,13 +315,44 @@ const buildApiPayload = (): ApiProject => {
prjEndDt: today,
delYn: "N",
regDate: nowIso,
regUserId: namesCsv,
regUserId: idsCsv,
regUserNm: namesCsv,
};
}
function buildUpdatePayload(): UpdateProjectPayload {
const today = new Date().toISOString().slice(0, 10);
const nowIso = new Date().toISOString();
const names = form.value.selectedUsers;
const namesCsv = names.join(",");
const idsCsv = names
.map((name) => userOptions.value.find((u) => u.username === name)?.id)
.filter(
(v): v is number | string => v !== undefined && v !== null && v !== "",
)
.map(String)
.join(",");
const id = editingProjectId.value!;
const kept = projectRegById.value[id] || {};
return {
id,
prjCd: form.value.prjCd,
prjNm: form.value.prjNm,
prjDesc: form.value.prjDesc,
prjStartDt: today,
prjEndDt: today,
delYn: "N",
regDate: nowIso,
regUserId: kept.regId,
regUserNm: kept.regNm,
modDate: nowIso,
modUserId: namesCsv,
modUserId: idsCsv,
modUserNm: namesCsv,
};
};
}
async function grantDefaultPermissions(projectId: number, usernames: string[]) {
if (!usernames?.length) return;
@ -198,13 +375,14 @@ async function grantDefaultPermissions(projectId: number, usernames: string[]) {
async function saveProject() {
try {
const payload = buildApiPayload();
let projectId: number;
if (data.value.modalMode === "create") {
const payload = buildCreatePayload();
const res = await ProjectService.add(payload);
projectId = res.data.id;
} else {
const payload = buildUpdatePayload();
await ProjectService.update(editingProjectId.value!, payload);
projectId = editingProjectId.value!;
}
@ -217,15 +395,41 @@ async function saveProject() {
}
}
//
//
//
function openCreateModal() {
data.value.modalMode = "create";
editingProjectId.value = null;
resetForm();
data.value.isCreateVisible = true;
}
function openEditModal(row: Row) {
data.value.modalMode = "edit";
editingProjectId.value = row.deviceKey;
form.value.prjCd = row.name;
form.value.prjNm = row.name;
form.value.prjDesc = row.desc === "-" ? "" : row.desc;
form.value.selectedUsers = Array.isArray(row.users) ? [...row.users] : [];
//
const known = new Set(userOptions.value.map((u) => u.username));
const missing = form.value.selectedUsers
.filter((u) => !known.has(u))
.map((u) => ({ id: u, username: u }));
if (missing.length) userOptions.value = [...userOptions.value, ...missing];
data.value.isCreateVisible = true;
}
function getSelectedAllData() {
data.value.selected = data.value.allSelected
? data.value.results.map((r) => ({ deviceKey: r.deviceKey }))
: [];
}
async function deleteRows(targetList?: Array<{ deviceKey: number }>) {
const removeList = targetList ?? data.value.selected;
if (!removeList?.length) return;
const ids = removeList.map((x) => x.deviceKey);
const remove = (id: number) =>
ProjectService.delete(id).then((res) => {
if (res.status < 200 || res.status >= 300) return Promise.reject(res);
@ -283,55 +487,6 @@ async function deleteRows(targetList?: Array<{ deviceKey: number }>) {
}
}
//
// UI ( / )
//
function getSelectedAllData() {
data.value.selected = data.value.allSelected
? data.value.results.map((r) => ({ deviceKey: r.deviceKey }))
: [];
}
function changePageNum(page: number) {
data.value.params.pageNum = page;
getData();
}
function openCreateModal() {
data.value.modalMode = "create";
editingProjectId.value = null;
resetForm();
data.value.isCreateVisible = true;
}
function openEditModal(row: Row) {
data.value.modalMode = "edit";
editingProjectId.value = row.deviceKey;
form.value.prjCd = row.name;
form.value.prjNm = row.name;
form.value.prjDesc = row.desc === "-" ? "" : row.desc;
form.value.selectedUsers = Array.isArray(row.users) ? [...row.users] : [];
// v-select
const known = new Set(userOptions.value.map((u) => u.username));
const missing = form.value.selectedUsers
.filter((u) => !known.has(u))
.map((u) => ({ id: u, username: u }));
if (missing.length) userOptions.value = [...userOptions.value, ...missing];
data.value.isCreateVisible = true;
}
function openDetailModal(row: Row) {
data.value.selectedData = row;
}
function closeDetail() {
data.value.selectedData = null;
}
//
watch(
() => data.value.isCreateVisible,
(now, prev) => {
@ -339,9 +494,6 @@ watch(
},
);
//
//
//
onMounted(async () => {
refreshRoles();
await Promise.all([loadUsers(), getData()]);
@ -359,7 +511,7 @@ onMounted(async () => {
<v-card flat class="bg-shades-transparent w-100">
<v-card-item class="text-h5 font-weight-bold pt-0 pa-5 pl-0">
<div class="d-flex flex-row justify-start align-center">
<div class="text-primary">Project</div>
<div class="text-primary">Projects</div>
</div>
</v-card-item>
</v-card>
@ -373,13 +525,14 @@ onMounted(async () => {
min-width="180"
class="mr-3 mt-3 mb-3"
>
<!-- [object Object] 해결 -->
<v-select
v-model="data.params.searchType"
label="검색조건"
density="compact"
:items="searchOptions"
item-title="searchType"
item-value="searchText"
item-title="label"
item-value="value"
hide-details
/>
</v-responsive>
@ -393,7 +546,7 @@ onMounted(async () => {
required
class="mt-3 mb-3"
hide-details
@keyup.enter="changePageNum(1)"
@keyup.enter="doSearch"
/>
</v-responsive>
@ -402,7 +555,7 @@ onMounted(async () => {
size="large"
color="primary"
:rounded="5"
@click="changePageNum(1)"
@click="doSearch"
>
<v-icon>mdi-magnify</v-icon>
</v-btn>
@ -410,6 +563,7 @@ onMounted(async () => {
</div>
</v-card>
<!-- 상단 툴바 -->
<v-sheet
class="bg-shades-transparent d-flex flex-wrap align-center mb-2"
>
@ -421,6 +575,7 @@ onMounted(async () => {
> {{ data.totalDataLength.toLocaleString() }}</v-chip
>
</v-sheet>
<v-sheet class="bg-shades-transparent">
<v-responsive max-width="140" min-width="140" class="mb-2">
<v-select
@ -432,7 +587,7 @@ onMounted(async () => {
variant="outlined"
color="primary"
hide-details
@update:model-value="changePageNum(1)"
@update:model-value="changePageSize"
/>
</v-responsive>
</v-sheet>
@ -502,12 +657,10 @@ onMounted(async () => {
<td>{{ item.no }}</td>
<td>{{ item.name }}</td>
<!-- Description -->
<td>
<div class="truncate-2">{{ item.desc }}</div>
</td>
<!-- Select Users -->
<td>
<template v-if="item.users?.length">
<v-chip
@ -586,10 +739,10 @@ onMounted(async () => {
</v-card-text>
<v-card-actions>
<v-spacer />
<v-btn text @click="data.isCreateVisible = false">Cancel</v-btn>
<v-btn color="primary" @click="saveProject">
{{ data.modalMode === "create" ? "Create" : "Save" }}
</v-btn>
<v-btn text @click="data.isCreateVisible = false">Cancel</v-btn>
</v-card-actions>
</v-card>
</v-dialog>

@ -1,296 +1,299 @@
<script setup lang="ts">
import IconDeleteBtn from "@/components/atoms/button/IconDeleteBtn.vue";
import IconInfoBtn from "@/components/atoms/button/IconInfoBtn.vue";
import { onMounted, ref, watch } from "vue";
import { onMounted, ref } from "vue";
import { storage } from "@/utils/storage";
import ViewComponent from "@/components/templates/run/experiment/ViewComponent.vue";
import ExperimentCreateDialog from "@/components/atoms/organisms/ExperimentCreateDialog.vue";
import { ExperimentService } from "@/components/service/management/ExperimentService";
import { commonStore } from "@/stores/commonStore";
// const store = commonStore();
const store = commonStore();
const detailDialog = ref(false);
const openView = ref(false);
const username = ref<string>("");
const selectedExperiment = ref<{
name: string;
description: string;
createdDate: string;
createdID: string;
deviceKey: number;
} | null>(null);
// ===== =====
const tableHeader = [
{
label: "Experiment Name",
width: "20%",
style: "word-break: keep-all;",
},
{
label: "Description",
width: "20%",
style: "word-break: keep-all;",
},
{
label: "Created Date",
width: "20%",
style: "word-break: keep-all;",
},
{
label: "Created ID",
width: "20%",
style: "word-break: keep-all;",
},
{
label: "Action",
width: "20%",
style: "word-break: keep-all;",
},
{ label: "Experiment Name", width: "20%", style: "word-break: keep-all;" },
{ label: "Description", width: "20%", style: "word-break: keep-all;" },
{ label: "Created Date", width: "20%", style: "word-break: keep-all;" },
{ label: "Created ID", width: "20%", style: "word-break: keep-all;" },
{ label: "Action", width: "20%", style: "word-break: keep-all;" },
];
// ===== / (/ '') =====
type SearchType = "전체" | "제목" | "작성자";
const searchOptions = [
{ searchType: "All", searchText: "" },
{ searchType: "Experiment Name", searchText: "name" },
{ searchType: "Description", searchText: "description" },
{ searchType: "Created Date", searchText: "createdDate" },
{ searchType: "Created ID", searchText: "createdID" },
{ label: "전체", value: "전체" as SearchType },
{ label: "제목", value: "제목" as SearchType },
{ label: "작성자", value: "작성자" as SearchType },
];
const SEARCH_TYPE_MAP: Record<SearchType | "", "ALL" | "TITLE" | "AUTHOR"> = {
"": "ALL",
전체: "ALL",
제목: "TITLE",
작성자: "AUTHOR",
};
const pageSizeOptions = [
{ text: "10 페이지", value: 10 },
{ text: "50 페이지", value: 50 },
{ text: "100 페이지", value: 100 },
];
// ===== =====
const data = ref({
params: {
pageNum: 1,
pageSize: 10,
searchType: "",
searchType: "전체" as SearchType,
searchText: "",
},
results: [],
totalDataLength: 0,
results: [] as any[],
totalElements: 0,
pageLength: 0,
modalMode: "",
selectedData: null,
modalMode: "" as "create" | "edit" | "",
selectedData: null as any,
allSelected: false,
selected: [],
selected: [] as any[],
isCreateVisible: false,
isModalVisible: false,
isConfirmDialogVisible: false,
userOption: [],
userOption: [] as any[],
});
const getCodeList = () => {
// UserService.search(data.value.params).then((d) => {
// if (d.status === 200) {
// data.value.userOption = d.data.userList;
// }
// });
// ===== =====
function readUsernameFromStorage(): string {
try {
const raw =
storage?.get?.("autoflow-auth") ??
storage?.getAuth?.() ??
localStorage.getItem("autoflow-auth") ??
null;
const auth = typeof raw === "string" ? JSON.parse(raw) : raw;
const u1 = auth?.userInfo?.username;
const u2 = auth?.username;
const u3 = auth?.userInfo?.userName;
const u4 = auth?.userInfo?.email?.split?.("@")?.[0];
return (u1 || u2 || u3 || u4 || "").toString();
} catch {
return "";
}
}
const getProjectId = (): number => {
const v = Number(localStorage.getItem("projectId"));
return Number.isFinite(v) ? v : 0;
};
const fmtDate = (v?: string) =>
v ? String(v).replace("T", " ").slice(0, 19) : "";
const getData = () => {
const params = { ...data.value.params };
if (params.searchType === "" || params.searchText === "") {
delete params.searchType;
delete params.searchText;
// Row
const toRow = (e: any) => ({
name: e.displayName,
description: e.description,
createdDate: fmtDate(e.lastUpdateTime),
deviceKey: e.id,
createdID: e.regUserId,
});
// ===== ( ) =====
const fetchList = async () => {
const projectId = getProjectId();
if (!projectId) {
console.warn("[Experiments] projectId 없음 — 프로젝트 먼저 선택");
data.value.results = [];
data.value.totalElements = 0;
data.value.pageLength = 0;
return;
}
data.value.results = [
{
name: "Baseline Model Training",
description: "기본 모델 구조로 학습 성능 측정",
createdDate: "2025-04-28",
createdID: "ADMIN_001",
},
{
name: "Batch Size Tuning",
description: "배치 사이즈 변경에 따른 학습 성능",
createdDate: "2025-04-20",
createdID: "ADMIN_001",
},
{
name: "Learning Rate Sweep",
description: "러닝레이트 변경에 따른 손실 ",
createdDate: "2025-04-20",
createdID: "ADMIN_001",
},
{
name: "Optimizer Comparison",
description: "Adam, SGD 등 옵티마이저 종류",
createdDate: "2025-04-20",
createdID: "ADMIN_001",
},
{
name: "Model Architecture A vs B",
description: "서로 다른 모델 구조",
createdDate: "2025-01-28",
createdID: "ADMIN_001",
},
];
data.value.totalDataLength = data.value.results.length;
setPaginationLength();
// DeviceService.search(params).then((d) => {
// if (d.status === 200) {
// data.value.results = d.data.deviceList;
// data.value.totalDataLength = d.data.totalCount;
// setTimeout(() => {
// setPaginationLength();
// }, 200);
// } else {
// store.setSnackbarMsg({
// text: " ",
// color: "error",
// });
// }
// });
// DeviceService.search().then((d) => {
// data.value.totalDataLength = d.data.totalCount;
// setTimeout(() => {
// setPaginationLength();
// }, 200);
// });
const { pageNum, pageSize, searchType, searchText } = data.value.params;
const mapped = SEARCH_TYPE_MAP[searchType] || "ALL";
const keyword = (searchText || "").trim();
const needLocalFilter = mapped !== "ALL" && keyword.length > 0;
let reqPage = data.value.params.pageNum;
let reqSize = data.value.params.pageSize;
if (needLocalFilter) {
// +
reqPage = 0;
reqSize = 1000;
}
const payload = {
projectId,
page: reqPage,
size: reqSize,
keyword,
searchType: mapped,
};
const setPaginationLength = () => {
if (data.value.totalDataLength % data.value.params.pageSize === 0) {
data.value.pageLength =
data.value.totalDataLength / data.value.params.pageSize;
} else {
data.value.pageLength = Math.ceil(
data.value.totalDataLength / data.value.params.pageSize,
try {
const res = await ExperimentService.search(payload as any);
const result = res?.data ?? res;
let list = result?.content ?? [];
if (needLocalFilter) {
const kw = keyword.toLowerCase();
if (mapped === "TITLE") {
list = list.filter((x: any) =>
String(x?.name ?? x?.displayName ?? "")
.toLowerCase()
.includes(kw),
);
} else if (mapped === "AUTHOR") {
list = list.filter((x: any) =>
String(x?.regUserId ?? "")
.toLowerCase()
.includes(kw),
);
}
};
const saveData = (formData) => {
if (data.value.modalMode === "create") {
// DeviceService.add(formData).then((d) => {
// if (d.status === 200) {
// data.value.isModalVisible = false;
// store.setSnackbarMsg({
// text: " .",
// result: 200,
// });
// changePageNum(1);
// } else {
// store.setSnackbarMsg({
// text: d,
// result: 500,
// });
// }
// });
} else {
// DeviceService.update(formData.deviceKey, formData).then((d) => {
// if (d.status === 200) {
// data.value.isModalVisible = false;
// store.setSnackbarMsg({
// text: " .",
// result: 200,
// });
// changePageNum();
// } else {
// store.setSnackbarMsg({
// text: d,
// result: 500,
// });
// }
// });
//
const uiSize = data.value.params.pageSize;
const totalElements = list.length;
const totalPages = Math.max(1, Math.ceil(totalElements / uiSize));
const safePage = Math.min(Math.max(1, pageNum), totalPages);
const start = (safePage - 1) * uiSize;
const pageSlice = list.slice(start, start + uiSize);
data.value.results = pageSlice.map(toRow);
data.value.totalElements = totalElements;
data.value.pageLength = totalPages;
return;
}
data.value.results = (list as any[]).map(toRow);
data.value.totalElements = result?.totalElements ?? list.length;
data.value.pageLength = result?.totalPages ?? 1;
} catch (err) {
console.error("[Experiments] 조회 에러:", err);
data.value.results = [];
data.value.totalElements = 0;
data.value.pageLength = 1;
}
};
const removeData = (value) => {
let removeList = value ? value : data.value.selected;
const remove = (code) => {
// return DeviceService.delete(code).then((d) => {
// if (d.status !== 200) {
// store.setSnackbarMsg({
// text: d,
// result: 500,
// });
// }
// });
// ===== / =====
const doSearch = () => {
data.value.params.pageNum = 1;
fetchList();
};
const changePageNum = (page: number) => {
data.value.params.pageNum = page;
fetchList();
};
const changePageSize = (size: number) => {
data.value.params.pageSize = size;
data.value.params.pageNum = 1;
fetchList();
};
if (removeList.length === 1) {
remove(removeList[0].deviceKey).then(() => {
// store.setSnackbarMsg({
// / ( )
const removeData = (value?: Array<{ deviceKey: number }>) => {
const removeList = value ?? data.value.selected;
if (!removeList || removeList.length === 0) return;
// text: ".",
// result: 200,
// });
changePageNum();
data.value.isConfirmDialogVisible = false;
data.value.selected = [];
data.value.allSelected = false;
const ids = removeList.map((x) => x.deviceKey);
const removeOne = (id: number) =>
ExperimentService.delete(id).then((res) => {
if (res.status < 200 || res.status >= 300) return Promise.reject(res);
});
} else {
Promise.all(removeList.map((item) => remove(item.deviceKey))).finally(
() => {
// store.setSnackbarMsg({
// text: " .",
// result: 200,
// });
changePageNum();
const after = () => {
if (
ids.length >= data.value.results.length &&
data.value.params.pageNum > 1
) {
data.value.params.pageNum -= 1;
}
fetchList();
data.value.isConfirmDialogVisible = false;
data.value.selected = [];
data.value.allSelected = false;
},
);
}
};
const handleRemoveData = () => {
if (data.value.selected.length === 0) {
// store.setSnackbarMsg({
// text: " . ",
// result: 500,
// });
return;
}
if (data.value.allSelected || data.value.selected.length !== 1) {
data.value.isConfirmDialogVisible = true;
return;
// /
if (ids.length === 1) {
removeOne(ids[0])
.then(() => {
store.setSnackbarMsg({
color: "success",
text: "삭제되었습니다.",
result: 200,
});
after();
})
.catch((err) => {
console.error("삭제 실패:", err);
store.setSnackbarMsg({
color: "warning",
text: "삭제 실패",
result: 500,
});
});
} else {
Promise.all(ids.map(removeOne))
.then(() => {
store.setSnackbarMsg({
color: "success",
text: "모두 삭제되었습니다.",
result: 200,
});
})
.catch((err) => {
console.error("일부 삭제 실패:", err);
store.setSnackbarMsg({
color: "warning",
text: "일부 삭제 실패",
result: 500,
});
})
.finally(after);
}
//
removeData(undefined);
};
const changePageNum = (page) => {
data.value.params.pageNum = page;
getData();
};
const openDetail = (item: {
name: string;
description: string;
createdDate: string;
createdID: string;
}) => {
selectedExperiment.value = item;
openView.value = true;
};
// ===== & ( ) =====
const closeDetail = () => {
openView.value = false;
selectedExperiment.value = null;
};
const openDetailModal = (selectedItem: any) => {
console.log("[Experiment/List] row clicked:", selectedItem);
if (!selectedItem?.deviceKey) {
console.warn("[Experiment/List] deviceKey 없음!", selectedItem);
}
data.value.selectedData = selectedItem;
openView.value = true;
};
const openCreateModal = () => {
data.value.selectedData = null;
data.value.modalMode = "create";
data.value.isModalVisible = true;
data.value.selectedData = {
username: username.value,
projectId: getProjectId(),
};
data.value.isCreateVisible = true;
};
const closeModal = () => {
data.value.isModalVisible = false;
data.value.isCreateVisible = false;
data.value.selectedData = null;
};
const getSelectedAllData = () => {
data.value.selected = data.value.allSelected
? data.value.results.map((item) => {
return {
deviceKey: item.deviceKey,
};
})
: [];
};
onMounted(() => {
getData();
getCodeList();
username.value = readUsernameFromStorage();
fetchList();
});
</script>
@ -308,7 +311,9 @@ onMounted(() => {
</div>
</v-card-item>
</v-card>
<v-card flat class="bg-shades-transparent w-100">
<!-- 검색 -->
<v-card flat class="bg-shades-transparent mb-4">
<div class="d-flex justify-center flex-wrap align-center">
<v-responsive
@ -321,11 +326,12 @@ onMounted(() => {
label="검색조건"
density="compact"
:items="searchOptions"
item-title="searchType"
item-value="searchText"
item-title="label"
item-value="value"
hide-details
></v-select>
/>
</v-responsive>
<v-responsive min-width="540" max-width="540">
<v-text-field
v-model="data.params.searchText"
@ -335,8 +341,8 @@ onMounted(() => {
required
class="mt-3 mb-3"
hide-details
@keyup.enter="changePageNum(1)"
></v-text-field>
@keyup.enter="doSearch"
/>
</v-responsive>
<div class="ml-3">
@ -344,7 +350,7 @@ onMounted(() => {
size="large"
color="primary"
:rounded="5"
@click="changePageNum(1)"
@click="doSearch"
>
<v-icon>mdi-magnify</v-icon>
</v-btn>
@ -352,6 +358,7 @@ onMounted(() => {
</div>
</v-card>
<!-- 상단 툴바 -->
<v-sheet
class="bg-shades-transparent d-flex flex-wrap align-center mb-2"
>
@ -360,8 +367,8 @@ onMounted(() => {
class="d-flex align-center mr-3 mb-2 bg-shades-transparent"
>
<v-chip color="primary"
> {{ data.totalDataLength.toLocaleString() }}
</v-chip>
> {{ data.totalElements.toLocaleString() }}</v-chip
>
</v-sheet>
<v-sheet class="bg-shades-transparent">
<v-responsive max-width="140" min-width="140" class="mb-2">
@ -374,18 +381,20 @@ onMounted(() => {
variant="outlined"
color="primary"
hide-details
@update:model-value="changePageNum(1)"
></v-select>
@update:model-value="changePageSize"
/>
</v-responsive>
</v-sheet>
</v-sheet>
<v-sheet class="justify-end mb-2">
<v-btn color="primary" @click="openCreateModal"
>Create Experiment
</v-btn>
>Create Experiment</v-btn
>
</v-sheet>
</v-sheet>
<!-- 목록 -->
<v-card class="rounded-lg pa-8">
<v-col cols="12">
<v-sheet>
@ -393,8 +402,6 @@ onMounted(() => {
density="comfortable"
fixed-header
height="625"
col-md-12
col-12
overflow-x-auto
>
<colgroup>
@ -406,20 +413,11 @@ onMounted(() => {
</colgroup>
<thead>
<tr>
<!-- <th>
<v-checkbox
v-model="data.allSelected"
style="min-width: 36px"
:indeterminate="data.allSelected === true"
hide-details
@change="getSelectedAllData"
></v-checkbox>
</th> -->
<th
v-for="(item, i) in tableHeader"
:key="i"
class="text-center font-weight-bold"
:style="`${item.style}`"
:style="item.style"
>
{{ item.label }}
</th>
@ -431,21 +429,12 @@ onMounted(() => {
:key="i"
class="text-center"
>
<!-- <td>
<v-checkbox
v-model="data.selected"
hide-details
:value="{
deviceKey: item.deviceKey,
}"
></v-checkbox>
</td> -->
<td>{{ item.name }}</td>
<td>{{ item.description }}</td>
<td>{{ item.createdDate }}</td>
<td>{{ item.createdID }}</td>
<td style="white-space: nowrap">
<IconInfoBtn @on-click="openDetail(item)" />
<IconInfoBtn @on-click="openDetailModal(item)" />
<IconDeleteBtn
@on-click="
removeData([{ deviceKey: item.deviceKey }])
@ -456,6 +445,7 @@ onMounted(() => {
</tbody>
</v-table>
</v-sheet>
<v-card-actions class="text-center mt-8 justify-center">
<v-pagination
v-model="data.params.pageNum"
@ -463,26 +453,33 @@ onMounted(() => {
:total-visible="10"
color="primary"
rounded="circle"
@update:model-value="getData"
></v-pagination>
@update:model-value="changePageNum"
/>
</v-card-actions>
</v-col>
</v-card>
</v-card>
</v-card>
</v-container>
<v-dialog v-model="data.isModalVisible" max-width="600" persistent>
<!-- 생성 다이얼로그 -->
<v-dialog v-model="data.isCreateVisible" max-width="600" persistent>
<ExperimentCreateDialog
:edit-data="data.selectedData"
:mode="data.modalMode"
@close-modal="closeModal"
@handle-data="saveData"
:user-option="data.userOption"
@saved="fetchList"
@handle-data="() => {}"
/>
</v-dialog>
</div>
<div class="w-100" v-else>
<ViewComponent :experiment="selectedExperiment" @close="closeDetail" />
<ViewComponent
v-if="data.selectedData"
:id="data.selectedData.deviceKey"
@close="closeDetail"
/>
</div>
</template>

@ -1,246 +1,78 @@
<script setup lang="ts">
import IconDeleteBtn from "@/components/atoms/button/IconDeleteBtn.vue";
import IconModifyBtn from "@/components/atoms/button/IconModifyBtn.vue";
// import FormComponent from "@/components/device/FormComponent.vue";
import { onMounted, ref, watch } from "vue";
import { ref, computed, onMounted, watch } from "vue";
import { ExperimentService } from "@/components/service/management/ExperimentService";
import { ProjectService } from "@/components/service/project/projectService"; //
// const store = commonStore();
const props = defineProps<{ id: number | string }>();
const emit = defineEmits<{ (e: "close"): void }>();
const tableHeader = [
{
label: "Run Name",
width: "20%",
style: "word-break: keep-all;",
},
{
label: "Status",
width: "20%",
style: "word-break: keep-all;",
},
{
label: "Duration",
width: "20%",
style: "word-break: keep-all;",
},
{
label: "Pipeline",
width: "20%",
style: "word-break: keep-all;",
},
{
label: "Start Time",
width: "20%",
style: "word-break: keep-all;",
},
];
const loading = ref(false);
const detailRaw = ref<any | null>(null);
const experimentInfo = ref({
experimentName: "Baseline Model Training",
projectName: "배터리 상태 예측 모델 프로젝트",
createdDate: "2025-02-06",
createdId: "ADMIN_001",
description: "기본 모델 구조로 학습 성능 측정",
experimentName: "-",
projectName: "-",
createdDate: "-",
createdId: "-",
description: "-",
kubeFlowId: "-",
mlFlowId: "-",
});
const data = ref({
params: {
pageNum: 1,
pageSize: 10,
searchType: "",
searchText: "",
},
results: [],
totalDataLength: 0,
pageLength: 0,
modalMode: "",
selectedData: null,
allSelected: false,
selected: [],
isModalVisible: false,
isConfirmDialogVisible: false,
userOption: [],
const formatIso = (s?: string) =>
s ? String(s).replace("T", " ").slice(0, 19) : "-";
const mapToViewModel = (raw: any) => ({
experimentName: raw.displayName ?? raw.name ?? "-",
projectName: "-",
createdDate: formatIso(raw.lastUpdateTime),
createdId: raw.regUserId ?? "-",
description: raw.description ?? "-",
kubeFlowId: raw.kubeFlowId ?? "-",
mlFlowId: raw.mlFlowId ?? "-",
});
const getCodeList = () => {
// UserService.search(data.value.params).then((d) => {
// if (d.status === 200) {
// data.value.userOption = d.data.userList;
// }
// });
};
const getData = () => {
const params = { ...data.value.params };
if (params.searchType === "" || params.searchText === "") {
delete params.searchType;
delete params.searchText;
}
data.value.results = [
{
name: "run-batch32-lr0.001",
status: "Succeeded",
Duration: "0:00:21",
configProgress: "0/2",
Pipeline: "baseline_train_pipeline",
registDt: "2025-06-10T00:00:00Z",
},
{
name: "run-batch64-lr0.001",
status: "Failed",
Duration: "0:00:21",
configProgress: "1/3",
Pipeline: "baseline_train_pipeline",
registDt: "2025-06-09T00:00:00Z",
},
{
name: "run-batch32-lr0.0005",
status: "Succeeded",
Duration: "0:00:21",
configProgress: "0/3",
Pipeline: "baseline_train_pipeline",
registDt: "2025-06-01T00:00:00Z",
},
{
name: "run-batch64-lr0.0005",
status: "Running",
Duration: "0:00:21",
configProgress: "1/3",
Pipeline: "baseline_train_pipeline",
registDt: "2025-05-29T00:00:00Z",
},
{
name: "run-augmented-data",
status: "Succeeded",
Duration: "0:00:21",
configProgress: "0/3",
Pipeline: "baseline_train_pipeline",
registDt: "2025-05-31T00:00:00Z",
},
];
data.value.totalDataLength = 5;
setPaginationLength();
// DeviceService.search(params).then((d) => {
// if (d.status === 200) {
// data.value.results = d.data.deviceList;
// data.value.totalDataLength = d.data.totalCount;
// setTimeout(() => {
// setPaginationLength();
// }, 200);
// } else {
// store.setSnackbarMsg({
// text: " ",
// color: "error",
// });
// }
// });
// DeviceService.search().then((d) => {
// data.value.totalDataLength = d.data.totalCount;
// setTimeout(() => {
// setPaginationLength();
// }, 200);
// });
};
const info = computed(() => mapToViewModel(detailRaw.value || {}));
const setPaginationLength = () => {
if (data.value.totalDataLength % data.value.params.pageSize === 0) {
data.value.pageLength =
data.value.totalDataLength / data.value.params.pageSize;
} else {
data.value.pageLength = Math.ceil(
data.value.totalDataLength / data.value.params.pageSize,
);
async function fetchProjectName(projectId?: number) {
if (!projectId && projectId !== 0) return;
try {
const res = await ProjectService.fetchProjectById(projectId as number);
const prj = res?.data ?? res;
experimentInfo.value.projectName = prj?.prjNm ?? prj?.name ?? "-";
} catch (e) {
console.warn("[Experiment/View] project fetch fail:", e);
}
};
const saveData = (formData) => {
if (data.value.modalMode === "create") {
// DeviceService.add(formData).then((d) => {
// if (d.status === 200) {
// data.value.isModalVisible = false;
// store.setSnackbarMsg({
// text: " .",
// result: 200,
// });
// changePageNum(1);
// } else {
// store.setSnackbarMsg({
// text: d,
// result: 500,
// });
// }
// });
} else {
// DeviceService.update(formData.deviceKey, formData).then((d) => {
// if (d.status === 200) {
// data.value.isModalVisible = false;
// store.setSnackbarMsg({
// text: " .",
// result: 200,
// });
// changePageNum();
// } else {
// store.setSnackbarMsg({
// text: d,
// result: 500,
// });
// }
// });
}
};
const removeData = (value) => {
let removeList = value ? value : data.value.selected;
const remove = (code) => {
// return DeviceService.delete(code).then((d) => {
// if (d.status !== 200) {
// store.setSnackbarMsg({
// text: d,
// result: 500,
// });
// }
// });
};
async function fetchDetail(id: number | string) {
const idNum = typeof id === "string" ? Number(id) : id;
if (!Number.isFinite(idNum as number)) return;
if (removeList.length === 1) {
remove(removeList[0].deviceKey).then(() => {
// store.setSnackbarMsg({
// text: ".",
// result: 200,
// });
changePageNum();
data.value.isConfirmDialogVisible = false;
data.value.selected = [];
data.value.allSelected = false;
});
} else {
Promise.all(removeList.map((item) => remove(item.deviceKey))).finally(
() => {
// store.setSnackbarMsg({
// text: " .",
// result: 200,
// });
changePageNum();
data.value.isConfirmDialogVisible = false;
data.value.selected = [];
data.value.allSelected = false;
},
);
}
};
loading.value = true;
try {
const res = await ExperimentService.view(idNum as number);
detailRaw.value = res?.data ?? res;
const changePageNum = (page) => {
data.value.params.pageNum = page;
getData();
};
const vm = mapToViewModel(detailRaw.value);
experimentInfo.value = { ...experimentInfo.value, ...vm };
const emit = defineEmits<{
(e: "close"): void;
}>();
//
await fetchProjectName(detailRaw.value?.projectId);
} catch (e) {
console.error("[Experiment/View] fetch detail error:", e);
} finally {
loading.value = false;
}
}
onMounted(() => {
getData();
getCodeList();
});
onMounted(() => fetchDetail(props.id));
watch(
() => props.id,
(nv) => {
if (nv !== undefined && nv !== null && nv !== "") fetchDetail(nv);
},
);
</script>
<template>
@ -257,7 +89,10 @@ onMounted(() => {
</v-card-item>
</v-card>
<v-card flat class="bordered-box mb-6 w-100 rounded-lg pa-8">
<v-card
flat
class="bordered-box mb-6 w-100 rounded-lg pa-8 position-relative"
>
<v-card-title class="grey lighten-4 py-2 px-4">
<span class="font-weight-bold">Experiment Information</span>
</v-card-title>
@ -287,14 +122,23 @@ onMounted(() => {
<!-- Created Date / ID -->
<v-row align="center" class="py-2">
<v-col cols="3" class="text-h6 font-weight-bold">Created ID</v-col>
<v-col cols="3" class="pa-2">{{ experimentInfo.createdId }}</v-col>
<v-col cols="3" class="text-h6 font-weight-bold"
>Created Date</v-col
>
<v-col cols="3" class="pa-2">{{
experimentInfo.createdDate
}}</v-col>
<v-col cols="3" class="text-h6 font-weight-bold">Created ID</v-col>
<v-col cols="3" class="pa-2">{{ experimentInfo.createdId }}</v-col>
</v-row>
<VDivider class="my-2" />
<!-- Kubeflow / MLflow ID -->
<v-row align="center" class="py-2">
<v-col cols="3" class="text-h6 font-weight-bold">Kubeflow ID</v-col>
<v-col cols="3" class="pa-2">{{ experimentInfo.kubeFlowId }}</v-col>
<v-col cols="3" class="text-h6 font-weight-bold">MLflow ID</v-col>
<v-col cols="3" class="pa-2">{{ experimentInfo.mlFlowId }}</v-col>
</v-row>
<VDivider class="my-2" />
@ -306,100 +150,20 @@ onMounted(() => {
}}</v-col>
</v-row>
</v-card-text>
</v-card>
<v-card flat class="bg-shades-transparent w-100">
<v-card class="rounded-lg pa-8">
<v-card-title class="grey lighten-4 py-2 px-4">
<span class="font-weight-bold">Runs</span>
</v-card-title>
<v-col cols="12">
<v-sheet>
<v-table
density="comfortable"
fixed-header
height="300"
col-md-12
col-12
overflow-x-auto
>
<colgroup>
<col
v-for="(item, i) in tableHeader"
:key="i"
:style="`width:${item.width}`"
/>
</colgroup>
<thead>
<tr>
<th
v-for="(item, i) in tableHeader"
:key="i"
class="text-center font-weight-bold"
:style="`${item.style}`"
>
{{ item.label }}
</th>
</tr>
</thead>
<tbody class="text-body-2">
<tr
v-for="(item, i) in data.results"
:key="i"
class="text-center"
<v-overlay
:model-value="loading"
contained
persistent
class="align-center justify-center"
>
<td>{{ item.name }}</td>
<td>{{ item.status }}</td>
<td>{{ item.Duration }}</td>
<td>{{ item.Pipeline }}</td>
<td>{{ item.registDt }}</td>
</tr>
</tbody>
</v-table>
</v-sheet>
<v-card-actions class="text-center mt-8 justify-center">
<v-pagination
v-model="data.params.pageNum"
:length="data.pageLength"
:total-visible="10"
color="primary"
rounded="circle"
@update:model-value="getData"
></v-pagination>
</v-card-actions>
</v-col>
<v-progress-circular indeterminate size="48" />
</v-overlay>
<v-sheet class="d-flex justify-end mb-2">
<v-btn color="primary" @click="emit('close')">Back to List</v-btn>
</v-sheet>
</v-card>
</v-card>
</v-card>
</v-container>
</template>
<style scoped>
.v-card-text {
width: 100% !important;
border-collapse: collapse;
/* 전체 테이블 1px 테두리 */
}
.v-card-text th {
font-size: 20px;
min-width: 400px;
border: 1px solid rgba(255, 255, 255, 0.12);
background-color: rgba(255, 255, 255, 0.05);
font-weight: 600;
text-align: center;
white-space: nowrap;
}
.v-card-text td {
font-size: 16px;
min-width: 600px;
padding: 12px 16px;
text-align: left;
border: 1px solid rgba(255, 255, 255, 0.12);
}
.v-card-text tr:nth-child(odd) {
background-color: rgba(255, 255, 255, 0.02);
}
</style>

@ -333,7 +333,7 @@ onMounted(() => {
>
<v-select
v-model="data.params.searchType"
label="검색유형"
label="검색조건"
density="compact"
:items="searchOptions"
item-title="label"

@ -2,340 +2,334 @@
import IconDeleteBtn from "@/components/atoms/button/IconDeleteBtn.vue";
import IconModifyBtn from "@/components/atoms/button/IconModifyBtn.vue";
import IconInfoBtn from "@/components/atoms/button/IconInfoBtn.vue";
// import FormComponent from "@/components/device/FormComponent.vue";
import { onMounted, ref, watch } from "vue";
import { onMounted, ref } from "vue";
import { storage } from "@/utils/storage";
import ViewComponent from "@/components/templates/trainingscript/ViewComponent.vue";
import TrainingScriptBaseDoalog from "@/components/atoms/organisms/TrainingScriptBaseDoalog.vue";
import WorkflowsUploadDialog from "@/components/atoms/organisms/WorkflowsUploadDialog.vue";
// const store = commonStore();
import { AttachmentsService } from "@/components/service/management/attachmentsService";
import { commonStore } from "@/stores/commonStore";
const store = commonStore();
const openView = ref(false);
const openModify = ref(false);
const tableHeader = [
{
label: "Title",
width: "7%",
style: "word-break: keep-all;",
},
{
label: "File Name",
width: "7%",
style: "word-break: keep-all;",
},
{
label: "File Path",
width: "7%",
style: "word-break: keep-all;",
},
{
label: "Description",
width: "7%",
style: "word-break: keep-all;",
},
{
label: "Created Data",
width: "7%",
style: "word-break: keep-all;",
},
{
label: "Modified Data",
width: "7%",
style: "word-break: keep-all;",
},
{
label: "Action",
width: "7%",
style: "word-break: keep-all;",
},
];
const username = ref<string>("");
type SearchType = "전체" | "제목" | "작성자";
const searchOptions = [
{
searchType: "전체",
searchText: "",
},
{
searchType: "디바이스 별칭",
searchText: "deviceAlias",
},
{
searchType: "디바이스 키",
searchText: "deviceKey",
},
{
searchType: "사용자",
searchText: "userId",
},
{
searchType: "디바이스 이름",
searchText: "deviceName",
},
{
searchType: "디바이스 모델",
searchText: "deviceModel",
},
{
searchType: "디바이스 OS",
searchText: "deviceOs",
},
{ label: "전체", value: "전체" as SearchType },
{ label: "제목", value: "제목" as SearchType },
{ label: "작성자", value: "작성자" as SearchType },
];
const SEARCH_TYPE_MAP: Record<SearchType | "", "ALL" | "TITLE" | "AUTHOR"> = {
"": "ALL",
전체: "ALL",
제목: "TITLE",
작성자: "AUTHOR",
};
const pageSizeOptions = [
{ text: "10 페이지", value: 10 },
{ text: "50 페이지", value: 50 },
{ text: "100 페이지", value: 100 },
];
//
const tableHeader = [
{ label: "Title", width: "7%", style: "word-break: keep-all;" },
{ label: "File Name", width: "7%", style: "word-break: keep-all;" },
{ label: "File Path", width: "7%", style: "word-break: keep-all;" },
{ label: "Description", width: "7%", style: "word-break: keep-all;" },
{ label: "Created Data", width: "7%", style: "word-break: keep-all;" },
{ label: "Modified Data", width: "7%", style: "word-break: keep-all;" },
{ label: "Action", width: "7%", style: "word-break: keep-all;" },
];
const data = ref({
params: {
pageNum: 1,
pageSize: 10,
searchType: "",
searchType: "전체" as SearchType,
searchText: "",
},
results: [],
totalDataLength: 0,
results: [] as any[],
totalElements: 0,
pageLength: 0,
modalMode: "",
selectedData: null,
modalMode: "" as "create" | "edit" | "setting" | "",
selectedData: null as any,
allSelected: false,
selected: [],
selected: [] as Array<{ deviceKey: number }>,
isCreateVisible: false,
isUploadVisible: false,
isModalVisible: false,
isConfirmDialogVisible: false,
userOption: [],
userOption: [] as any[],
});
const getCodeList = () => {
// UserService.search(data.value.params).then((d) => {
// if (d.status === 200) {
// data.value.userOption = d.data.userList;
// }
// });
//
function readUsernameFromStorage(): string {
try {
const raw =
storage?.get?.("autoflow-auth") ??
storage?.getAuth?.() ??
localStorage.getItem("autoflow-auth") ??
null;
const auth = typeof raw === "string" ? JSON.parse(raw) : raw;
const u1 = auth?.userInfo?.username;
return u1.toString();
} catch {
return "";
}
}
// ID
const getProjectId = (): number => {
const v = Number(localStorage.getItem("projectId"));
return Number.isFinite(v) ? v : 0;
};
const getData = () => {
const params = { ...data.value.params };
if (params.searchType === "" || params.searchText === "") {
delete params.searchType;
delete params.searchText;
const fmtDate = (v?: string) =>
v ? String(v).replace("T", " ").slice(0, 19) : "";
// ( )
const toRow = (a: any) => ({
deviceKey: a.id,
id: a.id,
title: a.title ?? "",
fileName: a.originalName ?? "",
filePath: a.storagePath ?? "",
description: a.description ?? "",
createdData: fmtDate(a.regDt),
modifiedData: "-",
});
const fetchList = async () => {
const projectId = Number(localStorage.getItem("projectId"));
if (!projectId) {
console.warn("[TrainingScript] projectId 없음 — 프로젝트 먼저 선택");
data.value.results = [];
data.value.totalElements = 0;
data.value.pageLength = 0;
return;
}
data.value.results = [
{
title: "배터리 상태 예측 모델 프로젝트",
fileName: "train.py",
filePath: "/kubeflow-users/battery/train.py",
description: "배터리 상태 예측 스크립트",
createdData: "2025-04-28 12:01:00",
modifiedData: "2025-04-28 12:01:00",
},
{
title: "상태 추적 모델",
fileName: "detection.py",
filePath: "/kubeflow-users/status/detection.py",
description: "상태 추적 스크립트",
createdData: "2025-04-20 12:01:00",
modifiedData: "2025-04-28 12:01:00",
},
];
data.value.totalDataLength = 5;
// DeviceService.search(params).then((d) => {
// if (d.status === 200) {
// data.value.results = d.data.deviceList;
// data.value.totalDataLength = d.data.totalCount;
// setTimeout(() => {
// setPaginationLength();
// }, 200);
// } else {
// store.setSnackbarMsg({
// text: " ",
// color: "error",
// });
// }
// });
// DeviceService.search().then((d) => {
// data.value.totalDataLength = d.data.totalCount;
// setTimeout(() => {
// setPaginationLength();
// }, 200);
// });
const { pageNum, pageSize, searchType, searchText } = data.value.params;
const mapped = SEARCH_TYPE_MAP[searchType] || "ALL";
const keyword = (searchText || "").trim();
const needLocalFilter = mapped !== "ALL" && keyword.length > 0;
let reqPage = data.value.params.pageNum;
let reqSize = data.value.params.pageSize;
if (needLocalFilter) {
reqPage = 0;
reqSize = 1000;
}
const payload = {
projectId,
page: reqPage,
size: reqSize,
keyword,
searchType: mapped,
sortField: "id",
sortDirection: "DESC",
refType: "TRAINING_SCRIPT",
};
const setPaginationLength = () => {
if (data.value.totalDataLength % data.value.params.pageSize === 0) {
data.value.pageLength =
data.value.totalDataLength / data.value.params.pageSize;
} else {
data.value.pageLength = Math.ceil(
data.value.totalDataLength / data.value.params.pageSize,
try {
const res = await AttachmentsService.search(payload as any);
const result = res?.data ?? res;
let list = result?.content ?? [];
if (needLocalFilter) {
const kw = keyword.toLowerCase();
if (mapped === "TITLE") {
list = list.filter((x: any) =>
String(x?.title ?? "")
.toLowerCase()
.includes(kw),
);
} else if (mapped === "AUTHOR") {
list = list.filter((x: any) =>
String(x?.regUserId ?? "")
.toLowerCase()
.includes(kw),
);
}
};
const saveData = (formData) => {
if (data.value.modalMode === "create") {
// DeviceService.add(formData).then((d) => {
// if (d.status === 200) {
// data.value.isModalVisible = false;
// store.setSnackbarMsg({
// text: " .",
// result: 200,
// });
// changePageNum(1);
// } else {
// store.setSnackbarMsg({
// text: d,
// result: 500,
// });
// }
// });
} else {
// DeviceService.update(formData.deviceKey, formData).then((d) => {
// if (d.status === 200) {
// data.value.isModalVisible = false;
// store.setSnackbarMsg({
// text: " .",
// result: 200,
// });
// changePageNum();
// } else {
// store.setSnackbarMsg({
// text: d,
// result: 500,
// });
// }
// });
//
const uiSize = data.value.params.pageSize;
const totalElements = list.length;
const totalPages = Math.max(1, Math.ceil(totalElements / uiSize));
const safePage = Math.min(Math.max(1, pageNum), totalPages);
const start = (safePage - 1) * uiSize;
const pageSlice = list.slice(start, start + uiSize);
data.value.results = pageSlice.map(toRow);
data.value.totalElements = totalElements;
data.value.pageLength = totalPages;
return;
}
//
data.value.results = (list as any[]).map(toRow);
data.value.totalElements = result?.totalElements ?? list.length;
data.value.pageLength = result?.totalPages ?? 1;
} catch (err) {
console.error("[TrainingScript] 조회 에러:", err);
data.value.results = [];
data.value.totalElements = 0;
data.value.pageLength = 1;
}
};
const removeData = (value) => {
let removeList = value ? value : data.value.selected;
const remove = (code) => {
// return DeviceService.delete(code).then((d) => {
// if (d.status !== 200) {
// store.setSnackbarMsg({
// text: d,
// result: 500,
// });
// }
// });
/** 검색 실행 (페이지 1로 리셋) */
const doSearch = () => {
data.value.params.pageNum = 1;
fetchList();
};
if (removeList.length === 1) {
remove(removeList[0].deviceKey).then(() => {
// store.setSnackbarMsg({
// text: ".",
// result: 200,
// });
changePageNum();
data.value.isConfirmDialogVisible = false;
data.value.selected = [];
data.value.allSelected = false;
/** 페이지 이동 */
const changePageNum = (page: number) => {
data.value.params.pageNum = page;
fetchList();
};
/** 페이지 사이즈 변경 */
const changePageSize = (size: number) => {
data.value.params.pageSize = size;
data.value.params.pageNum = 1;
fetchList();
};
// / ( )
const removeData = (value?: Array<{ deviceKey: number }>) => {
const removeList = value ?? data.value.selected;
if (!removeList || removeList.length === 0) return;
const ids = removeList.map((x) => x.deviceKey);
const removeOne = (id: number) =>
AttachmentsService.delete(id).then((res) => {
if (res.status < 200 || res.status >= 300) return Promise.reject(res);
});
} else {
Promise.all(removeList.map((item) => remove(item.deviceKey))).finally(
() => {
// store.setSnackbarMsg({
// text: " .",
// result: 200,
// });
changePageNum();
const after = () => {
if (
ids.length >= data.value.results.length &&
data.value.params.pageNum > 1
) {
data.value.params.pageNum -= 1;
}
fetchList();
data.value.isConfirmDialogVisible = false;
data.value.selected = [];
data.value.allSelected = false;
},
);
}
};
const handleRemoveData = () => {
if (data.value.selected.length === 0) {
// store.setSnackbarMsg({
// text: " . ",
// result: 500,
// });
return;
}
if (data.value.allSelected || data.value.selected.length !== 1) {
data.value.isConfirmDialogVisible = true;
return;
// /
if (ids.length === 1) {
removeOne(ids[0])
.then(() => {
store.setSnackbarMsg({
color: "success",
text: "삭제되었습니다.",
result: 200,
});
after();
})
.catch((err) => {
console.error("삭제 실패:", err);
store.setSnackbarMsg({
color: "warning",
text: "삭제 실패",
result: 500,
});
});
} else {
Promise.all(ids.map(removeOne))
.then(() => {
store.setSnackbarMsg({
color: "success",
text: "모두 삭제되었습니다.",
result: 200,
});
})
.catch((err) => {
console.error("일부 삭제 실패:", err);
store.setSnackbarMsg({
color: "warning",
text: "일부 삭제 실패",
result: 500,
});
})
.finally(after);
}
//
removeData(undefined);
};
const closeDetail = () => {
openView.value = false;
};
const changePageNum = (page) => {
data.value.params.pageNum = page;
getData();
};
const openSettingModal = (selectedItem) => {
const openDetailModal = (selectedItem: any) => {
data.value.selectedData = selectedItem;
data.value.modalMode = "setting";
openView.value = true;
};
const openCreateModal = () => {
data.value.selectedData = null;
data.value.modalMode = "create";
data.value.selectedData = {
username: username.value,
projectId: getProjectId(),
};
data.value.isCreateVisible = true;
};
const openModifyModal = () => {
data.value.selectedData = null;
const openModifyModal = (item: any) => {
data.value.modalMode = "edit";
data.value.isUploadVisible = true;
data.value.selectedData = {
id: item.deviceKey,
title: item.title,
description: item.description,
};
data.value.isCreateVisible = true;
};
const closeCreateModal = () => {
data.value.isModalVisible = false;
data.value.isCreateVisible = null;
data.value.isCreateVisible = false;
data.value.selectedData = null;
};
const closeModifyModal = () => {
data.value.isModalVisible = false;
data.value.isUploadVisible = null;
data.value.isUploadVisible = false;
data.value.selectedData = null;
};
const getSelectedAllData = () => {
data.value.selected = data.value.allSelected
? data.value.results.map((item) => {
return {
deviceKey: item.deviceKey,
};
})
? data.value.results.map((item: any) => ({ deviceKey: item.deviceKey }))
: [];
};
onMounted(() => {
getData();
getCodeList();
username.value = readUsernameFromStorage();
fetchList();
});
</script>
<template>
<div class="w-100" v-if="!openView">
<!-- <v-dialog v-model="data.isModalVisible" max-width="600" persistent>-->
<!-- <FormComponent-->
<!-- :edit-data="data.selectedData"-->
<!-- :mode="data.modalMode"-->
<!-- @close-modal="closeModal"-->
<!-- @handle-data="saveData"-->
<!-- :user-option="data.userOption"-->
<!-- />-->
<!-- </v-dialog>-->
<!-- <v-dialog v-model="data.isConfirmDialogVisible" persistent max-width="300">-->
<!-- <ConfirmDialogComponent-->
<!-- @cancel="data.isConfirmDialogVisible = false"-->
<!-- @delete="removeData(undefined)"-->
<!-- @init="(data.selected = []), (data.allSelected = false)"-->
<!-- />-->
<!-- </v-dialog>-->
<v-container fluid class="h-100 pa-5 d-flex flex-column align-center">
<v-card
flat
class="bg-shades-transparent d-flex flex-column align-center justify-center w-100"
>
<!-- 헤더 -->
<v-card flat class="bg-shades-transparent w-100">
<v-card-item class="text-h5 font-weight-bold pt-0 pa-5 pl-0">
<div class="d-flex flex-row justify-start align-center">
@ -343,7 +337,9 @@ onMounted(() => {
</div>
</v-card-item>
</v-card>
<v-card flat class="bg-shades-transparent w-100">
<!-- 검색 영역 -->
<v-card flat class="bg-shades-transparent mb-4">
<div class="d-flex justify-center flex-wrap align-center">
<v-responsive
@ -356,11 +352,12 @@ onMounted(() => {
label="검색조건"
density="compact"
:items="searchOptions"
item-title="searchType"
item-value="searchText"
item-title="label"
item-value="value"
hide-details
></v-select>
/>
</v-responsive>
<v-responsive min-width="540" max-width="540">
<v-text-field
v-model="data.params.searchText"
@ -370,8 +367,8 @@ onMounted(() => {
required
class="mt-3 mb-3"
hide-details
@keyup.enter="changePageNum(1)"
></v-text-field>
@keyup.enter="doSearch"
/>
</v-responsive>
<div class="ml-3">
@ -379,7 +376,7 @@ onMounted(() => {
size="large"
color="primary"
:rounded="5"
@click="changePageNum(1)"
@click="doSearch"
>
<v-icon>mdi-magnify</v-icon>
</v-btn>
@ -387,6 +384,7 @@ onMounted(() => {
</div>
</v-card>
<!-- 상단 툴바 -->
<v-sheet
class="bg-shades-transparent d-flex flex-wrap align-center mb-2"
>
@ -394,10 +392,12 @@ onMounted(() => {
<v-sheet
class="d-flex align-center mr-3 mb-2 bg-shades-transparent"
>
<!-- 스크립트의 totalElements 사용 -->
<v-chip color="primary"
> {{ data.totalDataLength.toLocaleString() }}
</v-chip>
> {{ data.totalElements.toLocaleString() }}</v-chip
>
</v-sheet>
<v-sheet class="bg-shades-transparent">
<v-responsive max-width="140" min-width="140" class="mb-2">
<v-select
@ -409,18 +409,18 @@ onMounted(() => {
variant="outlined"
color="primary"
hide-details
@update:model-value="changePageNum(1)"
></v-select>
@update:model-value="changePageSize"
/>
</v-responsive>
</v-sheet>
</v-sheet>
<v-sheet class="justify-end mb-2">
<v-btn color="info" @click="openCreateModal"
>Create Script
</v-btn>
<v-btn color="info" @click="openCreateModal">Create Script</v-btn>
</v-sheet>
</v-sheet>
<!-- 목록 -->
<v-card class="rounded-lg pa-8">
<v-col cols="12">
<v-sheet>
@ -428,8 +428,6 @@ onMounted(() => {
density="comfortable"
fixed-header
height="625"
col-md-12
col-12
overflow-x-auto
>
<colgroup>
@ -439,18 +437,20 @@ onMounted(() => {
:style="`width:${item.width}`"
/>
</colgroup>
<thead>
<tr>
<th
v-for="(item, i) in tableHeader"
:key="i"
class="text-center font-weight-bold"
:style="`${item.style}`"
:style="item.style"
>
{{ item.label }}
</th>
</tr>
</thead>
<tbody class="text-body-2">
<tr
v-for="(item, i) in data.results"
@ -464,8 +464,8 @@ onMounted(() => {
<td>{{ item.createdData }}</td>
<td>{{ item.modifiedData }}</td>
<td style="white-space: nowrap">
<IconInfoBtn @on-click="openSettingModal(item)" />
<IconModifyBtn @on-click="openModifyModal()" />
<IconInfoBtn @on-click="openDetailModal(item)" />
<IconModifyBtn @on-click="openModifyModal(item)" />
<IconDeleteBtn
@on-click="
removeData([{ deviceKey: item.deviceKey }])
@ -476,6 +476,7 @@ onMounted(() => {
</tbody>
</v-table>
</v-sheet>
<v-card-actions class="text-center mt-8 justify-center">
<v-pagination
v-model="data.params.pageNum"
@ -483,36 +484,33 @@ onMounted(() => {
:total-visible="10"
color="primary"
rounded="circle"
@update:model-value="getData"
></v-pagination>
@update:model-value="changePageNum"
/>
</v-card-actions>
</v-col>
</v-card>
</v-card>
</v-card>
</v-container>
<!-- 등록 다이얼로그 -->
<v-dialog v-model="data.isCreateVisible" max-width="600" persistent>
<TrainingScriptBaseDoalog
:edit-data="data.selectedData"
:mode="data.modalMode"
@close-modal="closeCreateModal"
@handle-data="saveData"
:user-option="data.userOption"
/>
</v-dialog>
<v-dialog v-model="data.isUploadVisible" max-width="600" persistent>
<TrainingScriptBaseDoalog
:edit-data="data.selectedData"
:mode="data.modalMode"
@close-modal="closeModifyModal"
@handle-data="saveData"
@saved="fetchList"
:user-option="data.userOption"
/>
</v-dialog>
</div>
<div class="w-100" v-else>
<ViewComponent @close="closeDetail" />
<ViewComponent
v-if="data.selectedData"
:id="data.selectedData.deviceKey"
@close="closeDetail"
/>
</div>
</template>

@ -1,188 +1,113 @@
<script setup lang="ts">
import IconDeleteBtn from "@/components/atoms/button/IconDeleteBtn.vue";
import IconModifyBtn from "@/components/atoms/button/IconModifyBtn.vue";
// import FormComponent from "@/components/device/FormComponent.vue";
import { onBeforeUnmount, onMounted, ref, watch } from "vue";
import {
defineProps,
defineEmits,
ref,
computed,
onMounted,
watch,
onBeforeUnmount,
} from "vue";
import * as monaco from "monaco-editor";
import "monaco-editor/min/vs/editor/editor.main.css";
// const store = commonStore();
const editorRef = ref<HTMLDivElement | null>(null);
let editorInstance: monaco.editor.IStandaloneCodeEditor | null = null;
const experimentInfo = ref({
modelName: "ImageClassifier",
projectName: "배터리 상태 예측 모델 프로젝트",
experimentName: "Baseline Model Training",
executionName: "run-batch32-lr0.001",
deployDate: "2025-02-06",
createdId: "ADMIN_001",
description: "기본 모델 구조로 학습 성능 측정",
});
import { AttachmentsService } from "@/components/service/management/attachmentsService";
const yamlContent = `import argparse
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset
import os
class SimpleNet(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim):
super(SimpleNet, self).__init__()
self.fc1 = nn.Linear(input_dim, hidden_dim)
self.relu = nn.ReLU()
`;
const props = defineProps<{ id: number | string }>();
const emit = defineEmits<{ (e: "close"): void }>();
const data = ref({
params: {
pageNum: 1,
pageSize: 10,
searchType: "",
searchText: "",
},
results: [],
totalDataLength: 0,
pageLength: 0,
modalMode: "",
selectedData: null,
allSelected: false,
selected: [],
isModalVisible: false,
isConfirmDialogVisible: false,
userOption: [],
});
const loading = ref(false);
const detailRaw = ref<any | null>(null);
const getCodeList = () => {
// UserService.search(data.value.params).then((d) => {
// if (d.status === 200) {
// data.value.userOption = d.data.userList;
// }
// });
};
const editorRef = ref<HTMLDivElement | null>(null);
let editorInstance: monaco.editor.IStandaloneCodeEditor | null = null;
const setPaginationLength = () => {
if (data.value.totalDataLength % data.value.params.pageSize === 0) {
data.value.pageLength =
data.value.totalDataLength / data.value.params.pageSize;
} else {
data.value.pageLength = Math.ceil(
data.value.totalDataLength / data.value.params.pageSize,
);
}
};
const formatIso = (s?: string) =>
s ? String(s).replace("T", " ").slice(0, 19) : "-";
const mapToViewModel = (raw: any) => ({
title: raw?.title ?? "-",
fileName: raw?.originalName ?? "-",
filePath: raw?.storagePath ?? "-",
createdDate: formatIso(raw?.regDt),
modifiedDate: "-",
createdId: raw?.regUserId ?? "-",
description: raw?.description ?? "-",
});
const info = computed(() => mapToViewModel(detailRaw.value || {}));
const saveData = (formData) => {
if (data.value.modalMode === "create") {
// DeviceService.add(formData).then((d) => {
// if (d.status === 200) {
// data.value.isModalVisible = false;
// store.setSnackbarMsg({
// text: " .",
// result: 200,
// });
// changePageNum(1);
// } else {
// store.setSnackbarMsg({
// text: d,
// result: 500,
// });
// }
// });
} else {
// DeviceService.update(formData.deviceKey, formData).then((d) => {
// if (d.status === 200) {
// data.value.isModalVisible = false;
// store.setSnackbarMsg({
// text: " .",
// result: 200,
// });
// changePageNum();
// } else {
// store.setSnackbarMsg({
// text: d,
// result: 500,
// });
// }
// });
function ensureEditor() {
if (editorInstance || !editorRef.value) return;
editorInstance = monaco.editor.create(editorRef.value, {
value: "",
language: "plaintext",
theme: "vs-dark",
readOnly: true,
automaticLayout: true,
minimap: { enabled: false },
lineNumbers: "on",
});
}
};
const removeData = (value) => {
let removeList = value ? value : data.value.selected;
const remove = (code) => {
// return DeviceService.delete(code).then((d) => {
// if (d.status !== 200) {
// store.setSnackbarMsg({
// text: d,
// result: 500,
// });
// }
// });
};
async function loadPreviewFromStoragePath(objectName?: string) {
const key = (objectName || "").trim();
if (!key) return;
if (removeList.length === 1) {
remove(removeList[0].deviceKey).then(() => {
// store.setSnackbarMsg({
// text: ".",
// result: 200,
// });
// ( )
const res = await AttachmentsService.readTextByPath(key);
data.value.isConfirmDialogVisible = false;
data.value.selected = [];
data.value.allSelected = false;
});
} else {
Promise.all(removeList.map((item) => remove(item.deviceKey))).finally(
() => {
// store.setSnackbarMsg({
// text: " .",
// result: 200,
// });
const text =
typeof res?.data === "string" ? res.data : String(res?.data ?? "");
data.value.isConfirmDialogVisible = false;
data.value.selected = [];
data.value.allSelected = false;
},
);
ensureEditor();
editorInstance?.setValue(text || "# (empty)");
}
};
const changePageNum = (page) => {
data.value.params.pageNum = page;
};
/** 상세 조회 후 storagePath로 프리뷰 호출 */
async function fetchDetail(id: number | string) {
const idNum = typeof id === "string" ? Number(id) : id;
if (!Number.isFinite(idNum as number)) return;
loading.value = true;
try {
const res = await AttachmentsService.view(idNum as number);
detailRaw.value = res?.data ?? res;
ensureEditor();
editorInstance?.setValue(
"# Preview (loading...)\n" +
`# title: ${info.value.title}\n` +
`# file : ${info.value.fileName}\n`,
);
const emit = defineEmits<{
(e: "close"): void;
}>();
await loadPreviewFromStoragePath(
detailRaw.value?.storagePath || detailRaw.value?.storedName,
);
} catch (e) {
console.error("[TrainingScript View] fetch detail error:", e);
} finally {
loading.value = false;
}
}
onMounted(() => {
getCodeList();
if (editorRef.value) {
editorInstance = monaco.editor.create(editorRef.value, {
value: yamlContent,
language: "yaml",
theme: "vs-dark",
readOnly: true,
automaticLayout: true,
minimap: { enabled: false },
lineNumbers: "on",
});
}
ensureEditor();
fetchDetail(props.id);
});
watch(
() => props.id,
(now) => {
if (now !== undefined && now !== null && now !== "") fetchDetail(now);
},
);
onBeforeUnmount(() => {
if (editorInstance) {
editorInstance.dispose();
editorInstance?.dispose();
editorInstance = null;
}
});
</script>
<template>
<v-container fluid class="h-100 pa-5 d-flex flex-column align-center">
<v-card
flat
class="bg-shades-transparent d-flex flex-column justify-center w-100"
>
<v-card flat class="bg-shades-transparent w-100">
<v-card flat class="bg-shades-transparent w-100 mb-6">
<v-card-item class="text-h5 font-weight-bold pt-0 pa-5 pl-0">
<div class="d-flex flex-row justify-start align-center">
<div class="text-primary">View Details</div>
@ -196,96 +121,62 @@ onBeforeUnmount(() => {
</v-card-title>
<v-card-text class="px-6 pb-6 pt-4">
<!-- Experiment Name -->
<v-row align="center" class="py-2">
<v-col cols="3" class="text-h6 font-weight-bold"
>Training Script Title
</v-col>
<v-col cols="9" class="pa-2">{{ experimentInfo.modelName }}</v-col>
>Training Script Title</v-col
>
<v-col cols="9" class="pa-2">{{ info.title }}</v-col>
</v-row>
<VDivider class="my-2" />
<!-- Project Name -->
<v-divider class="my-2" />
<v-row align="center" class="py-2">
<v-col cols="3" class="text-h6 font-weight-bold">File Name</v-col>
<v-col cols="9" class="pa-2">{{
experimentInfo.projectName
}}</v-col>
<v-col cols="9" class="pa-2">{{ info.fileName }}</v-col>
</v-row>
<VDivider class="my-2" />
<v-divider class="my-2" />
<v-row align="center" class="py-2">
<v-col cols="3" class="text-h6 font-weight-bold">File Path</v-col>
<v-col cols="9" class="pa-2">{{
experimentInfo.experimentName
<v-col cols="9" class="pa-2" style="word-break: break-all">{{
info.filePath
}}</v-col>
</v-row>
<VDivider class="my-2" />
<!-- Created Date / ID -->
<v-divider class="my-2" />
<v-row align="center" class="py-2">
<v-col cols="3" class="text-h6 font-weight-bold"
>Created Date
</v-col>
<v-col cols="3" class="pa-2">{{ experimentInfo.deployDate }}</v-col>
<v-col cols="3" class="text-h6 font-weight-bold"
>Modified Date
</v-col>
<v-col cols="3" class="pa-2">{{ experimentInfo.createdId }}</v-col>
<v-col cols="3" class="text-h6 font-weight-bold">Created Date</v-col>
<v-col cols="3" class="pa-2">{{ info.createdDate }}</v-col>
<v-col cols="3" class="text-h6 font-weight-bold">Modified Date</v-col>
<v-col cols="3" class="pa-2">{{ info.modifiedDate }}</v-col>
</v-row>
<VDivider class="my-2" />
<!-- Description -->
<v-divider class="my-2" />
<v-row align="center" class="py-2">
<v-col cols="3" class="text-h6 font-weight-bold">Created ID</v-col>
<v-col cols="9" class="pa-2">{{ info.createdId }}</v-col>
</v-row>
<v-divider class="my-2" />
<v-row align="center" class="py-2">
<v-col cols="3" class="text-h6 font-weight-bold">Description</v-col>
<v-col cols="9" class="pa-2">{{
experimentInfo.description
}}</v-col>
<v-col cols="9" class="pa-2">{{ info.description }}</v-col>
</v-row>
</v-card-text>
</v-card>
<!-- 미리보기 -->
<v-card flat class="bordered-box mb-6 w-100 rounded-lg pa-8">
<v-card-title class="grey lighten-4 py-2 px-4">
<span class="font-weight-bold">Training Script Preview</span>
</v-card-title>
<v-card-text class="px-6 pb-6 pt-4">
<div ref="editorRef" class="editor-container"></div
></v-card-text>
<div ref="editorRef" class="editor-container"></div>
</v-card-text>
<v-sheet class="d-flex justify-end mb-2">
<v-btn color="primary" @click="emit('close')">Back to List</v-btn>
</v-sheet>
</v-card>
</v-card>
</v-container>
</template>
<style scoped>
.editor-container {
width: 100%;
height: 400px; /* 원하시는 높이로 설정하세요 */
}
.v-card-text {
width: 100% !important;
border-collapse: collapse;
/* 전체 테이블 1px 테두리 */
}
.v-card-text th {
font-size: 20px;
min-width: 400px;
border: 1px solid rgba(255, 255, 255, 0.12);
background-color: rgba(255, 255, 255, 0.05);
font-weight: 600;
text-align: center;
white-space: nowrap;
}
.v-card-text td {
font-size: 16px;
min-width: 600px;
padding: 12px 16px;
text-align: left;
border: 1px solid rgba(255, 255, 255, 0.12);
}
.v-card-text tr:nth-child(odd) {
background-color: rgba(255, 255, 255, 0.02);
height: 400px;
}
</style>

@ -0,0 +1,669 @@
<script setup lang="ts">
import { ref, onMounted, watch, computed } from "vue";
import { commonStore } from "@/stores/commonStore";
import { storage } from "@/utils/storage.js";
import { ProjectService } from "@/components/service/project/projectService";
import { UserManagerService } from "@/components/service/management/userManagerService";
import IconDeleteBtn from "@/components/atoms/button/IconDeleteBtn.vue";
import IconModifyBtn from "@/components/atoms/button/IconModifyBtn.vue";
/** ---------- 상수/상태 ---------- */
const store = commonStore();
const roleOptions = ["ROLE_USER", "ROLE_MODERATOR", "ROLE_ADMIN"] as const;
type SearchType = "전체" | "제목" | "작성자";
const searchOptions = [
{ label: "전체", value: "전체" as SearchType },
{ label: "제목", value: "제목" as SearchType },
{ label: "작성자", value: "작성자" as SearchType },
];
const SEARCH_TYPE_MAP: Record<SearchType | "", "ALL" | "TITLE" | "AUTHOR"> = {
"": "ALL",
전체: "ALL",
제목: "TITLE",
작성자: "AUTHOR",
};
const fmtDate = (v?: string) => (v ? v.replace("T", " ").slice(0, 19) : "-");
const splitCsv = (v?: string) =>
String(v ?? "")
.split(",")
.map((s) => s.trim())
.filter(Boolean);
/** 로그인한 사용자의 권한 (필요 시) */
const roles = ref<string[]>([]);
const refreshRoles = () => {
const auth = storage.getAuth?.() ?? storage.get?.("vpp-Auth") ?? null;
const r = auth?.userInfo?.roles ?? auth?.roles ?? [];
roles.value = Array.isArray(r) ? r : [];
};
const isAdmin = computed(() => roles.value.includes("ROLE_ADMIN"));
/** 테이블 정의 */
const tableHeader = [
{ label: "No", width: "6%", style: "word-break: keep-all;" },
{ label: "Username", width: "10%", style: "word-break: keep-all;" },
{ label: "Email", width: "20%", style: "word-break: keep-all;" },
{ label: "Roles", width: "27%", style: "word-break: keep-all;" },
{ label: "Projects", width: "27%", style: "word-break: keep-all;" },
{ label: "Action", width: "10%", style: "word-break: keep-all;" },
];
const pageSizeOptions = [
{ text: "10 페이지", value: 10 },
{ text: "50 페이지", value: 50 },
{ text: "100 페이지", value: 100 },
];
/** ---------- 타입 ---------- */
type Row = {
no: number;
name: string; // username
desc: string; // email
users: string[]; // roles
projects: string[]; // project names
registDt: string;
deviceKey: number; // user id
};
type SelectedUser = {
id: number;
username: string;
email: string;
role: string; //
} | null;
/** ---------- 상태 ---------- */
const data = ref({
params: {
pageNum: 1,
pageSize: 10,
searchType: "전체" as SearchType,
searchText: "",
},
results: [] as Row[],
totalDataLength: 0,
pageLength: 0,
modalMode: "" as "create" | "edit" | "",
selectedData: null as SelectedUser,
allSelected: false,
selected: [] as Array<{ deviceKey: number }>,
isCreateVisible: false,
isConfirmDialogVisible: false,
});
/** 사용자 폼: Roles 단일 선택 */
const userForm = ref({
username: "",
email: "",
password: "",
roles: "" as (typeof roleOptions)[number] | "", //
});
const resetUserForm = () => {
userForm.value = { username: "", email: "", password: "", roles: "" };
};
/** ---------- 목록/검색 ---------- */
function toRow(u: any, no: number, projectNames: string[] = []): Row {
const rolesArr = Array.isArray(u?.roles)
? u.roles
: typeof u?.roles === "string"
? splitCsv(u.roles)
: [];
return {
no,
name: u?.username ?? u?.name ?? "-",
desc: u?.email ?? "-", //
users: rolesArr,
projects: projectNames,
registDt: fmtDate(u?.createdAt ?? u?.regDate),
deviceKey: Number(u?.id),
};
}
async function getData() {
const { pageNum, pageSize, searchType, searchText } = data.value.params;
const mapped = SEARCH_TYPE_MAP[searchType] || "ALL";
const keyword = (searchText || "").trim().toLowerCase();
try {
// 1)
const res = await UserManagerService.getAll();
let list: any[] = Array.isArray(res?.data) ? res.data : [];
// 2)
if (keyword) {
list = list.filter((u) => {
const username = String(u?.username ?? u?.name ?? "").toLowerCase();
const email = String(u?.email ?? "").toLowerCase();
const rolesStr = Array.isArray(u?.roles)
? u.roles.join(",").toLowerCase()
: String(u?.roles ?? "").toLowerCase();
if (mapped === "TITLE") return username.includes(keyword);
if (mapped === "AUTHOR")
return email.includes(keyword) || rolesStr.includes(keyword);
return (
username.includes(keyword) ||
email.includes(keyword) ||
rolesStr.includes(keyword)
);
});
}
// 3) &
list.sort((a, b) => (Number(b?.id) || 0) - (Number(a?.id) || 0));
const totalElements = list.length;
const totalPages = Math.max(1, Math.ceil(totalElements / pageSize));
const safePage = Math.min(Math.max(1, pageNum), totalPages);
const start = (safePage - 1) * pageSize;
const pageSlice = list.slice(start, start + pageSize);
const firstNo = totalElements - start;
// 4)
data.value.results = pageSlice.map((u: any, i: number) =>
toRow(u, Math.max(1, firstNo - i), []),
);
data.value.totalDataLength = totalElements;
data.value.pageLength = totalPages;
const projectLists = await Promise.all(
pageSlice.map((u) =>
ProjectService.userProjectAuthority(Number(u?.id))
.then((r: any) => (Array.isArray(r?.data) ? r.data : []))
.catch(() => []),
),
);
data.value.results = pageSlice.map((u: any, i: number) => {
const projs = projectLists[i] || [];
const names = projs
.map((p: any) => String(p?.projectName ?? ""))
.filter(Boolean);
return toRow(u, Math.max(1, firstNo - i), names);
});
} catch (e) {
console.error("[Users] fetch error:", e);
data.value.results = [];
data.value.totalDataLength = 0;
data.value.pageLength = 1;
}
}
/** ---------- 페이지/검색 트리거 ---------- */
function doSearch() {
data.value.params.pageNum = 1;
getData();
}
function changePageSize(size: number) {
data.value.params.pageSize = size;
data.value.params.pageNum = 1;
getData();
}
function changePageNum(page: number) {
data.value.params.pageNum = page;
getData();
}
watch(
() => data.value.params.searchType,
() => doSearch(),
);
/** ---------- 모달 열기/닫기 (워크플로우 패턴) ---------- */
const openCreateModal = () => {
data.value.selectedData = null;
data.value.modalMode = "create";
resetUserForm();
data.value.isCreateVisible = true;
};
const openModifyModal = (row: Row) => {
data.value.selectedData = {
id: row.deviceKey,
username: row.name,
email: row.desc === "-" ? "" : row.desc,
role: row.users?.[0] || "",
};
data.value.modalMode = "edit";
//
userForm.value.username = row.name || "";
userForm.value.email = row.desc === "-" ? "" : row.desc || "";
userForm.value.password = ""; //
userForm.value.roles = (row.users?.[0] as any) || "";
data.value.isCreateVisible = true;
};
const closeCreateModal = () => {
data.value.isCreateVisible = false;
};
/** 모달 열림/닫힘 감시 → 닫힐 때 목록 갱신 */
watch(
() => data.value.isCreateVisible,
(now, prev) => {
if (prev && !now) getData();
},
);
/** ---------- 저장(생성/수정) ---------- */
async function saveUser() {
try {
const username = userForm.value.username.trim();
const password = (userForm.value.password || "").trim();
const email = (userForm.value.email || "").trim();
const roleOne = userForm.value.roles || "";
if (!username || (data.value.modalMode === "create" && !password)) {
return store.setSnackbarMsg?.({
color: "warning",
text: "Username은 필수이며, 생성 시 Password도 필요합니다.",
result: 400,
});
}
const payload: any = {
username,
email,
role: roleOne ? [roleOne] : undefined, //
};
if (password) payload.password = password; //
if (data.value.modalMode === "create") {
await UserManagerService.signUp(payload);
store.setSnackbarMsg?.({
color: "success",
text: "계정이 생성되었습니다.",
result: 200,
});
} else {
const id = Number(data.value.selectedData?.id);
if (!id) {
return store.setSnackbarMsg?.({
color: "warning",
text: "수정할 사용자 ID가 없습니다.",
result: 400,
});
}
// update(id, body) .
await UserManagerService.update(id, payload);
store.setSnackbarMsg?.({
color: "success",
text: "수정되었습니다.",
result: 200,
});
}
await getData();
data.value.isCreateVisible = false;
} catch (e: any) {
console.error("[User] save error:", e?.response?.data || e);
store.setSnackbarMsg?.({
color: "warning",
text:
e?.response?.data?.message || e?.response?.data?.error || "요청 실패",
result: e?.response?.status || 500,
});
}
}
/** ---------- 삭제 ---------- */
function getSelectedAllData() {
data.value.selected = data.value.allSelected
? data.value.results.map((r) => ({ deviceKey: r.deviceKey }))
: [];
}
async function deleteRows(targetList?: Array<{ deviceKey: number }>) {
const removeList = targetList ?? data.value.selected;
if (!removeList?.length) return;
const ids = removeList.map((x) => x.deviceKey);
const remove = (id: number) =>
UserManagerService.delete(id).then((res) => {
if (res.status < 200 || res.status >= 300) return Promise.reject(res);
});
const after = async () => {
if (
ids.length >= data.value.results.length &&
data.value.params.pageNum > 1
) {
data.value.params.pageNum -= 1;
}
await getData();
data.value.isConfirmDialogVisible = false;
data.value.selected = [];
data.value.allSelected = false;
};
if (ids.length === 1) {
try {
await remove(ids[0]);
store.setSnackbarMsg?.({
color: "success",
text: "삭제되었습니다.",
result: 200,
});
} catch (err) {
store.setSnackbarMsg?.({
color: "warning",
text: "삭제 실패",
result: 500,
});
console.error(err);
} finally {
after();
}
} else {
Promise.all(ids.map(remove))
.then(() =>
store.setSnackbarMsg?.({
color: "success",
text: "모두 삭제되었습니다.",
result: 200,
}),
)
.catch((err) => {
store.setSnackbarMsg?.({
color: "warning",
text: "일부 삭제 실패",
result: 500,
});
console.error(err);
})
.finally(after);
}
}
/** ---------- 마운트 ---------- */
onMounted(async () => {
refreshRoles();
await getData();
});
</script>
<template>
<div class="w-100">
<v-container fluid class="h-100 pa-5 d-flex flex-column align-center">
<v-card
flat
class="bg-shades-transparent d-flex flex-column align-center justify-center w-100"
>
<!-- 헤더 -->
<v-card flat class="bg-shades-transparent w-100">
<v-card-item class="text-h5 font-weight-bold pt-0 pa-5 pl-0">
<div class="d-flex flex-row justify-start align-center">
<div class="text-primary">Users</div>
</div>
</v-card-item>
</v-card>
<!-- 검색/페이지 -->
<v-card flat class="bg-shades-transparent w-100">
<v-card flat class="bg-shades-transparent mb-4">
<div class="d-flex justify-center flex-wrap align-center">
<v-responsive
max-width="180"
min-width="180"
class="mr-3 mt-3 mb-3"
>
<v-select
v-model="data.params.searchType"
label="검색조건"
density="compact"
:items="searchOptions"
item-title="label"
item-value="value"
hide-details
/>
</v-responsive>
<v-responsive min-width="540" max-width="540">
<v-text-field
v-model="data.params.searchText"
label="검색어"
density="compact"
clearable
required
class="mt-3 mb-3"
hide-details
@keyup.enter="doSearch"
/>
</v-responsive>
<div class="ml-3">
<v-btn
size="large"
color="primary"
:rounded="5"
@click="doSearch"
>
<v-icon>mdi-magnify</v-icon>
</v-btn>
</div>
</div>
</v-card>
<!-- 상단 툴바 -->
<v-sheet
class="bg-shades-transparent d-flex flex-wrap align-center mb-2"
>
<v-sheet class="d-flex flex-wrap me-auto bg-shades-transparent">
<v-sheet
class="d-flex align-center mr-3 mb-2 bg-shades-transparent"
>
<v-chip color="primary"
> {{ data.totalDataLength.toLocaleString() }}</v-chip
>
</v-sheet>
<v-sheet class="bg-shades-transparent">
<v-responsive max-width="140" min-width="140" class="mb-2">
<v-select
v-model="data.params.pageSize"
density="compact"
:items="pageSizeOptions"
item-title="text"
item-value="value"
variant="outlined"
color="primary"
hide-details
@update:model-value="changePageSize"
/>
</v-responsive>
</v-sheet>
</v-sheet>
<v-sheet class="justify-end mb-2">
<v-btn color="info" @click="openCreateModal">Create User</v-btn>
</v-sheet>
</v-sheet>
<!-- 테이블 -->
<v-card class="rounded-lg pa-8">
<v-col cols="12">
<v-sheet>
<v-table
density="comfortable"
fixed-header
height="625"
overflow-x-auto
>
<colgroup>
<col style="width: 5%" />
<col
v-for="(item, i) in tableHeader"
:key="i"
:style="`width:${item.width}`"
/>
</colgroup>
<thead>
<tr>
<th>
<v-checkbox
v-model="data.allSelected"
style="min-width: 36px"
:indeterminate="data.allSelected === true"
hide-details
@change="getSelectedAllData"
/>
</th>
<th
v-for="(item, i) in tableHeader"
:key="i"
class="text-center font-weight-bold"
:style="`${item.style}`"
>
{{ item.label }}
</th>
</tr>
</thead>
<tbody class="text-body-2">
<tr
v-for="(item, i) in data.results"
:key="i"
class="text-center"
>
<td>
<v-checkbox
v-model="data.selected"
hide-details
:value="{ deviceKey: item.deviceKey }"
/>
</td>
<td>{{ item.no }}</td>
<td>{{ item.name }}</td>
<td>
<div class="truncate-2">{{ item.desc || "-" }}</div>
</td>
<td>
<template v-if="item.users?.length">
<v-chip
v-for="u in item.users"
:key="u"
size="small"
class="ma-1"
color="blue-lighten-2"
text-color="white"
>
{{ u }}
</v-chip>
</template>
<span v-else>-</span>
</td>
<td>
<template v-if="item.projects?.length">
<v-chip
v-for="p in item.projects"
:key="p"
size="small"
class="ma-1"
color="purple-lighten-2"
text-color="white"
>
{{ p }}
</v-chip>
</template>
<span v-else>-</span>
</td>
<td style="white-space: nowrap">
<IconModifyBtn @on-click="openModifyModal(item)" />
<IconDeleteBtn
@on-click="
deleteRows([{ deviceKey: item.deviceKey }])
"
/>
</td>
</tr>
</tbody>
</v-table>
</v-sheet>
<v-card-actions class="text-center mt-8 justify-center">
<v-pagination
v-model="data.params.pageNum"
:length="data.pageLength"
:total-visible="10"
color="primary"
rounded="circle"
@update:model-value="changePageNum"
/>
</v-card-actions>
</v-col>
</v-card>
</v-card>
</v-card>
</v-container>
<!-- 생성/수정 모달 -->
<v-dialog
v-model="data.isCreateVisible"
max-width="560"
:persistent="false"
:close-on-esc="true"
>
<v-card>
<v-card-title class="headline">
{{ data.modalMode === "create" ? "Create User" : "Modify User" }}
</v-card-title>
<v-card-text>
<v-form>
<v-text-field
label="Username"
v-model="userForm.username"
:disabled="data.modalMode === 'edit'"
required
/>
<v-text-field
label="Email"
type="email"
v-model="userForm.email"
autocomplete="off"
/>
<v-text-field
label="Password"
type="password"
v-model="userForm.password"
:required="data.modalMode === 'create'"
autocomplete="new-password"
/>
<v-select
label="Roles"
v-model="userForm.roles"
:items="roleOptions"
:multiple="false"
clearable
chips
/>
</v-form>
</v-card-text>
<v-card-actions>
<v-spacer />
<v-btn color="primary" @click="saveUser">
{{ data.modalMode === "create" ? "Create" : "Save" }}
</v-btn>
<v-btn text @click="closeCreateModal">Cancel</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</div>
</template>
<style scoped></style>

@ -363,7 +363,7 @@ onMounted(() => {
>
<v-select
v-model="data.params.searchType"
label="검색유형"
label="검색조건"
density="compact"
:items="searchOptions"
item-title="label"

Loading…
Cancel
Save