HEX
Server: nginx/1.18.0
System: Linux test-ipsremont 5.4.0-214-generic #234-Ubuntu SMP Fri Mar 14 23:50:27 UTC 2025 x86_64
User: ips (1000)
PHP: 8.0.30
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: /var/www/ipsremont-demo/app/Console/Commands/ExportRepairsReport.php
<?php

namespace App\Console\Commands;

use App\Models\Branch;
use App\Models\Region;
use App\Models\Repair\Repair;
use App\Services\Repair\RepairService;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Http;
use SimpleXMLElement;
use Symfony\Component\Console\Command\Command as CommandAlias;

class ExportRepairsReport extends Command
{

    const SUCCESS_RESULT = 'Рабочий центр принят';

    protected $signature = 'export:repair-report {--W|with-errors : Отправить ошибочные}';

    protected $description = 'Export repair report to 1S';

    protected function formatData(string $data)
    {
        $data = str_replace('&', '', trim($data));
        if (empty($data)) {
            return false;
        }

        $data = iconv('cp1251', 'UTF-8', $data);

        return new SimpleXMLElement($data);
    }

    public function handle(): void
    {
        $regions = Region::all();
        foreach ($regions as $region) {
            $this->info(PHP_EOL . 'Регион: ' . $region->name);
            $this->export($region);
        }
    }

    public function export(Region $region): int
    {
        $this->info('Export repair report to 1S');

        $branchIds = Branch::query()->where('region_id', $region->id)->pluck('id')->toArray();

        /** @var Repair[]|Collection $repairs */
        $repairs = RepairService::getRepairsForExport($this->option('with-errors'), $branchIds);
        if ($repairs->isEmpty()) {
            return CommandAlias::SUCCESS;
        }

        $this->info('Найдено отчётов: ' . $repairs->count());

        $dates = [];
        foreach ($repairs as $repair) {
            $month = date('Y-m-01', strtotime($repair->close_date));
            if (in_array($month, array_keys($dates))) {
                $repair->export_status = Repair::EXPORT_STATUS_DONE;
                $repair->save();

                $this->info('Уже экспортирован');

                continue;
            }

            $repair->export_status = Repair::EXPORT_STATUS_IN_PROGRESS;
            $repair->save();

            $dates[$month] = Repair::EXPORT_STATUS_IN_PROGRESS;
            $filePath = public_path('storage/reports/report_' . $repair->service_id . '_' . $repair->report_name);
            if (!file_exists($filePath)) {
                $repair->export_status = Repair::EXPORT_STATUS_ERROR;
                $repair->save();

                $this->error('Файл отсутствует ' . $filePath);
                continue;
            }

            $request = Http::withBasicAuth(config('import1c.username'), config('import1c.password'))
                ->withBody(file_get_contents($filePath), basename($filePath))
                ->withOptions(['verify' => false]);
            $url = config('import1c.host') . '/receptiondocuments/v1/WorkingWithCenters/' . $region->external_database_code;
            $this->line($url);
            $response = $request->post($url);
            if (empty($response)) {
                $this->error('Пустой ответ');

                return CommandAlias::FAILURE;
            }

            if ($response->status() !== 200) {
                $this->error('Статус ответа: ' . $response->status());
                $this->error('Ошибка: ' . $response->body());

                return CommandAlias::FAILURE;
            }

            $data = $this->formatData($response->body());

            $result = trim((string) $data->WorkingWithCenter->result);
            if (self::SUCCESS_RESULT !== $result) {
                $this->error(basename($filePath) . ' ошибка');
                $this->error('Результат: ' . ($result ?? $response->body()));
                $repair->export_status = Repair::EXPORT_STATUS_ERROR;
                $repair->save();

                continue;
            }

            $repair->export_status = Repair::EXPORT_STATUS_DONE;
            $repair->save();

            $dates[$month] = Repair::EXPORT_STATUS_DONE;

            $this->info(basename($filePath) . ' успешно экспортирован');
        }

        return CommandAlias::SUCCESS;
    }

}