Merge branch 'develop'

This commit is contained in:
Warunee Tamkoo 2025-09-01 17:40:02 +07:00
commit 506241b44c
14 changed files with 1170 additions and 7455 deletions

View file

@ -33,6 +33,7 @@
"quasar": "^2.11.1",
"socket.io-client": "^4.7.4",
"structure-chart": "^0.0.9",
"swagger-ui-dist": "^5.27.1",
"v-code-diff": "^1.12.0",
"vue": "^3.4.15",
"vue-currency-input": "^3.0.5",
@ -44,6 +45,7 @@
"@rushstack/eslint-patch": "^1.1.4",
"@types/jsdom": "^20.0.1",
"@types/node": "^18.11.12",
"@types/swagger-ui-dist": "^3.30.6",
"@vitejs/plugin-vue": "^4.0.0",
"@vitejs/plugin-vue-jsx": "^3.0.0",
"@vue/eslint-config-prettier": "^7.0.0",
@ -55,7 +57,6 @@
"eslint-plugin-cypress": "^2.12.1",
"eslint-plugin-vue": "^9.3.0",
"jsdom": "^20.0.3",
"node-sass": "^9.0.0",
"npm-run-all": "^4.1.5",
"prettier": "^2.7.1",
"quasar-ui-q-draggable-table": "^1.0.1",

7433
pnpm-lock.yaml generated

File diff suppressed because it is too large Load diff

View file

@ -1,7 +1,11 @@
import env from "../index";
const apiKey = `${env.API_URI}/org/apiKey`;
const apiManage = `${env.API_URI}/org/api-manage/`;
const apiManualSwagger = `${env.API_URI}/org/api-manage/manual/swagger`;
export default {
apiKeyMain: apiKey,
apiManage: apiManage,
apiManualSwagger: apiManualSwagger,
};

View file

