Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 102
0.00% covered (danger)
0.00%
0 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
CofraiBulkSyncController
0.00% covered (danger)
0.00%
0 / 102
0.00% covered (danger)
0.00%
0 / 4
132
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 bulkSyncRegions
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 bulkSync
0.00% covered (danger)
0.00%
0 / 75
0.00% covered (danger)
0.00%
0 / 1
56
 bulkSyncStatus
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2
3namespace App\Http\Controllers;
4
5use App\Models\TblCofraiBulkSyncRuns;
6use App\Services\CofraiBulkSyncService;
7use Carbon\Carbon;
8use Illuminate\Http\JsonResponse;
9use Illuminate\Http\Request;
10use Illuminate\Support\Facades\Log;
11use Symfony\Component\Process\PhpExecutableFinder;
12
13/**
14 * Cofrai mirror of the bulk-sync endpoints added to PresupuestosController
15 * by FIRE-1170. Three endpoints feed the admin "Sincronización masiva
16 * (Cofrai)" page:
17 *
18 *  - GET /api/cofrai/bulk-sync/regions          → list regions with cofrai_active
19 *  - POST /api/cofrai/bulk-sync                 → fire-and-forget run
20 *  - GET /api/cofrai/bulk-sync/{runId}          → poll endpoint
21 *
22 * Lives as a dedicated controller (rather than methods bolted onto
23 * CofraiBudgetsController) so the bulk-sync surface stays isolated from
24 * the daily-sync controller — the sibling agent owning the FIRE-1201
25 * `syncById` source-collision fix can land their changes without
26 * conflicting with these methods.
27 */
28class CofraiBulkSyncController extends Controller
29{
30    public function __construct(
31        protected CofraiBulkSyncService $cofraiBulkSyncService,
32    ) {}
33
34    /**
35     * GET /api/cofrai/bulk-sync/regions
36     * Returns the regions a Cofrai bulk-sync can target. Admin-only —
37     * gated at the route level by `require.admin`. The UI uses this to
38     * populate the "Regiones" multi-select on init; the "Todas las
39     * regiones" sticky option is purely client-side and not returned here.
40     */
41    public function bulkSyncRegions(): JsonResponse
42    {
43        return response()->json([
44            'data' => $this->cofraiBulkSyncService->listBulkSyncRegions(),
45        ]);
46    }
47
48    /**
49     * POST /api/cofrai/bulk-sync
50     * Kick off a Cofrai bulk re-sync run across regions × date range ×
51     * selected fields, optionally suppressing the per-toggle approval-
52     * notification side effects. Always async — returns a `run_id` for
53     * the UI to poll via `bulkSyncStatus`.
54     *
55     * Validation cap: 90-day max range — wider than that almost always
56     * means someone picked the wrong "desde" by mistake. The Cofrai API
57     * can handle it but the wall-time would be hours.
58     */
59    public function bulkSync(Request $request): JsonResponse
60    {
61        $data = $request->validate([
62            'regions' => 'required|array|min:1',
63            'regions.*' => 'string|max:50',
64            'date_from' => 'required|date_format:Y-m-d',
65            'date_to' => 'required|date_format:Y-m-d|after_or_equal:date_from',
66            'fields' => 'required|array|min:1',
67            'fields.*' => 'string|in:'.implode(',', array_keys(CofraiBulkSyncService::BULK_SYNC_FIELD_MAP)),
68            'send_approval_ops' => 'sometimes|boolean',
69            'send_approval_fin' => 'sometimes|boolean',
70        ]);
71
72        $from = Carbon::parse($data['date_from']);
73        $to = Carbon::parse($data['date_to']);
74        if ($from->diffInDays($to) > 90) {
75            return response()->json([
76                'message' => 'KO',
77                'error' => 'El rango máximo es de 90 días. Reduce el periodo o ejecuta el bulk-sync en varias tandas.',
78            ], 422);
79        }
80
81        $user = $request->user();
82        $triggeredBy = $user?->name ?? 'System';
83        $triggeredById = $user?->id;
84
85        $suppressOps = ! ($data['send_approval_ops'] ?? true);
86        $suppressFin = ! ($data['send_approval_fin'] ?? true);
87        //   ^^^ payload semantics: the UI sends `send_approval_*` (toggle ON
88        //       means notify; default ON). We store the *suppression* (opposite)
89        //       on the run row so the worker can read it directly. The
90        //       negation here is the only place the polarity flips.
91
92        $run = TblCofraiBulkSyncRuns::create([
93            'triggered_by' => $triggeredBy,
94            'triggered_by_id' => $triggeredById,
95            'regions' => array_values($data['regions']),
96            'date_from' => $data['date_from'],
97            'date_to' => $data['date_to'],
98            'fields' => array_values($data['fields']),
99            'suppress_approval_ops' => $suppressOps,
100            'suppress_approval_fin' => $suppressFin,
101            'started_at' => now(),
102        ]);
103
104        // Fire-and-forget pattern (mirrors CofraiBudgetsController::syncByDate
105        // and the FIRE-1170 G3W bulkSync). Both QUEUE_CONNECTION=sync and
106        // `dispatchAfterResponse` keep the worker hostage on Apache mod_php
107        // — the response only flushes when the PHP script ends. Forking a
108        // true background process via exec() lets the POST return in
109        // milliseconds so the frontend can start polling.
110        //
111        // PHP_BINARY is empty under Apache mod_php (it's a CLI-only
112        // constant), so PhpExecutableFinder is the reliable resolution
113        // path. Fallbacks cover both Debian-style (/usr/bin/php) and
114        // source-built (/usr/local/bin/php) Docker images.
115        $phpBinary = (new PhpExecutableFinder)->find(false)
116            ?: (is_executable('/usr/local/bin/php') ? '/usr/local/bin/php' : '/usr/bin/php');
117        $artisanPath = escapeshellarg(base_path('artisan'));
118        $fieldsArg = escapeshellarg(implode(',', array_values($data['fields'])));
119        $dateFromArg = escapeshellarg($data['date_from']);
120        $dateToArg = escapeshellarg($data['date_to']);
121        $opsArg = $suppressOps ? 1 : 0;
122        $finArg = $suppressFin ? 1 : 0;
123
124        foreach ($data['regions'] as $region) {
125            $regionArg = escapeshellarg($region);
126            $logFile = storage_path('logs/cofrai-bulk-spawn-'.$run->id.'-'.preg_replace('/[^a-zA-Z0-9]/', '_', $region).'.log');
127            // Detach via `nohup setsid` so the artisan keeps running after
128            // the Apache worker that fired this exec is recycled. Redirect
129            // both streams to a per-run log file so silent spawn failures
130            // are recoverable instead of vanishing.
131            $command = sprintf(
132                'nohup setsid %s %s cofrai-bulk-sync:run %d %s %s %s %s %d %d > %s 2>&1 < /dev/null &',
133                $phpBinary,
134                $artisanPath,
135                $run->id,
136                $regionArg,
137                $dateFromArg,
138                $dateToArg,
139                $fieldsArg,
140                $opsArg,
141                $finArg,
142                escapeshellarg($logFile)
143            );
144            exec($command, $execOutput, $execCode);
145            Log::channel('cofrai')->info('Cofrai bulk-sync exec', [
146                'run_id' => $run->id,
147                'region' => $region,
148                'exit_code' => $execCode,
149                'output' => $execOutput,
150                'cmd' => $command,
151            ]);
152        }
153
154        Log::channel('cofrai')->info('Cofrai bulk-sync run dispatched', [
155            'run_id' => $run->id,
156            'regions' => $data['regions'],
157            'fields' => $data['fields'],
158            'triggered_by' => $triggeredBy,
159        ]);
160
161        return response()->json([
162            'message' => 'OK',
163            'run_id' => $run->id,
164        ]);
165    }
166
167    /**
168     * GET /api/cofrai/bulk-sync/{runId}
169     * Poll endpoint. The UI hits this every 2-3s while `ended_at` is null
170     * and shows the live totals. Once `ended_at` is set the polling stops
171     * and the result summary is rendered.
172     */
173    public function bulkSyncStatus(int $runId): JsonResponse
174    {
175        $run = TblCofraiBulkSyncRuns::find($runId);
176        if (! $run) {
177            return response()->json(['message' => 'KO', 'error' => 'Run not found'], 404);
178        }
179
180        return response()->json([
181            'data' => [
182                'id' => $run->id,
183                'triggered_by' => $run->triggered_by,
184                'regions' => $run->regions,
185                'date_from' => $run->date_from?->format('Y-m-d'),
186                'date_to' => $run->date_to?->format('Y-m-d'),
187                'fields' => $run->fields,
188                'suppress_approval_ops' => $run->suppress_approval_ops,
189                'suppress_approval_fin' => $run->suppress_approval_fin,
190                'started_at' => $run->started_at?->toIso8601String(),
191                'ended_at' => $run->ended_at?->toIso8601String(),
192                'total_cofrai_budgets' => $run->total_cofrai_budgets,
193                'updated_count' => $run->updated_count,
194                'created_count' => $run->created_count,
195                'skipped_count' => $run->skipped_count,
196                'error_count' => $run->error_count,
197                'errors_json' => $run->errors_json ?? [],
198            ],
199        ]);
200    }
201}