bourse/api/shares.js
2024-12-18 09:39:20 +01:00

77 lines
2.4 KiB
JavaScript

const express = require('express');
const router = express.Router();
const { getConnection, getShares, getShare, getShareholder, setShareOwner, addTransaction, getCompany, addShare, setCompanyCapital, setShareholderCapital } = require("../libs/mysql.js")
router.get('/', async (req, res) => {
const connection = await getConnection()
const shares = await getShares(connection)
connection.end()
if (!shares[0]) {
return res.status(500).send({message: "There are no shares in the databse."})
}
return res.status(200).send(shares)
});
router.get('/:id', async (req, res) => {
const id = req.params.id
const connection = await getConnection()
const share = await getShare(connection, id)
connection.end()
if (!share[0]) {
return res.status(500).send({message: "There are no share for that id."})
}
return res.status(200).send(share)
});
router.post('/buy', async (req, res) => {
const { buyer_id, share_id, price } = req.body
const connection = await getConnection()
const share = await getShare(connection, share_id)
const shareholder = await getShareholder(connection, buyer_id)
if (!share[0]) {
return res.status(500).send({message: "There are no share for that id."})
}
if (!shareholder[0]) {
return res.status(500).send({message: "There are no shareholder for that id."})
}
if (share[0].owner_id == buyer_id) {
return res.status(500).send({message: "This shareholder already owns that share."})
}
await addTransaction(connection, price, share[0].owner_id, buyer_id, share_id)
await setShareOwner(connection, share_id, buyer_id)
if (share[0].owner != -1) {
const seller = await getShareholder(connection, share[0].owner_id)
await setShareholderCapital(connection, share[0].owner_id, seller[0].capital + price)
}
await setShareholderCapital(connection, buyer_id, shareholder[0].capital - price)
connection.end()
return res.status(200).send({ message: "Success." })
});
router.post('/emit', async (req, res) => {
const { company_id, price } = req.body
const connection = await getConnection()
const company = await getCompany(connection, company_id)
if (!company[0]) {
return res.status(500).send({message: "There are no company for that id."})
}
await addShare(connection, price, company_id)
await setCompanyCapital(connection, company_id, company[0].capital + price)
connection.end()
return res.status(200).send({ message: "Success." })
});
module.exports = router;