> ## Documentation Index
> Fetch the complete documentation index at: https://docs.encoreos.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Preventive Maintenance Administrator Guide

> This guide covers administrative setup and configuration of Preventive Maintenance (PM) in the Facilities Management module.

This guide covers administrative setup and configuration of Preventive Maintenance (PM) in the Facilities Management module.

***

## Overview

As an FM administrator, you are responsible for:

* Creating and managing PM templates
* Setting up PM schedules for sites and assets
* Configuring automation settings
* Monitoring compliance and performance
* Troubleshooting PM issues

***

## Initial Setup

### Configure FM Module Settings

1. Navigate to **FM → Settings**
2. Select the **Maintenance** tab
3. Configure PM-specific settings:

| Setting                          | Description                                  | Recommended Value |
| -------------------------------- | -------------------------------------------- | ----------------- |
| **PM Schedule Lookahead (Days)** | Days before due date to generate work orders | 7-14 days         |
| **Auto-Generate PM Work Orders** | Automatically create work orders when due    | Enabled           |

4. Click **Save Settings**

### Verify Cron Job Setup

PM automation requires scheduled jobs to run:

| Job                       | Schedule             | Purpose                              |
| ------------------------- | -------------------- | ------------------------------------ |
| `generate-pm-work-orders` | Daily at 6:00 AM UTC | Creates work orders for upcoming PMs |
| `check-overdue-pms`       | Daily at 7:00 AM UTC | Identifies and alerts on overdue PMs |

Contact your system administrator to verify these are configured.

***

## Creating PM Templates

PM templates define the maintenance tasks that will be scheduled.

### Step-by-Step Template Creation

1. Navigate to **FM → PM Templates**
2. Click **New Template**
3. Fill in template details:

**Basic Information**

* **Name**: Descriptive name (e.g., "HVAC Filter Replacement - Monthly")
* **Description**: Detailed explanation of the maintenance
* **Asset Type**: Select from picklist (HVAC, plumbing, electrical, etc.)
* **Frequency**: How often (daily, weekly, monthly, quarterly, semi-annual, annual)
* **Estimated Duration**: Expected completion time in minutes

**Assignment**

* **Default Assignee**: Technician to assign by default (optional)
* **Default Vendor**: External vendor if outsourced (optional)

**Compliance**

* **Compliance Required**: Toggle if regulatory requirement
* **Compliance Category**: Type of compliance (safety, regulatory, insurance)

4. Click **Save** to create the template

### Adding Checklist Items

After creating a template, add step-by-step tasks:

1. Open the template detail page
2. Navigate to **Checklist Items** tab
3. Click **Add Item**
4. For each item, specify:
   * **Description**: What to check or do
   * **Pass Criteria**: How to determine pass/fail (optional)
   * **Required**: Whether completion is mandatory
   * **Display Order**: Sequence in the checklist
5. Repeat for all checklist items

**Example Checklist for HVAC Filter Replacement:**

1. Turn off HVAC system
2. Remove access panel
3. Remove old filter and inspect
4. Install new filter with correct orientation
5. Replace access panel
6. Turn on HVAC system and verify operation

### Adding Required Materials

Specify materials needed from inventory:

1. Open the template detail page
2. Navigate to **Materials** tab
3. Click **Add Material**
4. Select the inventory item
5. Enter the quantity needed
6. Add notes if applicable
7. Repeat for all materials

***

## Managing PM Schedules

PM schedules link templates to specific sites for recurring maintenance.

### Creating a Schedule

1. Navigate to **FM → PM Schedules**
2. Click **New Schedule**
3. Configure the schedule:

| Field          | Description                        |
| -------------- | ---------------------------------- |
| **Template**   | Select the PM template to use      |
| **Site**       | Select the site for maintenance    |
| **Start Date** | When the schedule begins           |
| **Notes**      | Additional schedule-specific notes |

4. Click **Save**

The **Next Due Date** is automatically calculated based on the template frequency.

### Pausing and Activating Schedules

**To Pause a Schedule:**

1. Open the schedule detail page
2. Click **Pause Schedule**
3. Confirm the action

Paused schedules will not generate work orders.

**To Reactivate:**

1. Open the paused schedule
2. Click **Activate Schedule**
3. The next due date will be recalculated

### Understanding Due Date Calculation

Due dates are calculated based on frequency:

| Frequency   | Calculation            |
| ----------- | ---------------------- |
| Daily       | Add 1 day              |
| Weekly      | Add 7 days             |
| Monthly     | Add 1 month (same day) |
| Quarterly   | Add 3 months           |
| Semi-Annual | Add 6 months           |
| Annual      | Add 1 year             |

**Edge Cases:**

* January 31 + 1 month = February 28/29
* Leap years are handled correctly

***

## Work Order Integration

### Automatic Work Order Generation

When **Auto-Generate PM Work Orders** is enabled:

1. Daily at 6:00 AM UTC, the system checks all active schedules
2. Schedules with `next_due_date` within the lookahead window are processed
3. Work orders are created with:
   * **Type**: `preventive_maintenance`
   * **Priority**: `high` for compliance PMs, `medium` otherwise
   * **Due Date**: The PM schedule's due date
   * **Linked Schedule**: Reference to the PM schedule
   * **Checklist Items**: Copied from template
   * **Materials**: Suggested from template

