# Return to Generating Feature (REVERTED)

This feature was implemented and then reverted due to issues. This document captures all the code changes so they can be re-applied if needed.

## Overview

The "Return to Generating" action allowed users to revert a PR from `draft`, `pending_supplier`, or `pending_approval` status back to `generating` status, enabling them to re-edit the PR products on the generate page. Existing supplier data was preserved.

## Files Affected

### 1. PrIndexController.php

**Location:** `Modules/PurchaseRequisition/Http/Controllers/PrIndexController.php`

#### A. Action dropdown item (inside `getRequests()` -> `addColumn('action')`)

Add this block after the "Return to Supplier" divider/action block (around line 131):

```php
// Return to Generating - for draft, pending_supplier, pending_approval statuses
if ((auth()->user()->can('purchase_requisition.edit') || auth()->user()->can('purchase_requisition.create')) && in_array($row->status, ['draft', 'pending_supplier', 'pending_approval'])) {
    if (!in_array($row->status, ['pending_approval'])) {
        $html .= '<li class="divider"></li>';
    }
    $html .= '<li><a href="#" class="return-to-generating" data-id="' . $row->id . '"><i class="fa fa-pencil"></i> ' . __('purchaseRequisition::lang.return_to_generating') . '</a></li>';
}
```

**Note:** The divider logic: if `pending_approval`, the divider is already added by the "Return to Supplier" block, so we skip adding another. For other statuses (`draft`, `pending_supplier`), we add a divider before this item.

#### B. New method: `returnToGenerating()`

Add this method to `PrIndexController`:

```php
/**
 * Return PR to generating status.
 *
 * @param Request $request
 * @return \Illuminate\Http\JsonResponse
 */
public function returnToGenerating(Request $request)
{
    if (!auth()->user()->can('purchase_requisition.edit') && !auth()->user()->can('purchase_requisition.create')) {
        abort(403, 'Unauthorized action.');
    }

    $request->validate([
        'pr_id' => 'required|exists:pr_requests,id',
    ]);

    try {
        DB::beginTransaction();

        $prRequest = PrRequest::findOrFail($request->pr_id);
        $prRequest->update(['status' => 'generating']);

        DB::commit();

        return response()->json([
            'success' => true,
            'msg' => __('purchaseRequisition::lang.returned_to_generating_successfully')
        ]);
    } catch (\Exception $e) {
        DB::rollBack();
        \Log::emergency('File:' . $e->getFile() . ' Line:' . $e->getLine() . ' Message:' . $e->getMessage());

        return response()->json([
            'success' => false,
            'msg' => __('messages.something_went_wrong')
        ]);
    }
}
```

**Behavior:**
- Permission: `purchase_requisition.edit` OR `purchase_requisition.create`
- Simply changes PR status to `generating`
- Does NOT delete supplier responses, supplier products, or any other data
- After returning to generating, the user can click "Edit" on the list page to go back to the generate page and modify products

### 2. Index View (index/index.blade.php)

**Location:** `Modules/PurchaseRequisition/Resources/views/index/index.blade.php`

#### JavaScript handler

Add this inside `$(document).ready(function() { ... })`:

```javascript
// Return to Generating
$(document).on('click', '.return-to-generating', function(e) {
    e.preventDefault();
    var prId = $(this).data('id');

    swal({
        title: '@lang("messages.sure")',
        text: '@lang("purchaseRequisition::lang.return_to_generating_confirm")',
        icon: "warning",
        buttons: true,
        dangerMode: true,
    }).then((willReturn) => {
        if (willReturn) {
            $.ajax({
                url: '{{ action([\Modules\PurchaseRequisition\Http\Controllers\PrIndexController::class, "returnToGenerating"]) }}',
                type: 'POST',
                data: {
                    _token: '{{ csrf_token() }}',
                    pr_id: prId
                },
                success: function(result) {
                    if (result.success) {
                        toastr.success(result.msg);
                        pr_table.ajax.reload();
                    } else {
                        toastr.error(result.msg);
                    }
                }
            });
        }
    });
});
```

### 3. Routes (web.php)

**Location:** `Modules/PurchaseRequisition/Routes/web.php`

Add inside the admin routes group:

```php
Route::post('/return-to-generating', [PrIndexController::class, 'returnToGenerating'])->name('pr.returnToGenerating');
```

### 4. Translation Keys (lang/en/lang.php)

**Location:** `Modules/PurchaseRequisition/Resources/lang/en/lang.php`

```php
'return_to_generating' => 'Return to Generating',
'return_to_generating_confirm' => 'Are you sure you want to return this request to generating? Existing supplier data will be kept.',
'returned_to_generating_successfully' => 'Returned to generating successfully',
```

## Known Issues

The feature was reverted due to problems that need investigation. Potential areas to investigate:
- Status transitions may conflict with existing supplier response data
- Edit mode on the generate page may need additional handling when supplier responses already exist
- The "generating" status enum value and the edit/update routes for generate page remain in place (these are part of the Save/Submit feature and are NOT reverted)

## Related Features (NOT reverted)

The following features remain active and depend on the `generating` status:
- **Save vs Submit on Generate page**: Save -> status `generating`, Submit -> status `draft`
- **Edit action on list page**: Available for `generating` status PRs, links to generate/{id}/edit
- **Generate page edit mode**: PrGenerateController `edit()` and `update()` methods
