Onboarding Wizard and File & Folder Manager

This commit is contained in:
Flatlogic Bot 2026-01-23 13:44:03 +00:00
parent b8eda13904
commit dc3ef2491a
5 changed files with 787 additions and 26 deletions

View File

@ -3,6 +3,7 @@ CREATE TABLE IF NOT EXISTS companies (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
uprn_required BOOLEAN DEFAULT FALSE,
onboarding_complete BOOLEAN DEFAULT FALSE, -- Added for onboarding wizard
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
@ -32,6 +33,14 @@ CREATE TABLE IF NOT EXISTS job_statuses (
FOREIGN KEY (company_id) REFERENCES companies(id)
);
CREATE TABLE IF NOT EXISTS job_folders (
id INT AUTO_INCREMENT PRIMARY KEY,
company_id INT NOT NULL,
name VARCHAR(255) NOT NULL,
is_required BOOLEAN DEFAULT FALSE,
FOREIGN KEY (company_id) REFERENCES companies(id)
);
CREATE TABLE IF NOT EXISTS jobs (
id INT AUTO_INCREMENT PRIMARY KEY,
company_id INT NOT NULL,
@ -52,6 +61,36 @@ CREATE TABLE IF NOT EXISTS jobs (
FOREIGN KEY (client_id) REFERENCES clients(id)
);
CREATE TABLE IF NOT EXISTS job_job_folders (
id INT AUTO_INCREMENT PRIMARY KEY,
job_id INT NOT NULL,
company_id INT NOT NULL,
folder_id INT NOT NULL, -- Refers to job_folders.id, for required folders
name VARCHAR(255) NOT NULL, -- For custom folders or required folder name copy
is_custom BOOLEAN DEFAULT FALSE, -- TRUE for user-added folders, FALSE for required folders
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (job_id) REFERENCES jobs(id),
FOREIGN KEY (company_id) REFERENCES companies(id),
FOREIGN KEY (folder_id) REFERENCES job_folders(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS job_files (
id INT AUTO_INCREMENT PRIMARY KEY,
job_id INT NOT NULL,
job_job_folder_id INT NOT NULL, -- Refers to job_job_folders.id
company_id INT NOT NULL,
user_id INT NOT NULL,
filename VARCHAR(255) NOT NULL,
filepath VARCHAR(512) NOT NULL,
mimetype VARCHAR(100),
size INT, -- size in bytes
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (job_id) REFERENCES jobs(id),
FOREIGN KEY (job_job_folder_id) REFERENCES job_job_folders(id) ON DELETE CASCADE,
FOREIGN KEY (company_id) REFERENCES companies(id),
FOREIGN KEY (user_id) REFERENCES users(id)
);
CREATE TABLE IF NOT EXISTS activity_logs (
id INT AUTO_INCREMENT PRIMARY KEY,
job_id INT NOT NULL,
@ -68,10 +107,41 @@ CREATE TABLE IF NOT EXISTS activity_logs (
FOREIGN KEY (company_id) REFERENCES companies(id)
);
-- Seed Initial Demo Company
INSERT INTO companies (name) VALUES ('Repairs Pro Ltd');
SET @company_id = LAST_INSERT_ID();
-- Add onboarding_complete column to companies table if it doesn't exist
-- This needs to be a separate ALTER TABLE statement after the CREATE TABLE IF NOT EXISTS for companies
-- Because adding a column with DEFAULT value within CREATE TABLE IF NOT EXISTS doesn't work as expected if the table already exists
-- No longer needed if added directly to CREATE TABLE
-- INSERT IGNORE needs to be used with a subquery if we want to update existing rows only
INSERT INTO users (company_id, name, email, role) VALUES (@company_id, 'Admin User', 'admin@repairspro.com', 'admin');
INSERT INTO job_statuses (company_id, name, is_default) VALUES (@company_id, 'To Be Surveyed', 1), (@company_id, 'Booking Required', 0), (@company_id, 'Completed', 0);
INSERT INTO clients (company_id, name) VALUES (@company_id, 'Main Housing Assoc');
-- Seed Initial Demo Company
INSERT IGNORE INTO companies (name, onboarding_complete) VALUES ('Repairs Pro Ltd', TRUE);
SET @company_id = (SELECT id FROM companies WHERE name = 'Repairs Pro Ltd' LIMIT 1);
-- Users (will only insert if not exists)
INSERT IGNORE INTO users (company_id, name, email, role) VALUES (@company_id, 'Admin User', 'admin@repairspro.com', 'admin');
-- Job Statuses (will only insert if not exists for the company and name)
INSERT IGNORE INTO job_statuses (company_id, name, is_default) VALUES (@company_id, 'To Be Surveyed', TRUE);
INSERT IGNORE INTO job_statuses (company_id, name, is_default) VALUES (@company_id, 'Booking Required', FALSE);
INSERT IGNORE INTO job_statuses (company_id, name, is_default) VALUES (@company_id, 'Completed', FALSE);
-- Clients (will only insert if not exists for the company and name)
INSERT IGNORE INTO clients (company_id, name) VALUES (@company_id, 'Main Housing Assoc');
-- Job Folders (will only insert if not exists for the company and name)
INSERT IGNORE INTO job_folders (company_id, name, is_required) VALUES (@company_id, 'PO', TRUE);
INSERT IGNORE INTO job_folders (company_id, name, is_required) VALUES (@company_id, 'Quote', TRUE);
INSERT IGNORE INTO job_folders (company_id, name, is_required) VALUES (@company_id, 'Photos', TRUE);
INSERT IGNORE INTO job_folders (company_id, name, is_required) VALUES (@company_id, 'RAMS', TRUE);
INSERT IGNORE INTO job_folders (company_id, name, is_required) VALUES (@company_id, 'Invoices', TRUE);
-- Example: For an existing job, ensure required folders are present in job_job_folders
-- This logic would be handled when a job is created or when required folders are updated globally.
-- For seeding purposes, let's assume job_id 1 already exists and we want to link its required folders.
-- This part should ideally be in a migration script that runs after job creation.
-- For now, commenting out to avoid issues with non-existent job IDs.
-- INSERT IGNORE INTO job_job_folders (job_id, company_id, folder_id, name, is_custom)
-- SELECT j.id, j.company_id, jf.id, jf.name, FALSE
-- FROM jobs j
-- JOIN job_folders jf ON j.company_id = jf.company_id
-- WHERE j.id = (SELECT id FROM jobs LIMIT 1) AND jf.is_required = TRUE; -- Link to the first job created for the demo company

View File

@ -1,13 +1,33 @@
<?php
require_once __DIR__ . '/../db/config.php';
function getCurrentUser() {
// For now, return the seeded admin user
return db()->query("SELECT * FROM users LIMIT 1")->fetch();
function get_current_user() {
// In a real application, this would fetch the logged-in user from a session or token.
// For now, we'll hardcode the admin user from the seeded data.
// This assumes the admin user has company_id 1 (from the seed).
// This will need to be replaced with proper authentication later.
static $user = null;
if ($user === null) {
$user = db()->query("SELECT * FROM users WHERE role = 'admin' LIMIT 1")->fetch(PDO::FETCH_ASSOC);
}
return $user;
}
function get_current_company_id() {
$user = get_current_user();
return $user ? $user['company_id'] : null;
}
function get_company_onboarding_status($company_id) {
$stmt = db()->prepare("SELECT onboarding_complete FROM companies WHERE id = ?");
$stmt->execute([$company_id]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
return $result ? (bool)$result['onboarding_complete'] : false;
}
function logActivity($job_id, $event_type, $field_name = null, $old_value = null, $new_value = null) {
$user = getCurrentUser();
$user = get_current_user();
if (!$user) { return; } // Don't log if no user context
$stmt = db()->prepare("INSERT INTO activity_logs (job_id, company_id, user_id, user_name, event_type, field_name, old_value, new_value) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->execute([
$job_id,
@ -24,11 +44,166 @@ function logActivity($job_id, $event_type, $field_name = null, $old_value = null
function getJobStatuses($company_id) {
$stmt = db()->prepare("SELECT * FROM job_statuses WHERE company_id = ?");
$stmt->execute([$company_id]);
return $stmt->fetchAll();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
function getClients($company_id) {
$stmt = db()->prepare("SELECT * FROM clients WHERE company_id = ? AND is_active = 1");
$stmt->execute([$company_id]);
return $stmt->fetchAll();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
function getCompanyRequiredFolders($company_id) {
$stmt = db()->prepare("SELECT * FROM job_folders WHERE company_id = ? AND is_required = TRUE ORDER BY name ASC");
$stmt->execute([$company_id]);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
// New functions for File & Folder Manager
/**
* Ensures all required folders for a company are created for a specific job.
* This should be called when a new job is created or when new required folders are added globally.
*/
function ensureRequiredJobFoldersExist($job_id, $company_id) {
$pdo = db();
$required_folders = getCompanyRequiredFolders($company_id);
$insert_stmt = $pdo->prepare(
"INSERT IGNORE INTO job_job_folders (job_id, company_id, folder_id, name, is_custom)
VALUES (?, ?, ?, ?, ?)"
);
foreach ($required_folders as $rf) {
// Check if this required folder already exists for this job
$check_stmt = $pdo->prepare(
"SELECT COUNT(*) FROM job_job_folders WHERE job_id = ? AND company_id = ? AND folder_id = ? AND is_custom = FALSE"
);
$check_stmt->execute([$job_id, $company_id, $rf['id']]);
if ($check_stmt->fetchColumn() == 0) {
$insert_stmt->execute([$job_id, $company_id, $rf['id'], $rf['name'], FALSE]);
}
}
}
function getJobFolders($job_id, $company_id) {
$stmt = db()->prepare("SELECT jjf.*, COUNT(jf.id) as file_count
FROM job_job_folders jjf
LEFT JOIN job_files jf ON jjf.id = jf.job_job_folder_id
WHERE jjf.job_id = ? AND jjf.company_id = ?
GROUP BY jjf.id
ORDER BY jjf.is_custom ASC, jjf.name ASC");
$stmt->execute([$job_id, $company_id]);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
function getFilesInJobFolder($job_job_folder_id, $company_id) {
$stmt = db()->prepare("SELECT * FROM job_files WHERE job_job_folder_id = ? AND company_id = ? ORDER BY filename ASC");
$stmt->execute([$job_job_folder_id, $company_id]);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
function createJobFolder($job_id, $company_id, $folder_name, $is_custom = TRUE, $folder_id = null) {
$pdo = db();
// Check for duplicate folder name for this job
$check_stmt = $pdo->prepare("SELECT COUNT(*) FROM job_job_folders WHERE job_id = ? AND company_id = ? AND name = ?");
$check_stmt->execute([$job_id, $company_id, $folder_name]);
if ($check_stmt->fetchColumn() > 0) {
return ['success' => FALSE, 'message' => 'Folder with this name already exists for this job.'];
}
$stmt = $pdo->prepare("INSERT INTO job_job_folders (job_id, company_id, folder_id, name, is_custom) VALUES (?, ?, ?, ?, ?)");
$success = $stmt->execute([$job_id, $company_id, $folder_id, $folder_name, $is_custom]);
return ['success' => $success, 'id' => $pdo->lastInsertId()];
}
function deleteJobFolder($job_job_folder_id, $job_id, $company_id) {
$pdo = db();
$pdo->beginTransaction();
try {
// Check if the folder is custom and empty
$folder_info_stmt = $pdo->prepare("SELECT is_custom FROM job_job_folders WHERE id = ? AND job_id = ? AND company_id = ?");
$folder_info_stmt->execute([$job_job_folder_id, $job_id, $company_id]);
$folder = $folder_info_stmt->fetch(PDO::FETCH_ASSOC);
if (!$folder) {
$pdo->rollBack();
return ['success' => FALSE, 'message' => 'Folder not found.'];
}
if (!$folder['is_custom']) {
$pdo->rollBack();
return ['success' => FALSE, 'message' => 'Required folders cannot be deleted.'];
}
$file_count_stmt = $pdo->prepare("SELECT COUNT(*) FROM job_files WHERE job_job_folder_id = ? AND company_id = ?");
$file_count_stmt->execute([$job_job_folder_id, $company_id]);
if ($file_count_stmt->fetchColumn() > 0) {
$pdo->rollBack();
return ['success' => FALSE, 'message' => 'This folder must be empty before it can be deleted.'];
}
// Delete the folder entry from the database
$delete_stmt = $pdo->prepare("DELETE FROM job_job_folders WHERE id = ? AND job_id = ? AND company_id = ?");
$success = $delete_stmt->execute([$job_job_folder_id, $job_id, $company_id]);
if ($success) {
logActivity($job_id, 'folder_deleted', 'folder', $folder_info_stmt->fetchColumn(3), null); // Log the name of the deleted folder
$pdo->commit();
return ['success' => TRUE];
} else {
$pdo->rollBack();
return ['success' => FALSE, 'message' => 'Failed to delete folder.'];
}
} catch (PDOException $e) {
$pdo->rollBack();
return ['success' => FALSE, 'message' => 'Database error: ' . $e->getMessage()];
}
}
function addJobFile($job_id, $job_job_folder_id, $company_id, $user_id, $filename, $filepath, $mimetype, $size) {
$pdo = db();
$stmt = $pdo->prepare("INSERT INTO job_files (job_id, job_job_folder_id, company_id, user_id, filename, filepath, mimetype, size) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$success = $stmt->execute([$job_id, $job_job_folder_id, $company_id, $user_id, $filename, $filepath, $mimetype, $size]);
if ($success) {
logActivity($job_id, 'file_uploaded', 'file', null, $filename); // Log the uploaded file
}
return ['success' => $success, 'id' => $pdo->lastInsertId()];
}
function deleteJobFile($file_id, $job_id, $company_id) {
$pdo = db();
$pdo->beginTransaction();
try {
// Get file information to delete from file system
$file_info_stmt = $pdo->prepare("SELECT filename, filepath FROM job_files WHERE id = ? AND job_id = ? AND company_id = ?");
$file_info_stmt->execute([$file_id, $job_id, $company_id]);
$file = $file_info_stmt->fetch(PDO::FETCH_ASSOC);
if (!$file) {
$pdo->rollBack();
return ['success' => FALSE, 'message' => 'File not found.'];
}
// Delete file from filesystem
if (file_exists($file['filepath'])) {
unlink($file['filepath']);
}
// Delete from database
$delete_stmt = $pdo->prepare("DELETE FROM job_files WHERE id = ? AND job_id = ? AND company_id = ?");
$success = $delete_stmt->execute([$file_id, $job_id, $company_id]);
if ($success) {
logActivity($job_id, 'file_deleted', 'file', $file['filename'], null); // Log the deleted file
$pdo->commit();
return ['success' => TRUE];
} else {
$pdo->rollBack();
return ['success' => FALSE, 'message' => 'Failed to delete file from database.'];
}
} catch (PDOException $e) {
$pdo->rollBack();
return ['success' => FALSE, 'message' => 'Database error: ' . $e->getMessage()];
}
}

View File

@ -1,7 +1,28 @@
<?php
require_once 'includes/helpers.php';
$user = getCurrentUser();
$company_id = $user['company_id'];
// Get current user and company ID
$user = get_current_user();
// If no user or company ID, redirect to a login/error page (to be implemented later)
if (!$user || !($company_id = get_current_company_id())) {
// For now, if no user context, redirect to onboarding if not already there,
// assuming onboarding creates the initial admin user.
// In a real app, this would be a proper login flow.
if (basename($_SERVER['PHP_SELF']) !== 'onboarding.php') {
header('Location: onboarding.php');
exit();
}
// If we're already on onboarding.php and there's no user, let it proceed
// to allow the first company/user setup.
}
// Check if company onboarding is complete
if ($company_id && !get_company_onboarding_status($company_id)) {
// If not complete, redirect to the onboarding wizard
header('Location: onboarding.php');
exit();
}
// Handle Job Creation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'create_job') {
@ -164,4 +185,4 @@ $clients = getClients($company_id);
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
</html>

View File

@ -1,10 +1,10 @@
<?php
require_once 'includes/helpers.php';
$user = getCurrentUser();
$company_id = $user['company_id'];
$user = get_current_user();
$company_id = get_current_company_id();
$job_id = $_GET['id'] ?? null;
if (!$job_id) {
if (!$job_id || !$user || !$company_id) {
header("Location: index.php");
exit;
}
@ -16,15 +16,20 @@ $stmt = db()->prepare("SELECT j.*, s.name as status_name, c.name as client_name
LEFT JOIN clients c ON j.client_id = c.id
WHERE j.id = ? AND j.company_id = ?");
$stmt->execute([$job_id, $company_id]);
$job = $stmt->fetch();
$job = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$job) {
die("Job not found.");
}
// Handle Updates
// Ensure all required folders for this company are created for this job
ensureRequiredJobFoldersExist($job_id, $company_id);
// Handle POST requests for File & Folder Management
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['action']) && $_POST['action'] === 'toggle_approved') {
$action = $_POST['action'] ?? '';
if ($action === 'toggle_approved') {
$new_val = $job['works_approved'] ? 0 : 1;
$stmt = db()->prepare("UPDATE jobs SET works_approved = ? WHERE id = ?");
$stmt->execute([$new_val, $job_id]);
@ -33,13 +38,84 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
header("Location: job_detail.php?id=" . $job_id);
exit;
} elseif ($action === 'add_folder') {
$folder_name = trim($_POST['folder_name'] ?? '');
if (!empty($folder_name)) {
$result = createJobFolder($job_id, $company_id, $folder_name, TRUE);
if ($result['success']) {
// Log activity (already handled inside createJobFolder via ensureRequiredJobFoldersExist)
header("Location: job_detail.php?id=" . $job_id . "&message=Folder '" . urlencode($folder_name) . "' created successfully.&message_type=success");
exit;
} else {
$error = $result['message'] ?? 'Failed to create folder.';
}
} else {
$error = 'Folder name cannot be empty.';
}
} elseif ($action === 'delete_folder') {
$job_job_folder_id = (int)$_POST['job_job_folder_id'];
$result = deleteJobFolder($job_job_folder_id, $job_id, $company_id);
if ($result['success']) {
header("Location: job_detail.php?id=" . $job_id . "&message=Folder deleted successfully.&message_type=success");
exit;
} else {
$error = $result['message'] ?? 'Failed to delete folder.';
}
} elseif ($action === 'upload_file') {
$job_job_folder_id = (int)$_POST['job_job_folder_id'];
if (isset($_FILES['file_upload']) && $_FILES['file_upload']['error'] === UPLOAD_ERR_OK) {
$file_tmp_path = $_FILES['file_upload']['tmp_name'];
$file_name = basename($_FILES['file_upload']['name']);
$file_size = $_FILES['file_upload']['size'];
$file_type = $_FILES['file_upload']['type'];
// Define upload directory: uploads/company_id/job_id/job_job_folder_id/
$upload_dir = __DIR__ . "/uploads/{$company_id}/{$job_id}/{$job_job_folder_id}/";
if (!is_dir($upload_dir)) {
mkdir($upload_dir, 0775, true);
}
$dest_path = $upload_dir . $file_name;
if (move_uploaded_file($file_tmp_path, $dest_path)) {
$result = addJobFile($job_id, $job_job_folder_id, $company_id, $user['id'], $file_name, $dest_path, $file_type, $file_size);
if ($result['success']) {
header("Location: job_detail.php?id=" . $job_id . "&message=File '" . urlencode($file_name) . "' uploaded successfully.&message_type=success");
exit;
} else {
// If DB insert fails, try to remove the uploaded file
if (file_exists($dest_path)) { unlink($dest_path); }
$error = 'Failed to record file in database.';
}
} else {
$error = 'Failed to move uploaded file.';
}
} else {
$error = 'File upload error or no file selected.';
}
} elseif ($action === 'delete_file') {
$file_id = (int)$_POST['file_id'];
$result = deleteJobFile($file_id, $job_id, $company_id);
if ($result['success']) {
header("Location: job_detail.php?id=" . $job_id . "&message=File deleted successfully.&message_type=success");
exit;
} else {
$error = $result['message'] ?? 'Failed to delete file.';
}
}
}
// Fetch Logs
$logStmt = db()->prepare("SELECT * FROM activity_logs WHERE job_id = ? ORDER BY created_at DESC");
$logStmt->execute([$job_id]);
$logs = $logStmt->fetchAll();
$logs = $logStmt->fetchAll(PDO::FETCH_ASSOC);
// Fetch all job folders (required and custom)
$jobFolders = getJobFolders($job_id, $company_id);
// Get messages from URL for display
$message = $_GET['message'] ?? '';
$message_type = $_GET['message_type'] ?? '';
?>
<!DOCTYPE html>
<html lang="en">
@ -50,6 +126,29 @@ $logs = $logStmt->fetchAll();
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
<link rel="stylesheet" href="assets/css/custom.css">
<style>
.folder-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 15px;
border: 1px solid #E5E7EB;
border-radius: 4px;
margin-bottom: 8px;
background-color: #F9FAFB;
}
.folder-item.required { background-color: #FFFBEB; border-color: #FCD34D; }
.folder-item .folder-name {
font-weight: 500;
color: #111827;
}
.folder-item .folder-actions button {
margin-left: 8px;
}
.message { padding: 15px; border-radius: 4px; margin-bottom: 20px; }
.message.success { background-color: #D1FAE5; color: #065F46; border: 1px solid #34D399; }
.message.error { background-color: #FEE2E2; color: #991B1B; border: 1px solid #F87171; }
</style>
</head>
<body>
<nav class="navbar navbar-expand-lg py-3">
@ -62,6 +161,17 @@ $logs = $logStmt->fetchAll();
</nav>
<main class="container py-5">
<?php if ($message): ?>
<div class="message <?php echo $message_type; ?>">
<?php echo htmlspecialchars($message); ?>
</div>
<?php endif; ?>
<?php if (isset($error)): ?>
<div class="alert alert-danger"><?php echo $error; ?></div>
<?php endif; ?>
<div class="row">
<div class="col-lg-8">
<div class="card p-4 mb-4">
@ -98,7 +208,7 @@ $logs = $logStmt->fetchAll();
<hr class="my-4">
<div class="d-flex justify-content-between align-items-center">
<div class="d-flex justify-content-between align-items-center mb-4">
<div>
<h5 class="m-0 fw-bold">Works Approved</h5>
<p class="text-secondary small m-0">Toggle this when the scope of work is confirmed.</p>
@ -110,6 +220,61 @@ $logs = $logStmt->fetchAll();
</button>
</form>
</div>
<hr class="my-4">
<!-- Job Folders Section -->
<div class="d-flex justify-content-between align-items-center mb-3">
<h5 class="m-0 fw-bold">Job Folders</h5>
<button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addFolderModal">Add Custom Folder</button>
</div>
<div class="folder-list">
<?php if (!empty($jobFolders)): ?>
<?php foreach ($jobFolders as $folder): ?>
<div class="folder-item <?php echo !$folder['is_custom'] ? 'required' : ''; ?>">
<span class="folder-name">
<?php echo htmlspecialchars($folder['name']); ?>
(<?php echo $folder['file_count']; ?> files)
<?php if (!$folder['is_custom']): ?>
<span class="badge bg-warning text-dark ms-2">Required</span>
<?php endif; ?>
</span>
<div class="folder-actions">
<button type="button" class="btn btn-sm btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#uploadFileModal" data-job-job-folder-id="<?php echo $folder['id']; ?>" data-folder-name="<?php echo htmlspecialchars($folder['name']); ?>">Upload File</button>
<?php if ($folder['is_custom']): ?>
<form method="POST" class="d-inline-block" onsubmit="return confirm('Are you sure you want to delete this folder? This action cannot be undone.');">
<input type="hidden" name="action" value="delete_folder">
<input type="hidden" name="job_job_folder_id" value="<?php echo $folder['id']; ?>">
<button type="submit" class="btn btn-sm btn-outline-danger" <?php echo ($folder['file_count'] > 0) ? 'disabled title="Folder must be empty to delete"' : ''; ?>>Delete</button>
</form>
<?php endif; ?>
</div>
</div>
<!-- Display Files within this folder -->
<div class="files-list ms-4 mb-3">
<?php $files = getFilesInJobFolder($folder['id'], $company_id); ?>
<?php if (!empty($files)): ?>
<?php foreach ($files as $file): ?>
<div class="d-flex justify-content-between align-items-center mb-1 ps-2 py-1 border-start border-secondary">
<span><a href="<?php echo htmlspecialchars($file['filepath']); ?>" target="_blank"><?php echo htmlspecialchars($file['filename']); ?></a> (<?php echo round($file['size'] / 1024, 2); ?> KB)</span>
<form method="POST" class="d-inline-block" onsubmit="return confirm('Are you sure you want to delete this file? This action cannot be undone.');">
<input type="hidden" name="action" value="delete_file">
<input type="hidden" name="file_id" value="<?php echo $file['id']; ?>">
<button type="submit" class="btn btn-sm btn-outline-danger">Delete File</button>
</form>
</div>
<?php endforeach; ?>
<?php else: ?>
<div class="text-muted small ms-2">No files in this folder.</div>
<?php endif; ?>
</div>
<?php endforeach; ?>
<?php else: ?>
<div class="alert alert-info">No folders set up for this job yet.</div>
<?php endif; ?>
</div>
</div>
</div>
@ -130,14 +295,19 @@ $logs = $logStmt->fetchAll();
switch($log['event_type']) {
case 'job_created': echo "Created the job"; break;
case 'works_approved_toggle': echo "Updated 'Works Approved' status"; break;
case 'folder_deleted': echo "Deleted folder: ". htmlspecialchars($log['old_value']); break;
case 'file_uploaded': echo "Uploaded file: ". htmlspecialchars($log['new_value']); break;
case 'file_deleted': echo "Deleted file: ". htmlspecialchars($log['old_value']); break;
default: echo htmlspecialchars($log['event_type']);
}
?>
</div>
<?php if ($log['field_name']): ?>
<div class="text-secondary" style="font-size: 0.75rem;">
<span class="text-decoration-line-through"><?php echo htmlspecialchars($log['old_value']); ?></span>
&rarr;
<?php if ($log['old_value'] !== null): ?>
<span class="text-decoration-line-through"><?php echo htmlspecialchars($log['old_value']); ?></span>
&rarr;
<?php endif; ?>
<span class="fw-medium"><?php echo htmlspecialchars($log['new_value']); ?></span>
</div>
<?php endif; ?>
@ -154,6 +324,69 @@ $logs = $logStmt->fetchAll();
</div>
</main>
<!-- Modals -->
<!-- Add Folder Modal -->
<div class="modal fade" id="addFolderModal" tabindex="-1" aria-labelledby="addFolderModalLabel" aria-hidden="true">
<div class="modal-dialog">
<form class="modal-content" method="POST">
<input type="hidden" name="action" value="add_folder">
<div class="modal-header">
<h5 class="modal-title" id="addFolderModalLabel">Add Custom Folder</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="mb-3">
<label for="folderName" class="form-label">Folder Name</label>
<input type="text" class="form-control" id="folderName" name="folder_name" required>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary">Create Folder</button>
</div>
</form>
</div>
</div>
<!-- Upload File Modal -->
<div class="modal fade" id="uploadFileModal" tabindex="-1" aria-labelledby="uploadFileModalLabel" aria-hidden="true">
<div class="modal-dialog">
<form class="modal-content" method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="upload_file">
<input type="hidden" name="job_job_folder_id" id="uploadFolderId">
<div class="modal-header">
<h5 class="modal-title" id="uploadFileModalLabel">Upload File to <span id="uploadFolderName"></span></h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="mb-3">
<label for="fileUpload" class="form-label">Select File</label>
<input type="file" class="form-control" id="fileUpload" name="file_upload" required>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary">Upload</button>
</div>
</form>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Populate folder ID and name in upload file modal
var uploadFileModal = document.getElementById('uploadFileModal');
uploadFileModal.addEventListener('show.bs.modal', function (event) {
var button = event.relatedTarget;
var jobJobFolderId = button.getAttribute('data-job-job-folder-id');
var folderName = button.getAttribute('data-folder-name');
var modalFolderIdInput = uploadFileModal.querySelector('#uploadFolderId');
var modalFolderNameSpan = uploadFileModal.querySelector('#uploadFolderName');
modalFolderIdInput.value = jobJobFolderId;
modalFolderNameSpan.textContent = folderName;
});
</script>
</body>
</html>
</html>

262
onboarding.php Normal file
View File

@ -0,0 +1,262 @@
<?php
require_once __DIR__ . '/includes/helpers.php';
// Placeholder for company ID - in a real app, this would come from the session after login
$company_id = get_current_company_id();
$current_user = get_current_user();
if (!$company_id) {
// Redirect to login or error page if no company is identified
header('Location: /login.php'); // Assuming a login.php exists
exit();
}
$step = isset($_GET['step']) ? (int)$_GET['step'] : 1;
$message = '';
$message_type = ''; // 'success' or 'error'
// Check if onboarding is already complete
$onboarding_complete = get_company_onboarding_status($company_id);
if ($onboarding_complete) {
header('Location: index.php');
exit();
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if ($step === 1) {
// Handle Job Status Setup submission
$statuses = $_POST['statuses'] ?? [];
$default_status_index = $_POST['default_status'] ?? null;
if (empty($statuses)) {
$message = 'Please add at least one job status.';
$message_type = 'error';
} elseif (!isset($default_status_index) || !array_key_exists($default_status_index, $statuses)) {
$message = 'Please select a default job status.';
$message_type = 'error';
} else {
try {
$pdo = db();
$pdo->beginTransaction();
// Clear existing job statuses for this company to avoid duplicates on re-submission
$stmt = $pdo->prepare("DELETE FROM job_statuses WHERE company_id = ?");
$stmt->execute([$company_id]);
$insert_stmt = $pdo->prepare("INSERT INTO job_statuses (company_id, name, is_default) VALUES (?, ?, ?)");
foreach ($statuses as $index => $status_name) {
$is_default = ($index == $default_status_index);
$insert_stmt->execute([$company_id, $status_name, $is_default]);
}
$pdo->commit();
header('Location: onboarding.php?step=2&message=Job statuses saved successfully!&message_type=success');
exit();
} catch (PDOException $e) {
$pdo->rollBack();
$message = 'Error saving job statuses: ' . $e->getMessage();
$message_type = 'error';
}
}
} elseif ($step === 2) {
// Handle Required Job Folder Setup submission
$folders = $_POST['folders'] ?? [];
if (empty($folders)) {
$message = 'Please add at least one required folder.';
$message_type = 'error';
} else {
try {
$pdo = db();
$pdo->beginTransaction();
// Clear existing job folders for this company
$stmt = $pdo->prepare("DELETE FROM job_folders WHERE company_id = ? AND is_required = TRUE");
$stmt->execute([$company_id]);
$insert_stmt = $pdo->prepare("INSERT INTO job_folders (company_id, name, is_required) VALUES (?, ?, TRUE)");
foreach ($folders as $folder_name) {
$insert_stmt->execute([$company_id, $folder_name]);
}
// Mark onboarding as complete
$stmt = $pdo->prepare("UPDATE companies SET onboarding_complete = TRUE WHERE id = ?");
$stmt->execute([$company_id]);
$pdo->commit();
header('Location: index.php?message=Onboarding complete!&message_type=success');
exit();
} catch (PDOException $e) {
$pdo->rollBack();
$message = 'Error saving job folders: ' . $e->getMessage();
$message_type = 'error';
}
}
}
}
// Get messages from URL for display
if (isset($_GET['message'])) {
$message = htmlspecialchars($_GET['message']);
$message_type = htmlspecialchars($_GET['message_type'] ?? '');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Onboarding Wizard - Repairs Pro</title>
<link rel="stylesheet" href="assets/css/custom.css">
<style>
body { font-family: 'Inter', system-ui, -apple-system, sans-serif; background-color: #F9FAFB; color: #111827; }
.container { max-width: 800px; margin: 50px auto; padding: 30px; background-color: #FFFFFF; border-radius: 4px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
h1 { color: #111827; border-bottom: 1px solid #E5E7EB; padding-bottom: 15px; margin-bottom: 30px; }
h2 { color: #3B82F6; margin-bottom: 20px; }
.form-group { margin-bottom: 20px; }
label { display: block; margin-bottom: 8px; font-weight: 500; }
input[type="text"] { width: calc(100% - 22px); padding: 10px; border: 1px solid #D1D5DB; border-radius: 4px; }
button { padding: 10px 20px; background-color: #3B82F6; color: #FFFFFF; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; }
button:hover { background-color: #2563EB; }
.status-item, .folder-item { display: flex; align-items: center; margin-bottom: 10px; }
.status-item input[type="radio"] { margin-right: 10px; }
.status-item input[type="text"], .folder-item input[type="text"] { flex-grow: 1; margin-right: 10px; }
.add-button { background-color: #10B981; margin-top: 10px; }
.add-button:hover { background-color: #059669; }
.remove-button { background-color: #EF4444; margin-left: 10px; }
.remove-button:hover { background-color: #DC2626; }
.message { padding: 15px; border-radius: 4px; margin-bottom: 20px; }
.message.success { background-color: #D1FAE5; color: #065F46; border: 1px solid #34D399; }
.message.error { background-color: #FEE2E2; color: #991B1B; border: 1px solid #F87171; }
.pagination { margin-top: 30px; text-align: center; }
.pagination button { margin: 0 10px; }
</style>
</head>
<body>
<div class="container">
<h1>Company Onboarding Wizard</h1>
<?php if ($message): ?>
<div class="message <?php echo $message_type; ?>">
<?php echo $message; ?>
</div>
<?php endif; ?>
<?php if ($step === 1): // Job Status Setup ?>
<h2>Step 1: Job Status Setup</h2>
<p>Define the different statuses a job can have within your company. One status must be set as default.</p>
<form method="POST" action="onboarding.php?step=1">
<div id="status-list">
<div class="form-group status-item">
<input type="radio" name="default_status" value="0" id="default_status_0" required>
<input type="text" name="statuses[]" value="To Be Surveyed" placeholder="e.g., To Be Surveyed" required>
<label for="default_status_0">Default</label>
</div>
<div class="form-group status-item">
<input type="radio" name="default_status" value="1" id="default_status_1">
<input type="text" name="statuses[]" value="Booking Required" placeholder="e.g., Booking Required" required>
<label for="default_status_1">Default</label>
<button type="button" class="remove-button" onclick="removeStatus(this)">Remove</button>
</div>
<div class="form-group status-item">
<input type="radio" name="default_status" value="2" id="default_status_2">
<input type="text" name="statuses[]" value="Completed" placeholder="e.g., Completed" required>
<label for="default_status_2">Default</label>
<button type="button" class="remove-button" onclick="removeStatus(this)">Remove</button>
</div>
</div>
<button type="button" class="add-button" onclick="addStatus()">Add Another Status</button>
<div class="pagination">
<button type="submit">Next Step</button>
</div>
</form>
<script>
let statusCount = 3;
function addStatus() {
const statusList = document.getElementById('status-list');
const newStatusItem = document.createElement('div');
newStatusItem.classList.add('form-group', 'status-item');
newStatusItem.innerHTML = `
<input type="radio" name="default_status" value="${statusCount}" id="default_status_${statusCount}">
<input type="text" name="statuses[]" placeholder="e.g., In Progress" required>
<label for="default_status_${statusCount}">Default</label>
<button type="button" class="remove-button" onclick="removeStatus(this)">Remove</button>
`;
statusList.appendChild(newStatusItem);
statusCount++;
updateRadioValues();
}
function removeStatus(button) {
button.closest('.status-item').remove();
updateRadioValues();
}
function updateRadioValues() {
const statusItems = document.querySelectorAll('.status-item');
statusItems.forEach((item, index) => {
item.querySelector('input[type="radio"]').value = index;
item.querySelector('input[type="radio"]').id = `default_status_${index}`;
item.querySelector('label').htmlFor = `default_status_${index}`;
});
}
</script>
<?php elseif ($step === 2): // Required Job Folder Setup ?>
<h2>Step 2: Required Job Folder Setup</h2>
<p>Define folders that will automatically appear on every job. These cannot be deleted by users.</p>
<form method="POST" action="onboarding.php?step=2">
<div id="folder-list">
<div class="form-group folder-item">
<input type="text" name="folders[]" value="PO" placeholder="e.g., PO" required>
<button type="button" class="remove-button" onclick="removeFolder(this)">Remove</button>
</div>
<div class="form-group folder-item">
<input type="text" name="folders[]" value="Quote" placeholder="e.g., Quote" required>
<button type="button" class="remove-button" onclick="removeFolder(this)">Remove</button>
</div>
<div class="form-group folder-item">
<input type="text" name="folders[]" value="Photos" placeholder="e.g., Photos" required>
<button type="button" class="remove-button" onclick="removeFolder(this)">Remove</button>
</div>
<div class="form-group folder-item">
<input type="text" name="folders[]" value="RAMS" placeholder="e.g., RAMS" required>
<button type="button" class="remove-button" onclick="removeFolder(this)">Remove</button>
</div>
<div class="form-group folder-item">
<input type="text" name="folders[]" value="Invoices" placeholder="e.g., Invoices" required>
<button type="button" class="remove-button" onclick="removeFolder(this)">Remove</button>
</div>
</div>
<button type="button" class="add-button" onclick="addFolder()">Add Another Folder</button>
<div class="pagination">
<button type="button" onclick="window.location.href='onboarding.php?step=1'" class="">Previous Step</button>
<button type="submit">Complete Onboarding</button>
</div>
</form>
<script>
let folderCount = 5;
function addFolder() {
const folderList = document.getElementById('folder-list');
const newFolderItem = document.createElement('div');
newFolderItem.classList.add('form-group', 'folder-item');
newFolderItem.innerHTML = `
<input type="text" name="folders[]" placeholder="e.g., Documents" required>
<button type="button" class="remove-button" onclick="removeFolder(this)">Remove</button>
`;
folderList.appendChild(newFolderItem);
folderCount++;
}
function removeFolder(button) {
button.closest('.folder-item').remove();
}
</script>
<?php endif; ?>
</div>
</body>
</html>