# Premiere Warehousing - Business Logic Documentation

This document provides a comprehensive overview of the business logic, module relationships, and operational workflows within the Premiere Warehousing system.

---

## Table of Contents

1. [System Overview](#system-overview)
2. [Master Modules](#master-modules)
3. [Module Relationships](#module-relationships)
4. [Yard Check Module](#yard-check-module)
5. [Schedule Module](#schedule-module)
6. [Invoice Module](#invoice-module)
7. [Reports Module](#reports-module)
8. [Business Rules Summary](#business-rules-summary)
9. [Integration Points](#integration-points)

---

## System Overview

The Premiere Warehousing system is a comprehensive warehouse management platform that handles trailer operations, scheduling, and billing. The system manages the complete lifecycle from trailer entry to invoice payment processing.

### Core Business Flow

#### High-Level Process Flow

```
Trailer Entry → Yard Check → Scheduling → Operations → Invoice Generation → Payment Processing
```

#### Detailed Business Process Flow

**1. Trailer Management Cycle**

```
Gate Entry (QR Scan) → empty Status → Yard Check Activities → loaded Status → completed Status → out Status → Gate Exit
```

**2. Scheduling & Operations Cycle**

```
Trailer Selection (empty/loaded/completed) → Schedule Creation → Door Assignment → Service/Equipment Assignment →
Driver Login → Operations Execution → Driver Logout → Schedule Completion
```

**3. Billing & Payment Cycle**

```
Schedule Completion → Invoice Generation → Client Grouping → Tax Calculation →
Invoice Delivery → Payment Processing (CSV Upload) → Status Updates → Credit Memo Processing (if needed)
```

**4. Status Progression Flow**

```
Trailer: empty → loaded → completed → out
Schedule: Created → In Progress → Completed
Invoice: Draft → Unpaid → Underpaid/Paid/Overpaid
Credit Memo: OPEN → CLOSED
```

#### Key Integration Points

-   **Yard Check ↔ Scheduling**: Only available trailers can be scheduled
-   **Scheduling ↔ Invoicing**: Completed schedules generate invoice items
-   **Scheduling ↔ Reports**: Reports aggregate data from completed schedules
-   **Invoicing ↔ Payments**: Payment status affects invoice status
-   **Credit Memos ↔ Invoicing**: Credit memos adjust invoice balances

---

## Master Modules

### 1. Services Module

**Purpose**: Manages warehouse services and operations

**Key Features**:

-   Service definitions and pricing
-   Location-specific service availability
-   Service categories and types
-   Add-on services and customizations

**Business Rules**:

-   Services are location-specific
-   Services are **not subject to tax**
-   Services can have different pricing models

### 2. Equipment Module

**Purpose**: Manages warehouse equipment and usage tracking

**Key Features**:

-   Equipment inventory and specifications
-   Location-based equipment assignment
-   Usage tracking and billing

**Business Rules**:

-   Equipment is location-specific
-   Equipment usage is **always subject to tax**
-   Equipment is always charged to carrier's client

### 3. Clients Module

**Purpose**: Manages customer relationships and billing preferences

**Key Features**:

-   Client registration and management
-   Payment responsibility settings
-   Client-specific service templates

**Business Rules**:

-   Clients can be location or carriers
-   Payment responsibility settings determine billing rules

---

## Module Relationships

### Parent-Child Relationships

```
Clients (Parent)
├── Locations (Child)
└── Carriers (Child)
    └── Trailers (Child of Carriers)
```

### Location Settings

**Location Components**:

-   **Doors**: Individual loading/unloading points
-   **Services**: Available services at the location
-   **Equipment**: Available equipment at the location
-   **Payment Settings**: Who pays for services at this location

**Location Configuration**:

-   Each location can have multiple doors
-   Services and equipment are location-specific
-   Payment responsibility is set per location

---

## Yard Check Module

### Overview

The Yard Check module manages trailer entry and exit from the warehouse yard, making trailers available for scheduling operations.

### QR Code Scanning Process

#### Trailer Entry Process

**Process Flow**:

1. **Gate Entry**: Trailer arrives at warehouse gate
2. **QR Code Scan**: Gate staff scans trailer's QR code
3. **Form Completion**: Driver fills in required information using gate passcode
4. **Status Update**: Trailer status changes to **empty**
5. **Availability**: Trailer becomes available for scheduling

**Required Information**:

-   Carrier information
-   Trailer number
-   Trailer type and specifications
-   Driver details
-   Entry date and time

#### Trailer Exit Process

**Process Flow**:

1. **Gate Exit**: Trailer ready to leave warehouse
2. **QR Code Scan**: Gate staff scans trailer's QR code
3. **Status Update**: Trailer status changes to **out**
4. **Completion**: Trailer is no longer available for scheduling

### Business Rules

**Yard Check Status Values**:

-   `empty` - Trailer is empty and available for operations
-   `loaded` - Trailer has been loaded with cargo
-   `completed` - Trailer operation is completed
-   `out` - Trailer has left the warehouse yard

**Yard Check Activity Types**:

-   `pending` - Activity is pending
-   `loading` - Currently loading trailer
-   `unloading` - Currently unloading trailer
-   `loaded` - Trailer has been loaded
-   `empty` - Trailer is empty
-   `out` - Trailer has left
-   `completed` - Operation completed

**Yard Check Rules**:

-   There is passcode on gate for filling trailer information
-   Only trailers with `empty`, `loaded`, or `completed` status are available for scheduling
-   QR codes must be valid and properly formatted
-   All required information must be completed before status update

**Trailer Status Lifecycle**:

```
Gate Entry → empty → loaded → completed → out → Gate Exit
```

---

## Schedule Module

### Overview

The Schedule module manages warehouse operations, coordinating trailers, services, and equipment for loading/unloading operations.

### Scheduling Process

#### Trailer Selection

**Availability Criteria**:

-   Trailer must have `empty`, `loaded`, or `completed` status
-   Trailer must be at the correct location
-   Trailer must not be already scheduled for the time period
-   Trailer must match carrier requirements (if specified)

#### Door Assignment

**Assignment Process**:

1. **Location Selection**: Choose warehouse location
2. **Door Selection**: Select specific door for operation

### Schedule Components

**Required Elements**:

-   **Client**: Who the schedule is for
-   **Location**: Which warehouse location
-   **Door**: Specific door assignment
-   **Trailer**: Which trailer to use
-   **Services**: Required services for the operation
-   **Equipment**: Required equipment for the operation

### Schedule Completion

**Completion Process**:

1. **Operations Begin**: Driver starts the scheduled operation
2. **Progress Tracking**: Monitor operation progress
3. **Completion Marking**: Driver marks trailer as **Completed**
4. **Next Operation**: Trailer becomes available for next operation

### Business Rules

**Scheduling Constraints**:

-   Only trailers with `empty`, `loaded`, or `completed` status can be scheduled
-   Resources can be double-booked

---

## Invoice Module

### Overview

The Invoice module handles billing for warehouse operations, processing services and equipment usage with complex payment responsibility rules.

### Invoice Generation Process

#### Payment Responsibility Assignment

**Equipment Billing Rules**:

-   **Always charged to carrier's client**
-   Equipment used during loading/unloading operations
-   Tax is applied to equipment costs
-   Billing is independent of location settings

**Service Billing Rules**:

-   **Charged based on location settings**:
    -   If location setting = **"carrier"** → charged to carrier's client
    -   If location setting = **"location"** → charged to location's client
-   Services are **not subject to tax**
-   Billing depends on location configuration

#### Invoice Creation Logic

**Grouping Process**:

1. **Client Grouping**: Group all items by `pay_by_client_id`
2. **Invoice Generation**: Create separate invoice for each client
3. **Item Assignment**: Assign services/equipment to appropriate invoice
4. **Tax Calculation**: Apply tax only to equipment costs

**Invoice Contents**:

-   All services where `pay_by_client_id` matches client
-   All equipment where `pay_by_client_id` matches client
-   Tax calculations for equipment only
-   Total amounts and payment terms

### Tax Rules

**Tax Application**:

-   **Equipment**: Subject to tax (based on location tax rate)
-   **Services**: Not subject to tax
-   **Tax Calculation**: `Tax Amount = (Equipment Sub Total × Tax Rate) / 100`

**Tax Formula**:

```
Total Equipment Cost = Equipment Sub Total + Tax Amount
Total Service Cost = Service Sub Total (no tax)
Invoice Total = Total Equipment Cost + Total Service Cost
```

### Invoice Lifecycle

#### Status Definitions

1. **Draft**

    - Invoice created but not finalized (completed_steps != 3)
    - Can be modified or cancelled
    - Not sent to client

2. **Unpaid**

    - No payments received yet

3. **Underpaid** (was "Partially Paid")

    - Some payments received but less than total amount
    - Balance remains outstanding
    - Additional payments expected

4. **Paid**

    - Full amount received
    - Invoice completely settled
    - No further action required

5. **Overpaid** (was "Over Paid")

    - More amount received than invoice total
    - Current balance < 0
    - May require refund processing

6. **Overdue**
    - Payment past due date
    - Calculated dynamically based on due_date
    - No payments received or underpaid

#### Status Transitions

```
Draft → Unpaid → Underpaid → Paid → Overpaid
  ↓       ↓        ↓       ↓
Overdue ← ← ← ← ← ← ← ← ← ←
```

### Credit Memo Sub-Module

#### Overview

Credit memos are invoice sub-modules that handle adjustments to service and equipment charges, providing refunds and corrections to invoices.

#### Credit Memo Status

**Status Values**:

-   `OPEN` - Credit memo is active and can be modified
-   `CLOSED` - Credit memo is finalized and cannot be modified

#### Credit Memo Creation

**Triggers**:

-   Invoice adjustments and corrections
-   Service cancellations
-   Equipment issues and refunds
-   Client disputes and resolutions
-   Partial refunds

#### Credit Memo Calculations

**Service Credit Calculation**:

```
Service Credit Amount = Credit Amount (if specified) OR Original Service Total Charges
```

**Equipment Credit Calculation**:

_Custom Credit Amount_:

```
Sub Total = Custom Credit Amount
Tax Amount = Sub Total × Tax Rate
Total Amount = Sub Total + Tax Amount
```

_Full Credit (No Custom Amount)_:

```
Sub Total = Original Equipment Sub Total
Tax Amount = Original Equipment Tax Amount
Total Amount = Original Equipment Total Charges
```

#### Net Amount Calculations

**Service Totals**:

```
Net Service Total = Σ(Service Total Charges) - Σ(Service Credit Memo Amounts)
```

**Equipment Totals**:

```
Net Equipment Sub Total = Σ(Equipment Sub Totals) - Σ(Equipment Credit Sub Totals)
Net Equipment Tax = Σ(Equipment Tax Amounts) - Σ(Equipment Credit Tax Amounts)
Net Equipment Total = Σ(Equipment Total Charges) - Σ(Equipment Credit Total Amounts)
```

**Current Balance**:

```
Current Balance = (Net Service Total + Net Equipment Total) - Payments Received
```

### Payment Processing Sub-Module

#### Overview

The payment processing system handles CSV-based payment uploads and tracks payment status against invoices.

#### CSV Payment Format

**Required Fields**:

| Field          | Description               | Format             | Example    |
| -------------- | ------------------------- | ------------------ | ---------- |
| Invoice Number | Unique invoice identifier | String             | IN-0001    |
| Amount Paid    | Payment amount            | Numeric            | 5000       |
| Paid Date      | Payment date              | MM-DD-YYYY or null | 07-22-2025 |

**CSV Example**:

```csv
Invoice Number,Amount Paid,Paid Date
IN-0001,5000,07-22-2025
IN-0002,2000,07-21-2025
IN-0003,1000,07-20-2025
IN-0004,500,
IN-0005,100,
```

#### Payment Processing Workflow

1. **File Upload**

    - CSV file uploaded to system
    - File format validation
    - Required field verification

2. **Payment Matching**

    - Match payments to existing invoices
    - Validate invoice numbers
    - Check for duplicate payments

3. **Amount Validation**

    - Verify payment amounts
    - Check against invoice totals
    - Handle overpayment scenarios

4. **Status Update**
    - Update invoice payment status
    - Calculate new balances
    - Trigger status transitions

#### Payment Status Logic

**Status Updates**:

-   If `Paid Amount = 0`: Invoice status → **"unpaid"**
-   If `Current Balance = 0`: Invoice status → **"paid"**
-   If `Current Balance > 0`: Invoice status → **"underpaid"**
-   If `Current Balance < 0`: Invoice status → **"overpaid"**

#### Payment Validation Rules

**Validation Requirements**:

-   Payment amounts must be positive
-   Duplicate payments are rejected
-   Payment dates cannot be in the future
-   Invoice numbers must exist in system

**Status Updates**:

-   Status automatically updated based on payments
-   Credit memos affect balance calculations
-   Overdue status triggered by due date

---

## Reports Module

### Overview

The Reports module provides comprehensive analytics and automated report generation capabilities for warehouse operations. It aggregates data from completed schedules to generate insights on services and equipment usage, supporting data-driven decision-making and automated stakeholder communication.

The module supports both one-time report generation for manual analysis and scheduled automated report delivery via email, making it a critical tool for operational monitoring and compliance reporting.

### Report Types

#### 1. One-Time Reports (Download-Only)

**Purpose**: Manual report generation for on-demand analysis

**Key Features**:

-   User-initiated report generation
-   Downloadable in multiple formats (PDF, XLSX, CSV)
-   Custom time frame selection
-   Location, carrier, and driver filtering
-   Immediate data retrieval based on selected criteria

**Use Cases**:

-   Ad-hoc operational analysis
-   Spot checks on performance metrics
-   Custom date range investigations
-   Data export for external analysis

**Business Rules**:

-   Reports are generated on-demand when requested
-   Time frame must be explicitly selected
-   Filters apply to all selected locations, carriers, or drivers
-   Report data reflects current state of completed schedules

**One-Time Report Creation Process**:

1. **Report Configuration**

    - User selects report name
    - Chooses report type: Single Time Frame OR Comparison Time Frame
    - Selects time frame(s):
        - **Single Time Frame**: Start date and end date (one period)
        - **Comparison Time Frame**: User selects two separate time frames:
            - Time Frame 1: Start date and end date (first period)
            - Time Frame 2: Start date and end date (second period)

2. **Metric Selection**

    - User selects from available metrics
    - **Important**: Must choose either calculation metrics OR information metrics (not both)
    - Can select multiple metrics within the chosen category

3. **Filter Configuration**

    - Location selection: Specific locations OR "All Locations"
    - Carrier selection: Specific carriers OR "All Carriers"
    - Driver selection: Specific drivers OR "All Drivers"

4. **Report Generation**

    - System queries completed schedules based on filters and time frame
    - Aggregates data by location for selected metrics
    - Generates report data structure

5. **Export and Download**
    - User selects export format (PDF, XLSX, CSV)
    - System generates file in selected format
    - User downloads file immediately

#### 2. Scheduled Reports (Automated Email Delivery)

**Purpose**: Automated report generation and delivery to stakeholders

**Key Features**:

-   Automated generation at scheduled intervals
-   Email delivery via SendGrid dynamic email templates
-   Rolling time frame calculations based on schedule execution time
-   Multi-recipient email distribution
-   Format selection (PDF, XLSX, CSV) per email configuration
-   Email delivery logging and failure tracking

**Use Cases**:

-   Regular performance dashboards for management
-   Weekly operational summaries
-   Monthly financial reports
-   Automated compliance reporting

**Business Rules**:

-   Reports must be configured with email recipients and configuration
-   Time frames are calculated dynamically based on schedule execution time
-   Only single time frame reports can be scheduled (comparison reports excluded)
-   Email delivery failures are logged for monitoring and troubleshooting

**Scheduled Report Creation Process**:

1. **Report Configuration**

    - User selects report name
    - Marks report as scheduled or create new one
    - **Note**: Comparison time frame option is disabled for scheduled reports

2. **Metric Selection**

    - User selects calculation metrics OR information metrics
    - Same mutual exclusivity rules apply

3. **Filter Configuration**

    - Location, carrier, and driver filtering (same as one-time reports)

4. **Schedule Configuration**

    - **Frequency Selection**:
        - Daily: Every day
        - Weekly: Specific day of week (1-7, Monday-Sunday)
        - Monthly: Specific day of month (1-31)
    - **Time to Send**: Specific time of day (HH:MM format)
    - **Rolling Time Frame**: Select from predefined options:
        - `today`, `yesterday`, `last_7_days`, `previous_week`, `current_month`, `previous_month`, or `custom`
    - **Custom Time Frame** (if selected):
        - Number of periods: e.g., 14 days, 3 weeks, 2 months
        - Time unit: days, weeks, or months

5. **Email Configuration**

    - **Recipients**: Add one or more email addresses
    - **Email Title**: Subject line (supports `[DateSent]` placeholder)
    - **Report Format**: PDF, XLSX, or CSV (applied to all emails)
    - SendGrid dynamic template selection

6. **Schedule Activation**
    - System calculates `next_run_at` based on frequency and time to send
    - Schedule marked as active (`is_active = true`)
    - Report ready for automated execution

**Scheduled Report Execution Process**:

1. **ScheduleBatch Command Execution** (runs every 30 minutes)

    - Finds schedules with `next_run_at` between -3 hours and +30 minutes
    - Validates schedule is active and report is not deleted
    - Queues `ProcessScheduledReport` job for each ready schedule

2. **ProcessScheduledReport Job Execution**

    - Validates execution window (-3 hours to +5 minutes)
    - Checks schedule is still active
    - Validates email configuration and recipients exist

3. **Report Data Generation**

    - Calculates actual time frame dates based on rolling time frame option
    - Queries completed schedules matching filters and time frame
    - Aggregates data by location for selected metrics
    - Generates report data structure

4. **File Generation**

    - Creates report file in configured format (PDF/XLSX/CSV)
    - Formats filename with timestamp and date sent placeholder
    - Prepares file for email attachment

5. **Email Delivery**

    - Sends email via SendGrid using dynamic template
    - Attaches generated report file
    - Includes report name and date range in email body
    - Logs email delivery attempt (success or failure)

6. **Schedule Progression**
    - Updates `last_run_at` timestamp (on success)
    - Calculates `next_run_at` for next execution based on frequency
    - Updates schedule record
    - Schedule continues for next period

### Report Generation Process Flow

#### Data Aggregation Workflow

**Step-by-Step Data Processing**:

1. **Schedule Query**

    - Filter schedules by location (if not "all locations")
    - Filter schedules by carrier (if not "all carriers")
    - Filter schedules by driver (if not "all drivers")

2. **Time Frame Filtering**

    - For each schedule, check service and equipment creation dates
    - Include schedules where services/equipment fall within time frame
    - Uses `created_at` timestamp of scheduled services/equipment

3. **Data Grouping**

    - Group schedules by location (or location + carrier combination)
    - For each location group, collect all related services and equipment

4. **Metric Calculation**

    - **For Calculation Metrics**:
        - `services_number`: Count all services in location group
        - `equipment_number`: Count all equipment in location group
        - `services_amount`: Sum `total_charges` or `price` of all services
        - `equipment_amount`: Sum `total_charges` or `price` of all equipment
    - **For Information Metrics**:
        - `services_details`: Collect all service records with full details
        - `equipment_details`: Collect all equipment records with full details

5. **Report Structure Assembly**

    - **Calculation Metrics**: Create single table with:
        - Rows: One per location
        - Columns: Selected calculation metrics
        - Totals row: Sum of all metrics across all locations
    - **Information Metrics**: Create separate table per metric with:
        - Columns: Date, Location, Item Name, Carrier, Trailer, Price
        - Rows: One per service/equipment record
        - No totals (detailed listing only)

6. **Format Generation**
    - PDF: Renders tables using PDF template with professional formatting
    - XLSX: Creates spreadsheet with proper column headers and data rows
    - CSV: Generates comma-separated values with header row

#### Example Report Structures

**Example 1: Calculation Metrics Report (Single Time Frame)**

```
Report: Monthly Services Summary - January 2025

Location          | Services (#) | Equipment (#) | Services ($) | Equipment ($)
------------------|--------------|----------------|--------------|---------------
Warehouse A       | 150          | 75             | $45,000      | $22,500
Warehouse B       | 200          | 100            | $60,000      | $30,000
Warehouse C       | 120          | 60             | $36,000      | $18,000
------------------|--------------|----------------|--------------|---------------
Grand Total       | 470          | 235            | $141,000     | $70,500
```

**Example 2: Information Metrics Report (Services Details)**

```
Report: Services Detail Report - January 2025

Date       | Location    | Service       | Carrier    | Trailer  | Price
-----------|-------------|---------------|------------|----------|--------
2025-01-05 | Warehouse A | Loading       | Carrier X  | TR-1234  | $500
2025-01-05 | Warehouse A | Unloading     | Carrier X  | TR-1234  | $400
2025-01-06 | Warehouse A | Loading       | Carrier Y  | TR-5678  | $550
...        | ...         | ...           | ...        | ...      | ...
```

**Example 3: Comparison Report (Calculation Metrics)**

```
Report: Services (#) Comparison

Location    | Time Frame 2 | Time Frame 1 | Total Change | % Change
------------|-------------|-------------|-------------|----------
Warehouse A | 140          | 150         | +10         | +7.14%
Warehouse B | 180          | 200         | +20         | +11.11%
Warehouse C | 110          | 120         | +10         | +9.09%
------------|-------------|-------------|-------------|----------
Grand Total | 430          | 470         | +40         | +9.30%
```

### Report Generation Modes

#### 1. Single Time Frame Reports

**Purpose**: Analyze data within a single time period

**Key Features**:

-   Single date range selection
-   Aggregated metrics display
-   Location-based breakdown
-   Can be used for both one-time and scheduled reports

**Report Structure**:

-   **Calculation Metrics**: Single table with rows per location, columns per metric, grand totals
-   **Information Metrics**: Separate table per metric showing detailed line items
-   **Mixed Metrics**: Not allowed (mutual exclusivity rule)

**Time Frame Options (One-Time Reports)**:

-   Custom date range selection
-   Start and end dates explicitly defined

**Time Frame Options (Scheduled Reports - Rolling)**:

-   `today` - Current day to date
-   `yesterday` - Previous complete day
-   `last_7_days` - Last 7 days including today
-   `previous_week` - Complete previous calendar week
-   `current_month` - Current month from start to date
-   `previous_month` - Complete previous calendar month
-   `custom` - Custom rolling period (days, weeks, or months)

**Business Rules**:

-   Time frames are calculated at report generation time
-   For scheduled reports, rolling time frames ensure consistent relative periods
-   Date calculations use configured schedule timezone (default: America/New_York)

#### 2. Comparison Time Frame Reports (Double Time Frame)

**Purpose**: Compare performance across two different time periods

**Key Features**:

-   **Two time frames selected by user** (Time Frame 1 and Time Frame 2)
-   Side-by-side comparison tables
-   Change calculations (absolute and percentage)
-   Per-metric comparison tables
-   Cannot be scheduled (one-time generation only)

**Time Frame Selection**:

Users must explicitly select two time frames for comparison:

-   **Time Frame 1**: Start date and end date for the first period
-   **Time Frame 2**: Start date and end date for the second period to compare against

Both time frames are independent and can be any date ranges (e.g., current month vs previous month, last 7 days vs previous 7 days, custom periods).

**Report Structure**:

-   One comparison table generated per selected calculation metric
-   Each table shows:
    -   Location name
    -   Time Frame 2 value (second period)
    -   Time Frame 1 value (first period)
    -   Total change (absolute difference)
    -   Percentage change
-   Grand totals row with aggregated comparisons

**Comparison Calculations**:

-   **Total Change**: `Time Frame 1 Value - Time Frame 2 Value`
-   **Percentage Change**:
    -   If Time Frame 2 = 0 and Time Frame 1 > 0: 100%
    -   If Time Frame 2 = 0 and Time Frame 1 = 0: 0%
    -   Otherwise: `((Total Change / Time Frame 2 Value) × 100)`

**Business Rules**:

-   Comparison reports cannot be scheduled (manual generation only)
-   **Both time frames must be explicitly selected by the user** (start and end dates for each period)
-   Only calculation metrics generate comparison tables
-   Information metrics are not supported in comparison reports
-   Time frames can be of different durations (e.g., compare 7 days vs 30 days)

### Metric Selection

The Reports module supports six distinct metrics organized into two mutually exclusive categories.

#### Calculation Metrics (`used_type = "calculation"`)

These metrics provide aggregated numerical summaries:

1. **Services (#)** (`services_number`)

    - **Type**: Count
    - **Aggregation**: Count of services performed
    - **Display**: Number of services per location

2. **Equipment (#)** (`equipment_number`)

    - **Type**: Count
    - **Aggregation**: Count of equipment items used
    - **Display**: Number of equipment per location

3. **Services ($ Amount)** (`services_amount`)

    - **Type**: Currency
    - **Aggregation**: Sum of service charges
    - **Display**: Total monetary value of services per location

4. **Equipment ($ Amount)** (`equipment_amount`)
    - **Type**: Currency
    - **Aggregation**: Sum of equipment charges
    - **Display**: Total monetary value of equipment per location

**Report Format**:

-   Single table structure
-   Rows: One per location (or carrier/location combination)
-   Columns: Selected calculation metrics
-   Totals: Grand total row with aggregated sums

#### Information Metrics (`used_type = "information"`)

These metrics provide detailed line-item listings:

5. **Services (Details)** (`services_details`)

    - **Type**: List
    - **Aggregation**: None (detailed records)
    - **Display**: Line items with columns:
        - Date (`service_date`)
        - Location (`location_name`)
        - Service Name (`item_name`)
        - Carrier (`carrier_name`)
        - Trailer (`trailer_number`)
        - Price (`price`)

6. **Equipment (Details)** (`equipment_details`)
    - **Type**: List
    - **Aggregation**: None (detailed records)
    - **Display**: Line items with columns:
        - Date (`service_date`)
        - Location (`location_name`)
        - Equipment Name (`item_name`)
        - Carrier (`carrier_name`)
        - Trailer (`trailer_number`)
        - Price (`price`)

**Report Format**:

-   Separate table per information metric
-   Each table shows detailed line items
-   No aggregation or totals (detailed listing only)

#### Metric Selection Rules

**Mutual Exclusivity Rule**:

-   **Calculation metrics and Information metrics cannot be mixed in the same report**
-   Users must select either:
    -   One or more calculation metrics (Services #, Equipment #, Services $, Equipment $), OR
    -   One or more information metrics (Services Details, Equipment Details)
-   This rule ensures consistent report structure and meaningful data presentation

**Rationale**:

-   Calculation metrics aggregate data for summary analysis
-   Information metrics provide detailed transactional listings
-   Mixing types creates incompatible data structures

### Data Sources and Filtering

#### Data Aggregation

Reports aggregate data from completed schedules within the selected time frame:

**Source Data**:

-   **Schedules**: Completed schedules with services and equipment
-   **Scheduled Services**: Services performed during operations
-   **Scheduled Equipment**: Equipment used during operations

**Aggregation Logic**:

-   Data grouped by location (or location + carrier combination)
-   Services counted/summed per location
-   Equipment counted/summed per location
-   Time frame filtering based on service/equipment `created_at` timestamps

#### Filtering Options

**Location Filtering**:

-   Select specific locations OR select all locations
-   Filter applied to schedule locations
-   `has_all_locations` flag controls filtering behavior

**Carrier Filtering**:

-   Select specific carriers OR select all carriers
-   Filter applied to schedule carriers
-   `has_all_carriers` flag controls filtering behavior

**Driver Filtering**:

-   Select specific drivers OR select all drivers
-   Filter applied to schedule drivers
-   `has_all_drivers` flag controls filtering behavior

**Filter Type**:

-   `service` - Only include schedules with services
-   `equipment` - Only include schedules with equipment
-   `all` - Include all schedules (default)

**Business Rules**:

-   Filters are applied at the schedule level
-   Time frame filtering checks service/equipment creation dates
-   All filters are optional (can select "all" for any filter)

### Scheduling System

#### Schedule Configuration

Scheduled reports require comprehensive configuration for automated execution:

**Frequency Types**:

-   **Daily**: Report generated and emailed every day at specified time
-   **Weekly**: Report generated on specific day of week (Monday-Sunday)
    -   Value: 1-7 (1 = Monday, 7 = Sunday)
-   **Monthly**: Report generated on specific day of month
    -   Value: 1-31 (day of month)

**Time to Send**:

-   Specific time of day for email delivery
-   Format: HH:MM (e.g., 09:00, 14:30)
-   Default: 09:00
-   Timezone-aware (uses configured schedule timezone)

**Rolling Time Frame**:

-   Time frame calculated dynamically based on when schedule executes
-   Options: `today`, `yesterday`, `last_7_days`, `previous_week`, `current_month`, `previous_month`, `custom`
-   Custom time frames support days, weeks, or months as units

**Email Configuration**:

-   **Recipients**: Multiple email addresses for report distribution
-   **Email Title**: Subject line template (supports `[DateSent]` placeholder)
-   **Report Format**: PDF, XLSX, or CSV for email attachment
-   **SendGrid Template**: Dynamic email template for professional formatting

#### Automated Scheduling System

**ScheduleBatch Command** (`reports:schedule-batch`):

**Execution**:

-   Runs every 30 minutes via cron
-   Checks for schedules ready to execute
-   Queues report generation jobs

**Processing Window**:

-   Looks for schedules from 3 hours ago to 30 minutes in the future
-   Handles both upcoming schedules and missed schedule recovery

**Missed Schedule Recovery**:

-   **Recent Misses (0-5 minutes)**: Immediate execution allowed
-   **Medium Misses (5 minutes - 3 hours)**: Retry and reschedule
-   **Old Misses (>3 hours)**: Reschedule only (no retry to prevent stale data)

**Abandoned Schedule Handling**:

-   Schedules older than 3 hours are considered "abandoned"
-   Abandoned schedules are rescheduled for next appropriate time
-   No retry attempted (data would be stale)
-   Prevents schedules from getting permanently stuck

**Execution Window Validation**:

-   `ProcessScheduledReport` job validates execution window (-3 hours to +5 minutes)
-   Prevents race conditions from admin schedule changes
-   Ensures reports are generated at appropriate times

**Schedule Progression**:

-   After successful execution, schedule updates:
    -   `last_run_at`: Timestamp of successful execution
    -   `next_run_at`: Calculated based on frequency for next run
-   After failure, schedule still updates `next_run_at` to prevent getting stuck

**Business Rules**:

-   Only active schedules with active reports are processed
-   Deleted schedules and deleted reports are skipped
-   Email configuration must exist before scheduling
-   Recipients must be configured before email delivery

### Export Formats

Reports support three export formats, each optimized for different use cases:

#### PDF Format

-   **Best For**: Printing, sharing, formal reporting
-   **Features**: Professional formatting, page breaks, landscape orientation
-   **Use Cases**: Executive summaries, printed reports, compliance documentation

#### XLSX Format (Excel)

-   **Best For**: Data analysis, calculations, editing
-   **Features**: Spreadsheet format, editable cells, formulas support
-   **Use Cases**: Financial analysis, data manipulation, further calculations

#### CSV Format

-   **Best For**: Data import/export, system integration
-   **Features**: Plain text, comma-separated values, universal compatibility
-   **Use Cases**: Database imports, third-party system integration, bulk data transfer

**Format Selection**:

-   One-time reports: Selected at generation time
-   Scheduled reports: Configured in email settings (applied to all emails)

### Business Rules Summary

#### Report Generation Rules

1. **Metric Selection**

    - Calculation metrics and Information metrics are mutually exclusive
    - Cannot mix calculation and information metrics in same report

2. **Scheduling Constraints**

    - Only single time frame reports can be scheduled
    - Comparison time frame reports cannot be scheduled (manual only)

3. **Time Frame Rules**

    - Scheduled reports use rolling time frames calculated at execution time
    - One-time reports use fixed date ranges explicitly selected
    - **Comparison reports require two time frames selected by user** (Time Frame 1 and Time Frame 2)
    - Custom time frames support days, weeks, or months

4. **Data Filtering**
    - Filters apply at schedule level
    - Time frame filtering uses service/equipment creation timestamps
    - All filters are optional ("all" option available)

#### Email Delivery Rules

1. **Configuration Requirements**

    - Email configuration must exist for scheduled reports
    - At least one recipient must be configured
    - Email format must be specified

2. **Delivery Process**

    - Reports generated before email sending
    - SendGrid dynamic template used for email body
    - Report attached in configured format
    - Email delivery logged for audit trail

3. **Failure Handling**
    - Email failures logged with error messages
    - Schedule continues to next run even after failure
    - Failed deliveries can be monitored and retried manually

#### Schedule Execution Rules

1. **Execution Window**

    - Valid window: -3 hours to +5 minutes from current time
    - Schedules outside window are skipped
    - Prevents stale data and race conditions

2. **Missed Schedule Recovery**

    - Recent misses (0-5 min): Immediate execution
    - Medium misses (5 min - 3 hours): Retry and reschedule
    - Old misses (>3 hours): Reschedule only (no retry)

3. **Schedule Progression**
    - Next run time calculated based on frequency after each execution
    - Schedule continues even after failures
    - Last run timestamp updated only on successful execution

---

## Business Rules Summary

### Core Business Rules

1. **Trailer Operations**

    - Only `empty`, `loaded`, or `completed` status trailers can be scheduled
    - QR code scanning required for entry/exit
    - Trailers must be at correct location for scheduling

2. **Billing Rules**

    - Equipment always charged to carrier's client
    - Services charged based on location settings
    - Equipment subject to tax, services are not

3. **Invoice Processing**

    - Separate invoices created per client
    - Payment responsibility determined by business rules
    - Credit memos adjust invoice balances

4. **Payment Processing**

    - CSV-based payment uploads
    - Automatic status updates
    - Duplicate payment prevention

5. **Report Generation**
    - Calculation and Information metrics are mutually exclusive
    - Only single time frame reports can be scheduled
    - Comparison reports require manual generation
    - Scheduled reports use rolling time frames

### Data Integrity Rules

1. **Referential Integrity**

    - All foreign keys must reference valid records
    - Cascade deletes handled appropriately
    - Orphaned records prevented

2. **Business Logic Validation**
    - Status transitions follow defined rules
    - Calculations use consistent formulas
    - Data validation at all entry points

---

## Integration Points

### External Systems

1. **QR Code System**

    - Trailer identification and tracking
    - Gate entry/exit processing
    - Status management

2. **Email Services**

    - Invoice delivery
    - Scheduled report delivery via SendGrid dynamic templates

3. **File Storage**

    - Invoice PDF generation

4. **Report Scheduling System**
    - Automated report generation via ScheduleBatch command (runs every 30 minutes)
    - Queue-based job processing for scheduled reports
    - Missed schedule recovery and abandoned schedule handling

---

## Conclusion

This business logic documentation provides a comprehensive understanding of the Premiere Warehousing system's operations. The system follows a logical flow from trailer entry through scheduling and operations to invoice generation, payment processing, and analytics reporting.

The modular design ensures clear separation of concerns while maintaining data integrity and business rule compliance throughout all operations. The Reports module extends the system's capabilities by providing automated analytics and stakeholder communication, enabling data-driven decision-making and operational monitoring.

---
