Skip to content

Commit

Permalink
Merge branch 'main' into issue/57-crud-contractes
Browse files Browse the repository at this point in the history
  • Loading branch information
0x1026 authored Nov 16, 2024
2 parents b82dbd2 + cb4fc8b commit 444ff2c
Show file tree
Hide file tree
Showing 17 changed files with 366 additions and 254 deletions.
52 changes: 31 additions & 21 deletions docker/database/start-scripts/0-init.sql
Original file line number Diff line number Diff line change
Expand Up @@ -8,25 +8,35 @@ create table zones (
id int auto_increment primary key,
name varchar(255),
quantity int,
postal_code int,
point_id int,
postal_code int,
point_id int,
foreign key (point_id) references points(id)
);

create table tree_types (
id int auto_increment primary key,
family varchar(255) not null,
genus varchar(255) not null,
species varchar(255) not null unique,
constraint UC_TreeType unique (family, genus, species)
);

create table elements (
id int auto_increment primary key,
name varchar(255),
latitude decimal,
longitude decimal,
tree_types_id int,
created_at timestamp,
deleted_at timestamp,
updated_at timestamp
updated_at timestamp,
foreign key (tree_types_id) references tree_types(id)
);

create table inventory (
id int auto_increment primary key,
element_id int,
zone_id int,
element_id int,
zone_id int,
foreign key (element_id) references elements(id),
foreign key (zone_id) references zones(id)
);
Expand All @@ -35,25 +45,25 @@ create table incidences (
id int auto_increment primary key,
name varchar(255),
photo varchar(255),
element_id int,
element_id int,
description varchar(255),
incident_date timestamp,
incident_date timestamp,
foreign key (element_id) references elements(id)
);

create table roles (
id int auto_increment primary key,
role_name varchar(255)
name varchar(255) unique
);

