Director hiring added

This commit is contained in:
Torsten Schulz
2025-01-09 15:31:55 +01:00
parent 6f7d97672e
commit 2f60741116
30 changed files with 2368 additions and 751 deletions

View File

@@ -9,6 +9,18 @@ class FalukantController {
this.getInfo = this.getInfo.bind(this); this.getInfo = this.getInfo.bind(this);
this.getInventory = this.getInventory.bind(this); this.getInventory = this.getInventory.bind(this);
this.sellProduct = this.sellProduct.bind(this); this.sellProduct = this.sellProduct.bind(this);
this.sellAllProducts = this.sellAllProducts.bind(this);
this.moneyHistory = this.moneyHistory.bind(this);
this.getStorage = this.getStorage.bind(this);
this.buyStorage = this.buyStorage.bind(this);
this.sellStorage = this.sellStorage.bind(this);
this.getStockTypes = this.getStockTypes.bind(this);
this.getStockOverview = this.getStockOverview.bind(this);
this.getAllProductions = this.getAllProductions.bind(this);
this.getDirectorProposals = this.getDirectorProposals.bind(this);
this.convertProposalToDirector = this.convertProposalToDirector.bind(this);
this.getDirectorForBranch = this.getDirectorForBranch.bind(this);
this.setSetting = this.setSetting.bind(this);
} }
async getUser(req, res) { async getUser(req, res) {
@@ -118,6 +130,7 @@ class FalukantController {
} }
async createStock(req, res) { async createStock(req, res) {
console.log('build stock');
try { try {
const { userid: hashedUserId } = req.headers; const { userid: hashedUserId } = req.headers;
const { branchId, stockTypeId, stockSize } = req.body; const { branchId, stockTypeId, stockSize } = req.body;
@@ -159,6 +172,146 @@ class FalukantController {
res.status(500).json({ error: error.message }); res.status(500).json({ error: error.message });
} }
} }
async sellAllProducts(req, res) {
try {
const { userid: hashedUserId } = req.headers;
const { branchId } = req.body;
const result = await FalukantService.sellAllProducts(hashedUserId, branchId);
res.status(201).json(result);
} catch (error) {
res.status(500).json({ error: error.message });
}
}
async moneyHistory(req, res) {
try {
const { userid: hashedUserId } = req.headers;
const { page, filter } = req.body;
if (!page) {
page = 1;
}
const result = await FalukantService.moneyHistory(hashedUserId, page, filter);
res.status(201).json(result);
} catch (error) {
res.status(500).json({ error: error.message });
}
}
async getStorage(req, res) {
try {
const { userid: hashedUserId } = req.headers;
const { branchId } = req.params;
const result = await FalukantService.getStorage(hashedUserId, branchId);
res.status(200).json(result);
} catch (error) {
res.status(500).json({ error: error.message});
console.log(error);
}
}
async buyStorage(req, res) {
try {
const { userid: hashedUserId } = req.headers;
const { branchId, amount, stockTypeId } = req.body;
const result = await FalukantService.buyStorage(hashedUserId, branchId, amount, stockTypeId);
res.status(201).json(result);
} catch (error) {
res.status(500).json({ error: error.message});
console.log(error);
}
}
async sellStorage(req, res) {
try {
const { userid: hashedUserId } = req.headers;
const { branchId, amount, stockTypeId } = req.body;
const result = await FalukantService.sellStorage(hashedUserId, branchId, amount, stockTypeId);
res.status(202).json(result);
} catch (error) {
res.status(500).json({ error: error.message});
console.log(error);
}
}
async getStockTypes(req, res) {
console.log('load stock');
try {
const result = await FalukantService.getStockTypes();
res.status(200).json(result);
} catch (error) {
res.status(500).json({ error: error.message });
console.log(error);
}
}
async getStockOverview(req, res) {
try {
const result = await FalukantService.getStockOverview();
res.status(200).json(result);
} catch (error) {
res.status(500).json({ error: error.message });
}
}
async getAllProductions(req, res) {
try {
const { userid: hashedUserId } = req.headers;
const result = await FalukantService.getAllProductions(hashedUserId);
res.status(200).json(result);
} catch (error) {
res.status(500).json({ error: error.message });
}
}
async getDirectorProposals(req, res) {
try {
const { userid: hashedUserId } = req.headers;
const { branchId } = req.body;
const result = await FalukantService.getDirectorProposals(hashedUserId, branchId);
res.status(200).json(result);
} catch (error) {
res.status(500).json({ error: error.message });
}
}
async convertProposalToDirector(req, res) {
try {
const { userid: hashedUserId } = req.headers;
const { proposalId } = req.body;
const result = await FalukantService.convertProposalToDirector(hashedUserId, proposalId);
res.status(200).json(result);
} catch (error) {
res.status(500).json({ error: error.message });
}
}
async getDirectorForBranch(req, res) {
try {
const { userid: hashedUserId } = req.headers;
const { branchId } = req.params;
const result = await FalukantService.getDirectorForBranch(hashedUserId, branchId);
if (!result) {
return res.status(404).json({ message: 'No director found for this branch' });
}
res.status(200).json(result);
} catch (error) {
res.status(500).json({ error: error.message });
}
}
async setSetting(req, res) {
try {
const { userid: hashedUserId } = req.headers;
const { branchId, directorId, settingKey, value } = req.body;
const result = await FalukantService.setSetting(hashedUserId, branchId, directorId, settingKey, value);
res.status(200).json(result);
} catch (error) {
res.status(500).json({ error: error.message });
console.log(error);
}
}
} }
export default FalukantController; export default FalukantController;

