87 lines
2.8 KiB
PHP
87 lines
2.8 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
class ErpSync
|
|
{
|
|
public static function sync(): array
|
|
{
|
|
$apiUrl = env('ERP_SYNC_API_URL', '');
|
|
$apiKey = env('ERP_SYNC_API_KEY', '');
|
|
|
|
if ($apiUrl === '') {
|
|
return ['error' => 'ERP_SYNC_API_URL no configurado'];
|
|
}
|
|
|
|
$httpHeader = ['Accept: application/json'];
|
|
if ($apiKey !== '') {
|
|
$httpHeader[] = 'Authorization: Bearer ' . $apiKey;
|
|
}
|
|
|
|
$ch = curl_init($apiUrl);
|
|
curl_setopt_array($ch, [
|
|
CURLOPT_RETURNTRANSFER => true,
|
|
CURLOPT_HTTPHEADER => $httpHeader,
|
|
CURLOPT_TIMEOUT => 30,
|
|
]);
|
|
|
|
$response = curl_exec($ch);
|
|
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
|
curl_close($ch);
|
|
|
|
if ($httpCode !== 200) {
|
|
return ['error' => "HTTP {$httpCode}", 'response' => mb_substr((string)$response, 0, 1000)];
|
|
}
|
|
|
|
$companies = json_decode($response, true);
|
|
if (!is_array($companies)) {
|
|
return ['error' => 'JSON inválido del ERP'];
|
|
}
|
|
|
|
$synced = 0;
|
|
$errors = [];
|
|
|
|
foreach ($companies as $company) {
|
|
try {
|
|
self::upsert($company);
|
|
$synced++;
|
|
} catch (\Exception $e) {
|
|
$errors[] = $e->getMessage();
|
|
}
|
|
}
|
|
|
|
return ['synced' => $synced, 'errors' => $errors];
|
|
}
|
|
|
|
private static function upsert(array $data): void
|
|
{
|
|
$stmt = db()->prepare("
|
|
INSERT INTO companies
|
|
(name, display_name, phone_number_id, display_phone, api_base_url, api_key, bot_type, requires_approval, is_active, config_json)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
ON DUPLICATE KEY UPDATE
|
|
name = VALUES(name),
|
|
display_name = VALUES(display_name),
|
|
api_base_url = VALUES(api_base_url),
|
|
api_key = VALUES(api_key),
|
|
bot_type = VALUES(bot_type),
|
|
requires_approval = VALUES(requires_approval),
|
|
is_active = VALUES(is_active),
|
|
config_json = VALUES(config_json),
|
|
updated_at = NOW()
|
|
");
|
|
|
|
$stmt->execute([
|
|
$data['name'] ?? '',
|
|
$data['display_name'] ?? $data['name'] ?? '',
|
|
$data['phone_number_id'] ?? '',
|
|
$data['display_phone'] ?? '',
|
|
$data['api_base_url'] ?? '',
|
|
$data['api_key'] ?? '',
|
|
$data['bot_type'] ?? 'normal',
|
|
(int)($data['requires_approval'] ?? 0),
|
|
(int)($data['is_active'] ?? 1),
|
|
isset($data['config_json']) ? (is_string($data['config_json']) ? $data['config_json'] : json_encode($data['config_json'])) : null,
|
|
]);
|
|
}
|
|
}
|