Merge pull request 'Rollback to master' (#3) from rollback_to_master into master

Reviewed-on: #3
This commit was merged in pull request #3.
This commit is contained in:
2026-10-15 14:37:29 +01:00
51 changed files with 1276 additions and 1521 deletions
+4
View File
@@ -0,0 +1,4 @@
PGDATA=/var/lib/postgresql/data
POSTGRES_USER=expdbuser
POSTGRES_PASSWORD=expDBPass
POSTGRES_DB=expenses
+12
View File
@@ -13,6 +13,18 @@ build_release_alpine:
mkdir -p $(build)/data/ mkdir -p $(build)/data/
find $(build) -name "*.ttf" ! -name DejaVuSansMono.ttf -delete find $(build) -name "*.ttf" ! -name DejaVuSansMono.ttf -delete
devdb_start:
podman compose up database --force-recreate
devdb_clear:
podman compose down -v database
devdb_status:
podman compose stats database
devdb_stop:
podman compose stop database
build_image: build_release_alpine build_image: build_release_alpine
docker buildx build -t $(registry)/$(repo)/expensesweb:$(tag) . docker buildx build -t $(registry)/$(repo)/expensesweb:$(tag) .
+37 -5
View File
@@ -27,17 +27,17 @@
@keyframes flicker { @keyframes flicker {
0% { 0% {
opacity: 1.1; opacity: 0.9;
} }
20% { 20% {
opacity: 0.9;
}
40% {
opacity: 1.1; opacity: 1.1;
} }
60% { 40% {
opacity: 0.9; opacity: 0.9;
} }
60% {
opacity: 1;
}
80% { 80% {
opacity: 1; opacity: 1;
} }
@@ -302,6 +302,35 @@ code {
color: var(--url-color); color: var(--url-color);
} }
.table-container {
overflow-x: auto;
width: 0;
min-width: 100%;
}
.table-container table {
min-width: max-content;
border-collapse: collapse;
}
.table-container th {
border-bottom: 2px solid var(--text-color);
padding: 2px 4px;
}
.table-container td {
padding: 2px 4px;
}
.table-container th:not(:last-child),
.table-container td:not(:last-child) {
border-right: 1px solid var(--text-color);
}
.table-container tr.negative-row {
background-color: var(--warning-color);
}
/* CSS for centering images */ /* CSS for centering images */
.centeredImgContainer { .centeredImgContainer {
max-width: 80%; max-width: 80%;
@@ -344,6 +373,7 @@ dt {
} }
#container { #container {
max-width: 100%;
width: 100%; width: 100%;
margin: auto; margin: auto;
display: flex; display: flex;
@@ -369,6 +399,8 @@ dt {
} }
.main-container-content { .main-container-content {
width: 100%;
max-width: 100%;
height: 100%; height: 100%;
overflow-y: auto; overflow-y: auto;
/* IE and Edge */ /* IE and Edge */
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sourceRoot":"","sources":["crt.scss","expensesTable.scss","forms.scss","modals.scss","main.scss"],"names":[],"mappings":";AAMA;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EAGA;EACA;EACA;;;AAGF;EACE;EACA;EACA;EACA;EAIA;EACA;EACA;EACA;EAEA;;;AAGF;EAII;IACE;;EADF;IACE;;EADF;IACE;;EADF;IACE;;EADF;IACE;;EADF;IACE;;;AAKN;EACE;IACE;;;AAIJ;EACE;IACE;;EAGF;IACE;;EAGF;IACE;;;AAIJ;EACE;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;;ACtJJ;EACE;EACA;EACA;;;AAGF;EACE;;;ACPF;EACE;;;AAGF;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EAEA;EACA;EACA;EACA;;;AAGF;EACE;EACA;EACA;EACA;EACA;;;AAGF;EACE;EACA;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;EACA;EACA;EACA;EACA;EACA;;;AAGF;EACE;EACA;;;AAGF;AAAA;EAEE;EACA;;;AC1DF;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;AAGF;EACE;;;AAGF;EACE;EACA;EACA;EACA;;;AAGF;EACE;EACA;;;ACnBF;EACE;EACA;EACA;EACA;EACA;EACA;EACA;;;AAGF;EACE;EACA;;AAGF;EACE;EACA;EACA;EAEA;EAEA;EACA;AAEA;EACA;EACA;;;AAGF;EACE;EACA;EACA;EAEA;EAEA;;;AAGF;EACE;;;AAGF;EACE;EACA;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;EACA;;;AAGF;EACE;EACA;;;AAGF;EACE;;;AAGF;EACE;EACA;;;AAGF;EACE;EACA;EACA;EACA;EACA;EACA;;;AAGF;AACA;EACE;EACA;EACA;;;AAGF;EACE;EACA;EACA;EACA;;;AAGF;AAEA;EACE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;AAAA;EAEE;EACA,aACE;;;AAGJ;EACE;;;AAGF;EACE;EACA;EAEA;EACA;;;AAGF;AACE;EACA;EACA;EACA;EACA;EACA;AAEA;EACA;EACA;EACA;EACA;EAEA;EACA;EAEA;EAEA;;;AAGF;EACE;EAEA;AAEA;EACA;AACA;EACA;EAEA;;;AAGF;EACE;;;AAGF;EACE;EACA;;;AAGF;EACE;EACA;;;AAGF;EACE;EACA;;;AAGF;AACA;AACA;AACA;EACE;;;AAGF;EACE;;;AAGF;EACE;EACA;;;AAGF;EACE;;;AAGF;EACE;IACE;;;AAIJ;EACE;;;AAGF;EACE;EAGA;EACA","file":"aesthetic.css"} {"version":3,"sourceRoot":"","sources":["crt.scss","expensesTable.scss","forms.scss","modals.scss","main.scss"],"names":[],"mappings":";AAMA;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EAGA;EACA;EACA;;;AAGF;EACE;EACA;EACA;EACA;EAIA;EACA;EACA;EACA;EAEA;;;AAGF;EAII;IACE;;EADF;IACE;;EADF;IACE;;EADF;IACE;;EADF;IACE;;EADF;IACE;;;AAKN;EACE;IACE;;;AAIJ;EACE;IACE;;EAGF;IACE;;EAGF;IACE;;;AAIJ;EACE;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;;ACtJJ;EACE;EACA;EACA;;;AAGF;EACE;;;ACPF;EACE;;;AAGF;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EAEA;EACA;EACA;EACA;;;AAGF;EACE;EACA;EACA;EACA;EACA;;;AAGF;EACE;EACA;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;EACA;EACA;EACA;EACA;EACA;;;AAGF;EACE;EACA;;;AAGF;AAAA;EAEE;EACA;;;AC1DF;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;AAGF;EACE;;;AAGF;EACE;EACA;EACA;EACA;;;AAGF;EACE;EACA;;;ACnBF;EACE;EACA;EACA;EACA;EACA;EACA;EACA;;;AAGF;EACE;EACA;;AAGF;EACE;EACA;EACA;EAEA;EAEA;EACA;AAEA;EACA;EACA;;;AAGF;EACE;EACA;EACA;EAEA;EAEA;;;AAGF;EACE;;;AAGF;EACE;EACA;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;EACA;;;AAGF;EACE;EACA;;;AAGF;EACE;;;AAGF;EACE;EACA;;;AAGF;EACE;EACA;EACA;EACA;EACA;EACA;;;AAIF;EACE;EACA;EACA;;;AAGF;EACE;EACA;;;AAGF;EACE;EACA;;;AAGF;EACE;;;AAGF;AAAA;EAEE;;;AAGF;EACE;;;AAIF;AACA;EACE;EACA;EACA;;;AAGF;EACE;EACA;EACA;EACA;;;AAGF;AAEA;EACE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;AAAA;EAEE;EACA,aACE;;;AAGJ;EACE;;;AAGF;EACE;EACA;EACA;EAEA;EACA;;;AAGF;AACE;EACA;EACA;EACA;EACA;EACA;AAEA;EACA;EACA;EACA;EACA;EAEA;EACA;EAEA;EAEA;;;AAGF;EACE;EACA;EACA;EAEA;AAEA;EACA;AACA;EACA;EAEA;;;AAGF;EACE;;;AAGF;EACE;EACA;;;AAGF;EACE;EACA;;;AAGF;EACE;EACA;;;AAGF;AACA;AACA;AACA;EACE;;;AAGF;EACE;;;AAGF;EACE;EACA;;;AAGF;EACE;;;AAGF;EACE;IACE;;;AAIJ;EACE;;;AAGF;EACE;EAGA;EACA","file":"aesthetic.css"}
+34
View File
@@ -88,6 +88,37 @@ code {
color: var(--url-color); color: var(--url-color);
} }
// Table stuff
.table-container {
overflow-x: auto;
width: 0;
min-width: 100%;
}
.table-container table {
min-width: max-content;
border-collapse: collapse;
}
.table-container th {
border-bottom: 2px solid var(--text-color);
padding: 2px 4px;
}
.table-container td {
padding: 2px 4px;
}
.table-container th:not(:last-child),
.table-container td:not(:last-child) {
border-right: 1px solid var(--text-color);
}
.table-container tr.negative-row {
background-color: var(--warning-color);
}
// End of table stuff
/* CSS for centering images */ /* CSS for centering images */
.centeredImgContainer { .centeredImgContainer {
max-width: 80%; max-width: 80%;
@@ -132,6 +163,7 @@ dt {
} }
#container { #container {
max-width: 100%;
width: 100%; width: 100%;
margin: auto; margin: auto;
@@ -162,6 +194,8 @@ dt {
} }
.main-container-content { .main-container-content {
width: 100%;
max-width: 100%;
height: 100%; height: 100%;
overflow-y: auto; overflow-y: auto;
+10 -112
View File
@@ -1,115 +1,13 @@
{{ define "analysis" }} {{ define "analysis" }}
<div> <ol>
<canvas id="monthlyTotal"></canvas> <li>
</div> <button
hx-post="/filtered-analysis"
<div> hx-target="#content"
<canvas id="monthlyBalance"></canvas> hx-swap="innerHTML"
</div> hx-replace-url="true"
id="overview">FILTERED ANALYSIS</button>
<script src="/assets/js/chart.js"></script> </li>
<script src="/assets/js/chartjs-plugin-datalabels.js"></script> </ol>
<script>
const mBalanceChart = document.getElementById('monthlyBalance');
const monthlyBalanceData = {{ .plotData.mBalance | toJson }};
const labels = monthlyBalanceData.map(entry =>
new Date(2000, entry.month, 1).toLocaleString('en', {month: 'short'})
);
const values = monthlyBalanceData.map(entry => Number(entry.total));
// TODO - make the fucking folds work
new Chart(mBalanceChart, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Monthly Balance',
data: values,
backgroundColor: (ctx) => {
const value = ctx.raw; // the data point value
return value < 0 ? 'rgb(231 144 234 / 50%)' : 'rgb(67 149 84 / 50%)';
},
borderColor: (ctx) => {
const value = ctx.raw;
return value < 0 ? 'rgb(231 144 234 / 100%)' : 'rgb(67 149 84 / 100%)';
},
borderWidth: 1
}]
},
options: {
plugins: {
datalabels: {
// anchor: (ctx) => ctx.raw > 0 ? 'start' : 'end', // below bar for negative
// align: (ctx) => ctx.raw > 0 ? 'end' : 'start',
anchor: "end",
align: "end",
formatter: (value) => value,
color: (context) => {
const value = context.dataset.data[context.dataIndex];
return value < 0 ? 'rgb(231 144 234 / 100%)' : 'rgb(67 149 84 / 100%)';
},
font: {
weight: 'bold'
}
}
},
scales: {
y: {beginAtZero: true}
}
},
plugins: [ChartDataLabels]
});
// Total Chart
const mTotalChart = document.getElementById('monthlyTotal');
const mTotalData = {{ .plotData.mTotal | toJson }};
const mTotalLabels = mTotalData.map(entry =>
new Date(2000, entry.month, 1).toLocaleString('en', {month: 'short'})
);
const mTotalValues = mTotalData.map(entry => Number(entry.total));
new Chart(mTotalChart, {
type: 'line',
data: {
labels: mTotalLabels,
datasets: [{
label: 'Monthly Total',
data: mTotalValues,
backgroundColor: (ctx) => {
const value = ctx.raw; // the data point value
return value < 0 ? 'rgb(231 144 234 / 50%)' : 'rgb(67 149 84 / 50%)';
},
borderColor: (ctx) => {
const value = ctx.raw;
return value < 0 ? 'rgb(231 144 234 / 100%)' : 'rgb(67 149 84 / 100%)';
},
borderWidth: 1
}]
},
options: {
plugins: {
datalabels: {
// anchor: (ctx) => ctx.raw > 0 ? 'start' : 'end', // below bar for negative
// align: (ctx) => ctx.raw > 0 ? 'end' : 'start',
anchor: "end",
align: "end",
formatter: (value) => value,
color: (context) => {
const value = context.dataset.data[context.dataIndex];
return value < 0 ? 'rgb(231 144 234 / 100%)' : 'rgb(67 149 84 / 100%)';
},
font: {
weight: 'bold'
}
}
},
scales: {
y: {beginAtZero: true}
}
},
plugins: [ChartDataLabels]
});
</script>
{{ end }} {{ end }}
+44
View File
@@ -0,0 +1,44 @@
{{ define "analysis-filtered" }}
<form
hx-get="/filtered-analysis/filters"
hx-target="#filtered-analysis"
hx-swap="innerHTML"
>
<p>
<label for="range-start">Start date:</label>
<input
class="tui-input underline fullwidth" type="text" name="range-start"
value="" id="expense-date"><br>
</p>
<p>
<label for="range-end">End date:</label>
<input
class="tui-input underline fullwidth" type="text" name="range-end"
value="" id="expense-date"><br>
</p>
<button type="submit" id="expenses">QUERY</button>
</form>
<div id="filtered-analysis">
</div>
<!-- <div> -->
<!-- <canvas id="monthlyTotal"></canvas> -->
<!-- </div> -->
<!---->
<!-- <div> -->
<!-- <canvas id="monthlyBalance"></canvas> -->
<!-- </div> -->
<!---->
<!-- <script> -->
<!-- <!-- Inject go data here -->
<!-- window.analysisBalanceData = {{ .plotData.mBalance | toJson }}; -->
<!-- window.analysisTotalData = {{ .plotData.mTotal | toJson }}; -->
<!-- </script> -->
<!---->
<!-- <script src="/assets/js/analysis.js"></script> -->
{{ end }}
@@ -0,0 +1,54 @@
{{ define "analysis-filtered-results" }}
<fieldset>
<legend>MONTHLY SUMMARY</legend>
<!-- <div style="overflow-x: auto; width: 0; min-width: 100%;"> -->
<div class="table-container">
<table>
<thead>
<tr>
<th>Month</th>
<th>Despesa</th>
<th>Salário</th>
<th>Cartão Refeição</th>
<th>Reembolso</th>
<th>Prenda</th>
<th>Investment</th>
<th>Adjustment</th>
<th>Adjustment Liquid</th>
<th>Poupança</th>
<th>Poupança Liquid</th>
<th>Running Balance</th>
<th>Running Balance Liquid</th>
</tr>
</thead>
<tbody>
{{ range . }}
<tr {{ if .PoupancaLiquid.IsNegative }}class="negative-row"{{ end }}>
<td>{{ .MonthYear }}</td>
<td>{{ .Despesa }}</td>
<td>{{ .Salario }}</td>
<td>{{ .CartaoRefeicao }}</td>
<td>{{ .Reembolso }}</td>
<td>{{ .Prenda }}</td>
<td>{{ .Investment }}</td>
<td>{{ .Adjustment }}</td>
<td>{{ .AdjustmentLiquid }}</td>
<td>{{ .Poupanca }}</td>
<td>{{ .PoupancaLiquid }}</td>
<td>{{ .RunningBalance }}</td>
<td>{{ .RunningBalanceLiquid }}</td>
</tr>
{{ else }}
<tr>
<td colspan="13" class="text-center text-muted">No monthly summary data available.</td>
</tr>
{{ end }}
</tbody>
</table>
</div>
</fieldset>
<fieldset>
<legend>PERIOD AVERAGES</legend>
</fieldset>
{{ end }}
+22 -20
View File
@@ -1,22 +1,24 @@
{{ define "expensesTable" }} {{ define "expensesTable" }}
<table id="expenses-table"> <div class="table-container">
<tr> <table id="expenses-table">
<th>ID</th> <tr>
<th>OWNER</th> <th>ID</th>
<th>DESC</th> <th>OWNER</th>
<th>PRICE</th> <th>DESC</th>
<th>DATE</th> <th>PRICE</th>
<th>Category</th> <th>DATE</th>
</tr> <th>Category</th>
{{ range .expenses }} </tr>
<tr> {{ range .expenses }}
<th><a href="/expenses/{{ .ExpID }}">{{ .ExpID }}</th> <tr>
<th spellcheck="false">{{ .Owner.UserName }}</th> <th><a href="/expenses/{{ .ExpID }}">{{ .ExpID }}</th>
<th spellcheck="false">{{ .Description }}</th> <th spellcheck="false">{{ .Owner.UserName }}</th>
<th spellcheck="false">{{ formatPrice .Value }}</th> <th spellcheck="false">{{ .Description }}</th>
<th spellcheck="false">{{ formatDate .Date }}</th> <th spellcheck="false">{{ formatPrice .Value }}</th>
<th spellcheck="false">{{ .Category.CategoryName }}</th> <th spellcheck="false">{{ formatDate .Date }}</th>
</tr> <th spellcheck="false">{{ .Category.CategoryName }}</th>
{{ end }} </tr>
</table> {{ end }}
</table>
</div>
{{ end }} {{ end }}
+3
View File
@@ -1,4 +1,7 @@
{{ define "mainPage" }} {{ define "mainPage" }}
{{ template "expensesFilterBox" . }} {{ template "expensesFilterBox" . }}
<br>
Table
<br>
{{ template "expensesTable" . }} {{ template "expensesTable" . }}
{{ end }} {{ end }}
+2
View File
@@ -70,6 +70,8 @@
{{ template "overview" . }} {{ template "overview" . }}
{{ else if eq .content "analysis" }} {{ else if eq .content "analysis" }}
{{ template "analysis" . }} {{ template "analysis" . }}
{{ else if eq .content "analysis-filtered" }}
{{ template "analysis-filtered" . }}
{{ else if eq .content "stores" }} {{ else if eq .content "stores" }}
{{ template "stores" . }} {{ template "stores" . }}
{{ else if eq .content "store" }} {{ else if eq .content "store" }}
+125
View File
@@ -0,0 +1,125 @@
(function() {
function loadScript(src, callback) {
if (window.Chart && src.includes('chart.js')) {
callback();
return;
}
if (document.querySelector(`script[src="${src}"]`)) {
if (window.Chart) {
callback();
} else {
const existingScript = document.querySelector(`script[src="${src}"]`);
existingScript.addEventListener('load', callback);
}
return;
}
const script = document.createElement('script');
script.src = src;
script.onload = callback;
document.head.appendChild(script);
}
// Load Chart.js first, then the plugin, then render charts
loadScript('/assets/js/chart.js', function() {
loadScript('/assets/js/chartjs-plugin-datalabels.js', function() {
renderAnalysisCharts();
});
});
function renderAnalysisCharts() {
// Read the global data injected by the HTML template
const monthlyBalanceData = window.analysisBalanceData || [];
const mTotalData = window.analysisTotalData || [];
// --- Monthly Balance Chart ---
const mBalanceChart = document.getElementById('monthlyBalance');
const labels = monthlyBalanceData.map(entry =>
new Date(2000, entry.month, 1).toLocaleString('en', {month: 'short'})
);
const values = monthlyBalanceData.map(entry => Number(entry.total));
new Chart(mBalanceChart, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Monthly Balance',
data: values,
backgroundColor: (ctx) => {
const value = ctx.raw;
return value < 0 ? 'rgb(231 144 234 / 50%)' : 'rgb(67 149 84 / 50%)';
},
borderColor: (ctx) => {
const value = ctx.raw;
return value < 0 ? 'rgb(231 144 234 / 100%)' : 'rgb(67 149 84 / 100%)';
},
borderWidth: 1
}]
},
options: {
plugins: {
datalabels: {
anchor: "end",
align: "end",
formatter: (value) => value,
color: (context) => {
const value = context.dataset.data[context.dataIndex];
return value < 0 ? 'rgb(231 144 234 / 100%)' : 'rgb(67 149 84 / 100%)';
},
font: { weight: 'bold' }
}
},
scales: {
y: { beginAtZero: true }
}
},
plugins: [ChartDataLabels]
});
// --- Total Chart ---
const mTotalChart = document.getElementById('monthlyTotal');
const mTotalLabels = mTotalData.map(entry =>
new Date(2000, entry.month, 1).toLocaleString('en', {month: 'short'})
);
const mTotalValues = mTotalData.map(entry => Number(entry.total));
new Chart(mTotalChart, {
type: 'line',
data: {
labels: mTotalLabels,
datasets: [{
label: 'Monthly Total',
data: mTotalValues,
backgroundColor: (ctx) => {
const value = ctx.raw;
return value < 0 ? 'rgb(231 144 234 / 50%)' : 'rgb(67 149 84 / 50%)';
},
borderColor: (ctx) => {
const value = ctx.raw;
return value < 0 ? 'rgb(231 144 234 / 100%)' : 'rgb(67 149 84 / 100%)';
},
borderWidth: 1
}]
},
options: {
plugins: {
datalabels: {
anchor: "end",
align: "end",
formatter: (value) => value,
color: (context) => {
const value = context.dataset.data[context.dataIndex];
return value < 0 ? 'rgb(231 144 234 / 100%)' : 'rgb(67 149 84 / 100%)';
},
font: { weight: 'bold' }
}
},
scales: {
y: { beginAtZero: true }
}
},
plugins: [ChartDataLabels]
});
}
})();
+5 -4
View File
@@ -2,6 +2,10 @@ package cmd
import ( import (
"encoding/json" "encoding/json"
"html/template"
"log"
"net/http"
"time"
"github.com/ESilva15/expenses/api" "github.com/ESilva15/expenses/api"
"github.com/ESilva15/expenses/config" "github.com/ESilva15/expenses/config"
@@ -14,11 +18,7 @@ import (
"github.com/shopspring/decimal" "github.com/shopspring/decimal"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"html/template"
"log"
"net/http"
fp "path/filepath" fp "path/filepath"
"time"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
@@ -73,6 +73,7 @@ func setRoutes(router *gin.RouterGroup, eng *gin.Engine) {
pages.RouteShares(router) pages.RouteShares(router)
pages.RouteOverview(router) pages.RouteOverview(router)
pages.RouteAnalysis(router) pages.RouteAnalysis(router)
pages.RouteAnalysisDashboard(router)
// This are for the engine, I really need to rethink this // This are for the engine, I really need to rethink this
pages.RouteLogin(eng) pages.RouteLogin(eng)
+4 -4
View File
@@ -2,9 +2,9 @@ assets: "./assets/"
port: 8081 port: 8081
postgres: postgres:
user: expdbuser user: expdbuser
pass: thepass pass: expDBPass
db: thedb db: expenses
host: /home/esilva/Desktop/projetos/expenses/src/pgImage/pgSocket/ host: "127.0.0.1"
port: 5432 port: 5431
migrationsPath: "file://expenses/repo/pgdb/migrations/" migrationsPath: "file://expenses/repo/pgdb/migrations/"
migCustomScripts: "./expenses/repo/pgdb/migrations/custom/" migCustomScripts: "./expenses/repo/pgdb/migrations/custom/"
+29
View File
@@ -0,0 +1,29 @@
# Database stuff
## Download a production database's data
```bash
docker exec -i <container-name> \
pg_dump -U <db-user> -a -d <database> > outputfile.sql
```
## Start a local development database
```bash
# Use to clean the volumens and kill the current running database
podman compose down -v database
# Use to recreate database
podman compose up database --force-recreate
# Alternatively, to down the service and clear it
make devdb_clear
# And to start it
make devdb_start
```
## Upload a database
```bash
# Don't forget to devdb_clear the current existing database
psql -h 127.0.0.1 -p 5431 -U expdbuser -d expenses -f ./data.sql
```
# CSS
Go to `assets/css` and run `sass --watch main.scss aesthetic.css`
+10
View File
@@ -0,0 +1,10 @@
services:
database:
image: docker.io/library/postgres:16
container_name: expenses-dev-db
hostname: expenses-dev-db
env_file:
- .pgenv
ports:
- "5431:5432"
restart: unless-stopped
+105 -23
View File
@@ -3,40 +3,43 @@ package expenses
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"log" "log"
"strings"
"github.com/ESilva15/expenses/config" "github.com/ESilva15/expenses/config"
"github.com/ESilva15/expenses/expenses/repo" "github.com/ESilva15/expenses/expenses/repo"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
lua "github.com/yuin/gopher-lua" lua "github.com/yuin/gopher-lua"
) )
// ExpApp is the data structure for the main runtime of this application. // ExpApp is the data structure for the main runtime of this application.
type ExpApp struct { type ExpApp struct {
Lua *lua.LState Lua *lua.LState
ExpRepo repo.ExpenseRepository FinancialRepo repo.FinancialRepository
CategoryRepo repo.CategoryRepository ExpRepo repo.ExpenseRepository
UserRepo repo.UserRepository CategoryRepo repo.CategoryRepository
StoreRepo repo.StoreRepository UserRepo repo.UserRepository
TypeRepo repo.TypeRepository StoreRepo repo.StoreRepository
TypeRepo repo.TypeRepository
} }
var ( // App provides access to the expenses main service.
// App provides access to the expenses main service. var App *ExpApp
App *ExpApp
)
// NewExpenseApp returns a new instance of our core App. // NewExpenseApp returns a new instance of our core App.
func NewExpenseApp(dbPool *pgxpool.Pool, luaVM *lua.LState) *ExpApp { func NewExpenseApp(dbPool *pgxpool.Pool, luaVM *lua.LState) *ExpApp {
return &ExpApp{ return &ExpApp{
ExpRepo: repo.NewPgExpRepo(dbPool), FinancialRepo: repo.NewPgFinancialRepo(dbPool),
CategoryRepo: repo.NewPgCatRepo(dbPool), ExpRepo: repo.NewPgExpRepo(dbPool),
UserRepo: repo.NewPgUserRepo(dbPool), CategoryRepo: repo.NewPgCatRepo(dbPool),
StoreRepo: repo.NewPgStoreRepo(dbPool), UserRepo: repo.NewPgUserRepo(dbPool),
TypeRepo: repo.NewPgTypeRepo(dbPool), StoreRepo: repo.NewPgStoreRepo(dbPool),
Lua: luaVM, TypeRepo: repo.NewPgTypeRepo(dbPool),
Lua: luaVM,
} }
} }
@@ -59,25 +62,73 @@ func getPgConnString(cfg *config.Configuration) string {
cfg.PgCfg.User, cfg.PgCfg.Pass, cfg.PgCfg.DB, cfg.PgCfg.Host, cfg.PgCfg.Port) cfg.PgCfg.User, cfg.PgCfg.Pass, cfg.PgCfg.DB, cfg.PgCfg.Host, cfg.PgCfg.Port)
} }
func createTargetDatabase(cfg *config.Configuration) error {
// Connect to the default 'postgres' database instead of cfg.PgCfg.DB
adminConnStr := fmt.Sprintf("postgres://%s:%s@/%s?host=%s&port=%s&sslmode=disable",
cfg.PgCfg.User, cfg.PgCfg.Pass, "postgres", cfg.PgCfg.Host, cfg.PgCfg.Port)
ctx := context.Background()
pool, err := pgxpool.New(ctx, adminConnStr)
if err != nil {
return fmt.Errorf("failed to connect to default postgres db: %w", err)
}
defer pool.Close()
// Execute CREATE DATABASE (Note: database identifiers cannot be parameterized with $1)
query := fmt.Sprintf("CREATE DATABASE %s", cfg.PgCfg.DB)
_, err = pool.Exec(ctx, query)
if err != nil {
return fmt.Errorf("failed to create database: %w", err)
}
log.Printf("Database %q created successfully!", cfg.PgCfg.DB)
return nil
}
func runMigrations(luaVM *lua.LState) error { func runMigrations(luaVM *lua.LState) error {
cfg := config.GetInstance() cfg := config.GetInstance()
pgStr := getPgConnString(cfg) pgStr := getPgConnString(cfg)
migrator, err := repo.NewPgMigrator(pgStr) migrator, err := repo.NewPgMigrator(pgStr)
if err != nil { if err != nil {
return err // Check if error is due to database not existing
if isDatabaseNotFoundError(err) {
log.Printf("Database %q does not exist. Creating it...", cfg.PgCfg.DB)
if createErr := createTargetDatabase(cfg); createErr != nil {
return fmt.Errorf("failed to create missing database: %w", createErr)
}
// Retry creating the migrator after the database is created
migrator, err = repo.NewPgMigrator(pgStr)
if err != nil {
return err
}
} else {
return err
}
} }
err = migrator.RunMigrations(luaVM) err = migrator.RunMigrations(luaVM)
if err != nil { if err != nil {
log.Fatalf("Failed to apply migrations: %v", err) migrator.Close()
return fmt.Errorf("failed to apply migrations: %w", err)
} }
migrator.Close() migrator.Close()
return nil return nil
} }
// Helper to check for PostgreSQL code "3D000" or text fallback
func isDatabaseNotFoundError(err error) bool {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "3D000" {
return true
}
// Fallback string check if wrapped differently by the repo layer
return strings.Contains(err.Error(), "does not exist")
}
// GoToMigration provides a way to force moving to the specified migration. // GoToMigration provides a way to force moving to the specified migration.
func (a *ExpApp) GoToMigration(id uint) error { func (a *ExpApp) GoToMigration(id uint) error {
cfg := config.GetInstance() cfg := config.GetInstance()
@@ -103,12 +154,43 @@ func createPGXPoolConn(ctx context.Context) (*pgxpool.Pool, error) {
var result int var result int
err = conn.QueryRow(ctx, "SELECT 1").Scan(&result) err = conn.QueryRow(ctx, "SELECT 1").Scan(&result)
if err != nil { if err != nil {
panic("connection test query failed: " + err.Error()) return nil, err
} }
return conn, nil return conn, nil
} }
func PrepareDB(ctx context.Context, luaVM *lua.LState) error {
// Attempt to prepare the database
err := runMigrations(luaVM)
if err != nil {
log.Fatalf("Unable to run migrations: %v", err)
}
return nil
}
func CheckDatabase(ctx context.Context, luaVM *lua.LState) error {
cfg := config.GetInstance()
pgStr := getPgConnString(cfg)
conn, err := pgxpool.New(ctx, pgStr)
if err != nil {
// Unable to create the database
return err
}
var result int
err = conn.QueryRow(ctx, "SELECT status,version FROM dbstat").Scan(&result)
if err != nil {
if err := PrepareDB(ctx, luaVM); err != nil {
return err
}
}
return nil
}
// StartApp will configure and open the required connections to run this app. // StartApp will configure and open the required connections to run this app.
func StartApp() error { func StartApp() error {
config.SetConfig("./config.yaml") config.SetConfig("./config.yaml")
@@ -120,13 +202,13 @@ func StartApp() error {
return err return err
} }
// Run the migrations // Run migrations (will automatically create the database if it doesn't exist)
err = runMigrations(luaVM) err = runMigrations(luaVM)
if err != nil { if err != nil {
log.Printf("Unable to run migrations: %v", err) log.Fatalf("Unable to run migrations: %v", err)
} }
// Create our final app thing // Create our final app pool connection
conn, err := createPGXPoolConn(ctx) conn, err := createPGXPoolConn(ctx)
if err != nil { if err != nil {
log.Fatalf("Failed to open DB: %v", err) log.Fatalf("Failed to open DB: %v", err)
+21
View File
@@ -0,0 +1,21 @@
package expenses
import (
"context"
mod "github.com/ESilva15/expenses/expenses/models"
)
func (a *ExpApp) GetMonthlySummary(
ctx context.Context,
filter *mod.Filter,
) ([]mod.MonthlySummary, error) {
return a.FinancialRepo.GetMonthlySummary(ctx, filter)
}
func (a *ExpApp) GetMonthlySavingsAverage(
ctx context.Context,
filter *mod.Filter,
) (mod.MonthlySavingsAverage, error) {
return a.FinancialRepo.GetMonthlySavingsAverage(ctx, filter)
}
+50
View File
@@ -0,0 +1,50 @@
package models
import (
"time"
dec "github.com/shopspring/decimal"
)
type MonthlySummary struct {
MonthYear string `json:"month_year"`
Despesa dec.Decimal `json:"despesa"`
Salario dec.Decimal `json:"salario"`
CartaoRefeicao dec.Decimal `json:"cartao_refeicao"`
Reembolso dec.Decimal `json:"reembolso"`
Prenda dec.Decimal `json:"prenda"`
Investment dec.Decimal `json:"investment"`
Adjustment dec.Decimal `json:"adjustment"`
AdjustmentLiquid dec.Decimal `json:"adjustment_liquid"`
Poupanca dec.Decimal `json:"poupanca"`
PoupancaLiquid dec.Decimal `json:"poupanca_liquid"`
RunningBalance dec.Decimal `json:"running_balance"`
RunningBalanceLiquid dec.Decimal `json:"running_balance_liquid"`
}
type MonthlySavingsAverage struct {
AvgPoupanca dec.Decimal `json:"avg_poupanca"`
AvgPoupancaLiquid dec.Decimal `json:"avg_poupanca_liquid"`
}
// ExpFilter has the fields required to query the database.
type Filter struct {
Start *time.Time // Start is the earliest an expense can be
End *time.Time // End is the latest an expense can be
UserIDs int32 // UserIDs is a list of IDs to match against
CatIDs []int32 // CatIDs is a list of categories to match against
StoreIDs []int32 // StoreIDs is a list of stores to match against
TypeIDs []int32 // TypeIDs is a list of types to match against
}
// NewExpFilter returns a newly initialized ExpFilter.
func NewFilter() Filter {
return Filter{
Start: nil,
End: nil,
UserIDs: -1,
CatIDs: nil,
StoreIDs: nil,
TypeIDs: nil,
}
}
+14
View File
@@ -0,0 +1,14 @@
package repo
import (
"context"
mod "github.com/ESilva15/expenses/expenses/models"
)
// CategoryRepository defines the repository for the category data model.
type FinancialRepository interface {
GetMonthlySummary(context.Context, *mod.Filter) ([]mod.MonthlySummary, error)
GetMonthlySavingsAverage(context.Context, *mod.Filter) (mod.MonthlySavingsAverage, error)
Close()
}
+39
View File
@@ -0,0 +1,39 @@
package repo
import (
mod "github.com/ESilva15/expenses/expenses/models"
pgsqlc "github.com/ESilva15/expenses/expenses/repo/pgdb/pgsqlc"
)
func mapRepoMonthlySummary(r pgsqlc.GetMonthlySummaryRow) mod.MonthlySummary {
return mod.MonthlySummary{
MonthYear: r.MonthYear,
Despesa: pgNumericToDecimal(r.Despesa),
Salario: pgNumericToDecimal(r.Salario),
CartaoRefeicao: pgNumericToDecimal(r.CartaoRefeicao),
Reembolso: pgNumericToDecimal(r.Reembolso),
Prenda: pgNumericToDecimal(r.Prenda),
Investment: pgNumericToDecimal(r.Investment),
Adjustment: pgNumericToDecimal(r.Adjustment),
AdjustmentLiquid: pgNumericToDecimal(r.AdjustmentLiquid),
Poupanca: pgNumericToDecimal(r.Poupanca),
PoupancaLiquid: pgNumericToDecimal(r.PoupancaLiquid),
RunningBalance: pgNumericToDecimal(r.RunningBalance),
RunningBalanceLiquid: pgNumericToDecimal(r.RunningBalanceLiquid),
}
}
func mapRepoMonthlySummaries(rows []pgsqlc.GetMonthlySummaryRow) []mod.MonthlySummary {
summaries := make([]mod.MonthlySummary, len(rows))
for i, row := range rows {
summaries[i] = mapRepoMonthlySummary(row)
}
return summaries
}
func mapRepoMonthlySavingsAverage(r pgsqlc.GetMonthlySavingsAverageRow) mod.MonthlySavingsAverage {
return mod.MonthlySavingsAverage{
AvgPoupanca: pgNumericToDecimal(r.AvgPoupanca),
AvgPoupancaLiquid: pgNumericToDecimal(r.AvgPoupancaLiquid),
}
}
+61
View File
@@ -0,0 +1,61 @@
package repo
import (
"context"
mod "github.com/ESilva15/expenses/expenses/models"
"github.com/ESilva15/expenses/expenses/repo/pgdb/pgsqlc"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
)
type PgFinancialRepo struct {
DB *pgxpool.Pool
}
func NewPgFinancialRepo(db *pgxpool.Pool) PgFinancialRepo {
return PgFinancialRepo{DB: db}
}
func (f PgFinancialRepo) Close() {
f.DB.Close()
}
func (p PgFinancialRepo) GetMonthlySummary(
ctx context.Context,
filter *mod.Filter,
) ([]mod.MonthlySummary, error) {
queries := pgsqlc.New(p.DB)
var pgStart, pgEnd pgtype.Timestamp
if filter.Start != nil {
pgStart = pgtype.Timestamp{Time: *filter.Start, Valid: true}
}
if filter.End != nil {
pgEnd = pgtype.Timestamp{Time: *filter.End, Valid: true}
}
rows, err := queries.GetMonthlySummary(ctx, pgsqlc.GetMonthlySummaryParams{
Startdate: pgStart,
Enddate: pgEnd,
UserID: filter.UserIDs,
})
if err != nil {
return nil, err
}
return mapRepoMonthlySummaries(rows), nil
}
func (p PgFinancialRepo) GetMonthlySavingsAverage(
ctx context.Context,
filter *mod.Filter,
) (mod.MonthlySavingsAverage, error) {
queries := pgsqlc.New(p.DB)
res, err := queries.GetMonthlySavingsAverage(ctx)
if err != nil {
return mod.MonthlySavingsAverage{}, err
}
return mapRepoMonthlySavingsAverage(res), nil
}
@@ -1 +0,0 @@
SELECT * FROM expenses;
@@ -1 +0,0 @@
SELECT * FROM expenses;
@@ -0,0 +1,7 @@
DROP TABLE IF EXISTS public."expensesShares";
DROP TABLE IF EXISTS public."expensesPayments";
DROP TABLE IF EXISTS public.expenses;
DROP TABLE IF EXISTS public.stores;
DROP TABLE IF EXISTS public."expenseTypes";
DROP TABLE IF EXISTS public.users;
DROP TABLE IF EXISTS public.categories;
@@ -0,0 +1,69 @@
-- Create base lookup/independent tables first
CREATE TABLE public.categories (
"CategoryID" integer NOT NULL GENERATED BY DEFAULT AS IDENTITY,
"CategoryName" text NOT NULL,
CONSTRAINT categories_pkey PRIMARY KEY ("CategoryID")
);
CREATE TABLE public.users (
"UserID" integer NOT NULL GENERATED BY DEFAULT AS IDENTITY,
"UserName" text NOT NULL,
"UserPass" text NOT NULL,
CONSTRAINT users_pkey PRIMARY KEY ("UserID")
);
CREATE TABLE public."expenseTypes" (
"TypeID" integer NOT NULL GENERATED BY DEFAULT AS IDENTITY,
"TypeName" text NOT NULL,
CONSTRAINT "expenseTypes_pkey" PRIMARY KEY ("TypeID")
);
CREATE TABLE public.stores (
"StoreID" integer NOT NULL GENERATED BY DEFAULT AS IDENTITY,
"StoreName" text NOT NULL,
"NIF" text DEFAULT ''::text,
CONSTRAINT stores_pkey PRIMARY KEY ("StoreID")
);
-- Create main expenses table including the 'qr' column
CREATE TABLE public.expenses (
"ExpID" integer NOT NULL GENERATED BY DEFAULT AS IDENTITY,
"Description" text NOT NULL,
"Value" numeric(12,2) DEFAULT 0 NOT NULL,
"StoreID" integer DEFAULT 0 NOT NULL,
"CategoryID" integer DEFAULT 0 NOT NULL,
"OwnerUserID" integer DEFAULT 0 NOT NULL,
"TypeID" integer DEFAULT 0 NOT NULL,
"ExpDate" timestamp without time zone NOT NULL,
"CreationDate" timestamp without time zone NOT NULL,
"PaidOff" boolean DEFAULT false,
"SharesEven" boolean DEFAULT false,
qr text DEFAULT ''::text,
CONSTRAINT expenses_pkey PRIMARY KEY ("ExpID"),
CONSTRAINT "expenses_StoreID_fkey" FOREIGN KEY ("StoreID") REFERENCES public.stores("StoreID") ON DELETE RESTRICT,
CONSTRAINT "expenses_CategoryID_fkey" FOREIGN KEY ("CategoryID") REFERENCES public.categories("CategoryID") ON DELETE RESTRICT,
CONSTRAINT "expenses_OwnerUserID_fkey" FOREIGN KEY ("OwnerUserID") REFERENCES public.users("UserID") ON DELETE RESTRICT,
CONSTRAINT "expenses_TypeID_fkey" FOREIGN KEY ("TypeID") REFERENCES public."expenseTypes"("TypeID") ON DELETE RESTRICT
);
-- Create dependent relationship tables
CREATE TABLE public."expensesPayments" (
"ExpPaymID" integer NOT NULL GENERATED BY DEFAULT AS IDENTITY,
"ExpID" integer NOT NULL,
"UserID" integer NOT NULL,
"Payed" numeric(12,2) DEFAULT 0 NOT NULL,
CONSTRAINT "expensesPayments_pkey" PRIMARY KEY ("ExpPaymID"),
CONSTRAINT "expensesPayments_ExpID_fkey" FOREIGN KEY ("ExpID") REFERENCES public.expenses("ExpID") ON DELETE RESTRICT,
CONSTRAINT "expensesPayments_UserID_fkey" FOREIGN KEY ("UserID") REFERENCES public.users("UserID") ON DELETE RESTRICT
);
CREATE TABLE public."expensesShares" (
"ExpShareID" integer NOT NULL GENERATED BY DEFAULT AS IDENTITY,
"ExpID" integer NOT NULL,
"UserID" integer NOT NULL,
"Share" numeric(6,2) DEFAULT 0.5 NOT NULL,
"Calculated" numeric(12,2) DEFAULT 0 NOT NULL,
CONSTRAINT "expensesShares_pkey" PRIMARY KEY ("ExpShareID"),
CONSTRAINT "expensesShares_ExpID_fkey" FOREIGN KEY ("ExpID") REFERENCES public.expenses("ExpID") ON DELETE RESTRICT,
CONSTRAINT "expensesShares_UserID_fkey" FOREIGN KEY ("UserID") REFERENCES public.users("UserID") ON DELETE RESTRICT
);
@@ -1,4 +0,0 @@
--- 0001_qr_feature.down.sql
ALTER TABLE expenses DROP COLUMN "qr";
ALTER TABLE stores DROP COLUMN "NIF";
@@ -1,4 +0,0 @@
--- 0001_qr_feature.up.sql
ALTER TABLE expenses ADD qr TEXT DEFAULT '';
ALTER TABLE stores ADD "NIF" TEXT DEFAULT '';
@@ -1,6 +1,6 @@
// Code generated by sqlc. DO NOT EDIT. // Code generated by sqlc. DO NOT EDIT.
// versions: // versions:
// sqlc v1.30.0 // sqlc v1.31.1
// source: categories.sql // source: categories.sql
package pgsqlc package pgsqlc
+1 -1
View File
@@ -1,6 +1,6 @@
// Code generated by sqlc. DO NOT EDIT. // Code generated by sqlc. DO NOT EDIT.
// versions: // versions:
// sqlc v1.30.0 // sqlc v1.31.1
package pgsqlc package pgsqlc
+93 -1
View File
@@ -1,6 +1,6 @@
// Code generated by sqlc. DO NOT EDIT. // Code generated by sqlc. DO NOT EDIT.
// versions: // versions:
// sqlc v1.30.0 // sqlc v1.31.1
// source: expenses.sql // source: expenses.sql
package pgsqlc package pgsqlc
@@ -84,6 +84,59 @@ func (q *Queries) GetExpense(ctx context.Context, expid int32) (GetExpenseRow, e
return i, err return i, err
} }
const getExpenseSum = `-- name: GetExpenseSum :one
SELECT "ExpID", "Description", "Value", "StoreID", "CategoryID", "OwnerUserID", "TypeID", "ExpDate", "CreationDate", "PaidOff", "SharesEven", qr, "ExpShareID", "ExpID", "UserID", "Share", "Calculated" from "expenses"
JOIN "expensesShares" ON "expenses"."ExpID" = "expensesShares"."ExpID"
WHERE
"expenses"."ExpID" = 673 AND
"expensesShares"."UserID" = 1
`
type GetExpenseSumRow struct {
ExpID int32
Description string
Value pgtype.Numeric
StoreID int32
CategoryID int32
OwnerUserID int32
TypeID int32
ExpDate pgtype.Timestamp
CreationDate pgtype.Timestamp
PaidOff pgtype.Bool
SharesEven pgtype.Bool
Qr string
ExpShareID int32
ExpID_2 int32
UserID int32
Share pgtype.Numeric
Calculated pgtype.Numeric
}
func (q *Queries) GetExpenseSum(ctx context.Context) (GetExpenseSumRow, error) {
row := q.db.QueryRow(ctx, getExpenseSum)
var i GetExpenseSumRow
err := row.Scan(
&i.ExpID,
&i.Description,
&i.Value,
&i.StoreID,
&i.CategoryID,
&i.OwnerUserID,
&i.TypeID,
&i.ExpDate,
&i.CreationDate,
&i.PaidOff,
&i.SharesEven,
&i.Qr,
&i.ExpShareID,
&i.ExpID_2,
&i.UserID,
&i.Share,
&i.Calculated,
)
return i, err
}
const getExpenses = `-- name: GetExpenses :many const getExpenses = `-- name: GetExpenses :many
SELECT SELECT
expenses."ExpID", expenses."Description", expenses."Value", expenses."StoreID", expenses."CategoryID", expenses."OwnerUserID", expenses."TypeID", expenses."ExpDate", expenses."CreationDate", expenses."PaidOff", expenses."SharesEven", expenses.qr, expenses."ExpID", expenses."Description", expenses."Value", expenses."StoreID", expenses."CategoryID", expenses."OwnerUserID", expenses."TypeID", expenses."ExpDate", expenses."CreationDate", expenses."PaidOff", expenses."SharesEven", expenses.qr,
@@ -182,6 +235,45 @@ func (q *Queries) GetExpenses(ctx context.Context, arg GetExpensesParams) ([]Get
return items, nil return items, nil
} }
const getMonthlyTotalPaid = `-- name: GetMonthlyTotalPaid :many
SELECT
EXTRACT(MONTH FROM e."ExpDate") AS month,
SUM(ep."Payed") AS monthly_total_paid
FROM "expensesPayments" ep
JOIN
expenses e ON ep."ExpID" = e."ExpID"
WHERE
ep."UserID" = 1
AND e."TypeID" = 0
GROUP BY EXTRACT(MONTH FROM e."ExpDate")
ORDER BY month
`
type GetMonthlyTotalPaidRow struct {
Month pgtype.Numeric
MonthlyTotalPaid int64
}
func (q *Queries) GetMonthlyTotalPaid(ctx context.Context) ([]GetMonthlyTotalPaidRow, error) {
rows, err := q.db.Query(ctx, getMonthlyTotalPaid)
if err != nil {
return nil, err
}
defer rows.Close()
var items []GetMonthlyTotalPaidRow
for rows.Next() {
var i GetMonthlyTotalPaidRow
if err := rows.Scan(&i.Month, &i.MonthlyTotalPaid); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const insertExpense = `-- name: InsertExpense :one const insertExpense = `-- name: InsertExpense :one
INSERT INTO expenses( INSERT INTO expenses(
"Description", "Description",
@@ -0,0 +1,168 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: financial.sql
package pgsqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const getMonthlySavingsAverage = `-- name: GetMonthlySavingsAverage :one
WITH monthly_summary AS (
SELECT
TO_CHAR(e."ExpDate", 'MM/YYYY') AS month_year,
DATE_TRUNC('month', e."ExpDate") AS month_sort,
SUM(CASE WHEN e."TypeID" = 0 THEN ep."Payed" ELSE 0 END)::NUMERIC AS despesa,
SUM(CASE WHEN e."TypeID" = 1 THEN ep."Payed" ELSE 0 END)::NUMERIC AS salario,
SUM(CASE WHEN e."TypeID" = 2 THEN ep."Payed" ELSE 0 END)::NUMERIC AS cartao_refeicao,
SUM(CASE WHEN e."TypeID" = 3 THEN ep."Payed" ELSE 0 END)::NUMERIC AS reembolso,
SUM(CASE WHEN e."TypeID" = 4 THEN ep."Payed" ELSE 0 END)::NUMERIC AS prenda,
SUM(CASE WHEN e."TypeID" = 5 THEN ep."Payed" ELSE 0 END)::NUMERIC AS investment,
SUM(CASE WHEN e."TypeID" = 6 THEN ep."Payed" ELSE 0 END)::NUMERIC AS adjustment,
SUM(CASE WHEN e."TypeID" = 7 THEN ep."Payed" ELSE 0 END)::NUMERIC AS adjustment_liquid
FROM "expensesPayments" ep
JOIN expenses e ON ep."ExpID" = e."ExpID"
WHERE ep."UserID" = 1
GROUP BY
TO_CHAR(e."ExpDate", 'MM/YYYY'),
DATE_TRUNC('month', e."ExpDate")
),
calculated_summary AS (
SELECT
((salario + cartao_refeicao + reembolso) - (despesa + prenda))::NUMERIC AS poupanca,
((salario + cartao_refeicao + reembolso) - (despesa + investment + prenda))::NUMERIC AS poupanca_liquid
FROM monthly_summary
)
SELECT
TRUNC(AVG(poupanca), 2)::NUMERIC AS avg_poupanca,
TRUNC(AVG(poupanca_liquid), 2)::NUMERIC AS avg_poupanca_liquid
FROM calculated_summary
`
type GetMonthlySavingsAverageRow struct {
AvgPoupanca pgtype.Numeric
AvgPoupancaLiquid pgtype.Numeric
}
func (q *Queries) GetMonthlySavingsAverage(ctx context.Context) (GetMonthlySavingsAverageRow, error) {
row := q.db.QueryRow(ctx, getMonthlySavingsAverage)
var i GetMonthlySavingsAverageRow
err := row.Scan(&i.AvgPoupanca, &i.AvgPoupancaLiquid)
return i, err
}
const getMonthlySummary = `-- name: GetMonthlySummary :many
WITH monthly_summary AS (
SELECT
TO_CHAR(e."ExpDate", 'MM/YYYY') AS month_year,
DATE_TRUNC('month', e."ExpDate") AS month_sort,
SUM(CASE WHEN e."TypeID" = 0 THEN ep."Payed" ELSE 0 END)::NUMERIC AS despesa,
SUM(CASE WHEN e."TypeID" = 1 THEN ep."Payed" ELSE 0 END)::NUMERIC AS salario,
SUM(CASE WHEN e."TypeID" = 2 THEN ep."Payed" ELSE 0 END)::NUMERIC AS cartao_refeicao,
SUM(CASE WHEN e."TypeID" = 3 THEN ep."Payed" ELSE 0 END)::NUMERIC AS reembolso,
SUM(CASE WHEN e."TypeID" = 4 THEN ep."Payed" ELSE 0 END)::NUMERIC AS prenda,
SUM(CASE WHEN e."TypeID" = 5 THEN ep."Payed" ELSE 0 END)::NUMERIC AS investment,
SUM(CASE WHEN e."TypeID" = 6 THEN ep."Payed" ELSE 0 END)::NUMERIC AS adjustment,
SUM(CASE WHEN e."TypeID" = 7 THEN ep."Payed" ELSE 0 END)::NUMERIC AS adjustment_liquid
FROM "expensesPayments" ep
JOIN expenses e ON ep."ExpID" = e."ExpID"
WHERE ep."UserID" = $1
AND ($2::timestamp IS NULL OR e."ExpDate" >= $2::timestamp)
AND ($3::timestamp IS NULL OR e."ExpDate" <= $3::timestamp)
GROUP BY
TO_CHAR(e."ExpDate", 'MM/YYYY'),
DATE_TRUNC('month', e."ExpDate")
),
calculated_summary AS (
SELECT
month_year,
month_sort,
despesa,
salario,
cartao_refeicao,
reembolso,
prenda,
investment,
adjustment,
adjustment_liquid,
((salario + cartao_refeicao + reembolso) - (despesa + prenda))::NUMERIC AS poupanca,
((salario + cartao_refeicao + reembolso) - (despesa + investment + prenda))::NUMERIC AS poupanca_liquid
FROM monthly_summary
)
SELECT
month_year,
despesa,
salario,
cartao_refeicao,
reembolso,
prenda,
investment,
adjustment,
adjustment_liquid,
poupanca,
poupanca_liquid,
(SUM(poupanca) OVER (ORDER BY month_sort ASC) + SUM(adjustment) OVER (ORDER BY month_sort ASC) + SUM(adjustment_liquid) OVER (ORDER BY month_sort ASC))::NUMERIC AS running_balance,
(SUM(poupanca_liquid) OVER (ORDER BY month_sort ASC) + SUM(adjustment_liquid) OVER (ORDER BY month_sort ASC))::NUMERIC AS running_balance_liquid
FROM calculated_summary
ORDER BY month_sort ASC
`
type GetMonthlySummaryParams struct {
UserID int32
Startdate pgtype.Timestamp
Enddate pgtype.Timestamp
}
type GetMonthlySummaryRow struct {
MonthYear string
Despesa pgtype.Numeric
Salario pgtype.Numeric
CartaoRefeicao pgtype.Numeric
Reembolso pgtype.Numeric
Prenda pgtype.Numeric
Investment pgtype.Numeric
Adjustment pgtype.Numeric
AdjustmentLiquid pgtype.Numeric
Poupanca pgtype.Numeric
PoupancaLiquid pgtype.Numeric
RunningBalance pgtype.Numeric
RunningBalanceLiquid pgtype.Numeric
}
func (q *Queries) GetMonthlySummary(ctx context.Context, arg GetMonthlySummaryParams) ([]GetMonthlySummaryRow, error) {
rows, err := q.db.Query(ctx, getMonthlySummary, arg.UserID, arg.Startdate, arg.Enddate)
if err != nil {
return nil, err
}
defer rows.Close()
var items []GetMonthlySummaryRow
for rows.Next() {
var i GetMonthlySummaryRow
if err := rows.Scan(
&i.MonthYear,
&i.Despesa,
&i.Salario,
&i.CartaoRefeicao,
&i.Reembolso,
&i.Prenda,
&i.Investment,
&i.Adjustment,
&i.AdjustmentLiquid,
&i.Poupanca,
&i.PoupancaLiquid,
&i.RunningBalance,
&i.RunningBalanceLiquid,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
+1 -1
View File
@@ -1,6 +1,6 @@
// Code generated by sqlc. DO NOT EDIT. // Code generated by sqlc. DO NOT EDIT.
// versions: // versions:
// sqlc v1.30.0 // sqlc v1.31.1
package pgsqlc package pgsqlc
@@ -1,6 +1,6 @@
// Code generated by sqlc. DO NOT EDIT. // Code generated by sqlc. DO NOT EDIT.
// versions: // versions:
// sqlc v1.30.0 // sqlc v1.31.1
// source: payments.sql // source: payments.sql
package pgsqlc package pgsqlc
+1 -1
View File
@@ -1,6 +1,6 @@
// Code generated by sqlc. DO NOT EDIT. // Code generated by sqlc. DO NOT EDIT.
// versions: // versions:
// sqlc v1.30.0 // sqlc v1.31.1
// source: shares.sql // source: shares.sql
package pgsqlc package pgsqlc
+1 -1
View File
@@ -1,6 +1,6 @@
// Code generated by sqlc. DO NOT EDIT. // Code generated by sqlc. DO NOT EDIT.
// versions: // versions:
// sqlc v1.30.0 // sqlc v1.31.1
// source: stores.sql // source: stores.sql
package pgsqlc package pgsqlc
+1 -1
View File
@@ -1,6 +1,6 @@
// Code generated by sqlc. DO NOT EDIT. // Code generated by sqlc. DO NOT EDIT.
// versions: // versions:
// sqlc v1.30.0 // sqlc v1.31.1
// source: types.sql // source: types.sql
package pgsqlc package pgsqlc
+1 -1
View File
@@ -1,6 +1,6 @@
// Code generated by sqlc. DO NOT EDIT. // Code generated by sqlc. DO NOT EDIT.
// versions: // versions:
// sqlc v1.30.0 // sqlc v1.31.1
// source: users.sql // source: users.sql
package pgsqlc package pgsqlc
@@ -87,3 +87,23 @@ SET
"qr" = $9, "qr" = $9,
"ExpDate" = $10 "ExpDate" = $10
WHERE "ExpID" = $11; WHERE "ExpID" = $11;
-- name: GetExpenseSum :one
SELECT * from "expenses"
JOIN "expensesShares" ON "expenses"."ExpID" = "expensesShares"."ExpID"
WHERE
"expenses"."ExpID" = 673 AND
"expensesShares"."UserID" = 1;
-- name: GetMonthlyTotalPaid :many
SELECT
EXTRACT(MONTH FROM e."ExpDate") AS month,
SUM(ep."Payed") AS monthly_total_paid
FROM "expensesPayments" ep
JOIN
expenses e ON ep."ExpID" = e."ExpID"
WHERE
ep."UserID" = 1
AND e."TypeID" = 0
GROUP BY EXTRACT(MONTH FROM e."ExpDate")
ORDER BY month;
@@ -0,0 +1,85 @@
-- name: GetMonthlySummary :many
WITH monthly_summary AS (
SELECT
TO_CHAR(e."ExpDate", 'MM/YYYY') AS month_year,
DATE_TRUNC('month', e."ExpDate") AS month_sort,
SUM(CASE WHEN e."TypeID" = 0 THEN ep."Payed" ELSE 0 END)::NUMERIC AS despesa,
SUM(CASE WHEN e."TypeID" = 1 THEN ep."Payed" ELSE 0 END)::NUMERIC AS salario,
SUM(CASE WHEN e."TypeID" = 2 THEN ep."Payed" ELSE 0 END)::NUMERIC AS cartao_refeicao,
SUM(CASE WHEN e."TypeID" = 3 THEN ep."Payed" ELSE 0 END)::NUMERIC AS reembolso,
SUM(CASE WHEN e."TypeID" = 4 THEN ep."Payed" ELSE 0 END)::NUMERIC AS prenda,
SUM(CASE WHEN e."TypeID" = 5 THEN ep."Payed" ELSE 0 END)::NUMERIC AS investment,
SUM(CASE WHEN e."TypeID" = 6 THEN ep."Payed" ELSE 0 END)::NUMERIC AS adjustment,
SUM(CASE WHEN e."TypeID" = 7 THEN ep."Payed" ELSE 0 END)::NUMERIC AS adjustment_liquid
FROM "expensesPayments" ep
JOIN expenses e ON ep."ExpID" = e."ExpID"
WHERE ep."UserID" = $1
AND (sqlc.narg(StartDate)::timestamp IS NULL OR e."ExpDate" >= sqlc.narg(StartDate)::timestamp)
AND (sqlc.narg(EndDate)::timestamp IS NULL OR e."ExpDate" <= sqlc.narg(EndDate)::timestamp)
GROUP BY
TO_CHAR(e."ExpDate", 'MM/YYYY'),
DATE_TRUNC('month', e."ExpDate")
),
calculated_summary AS (
SELECT
month_year,
month_sort,
despesa,
salario,
cartao_refeicao,
reembolso,
prenda,
investment,
adjustment,
adjustment_liquid,
((salario + cartao_refeicao + reembolso) - (despesa + prenda))::NUMERIC AS poupanca,
((salario + cartao_refeicao + reembolso) - (despesa + investment + prenda))::NUMERIC AS poupanca_liquid
FROM monthly_summary
)
SELECT
month_year,
despesa,
salario,
cartao_refeicao,
reembolso,
prenda,
investment,
adjustment,
adjustment_liquid,
poupanca,
poupanca_liquid,
(SUM(poupanca) OVER (ORDER BY month_sort ASC) + SUM(adjustment) OVER (ORDER BY month_sort ASC) + SUM(adjustment_liquid) OVER (ORDER BY month_sort ASC))::NUMERIC AS running_balance,
(SUM(poupanca_liquid) OVER (ORDER BY month_sort ASC) + SUM(adjustment_liquid) OVER (ORDER BY month_sort ASC))::NUMERIC AS running_balance_liquid
FROM calculated_summary
ORDER BY month_sort ASC;
-- name: GetMonthlySavingsAverage :one
WITH monthly_summary AS (
SELECT
TO_CHAR(e."ExpDate", 'MM/YYYY') AS month_year,
DATE_TRUNC('month', e."ExpDate") AS month_sort,
SUM(CASE WHEN e."TypeID" = 0 THEN ep."Payed" ELSE 0 END)::NUMERIC AS despesa,
SUM(CASE WHEN e."TypeID" = 1 THEN ep."Payed" ELSE 0 END)::NUMERIC AS salario,
SUM(CASE WHEN e."TypeID" = 2 THEN ep."Payed" ELSE 0 END)::NUMERIC AS cartao_refeicao,
SUM(CASE WHEN e."TypeID" = 3 THEN ep."Payed" ELSE 0 END)::NUMERIC AS reembolso,
SUM(CASE WHEN e."TypeID" = 4 THEN ep."Payed" ELSE 0 END)::NUMERIC AS prenda,
SUM(CASE WHEN e."TypeID" = 5 THEN ep."Payed" ELSE 0 END)::NUMERIC AS investment,
SUM(CASE WHEN e."TypeID" = 6 THEN ep."Payed" ELSE 0 END)::NUMERIC AS adjustment,
SUM(CASE WHEN e."TypeID" = 7 THEN ep."Payed" ELSE 0 END)::NUMERIC AS adjustment_liquid
FROM "expensesPayments" ep
JOIN expenses e ON ep."ExpID" = e."ExpID"
WHERE ep."UserID" = 1
GROUP BY
TO_CHAR(e."ExpDate", 'MM/YYYY'),
DATE_TRUNC('month', e."ExpDate")
),
calculated_summary AS (
SELECT
((salario + cartao_refeicao + reembolso) - (despesa + prenda))::NUMERIC AS poupanca,
((salario + cartao_refeicao + reembolso) - (despesa + investment + prenda))::NUMERIC AS poupanca_liquid
FROM monthly_summary
)
SELECT
TRUNC(AVG(poupanca), 2)::NUMERIC AS avg_poupanca,
TRUNC(AVG(poupanca_liquid), 2)::NUMERIC AS avg_poupanca_liquid
FROM calculated_summary;
-158
View File
@@ -1,158 +0,0 @@
package pages
import (
"net/http"
"sync"
exp "github.com/ESilva15/expenses/expenses"
mod "github.com/ESilva15/expenses/expenses/models"
val "github.com/ESilva15/expenses/expenses/values"
dec "github.com/shopspring/decimal"
"github.com/gin-gonic/gin"
)
// MonthlyTotal holds the data for the MonthlyTotal plot.
type MonthlyTotal struct {
Month int `json:"month"`
Total dec.Decimal `json:"total"`
}
func getMonthlyBalance(expenses mod.Expenses, uID int32) ([]MonthlyTotal, error) {
monthlyBalance := make([]MonthlyTotal, val.MonthsPerYear)
for k := range val.MonthsPerYear {
monthlyBalance[k].Month = k
}
for _, e := range expenses {
month := e.Date.Month() - 1
t := e.Type.TypeName
// Get the current expenses value and make it negative if its an expense
// It's not the value, its what we paid on it (our payments)
// I don't like this like this - takes too long, we should load it from DB
// at the start, and cache it too
_ = exp.App.LoadExpensePayments(&e)
value := exp.App.PaidByUser(e, uID)
// value := e.Value
if t == "Despesa" {
value = value.Neg()
}
// Store the data on the montly balance list
monthlyBalance[month].Total = monthlyBalance[month].Total.Add(value)
}
return monthlyBalance, nil
}
func getMonthlyTotal(expenses mod.Expenses, uID int32) ([]MonthlyTotal, error) {
mTotal := make([]MonthlyTotal, val.MonthsPerYear)
for k := range mTotal {
mTotal[k].Month = k
}
// Step 1: net total for each month
for _, e := range expenses {
month := int(e.Date.Month()) - 1 // Jan = 0
// Same as on the other one here
_ = exp.App.LoadExpensePayments(&e)
value := exp.App.PaidByUser(e, uID)
if e.Type.TypeName == "Despesa" {
value = value.Neg()
}
mTotal[month].Total = mTotal[month].Total.Add(value)
}
// Step 2: cumulative balance
for i := 1; i < len(mTotal); i++ {
mTotal[i].Total = mTotal[i].Total.Add(mTotal[i-1].Total)
}
return mTotal, nil
}
func getAnalysisDataWG(c *gin.Context) (map[string]any, error) {
ctx, err := getLoggedInUserCTX(c)
if err != nil {
return map[string]any{}, err
}
user := *ctx.Value("user").(*mod.User)
filter, err := expenseFilterFromQuery(c)
if err != nil {
return map[string]any{}, err
}
queriedExpenses, err := exp.App.GetAllExpenses(ctx, filter)
if err != nil {
return map[string]any{}, err
}
var (
mBalance []MonthlyTotal
mTotal []MonthlyTotal
bErr error
tErr error
wg sync.WaitGroup
)
wg.Add(2)
go func() {
defer wg.Done()
mBalance, bErr = getMonthlyBalance(queriedExpenses, user.UserID)
}()
go func() {
defer wg.Done()
mTotal, tErr = getMonthlyTotal(queriedExpenses, user.UserID)
}()
wg.Wait()
if tErr != nil {
return map[string]any{}, tErr
}
if bErr != nil {
return map[string]any{}, bErr
}
plotData := map[string]any{
"mBalance": mBalance,
"mTotal": mTotal,
}
return plotData, nil
}
func analysisPartialPage(c *gin.Context) {
// TODO - this is repeated code with the analysisPage one, figure something
data, err := getAnalysisDataWG(c)
if err != nil {
ServerErrorView(c, "failed to compiled analysis data")
return
}
c.HTML(http.StatusOK, "analysis", gin.H{
"plotData": data,
})
}
func analysisPage(c *gin.Context) {
data, err := getAnalysisDataWG(c)
if err != nil {
ServerErrorView(c, "failed to compiled analysis data")
return
}
c.HTML(http.StatusOK, "terminal", gin.H{
"page": "analysis",
"renderNavBar": true,
"content": "analysis",
"plotData": data,
})
}
// RouteAnalysis routes the endpoints for analysis stuff.
func RouteAnalysis(router *gin.RouterGroup) {
router.GET("/analysis", analysisPage)
router.POST("/analysis", analysisPartialPage)
}
+48
View File
@@ -15,6 +15,54 @@ import (
"github.com/shopspring/decimal" "github.com/shopspring/decimal"
) )
func filterFromQuery(c *gin.Context) (mod.Filter, error) {
var err error
var start, end time.Time
filter := mod.NewFilter()
startDate := c.Query("range-start")
if startDate != "" {
startDate += " 00:00:00"
start, err = time.ParseInLocation("02-Jan-2006 15:04:05", startDate, time.UTC)
if err != nil {
log.Printf("error startDate: %v", err)
return mod.Filter{}, nil
}
filter.Start = &start
}
endDate := c.Query("range-end")
if endDate != "" {
endDate += " 00:00:00"
end, err = time.ParseInLocation("02-Jan-2006 15:04:05", endDate, time.UTC)
if err != nil {
log.Printf("error endDate: %v", err)
return mod.Filter{}, nil
}
filter.End = &end
}
filter.CatIDs, err = ginaux.QueryIntArray(c, "cat-dropdown[]")
if err != nil {
log.Printf("Failed to retrieve IDs from cat-dropdown[] %+v", err)
return mod.Filter{}, nil
}
filter.StoreIDs, err = ginaux.QueryIntArray(c, "store-dropdown[]")
if err != nil {
log.Printf("Failed to retrieve IDs from store-dropdown[] %+v", err)
return mod.Filter{}, nil
}
filter.TypeIDs, err = ginaux.QueryIntArray(c, "type-dropdown[]")
if err != nil {
log.Printf("Failed to retrieve IDs from type-dropdown[] %+v", err)
return mod.Filter{}, nil
}
return filter, nil
}
func expenseFilterFromQuery(c *gin.Context) (repo.ExpFilter, error) { func expenseFilterFromQuery(c *gin.Context) (repo.ExpFilter, error) {
var err error var err error
var start, end time.Time var start, end time.Time
+25
View File
@@ -0,0 +1,25 @@
package pages
import (
"net/http"
"github.com/gin-gonic/gin"
)
func analysisPage(c *gin.Context) {
c.HTML(http.StatusOK, "terminal", gin.H{
"page": "analysis",
"renderNavBar": true,
"content": "analysis",
})
}
func analysisPartialPage(c *gin.Context) {
c.HTML(http.StatusOK, "analysis", gin.H{})
}
// RouteAnalysis routes the endpoints for analysis stuff.
func RouteAnalysis(router *gin.RouterGroup) {
router.GET("/analysis", analysisPage)
router.POST("/analysis", analysisPartialPage)
}
+67
View File
@@ -0,0 +1,67 @@
package pages
import (
"log"
"net/http"
exp "github.com/ESilva15/expenses/expenses"
mod "github.com/ESilva15/expenses/expenses/models"
"github.com/gin-gonic/gin"
)
func getSummaryData(c *gin.Context) ([]mod.MonthlySummary, error) {
ctx, err := getLoggedInUserCTX(c)
if err != nil {
log.Printf("error getting user from context: %+v", err)
ServerErrorView(c, "Could not get logged in user")
return nil, nil
}
filter, err := filterFromQuery(c)
if err != nil {
log.Printf("error parsing filters from query: %+v", err)
ServerErrorView(c, "Could not get logged in user")
return nil, nil
}
filter.UserIDs = *&ctx.Value("user").(*mod.User).UserID
summary, err := exp.App.GetMonthlySummary(ctx, &filter)
if err != nil {
log.Printf("error retrieving monthly summary from DB: %+v", err)
c.Header("HX-Redirect", "/500")
return nil, err
}
return summary, nil
}
func analysisDashboardPage(c *gin.Context) {
c.HTML(http.StatusOK, "terminal", gin.H{
"page": "analysis-filtered",
"renderNavBar": true,
"content": "analysis-filtered",
})
}
func analysisDashboardPagePartial(c *gin.Context) {
c.HTML(http.StatusOK, "analysis-filtered", gin.H{
// "plotData": data,
})
}
func analysisDashboardQuery(c *gin.Context) {
data, err := getSummaryData(c)
if err != nil {
log.Printf("error: %+v", err)
ServerErrorView(c, "failed to compile analysis data")
return
}
c.HTML(http.StatusOK, "analysis-filtered-results", data)
}
// RouteAnalysis routes the endpoints for analysis stuff.
func RouteAnalysisDashboard(router *gin.RouterGroup) {
router.GET("/filtered-analysis", analysisDashboardPage)
router.GET("/filtered-analysis/filters", analysisDashboardQuery)
router.POST("/filtered-analysis", analysisDashboardPagePartial)
}
-4
View File
@@ -1,4 +0,0 @@
schema.sql
.env
pgsql-data-dev/
pgSocket/
-33
View File
@@ -1,33 +0,0 @@
FROM dir.esilva.org/esilva/esilva-alpine:v1.0.0
# Required ENV variables for pg
ENV LANG=en_GB.utf8
# Downloads the required packages for the webserver
RUN apk --no-cache add su-exec zsh \
postgresql16 \
&& rm -rf /tmp/*
# Directory for the pg socket
RUN mkdir -p /run/postgresql && \
chown -R $UNAME:$UNAME /run/postgresql
RUN mkdir -p /var/lib/postgresql/data && \
chown -R $UNAME:$UNAME /var/lib/postgresql
COPY ./schema.sql /schema.sql
# Expose the pgsql port
EXPOSE 5431
# Copies the start script
COPY ./start.sh /start.sh
COPY ./healthcheck.sh /healthcheck.sh
USER $UNAME
STOPSIGNAL SIGTERM
ENTRYPOINT [ "/start.sh" ]
-38
View File
@@ -1,38 +0,0 @@
include ../vars.mk
service = expenses-pgdb
image = $(service)
container = $(image)-container
.PHONY: clean attach-test test
clean:
@docker image inspect $(image) > /dev/null 2>&1 && \
docker image rm $(image) || true
build:
cp ../expenses/repo/pgdb/schema.sql .
docker buildx build \
-t $(registry)/$(repo)/expensesdb:$(tag) .
push_image:
docker push $(registry)/$(repo)/expensesdb:$(tag)
attach:
docker exec -it $(container) zsh
attach-test:
docker exec -it $(container)-dev zsh
remove-dev-container:
docker container rm $(container)-dev --force > /dev/null 2>&1
test: remove-dev-container
docker run -p 5431:5432 \
--name $(container)-dev \
--env-file .env \
-v ./pgsql-data-dev/:/var/lib/postgresql/data/ \
-v ./pgSocket:/run/postgresql \
-it $(registry)/$(repo)/expensesdb:v0.0.91-alpha
build_image:
make -C ./
-9
View File
@@ -1,9 +0,0 @@
# README
Requires a `.env` file with the following fields:
```
PGDATA=<path-to-dir-where-pg-data-lives>
ExpDB_USER=<user-for-expenses-db>
ExpDB_PASS=<pass-for-expenses-db>
ExpDB_NAME=<name-for-expenses-db>
```
File diff suppressed because it is too large Load Diff
-4
View File
@@ -1,4 +0,0 @@
#!/bin/bash
set -e
pg_isready -U "$ExpDB_USER" -d "$ExpDB_NAME"
-44
View File
@@ -1,44 +0,0 @@
#!/bin/sh
set -e
if [ -z "$(ls -A "$PGDATA")" ]; then
echo "Creating database with:"
echo "DIR: $PGDATA"
echo "USER: $ExpDB_USER"
echo "PASS: $ExpDB_PASS"
echo "NAME: $ExpDB_NAME"
# Initiate PG data directory
initdb \
--locale=C.UTF-8 \
--encoding=UTF8 \
-D "$PGDATA" \
--data-checksums \
--username="$UNAME"
# Set PG to listen on all addresses
sed -ri "s/^#(listen_addresses\s*=\s*)\S+/\1'*'/" "$PGDATA"/postgresql.conf
# Start PG to add the NC DB
pg_ctl -D "$PGDATA" \
-o "-c listen_addresses=''" \
-w start
# Create the NC database
createUser="CREATE USER $ExpDB_USER WITH PASSWORD '$ExpDB_PASS';"
createDB="CREATE DATABASE $ExpDB_NAME TEMPLATE template0 ENCODING 'UNICODE';"
alterDB="ALTER DATABASE $ExpDB_NAME OWNER TO $ExpDB_USER;"
grantPriv="GRANT ALL PRIVILEGES ON DATABASE $ExpDB_NAME TO $ExpDB_USER;"
psql -d postgres -c "${createUser}"
psql -d postgres -c "${createDB}"
psql -d postgres -c "${alterDB}"
psql -d postgres -c "${grantPriv}"
# Execute the initial schema
psql -U "$ExpDB_USER" -d "$ExpDB_NAME" -a -f /schema.sql
pg_ctl -D "$PGDATA" -m fast -w stop
{ echo; echo "host all all 0.0.0.0/0 md5"; } >> "$PGDATA"/pg_hba.conf
fi
postgres "$@"