/*
 * 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 generateMapsWorkflows(version) {
    return {
        'territory-planning-setup.md': workflow(version, 'Territory Planning Setup', `
## 1. Gather Requirements

Ask:
- **Territory model:** What geographic units define territories? (ZIP codes, states, counties, custom polygons)
- **Assignment criteria:** How are accounts assigned to territories? (proximity, revenue, account count, custom score)
- **Optimization goals:** What should territory planning optimize for? (balanced workload, minimized travel, revenue equity)
- **Rep capacity:** What are the constraints per rep? (max accounts, max drive time per day, max territory area)
- **Alignment frequency:** How often do territories get realigned? (quarterly, annually, on demand)

Check \`force-app/main/default/objects/\` for existing Maps territory-related customizations before configuring.

## 2. Define Geographic Territories

### Territory Boundaries
1. Navigate to Setup → Salesforce Maps → Territory Planning.
2. Choose the geographic unit for territory boundaries:
   - **ZIP/Postal Code** — most common for urban/suburban coverage.
   - **State/Province** — for broad regional territories.
   - **County/District** — for mid-level granularity.
   - **Custom Polygons** — for non-standard boundaries (imported GeoJSON or manually drawn).
3. Import boundary data if using custom polygons — ensure coordinate system is WGS84 (EPSG:4326).
4. Define territory naming conventions (e.g., \`REGION-CITY-NUMBER\`: \`WEST-SF-001\`).

### Territory Hierarchy
- Define levels: Region → District → Territory (or flat if single level).
- Assign managers at each hierarchy level for reporting and approval workflows.
- Map territories to the existing sales hierarchy if applicable.

## 3. Configure Account Assignment Rules

### Assignment Criteria
1. Define primary assignment logic:
   - **Proximity-based:** Assign accounts to the nearest territory center point.
   - **Boundary-based:** Assign accounts within the geographic polygon of a territory.
   - **Rule-based:** Use account attributes (industry, segment, revenue) combined with geography.
2. Configure tie-breaking rules when an account qualifies for multiple territories.
3. Set priority weights: e.g., 60% proximity + 25% workload balance + 15% revenue equity.

### Workload Balancing
1. Define workload metrics:
   - Account count per territory
   - Annual revenue per territory
   - Required visit frequency (weekly, biweekly, monthly)
   - Estimated drive time per territory
2. Set balance thresholds: maximum deviation from average (e.g., ±15%).
3. Configure alerts when territory workload exceeds capacity constraints.

## 4. Run Optimization Scenarios

1. Create a new scenario in Territory Planning (do NOT modify the active alignment directly).
2. Run the optimization engine with defined criteria and constraints.
3. Review the scenario output:
   - Territory map visualization
   - Workload distribution chart
   - Unassigned or orphaned accounts
   - Constraint violations
4. Compare multiple scenarios side by side before committing.
5. Get stakeholder approval on the selected scenario.

## 5. Deploy Territory Alignment

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

Verify in the target org:
- Territory boundaries display correctly on the Maps canvas
- Account assignments reflect the approved scenario
- Rep territory views show their assigned accounts
- Workload metrics match the approved scenario output
`),
        'route-optimization-setup.md': workflow(version, 'Route Optimization Setup', `
## 1. Gather Requirements

Ask:
- **Route types:** What kinds of routes are needed? (daily visits, recurring service, ad-hoc sales calls)
- **Constraints:** What are the hard constraints? (max drive time, appointment windows, mandatory breaks, vehicle type)
- **Optimization priority:** Minimize total drive time, minimize distance, or maximize visits per day?
- **Schedule integration:** Do routes need to respect existing calendar appointments or service windows?
- **Driver profiles:** Are there different driver types with different constraints? (full-time, part-time, regional)

Check existing route templates in \`force-app/main/default/objects/maps__Route__c\` before creating new ones.

## 2. Configure Routing Constraints

### Time-Based Constraints
1. Navigate to Setup → Salesforce Maps → Route Optimization.
2. Define working hours per driver profile:
   - Start time / End time (e.g., 8:00 AM – 5:00 PM)
   - Lunch break window (e.g., 12:00 PM – 1:00 PM, flexible ±30 min)
   - Maximum continuous drive time before mandatory break
3. Set maximum daily drive time (e.g., 4 hours actual driving).
4. Configure overtime rules (allow/disallow, max overtime minutes).

### Visit Constraints
1. Define default visit duration per account type:
   - New prospect: 60 minutes
   - Existing client check-in: 30 minutes
   - Service call: variable (pull from Work Order estimate)
2. Configure appointment windows (hard constraints — cannot be violated).
3. Set priority levels for stops (required vs. optional/best-effort).

### Vehicle Constraints
- Define vehicle profiles if applicable (sedan, van, truck).
- Set road restrictions per vehicle type (weight limits, height restrictions).
- Configure fuel/charge stop requirements for long routes.

## 3. Define Driver Profiles

1. Create driver profile templates:
   - **Full-Time Field Rep:** 8-hour day, 4-hour max drive, standard vehicle.
   - **Part-Time Rep:** 4-hour day, 2-hour max drive, limited territory.
   - **Regional Manager:** 10-hour day, flexible schedule, larger territory.
2. Assign profiles to users via custom metadata or Maps configuration.
3. Define skill-based routing if applicable (certified for specific account types).

## 4. Configure Multi-Stop Planning

### Route Generation
1. Select accounts/stops for the route:
   - From territory assignment (all accounts in territory)
   - From a list view or report (filtered subset)
   - From a manual selection on the Maps canvas
2. Set the optimization algorithm:
   - **Shortest Time:** Minimize total travel time across all stops.
   - **Shortest Distance:** Minimize total mileage (ignores traffic).
   - **Maximum Coverage:** Fit as many stops as possible within time constraints.
3. Configure start and end points:
   - Start from home / office / first account
   - End at home / office / last account / open (no return requirement)

### Schedule Integration
1. Pull existing calendar events from Salesforce Events/Activities.
2. Block time slots that conflict with meetings or other commitments.
3. Insert route stops around fixed appointments.
4. Sync optimized route back to the rep's calendar as Events.

## 5. Set Up Recurring Routes

1. Define route templates for recurring visit patterns:
   - Weekly routes (same day, same accounts)
   - Biweekly alternating routes
   - Monthly service routes
2. Configure auto-optimization triggers:
   - Re-optimize when new accounts are added to territory
   - Re-optimize when an account is removed or deactivated
   - Re-optimize on schedule change (rep PTO, holiday)
3. Set notification preferences for route changes.

## 6. Deploy Route Configuration

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

Verify in the target org:
- Routes generate with correct stop sequence
- Constraint violations surface as warnings (not silent failures)
- Calendar integration syncs stops as Events
- Driver profiles apply correct constraints per user
`),
    };
}
//# sourceMappingURL=maps.js.map