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

# Upsert Menu Rules

> Create or update menu rules that control menu behavior, item availability, pricing logic, and operational constraints to automate menu management and ensure consistent business policy application.

This endpoint enables comprehensive menu rule management through upsert operations, allowing businesses to create new rules or update existing ones with sophisticated automation logic for menu behavior and business policy enforcement.

<Info>
  Menu rule upserts provide powerful automation capabilities, enabling businesses to implement complex business logic that automatically adjusts menus based on time, inventory, weather, customer segments, and operational conditions.
</Info>

### Path Parameters

<ParamField path="store_id" type="string" required>
  The unique identifier of the store to create or update menu rules for
</ParamField>

### Request Body

<ParamField body="rule_id" type="string" optional>
  Unique identifier for the rule (if updating existing rule)
</ParamField>

<ParamField body="rule_name" type="string" required>
  Human-readable name for the rule for management purposes
</ParamField>

<ParamField body="rule_type" type="string" required>
  Type of rule: availability, pricing, display, or operational
</ParamField>

<ParamField body="is_active" type="boolean" optional default="true">
  Whether the rule should be active upon creation/update
</ParamField>

<ParamField body="priority" type="integer" required>
  Rule execution priority (higher numbers execute first)
</ParamField>

<ParamField body="conditions" type="object" required>
  Rule activation conditions and triggers
</ParamField>

<ParamField body="actions" type="object" required>
  Actions to execute when rule conditions are met
</ParamField>

<ParamField body="scope" type="object" optional>
  Items, categories, or menus the rule applies to
</ParamField>

<ParamField body="effective_date_range" type="object" optional>
  Start and end dates for rule effectiveness
</ParamField>

### Request Example

```json theme={null}
{
    "rule_name": "Happy Hour Beverage Pricing",
    "rule_type": "pricing",
    "is_active": true,
    "priority": 10,
    "conditions": {
        "time_range": {
            "start": "15:00",
            "end": "18:00"
        },
        "days_of_week": ["monday", "tuesday", "wednesday", "thursday", "friday"],
        "date_exceptions": ["2024-12-25", "2024-01-01"]
    },
    "actions": {
        "adjust_pricing": {
            "type": "percentage",
            "value": -25,
            "round_to": 0.05
        },
        "apply_promotional_tag": "happy_hour"
    },
    "scope": {
        "apply_to_categories": ["beverages", "appetizers"],
        "exclude_items": ["premium_wine", "specialty_cocktails"]
    },
    "effective_date_range": {
        "start_date": "2024-02-01",
        "end_date": "2024-03-31"
    }
}
```

### Response

<ResponseField name="rule_id" type="string">
  Unique identifier of the created or updated rule
</ResponseField>

<ResponseField name="message" type="string">
  Confirmation message indicating the operation result
</ResponseField>

<ResponseField name="success" type="boolean">
  Whether the upsert operation completed successfully
</ResponseField>

<ResponseField name="rule_details" type="object">
  Complete configuration of the created or updated rule
</ResponseField>

### Response Example

```json theme={null}
{
    "rule_id": "rule_456",
    "message": "Menu rule created successfully",
    "success": true,
    "rule_details": {
        "rule_id": "rule_456",
        "rule_name": "Happy Hour Beverage Pricing",
        "rule_type": "pricing",
        "is_active": true,
        "priority": 10,
        "created_at": "2024-01-15T10:30:00Z",
        "next_evaluation": "2024-01-15T15:00:00Z"
    }
}
```

<Accordion title="Rule Configuration Strategies">
  **Time-Based Automation**

  * Schedule automatic menu changes throughout the day
  * Implement seasonal availability and pricing
  * Handle special events and holiday modifications
  * Coordinate with business hours and operational schedules

  **Inventory-Driven Rules**

  * Automatically adjust availability based on stock levels
  * Implement dynamic pricing based on inventory costs
  * Handle supply chain disruptions automatically
  * Optimize inventory turnover through menu adjustments

  **Customer-Centric Rules**

  * Personalize menus based on customer segments
  * Implement loyalty program benefits automatically
  * Adjust offerings based on customer behavior patterns
  * Optimize for customer satisfaction and engagement

  **Operational Efficiency Rules**

  * Adjust menus based on staffing levels
  * Handle equipment maintenance and capacity constraints
  * Optimize for kitchen efficiency and preparation times
  * Coordinate with delivery and pickup operations
</Accordion>

<Note>
  **Rule Conflicts**: When multiple rules affect the same items, rules with higher priority values take precedence. Design your rule hierarchy carefully to avoid unintended conflicts.
</Note>

<Tip>
  **Testing Strategy**: Use effective date ranges and the is\_active flag to test new rules safely before full deployment. Start with specific date ranges and limited scope for validation.
</Tip>

### Rule Types and Examples

