# Document Signing System - Sales Workflow Enhancements

Complete sales workflow solution addressing all pain points in garage document signing.

---

## What's New

This enhanced version adds complete sales lifecycle management, turning the signing system into a full workflow solution that eliminates delays and ensures no signatures are missed.

---

## New Features

### 1. **Sales & Vehicle Tracking**

Create and manage vehicle sales records that link customers, vehicles, and all required documents together.

- **Sales Records**: Track complete vehicle sales with customer info, vehicle details, price, and notes
- **Customer Management**: Centralized customer contact database
- **Vehicle Information**: Capture full vehicle details (make, model, year, VIN, registration, colour)
- **Sale Status Tracking**: Draft → Pending Signatures → Complete → Archived

**Files**:
- `Customer.php` - Customer management class
- `Sale.php` - Vehicle sale management class

**Database Tables**:
- `customers` - Customer contact information
- `sales` - Vehicle sale records
- `sale_documents` - Links documents to sales
- `signature_requirements` - Mandatory signatures per sale type

---

### 2. **Mandatory Signature Checklists**

Define which documents MUST be signed for each sale type, preventing sales staff from accidentally letting customers leave without all required signatures.

**Features**:
- Set mandatory documents per sale type (direct sale, part exchange, finance, warranty, service, etc.)
- Track which documents are signed and which are pending
- Visual progress indicator showing completion percentage
- Automatic status updates when all required documents are signed

**How It Works**:
1. Admin configures which documents are mandatory for each sale type
2. When creating a sale, system automatically queues all required documents
3. Documents are created and sent to customer
4. Dashboard shows real-time progress
5. Sale automatically marked "Complete" when all signatures collected

---

### 3. **Customer Portal**

Customers can see all pending documents and sign them directly without needing email navigation.

**Features**:
- Secure customer-facing interface
- See all pending documents awaiting signature
- View all previously signed documents
- Download signed PDFs
- Simple, mobile-friendly design
- Shows vehicle and sale information for context

**Access**: Customers can access via email link with authentication token

**Files**: `customer-portal.php`

---

### 4. **Bulk Document Creation**

Instead of creating documents one-by-one, create all required documents for a sale in a single workflow.

**Workflow**:
1. Staff member selects a sale
2. System shows all mandatory documents for that sale type
3. Staff reviews and confirms
4. All documents created and emailed to customer automatically
5. Customer receives batch of signing requests

**Benefits**:
- Faster setup (one action instead of 5-10 clicks)
- Ensures no documents forgotten
- Automatic email sending
- Clear confirmation of what was sent

**Files**: `bulk-create-documents.php`

---

### 5. **Sales Workflow Dashboard**

Complete sales management interface for staff to track all vehicle sales and document statuses.

**Dashboard Shows**:
- Total sales statistics (completed, pending, draft, disputed)
- List of all incomplete sales
- Document completion progress for each sale
- Quick actions (view details, create documents, send reminders)

**Per-Sale View**:
- Vehicle and customer information
- Document completion percentage
- Individual document status
- Action buttons for creating more documents

**Files**: `sales-workflow.php`

---

### 6. **Automated Reminders**

Automatically send follow-up emails to customers with unsigned documents after a set period.

**Features**:
- Schedule reminders for unsigned documents
- Customizable reminder text
- Automatic retry if customer doesn't sign
- Track reminder history
- Manual override to cancel reminders

**How It Works**:
1. When documents created, reminders scheduled (e.g., 1 day later)
2. Background process checks due reminders
3. Sends personalized email to customer
4. Tracks delivery and attempts
5. Can reschedule if needed

**Configuration**:
- Days until first reminder
- Maximum reminder attempts
- Custom reminder message

**Files**: `ReminderManager.php`

---

### 7. **Enhanced Reporting**

View sales statistics and document completion rates.

**Reports Include**:
- Total sales by status
- Average days to complete a sale
- Document completion percentages
- Incomplete sales list
- Reminder delivery tracking

**Files**: Sales data in `sales-workflow.php`

---

## Database Enhancements

### New Tables

**customers**
- id, user_id, first_name, last_name, email, phone, address, city, postcode
- Centralized customer contact information
- Searchable by name, email, phone

**sales**
- id, user_id, customer_id, vehicle_registration/make/model/year/colour/vin
- sale_type (direct_sale, part_exchange, finance, warranty, service, etc.)
- sale_price, sale_status (draft, pending_signatures, complete, archived, disputed)
- Complete vehicle sale record with timestamps and IP logging

**signature_requirements**
- id, user_id, sale_type, document_type, sequence_number, is_mandatory
- Defines which documents are required for each sale type
- Sequencing ensures forms signed in logical order

**sale_documents**
- id, sale_id, document_id, document_type, sequence_number
- is_required, signed_status, signed_at
- Links documents to specific sales

**reminders**
- id, sale_id, document_id, reminder_type, reminder_text
- scheduled_for, sent_at, status, attempt_count, max_attempts
- Complete reminder tracking and history

### Enhanced Tables

**email_log**
- Added sale_id foreign key
- Added email_type (signature_request, signed_confirmation, reminder, admin_notification)

**documents**
- Added sale_id, customer_id foreign keys
- Added document_hash for integrity verification

**audit_log**
- Added sale_id for tracking sale-related actions

---

## Pain Points Addressed