View File

@@ -44,8 +44,10 @@ import Branch from './falukant/data/branch.js';
import BranchType from './falukant/type/branch.js'; import BranchType from './falukant/type/branch.js';
import Production from './falukant/data/production.js'; import Production from './falukant/data/production.js';
import Inventory from './falukant/data/inventory.js'; import Inventory from './falukant/data/inventory.js';
import BuyableStock from './falukant/data/buayble_stock.js'; import BuyableStock from './falukant/data/buyable_stock.js';
import MoneyFlow from './falukant/log/moneyflow.js';
import Director from './falukant/data/director.js';
import DirectorProposal from './falukant/data/director_proposal.js';
export default function setupAssociations() { export default function setupAssociations() {
// UserParam related associations // UserParam related associations
@@ -251,4 +253,21 @@ export default function setupAssociations() {
Branch.hasMany(FalukantStock, { foreignKey: 'branchId', as: 'stocks' }); Branch.hasMany(FalukantStock, { foreignKey: 'branchId', as: 'stocks' });
FalukantStock.belongsTo(Branch, { foreignKey: 'branchId', as: 'branch' }); FalukantStock.belongsTo(Branch, { foreignKey: 'branchId', as: 'branch' });
MoneyFlow.belongsTo(FalukantUser, { foreignKey: 'falukantUserId', as: 'user' });
FalukantUser.hasMany(MoneyFlow, { foreignKey: 'falukantUserId', as: 'flows' });
BuyableStock.belongsTo(FalukantStockType, { foreignKey: 'stockTypeId', as: 'stockType' });
FalukantStockType.hasMany(BuyableStock, { foreignKey: 'stockTypeId', as: 'buyableStocks' });
Director.belongsTo(FalukantUser, { foreignKey: 'employerUserId', as: 'user' });
FalukantUser.hasMany(Director, { foreignKey: 'employerUserId', as: 'directors' });
Director.belongsTo(FalukantCharacter, { foreignKey: 'directorCharacterId', as: 'character' });
FalukantCharacter.hasMany(Director, { foreignKey: 'directorCharacterId', as: 'directors' });
DirectorProposal.belongsTo(FalukantUser, { foreignKey: 'employerUserId', as: 'user' });
FalukantUser.hasMany(DirectorProposal, { foreignKey: 'employerUserId', as: 'directorProposals' });
DirectorProposal.belongsTo(FalukantCharacter, { foreignKey: 'directorCharacterId', as: 'character' });
FalukantCharacter.hasMany(DirectorProposal, { foreignKey: 'directorCharacterId', as: 'directorProposals' });
} }

View File

@@ -18,7 +18,7 @@ Branch.init({
}, },
}, { }, {
sequelize, sequelize,
modelName: 'BranchType', modelName: 'Branch',
tableName: 'branch', tableName: 'branch',
schema: 'falukant_data', schema: 'falukant_data',
timestamps: false, timestamps: false,

View File

@@ -0,0 +1,48 @@
import { Model, DataTypes } from 'sequelize';
import { sequelize } from '../../../utils/sequelize.js';
class Director extends Model { }
Director.init({
directorCharacterId: {
type: DataTypes.INTEGER,
allowNull: false,
},
employerUserId: {
type: DataTypes.INTEGER,
allowNull: false,
},
income: {
type: DataTypes.INTEGER,
allowNull: false,
},
satisfaction: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 100,
},
mayProduce: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: true,
},
maySell: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: true,
},
mayStartTransport: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: true,
}
}, {
sequelize,
modelName: 'Director',
tableName: 'director',
schema: 'falukant_data',
timestamps: false,
underscored: true,
});
export default Director;

View File

@@ -0,0 +1,28 @@
import { Model, DataTypes } from 'sequelize';
import { sequelize } from '../../../utils/sequelize.js';
class DirectorProposal extends Model { }
DirectorProposal.init({
directorCharacterId: {
type: DataTypes.INTEGER,
allowNull: false,
},
employerUserId: {
type: DataTypes.INTEGER,
allowNull: false,
},
proposedIncome: {
type: DataTypes.INTEGER,
allowNull: false,
},
}, {
sequelize,
modelName: 'DirectorProposal',
tableName: 'director_proposal',
schema: 'falukant_data',
timestamps: true,
underscored: true,
});
export default DirectorProposal;

View File

@@ -19,7 +19,7 @@ FalukantStock.init({
}, },
}, { }, {
sequelize, sequelize,
modelName: 'StockType', modelName: 'StockData',
tableName: 'stock', tableName: 'stock',
schema: 'falukant_data', schema: 'falukant_data',
timestamps: false, timestamps: false,

View File

@@ -0,0 +1,45 @@
import { Model, DataTypes } from 'sequelize';
import { sequelize } from '../../../utils/sequelize.js';
class MoneyFlow extends Model { }
MoneyFlow.init({
falukantUserId: {
type: DataTypes.INTEGER,
allowNull: false,
},
activity: {
type: DataTypes.STRING,
allowNull: false,
},
moneyBefore: {
type: DataTypes.DOUBLE,
allowNull: false,
},
moneyAfter: {
type: DataTypes.DOUBLE,
allowNull: true,
},
time: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: DataTypes.NOW
},
changeValue: {
type: DataTypes.DOUBLE,
allowNull: false,
},
changedBy: {
type: DataTypes.INTEGER,
allowNull: true,
},
}, {
sequelize,
modelName: 'MoneyFlow',
tableName: 'moneyflow',
schema: 'falukant_log',
timestamps: false,
underscored: true,
});
export default MoneyFlow;

