ff-admin/src/stores/admin/user.ts

110 lines
3.4 KiB
TypeScript

import { defineStore } from "pinia";
import type { CreateOrUpdateUserViewModel, UserViewModel } from "../../viewmodels/admin/user.models";
import { http } from "../../serverCom";
import type { PermissionObject } from "../../types/permissionTypes";
export const useUserStore = defineStore("user", {
state: () => {
return {
users: [] as Array<UserViewModel>,
user: null as null | UserViewModel,
loadingAll: "loading" as "loading" | "fetched" | "failed",
loadingSingle: "loading" as "loading" | "fetched" | "failed",
createStatus: null as null | "loading" | { status: "success" | "failed"; reason?: string },
updateStatus: null as null | "loading" | { status: "success" | "failed"; reason?: string },
deleteStatus: null as null | "loading" | { status: "success" | "failed"; reason?: string },
};
},
actions: {
resetStatus() {
this.createStatus = null;
this.updateStatus = null;
this.deleteStatus = null;
},
fetchUsers() {
this.loadingAll = "loading";
http
.get("/admin/user")
.then((result) => {
this.users = result.data;
this.loadingAll = "fetched";
})
.catch((err) => {
this.loadingAll = "failed";
});
},
fetchUserById(id: number) {
this.user = null;
this.loadingSingle = "loading";
http
.get(`/admin/user/${id}`)
.then((result) => {
this.user = result.data;
this.loadingSingle = "fetched";
})
.catch((err) => {
this.loadingSingle = "failed";
});
},
updateActiveUser(user: CreateOrUpdateUserViewModel) {
if (this.user == null) return;
this.updateStatus = "loading";
http
.patch(`/admin/user/${this.user.id}`, {
username: user.username,
firstname: user.firstname,
lastname: user.lastname,
mail: user.mail,
})
.then((result) => {
this.updateStatus = { status: "success" };
this.fetchUsers();
})
.catch((err) => {
this.updateStatus = { status: "failed" };
});
},
updateActiveUserPermissions(permission: PermissionObject) {
if (this.user == null) return;
this.updateStatus = "loading";
http
.patch(`/admin/user/${this.user.id}/permissions`, {
permissions: permission,
})
.then((result) => {
this.updateStatus = { status: "success" };
this.fetchUsers();
})
.catch((err) => {
this.updateStatus = { status: "failed" };
});
},
updateActiveUserRoles(roles: Array<number>) {
if (this.user == null) return;
this.updateStatus = "loading";
http
.patch(`/admin/user/${this.user.id}/roles`, {
roleIds: roles,
})
.then((result) => {
this.updateStatus = { status: "success" };
this.fetchUsers();
})
.catch((err) => {
this.updateStatus = { status: "failed" };
});
},
deleteUser(user: number) {
this.deleteStatus = "loading";
http
.delete(`/admin/user/${user}`)
.then((res) => {
this.deleteStatus = { status: "success" };
this.fetchUsers();
})
.catch((err) => {
this.deleteStatus = { status: "failed", reason: err.data };
});
},
},
});