<Accordion title="Comprehensive Rule Type Examples">
  **Availability Rules**

  ```json theme={null}
  {
    "rule_type": "availability",
    "conditions": {
      "time_range": {"start": "22:00", "end": "06:00"},
      "inventory_threshold": {"operator": "less_than", "value": 10}
    },
    "actions": {
      "set_availability": false,
      "send_notification": {
        "type": "staff_alert",
        "message": "Low inventory items disabled overnight"
      }
    },
    "scope": {
      "apply_to_categories": ["perishable_items"]
    }
  }
  ```

  **Dynamic Pricing Rules**

  ```json theme={null}
  {
    "rule_type": "pricing",
    "conditions": {
      "weather_condition": {"type": "temperature", "operator": "greater_than", "value": 85},
      "time_range": {"start": "11:00", "end": "16:00"}
    },
    "actions": {
      "adjust_pricing": {"type": "percentage", "value": -15},
      "apply_promotional_tag": "beat_the_heat"
    },
    "scope": {
      "apply_to_categories": ["cold_beverages", "ice_cream"]
    }
  }
  ```

  **Display Optimization Rules**

  ```json theme={null}
  {
    "rule_type": "display",
    "conditions": {
      "customer_segment": "health_conscious",
      "days_of_week": ["monday", "tuesday", "wednesday"]
    },
    "actions": {
      "update_display_order": {"boost_factor": 5},
      "apply_promotional_tag": "healthy_choice",
      "feature_in_section": "recommended"
    },
    "scope": {
      "apply_to_items": ["salads", "grilled_proteins", "fresh_juices"]
    }
  }
  ```

  **Operational Rules**

  ```json theme={null}
  {
    "rule_type": "operational",
    "conditions": {
      "staff_count": {"operator": "less_than", "value": 4},
      "order_volume": {"operator": "greater_than", "value": 50}
    },
    "actions": {
      "set_availability": false,
      "send_notification": {
        "type": "manager_alert",
        "message": "Complex items disabled due to high volume and low staffing"
      }
    },
    "scope": {
      "apply_to_items": ["complex_preparations", "made_to_order_items"]
    }
  }
  ```
</Accordion>

### Condition Configuration

<Accordion title="Rule Condition Options">
  **Time-Based Conditions**

  * `time_range`: Specific hours of the day
  * `days_of_week`: Specific days when rule applies
  * `date_range`: Specific calendar periods
  * `date_exceptions`: Specific dates to exclude
  * `recurring_schedule`: Complex recurring patterns

  **Inventory Conditions**

  * `inventory_threshold`: Stock level triggers
  * `cost_variance`: Pricing based on cost changes
  * `supplier_availability`: Supply chain status
  * `expiration_proximity`: Perishable item management

  **Environmental Conditions**

  * `weather_condition`: Weather-based triggers
  * `temperature_range`: Temperature-specific rules
  * `seasonal_conditions`: Season-based automation
  * `external_events`: Special event considerations

  **Operational Conditions**

  * `staff_count`: Staffing level requirements
  * `equipment_status`: Equipment availability
  * `order_volume`: Current demand levels
  * `delivery_capacity`: Delivery operation status

  **Customer Conditions**

  * `customer_segment`: Specific customer types
  * `loyalty_tier`: Customer loyalty levels
  * `order_history`: Customer behavior patterns
  * `demographic_data`: Customer demographic information
</Accordion>

### Action Configuration

<Accordion title="Rule Action Options">
  **Availability Actions**

  * `set_availability`: Enable or disable items/categories
  * `adjust_availability_window`: Modify time-based availability
  * `inventory_reserve`: Reserve inventory for specific purposes
  * `capacity_limit`: Limit order quantities

  **Pricing Actions**

  * `adjust_pricing`: Percentage or fixed amount changes
  * `apply_discount`: Specific discount configurations
  * `surge_pricing`: Demand-based price increases
  * `bundling_offers`: Create promotional bundles

  **Display Actions**

  * `update_display_order`: Change item positioning
  * `feature_items`: Highlight specific items
  * `category_promotion`: Promote entire categories
  * `personalized_recommendations`: Customer-specific suggestions

  **Communication Actions**

  * `send_notification`: Alert staff or customers
  * `update_descriptions`: Modify item descriptions
  * `apply_promotional_tag`: Add marketing tags
  * `social_media_post`: Automated social media updates

  **Integration Actions**

  * `update_external_systems`: Sync with third-party platforms
  * `trigger_workflow`: Initiate business processes
  * `log_analytics_event`: Track business intelligence data
  * `inventory_adjustment`: Automatic inventory management
</Accordion>

### Validation Rules

<Accordion title="Rule Validation Requirements">
  **Structure Validation**

  * Rule name must be unique within the store
  * Rule type must be from approved list
  * Priority must be a positive integer
  * Conditions and actions must have valid structure

  **Logic Validation**

  * Condition logic must be evaluable
  * Action specifications must be executable
  * Scope definitions must reference valid items/categories
  * Date ranges must be logically consistent

  **Business Rule Validation**

  * Pricing adjustments must be within allowed ranges
  * Availability changes must comply with business policies
  * Promotional actions must align with marketing guidelines
  * Operational rules must respect safety and compliance requirements

  **System Validation**

  * Referenced items and categories must exist
  * Integration endpoints must be accessible
  * Notification channels must be configured
  * External data sources must be available
