true, 'total' => count($offenders), 'created' => 0, 'found' => 0, 'errors' => 0, 'accounts' => array() ); // Обрабатываем каждого offender foreach ($offenders as $index => $offender) { $accountResult = array( 'index' => $index, 'success' => false, 'account_id' => null, 'action' => null, 'accountname' => $offender['accountname'] ?? '', 'inn' => $offender['inn'] ?? '', 'role' => $offender['role'] ?? null, 'message' => '' ); try { // Извлекаем данные $accountname = trim($offender['accountname'] ?? ''); $address = trim($offender['address'] ?? ''); $email = trim($offender['email'] ?? ''); $website = trim($offender['website'] ?? ''); $phone = trim($offender['phone'] ?? ''); $inn = preg_replace('/[^0-9]/', '', $offender['inn'] ?? ''); // Только цифры $ogrn = preg_replace('/[^0-9]/', '', $offender['ogrn'] ?? ''); // Только цифры $role = trim($offender['role'] ?? ''); // Проверка обязательных полей if (empty($accountname)) { throw new Exception('Не указано наименование контрагента (accountname)'); } if (empty($inn)) { throw new Exception('Не указан ИНН'); } // Валидация ИНН (10 или 12 цифр) if (strlen($inn) != 10 && strlen($inn) != 12) { $logstring = date('Y-m-d H:i:s') . " ⚠️ Нестандартный ИНН: $inn (длина " . strlen($inn) . ')'; file_put_contents($logFile, $logstring . PHP_EOL, FILE_APPEND); // Не падаем, просто логируем } // ======================================== // ПОИСК ПО ИНН // ======================================== $query = "SELECT a.accountid, a.accountname FROM vtiger_account a LEFT JOIN vtiger_crmentity e ON e.crmid = a.accountid WHERE e.deleted = 0 AND a.inn = ? LIMIT 1"; $res = $adb->pquery($query, array($inn)); if ($adb->num_rows($res) > 0) { // === НАЙДЕН — просто возвращаем ID === $existingId = $adb->query_result($res, 0, 'accountid'); $existingName = $adb->query_result($res, 0, 'accountname'); $accountResult['success'] = true; $accountResult['account_id'] = $existingId; $accountResult['action'] = 'found'; $accountResult['message'] = 'Контрагент найден по ИНН'; $accountResult['existing_name'] = $existingName; $results['found']++; $logstring = date('Y-m-d H:i:s') . " ✓ [$index] Найден: $existingId ($existingName) по ИНН $inn"; file_put_contents($logFile, $logstring . PHP_EOL, FILE_APPEND); } else { // === НЕ НАЙДЕН — создаём === $params = array( 'accountname' => $accountname, 'bill_street' => $address, 'email1' => $email, 'website' => $website, 'phone' => $phone, 'inn' => $inn, 'cf_1951' => $ogrn, // ОГРН в кастомном поле 'assigned_user_id' => vtws_getWebserviceEntityId('Users', $current_user->id) ); $logstring = date('Y-m-d H:i:s') . " 🆕 [$index] Создаём: " . json_encode($params, JSON_UNESCAPED_UNICODE); file_put_contents($logFile, $logstring . PHP_EOL, FILE_APPEND); $account = vtws_create('Accounts', $params, $current_user); $newAccountId = substr($account['id'], 3); // Убираем 11x $accountResult['success'] = true; $accountResult['account_id'] = $newAccountId; $accountResult['action'] = 'created'; $accountResult['message'] = 'Контрагент создан'; $results['created']++; $logstring = date('Y-m-d H:i:s') . " ✅ [$index] Создан: $newAccountId"; file_put_contents($logFile, $logstring . PHP_EOL, FILE_APPEND); } } catch (WebServiceException $ex) { $accountResult['success'] = false; $accountResult['message'] = $ex->getMessage(); $results['errors']++; $logstring = date('Y-m-d H:i:s') . " ❌ [$index] WebService ошибка: " . $ex->getMessage(); file_put_contents($logFile, $logstring . PHP_EOL, FILE_APPEND); } catch (Exception $ex) { $accountResult['success'] = false; $accountResult['message'] = $ex->getMessage(); $results['errors']++; $logstring = date('Y-m-d H:i:s') . " ❌ [$index] Ошибка: " . $ex->getMessage(); file_put_contents($logFile, $logstring . PHP_EOL, FILE_APPEND); } $results['accounts'][] = $accountResult; } // Итоговый статус $results['success'] = ($results['errors'] == 0); $logstring = date('Y-m-d H:i:s') . ' RESULT: total=' . $results['total'] . ', created=' . $results['created'] . ', found=' . $results['found'] . ', errors=' . $results['errors'] . PHP_EOL; file_put_contents($logFile, $logstring, FILE_APPEND); return json_encode($results, JSON_UNESCAPED_UNICODE); }