Commit b579f141 authored by Staś Kycia's avatar Staś Kycia
Browse files

moved js scripts to separate static files

parent 1b803cb4
Loading
Loading
Loading
Loading
+100 −0
Changes for stats/static/js/live_results.js: 100 added lines, 0 removed lines.
Original line number Diff line number Diff line
async function getElectionData() {
    try {
        const response = await fetch(apiUrl);

        const data = await response.json();
        console.log(data);

        const labels = data.options.map(option => option.name);
        const votes = data.options.map(option => option.votes);

        return {
            name: data.name,
            labels: labels,
            votes: votes
        };
    } catch(error) {
        console.error("Couldn't fetch results", error);
    }
}

let resultsChart;

function initializeChart(data){
    const ctx = document.getElementById('chart').getContext('2d');
    resultsChart = new Chart(
        ctx,
        {
            type : 'pie',
            data: 
            {
                labels: data.labels,
                datasets: [{
                    label: 'Liczba głosów',
                    data: data.votes,
                }]
            },
            options: 
            {
                responsive: true,
                plugins: {
                    title: {
                        display: true,
                        text: data.name + ' – wyniki',
                        font: {
                            size: 24,
                            weight: 'bold'
                        },
                        padding: {
                            top: 10,
                            bottom: 30
                        }
                    },
                    legend: {
                        position: 'bottom'
                    }
                }
            }
        }
    );
}

function updateTable(data) {
    const tbody = document.getElementById('table-body');
    const totalCell = document.getElementById('total-votes');

    let html = '';
    let total = 0;

    data.labels.forEach((label, index) => {
        const voteCount = data.votes[index];
        total += voteCount;
        html += `
            <tr>
                <td>${label}</td>
                <td style="text-align: right;">${voteCount}</td>
            </tr>
        `;
    });

    tbody.innerHTML = html;
    totalCell.innerText = total;
}

async function updateUI() {
    const freshData = await getElectionData();
    
    if(freshData){
        if(!resultsChart){
            initializeChart(freshData);
        } else {
            resultsChart.data.labels = freshData.labels;
            resultsChart.data.datasets[0].data = freshData.votes;
            resultsChart.update(); 
        }
        updateTable(freshData);
    }
}

updateUI();
setInterval(updateUI, 5000);
 No newline at end of file
+115 −0
Changes for stats/static/js/statistics.js: 115 added lines, 0 removed lines.
Original line number Diff line number Diff line
function getStats() {
    const element = document.getElementById('stats-data');
    return JSON.parse(element.TextContent);
}

async function getElectionData() {
    try {
        const response = await fetch(apiUrl);

        const data = await response.json();

        const labels = data.options.map(option => option.name);
        const votes = data.options.map(option => option.votes);

        return {
            name: data.name,
            labels: labels,
            votes: votes
        };
    } catch (error) {
        console.error('Failed to fetch results', error);
    }
}

let resultsChart;

function initializeChart(data) {
    const ctx = document.getElementById('chart').getContext('2d');
    resultsChart = new Chart(
        ctx,
        {
            type: 'pie',
            data:
            {
                labels: data.labels,
                datasets: [{
                    label: 'Liczba głosów',
                    data: data.votes,
                }]
            },
            options:
            {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'bottom'
                    }
                }
            }
        }
    );
}

function initializeTable(data) {
    const tbody = document.getElementById('table-body');
    const totalCell = document.getElementById('total-votes');

    let html = '';
    let total = 0;

    data.labels.forEach((label, index) => {
        const voteCount = data.votes[index];
        total += voteCount;
        html += `
            <tr>
                <td>${label}</td>
                <td style="text-align: right;">${voteCount}</td>
            </tr>
        `;
    });

    tbody.innerHTML = html;
    totalCell.innerText = total;
}

function initializeAttendanceChart() {
    const data = JSON.parse(document.getElementById('attendance-data-json').textContent);

    const labels = data.map(item => item.class_name);
    const percentages = data.map(item => item.percentage);

    const ctx = document.getElementById('attendance-bar-chart').getContext('2d');

    new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [{
                label: 'Frekwencja (%)',
                data: percentages,
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: { beginAtZero: true, max: 100 }
            },
            plugins: {
                legend: { display: false }
            }
        }
    });
}

async function displayResults() {
    const data = await getElectionData();

    initializeChart(data);
    initializeTable(data);
    initializeAttendanceChart();
}

displayResults();
 No newline at end of file
+3 −101
Changes for stats/templates/stats/live_results.html: 3 added lines, 101 removed lines.
Original line number Diff line number Diff line
{% extends 'admin/base_site.html' %}

{% load static %}

{% block title %} Wyniki na żywo | {{ site_title }}{% endblock %}

{% block content %}
@@ -28,107 +30,7 @@
</div>

