Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 108
0.00% covered (danger)
0.00%
0 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
GoogleAdsWebhooks
0.00% covered (danger)
0.00%
0 / 108
0.00% covered (danger)
0.00%
0 / 2
600
0.00% covered (danger)
0.00%
0 / 1
 receive
0.00% covered (danger)
0.00%
0 / 70
0.00% covered (danger)
0.00%
0 / 1
90
 parseUserColumnData
0.00% covered (danger)
0.00%
0 / 38
0.00% covered (danger)
0.00%
0 / 1
240
1<?php
2
3namespace App\Http\Controllers;
4
5use App\Models\TblGoogleAdsForms;
6use App\Models\TblGoogleAdsLeadsLog;
7use App\Models\TblQuotations;
8use Illuminate\Http\Request;
9use Illuminate\Support\Carbon;
10use Illuminate\Support\Facades\Log;
11
12/**
13 * FIRE-XXXX — receives Google Ads Lead Form Extensions webhook POSTs.
14 *
15 * Route: POST /api/webhooks/google-ads-leads/{form_key}
16 *
17 * Auth: Google can't bearer-auth, so the route is OUTSIDE the auth.token
18 * middleware group. Instead we verify the `google_key` field in the body
19 * against the per-form stored secret (hash_equals to avoid timing leaks).
20 *
21 * Behaviour:
22 *   - Always writes the raw payload to tbl_google_ads_leads_log first, so
23 *     forensics is available even when the webhook fails auth or errors.
24 *   - is_test=true → log only, no quotation. Lets Nicolás verify wiring.
25 *   - Real lead → creates a tbl_quotations row with the form's default
26 *     company_id / commercial / source_id, status_id=13 (Solicitud), and
27 *     last_follow_up_comment populated from FULL_NAME / EMAIL / PHONE
28 *     plus any custom fields (e.g. M2 range).
29 *   - Duplicates by email/phone are NOT merged — every webhook hit creates
30 *     a new quotation, so the comercial sees both and dedupes manually
31 *     (clean audit trail; per Nicolás).
32 */
33class GoogleAdsWebhooks extends Controller
34{
35    /**
36     * Standard Google Ads `column_id`s we recognise. Anything outside this
37     * set is treated as a custom field and appended to last_follow_up_comment.
38     */
39    private const STANDARD_COLUMN_IDS = [
40        'FULL_NAME', 'FIRST_NAME', 'LAST_NAME',
41        'EMAIL', 'PHONE_NUMBER',
42        'COMPANY_NAME',
43    ];
44
45    public function receive(Request $request, string $formKey)
46    {
47        $payload = $request->all();
48        $isTest = (bool) ($payload['is_test'] ?? false);
49
50        // Always log first — even auth failures land here for forensics.
51        $logRow = TblGoogleAdsLeadsLog::create([
52            'form_key' => $formKey,
53            'raw_payload' => $payload,
54            'is_test' => $isTest ? 1 : 0,
55            'quotation_id' => null,
56            'error_message' => null,
57            'created_at' => Carbon::now(),
58        ]);
59
60        try {
61            $form = TblGoogleAdsForms::where('form_key', $formKey)
62                ->where('active', 1)
63                ->first();
64
65            if (! $form) {
66                $logRow->update(['error_message' => 'form_key not found or inactive']);
67
68                return response(['message' => 'KO', 'error' => 'invalid form_key'], 404);
69            }
70
71            $providedKey = (string) ($payload['google_key'] ?? '');
72            if ($providedKey === '' || ! hash_equals($form->google_key, $providedKey)) {
73                $logRow->update(['error_message' => 'google_key mismatch']);
74
75                return response(['message' => 'KO', 'error' => 'invalid google_key'], 401);
76            }
77
78            // Test leads land in the log only — Nicolás can verify the
79            // wiring from Google's panel without polluting tbl_quotations.
80            if ($isTest) {
81                Log::channel('third-party')->info(
82                    "Google Ads webhook test lead received for form '{$formKey}' — not creating quotation"
83                );
84
85                return response(['message' => 'OK', 'note' => 'test lead, no quotation created'], 200);
86            }
87
88            $parsed = $this->parseUserColumnData($payload['user_column_data'] ?? []);
89
90            $commentParts = ['Lead Google Ads recibido '.Carbon::now()->format('d/m/Y H:i')];
91            foreach ($parsed['custom_fields'] as $label => $value) {
92                $commentParts[] = "{$label}: {$value}";
93            }
94            $comment = implode(' | ', $commentParts);
95
96            // Mirror create_quotation: allocate the next quote_id ("# en Titan")
97            // via Quotations::get_number(), which inserts a placeholder row
98            // with for_add=1 and returns its id + the new number. We then
99            // UPDATE that placeholder with our real fields. Without this the
100            // quote_id stayed NULL and the Pedidos listing couldn't render
101            // the row properly.
102            $numberRequest = new Request(['created_by' => 'Google Ads']);
103            $numberResponse = app(Quotations::class)->get_number($numberRequest, $form->company_id);
104            $placeholderId = $numberResponse->original['id'];
105            $newNumber = $numberResponse->original['number'];
106
107            // request_date / issue_date: Google's webhook doesn't carry a
108            // user-submission timestamp, but it fires within seconds of the
109            // user pressing submit, so "now" is accurate. Mirrors G3W sync,
110            // which sets both fields to `fecha_creacion`.
111            $now = Carbon::now();
112
113            TblQuotations::where('id', $placeholderId)->update([
114                'quote_id' => $newNumber,
115                'client' => $parsed['client'],
116                'email' => $parsed['email'],
117                'phone_number' => $parsed['phone_number'],
118                'budget_status_id' => $form->status_id ?: 6,   // 6 = Solicitud
119                'source_id' => $form->default_source_id,
120                'commercial' => $form->default_commercial,
121                'customer_type_id' => 2,
122                'created_by' => 'Google Ads',
123                'request_date' => $now,
124                'issue_date' => $now,
125                'updated_at' => $now,
126                'last_follow_up_comment' => $comment,
127                'has_attachment' => 0,
128                'sync_import' => 0,
129                'for_add' => 0,
130                'for_approval' => 0,
131            ]);
132            $quotation = TblQuotations::find($placeholderId);
133
134            $logRow->update(['quotation_id' => $quotation->id]);
135
136            Log::channel('third-party')->info(
137                "Google Ads webhook → quotation #{$quotation->id} created for form '{$formKey}'"
138            );
139
140            return response([
141                'message' => 'OK',
142                'quotation_id' => $quotation->id,
143            ], 200);
144        } catch (\Throwable $e) {
145            $logRow->update(['error_message' => substr($e->getMessage(), 0, 1000)]);
146
147            Log::channel('third-party')->error(
148                "Google Ads webhook error for form '{$formKey}': ".$e->getMessage(),
149                ['trace' => $e->getTraceAsString()]
150            );
151
152            return response(['message' => 'KO', 'error' => 'internal'], 500);
153        }
154    }
155
156    /**
157     * Walk Google's user_column_data[] and map standard column_ids to
158     * named fields. Unknown column_ids land in custom_fields keyed by
159     * the friendly column_name (or column_id if column_name is empty).
160     *
161     * @param  array<int, array{column_id?: string, column_name?: string, string_value?: string}>  $userData
162     * @return array{client: ?string, email: ?string, phone_number: ?string, custom_fields: array<string, string>}
163     */
164    private function parseUserColumnData(array $userData): array
165    {
166        $result = [
167            'client' => null,
168            'email' => null,
169            'phone_number' => null,
170            'custom_fields' => [],
171        ];
172
173        $firstName = null;
174        $lastName = null;
175
176        foreach ($userData as $field) {
177            $id = strtoupper((string) ($field['column_id'] ?? ''));
178            $name = (string) ($field['column_name'] ?? '');
179            $value = trim((string) ($field['string_value'] ?? ''));
180
181            if ($value === '') {
182                continue;
183            }
184
185            switch ($id) {
186                case 'FULL_NAME':
187                    $result['client'] = $value;
188                    break;
189                case 'FIRST_NAME':
190                    $firstName = $value;
191                    break;
192                case 'LAST_NAME':
193                    $lastName = $value;
194                    break;
195                case 'EMAIL':
196                    $result['email'] = $value;
197                    break;
198                case 'PHONE_NUMBER':
199                    $result['phone_number'] = $value;
200                    break;
201                case 'COMPANY_NAME':
202                    // Only fill client from COMPANY_NAME if we don't have
203                    // a FULL_NAME already (B2C forms might send only one).
204                    if ($result['client'] === null) {
205                        $result['client'] = $value;
206                    }
207                    break;
208                default:
209                    // Custom field — stash for the comment.
210                    $label = $name !== '' ? $name : $id;
211                    $result['custom_fields'][$label] = $value;
212            }
213        }
214
215        // FIRST_NAME + LAST_NAME → client when FULL_NAME wasn't sent.
216        if ($result['client'] === null && ($firstName !== null || $lastName !== null)) {
217            $result['client'] = trim(($firstName ?? '').' '.($lastName ?? ''));
218        }
219
220        return $result;
221    }
222}