</Accordion>

### Error Handling

<Accordion title="Common Error Scenarios">
  **Invalid Rule Configuration**

  ```json theme={null}
  {
    "error": "Invalid rule configuration",
    "message": "Rule conditions contain invalid logic",
    "details": {
      "field": "conditions.inventory_threshold",
      "issue": "Invalid operator 'not_equal_to'"
    }
  }
  ```

  **Business Rule Violation**

  ```json theme={null}
  {
    "error": "Business rule violation",
    "message": "Pricing adjustment exceeds maximum allowed variance",
    "details": {
      "requested_adjustment": -50,
      "maximum_allowed": -30
    }
  }
  ```

  **Conflicting Rule Priority**

  ```json theme={null}
  {
    "error": "Rule conflict",
    "message": "Rule with same priority already exists for overlapping scope",
    "details": {
      "conflicting_rule_id": "rule_123",
      "suggested_priority": 11
    }
  }
  ```

  **Invalid Scope Reference**

  ```json theme={null}
  {
    "error": "Invalid scope",
    "message": "Referenced items or categories do not exist",
    "details": {
      "invalid_items": ["non_existent_item"],
      "invalid_categories": ["invalid_category"]
    }
  }
  ```
</Accordion>

### Best Practices

<Accordion title="Menu Rule Development Best Practices">
  **Rule Design Principles**

  * Start with simple rules and add complexity gradually
  * Use descriptive names that clearly indicate rule purpose
  * Document rule rationale and expected business impact
  * Design rules with clear start and end conditions

  **Priority Management**

  * Leave gaps in priority numbers for future rule insertion
  * Group related rules with similar priority ranges
  * Use higher priorities for safety and compliance rules
  * Document priority hierarchy and conflict resolution strategy

  **Testing and Validation**

  * Test rules in staging environment before production deployment
  * Use effective date ranges for safe rule rollout
  * Monitor rule impact and adjust as needed
  * Implement rollback procedures for problematic rules

  **Performance Optimization**

  * Design efficient condition logic to minimize evaluation time
  * Use specific scopes rather than broad category applications
  * Monitor rule execution performance and optimize as needed
  * Cache rule results appropriately for consistent application
</Accordion>

### Rule Management Strategies

<Accordion title="Strategic Rule Implementation">
  **Phased Implementation**

  * Start with simple availability and pricing rules
  * Gradually add operational and display optimization rules
  * Implement customer segmentation rules after data collection
  * Build complex multi-condition rules based on experience

  **Business Alignment**

  * Align rules with overall business strategy and goals
  * Coordinate rule development with marketing and operations teams
  * Ensure rules support customer experience objectives
  * Integrate rules with loyalty and promotional programs

  **Continuous Improvement**

  * Regularly review rule effectiveness and business impact
  * Optimize rules based on performance data and customer feedback
  * Retire outdated rules that no longer serve business needs
  * Evolve rule complexity as business needs mature

  **Compliance and Governance**

  * Ensure rules comply with regulatory requirements
  * Implement approval processes for high-impact rules
  * Maintain audit trails for rule changes and impacts
  * Document rule governance and change management procedures
</Accordion>

### Integration Considerations

<Accordion title="System Integration for Menu Rules">
  **Real-time Rule Engine**

  * Implement efficient rule evaluation for real-time menu updates
  * Ensure consistent rule application across all customer touchpoints
  * Coordinate rule execution with system performance requirements
  * Handle rule conflicts and exceptions gracefully

  **Data Integration**

  * Integrate with inventory management for real-time stock data
  * Connect with weather services for environmental conditions
  * Sync with staff scheduling systems for operational rules
  * Coordinate with customer data platforms for segmentation

  **External System Coordination**

  * Update point-of-sale systems with rule-driven changes
  * Sync with mobile apps and online ordering platforms
  * Coordinate with third-party delivery services
  * Integrate with marketing automation platforms

  **Analytics and Monitoring**

  * Track rule activation frequency and business impact
  * Monitor rule performance and execution efficiency
  * Generate insights for rule optimization and business intelligence
  * Support compliance reporting and audit requirements
</Accordion>

### Rule Lifecycle Management

<Accordion title="Managing Rule Evolution">
  **Rule Development Lifecycle**

  * **Planning**: Define business objectives and rule requirements
  * **Design**: Create rule logic and validate against requirements
  * **Testing**: Validate rule behavior in controlled environments
  * **Deployment**: Implement rules with appropriate safeguards
  * **Monitoring**: Track rule performance and business impact
  * **Optimization**: Refine rules based on data and feedback
  * **Retirement**: Remove obsolete rules and archive historical data

  **Version Control and Change Management**

  * Maintain version history for all rule changes
  * Implement approval workflows for rule modifications
  * Document change rationale and expected impact
  * Coordinate rule changes with business operations

  **Performance and Optimization**

  * Monitor rule execution performance and system impact
  * Optimize rule logic for efficiency and accuracy
  * Balance rule complexity with system performance
  * Continuously improve rule effectiveness and business value
</Accordion>