### Manual Work Order Generation

To manually trigger work order creation:

1. Open the PM schedule
2. Click **Generate Work Order**
3. The work order is created immediately

### Duplicate Prevention

The system prevents duplicate work orders:

* Only one work order per schedule per due date
* Existing open work orders block new generation
* Completed work orders update the schedule before next generation

***

## Compliance Tracking

### Compliance Dashboard

Monitor PM compliance from the FM Dashboard:

| Metric               | Calculation                            |
| -------------------- | -------------------------------------- |
| **Compliance Rate**  | (Completed on time / Total due) × 100% |
| **Overdue Count**    | Active schedules past due date         |
| **Critical Overdue** | Overdue compliance-required PMs        |

### Overdue Alerts

The `check-overdue-pms` job runs daily to:

1. Identify schedules past their due date
2. Calculate days overdue
3. Categorize severity:
   * **Warning**: 1-3 days overdue
   * **Critical**: 4-7 days overdue
   * **Severe**: 7+ days overdue
4. Publish `pm_overdue` events for notification

### Compliance Reporting

For compliance audits, generate reports showing:

* PM completion history by schedule
* On-time completion rates
* Failure documentation
* Material usage

***

## Cron Job Setup

PM automation requires two scheduled jobs.

### Work Order Generation Job

**Schedule**: Daily at 6:00 AM UTC

```sql theme={null}
SELECT cron.schedule(
  'generate-pm-work-orders-daily',
  '0 6 * * *',
  $$
  SELECT net.http_post(
    url := 'https://<project-ref>.supabase.co/functions/v1/generate-pm-work-orders',
    headers := '{"Authorization": "Bearer <anon-key>", "Content-Type": "application/json"}'::jsonb,
    body := '{}'::jsonb
  );
  $$
);
```

### Overdue Check Job

**Schedule**: Daily at 7:00 AM UTC

```sql theme={null}
SELECT cron.schedule(
  'check-overdue-pms-daily',
  '0 7 * * *',
  $$
  SELECT net.http_post(
    url := 'https://<project-ref>.supabase.co/functions/v1/check-overdue-pms',
    headers := '{"Authorization": "Bearer <anon-key>", "Content-Type": "application/json"}'::jsonb,
    body := '{}'::jsonb
  );
  $$
);
```

### Verifying Cron Jobs

Check if jobs are scheduled:

```sql theme={null}
SELECT * FROM cron.job;
```

Check job execution history:

```sql theme={null}
SELECT * FROM cron.job_run_details 
WHERE jobname LIKE '%pm%' 
ORDER BY start_time DESC 
LIMIT 10;
```

***

## Troubleshooting

### Work Orders Not Generating

**Symptoms**: PM schedules are due but no work orders created

**Checklist**:

1. Verify **Auto-Generate PM Work Orders** is enabled in FM Settings
2. Check if schedule is **Active** (not Paused)
3. Verify schedule's `next_due_date` is within lookahead window
4. Check for existing open work order for this schedule
5. Verify cron job is scheduled and running

**Resolution**:

* Manually generate work order from schedule page
* Check edge function logs for errors
* Verify RLS policies allow work order creation

### Due Dates Not Calculating Correctly

**Symptoms**: Next due date is wrong after completion

**Checklist**:

1. Verify template frequency is set correctly
2. Check that work order is linked to PM schedule
3. Ensure work order status is "completed"

**Resolution**:

* Manually update schedule's next\_due\_date
* Verify the `fm_update_pm_schedule_on_completion` trigger is enabled

### Completion Not Updating Schedule

**Symptoms**: Work order completed but schedule not updated

**Checklist**:

1. Verify work order has `pm_schedule_id` set
2. Check database trigger is active
3. Look for errors in database logs

**Resolution**:

* Manually update schedule's last\_completed\_date and next\_due\_date
* Contact administrator to check trigger function

***

## Best Practices

### Template Design

1. **Clear Naming**: Use descriptive names with asset type and frequency
   * Good: "HVAC Filter Change - Monthly"
   * Bad: "Monthly Maintenance"

2. **Detailed Checklists**: Include specific, actionable steps
   * Good: "Inspect belt tension, tighten if deflection > 1/2 inch"
   * Bad: "Check belt"

3. **Pass Criteria**: Define clear pass/fail conditions for compliance PMs

4. **Material Accuracy**: Keep material lists current with correct quantities

### Frequency Selection

| Maintenance Type       | Recommended Frequency    |
| ---------------------- | ------------------------ |
| Filter changes         | Monthly                  |
| Safety inspections     | Monthly or Quarterly     |
| Full equipment service | Quarterly or Semi-Annual |
| Annual certifications  | Annual                   |

### Compliance Priority

* Mark all regulatory, safety, and insurance-required PMs as **Compliance Required**
* These get **High** priority work orders
* Monitor compliance PMs separately from routine maintenance

### Schedule Organization

* Create separate schedules per site, even for same template
* Use consistent start dates for easier planning
* Review and clean up unused schedules quarterly

***

## Related Guides

* [PM User Guide](./pm-user-guide.md) - End user documentation
* [Inventory Admin Guide](./inventory-admin-guide.md) - Managing PM materials
* [Vendor Admin Guide](./vendor-admin-guide.md) - Vendor PM assignments
