# `_cloudxm_nfe_auto_status` — Auto-Issue State Machine Field

## Overview

`_cloudxm_nfe_auto_status` is a WooCommerce order meta key that implements a **per-order auto-issuance state machine** for NFe (Nota Fiscal de Serviços Eletrônica). It was introduced in CLO-11 to allow individual orders to be flagged for automatic processing independently of the global auto-issue workflow (which runs on order status transitions).

## State Machine

| Constant | Value | Meaning |
|---|---|---|
| `AUTO_PENDING` | `pending` | Default state — order is not flagged for auto-processing |
| `AUTO_READY_NOW` | `ready_now` | Order is flagged and will be auto-processed on the next opportunity |
| `AUTO_SCHEDULE` | `schedule` | NFe has been scheduled on the server, waiting for emission |
| `AUTO_ISSUED` | `issued` | NFe has been successfully issued for this order |
| `AUTO_ERROR` | `error` | Auto-processing failed |

Defined in `src/Config/Configuration.php:308-323`.

## How It Works

### 1. Setting the Flag (UI)

In the WooCommerce order admin meta box, a **"Marcar Pronto para Emitir"** (Mark Ready to Issue) button is shown when the current auto-status is not `issued` or `schedule`. Clicking it triggers an AJAX request to `wp_ajax_cloudxm_nfe_set_ready_now` (`OrderMetaBoxController::handleSetReadyNow()`), which sets `_cloudxm_nfe_auto_status = 'ready_now'` on the order.

### 2. Processing (Hook)

`CoreServiceProvider::handleOrderMetaUpdated()` hooks into `updated_post_meta`. When `_cloudxm_nfe_auto_status` is set to `ready_now`, it delegates to `NFeAutomationService::processOrderFlags()`.

### 3. State Machine Logic

`NFeAutomationService::processOrderFlags()` (lines 100-141) follows this decision tree:

```
ready_now + existing scheduled emission in DB
  → cancel schedule + issue immediately (override)
  → status → issued | error

ready_now + schedule date field (_nfe_cloudxm_scheduled_at) is set
  → scheduleInvoice()
  → status → schedule | error

ready_now + no schedule date
  → autoIssueNFe()
  → status → issued | error
```

The status is updated via `setAutoStatus()` which persists the new value back to order meta.

## UI Representation

The meta box displays a color-coded badge:

- `pending` — Gray
- `ready_now` — Orange
- `schedule` — Blue
- `issued` — Green (with checkmark)
- `error` — Red

See `templates/admin/meta-boxes/order-nfe.php:358-372`.

## Relevant Source Files

| File | Role |
|---|---|
| `src/Config/Configuration.php` | Constants (`META_AUTO_STATUS`, `AUTO_PENDING`, etc.) |
| `src/Admin/Controllers/OrderMetaBoxController.php` | AJAX handler `handleSetReadyNow()` |
| `src/Providers/CoreServiceProvider.php` | Hook listener `handleOrderMetaUpdated()` |
| `src/Services/NFeAutomationService.php` | State machine logic in `processOrderFlags()` |
| `src/Services/OrderInvoiceLifecycleService.php` | `setAutoStatus()` helper and `buildMetaBoxData()` |
| `templates/admin/meta-boxes/order-nfe.php` | UI template with status badge and button |
