Remove cash

This commit is contained in:
Nikola Petrov 2024-11-01 15:33:15 +01:00
parent ea3167981c
commit 0727d5f71a
8 changed files with 1 additions and 369 deletions

View File

@ -7,7 +7,7 @@ async function build() {
} }
const sa = await Bun.build({ const sa = await Bun.build({
entrypoints: ["./frontend/cash/cash", "./frontend/list/list"], entrypoints: ["./frontend/list/list"],
outdir: "./public/assets/build/", outdir: "./public/assets/build/",
minify, minify,
}) })

View File

@ -1,97 +0,0 @@
import { type Request, type Response } from "express";
import cashTransactionModel from '../models/cashTransactionModel';
const types = ['ZAVRNITEV POS NAKUP', 'POS NAKUP', 'BA DVIG', 'priliv', 'SDD', 'SPLET/TEL NAKUP', 'PREDAVTORIZACIJE'];
// TODO hendel this PREDAVTORIZACIJA
export default {
list: async function (req: Request, res: Response) {
try {
var transactions;
const date = req.body.date;
if (date) {
const splitDate = date.split('-');
var year = splitDate[0];
var month = splitDate[1];
year = parseInt(year);
month = parseInt(month);
transactions = await cashTransactionModel.findWithPar(year, month);
} else {
transactions = await cashTransactionModel.find();
}
const data = { transactions: transactions, types: types };
return res.json(data);
} catch (err) {
return res.status(500).json({
message: 'Error when getting transactions.',
error: err
});
};
},
create: async function (req: Request, res: Response) {
const rawString = req.body.messageBody;
if (rawString == "") return res.status(400).json({ message: "empty string" });
const transaction = {
rawMessage: rawString,
day: 0,
month: 0,
year: 0,
amount: 0,
type: -1,
company: "",
};
const datePattern = /(0[1-9]|[12][0-9]|3[01])\.(0[1-9]|1[0-2])\.(19|20)\d{2}/;
const amountPattern = /\d{1,3}(?:[.]\d{3})*(?:[.,]\d{2})(?=\sEUR)/;
const companyPattern1 = /(?<=(UR,|\sod)\s).*?(?=\s(na\s|za\s|Inf))/;
for (var i = 0; i < types.length; i++) {
if (rawString.includes(types[i])) {
transaction.type = i;
break;
}
}
if (transaction.type != -1) {
const amountMatch = rawString.match(amountPattern);
if (amountMatch) {
const amount = amountMatch[0].replace('.', '').replace(',', '.');
transaction.amount = parseFloat(amount);
}
const companyMatch1 = rawString.match(companyPattern1);
if (companyMatch1) transaction.company = companyMatch1[0];
const dateMatch = rawString.match(datePattern);
if (dateMatch) {
const date = dateMatch[0].split('.');
transaction.day = date[0];
transaction.month = date[1];
transaction.year = date[2];
}
}
const trans = await cashTransactionModel.save(transaction.rawMessage, transaction.day, transaction.month, transaction.year, transaction.amount, transaction.type, transaction.company);
if (trans) {
return res.status(201).json(trans);
}
else {
return res.status(400).json({ message: "something went wrong" });
}
},
delete: async function (req: Request, res: Response) {
cashTransactionModel.findOneAndDelete(-1)
.then(data => {
res.status(201).json({ message: "OK" });
});
},
};

View File

@ -1,116 +0,0 @@
import Chart from 'chart.js/auto'
import * as elements from "frontend/elementcreate";
interface Transaction {
day: number;
month: number;
year: number;
amount: number;
type: number;
company: string;
}
var types: Array<string> = [];
async function submitMedia(event: SubmitEvent) {
event.preventDefault();
const pass = document.getElementById("pass") as HTMLInputElement | null;
const date = document.getElementById("date") as HTMLInputElement | null;
if (!pass || !date) return;
if (pass.value == "") return;
try {
const result = await fetch('/api/cash/list', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ pass: pass.value, date: date.value }),
})
const data: { types: string[]; transactions: Array<Transaction>; } = await result.json();
types = data.types;
renderData(data.transactions);
renderChart(data.transactions);
} catch (e) {
console.log(e);
}
pass.value = "";
};
document.addEventListener('DOMContentLoaded', async () => {
document.getElementById("myform")?.addEventListener("submit", submitMedia);
});
function renderChart(transactions: Array<Transaction>) {
const cash = [];
for (let index = 0; index < 7; index++) {
cash.push(0);
}
for (let index = 0; index < transactions.length; index++) {
const element = transactions[index];
const type = element.type;
const amount = element.amount;
if (type == -1) continue;
cash[type] += amount;
}
var data = {
labels: types,
datasets: [{
label: '',
data: cash
}]
};
var ctx = document.getElementById('acquisitions') as HTMLCanvasElement | null;
if (ctx == null) return;
new Chart(
ctx,
{
type: 'pie',
data: data,
}
);
};
function getTypeName(type: number) {
if (type == -1) return "UNKNOWN";
return types[type];
}
function renderData(transactions: Array<Transaction>) {
var tbody = document.getElementById("tbody");
if (tbody == null) return;
tbody.innerHTML = "";
transactions
.sort((a, b) => a.day - b.day)
.sort((a, b) => a.month - b.month)
.sort((a, b) => a.year - b.year);
for (let index = 0; index < transactions.length; index++) {
const element = transactions[index];
var row =
<tr>
<th scope="row">{index}</th>
<td>{element.day}</td>
<td>{element.month}</td>
<td>{element.year}</td>
<td>{element.amount}</td>
<td>{getTypeName(element.type)}</td>
<td>{element.company}</td>
</tr>
tbody.appendChild(row);
}
};