View File

@@ -48,7 +48,10 @@ import BranchType from './falukant/type/branch.js';
import Branch from './falukant/data/branch.js'; import Branch from './falukant/data/branch.js';
import Production from './falukant/data/production.js'; import Production from './falukant/data/production.js';
import Inventory from './falukant/data/inventory.js'; import Inventory from './falukant/data/inventory.js';
import BuyableStock from './falukant/data/buayble_stock.js'; import BuyableStock from './falukant/data/buyable_stock.js';
import MoneyFlow from './falukant/log/moneyflow.js';
import Director from './falukant/data/director.js';
import DirectorProposal from './falukant/data/director_proposal.js';
const models = { const models = {
SettingsType, SettingsType,
@@ -102,6 +105,9 @@ const models = {
Production, Production,
Inventory, Inventory,
BuyableStock, BuyableStock,
MoneyFlow,
Director,
DirectorProposal,
}; };
export default models; export default models;

View File

@@ -124,6 +124,62 @@ export async function createTriggers() {
EXECUTE FUNCTION falukant_data.create_knowledge_trigger(); EXECUTE FUNCTION falukant_data.create_knowledge_trigger();
`; `;
const updateMoney = `
CREATE OR REPLACE FUNCTION falukant_data.update_money(
p_falukant_user_id integer,
p_money_change numeric,
p_activity text,
p_changed_by integer DEFAULT NULL
)
RETURNS void
LANGUAGE plpgsql
AS $function$
DECLARE
v_money_before numeric(10,2);
v_money_after numeric(10,2);
v_moneyflow_id bigint;
BEGIN
SELECT money
INTO v_money_before
FROM falukant_data.falukant_user
WHERE id = p_falukant_user_id;
IF NOT FOUND THEN
RAISE EXCEPTION 'FalukantUser mit ID % nicht gefunden', p_falukant_user_id;
END IF;
v_money_after := v_money_before + p_money_change;
INSERT INTO falukant_log.moneyflow (
falukant_user_id,
activity,
money_before,
money_after,
change_value,
changed_by,
time
)
VALUES (
p_falukant_user_id,
p_activity,
v_money_before,
NULL, -- Wird gleich aktualisiert
p_money_change,
p_changed_by,
NOW()
)
RETURNING id INTO v_moneyflow_id;
UPDATE falukant_data.falukant_user
SET money = v_money_after
WHERE id = p_falukant_user_id;
UPDATE falukant_log.moneyflow
SET money_after = (
SELECT money
FROM falukant_data.falukant_user
WHERE id = p_falukant_user_id
)
WHERE id = v_moneyflow_id;
END;
$function$;
`;
try { try {
await sequelize.query(createTriggerFunction); await sequelize.query(createTriggerFunction);
await sequelize.query(createInsertTrigger); await sequelize.query(createInsertTrigger);
@@ -136,6 +192,7 @@ export async function createTriggers() {
await sequelize.query(createCharacterCreationTrigger); await sequelize.query(createCharacterCreationTrigger);
await sequelize.query(createKnowledgeTriggerMethod); await sequelize.query(createKnowledgeTriggerMethod);
await sequelize.query(createKnowledgeTrigger); await sequelize.query(createKnowledgeTrigger);
await sequelize.query(updateMoney);
console.log('Triggers created successfully'); console.log('Triggers created successfully');
} catch (error) { } catch (error) {

View File

@@ -11,11 +11,24 @@ router.get('/name/randomlastname', falukantController.randomLastName);
router.get('/info', falukantController.getInfo); router.get('/info', falukantController.getInfo);
router.get('/branches/:branch', falukantController.getBranch); router.get('/branches/:branch', falukantController.getBranch);
router.get('/branches', falukantController.getBranches); router.get('/branches', falukantController.getBranches);
router.get('/productions', falukantController.getAllProductions);
router.post('/production', falukantController.createProduction); router.post('/production', falukantController.createProduction);
router.get('/production/:branchId', falukantController.getProduction); router.get('/production/:branchId', falukantController.getProduction);
router.get('/stocktypes', falukantController.getStockTypes);
router.get('/stockoverview', falukantController.getStockOverview);
router.get('/stock/?:branchId', falukantController.getStock); router.get('/stock/?:branchId', falukantController.getStock);
router.post('/stock', falukantController.createStock); router.post('/stock', falukantController.createStock);
router.get('/products', falukantController.getProducts); router.get('/products', falukantController.getProducts);
router.get('/inventory/?:branchId', falukantController.getInventory); router.get('/inventory/?:branchId', falukantController.getInventory);
router.post('/sell/all', falukantController.sellAllProducts);
router.post('/sell', falukantController.sellProduct); router.post('/sell', falukantController.sellProduct);
router.post('/moneyhistory', falukantController.moneyHistory);
router.get('/storage/:branchId', falukantController.getStorage);
router.post('/storage', falukantController.buyStorage);
router.delete('/storage', falukantController.sellStorage);
router.post('/director/proposal', falukantController.getDirectorProposals);
router.post('/director/convertproposal', falukantController.convertProposalToDirector);
router.post('/director/settings', falukantController.setSetting);
router.get('/director/:branchId', falukantController.getDirectorForBranch);
export default router; export default router;

View File

@@ -104,12 +104,14 @@ export const loginUser = async ({ username, password }) => {
user.authCode = authCode; user.authCode = authCode;
await user.save(); await user.save();
const friends = await getFriends(user.id); const friends = await getFriends(user.id);
console.log('send login to friends');
for (const friend of friends) { for (const friend of friends) {
await notifyUser(friend.hashedId, 'friendloginchanged', { await notifyUser(friend.hashedId, 'friendloginchanged', {
userId: user.hashedId, userId: user.hashedId,
status: 'online', status: 'online',
}); });
} }
console.log('set user session');
const sessionData = { const sessionData = {
id: user.hashedId, id: user.hashedId,
username: user.username, username: user.username,
@@ -118,6 +120,7 @@ export const loginUser = async ({ username, password }) => {
timestamp: Date.now() timestamp: Date.now()
}; };
await setUserSession(user.id, sessionData); await setUserSession(user.id, sessionData);
console.log('get user params');
const params = await UserParam.findAll({ const params = await UserParam.findAll({
where: { where: {
userId: user.id userId: user.id
@@ -133,6 +136,7 @@ export const loginUser = async ({ username, password }) => {
const mappedParams = params.map(param => { const mappedParams = params.map(param => {
return { 'name': param.paramType.description, 'value': param.value }; return { 'name': param.paramType.description, 'value': param.value };
}); });
console.log('return user');
return { return {
id: user.hashedId, id: user.hashedId,
username: user.username, username: user.username,

File diff suppressed because it is too large Load Diff

View File

@@ -214,12 +214,15 @@ const initializeFalukantLastnames = async () => {
} }
async function initializeFalukantStockTypes() { async function initializeFalukantStockTypes() {
await FalukantStockType.bulkCreate([ try {
{ labelTr: 'wood', cost: 15 }, await FalukantStockType.bulkCreate([
{ labelTr: 'stone', cost: 25 }, { labelTr: 'wood', cost: 15 },
{ labelTr: 'iron', cost: 100 }, { labelTr: 'stone', cost: 25 },
{ labelTr: 'field', cost: 5 }, { labelTr: 'iron', cost: 100 },
]); { labelTr: 'field', cost: 5 },
]);
} catch (error) {
}
} }
async function initializeFalukantProducts() { async function initializeFalukantProducts() {

View File

@@ -20,6 +20,7 @@ const createSchemas = async () => {
await sequelize.query('CREATE SCHEMA IF NOT EXISTS falukant_data'); await sequelize.query('CREATE SCHEMA IF NOT EXISTS falukant_data');
await sequelize.query('CREATE SCHEMA IF NOT EXISTS falukant_type'); await sequelize.query('CREATE SCHEMA IF NOT EXISTS falukant_type');
await sequelize.query('CREATE SCHEMA IF NOT EXISTS falukant_predefine'); await sequelize.query('CREATE SCHEMA IF NOT EXISTS falukant_predefine');
await sequelize.query('CREATE SCHEMA IF NOT EXISTS falukant_log');
}; };
const initializeDatabase = async () => { const initializeDatabase = async () => {
@@ -34,4 +35,37 @@ const syncModels = async (models) => {
} }
}; };
export { sequelize, initializeDatabase, syncModels }; async function updateFalukantUserMoney(falukantUserId, moneyChange, activity, changedBy = null) {
try {
const result = await sequelize.query(
`SELECT falukant_data.update_money(
:falukantUserId,
:moneyChange,
:activity,
:changedBy
)`,
{
replacements: {
falukantUserId,
moneyChange,
activity,
changedBy,
},
type: sequelize.QueryTypes.SELECT,
}
);
return {
success: true,
message: 'Money updated successfully',
result
};
} catch (error) {
console.error('Error updating money:', error);
return {
success: false,
message: error.message
};
}
}
export { sequelize, initializeDatabase, syncModels, updateFalukantUserMoney };

View File

@@ -48,7 +48,9 @@ export async function notifyUser(recipientHashedUserId, event, data) {
if (recipientUser) { if (recipientUser) {
const socketId = userSockets[recipientUser.hashedId]; const socketId = userSockets[recipientUser.hashedId];
if (socketId) { if (socketId) {
io.to(socketId).emit(event, data); setTimeout(() => {
io.to(socketId).emit(event, data);
}, 250);
} }
} else { } else {
console.log(`Benutzer mit gehashter ID ${recipientHashedUserId} nicht gefunden.`); console.log(`Benutzer mit gehashter ID ${recipientHashedUserId} nicht gefunden.`);
@@ -56,6 +58,7 @@ export async function notifyUser(recipientHashedUserId, event, data) {
} catch (err) { } catch (err) {
console.error('Fehler beim Senden der Benachrichtigung:', err); console.error('Fehler beim Senden der Benachrichtigung:', err);
} }
console.log('done sending socket');
} }
export async function notifyAllUsers(event, data) { export async function notifyAllUsers(event, data) {

BIN
dump.rdb Normal file

Binary file not shown.

BIN
frontend/dump.rdb Normal file

Binary file not shown.

View File

@@ -75,5 +75,6 @@ export default {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
height: 100%; height: 100%;
overflow: hidden;
} }
</style> </style>

View File

@@ -113,3 +113,15 @@ span.button:hover {
.font-color-gender-nonbinary { .font-color-gender-nonbinary {
color: #DAA520; color: #DAA520;
} }
main,
.contenthidden {
width: 100%;
height: 100%;
overflow: hidden;
}
.contentscroll {
width: 100%;
height: 100%;
overflow: auto;
}

View File

@@ -81,6 +81,7 @@ export default {
width: calc(100% + 40px); width: calc(100% + 40px);
gap: 2em; gap: 2em;
margin: -21px -20px 1.5em -20px; margin: -21px -20px 1.5em -20px;
position: fixed;
} }
.status-item { .status-item {

View File

@@ -0,0 +1,162 @@
<template>
<DialogWidget ref="dialog" :title="$t('factset.newdirector.title')" :show-close="true" :buttons="buttons"
@close="closeDialog" name="FalukantNewDirector" :modal="true" :isTitleTranslated="true">
<div class="director-dialog">
<div class="proposal-list">
<ul>
<li v-for="proposal in proposals" :key="proposal.id" @click="selectProposal(proposal)"
:class="{ selected: selectedProposal && selectedProposal.id === proposal.id }">
{{ $t('falukant.titles.' + proposal.character.gender + '.' + proposal.character.title) }} {{ proposal.character.name }} ({{ proposal.character.age }} Jahre)
</li>
</ul>
</div>
<div class="proposal-details" v-if="selectedProposal">
<h3>{{ selectedProposal.character.name }}</h3>
<p><strong>{{ $t('falukant.newdirector.age') }}</strong> {{ selectedProposal.character.age }} Jahre</p>
<p><strong>{{ $t('falukant.newdirector.salary') }}</strong> {{ selectedProposal.proposedIncome }} $</p>
<h4>{{ $t('falukant.newdirector.skills') }}</h4>
<table>
<thead>
<tr>
<th>{{ $t('falukant.newdirector.product') }}</th>
<th>{{ $t('falukant.newdirector.knowledge') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="knowledge in selectedProposal.character.knowledge" :key="knowledge.id">
<td>{{ $t('falukant.product.' + knowledge.labelTr) }}</td>
<td>{{ mapKnowledgeToText(knowledge.value) }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</DialogWidget>
</template>
<script>
import apiClient from '@/utils/axios.js';
import DialogWidget from '@/components/DialogWidget.vue';
import { mapKnowledgeToText } from '@/utils/knowledgeHelper.js';
export default {
name: 'FalukantNewDirector',
components: {
DialogWidget,
},
data() {
return {
dialog: null,
proposals: [],
selectedProposal: null,
products: [],
buttons: [
{ text: 'Einstellen', action: this.hireDirector },
{ text: 'Abbrechen', action: 'close' },
],
};
},
methods: {
async open(branchId) {
this.dialog.open();
await this.loadProposals(branchId);
},
closeDialog() {
this.dialog.close();
this.proposals = [];
this.selectedProposal = null;
},
async loadProposals(branchId) {
try {
const response = await apiClient.post('/api/falukant/director/proposal', { branchId });
this.proposals = response.data.map((proposal) => {
return {
...proposal,
knowledge: proposal.knowledge || [],
};
});
} catch (error) {
console.error('Error loading proposals:', error);
}
},
selectProposal(proposal) {
this.selectedProposal = proposal;
},
async hireDirector() {
if (!this.selectedProposal) return;
try {
await apiClient.post('/api/falukant/director/convertproposal', { proposalId: this.selectedProposal.id });
this.closeDialog();
this.$emit('directorHired');
} catch (error) {
console.error('Error hiring director:', error);
}
},
mapKnowledgeToText(value) {
return mapKnowledgeToText(value, this.$t);
},
},
mounted() {
this.dialog = this.$refs.dialog;
},
beforeUnmount() { },
};
</script>
<style scoped>
.director-dialog {
display: flex;
gap: 20px;
}
.proposal-list {
width: 40%;
border-right: 1px solid #ddd;
padding-right: 20px;
}
.proposal-list ul {
list-style: none;
padding: 0;
}
.proposal-list li {
padding: 10px;
cursor: pointer;
border: 1px solid transparent;
margin-bottom: 10px;
border-radius: 4px;
}
.proposal-list li:hover {
background-color: #f9f9f9;
}
.proposal-list li.selected {
border-color: #f9a22c;
background-color: #fdf1db;
}
.proposal-details {
width: 60%;
}
.proposal-details table {
width: 100%;
border-collapse: collapse;
}
.proposal-details table th,
.proposal-details table td {
padding: 10px;
border: 1px solid #ddd;
text-align: left;
}
</style>

View File

@@ -50,7 +50,7 @@
"titles": { "titles": {
"male": { "male": {
"noncivil": "Leibeigener", "noncivil": "Leibeigener",
"civil": "Bürgerlich", "civil": "Freier Bürger",
"sir": "Herr", "sir": "Herr",
"townlord": "Stadtherr", "townlord": "Stadtherr",
"by": "von", "by": "von",
@@ -71,7 +71,7 @@
}, },
"female": { "female": {
"noncivil": "Leibeigene", "noncivil": "Leibeigene",
"civil": "Bürgerlich", "civil": "Freie Bürgerin",
"sir": "Frau", "sir": "Frau",
"townlord": "Stadtherrin", "townlord": "Stadtherrin",
"by": "zu", "by": "zu",
@@ -106,7 +106,18 @@
}, },
"director": { "director": {
"title": "Direktor-Infos", "title": "Direktor-Infos",
"info": "Informationen über den Direktor der Niederlassung." "info": "Informationen über den Direktor der Niederlassung.",
"actions": {
"new": "Direktor einstellen"
},
"name": "Name",
"salary": "Gehalt",
"satisfaction": "Zufriedenheit",
"fire": "Feuern",
"teach": "Weiterbilden",
"produce": "Darf produzieren",
"sell": "Darf verkaufen",
"starttransport": "Darf Transporte veranlassen"
}, },
"sale": { "sale": {
"title": "Inventar", "title": "Inventar",
@@ -137,7 +148,8 @@
"time": "Uhr", "time": "Uhr",
"current": "Laufende Produktionen", "current": "Laufende Produktionen",
"product": "Produkt", "product": "Produkt",
"remainingTime": "Verbleibende Zeit (Sekunden)" "remainingTime": "Verbleibende Zeit (Sekunden)",
"noProductions": "Keine laufenden Produktionen."
}, },
"columns": { "columns": {
"city": "Stadt", "city": "Stadt",
@@ -155,7 +167,31 @@
"perMinute": "Erlös pro Minute", "perMinute": "Erlös pro Minute",
"expand": "Erträge anzeigen", "expand": "Erträge anzeigen",
"collapse": "Erträge ausblenden", "collapse": "Erträge ausblenden",
"knowledge": "Produktwissen" "knowledge": "Produktwissen",
"profitAbsolute": "Gesamtgewinn",
"profitPerMinute": "Gewinn pro Minute"
},
"storage": {
"title": "Lager",
"currentCapacity": "Verwendetes Lager",
"stockType": "Lagerart",
"totalCapacity": "Vorhanden",
"used": "Verwendet",
"availableToBuy": "Zum Kauf verfügbar",
"buyAmount": "Größe",
"buyStorageButton": "Kaufen",
"sellAmount": "Größe",
"sellStorageButton": "Verkaufen",
"selectStockType": "Lagertyp auswählen",
"costPerUnit": "Kosten pro Einheit",
"buycost": "Kosten",
"sellincome": "Einnahmen"
},
"stocktype": {
"wood": "Holzlager",
"stone": "Steinlager",
"iron": "Eisenlager",
"field": "Feldlager"
} }
}, },
"product": { "product": {
@@ -194,6 +230,38 @@
}, },
"regionType": { "regionType": {
"city": "Stadt" "city": "Stadt"
},
"moneyHistory": {
"title": "Geldhistorie",
"filter": "Filter",
"search": "Filter setzen",
"activity": "Aktivität",
"moneyBefore": "Geld vor der Transaktion",
"moneyAfter": "Geld nach der Transaktion",
"changeValue": "Wertänderung",
"time": "Zeit",
"activities": {
"Product sale": "Produktverkauf",
"Production cost": "Produktionskosten",
"Sell all products": "Alle Produkte verkaufen"
}
},
"newdirector": {
"title": "Neuer Direktor",
"age": "Alter",
"salary": "Gehalt",
"skills": "Wissen",
"product": "Produkt",
"knowledge": "Produktwissen"
},
"skillKnowledges": {
"excelent": "Exzellent",
"veryhigh": "Sehr gut",
"high": "Gut",
"medium": "Mittel",
"low": "Schlecht",
"verylow": "Sehr schlecht",
"none": "Kein Wissen"
} }
} }
} }

View File

@@ -1,6 +1,7 @@
import BranchView from '../views/falukant/BranchView.vue'; import BranchView from '../views/falukant/BranchView.vue';
import Createview from '../views/falukant/CreateView.vue'; import Createview from '../views/falukant/CreateView.vue';
import FalukantOverviewView from '../views/falukant/OverviewView.vue'; import FalukantOverviewView from '../views/falukant/OverviewView.vue';
import MoneyHistoryView from '../views/falukant/MoneyHistoryView.vue';
const falukantRoutes = [ const falukantRoutes = [
{ {
@@ -21,6 +22,12 @@ const falukantRoutes = [
component: BranchView, component: BranchView,
meta: { requiresAuth: true }, meta: { requiresAuth: true },
}, },
{
path: '/falukant/moneyhistory',
name: 'MoneyHistoryView',
component: MoneyHistoryView,
meta: { requiresAuth: true },
},
]; ];
export default falukantRoutes; export default falukantRoutes;

View File

@@ -56,7 +56,7 @@ const store = createStore({
}, },
clearDaemonSocket(state) { clearDaemonSocket(state) {
if (state.daemonSocket) { if (state.daemonSocket) {
state.daemonSocket.disconnect(); state.daemonSocket.close();
} }
state.daemonSocket = null; state.daemonSocket = null;
}, },
@@ -73,6 +73,7 @@ const store = createStore({
await dispatch('loadMenu'); await dispatch('loadMenu');
}, },
logout({ commit }) { logout({ commit }) {
console.log('Logging out...');
commit('clearSocket'); commit('clearSocket');
commit('clearDaemonSocket'); commit('clearDaemonSocket');
commit('dologout'); commit('dologout');
@@ -80,12 +81,16 @@ const store = createStore({
}, },
initializeSocket({ commit, state }) { initializeSocket({ commit, state }) {
if (state.isLoggedIn && state.user) { if (state.isLoggedIn && state.user) {
let currentSocket = state.socket;
const connectSocket = () => { const connectSocket = () => {
if (currentSocket) {
currentSocket.disconnect();
}
const socket = io(import.meta.env.VITE_API_BASE_URL); const socket = io(import.meta.env.VITE_API_BASE_URL);
socket.on('connect', () => { socket.on('connect', () => {
console.log('Socket.io connected'); console.log('Socket.io connected');
socket.emit('setUserId', state.user.id); socket.emit('setUserId', state.user.id); // Sende user.id, wenn user vorhanden ist
}); });
socket.on('disconnect', (reason) => { socket.on('disconnect', (reason) => {
@@ -104,11 +109,17 @@ const store = createStore({
}; };
connectSocket(); connectSocket();
} else {
console.log("User is not logged in or user data is not available.");
} }
}, },
initializeDaemonSocket({ commit, state }) { initializeDaemonSocket({ commit, state }) {
if (state.isLoggedIn && state.user) { if (state.isLoggedIn && state.user) {
let currentDaemonSocket = state.daemonSocket;
const connectDaemonSocket = () => { const connectDaemonSocket = () => {
if (currentDaemonSocket) {
currentDaemonSocket.disconnect();
}
const daemonSocket = new WebSocket(import.meta.env.VITE_DAEMON_SOCKET); const daemonSocket = new WebSocket(import.meta.env.VITE_DAEMON_SOCKET);
daemonSocket.onopen = () => { daemonSocket.onopen = () => {
@@ -127,6 +138,7 @@ const store = createStore({
daemonSocket.onerror = (error) => { daemonSocket.onerror = (error) => {
console.error('Daemon WebSocket error:', error); console.error('Daemon WebSocket error:', error);
console.log('WebSocket readyState:', daemonSocket.readyState);
retryConnection(connectDaemonSocket); retryConnection(connectDaemonSocket);
}; };
@@ -134,7 +146,6 @@ const store = createStore({
const message = event.data; const message = event.data;
console.log(message); console.log(message);
if (message === "ping") { if (message === "ping") {
console.log("Ping received, sending Pong...");
daemonSocket.send("pong"); daemonSocket.send("pong");
} else { } else {
try { try {

View File

@@ -0,0 +1,9 @@
export function mapKnowledgeToText(value, t) {
if (value >= 90) return t('falukant.skillKnowledges.excelent');
if (value >= 75) return t('falukant.skillKnowledges.veryhigh');
if (value >= 60) return t('falukant.skillKnowledges.high');
if (value >= 45) return t('falukant.skillKnowledges.medium');
if (value >= 30) return t('falukant.skillKnowledges.low');
if (value >= 15) return t('falukant.skillKnowledges.verylow');
return t('falukant.skillKnowledges.none');
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,106 @@
<template>
<div>
<h2>{{ $t('falukant.moneyHistory.title') }}</h2>
<div class="filter-section">
<label>{{ $t('falukant.moneyHistory.filter') }}</label>
<input v-model="filter" type="text" />
<button @click="fetchMoneyHistory(1)">{{ $t('falukant.moneyHistory.search') }}</button>
</div>
<table>
<thead>
<tr>
<th>{{ $t('falukant.moneyHistory.activity') }}</th>
<th>{{ $t('falukant.moneyHistory.moneyBefore') }}</th>
<th>{{ $t('falukant.moneyHistory.moneyAfter') }}</th>
<th>{{ $t('falukant.moneyHistory.changeValue') }}</th>
<th>{{ $t('falukant.moneyHistory.time') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(entry, index) in moneyHistory.data" :key="index">
<td>{{ $t(`falukant.moneyHistory.activities.${entry.activity}`) }}</td>
<td>{{ entry.moneyBefore }}</td>
<td>{{ entry.moneyAfter }}</td>
<td>{{ entry.changeValue }}</td>
<td>{{ new Date(entry.time).toLocaleString() }}</td>
</tr>
</tbody>
</table>
<div class="pagination">
<button
v-if="moneyHistory.currentPage > 1"
@click="fetchMoneyHistory(moneyHistory.currentPage - 1)"
>
{{ $t('falukant.moneyHistory.prev') }}
</button>
<span>
{{ moneyHistory.currentPage }} / {{ moneyHistory.totalPages }}
</span>
<button
v-if="moneyHistory.currentPage < moneyHistory.totalPages"
@click="fetchMoneyHistory(moneyHistory.currentPage + 1)"
>
{{ $t('falukant.moneyHistory.next') }}
</button>
</div>
</div>
</template>
<script>
import apiClient from '@/utils/axios.js';
export default {
name: 'MoneyHistoryView',
data() {
return {
filter: '',
moneyHistory: {
data: [],
currentPage: 1,
totalPages: 1,
},
};
},
async mounted() {
await this.fetchMoneyHistory(1);
},
methods: {
async fetchMoneyHistory(page) {
try {
const response = await apiClient.post('/api/falukant/moneyhistory', {
page,
filter: this.filter,
});
this.moneyHistory = response.data;
} catch (error) {
console.error('Error fetching money history:', error);
}
},
},
};
</script>
<style scoped>
.filter-section {
margin-bottom: 1rem;
}
table {
width: 100%;
border-collapse: collapse;
margin-bottom: 1rem;
}
th, td {
border: 1px solid #ccc;
padding: 8px;
text-align: left;
}
.pagination {
display: flex;
align-items: center;
gap: 1rem;
}
</style>

View File

@@ -27,16 +27,56 @@
</div> </div>
<div> <div>
<h3>{{ $t('falukant.overview.productions.title') }}</h3> <h3>{{ $t('falukant.overview.productions.title') }}</h3>
<table v-if="productions.length > 0">
<thead>
<tr>
<th>{{ $t('falukant.branch.sale.region') }}</th>
<th>{{ $t('falukant.branch.production.product') }}</th>
<th>{{ $t('falukant.branch.production.quantity') }}</th>
<th>{{ $t('falukant.branch.production.ending') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(production, index) in productions" :key="index">
<td>{{ production.cityName }}</td>
<td>{{ $t(`falukant.product.${production.productName}`) }}</td>
<td>{{ production.quantity }}</td>
<td>{{ formatDate(production.endTimestamp) }}</td>
</tr>
</tbody>
</table>
<p v-else>{{ $t('falukant.branch.production.noProductions') }}</p>
</div> </div>
<div> <div>
<h3>{{ $t('falukant.overview.stock.title') }}</h3> <h3>{{ $t('falukant.overview.stock.title') }}</h3>
<table v-if="allStock.length > 0">
<thead>
<tr>
<th>{{ $t('falukant.branch.sale.region') }}</th>
<th>{{ $t('falukant.branch.sale.product') }}</th>
<th>{{ $t('falukant.branch.sale.quantity') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in allStock" :key="index">
<td>{{ item.regionName }}</td>
<td>{{ $t(`falukant.product.${item.productLabelTr}`) }}</td>
<td>{{ item.quantity }}</td>
</tr>
</tbody>
</table>
<p v-else>{{ $t('falukant.branch.sale.noInventory') }}</p>
</div> </div>
<div> <div>
<h3>{{ $t('falukant.overview.branches.title') }}</h3> <h3>{{ $t('falukant.overview.branches.title') }}</h3>
<table> <table>
<tr v-for="branch in falukantUser?.branches"> <tr v-for="branch in falukantUser?.branches" :key="branch.id">
<td><span @click="openBranch(branch.id)" class="link">{{ branch.region.name }}</span></td> <td>
<td>{{ $t(`falukant.overview.branches.level.${branch.branchType.labelTr}`) }}</td> <span @click="openBranch(branch.id)" class="link">{{ branch.region.name }}</span>
</td>
<td>
{{ $t(`falukant.overview.branches.level.${branch.branchType.labelTr}`) }}
</td>
</tr> </tr>
</table> </table>
</div> </div>
@@ -48,8 +88,9 @@
</template> </template>
<script> <script>
import apiClient from '@/utils/axios.js';
import StatusBar from '@/components/falukant/StatusBar.vue'; import StatusBar from '@/components/falukant/StatusBar.vue';
import apiClient from '@/utils/axios.js';
import { mapState } from 'vuex';
const AVATAR_POSITIONS = { const AVATAR_POSITIONS = {
male: { male: {
@@ -90,26 +131,18 @@ const AVATAR_POSITIONS = {
export default { export default {
name: 'FalukantOverviewView', name: 'FalukantOverviewView',
data() {
return {
falukantUser: null,
};
},
components: { components: {
StatusBar, StatusBar,
}, },
async mounted() { data() {
await this.fetchFalukantUser(); return {
if (this.socket) { falukantUser: null,
this.socket.on("falukantUserUpdated", this.fetchFalukantUser); allStock: [],
} productions: [],
}, };
beforeUnmount() {
if (this.socket) {
this.socket.off("falukantUserUpdated", this.fetchFalukantUser);
}
}, },
computed: { computed: {
...mapState(['daemonSocket']),
getAvatarStyle() { getAvatarStyle() {
if (!this.falukantUser) return {}; if (!this.falukantUser) return {};
const { gender, age } = this.falukantUser.character; const { gender, age } = this.falukantUser.character;
@@ -128,6 +161,38 @@ export default {
}; };
}, },
}, },
async mounted() {
await this.fetchFalukantUser();
await this.fetchAllStock();
await this.fetchProductions();
if (this.socket) {
this.socket.on("falukantUserUpdated", this.fetchFalukantUser);
this.socket.on("production_ready", this.handleProductionReadyEvent);
}
if (this.daemonSocket) {
this.daemonSocket.addEventListener('message', (event) => {
console.log('incoming event', event);
try {
if (event.data === "ping") return;
const message = JSON.parse(event.data);
if (message.event === 'production_ready') {
this.handleProductionReadyEvent(message);
}
} catch (error) {
console.error('Error processing WebSocket message in FalukantOverviewView:', error);
}
});
}
},
beforeUnmount() {
if (this.socket) {
this.socket.off("falukantUserUpdated", this.fetchFalukantUser);
this.socket.off("production_ready", this.handleProductionReadyEvent);
}
if (this.daemonSocket) {
this.daemonSocket.onmessage = null;
}
},
methods: { methods: {
getAgeGroup(age) { getAgeGroup(age) {
if (age <= 1) return "0-1"; if (age <= 1) return "0-1";
@@ -150,9 +215,41 @@ export default {
} }
this.falukantUser = falukantUser.data; this.falukantUser = falukantUser.data;
}, },
async fetchAllStock() {
const response = await apiClient.get('/api/falukant/stockoverview');
const rawData = response.data;
const aggregated = {};
for (const item of rawData) {
const key = `${item.regionName}__${item.productLabelTr}`;
if (!aggregated[key]) {
aggregated[key] = {
regionName: item.regionName,
productLabelTr: item.productLabelTr,
quantity: 0,
};
}
aggregated[key].quantity += item.quantity;
}
this.allStock = Object.values(aggregated);
},
handleProductionReadyEvent() {
this.fetchAllStock();
this.fetchProductions();
},
openBranch(branchId) { openBranch(branchId) {
this.$router.push({ name: 'BranchView', params: { branchId: branchId } }); this.$router.push({ name: 'BranchView', params: { branchId } });
} },
async fetchProductions() {
try {
const response = await apiClient.get('/api/falukant/productions');
this.productions = response.data;
} catch (error) {
console.error('Error fetching productions:', error);
}
},
formatDate(timestamp) {
return new Date(timestamp).toLocaleString();
},
}, },
}; };
</script> </script>