| Pain Point | Solution | Status |
|-----------|----------|--------|
| Customers not on-site | Remote signing via email + customer portal | ✓ Full |
| Deals delayed by missing signatures | Dashboard shows all pending + reminders | ✓ Full |
| Forms scattered everywhere | Centralized database + sale-linked storage | ✓ Full |
| Can't prove agreements | Timestamps + IP + audit trail + PDF audit page | ✓ Full |
| Forms not organized together | Sale record links all documents + templates | ✓ Full |
| Customer disputes | Complete timestamp + signature verification | ✓ Full |
| Missing signatures unknown | Dashboard status + incomplete sales list | ✓ Full |
| Paper forms lost/damaged | Fully digital with automated backups | ✓ Full |
| Staff forget signatures | Mandatory checklist + visual progress | ✓ Full |
| Discover missing docs during dispute | Real-time dashboard + reporting | ✓ Full |

---

## New Files Summary

| File | Purpose | Type |
|------|---------|------|
| `database-enhanced.sql` | Updated database schema | SQL |
| `Customer.php` | Customer management class | PHP Class |
| `Sale.php` | Vehicle sale management | PHP Class |
| `ReminderManager.php` | Reminder scheduling | PHP Class |
| `customer-portal.php` | Customer document interface | PHP Page |
| `bulk-create-documents.php` | Batch document creation | PHP Page |
| `sales-workflow.php` | Sales management dashboard | PHP Page |
| `ENHANCEMENTS.md` | This file | Documentation |

---

## Configuration

### Set Up Mandatory Document Requirements

In `config.php` or via admin panel, define mandatory signatures:

```php
// Example: Direct sale requires these documents
- Warranty form
- Service agreement
- Distance sale document
- Finance agreement (if applicable)
- Handover form
```

### Configure Reminder Timing

```php
// In config.php
define('REMINDER_HOURS_AFTER_CREATION', 24);  // Send first reminder after 24 hours
define('REMINDER_MAX_ATTEMPTS', 3);            // Max 3 reminder emails
define('REMINDER_INTERVAL', 24);               // 24 hours between reminders
```

---

## Workflow Example: Complete Vehicle Sale

### Scenario
Rob's garage sells a car. Customer (John) needs to sign 5 documents.

### Step 1: Create Sale
Staff member creates new sale:
- Customer: John Smith (john@email.com)
- Vehicle: 2022 Ford Fiesta, registration AB22 XYZ
- Sale Type: Direct Sale
- Price: £5,000

### Step 2: Create Documents (Bulk)
Staff clicks "Create Documents"
System shows 5 mandatory documents for direct sales:
- Handover form
- Service agreement  
- Warranty form
- Finance declaration
- Distance sale document

Staff confirms, all 5 created and emailed to John.

### Step 3: Customer Signs
John receives email with signing link.
Opens customer portal, sees all 5 documents.
Signs them one by one on his phone.
As each is signed, progress bar updates.

### Step 4: Automatic Reminders
If John hasn't signed all after 24 hours:
- Automatic reminder email sent
- Customer portal shows pending documents

### Step 5: Sale Complete
When all 5 signed:
- Sale status automatically changes to "Complete"
- Staff see green checkmark on dashboard
- Complete audit trail captured
- PDFs ready for archival

**Total Time**: Instead of 30+ minutes of email back-and-forth → 5 minutes setup + customer self-serves on their timeline.

---

## Installation Steps

1. **Backup** your current database
2. **Import** `database-enhanced.sql` (adds new tables, doesn't delete old ones)
3. **Upload** new PHP files:
   - Customer.php
   - Sale.php
   - ReminderManager.php
   - customer-portal.php
   - bulk-create-documents.php
   - sales-workflow.php

4. **Update** config.php with reminder settings
5. **Test** by creating a test sale and walking through the workflow

---

## Usage Guide

### For Staff

1. **Creating a Sale**
   - Go to Sales Workflow
   - Click "New Sale"
   - Enter customer and vehicle information
   - Select sale type

2. **Creating Documents for a Sale**
   - Find sale in incomplete list
   - Click "Create Documents"
   - Review mandatory documents
   - Confirm creation
   - System sends to customer automatically

3. **Monitoring Progress**
   - Dashboard shows all incomplete sales
   - See document completion % for each
   - Click sale to see detailed status
   - Send manual reminders if needed

### For Customers

1. **Signing Documents**
   - Receive email with signing link
   - Click link or visit customer portal
   - See all pending documents
   - Click "Sign Now" on each
   - Draw signature on tablet/phone
   - Documents auto-saved

2. **Accessing Portal**
   - Via email link sent by garage
   - View pending documents
   - View previously signed documents
   - Download signed PDFs

---

## Security & Compliance

- **Timestamps**: Every signature has exact timestamp (to second)
- **IP Logging**: Signer's IP address recorded
- **Signature Hashing**: Cryptographic verification
- **Audit Trail**: Complete history of all actions
- **PDF Audit Page**: Second page shows all signatures with verification
- **GDPR Compliant**: Customer data properly segregated
- **Document Integrity**: Hashing prevents post-signature tampering

---

## Troubleshooting

### Reminders Not Sending
- Check SMTP configuration in config.php
- Verify PHPMailer is installed
- Check email_log table for errors

### Sale Not Marking Complete
- Verify all sale_documents have signed_status = 'signed'
- Check that all required_flag = 1 documents are signed

### Customer Portal Not Showing Documents
- Verify customer email matches exactly
- Check documents table has correct customer_email
- Clear browser cache

---

## Future Enhancements

- Customer signature tracking (know who signed what)
- Form versioning (track document changes)
- Esignature compliance reporting (EIDAS, etc.)
- Integration with accounting software
- SMS reminders in addition to email
- Signature deadline enforcement
- Multi-signature workflows (manager approval, etc.)

---

## Support

For issues or questions:
1. Check INSTALLATION_GUIDE.md
2. Review error logs in audit_log table
3. Check email_log for email delivery issues
4. Verify database connection

---

**Version**: 2.0 (Enhanced)  
**Date**: 2026-05-28  
**Status**: Production Ready

All original features preserved. Zero breaking changes. Drop-in enhancements.