<script>
    async function getElectionData() {
    const apiUrl = "{{ request.scheme }}://{{ request.get_host }}{% url 'vote:api_internal_results' %}?election_id={{ election_id }}";

        try {
            const response = await fetch(apiUrl);

            const data = await response.json();
            console.log(data);

            const labels = data.options.map(option => option.name);
            const votes = data.options.map(option => option.votes);

            return {
                name: data.name,
                labels: labels,
                votes: votes
            };
        } catch(error) {
            console.error("Couldn't fetch results", error);
        }
    }

    let resultsChart;

    function initializeChart(data){
        const ctx = document.getElementById('chart').getContext('2d');
        resultsChart = new Chart(
            ctx,
            {
                type : 'pie',
                data: 
                {
                    labels: data.labels,
                    datasets: [{
                        label: 'Liczba głosów',
                        data: data.votes,
                    }]
                },
                options: 
                {
                    responsive: true,
                    plugins: {
                        title: {
                            display: true,
                            text: data.name + ' – wyniki',
                            font: {
                                size: 24,
                                weight: 'bold'
                            },
                            padding: {
                                top: 10,
                                bottom: 30
                            }
                        },
                        legend: {
                            position: 'bottom'
                        }
                    }
                }
            }
        );
    }

    function updateTable(data) {
        const tbody = document.getElementById('table-body');
        const totalCell = document.getElementById('total-votes');

        let html = '';
        let total = 0;

        data.labels.forEach((label, index) => {
            const voteCount = data.votes[index];
            total += voteCount;
            html += `
                <tr>
                    <td>${label}</td>
                    <td style="text-align: right;">${voteCount}</td>
                </tr>
            `;
        });

        tbody.innerHTML = html;
        totalCell.innerText = total;
    }

    async function updateUI() {
        const freshData = await getElectionData();
        
        if(freshData){
            if(!resultsChart){
                initializeChart(freshData);
            } else {
                resultsChart.data.labels = freshData.labels;
                resultsChart.data.datasets[0].data = freshData.votes;
                resultsChart.update(); 
            }
            updateTable(freshData);
        }
    }

    updateUI();
    setInterval(updateUI, 5000);
</script>
<script src="{% static 'js/live_results.js' %}"></script>
{% endblock %}
 No newline at end of file
+3 −116
Changes for stats/templates/stats/statistics.html: 3 added lines, 116 removed lines.
Original line number Diff line number Diff line
{% extends 'admin/base_site.html' %}

{% load static %}

{% block content %}
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.5.1/dist/chart.umd.min.js"></script>

@@ -83,123 +85,8 @@
{{ stats_by_class|json_script:"attendance-data-json" }}

<script>
    function getStats() {
        const element = document.getElementById('stats-data');
        return JSON.parse(element.TextContent);
    }

    async function getElectionData() {
    const apiUrl = "{{ request.scheme }}://{{ request.get_host }}{% url 'vote:api_internal_results' %}?election_id={{ election_id }}";

        try {
            const response = await fetch(apiUrl);

            const data = await response.json();

            const labels = data.options.map(option => option.name);
            const votes = data.options.map(option => option.votes);

            return {
                name: data.name,
                labels: labels,
                votes: votes
            };
        } catch (error) {
            console.error('Failed to fetch results', error);
        }
    }

    let resultsChart;

    function initializeChart(data) {
        const ctx = document.getElementById('chart').getContext('2d');
        resultsChart = new Chart(
            ctx,
            {
                type: 'pie',
                data:
                {
                    labels: data.labels,
                    datasets: [{
                        label: 'Liczba głosów',
                        data: data.votes,
                    }]
                },
                options:
                {
                    responsive: true,
                    plugins: {
                        legend: {
                            position: 'bottom'
                        }
                    }
                }
            }
        );
    }

    function initializeTable(data) {
        const tbody = document.getElementById('table-body');
        const totalCell = document.getElementById('total-votes');

        let html = '';
        let total = 0;

        data.labels.forEach((label, index) => {
            const voteCount = data.votes[index];
            total += voteCount;
            html += `
                <tr>
                    <td>${label}</td>
                    <td style="text-align: right;">${voteCount}</td>
                </tr>
            `;
        });

        tbody.innerHTML = html;
        totalCell.innerText = total;
    }

    function initializeAttendanceChart() {
        const data = JSON.parse(document.getElementById('attendance-data-json').textContent);

        const labels = data.map(item => item.class_name);
        const percentages = data.map(item => item.percentage);

        const ctx = document.getElementById('attendance-bar-chart').getContext('2d');

        new Chart(ctx, {
            type: 'bar',
            data: {
                labels: labels,
                datasets: [{
                    label: 'Frekwencja (%)',
                    data: percentages,
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: { beginAtZero: true, max: 100 }
                },
                plugins: {
                    legend: { display: false }
                }
            }
        });
    }

    async function displayResults() {
        const data = await getElectionData();

        initializeChart(data);
        initializeTable(data);
        initializeAttendanceChart();
    }

    displayResults();
</script>
<script src="{% static 'js/statistics.js' %}"></script>

{% endblock %}
 No newline at end of file
+39 −0
Changes for vote/static/js/countdowns.js: 39 added lines, 0 removed lines.
Original line number Diff line number Diff line
const clientTimeOnLoad = new Date();
const timeDelta = serverTimeOnLoad - clientTimeOnLoad;

function updateClock(){
    const now = new Date();
    const correctedNow = new Date(now.getTime() + timeDelta);

    const hours = String(correctedNow.getHours()).padStart(2, '0');
    const minutes = String(correctedNow.getMinutes()).padStart(2, '0');
    const seconds = String(correctedNow.getSeconds()).padStart(2, '0');

    document.getElementById('server-clock').textContent = `${hours}:${minutes}:${seconds}`;
}

function updateAllCountdowns(){
    const now = new Date();
    const correctedNow = new Date(now.getTime() + timeDelta);

    document.querySelectorAll('.countdown').forEach(countdown => {
        const deadline = new Date(countdown.dataset.deadline);
        const diff = Math.max(0, deadline - correctedNow);

        if(diff == 0){
            window.location.reload();
        }

        const hours =  String(Math.floor(diff / (1000 * 60 * 60))).padStart(2, '0');
        const minutes = String(Math.floor(diff / (1000 * 60) % 60)).padStart(2, '0');
        const seconds = String(Math.floor(diff / (1000) % 60)).padStart(2, '0');

        countdown.textContent = `${hours}:${minutes}:${seconds}`;
    });
}

setInterval(updateClock, 1000);
updateClock();

setInterval(updateAllCountdowns, 100);
updateAllCountdowns();
 No newline at end of file
Loading