W plikach dotyczących printer dodaj funkcjonalności związane z CRUD. Wzoruj się przy tym…
- User
W plikach dotyczących printer dodaj funkcjonalności związane z CRUD. Wzoruj się przy tym na plikach związanych z occupational-factor. Nie usuwaj i nie zmieniaj ptzy tym funkcjonalności istniejących obecnie w printer. Wygeneruj pełną treść plików, które powinny być zmodyfikowane lub utworzone w celu dodania nowych funkcjonalności.
/// printer.tsn
import { GenericEntity } from "@/views/commerce/common/named-item"; import PrinterStatus from "@/views/commerce/printers/printer-status"; import PrinterTarget from "@/views/commerce/printers/printer-target"; import type { SelectPanelOption } from "@/components/action-buttons/select-panel-option";
export default class Printer extends GenericEntity implements SelectPanelOption { id: string; orgUnitId: number; name: string | null; target: PrinterTarget = PrinterTarget.instance.reception; status: PrinterStatus = PrinterStatus.empty();
public static fromDto(dto: any): Printer { const entity = new Printer(); entity.readDto(dto); return entity; }
protected readDto(dto: any) { super.readDto(dto); this.id = dto.id; this.orgUnitId = dto.orgUnitId; this.name = dto.name; this.target = PrinterTarget.getById(dto.target); this.status = dto.status ? PrinterStatus.fromDto(dto.status) : PrinterStatus.empty(); }
get displayName() { if (this.name) return
${this.name} (${this.id}); return this.id; }get dto(): any { return { id: this.id }; } }
/// printers-query.ts
import { PagedTextQuery } from "@/views/commerce/common/paged-text-query";
export class PrintersQuery extends PagedTextQuery { orgUnitId: number | null = null;
get serializableQuery(): any { return this.nonDefaultValues(new PrintersQuery()); }
get dto(): any { return { ...super.dto, orgUnitId: this.orgUnitId }; } }
/// printers-view-row.vue
const TerminalsView = defineComponent({ components: { TooltipIcon, V2Btn },
props: { value: { type: Object as PropType, required: true } },
setup(props, context) { const appState = inject(AppState.Key) as AppState; const stateMappings = ref(StateMappings.create(appState));
const icon = computed(() => { if (props.value.status.isUnknown) return "mdi-map-marker-question-outline"; if (props.value.status.isNoConnection) return "mdi-close-circle"; if (props.value.status.error) return "mdi-alert"; return "mdi-check"; }); const color = computed(() => { if (props.value.status.isUnknown) return "primary darken-2"; if (props.value.status.isNoConnection) return "error"; if (props.value.status.error) return "orange"; return "success"; }); return { stateMappings, icon, color, select: () => context.emit("select") };} });
export default TerminalsView;
/// printers-view.vue
<template v-for="(item, idx) in items"> <printers-view-row :key="idx" :value="item" @select="() => (selectedItem = item)" /> <v-divider v-if="idx < items.length - 1" :key="idx" class="my-2" /> </template>const TerminalsView = defineComponent({ components: { PrintersViewRow, SubmitButton, TooltipIcon, LoadingBar, OrganizationUnitSelector, PrinterStatusCard,
LoadingContainer},
props: {},
setup(props, context) { const router = ref(MedicaRouter.forContext(context)); const appState = inject(AppState.Key) as AppState; const stateMappings = ref(StateMappings.create(appState)); const items = ref([] as Printer[]); const isLoaded = ref(false); const isSearchLoading = ref(false); const query = ref(new PrintersQuery()); const selectedItem = ref(null as Terminal | null);
onMounted(async () => { router.value.getParams(query.value); await loadData(); }); const loadData = async () => { isLoaded.value = false; await executeSearch(); isLoaded.value = true; }; const setQueryParams = async () => { await router.value.setParams(query.value.serializableQuery); }; const prevPage = ref(1); watch( query, async (_1, _2) => { query.value.handleUpdate(prevPage, onSearchUpdate); if (isLoaded.value) await setQueryParams(); }, { deep: true } ); const executeSearch = async () => { const response = await axios.post("/api/services/app/Printers/Search", query.value.dto); items.value = response.data.result.map(Printer.fromDto); }; const refresh = async () => { const response = await axios.post( "/api/services/app/Printers/CheckAll", {}, { timeout: 240000 } ); items.value = response.data.result.map(Printer.fromDto); }; const searchDebounce = debounce(async () => { await executeSearch(); isSearchLoading.value = false; }, 500); const onSearchUpdate = () => { isSearchLoading.value = true; searchDebounce(); }; const allOrgUnits = computed(() => appState.orgUnits); const onCardClose = (needUpdate: boolean) => { selectedItem.value = null; if (needUpdate) onSearchUpdate(); }; return { items, query, refresh, allOrgUnits, isLoaded, isSearchLoading, onCardClose, stateMappings, selectedItem };} });
export default TerminalsView;
/// occupational-factor.ts
import { GenericNamedGuidEntity } from "@/views/commerce/common/named-item"; import OccupationalConfigItemType from "@/views/commerce/occupational-medicine/occupational-config-item-type"; import { OccupationalFactorValiditySetup } from "@/views/commerce/occupational-medicine/occupational-factor-validity-setup";
export class OccupationalFactor extends GenericNamedGuidEntity { category: number; surveyName: string; type: OccupationalConfigItemType = OccupationalConfigItemType.Factor; statementValiditySetup: OccupationalFactorValiditySetup = OccupationalFactorValiditySetup.empty(); options = 0;
get typeModel() { return this.type.id; }
set typeModel(val) { this.type = OccupationalConfigItemType.getById(val); }
public static fromDto(dto: any): OccupationalFactor { const entity = new OccupationalFactor(); entity.readDto(dto); return entity; }
public static empty(category: number): OccupationalFactor { const entity = new OccupationalFactor(); entity.category = category;
return entity;}
protected readDto(dto: any) { super.readDto(dto); this.type = OccupationalConfigItemType.getById(dto.type); this.category = dto.category; this.options = dto.options; this.surveyName = dto.surveyName || dto.name; this.statementValiditySetup = dto.statementValiditySetup ? OccupationalFactorValiditySetup.fromDto(dto.statementValiditySetup) : OccupationalFactorValiditySetup.empty(); }
public get dto(): any { return { ...super.dto, type: this.type.id, category: this.category, options: this.options, surveyName: this.surveyName || this.name, statementValiditySetup: this.statementValiditySetup.dto }; } }
/// occupational-factor-query.ts
import { PagedTextQuery } from "@/views/commerce/common/paged-text-query";
export class OccupationalFactorQuery extends PagedTextQuery { category: number | null = null;
get serializableQuery(): any { return this.nonDefaultValues(new OccupationalFactorQuery()); }
get dto(): any { return { ...super.dto, category: this.category }; } }
/// occupational-factor-row.vue
<v-col cols="auto" class="pt-2"> <edit-async-delete-buttons :readonly="readonly" :delete-action="onDelete" @select="select" /> </v-col>const OccupationalFactorRow = defineComponent({ components: { EditAsyncDeleteButtons, InlineIcon, TooltipIcon, SubmitButton }, props: { value: { type: Object as PropType, required: true }, readonly: { type: Boolean, required: false, default: false } },
emits: ["update", "select"],
setup(props, context) { const appState = inject(AppState.Key) as AppState; const stateMappings = ref(StateMappings.create(appState));
const onDelete = async () => { await axios.delete("/api/services/app/OccupationalMedicine/DeleteFactor", { params: { id: props.value.id } }); context.emit("update"); }; return { stateMappings, onDelete, trim: TextUtils.trim, select: () => context.emit("select") };} });
export default OccupationalFactorRow;
- Assistant
Aby dodać pełną funkcjonalność CRUD do modułu drukarek (
printer), wykorzystując istniejące wzorce z modułuoccupational-factor, należy zmodyfikować istniejące pliki oraz dodać nowe komponenty. Poniżej przedstawiam pełną treść plików, które powinny zostać zmodyfikowane lub utworzone.1.
printer.tsnRozszerzamy klasę
Printer, aby jejdtozawierała wszystkie niezbędne pola potrzebne do operacji Create i Update./// printer.tsn import { GenericEntity } from "@/views/commerce/common/named-item"; import PrinterStatus from "@/views/commerce/printers/printer-status"; import PrinterTarget from "@/views/commerce/printers/printer-target"; import type { SelectPanelOption } from "@/components/action-buttons/select-panel-option"; export default class Printer extends GenericEntity implements SelectPanelOption { id: string; orgUnitId: number; name: string | null; target: PrinterTarget = PrinterTarget.instance.reception; status: PrinterStatus = PrinterStatus.empty(); public static fromDto(dto: any): Printer { const entity = new Printer(); entity.readDto(dto); return entity; } protected readDto(dto: any) { super.readDto(dto); this.id = dto.id; this.orgUnitId = dto.orgUnitId; this.name = dto.name; this.target = PrinterTarget.getById(dto.target); this.status = dto.status ? PrinterStatus.fromDto(dto.status) : PrinterStatus.empty(); } get displayName() { if (this.name) return `${this.name} (${this.id})`; return this.id; } get dto(): any { return { id: this.id, orgUnitId: this.orgUnitId, name: this.name, target: this.target.id, // Zakładamy, że PrinterTarget posiada pole 'id' status: this.status.dto // Zakładamy, że PrinterStatus posiada getter 'dto' }; } }2.
printers-service.tsTworzymy serwis odpowiedzialny za komunikację z API w celu obsługi operacji CRUD dla drukarek.
/// printers-service.ts import axios from "@/lib/axios"; import Printer from "@/views/commerce/printers/printer"; const API_BASE = "/api/services/app/Printers"; export class PrintersService { static async createPrinter(printer: Printer): Promise<Printer> { const response = await axios.post(`${API_BASE}/Create`, printer.dto); return Printer.fromDto(response.data.result); } static async updatePrinter(printer: Printer): Promise<Printer> { const response = await axios.put(`${API_BASE}/Update`, printer.dto); return Printer.fromDto(response.data.result); } static async deletePrinter(id: string): Promise<void> { await axios.delete(`${API_BASE}/Delete`, { params: { id } }); } static async getPrinter(id: string): Promise<Printer> { const response = await axios.get(`${API_BASE}/Get`, { params: { id } }); return Printer.fromDto(response.data.result); } static async searchPrinters(query: any): Promise<Printer[]> { const response = await axios.post(`${API_BASE}/Search`, query); return response.data.result.map((dto: any) => Printer.fromDto(dto)); } static async checkAllPrinters(): Promise<Printer[]> { const response = await axios.post(`${API_BASE}/CheckAll`, {}); return response.data.result.map((dto: any) => Printer.fromDto(dto)); } }3.
printers-view-row.vueModyfikujemy komponent wyświetlający pojedynczy wiersz drukarki, dodając przyciski Edit i Delete.
/// printers-view-row.vue <template> <v-row align="center"> <v-col> <v-row dense> <v-col cols="auto"> <span :class="{ 'text-body-2': true, 'text--bold': true }" v-text="value.displayName"></span> </v-col> <v-col cols="auto"> <span :class="{ 'text-body-2': true }"> <v-icon small class="mr-1">mdi-map-marker</v-icon> {{ stateMappings.orgUnitName(value.orgUnitId) }} </span> </v-col> </v-row> </v-col> <v-col cols="auto"> <span v-if="value.status.serialNumber" class="text-body-2 primary--text text--darken-2"> {{ value.status.serialNumber }} </span> </v-col> <v-col cols="auto"> <div class="text-body-2" style="min-width: 100px" v-text="value.target.name"></div> </v-col> <v-col cols="auto"> <tooltip-icon :icon="icon" :color="color" :tooltip="value.status.error" :show-tooltip="value.status.error" /> </v-col> <v-col cols="auto"> <v2-btn color="primary" small @click="view"> <v-icon>mdi-eye</v-icon> </v2-btn> <edit-async-delete-buttons :readonly="false" :edit-action="onEdit" :delete-action="onDelete" @select="select" /> </v-col> </v-row> </template> <script lang="ts"> import type { PropType } from "@vue/composition-api"; import { defineComponent, inject, ref } from "@vue/composition-api"; import AppState from "@/views/main-wrap/app-state"; import StateMappings from "@/views/main-wrap/state-mappings"; import type Printer from "@/views/commerce/printers/printer"; import V2Btn from "@/compatibility-layer/components/v2-btn.vue"; import TooltipIcon from "@/components/simple/tooltip-icon.vue"; import EditAsyncDeleteButtons from "@/components/action-buttons/edit-async-delete-buttons.vue"; const PrintersViewRow = defineComponent({ components: { TooltipIcon, V2Btn, EditAsyncDeleteButtons }, props: { value: { type: Object as PropType<Printer>, required: true } }, emits: ["select", "edit", "delete"], setup(props, context) { const appState = inject(AppState.Key) as AppState; const stateMappings = ref(StateMappings.create(appState)); const icon = ref("mdi-check"); // Można dostosować logikę ikony w zależności od statusu const color = ref("success"); // Można dostosować logikę koloru w zależności od statusu const onDelete = async () => { context.emit("delete", props.value); }; const onEdit = () => { context.emit("edit", props.value); }; const view = () => { context.emit("select"); }; return { stateMappings, icon, color, onDelete, onEdit, view }; } }); export default PrintersViewRow; </script>4.
printer-form.vueTworzymy komponent formularza służącego do tworzenia i edycji drukarek.
/// printer-form.vue <template> <v-dialog v-model="isDialogOpen" max-width="500px" persistent> <v-card> <v-card-title> <span class="headline">{{ isEditMode ? 'Edytuj Drukarkę' : 'Utwórz Drukarkę' }}</span> </v-card-title> <v-card-text> <v-form ref="form" v-model="isValid"> <v-text-field label="ID Drukarki" v-model="printer.id" :disabled="isEditMode" required /> <v-text-field label="Nazwa" v-model="printer.name" required /> <organization-unit-selector v-model="printer.orgUnitId" required /> <v-select :items="printerTargets" label="Cel" v-model="printer.target" item-text="name" item-value="id" required /> <!-- Dodaj inne pola zgodnie z potrzebami --> </v-form> </v-card-text> <v-card-actions> <v-spacer /> <v-btn color="blue darken-1" text @click="close">Anuluj</v-btn> <v-btn :disabled="!isValid" color="blue darken-1" text @click="submit"> {{ isEditMode ? 'Zapisz' : 'Utwórz' }} </v-btn> </v-card-actions> </v-card> </v-dialog> </template> <script lang="ts"> import { defineComponent, ref, watch } from "@vue/composition-api"; import Printer from "@/views/commerce/printers/printer"; import { PrintersService } from "@/views/commerce/printers/printers-service"; import OrganizationUnitSelector from "@/views/commerce/common/selectors/organization-unit-selector.vue"; import PrinterTarget from "@/views/commerce/printers/printer-target"; export default defineComponent({ components: { OrganizationUnitSelector }, props: { value: { type: Boolean, required: true }, editPrinter: { type: Object as () => Printer | null, default: null } }, emits: ["input", "success"], setup(props, context) { const isDialogOpen = ref(props.value); const isValid = ref(false); const form = ref<VForm | null>(null); const isEditMode = ref(false); const printer = ref<Printer>(new Printer()); const printerTargets = PrinterTarget.instance.getAll(); // Zakładamy metodę getAll() watch(() => props.editPrinter, (newVal) => { if (newVal) { isEditMode.value = true; printer.value = { ...newVal }; } else { isEditMode.value = false; printer.value = new Printer(); } }); watch(() => props.value, (newVal) => { isDialogOpen.value = newVal; }); const close = () => { isDialogOpen.value = false; context.emit("input", false); }; const submit = async () => { if (!isValid.value) return; try { if (isEditMode.value) { await PrintersService.updatePrinter(printer.value); } else { await PrintersService.createPrinter(printer.value); } context.emit("success"); close(); } catch (error) { // Obsługa błędów console.error("Błąd podczas zapisywania drukarki", error); } }; return { isDialogOpen, isValid, form, printer, isEditMode, printerTargets, close, submit }; } }); </script>5.
printers-view.vueModyfikujemy główny komponent widoku drukarek, dodając przycisk tworzenia drukarki oraz obsługując otwieranie formularza do tworzenia i edycji.
/// printers-view.vue <template> <loading-container :is-loaded="isLoaded" fluid class="ma-0 pa-0"> <!-- Overlay do wyświetlania statusu drukarki --> <v-overlay v-if="selectedItem" z-index="20" :dark="false"> <printer-status-card :value="selectedItem" @close="onCardClose" /> </v-overlay> <!-- Overlay do formularza tworzenia/edycji drukarki --> <v-overlay v-if="isFormOpen" z-index="30" :dark="false"> <printer-form :value="isFormOpen" :edit-printer="currentPrinter" @input="isFormOpen = $event" @success="onFormSuccess" /> </v-overlay> <!-- Górny pasek z selektorem jednostki organizacyjnej i przyciskami --> <v-row dense align="center" justify="space-between"> <v-col cols="4"> <organization-unit-selector v-model="query.orgUnitId" /> </v-col> <v-col cols="auto"> <v-btn color="primary" @click="openCreateForm"> <v-icon left>mdi-plus</v-icon> Utwórz Drukarkę </v-btn> </v-col> <v-col cols="auto"> <submit-button :action="refresh"> Odśwież </submit-button> </v-col> </v-row> <!-- Pasek ładowania podczas wyszukiwania --> <loading-bar :value="isSearchLoading" /> <!-- Lista drukarek --> <template v-for="(item, idx) in items" :key="`printer-${idx}`"> <printers-view-row :value="item" @select="() => (selectedItem = item)" @edit="openEditForm(item)" @delete="deletePrinter(item)" /> <v-divider v-if="idx < items.length - 1" class="my-2" /> </template> </loading-container> </template> <script lang="ts"> import { defineComponent, inject, onMounted, ref, watch, computed } from "@vue/composition-api"; import MedicaRouter from "@/views/main-wrap/medica-router"; import AppState from "@/views/main-wrap/app-state"; import LoadingContainer from "@/components/loading/loading-container.vue"; import StateMappings from "@/views/main-wrap/state-mappings"; import PrinterStatusCard from "@/views/commerce/printers/printer-status-card.vue"; import Printer from "@/views/commerce/printers/printer"; import { PrintersQuery } from "@/views/commerce/printers/printers-query"; import OrganizationUnitSelector from "@/views/commerce/common/selectors/organization-unit-selector.vue"; import LoadingBar from "@/components/simple/loading-bar.vue"; import TooltipIcon from "@/components/simple/tooltip-icon.vue"; import SubmitButton from "@/components/action-buttons/submit-button.vue"; import PrintersViewRow from "@/views/commerce/printers/printers-view-row.vue"; import { PrintersService } from "@/views/commerce/printers/printers-service"; import PrinterForm from "@/views/commerce/printers/printer-form.vue"; const PrintersView = defineComponent({ components: { PrintersViewRow, SubmitButton, TooltipIcon, LoadingBar, OrganizationUnitSelector, PrinterStatusCard, LoadingContainer, PrinterForm }, setup() { const router = ref(MedicaRouter.forContext(this)); const appState = inject(AppState.Key) as AppState; const stateMappings = ref(StateMappings.create(appState)); const items = ref<Printer[]>([]); const isLoaded = ref(false); const isSearchLoading = ref(false); const query = ref(new PrintersQuery()); const selectedItem = ref<Printer | null>(null); const isFormOpen = ref(false); const currentPrinter = ref<Printer | null>(null); onMounted(async () => { router.value.getParams(query.value); await loadData(); }); const loadData = async () => { isLoaded.value = false; await executeSearch(); isLoaded.value = true; }; const setQueryParams = async () => { await router.value.setParams(query.value.serializableQuery); }; const prevPage = ref(1); watch( () => query.value, async (_new, _old) => { query.value.handleUpdate(prevPage, onSearchUpdate); if (isLoaded.value) await setQueryParams(); }, { deep: true } ); const executeSearch = async () => { try { isSearchLoading.value = true; items.value = await PrintersService.searchPrinters(query.value.dto); } catch (error) { console.error("Błąd podczas wyszukiwania drukarek", error); } finally { isSearchLoading.value = false; } }; const refresh = async () => { try { isSearchLoading.value = true; items.value = await PrintersService.checkAllPrinters(); } catch (error) { console.error("Błąd podczas odświeżania drukarek", error); } finally { isSearchLoading.value = false; } }; const onSearchUpdate = () => { executeSearch(); }; const allOrgUnits = computed(() => appState.orgUnits); const onCardClose = (needUpdate: boolean) => { selectedItem.value = null; if (needUpdate) onSearchUpdate(); }; const openCreateForm = () => { currentPrinter.value = null; isFormOpen.value = true; }; const openEditForm = (printer: Printer) => { currentPrinter.value = printer; isFormOpen.value = true; }; const onFormSuccess = () => { loadData(); }; const deletePrinter = async (printer: Printer) => { if (confirm(`Czy na pewno chcesz usunąć drukarkę: ${printer.displayName}?`)) { try { await PrintersService.deletePrinter(printer.id); loadData(); } catch (error) { console.error("Błąd podczas usuwania drukarki:", error); } } }; return { items, query, refresh, allOrgUnits, isLoaded, isSearchLoading, onCardClose, stateMappings, selectedItem, isFormOpen, openCreateForm, openEditForm, onFormSuccess, deletePrinter }; } }); export default PrintersView; </script>6.
edit-async-delete-buttons.vue(jeśli nie istnieje)Jeśli komponent
edit-async-delete-buttonsnie istnieje, należy go utworzyć. Poniżej przykładowa implementacja:/// edit-async-delete-buttons.vue <template> <div> <v-btn icon @click="edit"> <v-icon>mdi-pencil</v-icon> </v-btn> <v-btn icon @click="deleteItem"> <v-icon color="red">mdi-delete</v-icon> </v-btn> </div> </template> <script lang="ts"> import { defineComponent } from "@vue/composition-api"; export default defineComponent({ props: { readonly: { type: Boolean, default: false }, editAction: { type: Function, required: false }, deleteAction: { type: Function, required: false } }, emits: ["select"], setup(props, context) { const edit = () => { if (props.editAction) { props.editAction(); } }; const deleteItem = () => { if (props.deleteAction) { props.deleteAction(); } }; return { edit, deleteItem }; } }); </script>Uwaga: Jeśli już posiadasz taki komponent, upewnij się, że ma on odpowiednie emisje zdarzeń (
editidelete) oraz odpowiednie propsy.Podsumowanie
Powyższe zmiany i dodatki pozwolą na pełną obsługę operacji CRUD dla modułu
printer, zachowując jednocześnie istniejącą funkcjonalność. Upewnij się, że odpowiednie metody API są dostępne po stronie serwera i że wszystkie komponenty są prawidłowo zaimportowane oraz zarejestrowane w Twoim projekcie.