update: auth & update modal

This commit is contained in:
2023-01-30 17:48:28 +01:00
parent ef72c5f129
commit 07e7995ad5
8 changed files with 880 additions and 753 deletions
+49 -8
View File
@@ -5,16 +5,34 @@
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { computed, defineComponent, watch } from 'vue';
import dataMixin from './mixins/dataMixin';
import { useStore } from './store';
import PopUpCard from './components/PopUpCard.vue';
import axios, { AxiosResponse } from 'axios';
import { RouterView, useRouter } from 'vue-router';
import { ILoginResponse, IUser, AuthState } from './types/types';
export default defineComponent({
mixins: [dataMixin],
components: { PopUpCard },
setup() {
const store = useStore();
const router = useRouter();
router.beforeEach(async (to, from, next) => {
if (store.authState != AuthState.AUTHORIZED && to.path != '/login') return next({ path: '/login' });
return next();
});
watch(
computed(() => store.authState),
(state) => {
if (router.currentRoute.value.path == '/login' && state == AuthState.AUTHORIZED) router.push('/');
}
);
return {
store,
};
@@ -22,15 +40,36 @@ export default defineComponent({
methods: {
async autoLogin() {
const token = window.localStorage.getItem('auth-token');
if (token) {
this.store.isAuthorized = true;
this.store.token = token;
this.store.user = JSON.parse(window.localStorage.getItem('user')!);
if (!token) {
this.store.authState = AuthState.UNAUTHORIZED;
return;
}
this.store.token = token;
const data = axios.post<{ user: IUser }>(`${this.API_URL}/auth/token`, { token: this.store.token });
data
.then((res) => {
console.log(res.data);
this.store.user = res.data.user;
this.store.authState = AuthState.AUTHORIZED;
this.$router.push('/');
})
.catch((err) => {
this.store.isAuthorized = false;
window.localStorage.removeItem('auth-token');
this.store.authState = AuthState.UNAUTHORIZED;
this.$router.push('/login');
});
},
},
mounted() {
this.autoLogin();
if (window.localStorage.getItem('notifyDiscord') !== null) {
this.store.notifyDiscord = Boolean(Number(window.localStorage.getItem('notifyDiscord')));
}
@@ -97,13 +136,15 @@ button:focus-visible {
transform: translate(-50%, -50%);
width: 90vw;
max-width: 350px;
max-width: 550px;
padding: 0.5em 1em;
margin-top: 1em;
background-color: #2e2e2e;
box-shadow: 0 0 6px 1px #131313;
border-radius: 1em;
background-color: #1d1c33;
box-shadow: 0 0 6px 1px #414141;
}
// Scrollbar
+340 -341
View File
@@ -1,341 +1,340 @@
<template>
<div class="table-actions">
<div class="pane info-pane">
<div>
<span v-if="store.user">
Zalogowany jako <b>{{ store.user.name }}</b>
</span>
&bull;
<span class="info-file" :class="store.dataState">
<span v-if="store.dataState == 'LOADING'">Ładowanie danych...</span>
<span v-if="store.dataState == 'LOADED'">Załadowano dane z bazy!</span>
<span v-if="store.dataState == 'ERROR'">Błąd podczas pobierania danych!</span>
</span>
//
<span class="file-changes" style="color: salmon" v-if="store.unsavedChanges">Niezapisane zmiany!</span>
<span class="file-changes" style="color: #aaa" v-else>Brak niezapisanych zmian</span>
</div>
</div>
<div class="pane actions-pane">
<button @click="addNewStation">Dodaj nową stację</button>
<button @click="confirmLoadData">Odśwież dane</button>
&nbsp;
<button @click="confirmUpdateList" :data-disabled="!store.unsavedChanges" :disabled="!store.unsavedChanges">
Zapisz zmiany
</button>
<button @click="signOut">Wyloguj się</button>
</div>
<div class="pane notify-pane">
<label id="notify">
<input
type="checkbox"
v-model="store.notifyDiscord"
@input="onNotifyCheckboxChange(($event.target as HTMLInputElement)!.checked)"
/>
<span>
Powiadom o zmianach: <b>{{ store.notifyDiscord ? 'TAK' : 'NIE' }}</b>
</span>
</label>
</div>
<div class="pane search-pane">
<input
class="search"
ref="search"
type="text"
v-model="store.searchedSceneryName"
placeholder="Wpisz nazwę scenerii..."
width="350"
/>
<button style="margin-left: 0.5em" @click="clearInput">Wyczyść</button>
</div>
<div class="pane">
<button @click="changelogVisible = !changelogVisible">
{{ changelogVisible ? 'Ukryj' : 'Pokaż' }} changelog
</button>
</div>
<div class="changelog" v-if="changelogVisible">
<div style="margin-bottom: 0.25em">Changelog:</div>
<div v-html="changelog || 'brak zmian'"></div>
</div>
</div>
</template>
<script lang="ts">
import axios from 'axios';
import { defineComponent } from 'vue';
import dataMixin from '../mixins/dataMixin';
import routesMixin from '../mixins/routesMixin';
import { useStore } from '../store';
import { Availability, ChangeProp, HeaderTypes, SceneryRowItem } from '../types/types';
import { getAvailabilityValue } from '../types/typeUitls';
export default defineComponent({
setup() {
return {
store: useStore(),
};
},
data() {
return {
changelogVisible: false,
};
},
mixins: [dataMixin, routesMixin],
computed: {
changelog() {
return this.store.changeList
.map((changeItem) => {
let itemChanges = [];
if (changeItem.toRemove) return `<b class='text--accent'>${changeItem.name} -></b> do usunięcia`;
for (let change in changeItem) {
let propChange = change as ChangeProp;
if (/id|name/.test(propChange)) continue;
let value =
typeof changeItem[propChange] === 'boolean'
? changeItem[propChange]
? 'TAK'
: 'NIE'
: changeItem[propChange];
if (propChange == 'availability') value = getAvailabilityValue(changeItem[propChange] as Availability);
if (propChange == 'routes') value = this.getRouteNames(changeItem[propChange] as string);
itemChanges.push(`<i>${(HeaderTypes as any)[propChange]}:</i> ${value || '-'}`);
}
return `<b class='text--accent'>${changeItem.name} -></b> ` + itemChanges.join('; ');
})
.join(' <br /> ');
},
},
methods: {
confirmLoadData() {
const confirmed = confirm('Czy na pewno chcesz odświeżyć dane? Wszelkie niezapisane zmiany zostaną utracone!');
if (confirmed) this.loadData();
},
confirmRestoreList() {
const confirmed = confirm(
'Czy na pewno chcesz zresetować listę do ustawień z pliku? Wszelkie niezapisane zmiany zostaną utracone!'
);
if (confirmed) this.restoreList();
},
confirmUpdateList() {
const confirmed = confirm('Czy na pewno chcesz wprowadzić obecne zmiany?');
if (confirmed) this.updateListToDb();
},
signOut() {
this.store.token = null;
this.store.isAuthorized = false;
window.localStorage.removeItem('auth-token');
window.localStorage.removeItem('user');
this.$router.push('/login');
},
onNotifyCheckboxChange(value: boolean) {
window.localStorage.setItem('notifyDiscord', Number(value).toString());
},
async updateListToDb() {
try {
const mappedChangeList = this.store.changeList.map((v) => {
if (/^#/.test(v.id)) {
return { ...v, id: undefined };
}
return { ...v };
});
const response = await axios.post(
`${this.API_URL}/manager/updateSceneryList`,
{
changeList: mappedChangeList,
token: this.store.token,
notify: this.store.notifyDiscord,
},
{
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${this.store.token}`,
},
}
);
this.store.changesResponse = response.data;
alert('Pomyślnie wprowadzono zmiany!');
this.loadData();
} catch (error) {
this.store.alertMessage = 'Ups! Wystąpił błąd podczas zapisywania danych!';
}
},
addNewStation() {
const name = prompt('Nazwa nowej scenerii');
if (!name) return;
if (
this.store.stationList.some(
(station) => station.name.toLocaleLowerCase('pl-PL') == name.toLocaleLowerCase('pl-PL')
)
) {
this.store.alertMessage = 'Sceneria o takiej nazwie już istnieje!';
return;
}
this.store.newStationsCount++;
const newSt: SceneryRowItem = {
name,
url: '',
lines: '',
project: null,
reqLevel: -1,
signalType: 'współczesna',
controlType: 'SCS',
SUP: false,
routes: 'Test_1EPB"',
checkpoints: '',
authors: '',
availability: 'default',
id: `#${Math.random().toString(32).substring(2)}`,
};
this.store.changeList.push({ ...newSt });
// this.store.changeBackupList[newSt.id] = null;
this.store.searchedSceneryName = name;
this.store.unsavedChanges = true;
this.store.stationList.unshift(newSt);
},
restoreList() {
if (this.store.backupList.length == 0) return;
this.store.stationList = JSON.parse(JSON.stringify(this.store.backupList));
this.store.changeList = [];
this.store.stationsToRemove = [];
this.store.unsavedChanges = false;
this.store.searchedSceneryName = '';
},
clearInput() {
this.store.searchedSceneryName = '';
},
},
});
</script>
<style lang="scss" scoped>
button {
&[data-disabled='true'] {
user-select: none;
-moz-user-select: none;
-webkit-user-select: none;
color: #999;
}
}
.info-file {
color: greenyellow;
}
.info-file.LOADING {
color: #aaa;
}
.info-file.ERROR {
color: salmon;
}
#notify-checkbox:checked + label {
color: gold;
}
.search {
color: black;
border: 1px solid white;
outline: none;
appearance: none;
padding: 0.35em 0.4em;
}
.pane {
display: flex;
flex-wrap: wrap;
align-items: center;
}
.actions-pane {
margin-top: 1em;
button {
margin: 0.5em 0.5em 0 0;
}
}
.notify-pane {
margin: 1em 0;
}
.search-pane {
margin-top: 0.5em;
}
label#notify {
cursor: pointer;
text-align: center;
color: #000;
span {
padding: 0.3em 0.25em;
background-color: salmon;
}
input {
display: none;
&:checked + span {
background-color: lightblue;
}
}
}
.changelog {
height: 200px;
overflow: auto;
}
@media screen and (max-width: 550px) {
.pane {
justify-content: center;
text-align: center;
}
}
</style>
<template>
<div class="table-actions">
<div class="pane info-pane">
<div>
<span v-if="store.user">
Zalogowany jako <b>{{ store.user.name }}</b>
</span>
&bull;
<span class="info-file" :class="store.dataState">
<span v-if="store.dataState == 'LOADING'">Ładowanie danych...</span>
<span v-if="store.dataState == 'LOADED'">Załadowano dane z bazy!</span>
<span v-if="store.dataState == 'ERROR'">Błąd podczas pobierania danych!</span>
</span>
//
<span class="file-changes" style="color: salmon" v-if="store.unsavedChanges">Niezapisane zmiany!</span>
<span class="file-changes" style="color: #aaa" v-else>Brak niezapisanych zmian</span>
</div>
</div>
<div class="pane actions-pane">
<button @click="addNewStation">Dodaj nową stację</button>
<button @click="confirmLoadData">Odśwież dane</button>
&nbsp;
<button @click="confirmUpdateList" :data-disabled="!store.unsavedChanges" :disabled="!store.unsavedChanges">
Zapisz zmiany
</button>
<button @click="signOut">Wyloguj się</button>
</div>
<div class="pane notify-pane">
<label id="notify">
<input
type="checkbox"
v-model="store.notifyDiscord"
@input="onNotifyCheckboxChange(($event.target as HTMLInputElement)!.checked)"
/>
<span>
Powiadom o zmianach: <b>{{ store.notifyDiscord ? 'TAK' : 'NIE' }}</b>
</span>
</label>
</div>
<div class="pane search-pane">
<input
class="search"
ref="search"
type="text"
v-model="store.searchedSceneryName"
placeholder="Wpisz nazwę scenerii..."
width="350"
/>
<button style="margin-left: 0.5em" @click="clearInput">Wyczyść</button>
</div>
<div class="pane">
<button @click="changelogVisible = !changelogVisible">
{{ changelogVisible ? 'Ukryj' : 'Pokaż' }} changelog
</button>
</div>
<div class="changelog" v-if="changelogVisible">
<div style="margin-bottom: 0.25em">Changelog:</div>
<div v-html="changelog || 'brak zmian'"></div>
</div>
</div>
</template>
<script lang="ts">
import axios from 'axios';
import { defineComponent } from 'vue';
import dataMixin from '../mixins/dataMixin';
import routesMixin from '../mixins/routesMixin';
import { useStore } from '../store';
import { AuthState, Availability, ChangeProp, HeaderTypes, SceneryRowItem } from '../types/types';
import { getAvailabilityValue } from '../types/typeUitls';
export default defineComponent({
setup() {
return {
store: useStore(),
};
},
data() {
return {
changelogVisible: false,
};
},
mixins: [dataMixin, routesMixin],
computed: {
changelog() {
return this.store.changeList
.map((changeItem) => {
let itemChanges = [];
if (changeItem.toRemove) return `<b class='text--accent'>${changeItem.name} -></b> do usunięcia`;
for (let change in changeItem) {
let propChange = change as ChangeProp;
if (/id|name/.test(propChange)) continue;
let value =
typeof changeItem[propChange] === 'boolean'
? changeItem[propChange]
? 'TAK'
: 'NIE'
: changeItem[propChange];
if (propChange == 'availability') value = getAvailabilityValue(changeItem[propChange] as Availability);
if (propChange == 'routes') value = this.getRouteNames(changeItem[propChange] as string);
itemChanges.push(`<i>${(HeaderTypes as any)[propChange]}:</i> ${value || '-'}`);
}
return `<b class='text--accent'>${changeItem.name} -></b> ` + itemChanges.join('; ');
})
.join(' <br /> ');
},
},
methods: {
confirmLoadData() {
const confirmed = confirm('Czy na pewno chcesz odświeżyć dane? Wszelkie niezapisane zmiany zostaną utracone!');
if (confirmed) this.loadData();
},
confirmRestoreList() {
const confirmed = confirm(
'Czy na pewno chcesz zresetować listę do ustawień z pliku? Wszelkie niezapisane zmiany zostaną utracone!'
);
if (confirmed) this.restoreList();
},
confirmUpdateList() {
const confirmed = confirm('Czy na pewno chcesz wprowadzić obecne zmiany?');
if (confirmed) this.updateListToDb();
},
signOut() {
this.store.token = null;
this.store.authState = AuthState.UNAUTHORIZED;
window.localStorage.removeItem('auth-token');
window.localStorage.removeItem('user');
this.$router.push('/login');
},
onNotifyCheckboxChange(value: boolean) {
window.localStorage.setItem('notifyDiscord', Number(value).toString());
},
async updateListToDb() {
try {
const mappedChangeList = this.store.changeList.map((v) => {
if (/^#/.test(v.id)) {
return { ...v, id: undefined };
}
return { ...v };
});
const response = await axios.post(
`${this.API_URL}/manager/updateSceneryList`,
{
changeList: mappedChangeList,
token: this.store.token,
notify: this.store.notifyDiscord,
},
{
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${this.store.token}`,
},
}
);
this.store.changesResponse = response.data;
this.loadData();
} catch (error) {
this.store.alertMessage = 'Ups! Wystąpił błąd podczas zapisywania danych!';
}
},
addNewStation() {
const name = prompt('Nazwa nowej scenerii');
if (!name) return;
if (
this.store.stationList.some(
(station) => station.name.toLocaleLowerCase('pl-PL') == name.toLocaleLowerCase('pl-PL')
)
) {
this.store.alertMessage = 'Sceneria o takiej nazwie już istnieje!';
return;
}
this.store.newStationsCount++;
const newSt: SceneryRowItem = {
name,
url: '',
lines: '',
project: null,
reqLevel: -1,
signalType: 'współczesna',
controlType: 'SCS',
SUP: false,
routes: 'Test_1EPB"',
checkpoints: '',
authors: '',
availability: 'default',
id: `#${Math.random().toString(32).substring(2)}`,
};
this.store.changeList.push({ ...newSt });
// this.store.changeBackupList[newSt.id] = null;
this.store.searchedSceneryName = name;
this.store.unsavedChanges = true;
this.store.stationList.unshift(newSt);
},
restoreList() {
if (this.store.backupList.length == 0) return;
this.store.stationList = JSON.parse(JSON.stringify(this.store.backupList));
this.store.changeList = [];
this.store.stationsToRemove = [];
this.store.unsavedChanges = false;
this.store.searchedSceneryName = '';
},
clearInput() {
this.store.searchedSceneryName = '';
},
},
});
</script>
<style lang="scss" scoped>
button {
&[data-disabled='true'] {
user-select: none;
-moz-user-select: none;
-webkit-user-select: none;
color: #999;
}
}
.info-file {
color: greenyellow;
}
.info-file.LOADING {
color: #aaa;
}
.info-file.ERROR {
color: salmon;
}
#notify-checkbox:checked + label {
color: gold;
}
.search {
color: black;
border: 1px solid white;
outline: none;
appearance: none;
padding: 0.35em 0.4em;
}
.pane {
display: flex;
flex-wrap: wrap;
align-items: center;
}
.actions-pane {
margin-top: 1em;
button {
margin: 0.5em 0.5em 0 0;
}
}
.notify-pane {
margin: 1em 0;
}
.search-pane {
margin-top: 0.5em;
}
label#notify {
cursor: pointer;
text-align: center;
color: #000;
span {
padding: 0.3em 0.25em;
background-color: salmon;
}
input {
display: none;
&:checked + span {
background-color: lightblue;
}
}
}
.changelog {
height: 200px;
overflow: auto;
}
@media screen and (max-width: 550px) {
.pane {
justify-content: center;
text-align: center;
}
}
</style>
+67
View File
@@ -0,0 +1,67 @@
<template>
<div class="bg-dimmer" @click="closeCard"></div>
<div class="g-card popup-card">
<div class="card_content">
<h1>Raport zmian</h1>
<p v-for="(ch, i) in changesResponseComp" :key="i" :style="{ color: ch.resolved ? 'lime' : 'crimson' }">
{{ ch.resolved ? `` : `` }} {{ ch.message }}
</p>
</div>
<div class="card_actions">
<button @click="closeCard">OK!</button>
</div>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { useStore } from '../store';
export default defineComponent({
setup() {
return {
store: useStore(),
};
},
computed: {
changesResponseComp() {
return this.store.changesResponse.map((ch) => ({
resolved: ch.split(' ')[0] == 'v',
message: ch.replace(/^[v|x] /, ''),
}));
},
},
methods: {
closeCard() {
this.store.changesResponse.length = 0;
},
},
});
</script>
<style lang="scss" scoped>
.bg-dimmer {
position: fixed;
z-index: 998;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background-color: #0000004f;
}
h1 {
text-align: center;
}
.card_actions {
display: flex;
justify-content: center;
}
</style>
+22 -32
View File
@@ -1,32 +1,22 @@
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
const routes: Array<RouteRecordRaw> = [
{
path: '/',
name: 'ManagerView',
component: () => import('./views/ManagerView.vue'),
},
{
path: '/login',
name: 'LoginView',
component: () => import('./views/LoginView.vue'),
},
];
const router = createRouter({
history: createWebHistory(),
routes,
});
router.beforeEach((to, from, next) => {
const token = window.localStorage.getItem('auth-token');
if (!token && to.path != '/login') return next({ path: '/login' });
if (token && to.path == '/login') return next({ path: '/' });
// else if (to.path == '/login') return next({ path: '/' });
return next();
});
export default router;
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
const routes: Array<RouteRecordRaw> = [
{
path: '/',
name: 'ManagerView',
component: () => import('./views/ManagerView.vue'),
},
{
path: '/login',
name: 'LoginView',
component: () => import('./views/LoginView.vue'),
},
];
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;
+31 -28
View File
@@ -1,28 +1,31 @@
import { defineStore } from 'pinia';
import { Availability, ChangeProp, HeaderTypes, IStore } from './types/types';
import { getAvailabilityValue } from './types/typeUitls';
export const useStore = defineStore('store', {
state: () =>
({
dataState: 'LOADING',
unsavedChanges: false,
stationList: [],
backupList: [],
stationsToRemove: [],
searchedSceneryName: '',
changeList: [],
newStationsCount: 0,
routesModalVisible: true,
currentStation: null,
selectedStationName: '',
token: null,
user: null,
isAuthorized: false,
notifyDiscord: true,
alertMessage: '',
confirmMessage: '',
changesResponse: [],
} as IStore),
});
import { defineStore } from 'pinia';
import { AuthState, Availability, ChangeProp, HeaderTypes, IStore } from './types/types';
import { getAvailabilityValue } from './types/typeUitls';
export const useStore = defineStore('store', {
state: () =>
({
dataState: 'LOADING',
authState: AuthState.LOADING,
unsavedChanges: false,
stationList: [],
backupList: [],
stationsToRemove: [],
searchedSceneryName: '',
changeList: [],
newStationsCount: 0,
routesModalVisible: true,
currentStation: null,
selectedStationName: '',
token: null,
user: null,
isAuthorized: false,
notifyDiscord: true,
alertMessage: '',
confirmMessage: '',
changesResponse: [],
} as IStore),
});
+103 -85
View File
@@ -1,85 +1,103 @@
export type Availability = 'default' | 'unavailable' | 'nonPublic' | 'abandoned' | 'nonDefault';
export type ChangeProp =
| 'name'
| 'url'
| 'lines'
| 'project'
| 'reqLevel'
| 'signalType'
| 'controlType'
| 'SUP'
| 'routes'
| 'checkpoints'
| 'authors'
| 'availability';
export enum HeaderTypes {
name = 'Nazwa',
url = 'URL',
lines = 'Linie',
project = 'Projekt',
reqLevel = 'Wym. poziom',
signalType = 'Sygnalizacja',
controlType = 'Sterowanie',
SUP = 'SUP',
authors = 'Autorzy',
routes = 'Szlaki',
checkpoints = 'Posterunki',
availability = 'Dostępność',
toRemove = 'Usuń',
}
export enum AvailabilityTypes {
'default' = 'w paczce',
'nonDefault' = 'poza paczką',
'nonPublic' = 'niepubliczna',
'abandoned' = 'wycofana',
'unavailable' = 'niedostępna',
}
export interface SceneryRowItem {
id: string;
name: string;
url: string;
lines: string;
project: string | null;
reqLevel: number;
signalType: string;
controlType: string;
SUP: boolean;
routes: string;
checkpoints: string;
authors: string;
availability: Availability;
}
export type ChangeItem = {
[key in ChangeProp]?: string | number | boolean | null;
} & {
id: string;
name: string;
toRemove?: boolean;
};
export interface IStore {
dataState: string;
unsavedChanges: boolean;
stationList: SceneryRowItem[];
backupList: SceneryRowItem[];
stationsToRemove: string[];
searchedSceneryName: string;
changeList: ChangeItem[];
newStationsCount: number;
routesModalVisible: boolean;
currentStation: SceneryRowItem | null;
selectedStationName: string;
token: string | null;
user: { name: string; id: string } | null;
isAuthorized: boolean;
notifyDiscord: boolean;
alertMessage: string;
confirmMessage: string;
changesResponse: string[];
}
export type Availability = 'default' | 'unavailable' | 'nonPublic' | 'abandoned' | 'nonDefault';
export type ChangeProp =
| 'name'
| 'url'
| 'lines'
| 'project'
| 'reqLevel'
| 'signalType'
| 'controlType'
| 'SUP'
| 'routes'
| 'checkpoints'
| 'authors'
| 'availability';
export enum HeaderTypes {
name = 'Nazwa',
url = 'URL',
lines = 'Linie',
project = 'Projekt',
reqLevel = 'Wym. poziom',
signalType = 'Sygnalizacja',
controlType = 'Sterowanie',
SUP = 'SUP',
authors = 'Autorzy',
routes = 'Szlaki',
checkpoints = 'Posterunki',
availability = 'Dostępność',
toRemove = 'Usuń',
}
export enum AvailabilityTypes {
'default' = 'w paczce',
'nonDefault' = 'poza paczką',
'nonPublic' = 'niepubliczna',
'abandoned' = 'wycofana',
'unavailable' = 'niedostępna',
}
export interface SceneryRowItem {
id: string;
name: string;
url: string;
lines: string;
project: string | null;
reqLevel: number;
signalType: string;
controlType: string;
SUP: boolean;
routes: string;
checkpoints: string;
authors: string;
availability: Availability;
}
export type ChangeItem = {
[key in ChangeProp]?: string | number | boolean | null;
} & {
id: string;
name: string;
toRemove?: boolean;
};
export enum AuthState {
'LOADING' = 0,
'AUTHORIZED' = 1,
'UNAUTHORIZED' = 2,
}
export interface IStore {
dataState: string;
authState: AuthState;
unsavedChanges: boolean;
stationList: SceneryRowItem[];
backupList: SceneryRowItem[];
stationsToRemove: string[];
searchedSceneryName: string;
changeList: ChangeItem[];
newStationsCount: number;
routesModalVisible: boolean;
currentStation: SceneryRowItem | null;
selectedStationName: string;
token: string | null;
user: { name: string; id: string } | null;
isAuthorized: boolean;
notifyDiscord: boolean;
alertMessage: string;
confirmMessage: string;
changesResponse: string[];
}
export interface ILoginResponse {
token: string;
user: IUser;
}
export interface IUser {
name: string;
id: string;
}
+18 -12
View File
@@ -1,5 +1,5 @@
<template>
<div class="login">
<div class="login" v-if="store.authState == AuthState.UNAUTHORIZED">
<div class="login-header">
<img src="/icon-logo.svg" alt="logo" />
<h1>Stacjownik Station Manager</h1>
@@ -14,7 +14,7 @@
<br />
<input type="password" id="password" v-model="password" />
<br />
<button>Zaloguj</button>
<button>{{ loginState == LoginState.LOADING ? 'Logowanie...' : 'Zaloguj się' }}</button>
</form>
</div>
</template>
@@ -24,13 +24,12 @@ import axios from 'axios';
import { defineComponent } from 'vue';
import dataMixin from '../mixins/dataMixin';
import { useStore } from '../store';
import { AuthState, ILoginResponse } from '../types/types';
interface LoginResponse {
token: string;
user: {
name: string;
id: string;
};
enum LoginState {
INITIALIZED = 0,
LOADING = 1,
LOADED = 2,
}
export default defineComponent({
@@ -40,18 +39,20 @@ export default defineComponent({
return {
name: '',
password: '',
loginState: LoginState.INITIALIZED,
LoginState,
store: useStore(),
AuthState,
};
},
methods: {
async signIn(e: Event) {
e.preventDefault();
console.log(import.meta.env.VITE_API_URL);
this.loginState = LoginState.LOADING;
try {
const data: LoginResponse = (
const data: ILoginResponse = (
await axios.post(
`${this.API_URL}/auth/login`,
{ username: this.name, password: this.password },
@@ -63,7 +64,9 @@ export default defineComponent({
)
).data;
this.store.isAuthorized = true;
this.store.authState = AuthState.AUTHORIZED;
this.loginState = LoginState.LOADED;
this.store.token = data.token;
this.store.user = data.user;
@@ -73,6 +76,9 @@ export default defineComponent({
this.loadData();
this.$router.push('/');
} catch (e: any) {
this.store.authState = AuthState.UNAUTHORIZED;
this.loginState = LoginState.LOADED;
if (!e.response || e.response.status === undefined) {
this.store.alertMessage = 'Wystąpił błąd podczas łączenia z serwerem!';
return;
+250 -247
View File
@@ -1,247 +1,250 @@
<template>
<div class="manager">
<RoutesModal v-if="store.currentStation" />
<hr color="white" />
<TableActions />
<hr color="white" />
<div class="table_container">
<table>
<thead>
<th v-for="header in headerNameList">{{ header }}</th>
<th>Dostępność</th>
<th>Usuń</th>
</thead>
<tbody>
<tr v-for="(station, row) in sortedStationList" tabindex="0">
<td v-for="(value, propName) in headerNameList" @click="changeProperty(station, row, propName as string)">
<span v-if="propName === 'url'" :style="station.url ? 'color: gold' : 'color: gray;'">URL</span>
<span v-else-if="propName === 'checkpoints'">{{ station[propName] ? 'POKAŻ' : 'DODAJ' }}</span>
<span v-else-if="propName === 'routes'" v-html="getRouteNames(station.routes)"></span>
<span v-else-if="propName === 'signalType'"> {{ station[propName] }}</span>
<span v-else-if="typeof (station as any)[propName] === 'boolean'">
{{ (station as any)[propName] ? '' : '' }}
</span>
<span v-else>{{ (station as any)[propName] }}</span>
</td>
<td>
<select
name="availability"
:id="`select-${row}`"
v-model="sortedStationList[row]['availability']"
@input="(e) => changeAvailability(station, sortedStationList[row]['availability'], e)"
>
<option value="default">dostępna (w paczce)</option>
<option value="nonDefault">dostępna (poza paczką)</option>
<option value="unavailable">niedostępna</option>
<option value="nonPublic">niepubliczna</option>
<option value="abandoned">wycofana</option>
</select>
</td>
<td @click="removeStation(station)"><img src="/icon-trash.svg" alt="remove" /></td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import changeMixin from '../mixins/changeMixin';
import dataMixin from '../mixins/dataMixin';
import { useStore } from '../store';
import { SceneryRowItem, Availability } from '../types/types';
import RoutesModal from '../components/RoutesModal.vue';
import TableActions from '../components/TableActions.vue';
import routesMixin from '../mixins/routesMixin';
export default defineComponent({
components: { RoutesModal, TableActions },
mixins: [dataMixin, changeMixin, routesMixin],
data: () => ({
headerNameList: {
name: 'Nazwa',
url: 'URL',
lines: 'Linie',
project: 'Projekt',
reqLevel: 'Wym. poziom',
signalType: 'Sygnalizacja',
controlType: 'Sterowanie',
SUP: 'SUP',
authors: 'Autorzy',
routes: 'Szlaki',
checkpoints: 'Posterunki',
} as {
[key: string]: string;
},
}),
setup() {
const store = useStore();
return {
store,
};
},
mounted() {
this.loadData();
},
computed: {
sortedStationList() {
const sortedList = this.store.stationList.sort((a, b) => (a.name > b.name ? 1 : -1));
if (!this.store.searchedSceneryName || this.store.searchedSceneryName == '') return sortedList;
return sortedList.filter((station) =>
station.name.toLowerCase().startsWith(this.store.searchedSceneryName.toLowerCase())
);
},
},
methods: {
changeProperty(station: SceneryRowItem, row: number, propertyName: string) {
this.store.selectedStationName = station.name;
if (propertyName == 'checkpoints') {
this.changeCheckpoints(row);
return;
}
if (propertyName == 'routes') {
this.showRoutesModal(station);
return;
}
const stationListRow = this.store.stationList.findIndex(
(station) => station.name == this.sortedStationList[row].name
);
if (stationListRow == -1) return;
const oldValue = (this.store.stationList[stationListRow] as any)[propertyName];
if (typeof oldValue === 'boolean') {
(this.store.stationList[stationListRow] as any)[propertyName] = !oldValue;
// this.$set(this.stationList[stationListRow], propertyName, !oldValue);
this.addChange(station, propertyName, oldValue, !oldValue);
return;
}
let newValue = prompt(`Zmień wartość dla rubryki ${this.headerNameList[propertyName]}`, oldValue);
if (newValue == null) return;
(this.store.stationList[stationListRow] as any)[propertyName] =
typeof oldValue === 'number' ? parseInt(newValue) : newValue;
// this.$set(this.stationList[stationListRow], propertyName, parseInt(newValue));
this.addChange(station, propertyName, oldValue, typeof oldValue === 'number' ? parseInt(newValue) : newValue);
},
changeCheckpoints(row: number) {
const stationListRow = this.store.stationList.findIndex(
(station) => station.name == this.sortedStationList[row].name
);
if (stationListRow == -1) return;
const oldCheckpoints = this.store.stationList[stationListRow].checkpoints;
const newCheckpoints = prompt('Wpisz posterunki (oddzielone średnikiem):', oldCheckpoints);
if (newCheckpoints === null) return;
this.store.stationList[stationListRow]['checkpoints'] = newCheckpoints;
this.addChange(this.sortedStationList[row], 'checkpoints', oldCheckpoints, newCheckpoints);
},
changeAvailability(scenery: SceneryRowItem, availability: Availability, e: Event) {
const selectedAvailability: Availability = (e.target as HTMLSelectElement).value as Availability;
this.addChange(scenery, 'availability', availability, selectedAvailability);
},
removeStation(scenery: SceneryRowItem) {
const confirmRemove = confirm('Czy na pewno chcesz zaznaczyć tę scenerię do usunięcia?');
if (!confirmRemove) return;
this.store.stationList = this.store.stationList.filter(({ id }) => id != scenery.id);
this.addRemovalChange(scenery);
},
showRoutesModal(scenery: SceneryRowItem) {
this.store.currentStation = scenery;
},
},
});
</script>
<style lang="scss" scoped>
.table_container {
overflow: auto;
height: 100vh;
margin: 0.5em 0;
}
table {
text-align: center;
color: white;
position: relative;
border-collapse: collapse;
width: 100%;
max-width: 2000px;
min-width: 1450px;
}
table thead {
position: sticky;
top: 0;
}
table th {
padding: 0.4rem 0.45rem;
background-color: #151b24;
color: white;
top: 0;
}
table tr {
background-color: #2c394b;
transition: background-color 100ms;
}
table tr.current {
outline: 1px solid white;
}
table tr:nth-child(even) {
background-color: #334756;
}
table tr:hover {
background-color: #1a293b;
cursor: pointer;
}
table tr td {
padding: 0.3rem 0.5rem;
border: 1px solid #2c2c2c;
overflow: auto;
text-overflow: ellipsis;
}
td img {
height: 1.45em;
vertical-align: middle;
}
@media screen and (max-width: 550px) {
table {
font-size: 0.85em;
}
}
</style>
<template>
<div class="manager" v-if="store.authState == AuthState.AUTHORIZED">
<RoutesModal v-if="store.currentStation" />
<UpdateCard v-if="store.changesResponse.length > 0" />
<hr color="white" />
<TableActions />
<hr color="white" />
<div class="table_container">
<table>
<thead>
<th v-for="header in headerNameList">{{ header }}</th>
<th>Dostępność</th>
<th>Usuń</th>
</thead>
<tbody>
<tr v-for="(station, row) in sortedStationList" tabindex="0">
<td v-for="(value, propName) in headerNameList" @click="changeProperty(station, row, propName as string)">
<span v-if="propName === 'url'" :style="station.url ? 'color: gold' : 'color: gray;'">URL</span>
<span v-else-if="propName === 'checkpoints'">{{ station[propName] ? 'POKAŻ' : 'DODAJ' }}</span>
<span v-else-if="propName === 'routes'" v-html="getRouteNames(station.routes)"></span>
<span v-else-if="propName === 'signalType'"> {{ station[propName] }}</span>
<span v-else-if="typeof (station as any)[propName] === 'boolean'">
{{ (station as any)[propName] ? '' : '' }}
</span>
<span v-else>{{ (station as any)[propName] }}</span>
</td>
<td>
<select
name="availability"
:id="`select-${row}`"
v-model="sortedStationList[row]['availability']"
@input="(e) => changeAvailability(station, sortedStationList[row]['availability'], e)"
>
<option value="default">dostępna (w paczce)</option>
<option value="nonDefault">dostępna (poza paczką)</option>
<option value="unavailable">niedostępna</option>
<option value="nonPublic">niepubliczna</option>
<option value="abandoned">wycofana</option>
</select>
</td>
<td @click="removeStation(station)"><img src="/icon-trash.svg" alt="remove" /></td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import changeMixin from '../mixins/changeMixin';
import dataMixin from '../mixins/dataMixin';
import { useStore } from '../store';
import { SceneryRowItem, Availability, AuthState } from '../types/types';
import RoutesModal from '../components/RoutesModal.vue';
import TableActions from '../components/TableActions.vue';
import routesMixin from '../mixins/routesMixin';
import UpdateCard from '../components/UpdateCard.vue';
export default defineComponent({
components: { RoutesModal, TableActions, UpdateCard },
mixins: [dataMixin, changeMixin, routesMixin],
data: () => ({
AuthState,
headerNameList: {
name: 'Nazwa',
url: 'URL',
lines: 'Linie',
project: 'Projekt',
reqLevel: 'Wym. poziom',
signalType: 'Sygnalizacja',
controlType: 'Sterowanie',
SUP: 'SUP',
authors: 'Autorzy',
routes: 'Szlaki',
checkpoints: 'Posterunki',
} as {
[key: string]: string;
},
}),
setup() {
const store = useStore();
return {
store,
};
},
mounted() {
this.loadData();
},
computed: {
sortedStationList() {
const sortedList = this.store.stationList.sort((a, b) => (a.name > b.name ? 1 : -1));
if (!this.store.searchedSceneryName || this.store.searchedSceneryName == '') return sortedList;
return sortedList.filter((station) =>
station.name.toLowerCase().startsWith(this.store.searchedSceneryName.toLowerCase())
);
},
},
methods: {
changeProperty(station: SceneryRowItem, row: number, propertyName: string) {
this.store.selectedStationName = station.name;
if (propertyName == 'checkpoints') {
this.changeCheckpoints(row);
return;
}
if (propertyName == 'routes') {
this.showRoutesModal(station);
return;
}
const stationListRow = this.store.stationList.findIndex(
(station) => station.name == this.sortedStationList[row].name
);
if (stationListRow == -1) return;
const oldValue = (this.store.stationList[stationListRow] as any)[propertyName];
if (typeof oldValue === 'boolean') {
(this.store.stationList[stationListRow] as any)[propertyName] = !oldValue;
// this.$set(this.stationList[stationListRow], propertyName, !oldValue);
this.addChange(station, propertyName, oldValue, !oldValue);
return;
}
let newValue = prompt(`Zmień wartość dla rubryki ${this.headerNameList[propertyName]}`, oldValue);
if (newValue == null) return;
(this.store.stationList[stationListRow] as any)[propertyName] =
typeof oldValue === 'number' ? parseInt(newValue) : newValue;
// this.$set(this.stationList[stationListRow], propertyName, parseInt(newValue));
this.addChange(station, propertyName, oldValue, typeof oldValue === 'number' ? parseInt(newValue) : newValue);
},
changeCheckpoints(row: number) {
const stationListRow = this.store.stationList.findIndex(
(station) => station.name == this.sortedStationList[row].name
);
if (stationListRow == -1) return;
const oldCheckpoints = this.store.stationList[stationListRow].checkpoints;
const newCheckpoints = prompt('Wpisz posterunki (oddzielone średnikiem):', oldCheckpoints);
if (newCheckpoints === null) return;
this.store.stationList[stationListRow]['checkpoints'] = newCheckpoints;
this.addChange(this.sortedStationList[row], 'checkpoints', oldCheckpoints, newCheckpoints);
},
changeAvailability(scenery: SceneryRowItem, availability: Availability, e: Event) {
const selectedAvailability: Availability = (e.target as HTMLSelectElement).value as Availability;
this.addChange(scenery, 'availability', availability, selectedAvailability);
},
removeStation(scenery: SceneryRowItem) {
const confirmRemove = confirm('Czy na pewno chcesz zaznaczyć tę scenerię do usunięcia?');
if (!confirmRemove) return;
this.store.stationList = this.store.stationList.filter(({ id }) => id != scenery.id);
this.addRemovalChange(scenery);
},
showRoutesModal(scenery: SceneryRowItem) {
this.store.currentStation = scenery;
},
},
});
</script>
<style lang="scss" scoped>
.table_container {
overflow: auto;
height: 100vh;
margin: 0.5em 0;
}
table {
text-align: center;
color: white;
position: relative;
border-collapse: collapse;
width: 100%;
max-width: 2000px;
min-width: 1450px;
}
table thead {
position: sticky;
top: 0;
}
table th {
padding: 0.4rem 0.45rem;
background-color: #151b24;
color: white;
top: 0;
}
table tr {
background-color: #2c394b;
transition: background-color 100ms;
}
table tr.current {
outline: 1px solid white;
}
table tr:nth-child(even) {
background-color: #334756;
}
table tr:hover {
background-color: #1a293b;
cursor: pointer;
}
table tr td {
padding: 0.3rem 0.5rem;
border: 1px solid #2c2c2c;
overflow: auto;
text-overflow: ellipsis;
}
td img {
height: 1.45em;
vertical-align: middle;
}
@media screen and (max-width: 550px) {
table {
font-size: 0.85em;
}
}
</style>