create table workers (
id int auto_increment primary key,
company varchar(255),
name varchar(255),
dni varchar(255) unique,
dni varchar(255) unique,
password varchar(255),
email varchar(255),
role_id int,
email varchar(255),
role_id int,
created_at timestamp,
deleted_at timestamp,
updated_at timestamp,
Expand Down Expand Up @@ -98,23 +108,23 @@ create table parts (

create table routes (
id int auto_increment primary key,
distance float,
point_id int,
travel_time int,
distance float,
point_id int,
travel_time int,
foreign key (point_id) references points(id)
);

create table tasks (
id int auto_increment primary key,
task_name varchar(255),
work_order_id int,
task_name varchar(255),
work_order_id int,
description varchar(255),
inventory_id int,
machine_id int,
route_id int,
inventory_id int,
machine_id int,
route_id int,
status BIT,
part_id int,
history_id int,
part_id int,
history_id int,
created_at timestamp,
deleted_at timestamp,
foreign key (work_order_id) references work_orders(id),
Expand Down
11 changes: 9 additions & 2 deletions docker/database/start-scripts/1-seed.sql
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
-- Insert sample roles (Admin, Manager, Worker)
INSERT INTO roles (role_name) VALUES
INSERT INTO roles (name) VALUES
('Administrador'),
('Gerente'),
('Trabajador');
Expand All @@ -8,4 +8,11 @@ INSERT INTO roles (role_name) VALUES
INSERT INTO workers (company, name, dni, password, email, role_id, created_at, updated_at, deleted_at) VALUES
('TechCorp', 'Carlos García', '12345678A', 'hashedpassword1', '[email protected]', 1, NOW(), NOW(), NULL), -- Admin
('InnovaTech', 'Ana Martínez', '23456789B', 'hashedpassword2', '[email protected]', 2, NOW(), NOW(), NULL), -- Manager
('DesignWorks', 'José Rodríguez', '34567890C', 'hashedpassword3', '[email protected]', 3, NOW(), NOW(), NULL); -- Worker
('DesignWorks', 'José Rodríguez', '34567890C', 'hashedpassword3', '[email protected]', 3, NOW(), NOW(), NULL); -- Worker

-- Insert sample tree types
INSERT INTO tree_types (family, genus, species) VALUES
('Fagaceae', 'Quercus', 'Quercus robur'),
('Pinaceae', 'Pinus', 'Pinus sylvestris'),
('Sapindaceae', 'Acer', 'Acer campestre');

11 changes: 8 additions & 3 deletions src/app/Controllers/AuthController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@

namespace App\Controllers;

use App\Core\BaseController;
use App\Core\View;

class AuthController
class AuthController implements BaseController
{
public function index()
public function get()
{
View::render([
"view" => "Auth/Login",
Expand All @@ -15,4 +16,8 @@ public function index()
"data" => []
]);
}
}

public function post() {}
public function put() {}
public function delete() {}
}
9 changes: 0 additions & 9 deletions src/app/Controllers/Controller.php

This file was deleted.

13 changes: 9 additions & 4 deletions src/app/Controllers/HomeController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,24 @@

namespace App\Controllers;

use App\Core\BaseController;
use App\Core\View;
use App\Models\Worker;

class HomeController
class HomeController implements BaseController
{
public function index()
public function get()
{
$workers = Worker::getAll();
$workers = Worker::findAll();
View::render([
"view" => "Home",
"title" => "Home Page",
"layout" => "MainLayout",
"data" => ["workers" => $workers]
]);
}
}

public function post() {}
public function put() {}
public function delete() {}
}
25 changes: 25 additions & 0 deletions src/app/Controllers/TreeTypeController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

namespace App\Controllers;

use App\Core\BaseController;
use App\Core\View;
use App\Models\TreeType;

class TreeTypeController implements BaseController
{
public function get()
{
$tree_types = TreeType::findAll();
View::render([
"view" => "TreeType",
"title" => "Tree Types",
"layout" => "MainLayout",
"data" => ["tree_types" => $tree_types]
]);
}

public function post() {}
public function put() {}
public function delete() {}
}
11 changes: 11 additions & 0 deletions src/app/Core/BaseController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

namespace App\Core;

interface BaseController
{
public function get();
public function post();
public function put();
public function delete();
}
151 changes: 151 additions & 0 deletions src/app/Core/BaseModel.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
<?php

namespace App\Core;

abstract class BaseModel
{
protected int $id;

// Get the related model in a one-to-one relationship
public function belongsTo($relatedModel, $foreignKey, $ownerKey = 'id')
{
$relatedTable = $relatedModel::getTableName();
$foreignKeyValue = $this->{$foreignKey};

$query = "SELECT * FROM $relatedTable WHERE $ownerKey = :foreignKeyValue LIMIT 1";
$results = Database::prepareAndExecute($query, ['foreignKeyValue' => $foreignKeyValue]);

return !empty($results) ? $relatedModel::mapDataToModel($results[0]) : null;
}

public function delete()
{
$table = static::getTableName();

if (static::hasSoftDelete()) {
$query = "UPDATE $table SET deleted_at = NOW() WHERE id = :id";
Database::prepareAndExecute($query, ['id' => $this->id]);
} else {
$query = "DELETE FROM $table WHERE id = :id";
Database::prepareAndExecute($query, ['id' => $this->id]);
}
}

public static function find($id)
{
$table = static::getTableName();
$query = "SELECT * FROM $table WHERE id = :id LIMIT 1";
$results = Database::prepareAndExecute($query, ['id' => $id]);

if (!empty($results))
return static::mapDataToModel($results[0]);

return null;
}

public static function findAll($conditions = [])
{
$table = static::getTableName();
$query = "SELECT * FROM $table";
$params = [];

if (!empty($conditions)) {
$clauses = [];
foreach ($conditions as $key => $value) {
$clauses[] = "$key = :$key";
$params[$key] = $value;
}
$query .= " WHERE " . implode(" AND ", $clauses);
}

$results = Database::prepareAndExecute($query, $params);

return array_map(fn($row) => static::mapDataToModel($row), $results);
}

// Fetch all soft deleted records
public static function findSoftDeleted()
{
if (!static::hasSoftDelete())
return [];

$table = static::getTableName();
$query = "SELECT * FROM $table WHERE deleted_at IS NOT NULL";
$results = Database::prepareAndExecute($query);

return array_map(fn($row) => static::mapDataToModel($row), $results);
}

// Dynamically relationship fetching
public function hasMany($relatedModel, $foreignKey, $localKey = 'id')
{
$relatedTable = $relatedModel::getTableName();
$localKeyValue = $this->{$localKey};

$query = "SELECT * FROM $relatedTable WHERE $foreignKey = :localKeyValue";
$results = Database::prepareAndExecute($query, ['localKeyValue' => $localKeyValue]);

return array_map(fn($row) => $relatedModel::mapDataToModel($row), $results);
}

// Dynamically check if a table has the deleted_at column
protected static function hasSoftDelete()
{
static $softDeleteCache = [];
$table = static::getTableName();

if (!isset($softDeleteCache[$table])) {
$query = "SHOW COLUMNS FROM $table LIKE 'deleted_at'";
$result = Database::prepareAndExecute($query);
$softDeleteCache[$table] = !empty($result); // Cache the result
}

return $softDeleteCache[$table];
}

public function restore()
{
if (static::hasSoftDelete()) {
$table = static::getTableName();
$query = "UPDATE $table SET deleted_at = NULL WHERE id = :id";
Database::prepareAndExecute($query, ['id' => $this->id]);
}
}

public function save()
{
$table = static::getTableName();
$properties = get_object_vars($this);
unset($properties['id']); // Avoid saving the id in the data fields

if ($this->id) {
// Update logic
$fields = [];
foreach ($properties as $key => $value) {
$fields[] = "$key = :$key";
}
$query = "UPDATE $table SET " . implode(", ", $fields) . " WHERE id = :id";
$properties['id'] = $this->id;
} else {
// Insert logic
$fields = array_keys($properties);
$placeholders = array_map(fn($field) => ":$field", $fields);
$query = "INSERT INTO $table (" . implode(", ", $fields) . ") VALUES (" . implode(", ", $placeholders) . ")";
}

Database::prepareAndExecute($query, $properties);

if (!$this->id)
$this->id = Database::connect()->lastInsertId();
}

//* Abstract methods to enforce subclass implementation
abstract protected static function getTableName();
abstract protected static function mapDataToModel($data);

//* Getters and Setters
public function getId()
{
return $this->id;
}
}
Loading

0 comments on commit 444ff2c

Please sign in to comment.