/*
 * Copyright 2026, Jaime Terrats.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { workflow } from '../workflow-generator.js';
export function generateEnergyWorkflows(version) {
    return {
        'meter-data-setup.md': workflow(version, 'Meter Data Setup', `
## 1. Gather Requirements

Ask:
- **Service territory:** What geographic areas or utility districts are served?
- **Service point types:** Electric, Gas, Water, or multi-commodity?
- **Meter hierarchy:** Single meters per service point, or sub-meters / check meters?
- **Reading collection:** Manual reads, AMI smart meter feeds, or hybrid?
- **Validation rules:** What estimation methods for missing reads? (Linear interpolation, weather-adjusted, historical average)
- **Interval data:** Is 15-minute / hourly interval data required, or just monthly register reads?

Check \`force-app/main/default/objects/\` for existing \`ServicePoint\`, \`UtilityMeter\`, and \`UtilityMeterReading\` customizations before adding new fields.

## 2. Configure Service Points

### Premise → Service Point → Meter Hierarchy
- **Premise** represents the physical location (address, parcel, building).
- **Service Point** represents the point of delivery (one premise may have multiple service points for different commodities).
- **UtilityMeter** represents the physical device installed at a service point.

### Service Point Setup
1. Navigate to Setup → Energy & Utilities → Service Points.
2. Define Service Point Record Types by commodity: Electric, Gas, Water.
3. Configure key fields:
   - \`ServicePointType\` — Delivery, Generation, Interconnection
   - \`Status\` — Active, Inactive, Pending Connection
   - \`Premise\` — lookup to the physical location
   - \`UtilityAccount\` — lookup to the customer account
4. Set up service territory assignments for dispatch and outage management.

## 3. Configure Meter Hierarchy

### Meter Registration
1. Create \`UtilityMeter\` records linked to Service Points.
2. Define meter attributes:
   - \`MeterType\` — AMI, AMR, Manual
   - \`Manufacturer\`, \`Model\`, \`SerialNumber\`
   - \`InstallDate\`, \`RemovalDate\`
   - \`Multiplier\` — CT/PT ratio for commercial meters
3. For sub-metering: set \`ParentMeter\` lookup to establish hierarchy.

### Meter Exchange / Rotation
- Use the meter lifecycle status: Installed, Removed, In Stock, Retired.
- On meter exchange: close the old meter reading period, open a new one with the replacement meter.
- Record the final read on the old meter and initial read on the new meter in the same transaction.

## 4. Configure Reading Collection

### Reading Sources
- **AMI Integration:** Configure Platform Events or API endpoints to receive interval data from the AMI headend system.
- **Manual Reads:** Create mobile-friendly flows for field workers to submit reads.
- **Estimated Reads:** Configure estimation rules for months with no actual read.

### Validation Rules
1. Define validation thresholds:
   - High/Low consumption limits (percentage of historical average)
   - Negative consumption detection (meter rollover vs. error)
   - Zero consumption for active service points
2. Configure validation actions:
   - Flag for review (soft fail)
   - Reject and request re-read (hard fail)
   - Auto-estimate using configured method

### Reading Storage
- \`UtilityMeterReading\` stores each reading event:
  - \`ReadingValue\`, \`ReadingDate\`, \`ReadingType\` (Actual, Estimated, Adjusted)
  - \`ConsumptionValue\` — calculated delta from previous read
  - \`ValidationStatus\` — Passed, Failed, Pending Review

## 5. Deploy Meter Data Configuration

\`\`\`bash
sf project deploy start \\
  --source-dir force-app/main/default/objects/ServicePoint \\
  --source-dir force-app/main/default/objects/UtilityMeter \\
  --source-dir force-app/main/default/objects/UtilityMeterReading \\
  --source-dir force-app/main/default/objects/Premise \\
  --target-org <alias>
\`\`\`

Verify in the target org:
- Service points display correct hierarchy under premises
- Meter readings validate against configured thresholds
- AMI integration events create readings with correct validation status
`),
        'rate-plan-setup.md': workflow(version, 'Rate Plan Setup', `
## 1. Gather Requirements

Ask:
- **Rate structure types:** Flat rate, tiered (inclining/declining block), time-of-use (TOU), demand charges, or combination?
- **Customer segments:** Residential, commercial, industrial, agricultural — which rate classes?
- **Seasonal rates:** Do rates vary by season (summer/winter)?
- **Net metering:** Are there customers with solar/DER who need net metering or feed-in tariff rates?
- **Demand charges:** Are demand charges based on peak kW, coincident peak, or ratcheted demand?
- **Billing frequency:** Monthly, bi-monthly, or quarterly billing cycles?
- **Regulatory context:** Which tariff schedule numbers apply? PUC/PSC docket references?

Check \`force-app/main/default/objects/\` for existing \`RatePlan\` and \`RatePlanCharge\` customizations.

## 2. Design Rate Structure

### Rate Plan Hierarchy
- **RatePlan** — the top-level tariff schedule (e.g., "Residential TOU - Schedule R-TOU")
- **RatePlanCharge** — individual charge components within a plan (energy charge, demand charge, fixed charge, taxes)

### Charge Types
| Charge Type | Description | Unit |
|------------|-------------|------|
| Fixed / Service Charge | Monthly customer charge regardless of usage | $/month |
| Energy Charge (Flat) | Single rate per kWh consumed | $/kWh |
| Energy Charge (Tiered) | Rate varies by consumption block | $/kWh per tier |
| Energy Charge (TOU) | Rate varies by time period (on-peak, off-peak, mid-peak) | $/kWh per period |
| Demand Charge | Based on peak kW demand in billing period | $/kW |
| Reactive Power Charge | Penalty for low power factor | $/kVAR |
| Net Metering Credit | Credit for excess generation exported to grid | $/kWh |

## 3. Configure Rate Plans

### Create Rate Plan Records
1. Navigate to the RatePlan object.
2. Create a RatePlan for each tariff schedule:
   - \`Name\` — human-readable tariff name
   - \`RateCode\` — regulatory schedule number (e.g., "R-TOU", "GS-2")
   - \`EffectiveDate\` / \`ExpirationDate\` — rate validity period
   - \`CustomerClass\` — Residential, Commercial, Industrial
   - \`SeasonalVariation\` — Yes/No
3. Assign Rate Plans to Service Points or Utility Accounts.

### Configure Tiered Rates
For inclining block structures:
1. Create RatePlanCharge records for each tier:
   - Tier 1: 0–500 kWh @ $0.08/kWh
   - Tier 2: 501–1000 kWh @ $0.12/kWh
   - Tier 3: 1001+ kWh @ $0.18/kWh
2. Set \`TierMinimum\`, \`TierMaximum\`, and \`UnitRate\` on each charge.
3. Configure tier reset period (monthly, annually for baseline allocation).

### Configure Time-of-Use (TOU) Rates
1. Define TOU periods:
   - On-Peak: weekdays 4 PM – 9 PM
   - Mid-Peak: weekdays 7 AM – 4 PM, 9 PM – 11 PM
   - Off-Peak: weekdays 11 PM – 7 AM, all weekends/holidays
2. Create RatePlanCharge records for each TOU period with:
   - \`TimePeriod\` — On-Peak, Mid-Peak, Off-Peak
   - \`SeasonType\` — Summer, Winter (if seasonal)
   - \`UnitRate\` — rate for that period
3. Link TOU schedule to a calendar configuration for holiday exclusions.

### Configure Demand Charges
1. Create a demand-type RatePlanCharge:
   - \`ChargeType\` = Demand
   - \`UnitRate\` — $/kW
   - \`MeasurementWindow\` — 15-minute, 30-minute, or 60-minute intervals
   - \`RatchetPercentage\` — if demand is ratcheted (e.g., 80% of highest peak in last 12 months)
2. Configure coincident vs. non-coincident peak measurement.

### Configure Net Metering
1. Create a net metering credit charge:
   - \`ChargeType\` = Credit
   - \`UnitRate\` — export credit rate (may differ from import rate)
   - \`CreditRollover\` — monthly rollover or annual true-up
2. Link to DER program enrollment on the customer account.
3. Configure generation meter reading source (bidirectional meter or separate production meter).

## 4. Billing Integration

### Rate Application Logic
- Billing engine reads the active RatePlan assigned to the Service Point / Utility Account.
- For each billing period:
  1. Pull validated meter readings for the period.
  2. Apply tiered/TOU rates to consumption intervals.
  3. Calculate demand charges from peak interval data.
  4. Apply net metering credits from generation readings.
  5. Sum all RatePlanCharge calculations into the bill total.

### CIS Integration
- If billing is handled by an external CIS (Customer Information System):
  - Export rate plan configurations via API or batch file.
  - Salesforce serves as the rate plan system of record; CIS consumes for bill calculation.
  - Sync billing results back to Salesforce for customer-facing display.

## 5. Deploy Rate Plan Configuration

\`\`\`bash
sf project deploy start \\
  --source-dir force-app/main/default/objects/RatePlan \\
  --source-dir force-app/main/default/objects/RatePlanCharge \\
  --target-org <alias>
\`\`\`

Verify in the target org:
- Rate plans display correct charge components
- Tiered calculations produce expected totals for sample consumption values
- TOU period assignments align with the configured calendar
- Net metering credits calculate correctly for bidirectional meter data
`),
    };
}
//# sourceMappingURL=energy.js.map