Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: fix global variable #9

Merged
merged 11 commits into from
Nov 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .containers-sugar.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
version: 1.0
compose-app: docker compose
env-file: ./src/.env
defaults:
group: dev
project-name: rinchen
service-groups:
- name: dev
compose-path: containers/docker-compose.yaml
env-file: ./src/.env
services:
default: web
available:
- name: web
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
db.sqlite
*.sqlite
src/.htpasswd
vendor/
.env*
Expand Down
6 changes: 3 additions & 3 deletions .makim.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ groups:
runserver:
help: Run the server application
run: |
cd src
# echo "HOST_ADDRESS=http://localhost:8081" > .env
php -S localhost:8081
sugar down
sugar build
sugar ext restart

tests:
help: Run the server application
Expand Down
4 changes: 4 additions & 0 deletions conda/dev.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,9 @@ dependencies:
- python
- pip
- makim 1.8.3
- containers-sugar 1.9.0
- jinja2
- requests
- pip:
- pygments
- compose-go>=1.23
20 changes: 18 additions & 2 deletions containers/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,2 +1,18 @@
FROM httpd:2.4
COPY ./public-html/ /usr/local/apache2/htdocs/
FROM webdevops/php-nginx:7.4

ARG UID=1000
ARG GID=1000

RUN apt-get update -y \
&& apt-get install -y \
sudo \
tzdata \
openssl \
&& rm -rf /var/lib/apt/lists/* \
/var/cache/apt/archives \
/tmp/*

# RUN addgroup --gid ${GID} devops \
# && useradd --uid ${UID} --gid ${GID} -ms /bin/bash devops \
# && echo "devops ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/devops \
# && chmod 0440 /etc/sudoers.d/devops
14 changes: 9 additions & 5 deletions containers/docker-compose.yaml
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
version: '3.3'

services:
my-apache2:
web:
build:
context: .
dockerfile: ./Dockerfile
context: ..
dockerfile: ./containers/Dockerfile
args:
- UID=${UID}
- GID=${GID}
ports:
- 8080:80
- ${HOST_PORT}:80
user: "${UID}:${GID}"
volumes:
- ./public-html:/usr/local/apache2/htdocs/
- ../src:/app
1 change: 1 addition & 0 deletions scripts/reports/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
output
9 changes: 9 additions & 0 deletions scripts/reports/run.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#!/usr/bin/env bash

set -ex

rm -f output/subscription_list.tex
python subscribers_list.py
cd output
pdflatex subscription_list.tex
pdflatex subscription_list.tex
54 changes: 54 additions & 0 deletions scripts/reports/subscribers_list.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import requests
import json
from jinja2 import Environment, FileSystemLoader

# Define the API endpoint URL
api_url = "http://localhost:8081/api/subscription/list.php"

# Make a GET request to the API
response = requests.get(api_url)

# Check if the request was successful (status code 200)
if response.status_code == 200:
# Parse the JSON response
data = json.loads(response.text)

# Check if the API response contains data
if 'data' in data:
subscriptions = data['data']

# Create a Jinja2 environment
env = Environment(loader=FileSystemLoader('.'))

# Load the LaTeX template
template = env.get_template('subscription_template.tex')

for subscription in subscriptions:
image_url = subscription["qr"]
response = requests.get(image_url)

tex_file_path = f"images/{image_url.split('/')[-1]}"
local_file_path = f"./output/{tex_file_path}"
image_data = response.content

subscription["qr_filename"] = f"./{tex_file_path}"

# Save the image to the local file
with open(local_file_path, 'wb') as file:
file.write(image_data)


# Render the LaTeX document with data
rendered_latex = template.render(subscriptions=subscriptions)

# Save the rendered LaTeX document to a .tex file
with open("output/subscription_list.tex", "w") as tex_file:
tex_file.write(rendered_latex)

print("LaTeX document created successfully.")
else:
print("No subscription data found in the API response.")
exit(0)
else:
print("Failed to fetch data from the API. Status code:", response.status_code)
exit(0)
38 changes: 38 additions & 0 deletions scripts/reports/subscription_template.tex
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
\documentclass[a4paper]{article}

% Include the geometry package to set page layout
\usepackage[margin=1in]{geometry}
\usepackage{graphicx}
\usepackage{longtable} % To support multi-page tables
\usepackage{geometry} % To adjust page margins
\usepackage[utf8]{inputenc}
\usepackage{booktabs,multirow,array}

% Set custom page margins
\geometry{left=0.5cm, right=0.5cm, top=0.5cm, bottom=0.5cm}

\begin{document}
\title{Subscription List}

\begin{longtable}{|c|c|}
\hline
\textbf{Personal Information} & \textbf{QR Code} \\
\hline
\endhead
{% for subscription in subscriptions -%}
\multirow{3}{*}{
\begin{tabular}{@{}c@{}}
\texttt{ {{- subscription["person"]["fullname"] -}} } \\
\texttt{ {{- subscription["person"]["email"].replace("_", "\\_").replace("%", "\\%") -}} } \\
\texttt{ {{- subscription["person"]["phone"] -}} }
\end{tabular} } &
\begin{tabular}{@{}c@{}}
\setlength{\fboxsep}{20pt} % Adjust the padding here
\fbox{ \includegraphics[width=2in]{ {{- subscription.qr_filename -}} } }
\end{tabular} \\
\hline
{% endfor %}

\end{longtable}

\end{document}
33 changes: 33 additions & 0 deletions src/api/subscription/list.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php
require_once dirname(dirname(__DIR__)) . '/lib/subscription.php'; // Adjust the path as needed

// Set the response content type to JSON
header('Content-Type: application/json');

// Fetch subscription data using Subscription::list()
try {
$subscriptions = Subscription::list(["active" => 1]);

if ($subscriptions === null) {
$response = [
'success' => true,
'message' => 'No subscriptions found',
'data' => []
];
} else {
$response = [
'success' => true,
'message' => 'Subscriptions retrieved successfully',
'data' => $subscriptions
];
}
} catch (Exception $e) {
// Handle any exceptions or errors
$response = [
'success' => false,
'message' => 'Error retrieving subscriptions: ' . $e->getMessage()
];
}

// Encode the response array as JSON and print it
echo json_encode($response);
6 changes: 3 additions & 3 deletions src/attendance_log.php → src/attendance_log.php/index.php
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
<?php

require_once "./lib/settings.php";
require_once dirname(__DIR__) . "/lib/settings.php";

global $URL_BASE;
global $BASE_URL;

// Redirect to templates/index.php
$params = str_replace("+", "%2B", $_SERVER['QUERY_STRING']);
$url = "{$URL_BASE}/templates/attendance/log.php?{$params}";
$url = "{$BASE_URL}/templates/attendance/log.php?{$params}";

header("Location: {$url}");
exit; // Make sure to exit after the redirection
Expand Down
27 changes: 19 additions & 8 deletions src/lib/attendance.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public static function list(): array {
$db = get_db();

// Perform a query to retrieve all attendance records
$query = "SELECT * FROM attendance";
$query = "SELECT * FROM attendance ORDER BY event_session_id, log_time";
$result = $db->query($query);

$attendanceList = [];
Expand Down Expand Up @@ -115,12 +115,22 @@ public static function log(
EventSession $eventSession
): Attendance {
$attendance = new Attendance($person, $eventSession, new DateTime());
return $attendance->insert();
return $attendance->insert(false);
}

public function insert(): Attendance
public static function log_force(
Person $person,
EventSession $eventSession
): Attendance {
$attendance = new Attendance($person, $eventSession, new DateTime());
return $attendance->insert(true);
}

public function insert(bool $force=false): Attendance
{
$this->validate();
if ($force !== true) {
$this->validate();
}

$db = get_db(); // Assuming get_db returns a database connection

Expand Down Expand Up @@ -188,16 +198,17 @@ public function validate(): bool
}

// Check if it's the first session of the event
$firstSession = $this->eventSession->isFirstSession(); // Implement this method
$firstSession = $this->eventSession->isFirstSession();

if (!$firstSession) {
// If it's not the first session, check if the person attended previous sessions
$previousSessions = $this->eventSession->getPreviousSessions(); // Implement this method
$previousSessions = $this->eventSession->getPreviousSessions();

foreach ($previousSessions as $previousSession) {
// Check if the person attended each previous session
if (!$this->attendedSession($this->person, $previousSession)) { // Implement this method
throw new Exception("Attendance is not allowed. Please attend previous sessions.");
// HARD CODED: don't do it without a support of an adult!
if (!$this->attendedSession($this->person, $previousSession) && $previousSession->id != 1) {
throw new Exception("Attendance is not allowed. The participant didn't attend previous sessions.");
}
}
}
Expand Down
14 changes: 9 additions & 5 deletions src/lib/person.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,25 +30,29 @@ function __construct(
public static function get(array $data): ?Person {
$db = get_db();

$query = "
SELECT * FROM person
WHERE 1=1";
$query = "SELECT * FROM person";
$query_filter = "";
$query_filter_sep = "";

// Iterate over the data dictionary
foreach ($data as $key => $value) {
// Escape the values to prevent SQL injection (assuming using SQLite3 class)
$escapedValue = $db->escapeString($value);

// Add the key-value pair to the WHERE clause
$query .= " AND $key='$escapedValue'";
$query_filter .= " {$query_filter_sep} $key='$escapedValue'";
$query_filter_sep = "AND";
}

if ($query_filter != "") {
$query .= " WHERE {$query_filter};";
}

$result = $db->query($query);

$row = $result->fetchArray(SQLITE3_ASSOC);

if ($row === false) {
// No rows returned, result is empty
$person = null;
} else {
$person = new Person();
Expand Down
4 changes: 4 additions & 0 deletions src/lib/qr.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ function generate_qr(string $fullname, string $email, string $phone): string {

$endpoint = "$root_url/attendance_log.php";

// todo: it shouldn't have this / after the $endpoint
// this works on apache but not on nginx
// as a workaround we needed to create a folder called attendance_log.php
// and we created a file called index.php
$page_url = "$endpoint/?fullname=$fullname&email=$email&phone=$phone";

$qr_url_with_data = "$qr_url=" . urlencode($page_url);
Expand Down
10 changes: 8 additions & 2 deletions src/lib/subscription.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,12 @@ public static function get(array $data): ?Subscription {
*/
public static function list(?array $filter=null): ?array {
$db = get_db();
$query = "SELECT * FROM subscription WHERE 1=1";
$query = "
SELECT subscription.*
FROM subscription INNER JOIN person
ON (subscription.person_id=person.id)
WHERE 1=1
";

if ($filter) {
// Iterate over the data dictionary
Expand All @@ -80,10 +85,11 @@ public static function list(?array $filter=null): ?array {
$escapedValue = $db->escapeString($value);

// Add the key-value pair to the WHERE clause
$query .= " AND $key='$escapedValue'";
$query .= " AND subscription.{$key}='$escapedValue'";
}
}

$query .= " ORDER BY person.fullname";
$result = $db->query($query);

$subscription_list = [];
Expand Down
2 changes: 2 additions & 0 deletions src/migrations/all.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,5 @@ function migrate_all(): void {
migrate_0003();
migrate_0004();
}

migrate_all();
Loading