View File

@ -1,69 +0,0 @@
import { type ResultSetHeader, type RowDataPacket, type QueryOptions } from "mysql2"
import pool from 'miscellaneous/db'
interface CashTransaction extends RowDataPacket {
id?: number;
rawMessage?: string;
day?: number;
month?: number;
year?: number;
amount?: number;
type?: number;
company?: string;
}
async function save(rawMessage: string, day: number, month: number, year: number, amount: number, type: number, company: string): Promise<number> {
try {
const options: QueryOptions = {
sql: "INSERT INTO bankCardTransaction (raw, day, month, year, amount, type, company) VALUES (?,?,?,?,?,?,?)",
values: [rawMessage, day, month, year, amount, type, company]
};
const [result, fields] = await pool.query<ResultSetHeader>(options);
return result.affectedRows;
}
catch (err) {
console.log(err);
}
return 0;
}
async function find(): Promise<CashTransaction[]> {
try {
const [rows, fields] = await pool.query<CashTransaction[]>("SELECT * FROM bankCardTransaction;");
return rows;
}
catch (err) {
console.log(err);
}
return [];
}
async function findWithPar(month: number, year: number): Promise<CashTransaction[]> {
try {
const [rows, fields] = await pool.query<CashTransaction[]>("SELECT * FROM bankCardTransaction;");
return rows;
}
catch (err) {
console.log(err);
}
return [];
}
async function findOneAndDelete(type: number): Promise<number> {
try {
const [result, fields] = await pool.query<ResultSetHeader>("DELETE FROM bankCardTransaction WHERE type = ?;", [type]);
return result.affectedRows;
}
catch (err) {
console.log(err);
}
return 0;
}
export default {
find,
findWithPar,
save,
findOneAndDelete
};

View File

@ -1,12 +1,10 @@
import express, { type Request, type Response } from "express"; import express, { type Request, type Response } from "express";
import checkAuthenticated from 'miscellaneous/checkAuthenticated'; import checkAuthenticated from 'miscellaneous/checkAuthenticated';
import mediaRouter from 'routes/api/mediaRouter'; import mediaRouter from 'routes/api/mediaRouter';
import cashTransactionRouter from 'routes/api/cashTransactionRouter';
const router = express.Router(); const router = express.Router();
router.use('/media', mediaRouter); router.use('/media', mediaRouter);
router.use('/cash', checkAuthenticated, cashTransactionRouter);
router.get('/', function (req: Request, res: Response) { router.get('/', function (req: Request, res: Response) {
res.status(200).json({ message: 'API is working' }); res.status(200).json({ message: 'API is working' });

View File

@ -1,12 +0,0 @@
import express from "express";
import cashTransaction from '../../controllers/cashTransactionController';
const router = express.Router();
router.post('/list', cashTransaction.list);
router.post('/', cashTransaction.create);
router.delete('/', cashTransaction.delete);
export default router;

View File

@ -24,10 +24,6 @@ router.get('/list', function (req: Request, res: Response) {
res.render('list'); res.render('list');
}); });
router.get('/cash', function (req: Request, res: Response) {
res.render('cash');
});
//import userRouter from './user'; //import userRouter from './user';
//router.use('/user', userRouter); //router.use('/user', userRouter);

View File

@ -1,68 +0,0 @@
<!doctype html>
<html lang="en" data-bs-theme="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="images/logo.ico" type="image/x-icon">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL"
crossorigin="anonymous"></script>
<title>Cash</title>
<script type="module" src="/assets/build/cash/cash.js"></script>
</head>
<body>
<header>
<nav class="navbar navbar-expand-md navbar-dark bg-dark">
<div class="container-fluid">
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<form class="d-flex" action="" id="myform">
<input class="form-control me-2" type="date" name="date" id="date" placeholder="date">
<input class="form-control me-2" type="password" name="password" id="pass" placeholder="password">
<input class="btn btn-outline-success" type="submit" value="Submit">
</form>
</div>
</div>
</nav>
</header>
<main class="bg-body-tertiary pt-5 pb-5">
<div class="container position-relative">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Day</th>
<th scope="col">Month</th>
<th scope="col">Year</th>
<th scope="col">Amount</th>
<th scope="col">Type</th>
<th scope="col">Company</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
<div class="row">
<div class="w-50 mx-auto"><canvas id="acquisitions"></canvas></div>
</div>
</div>
</main>
</body>
</html>