Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.76% covered (danger)
0.76%
1 / 132
33.33% covered (danger)
33.33%
1 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
FreshDeskTicketSync
0.76% covered (danger)
0.76%
1 / 132
33.33% covered (danger)
33.33%
1 / 3
1449.43
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 handle
0.00% covered (danger)
0.00%
0 / 120
0.00% covered (danger)
0.00%
0 / 1
930
 htmlToTextWithLineBreaks
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
56
1<?php
2
3namespace App\Console\Commands;
4
5use App\Models\TblLeave;
6use Carbon\Carbon;
7use Illuminate\Console\Command;
8use Illuminate\Support\Facades\Log;
9use Illuminate\Support\Facades\Http;
10use Illuminate\Http\Request;
11use GuzzleHttp\Client;
12
13class FreshDeskTicketSync extends Command
14{
15    /**
16     * The name and signature of the console command.
17     *
18     * @var string
19     */
20    protected $signature = 'sync:freshdesk';
21
22    /**
23     * The console command description.
24     *
25     * @var string
26     */
27    protected $description = 'Command description';
28
29    /**
30     * Create a new command instance.
31     *
32     * @return void
33     */
34    public function __construct()
35    {
36        parent::__construct();
37    }
38
39    /**
40     * Execute the console command.
41     *
42     * @return int
43     */
44    public function handle()
45    {
46
47        $regions = [
48            "CAT" => "firebusinesssl-help.freshdesk.com",
49            "MAD" => "firebusinessmadrid.freshdesk.com",
50            "ALM" => "firebusinessalmeria.freshdesk.com"
51        ];
52
53        foreach ($regions as $reg => $url) {
54
55            $companyId = 0;
56
57            switch ($reg) {
58                case 'CAT':
59                    $companyId = 19;
60                    break;
61                case 'MAD':
62                    $companyId = 18;
63                    break;
64                case 'ALM':
65                    $companyId = 21;
66                    break;
67                default:
68                    $region = 19;
69                break;
70            }
71            
72            $apiKey = env('FRESHDESK_TOKEN_' . $reg) . ":X";            
73
74            for ($i = 1; $i <= 10; $i++) { 
75                
76                $domain = 'https://' . $url . '/api/v2/tickets?page=' . $i. '&include=requester,description';            
77
78                $response = Http::withBasicAuth($apiKey, 'X')->get($domain);
79
80                $data = json_decode($response);
81
82                if(is_array($data)){
83                    foreach ($data as $item) {
84
85                        $tags = (is_object($item) && isset($item->tags) && is_array($item->tags)) ? $item->tags : [];
86
87                        if(in_array("RIESGO DE BAJA", $tags) || in_array("BAJA", $tags)){
88                            $cleanHtml = null;
89
90                            if(isset($item->description)){
91                                $cleanHtml = str_replace(["\n", "\r"], '', $item->description);                
92                                $cleanHtml = preg_replace('/\s+/', ' ', $cleanHtml);
93
94                                $doc = new \DOMDocument();
95                                libxml_use_internal_errors(true);
96                                
97                                $doc->loadHTML('<?xml encoding="UTF-8">' . $cleanHtml, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
98                                libxml_clear_errors();
99                                
100                                $fields = ['Client ID','Service Code','Nombre','CIF','Teléfono','Email','Dirección', 'Nombre (2nd try)', 'Teléfono llamada', 'Fecha y hora', 'Teléfono1', 'Resumen'];
101                                $result = array_fill_keys($fields, null);
102
103                                $tables = $doc->getElementsByTagName('table');
104
105                                foreach ($tables as $table) {
106                                    $rows = $table->getElementsByTagName('tr');
107
108                                    foreach ($rows as $row) {
109                                        $tds = $row->getElementsByTagName('td');
110                                        if ($tds->length >= 2) {
111                                            $key = trim($tds->item(0)->textContent);
112                                            $value = trim($tds->item(1)->textContent);
113                                            
114                                            $key = mb_convert_encoding($key, 'UTF-8', 'UTF-8');
115                                            $value = mb_convert_encoding($value, 'UTF-8', 'UTF-8');
116
117                                            if (in_array($key, $fields)) {
118                                                if ($key === "Resumen") {
119                                                    $resumenText = trim($this->htmlToTextWithLineBreaks($tds->item(1)));
120                                                    $result[$key] = $resumenText;
121                                                } else {
122                                                    $result[$key] = $value;
123                                                }
124                                            }
125                                        }
126                                    }
127                                }
128                            }                        
129
130                            $spans = $doc->getElementsByTagName('span');
131                            foreach ($spans as $span) {
132                                $text = trim($span->nodeValue);
133                                $parts = explode(':', $text, 2);
134                                if (count($parts) === 2) {
135                                    $result[trim($parts[0]) . 1] = trim($parts[1]);
136                                }
137                            }
138
139                            $container = $doc->getElementsByTagName('div')->item(1);
140                            
141                            $lines = [];
142                            if(!empty($container)){
143                                foreach (@$container->childNodes as $node) {
144                                    if ($node->nodeName === 'br') {
145                                        $lines[] = "\n";
146                                    } elseif ($node->nodeType === XML_ELEMENT_NODE && $node->nodeName === 'span') {
147                                        $lines[] = $node->textContent;
148                                    } elseif ($node->nodeType === XML_TEXT_NODE) {
149                                        $lines[] = $node->textContent;
150                                    }
151                                }
152                            }                            
153                            
154                            $text = implode('', $lines);
155                            $text_lines = array_filter(array_map('trim', preg_split('/\n+/', $text)));
156
157                            foreach ($text_lines as $line) {
158                                if (strpos($line, ':') !== false) {
159                                    list($key, $value) = explode(':', $line, 2);
160                                    $result[trim($key) . 1] = trim($value);
161                                }
162                            }
163
164                            $aiwf = Http::withHeaders([
165                                'Accept' => 'application/json',
166                                'Content-Type' => 'application/json',
167                            ])->post('https://aiwf.ibvgroup.com/webhook/client-finder', [
168                                'ticket_id' => $item->id,
169                                'region' => strtolower($reg)
170                            ]);
171
172                            $aiwfData = json_decode($aiwf->body());
173                            
174                            $aiwfData1 = @$aiwfData->data_crm->crm_record;
175                            $aiwfData2 = @$aiwfData->data_ai->output;
176
177                            TblLeave::upsert(
178                                [
179                                    [
180                                        'company_id' => $companyId,
181                                        'freshdesk_ticket_id' => $item->id,
182                                        'freshdesk_ticket_link' => $url . '/a/tickets/' . $item->id,
183                                        'customer_name' => $aiwfData1->service_name ?? $aiwfData2->company_name ?? $result['Nombre'] ?? $result['Nombre (2nd try)'] ?? $result['Nombre del cliente1'] ?? null,
184                                        'customer_email' => $aiwfData1->email ?? $aiwfData2->requester_email ?? $result['Email'] ?? $result['Correo1'] ?? null,
185                                        'customer_telephone_number' => $aiwfData1->phone ?? $aiwfData2->phone ?? $result['Teléfono'] ?? $result['Teléfono llamada'] ?? $result['Teléfono1'] ?? null,
186                                        'gestiona_customer_id' => $aiwfData1->g3w_client_id ?? $result['Client ID'] ?? null,
187                                        'description' => $cleanHtml,
188                                        'date_of_receipt' => $item->created_at,
189                                        'private_comment' => $result['Motivo/Consulta1'] ?? null,
190                                        'comment_for_administration' => $result['Resumen'],
191                                        'created_by' => 'System',
192                                        'updated_by' => 'System',
193                                        'updated_at' => now()
194                                    ],
195                                ],
196                                ['freshdesk_ticket_id'],
197                                [                   
198                                    'company_id',
199                                    'freshdesk_ticket_link',
200                                    'customer_name',
201                                    'customer_email',
202                                    'customer_telephone_number',
203                                    'gestiona_customer_id',
204                                    'description',
205                                    'date_of_receipt',
206                                    'private_comment',
207                                    'comment_for_administration',
208                                    'created_by',
209                                    'updated_by',
210                                    'updated_at',
211                                ]
212                            );
213                        }                
214                    }
215                }
216
217                
218            }
219
220            
221        }
222    }
223
224    function htmlToTextWithLineBreaks(\DOMNode $node) {
225        $text = '';
226                    
227        if(!empty($node)){
228            foreach (@$node->childNodes as $child) {
229                if ($child->nodeType === XML_TEXT_NODE) {
230                    $text .= $child->nodeValue;
231                } elseif ($child->nodeName === 'br') {
232                    $text .= "\n";
233                } elseif ($child->nodeName === 'div' || $child->nodeName === 'p') {
234                    $text .= $this->htmlToTextWithLineBreaks($child) . "\n";
235                } else {                
236                    $text .= $this->htmlToTextWithLineBreaks($child);
237                }
238            }            
239        }    
240        
241        return $text;
242    }
243}