@ -1,5 +1,5 @@
<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ref, onMounted, onUnmounted } from "vue";
import { useQuasar } from "quasar";
import http from "@/plugins/http";
@ -32,6 +32,7 @@ const {
fetchListBackup,
backupRunningList,
restoreRunningList,
stopAllPolling,
} = useDataStore();
const storeData = useDataStore();
const {
@ -160,6 +161,10 @@ onMounted(async () => {
await restoreRunningList(() => {});
dataMain.value = dataBackUp.value;
});
onUnmounted(() => {
stopAllPolling();
});
</script>
<template>

View file

@ -31,6 +31,9 @@ export const useDataStore = defineStore("systemStore", () => {
const recordRestore = ref<Record<string, DataBackup>>({});
let backupTimeoutId: NodeJS.Timeout | null = null; // Timeout สำหรับการสำรองข้อมูล
let restoreTimeoutId: NodeJS.Timeout | null = null; // Timeout สำหรับการคืนค่า
/**
*
*/
@ -131,6 +134,11 @@ export const useDataStore = defineStore("systemStore", () => {
* @param cb
*/
async function backupRunningList(cb: () => void) {
// Clear timeout
if (backupTimeoutId) {
clearTimeout(backupTimeoutId);
backupTimeoutId = null;
}
await http
.get<BackUpRunning[]>(config.API.backup + "/backup-running-list")
.then(async (res) => {
@ -142,10 +150,6 @@ export const useDataStore = defineStore("systemStore", () => {
return;
}
setTimeout(async () => {
backupRunningList(cb);
}, 3000);
if (prevBackupRunTotal.value !== backupRunTotal.value) {
res.data.forEach((item) => {
const index = dataBackUp.value.findIndex((data) => {
@ -166,6 +170,11 @@ export const useDataStore = defineStore("systemStore", () => {
prevBackupRunTotal.value = backupRunTotal.value;
}
// ตั้งเวลาเรียกใหม่
backupTimeoutId = setTimeout(() => {
backupRunningList(cb);
}, 3000);
})
.catch((err) => {
messageError($q, err);
@ -177,6 +186,12 @@ export const useDataStore = defineStore("systemStore", () => {
* @param cb
*/
async function restoreRunningList(cb: () => void) {
// Clear timeout
if (restoreTimeoutId) {
clearTimeout(restoreTimeoutId);
restoreTimeoutId = null;
}
await http
.get<BackUpRunning[]>(config.API.backup + "/restore-running-list")
.then(async (res) => {
@ -187,10 +202,6 @@ export const useDataStore = defineStore("systemStore", () => {
return;
}
setTimeout(async () => {
restoreRunningList(cb);
}, 3000);
if (prevRestoreRunTotal.value !== restoreRunTotal.value) {
for (const [key, value] of Object.entries(recordRestore.value)) {
if (!res.data.find((v) => v.id === key))
@ -200,6 +211,11 @@ export const useDataStore = defineStore("systemStore", () => {
prevRestoreRunTotal.value = restoreRunTotal.value;
}
// ตั้ง timeout
restoreTimeoutId = setTimeout(() => {
restoreRunningList(cb);
}, 3000);
})
.catch((err) => {
messageError($q, err);
@ -389,6 +405,28 @@ export const useDataStore = defineStore("systemStore", () => {
});
}
/** ฟังก์ชันหยุด polling สำหรับการสำรองข้อมูล */
function stopBackupPolling() {
if (backupTimeoutId) {
clearTimeout(backupTimeoutId);
backupTimeoutId = null;
}
}
/** ฟังก์ชันหยุด polling สำหรับการคืนค่า */
function stopRestorePolling() {
if (restoreTimeoutId) {
clearTimeout(restoreTimeoutId);
restoreTimeoutId = null;
}
}
/** ฟังก์ชันหยุดทั้งหมด */
function stopAllPolling() {
stopBackupPolling();
stopRestorePolling();
}
return {
dataBackUp,
@ -407,6 +445,7 @@ export const useDataStore = defineStore("systemStore", () => {
backupRunningList,
restoreRunningList,
stopAllPolling,
getSize,

View file

@ -0,0 +1,583 @@
<script setup lang="ts">
import { computed, reactive, ref, toRefs, watch } from "vue";
import { useQuasar } from "quasar";
import { useCounterMixin } from "@/stores/mixin";
import { useDataStoreManage } from "@/modules/06_webservices/stores/manage";
import type { DataOption } from "@/modules/06_webservices/interface/index/Main";
import type {
DataSystems,
Propertys,
DataAttributes,
} from "@/modules/06_webservices/interface/response/Main";
/** importComponents*/
import DialogHeader from "@/components/DialogHeader.vue";
import http from "@/plugins/http";
import config from "@/app.config";
const $q = useQuasar();
const { systemList, methodOptions } = toRefs(useDataStoreManage());
const {
showLoader,
hideLoader,
dialogConfirm,
success,
dialogMessageNotify,
messageError,
} = useCounterMixin();
const modal = defineModel<boolean>("modal", { required: true });
const isEdit = defineModel<boolean>("isEdit", { default: false });
const apiId = defineModel<string>("apiId", { default: "" });
const props = defineProps({
fetchData: {
type: Function,
required: true,
},
});
// title dialog
const titleName = computed(() => {
return isEdit.value ? "แก้ไข API" : "เพิ่ม API";
});
// "all"
const options = computed<DataOption[]>(() => {
return systemList.value.filter((e) => e.id !== "all") ?? [];
});
// Main
const mainFields = computed(() => {
return availableFields.value.filter((field) => field.isMain === true);
});
//
const getSelectedCount = computed(() => {
return (tbName: string) => {
if (!selectedAttributes.value[tbName]) return 0;
return Object.values(selectedAttributes.value[tbName]).filter(
(selected) => selected === true
).length;
};
});
const systemMain = ref<string>(""); // Default system
const systemOptions = ref<DataOption[]>(options.value); // Default to first option
const apiPath = ref<string>(""); // Path API
const splitterModel = ref<number>(15); // Initial splitter position
const tabs = ref<string>(""); // Tabs
// Form data
const formData = reactive({
name: "",
methodApi: "GET",
system: "",
isActive: false,
});
const availableFields = ref<DataSystems[]>([]); // fields
const selectedAttributes = ref<Record<string, Record<string, boolean>>>({}); // attributes
const dataAttributes = ref<DataAttributes[]>([]); // attributes
const loading = ref<boolean>(false); //
const validationErrors = ref<string[]>([]); // error validation
/**
* งขอม fields ของ API ตามชอระบบ
* @param system อระบบทองการดงขอม fields
*/
async function fetchData(system: string) {
availableFields.value = [];
loading.value = true;
try {
const res = await http.get(`${config.API.apiManage}${system}/fields`);
availableFields.value = res.data.result || [];
// Reset selected attributes system
selectedAttributes.value = {};
// properties
availableFields.value.forEach((field) => {
// group field ()
selectedAttributes.value[field.tb] = {};
if (field.propertys && field.propertys.length > 0) {
field.propertys.forEach((prop: Propertys) => {
// properties group
selectedAttributes.value[field.tb][prop.propertyName] = false;
});
}
});
tabs.value =
availableFields.value.length > 0 ? availableFields.value[0].tb : "";
} catch (error) {
messageError($q, error);
availableFields.value = [];
} finally {
loading.value = false;
}
}
/**
* งขอม API ตาม ID
* @param id ID ของ API องการดงขอม
*/
async function fetchDataId(id: string) {
showLoader();
try {
const res = await http.get(`${config.API.apiManage}${id}`);
const data = res.data.result;
systemMain.value = data.system;
formData.name = data.name;
formData.methodApi = data.methodApi;
formData.system = data.system;
formData.isActive = data.isActive;
apiPath.value = data.pathApi;
dataAttributes.value = data.apiAttributes || [];
// fields attributes
await fetchData(data.system);
// selectedAttributes
updateSelectedAttributes(data.apiAttributes);
} catch (error) {
messageError($q, error);
} finally {
hideLoader();
}
}
/**
* งกนเมอเลอกระบบจาก select
* @param value อระบบทกเลอก
*/
async function onSelectSystem(value: string) {
await fetchData(value);
if (systemMain.value === value && dataAttributes.value?.length > 0) {
updateSelectedAttributes(dataAttributes.value);
}
}
/** ฟังก์ชันตรวจสอบ validation */
function validateSelection(): boolean {
validationErrors.value = [];
// isMain: true
mainFields.value.forEach((field) => {
const selectedPropsCount = Object.keys(
selectedAttributes.value[field.tb] || {}
).filter(
(propKey) => selectedAttributes.value[field.tb][propKey] === true
).length;
if (selectedPropsCount === 0) {
validationErrors.value.push(
`กรุณาเลือกแอตทริบิวต์ในส่วนของ"${field.description}" อย่างน้อย 1 รายการ`
);
}
});
return validationErrors.value.length === 0;
}
/** ฟังก์ชันบันทึกข้อมูล */
function onSubmit() {
if (!validateSelection()) {
validationErrors.value.forEach((error) => {
dialogMessageNotify($q, error);
});
return;
}
dialogConfirm($q, async () => {
showLoader();
// apiAttributes array
const apiAttributes: Array<{
tbName: string;
propertyKey: string[];
}> = [];
// selectedAttributes apiAttributes
Object.keys(selectedAttributes.value).forEach((fieldKey) => {
const selectedProps: string[] = [];
// property (true)
Object.keys(selectedAttributes.value[fieldKey]).forEach((propKey) => {
if (selectedAttributes.value[fieldKey][propKey]) {
selectedProps.push(propKey);
}
});
// property apiAttributes
if (selectedProps.length > 0) {
apiAttributes.push({
tbName: fieldKey,
propertyKey: selectedProps,
});
}
});
// API
const payload = {
...formData,
apiAttributes: apiAttributes,
};
const method = isEdit.value ? http.put : http.post;
const pathAPI = isEdit.value
? `${config.API.apiManage}${apiId.value}`
: config.API.apiManage;
try {
await method(pathAPI, payload);
await props.fetchData(); // fetchData parent component
success($q, "บันทึกข้อมูลสำเร็จ");
onCloseDialog();
} catch (error) {
messageError($q, error);
return;
} finally {
hideLoader();
}
});
}
/**
* งกนอพเดต selectedAttributes ตามขอมลทงมา
* @param data อมลทองการอพเดต selectedAttributes
*/
function updateSelectedAttributes(
data: Array<{ tbName: string; propertyKey: string }>
) {
if (!data?.length) return;
data.forEach(({ tbName, propertyKey }) => {
if (selectedAttributes.value[tbName]?.[propertyKey] !== undefined) {
selectedAttributes.value[tbName][propertyKey] = true;
}
});
}
/**
* function นหาคำใน select
* @param val คำคนหา
* @param update function
*/
function filterSelector(val: string, update: Function) {
update(() => {
const newVal = val.toLowerCase();
systemOptions.value = options.value.filter(
(v: DataOption) => v.name.toLowerCase().indexOf(newVal) > -1
);
});
}
/** ฟังก์ชันปิด dialog และรีเซ็ตข้อมูล */
function onCloseDialog() {
modal.value = false;
formData.name = "";
formData.methodApi = "GET";
formData.system = "";
formData.isActive = false;
apiPath.value = "";
availableFields.value = [];
selectedAttributes.value = {};
validationErrors.value = [];
dataAttributes.value = [];
systemMain.value = "";
}
watch(modal, (newVal) => {
if (newVal && isEdit.value) {
systemOptions.value = options.value; // dialog
fetchDataId(apiId.value);
}
});
</script>
<template>
<q-dialog v-model="modal" full-height>
<q-card style="min-width: 90%">
<q-form
class="column full-height"
greedy
@submit.prevent
@validation-success="onSubmit"
>
<DialogHeader :tittle="titleName" :close="onCloseDialog" />
<q-separator />
<q-card-section class="col q-pt-none scroll">
<div class="q-pa-md">
<div class="row q-col-gutter-md q-mb-lg">
<div class="col-12 col-md-6">
<q-input
v-model="formData.name"
label="API Name"
outlined
dense
hide-bottom-space
lazy-rules
:rules="[(val:string) => !!val || 'กรุณากรอก API Name']"
/>
</div>
<div class="col-12 col-md-6">
<q-checkbox
v-model="formData.isActive"
color="primary"
:label="formData.isActive ? 'Active' : 'Inactive'"
/>
</div>
<div class="col-12 col-md-1">
<q-select
v-model="formData.methodApi"
label="Method"
:options="methodOptions"
outlined
dense
hide-bottom-space
disable
/>
</div>
<div class="col-12 col-md-5">
<q-input
v-model="apiPath"
outlined
dense
hide-bottom-space
placeholder="Auto generate"
disable
/>
</div>
</div>
<q-card bordered class="row col-12 text-dark">
<div class="bg-grey-1 q-pa-sm col-12 row items-center">
<div class="q-pl-sm text-weight-bold text-subtitle2">
เลอกระบบ
</div>
</div>
<div class="col-12"><q-separator /></div>
<div class="row col-12 q-pa-md">
<div class="col-12 row q-col-gutter-md">
<div class="col-12 col-md-4">
<q-select
dense
hide-bottom-space
outlined
option-label="name"
option-value="id"
emit-value
map-options
v-model="formData.system"
:options="systemOptions"
use-input
hide-selected
fill-input
lazy-rules
:rules="[(val:string) => !!val || 'กรุณาเลือกระบบข้อมูล']"
@update:model-value="onSelectSystem"
@filter="(inputValue: string,doneFn: Function) => filterSelector(inputValue, doneFn )"
>
<template v-slot:no-option>
<q-item>
<q-item-section class="text-grey">
ไมอม
</q-item-section>
</q-item>
</template>
</q-select>
</div>
<div v-if="loading" class="col-12 text-center">
<q-spinner-dots
color="primary"
size="30px"
class="q-mt-md"
/>
</div>
<q-splitter
v-model="splitterModel"
style="height: 55vh"
v-else-if="
!loading &&
formData.system !== '' &&
availableFields.length > 0
"
>
<template v-slot:before>
<div>
<q-tabs
v-model="tabs"
vertical
active-color="primary"
indicator-color="transparent"
dense
>
<q-tab
v-for="items in availableFields"
:key="items.tb"
:name="items.tb"
:label="
items.description +
' (' +
getSelectedCount(items.tb) +
')'
"
style="
justify-content: flex-start;
text-align: left;
"
/>
</q-tabs>
</div>
</template>
<template v-slot:after>
<div class="q-pa-none">
<q-tab-panels
v-model="tabs"
animated
swipeable
vertical
transition-prev="jump-up"
transition-next="jump-up"
>
<q-tab-panel
v-for="value in availableFields"
:key="value.tb"
:name="value.tb"
class="q-pt-none"
>
<div
v-if="
formData.system !== '' &&
value.propertys &&
value.propertys.length > 0
"
>
<div class="row q-col-gutter-sm">
<!-- Loop through properties of this field -->
<div
v-for="property in value.propertys"
:key="property.propertyName"
class="col-xs-12 col-sm-6 col-md-4 col-lg-3"
>
<!-- Property Card -->
<q-card flat bordered>
<q-card-section>
<!-- Property Name Header -->
<div class="text-subtitle2 text-primary">
{{ property.propertyName }}
</div>
<!-- Checkbox with details -->
<q-item
tag="label"
v-ripple
class="q-pa-none"
>
<q-item-section avatar>
<q-checkbox
v-model="
selectedAttributes[value.tb][
property.propertyName
]
"
color="primary"
/>
</q-item-section>
<q-item-section>
<q-item-label class="text-body2">
{{
property.comment ||
property.propertyName
}}
</q-item-label>
<q-item-label
caption
class="text-grey-6"
>
Type: {{ property.type }}
</q-item-label>
</q-item-section>
</q-item>
</q-card-section>
</q-card>
</div>
</div>
</div>
<!-- Empty state for this tab -->
<div
v-else-if="
!value.propertys || value.propertys.length === 0
"
class="text-center q-pa-lg text-grey-6"
>
<q-icon name="info_outline" size="48px" />
<div class="q-mt-md">
ไม properties สำหรบหมวดน
</div>
</div>
</q-tab-panel>
</q-tab-panels>
</div>
</template>
</q-splitter>
</div>
</div>
</q-card>
<!-- System Selection -->
<!-- <div class="row q-mb-lg">
<div class="col-12 col-md-4">
<div class="text-subtitle2 q-mb-sm">เลอกระบบ</div>
<q-select
dense
hide-bottom-space
outlined
option-label="name"
option-value="id"
emit-value
map-options
v-model="formData.system"
:options="systemOptions"
use-input
hide-selected
fill-input
lazy-rules
:rules="[(val:string) => !!val || 'กรุณาเลือกระบบข้อมูล']"
@update:model-value="onSelectSystem"
@filter="(inputValue: string,doneFn: Function) => filterSelector(inputValue, doneFn )"
>
<template v-slot:no-option>
<q-item>
<q-item-section class="text-grey">
ไมอม
</q-item-section>
</q-item>
</template>
</q-select>
</div>
</div> -->
</div>
</q-card-section>
<q-separator />
<q-card-actions align="right">
<q-btn unelevated label="บันทึก" color="public" type="submit" />
</q-card-actions>
</q-form>
</q-card>
</q-dialog>
</template>
<style scoped>
.scroll {
overflow-y: auto;
}
</style>

View file

@ -1,5 +1,6 @@
<script setup lang="ts">
import DialogHeader from "@/components/DialogHeader.vue";
import SwaggerViewer from "@/modules/06_webservices/components/SwaggerViewer.vue";
const modal = defineModel<boolean>("modal", { required: true });
@ -8,18 +9,14 @@ function onCloseDialog() {
}
</script>
<template>
<q-dialog v-model="modal" persistent>
<q-card style="width: 700px; max-width: 80vw">
<q-dialog v-model="modal" persistent maximized>
<q-card style="max-width: 85vw; height: 90vh">
<DialogHeader tittle="วิธีการใช้งาน" :close="onCloseDialog" />
<q-separator />
<q-card-section> </q-card-section>
<q-separator />
<q-card-actions align="right" class="bg-white text-teal">
<q-btn label="ปิด" color="secondary" @click.pervent="onCloseDialog()" />
</q-card-actions>
<q-card-section style="height: 80vh; overflow: auto">
<SwaggerViewer />
</q-card-section>
</q-card>
</q-dialog>
</template>

View file

@ -0,0 +1,55 @@
<template>
<div id="swagger-ui" />
</template>
<script lang="ts" setup>
import { onMounted, ref } from "vue";
import SwaggerUI from "swagger-ui-dist/swagger-ui-es-bundle.js";
import "swagger-ui-dist/swagger-ui.css";
import http from "@/plugins/http";
import config from "@/app.config";
// TypeScript swagger-ui preset
// ( type definition swagger-ui-dist )
interface SwaggerUIBundle {
presets: any;
[key: string]: any;
}
// URL Swagger JSON API
// const swaggerUrl: string = "https://petstore.swagger.io/v2/swagger.json";
const swaggerJson = ref();
async function fetchSwaggerJson() {
swaggerJson.value = await http
.get(`${config.API.apiManualSwagger}`)
.then((res) => {
return res.data.result;
})
.catch((error) => {
console.error("Error fetching Swagger JSON:", error);
return null; //
});
}
onMounted(async () => {
await fetchSwaggerJson();
SwaggerUI({
dom_id: "#swagger-ui",
// url: swaggerUrl,
spec: swaggerJson.value,
});
});
</script>
<style>
.swagger-ui h2.title {
line-height: 1rem;
}
.swagger-ui .scheme-container {
margin: 0 0 0px;
padding: 0px 0px 20px;
}
.swagger-ui .scheme-container .schemes .auth-wrapper {
justify-content: end;
}
</style>

View file

@ -31,4 +31,9 @@ interface DataOption {
name: string;
}
export type { ListWebServices, ListApi, DataOption, ItemsDropdown };
interface Pagination {
page: number;
rowsPerPage: number;
}
export type { ListWebServices, ListApi, DataOption, ItemsDropdown, Pagination };

View file

@ -1,3 +1,5 @@
import type { D } from "@fullcalendar/core/internal-common";
interface ResListWebServices {
id: string;
topic: string;
@ -26,4 +28,49 @@ interface ResApHistory {
ipApi: string;
}
export type { ResListWebServices, ResApiName, ResApHistory };
interface ListSystems {
code: string;
name: string;
}
interface ListApiManages {
code: string;
createdAt: Date;
id: string;
isActive: boolean;
lastUpdatedAt: Date;
methodApi: string;
name: string;
pathApi: string;
system: string;
}
interface DataSystems {
description: string;
isMain: boolean;
tb: string;
propertys: Propertys[];
}
interface Propertys {
comment: string;
key: string;
propertyName: string;
type: string;
}
interface DataAttributes {
propertyKey: string;
tbName: string;
}
export type {
ResListWebServices,
ResApiName,
ResApHistory,
ListSystems,
ListApiManages,
DataSystems,
Propertys,
DataAttributes,
};

View file

@ -0,0 +1,14 @@
import { defineStore } from "pinia";
import { ref } from "vue";
import type { DataOption } from "@/modules/06_webservices/interface/index/Main";
export const useDataStoreManage = defineStore("webservicesManage", () => {
const systemList = ref<DataOption[]>([{ id: "all", name: "ระบบทั้งหมด" }]);
const methodOptions = ["GET", "POST", "PUT", "DELETE"];
return {
systemList,
methodOptions,
};
});

View file

@ -58,7 +58,7 @@ const columns = ref<QTableProps["columns"]>([
style: "font-size: 14px",
format(val) {
return val
.map((e: ResApiName) => `<div class='q-mt-sm'>-${e.name}</div>`)
.map((e: ResApiName) => `<div class='q-mt-sm'>- ${e.name}</div>`)
.join("");
},
},

View file

@ -4,6 +4,7 @@ import { ref } from "vue";
/** importComponents*/
import ListView from "@/modules/06_webservices/view/listView.vue";
import LogView from "@/modules/06_webservices/view/historyView.vue";
import ManageWebServices from "@/modules/06_webservices/view/manage.vue";
const tabs = ref<string>("list");
</script>
@ -27,12 +28,16 @@ const tabs = ref<string>("list");
>
<q-tab name="list" label="รายการ web services" />
<q-tab name="log" label="ประวัติการใช้งาน" />
<q-tab name="manage" label="จัดการ API" />
</q-tabs>
<q-separator />
<q-tab-panels v-model="tabs" animated>
<q-tab-panel name="list"> <ListView /> </q-tab-panel>
<q-tab-panel name="log"> <LogView /> </q-tab-panel>
<q-tab-panel name="manage">
<ManageWebServices />
</q-tab-panel>
</q-tab-panels>
</q-card>
</template>

View file

@ -0,0 +1,393 @@
<script setup lang="ts">
import { onMounted, ref, toRefs, watch } from "vue";
import { useQuasar } from "quasar";
import { useCounterMixin } from "@/stores/mixin";
import { useDataStoreManage } from "@/modules/06_webservices/stores/manage";
import http from "@/plugins/http";
import config from "@/app.config";
/** importType*/
import type { QTableProps } from "quasar";
import type {
DataOption,
Pagination,
} from "@/modules/06_webservices/interface/index/Main";
import type {
ListSystems,
ListApiManages,
} from "@/modules/06_webservices/interface/response/Main";
/** importComponents*/
import DialogApi from "@/modules/06_webservices/components/DialogApi.vue";
/** use*/
const $q = useQuasar();
const { systemList } = toRefs(useDataStoreManage());
const {
dialogRemove,
showLoader,
hideLoader,
messageError,
success,
date2Thai,
} = useCounterMixin();
const systemOptions = ref<DataOption[]>(systemList.value);
/** Table*/
const page = ref<number>(1); //
const pageSize = ref<number>(10); //
const rows = ref<ListApiManages[]>([]); // webservices
const total = ref<number>(0); //
const maxPage = ref<number>(1); //
const keyword = ref<string>(""); // webservices
const systemfilter = ref<string>("all"); //
const isActive = ref<boolean>(true); //
const visibleColumns = ref<string[]>([
"system",
"name",
"methodApi",
"pathApi",
"lastUpdatedAt",
]);
const columns = ref<QTableProps["columns"]>([
{
name: "system",
align: "left",
label: "System",
sortable: true,
field: "system",
headerStyle: "font-size: 14px",
style: "font-size: 14px",
},
{
name: "name",
align: "left",
label: "API Name",
sortable: true,
field: "name",
headerStyle: "font-size: 14px",
style: "font-size: 14px",
},
{
name: "methodApi",
align: "left",
label: "Method",
sortable: true,
field: "methodApi",
headerStyle: "font-size: 14px",
style: "font-size: 14px",
},
{
name: "pathApi",
align: "left",
label: "API Path",
sortable: true,
field: "pathApi",
headerStyle: "font-size: 14px",
style: "font-size: 14px",
},
{
name: "lastUpdatedAt",
align: "left",
label: "updatedAt",
sortable: true,
field: "lastUpdatedAt",
headerStyle: "font-size: 14px",
style: "font-size: 14px",
format(val) {
return date2Thai(val, false, true);
},
},
]);
const modalDialog = ref<boolean>(false); // dialog
const isEditData = ref<boolean>(false); //
const apiId = ref<string>(""); // id api
/** ฟังก์ชันดึงข้อมูลรายการระบบ */
async function fetchSystemData() {
if (systemList.value.length > 1) return; //
try {
const res = await http.get(`${config.API.apiManage}systems`);
const data = res.data.result;
const systemData = data.map((item: ListSystems) => ({
id: item.code,
name: item.name,
}));
systemList.value.push(...systemData);
} catch (error) {
messageError(error);
}
}
/** ฟังก์ชันดึงข้อมูลรายการ API */
async function fetchData() {
try {
const queryParams = {
page: page.value,
pageSize: pageSize.value,
keyword: keyword.value,
system: systemfilter.value === "all" ? "" : systemfilter.value,
isActive: isActive.value,
};
const res = await http.get(`${config.API.apiManage}lists`, {
params: queryParams,
});
const result = res.data.result;
total.value = result.total;
maxPage.value = Math.ceil(total.value / pageSize.value);
rows.value = result.data;
} catch (error) {
messageError(error);
}
}
/**
* งกนลบขอมลรายการ API
* @param id ID ของ API องการลบ
*/
function onDeleteData(id: string) {
dialogRemove($q, async () => {
try {
showLoader();
await http.delete(`${config.API.apiManage}${id}`);
await fetchData();
success($q, "ลบข้อมูลสำเร็จ");
} catch (error) {
messageError($q, error);
} finally {
hideLoader();
}
});
}
/**
* งกนแกไขขอมลรายการ API
* @param id ID ของ API องการแกไข
*/
function onEditData(id: string) {
isEditData.value = true;
modalDialog.value = true;
apiId.value = id; // id api
}
/** ฟังก์ชันค้นหาข้อมูลในตารางใหม่ */
function onSearchDataTable() {
page.value = 1; // 1
fetchData();
}
/**
* งกนคนหาคำใน select
* @param val คำคนหา
* @param update function
*/
function filterSelector(val: string, update: Function) {
update(() => {
const newVal = val.toLowerCase();
systemOptions.value = systemList.value.filter(
(v: DataOption) => v.name.toLowerCase().indexOf(newVal) > -1
);
});
}
/**
* งกนอปเดท paging
* @param initialPagination อม pagination
*/
async function updatePagination(initialPagination: Pagination) {
pageSize.value = initialPagination.rowsPerPage;
}
/** function callback เมื่อมีการเปลี่ยนหน้า*/
watch(
() => pageSize.value,
() => {
onSearchDataTable();
}
);
/** ทำงานเมื่อ component ถูก mount */
onMounted(async () => {
try {
showLoader();
await fetchSystemData();
await fetchData();
} catch (error) {
messageError(error);
} finally {
hideLoader();
}
});
</script>
<template>
<div class="items-center col-12 row q-col-gutter-sm">
<div class="items-center row q-col-gutter-sm col-xs-12 col-sm-auto">
<div class="col-xs-12 col-sm-auto">
<q-select
dense
hide-bottom-space
outlined
option-label="name"
option-value="id"
emit-value
map-options
v-model="systemfilter"
:options="systemOptions"
label="ระบบ"
use-input
hide-selected
fill-input
:clearable="systemfilter !== 'all'"
@clear="systemfilter = 'all'"
@filter="(inputValue: string,doneFn: Function) => filterSelector(inputValue, doneFn )"
@update:model-value="onSearchDataTable"
>
<template v-slot:no-option>
<q-item>
<q-item-section class="text-grey"> ไมอม </q-item-section>
</q-item>
</template>
</q-select>
</div>
<div class="col-xs-12 col-sm-auto">
<q-btn
flat
round
dense
color="primary"
icon="add"
@click="(modalDialog = true), (isEditData = false)"
>
<q-tooltip>สราง API Key </q-tooltip>
</q-btn>
</div>
</div>
<q-space />
<div class="row q-col-gutter-sm col-xs-12 col-sm-auto">
<div class="col-xs-12 col-sm-auto">
<q-toggle
v-model="isActive"
:label="`${isActive ? 'Active' : 'Inactive'}`"
@update:model-value="onSearchDataTable"
/>
</div>
<div class="col-xs-12 col-sm-auto">
<q-input
borderless
dense
outlined
v-model="keyword"
placeholder="ค้นหาชื่อ API"
@keydown.enter.prevent="onSearchDataTable"
>
<template v-slot:append>
<q-icon name="search" />
</template>
</q-input>
</div>
<div class="col-xs-12 col-sm-auto">
<q-select
v-model="visibleColumns"
multiple
outlined
dense
options-dense
:display-value="$q.lang.table.columns"
emit-value
map-options
:options="columns"
option-value="name"
style="min-width: 140px"
/>
</div>
</div>
</div>
<!-- Table -->
<div class="col-12 q-pt-sm">
<d-table
ref="table"
:columns="columns"
:rows="rows"
row-key="id"
flat
bordered
:paging="true"
dense
:rows-per-page-options="[10, 25, 50, 100]"
:visible-columns="visibleColumns"
@update:pagination="updatePagination"
>
<template v-slot:header="props">
<q-tr :props="props">
<q-th auto-width />
<q-th v-for="col in props.cols" :key="col.name" :props="props">
<span class="text-weight-medium">{{ col.label }}</span>
</q-th>
</q-tr>
</template>
<template v-slot:body="props">
<q-tr :props="props">
<q-td auto-width>
<q-btn
dense
flat
round
color="edit"
@click="onEditData(props.row.id)"
icon="mdi-square-edit-outline"
>
<q-tooltip>แกไขขอม</q-tooltip>
</q-btn>
<q-btn
dense
flat
round
color="red"
@click="onDeleteData(props.row.id)"
icon="delete"
>
<q-tooltip>ลบขอม</q-tooltip>
</q-btn>
</q-td>
<q-td v-for="col in props.cols" :key="col.name" :props="props">
<div v-html="col.value ? col.value : '-'"></div>
<div></div>
</q-td>
</q-tr>
</template>
<template v-slot:pagination="scope">
งหมด {{ total }} รายการ
<q-pagination
v-model="page"
active-color="primary"
color="dark"
:max="Number(maxPage)"
size="sm"
boundary-links
direction-links
:max-pages="5"
@update:model-value="fetchData"
></q-pagination>
</template>
</d-table>
</div>
<DialogApi
v-model:modal="modalDialog"
:is-edit="isEditData"
:api-id="apiId"
:fetch-data="fetchData"
/>
</template>
<style scoped></style>