Your IP : 216.73.216.170


Current Path : /home/bitrix/ext_www/rg-so.yacl.site/
Upload File :
Current File : /home/bitrix/ext_www/rg-so.yacl.site/structure_import.php

<?
define("NOT_CHECK_PERMISSIONS", true);
if (!$_SERVER["DOCUMENT_ROOT"]) {
    $_SERVER["DOCUMENT_ROOT"] = realpath(__DIR__);
} else {
    die ('Script for console only');
}

require($_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/include/prolog_before.php");
require_once $_SERVER["DOCUMENT_ROOT"] . '/local/composer/vendor/autoload.php';

use Bitrix\Main\Type\DateTime;
use Bitrix\Main\Loader;
use Bitrix\Highloadblock\HighloadBlockTable as HLBT;
use Bitrix\Disk\Security\DiskSecurityContext;
use Bitrix\Disk\Security\SecurityContext;
use Bitrix\Disk\Storage;
use Bitrix\Main\Localization\Loc;

Loader::includeModule('tasks');
Loader::includeModule('iblock');



$offset = 3;
$dzoRootId = 512;
$entity = \Bitrix\Iblock\Model\Section::compileEntityByIblock(IBLOCK_DEPARTMENT);
$bs = new CIBlockSection;
$dzoRootSection = $entity::getList([
    'filter' => ['ID' => $dzoRootId, 'ACTIVE' => 'Y'],
    'select' => ['ID', 'NAME', 'LEFT_MARGIN', 'RIGHT_MARGIN']
])->fetch();
if (!$dzoRootSection) {
    echo "Wrong DZO Root Section!\n";
    die();
}


$dir = $_SERVER["DOCUMENT_ROOT"] . '/upload/structure/5_2';
foreach(glob($dir . '/*.xlsx') as $filename) {
    $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
//$reader->setReadDataOnly(true);
    $spreadsheet = $reader->load($filename);
    $data = $spreadsheet->getActiveSheet()->toArray();
    $rootSectionName = $data[3][6];
    if (!$rootSectionName) {
        $rootSectionName = $data[3][5];
    }
    if (mb_strpos($rootSectionName, 'АО') === false) {
        $rootSectionName = $data[4][6];
    }
    switch ($filename) {
        case $dir . '/yagf.xlsx':
            $rootSectionName = 'АО "Якутсгеофизика"';
            break;
        case $dir . '/png.xlsx':
            $rootSectionName = "ПАО ПНГ";
            break;
        case $dir . '/jumg.xlsx':
            $rootSectionName = 'АО "Южморгеология"';
            break;
        case $dir . '/ф-юг.xlsx':
            $rootSectionName = 'Филиал Юг-Геленджик';
            break;
        case $dir . '/ф-урал.xlsx':
            $rootSectionName = 'Филиал Урал (Пермь)';
            break;
        case $dir . '/ф-сиб.xlsx':
            $rootSectionName = 'Филиал Сибирь (Новосибирск)';
            break;
        case $dir . '/ф-сз.xlsx':
            $rootSectionName = 'Филиал С-Запад (С-Петербург)';
            break;
    }
//    okp($filename . ' -> ' . $rootSectionName);
//    continue;

//foreach ($names as $filePrefix => $rootSectionName) {
    echo $rootSectionName . "\n";
//    $filename = $_SERVER["DOCUMENT_ROOT"] . '/upload/structure/' . $filePrefix . '.xlsx';
    $rootSection = $entity::getList([
        'filter' => [
            'NAME' => $rootSectionName,
            'ACTIVE' => 'Y',
            '>=LEFT_MARGIN' => $dzoRootSection['LEFT_MARGIN'],
            '<=RIGHT_MARGIN' => $dzoRootSection['RIGHT_MARGIN']
        ],
        'select' => ['ID', 'NAME', 'LEFT_MARGIN', 'RIGHT_MARGIN']
    ])->fetch();
    if (!$rootSection) {
        $rootSectionId = $bs->Add([
            'IBLOCK_ID' => IBLOCK_DEPARTMENT,
            'SORT' => 500,
            'NAME' => $rootSectionName,
            'IBLOCK_SECTION_ID' => $dzoRootId,
            'ACTIVE' => 'Y',
        ]);

        $dzoRootSection = $entity::getList([
            'filter' => ['ID' => $dzoRootId, 'ACTIVE' => 'Y'],
            'select' => ['ID', 'NAME', 'LEFT_MARGIN', 'RIGHT_MARGIN']
        ])->fetch();

        $rootSection = $entity::getList([
            'filter' => ['ID' => $rootSectionId, 'ACTIVE' => 'Y'],
            'select' => ['ID', 'NAME', 'LEFT_MARGIN', 'RIGHT_MARGIN']
        ])->fetch();
    } else {
        $rootSectionId = $rootSection['ID'];
    }

    if (!$rootSection) {
        echo "Wrong Root Section for $filePrefix!\n";
        die();
    }

    $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
//$reader->setReadDataOnly(true);
    $spreadsheet = $reader->load($filename);
    $data = $spreadsheet->getActiveSheet()->toArray();
    $sections = [];
    $userList = [];
    for ($index = $offset; $index < count($data); ++$index) {
        $row = $data[$index];
        $sectionName = $row[5];
        $parentSectionName = $row[6];
        $email = $row[9];
        $userList[$email] = [
            'email' => $email,
            'section' => $sectionName,
            'parentSection' => $parentSectionName,
            'row' => $index
        ];
        $isSectionHead = mb_strtoupper($row[10]) == 'ДА' || $row[10] == 1;
        if ($sectionName) {
            $sections[$sectionName]['name'] = $sectionName;
            if ($parentSectionName) {
                $sections[$sectionName]['parent_name'] = $parentSectionName;
                $sections[$parentSectionName]['name'] = $parentSectionName;
            }
            if ($isSectionHead) {
                $sections[$sectionName]['head'] = $email;
            }
        }
    }
//okp($sections);
//okp($userList);

    $importedSections = [];

    foreach ($sections as &$dep) {
        $dep['name'] = preg_replace('/[ ]+$/', '', $dep['name']);
        $filter = [
            'NAME' => $dep['name'],
            'ACTIVE' => 'Y',
            '>=LEFT_MARGIN' => $rootSection['LEFT_MARGIN'],
            '<=RIGHT_MARGIN' => $rootSection['RIGHT_MARGIN']
        ];
//        if ($dep['name'] == $rootSection['NAME']) {
//            $filter['>=LEFT_MARGIN'] = $dzoRootSection['LEFT_MARGIN'];
//            $filter['<=RIGHT_MARGIN'] = $dzoRootSection['RIGHT_MARGIN'];
//        }
        $currentSection = $entity::getList([
            'filter' => $filter,
            'select' => ['ID', 'NAME']
        ])->fetch();
        if (!$currentSection) {
            if ($dep['name'] == $rootSection['NAME']) {
                okp($dep);
                okp($rootSection);
                okp($filter);
                okp("rootSection not found?!");
            }
//        okp('Try add');
//        okp([
//            'IBLOCK_ID' => IBLOCK_DEPARTMENT,
//            'SORT' => 500,
//            'NAME' => $dep['name'],
//            'IBLOCK_SECTION_ID' => $rootId,
//            'ACTIVE' => 'Y',
//        ]);
            $sectionId = $bs->Add([
                'IBLOCK_ID' => IBLOCK_DEPARTMENT,
                'SORT' => 500,
                'NAME' => $dep['name'],
                'IBLOCK_SECTION_ID' => $rootSectionId,
                'ACTIVE' => 'Y',
            ]);
            if (!$sectionId) {
                okp($bs->LAST_ERROR);
            } else {
                $dep['id'] = $sectionId;
                $rootSection = $entity::getList([
                    'filter' => ['ID' => $rootSectionId, 'ACTIVE' => 'Y'],
                    'select' => ['ID', 'NAME', 'LEFT_MARGIN', 'RIGHT_MARGIN']
                ])->fetch();
            }
        } else {
//        okp('Section exists');
//        okp($currentSection);
            $dep['id'] = $currentSection['ID'];
        }
    }

    foreach ($sections as $index => $depSection) {
        if ($depSection['id'] && $depSection['parent_name']) {
            $parentId = $sections[$depSection['parent_name']]['id'];
            if ($parentId > 0) {
                $fields = [
                    'IBLOCK_SECTION_ID' => $parentId,
                ];
                $headId = getUserIdByEmail($depSection['head'], true);
                if ($headId) {
                    $fields['UF_HEAD'] = $headId;
                }
                $res = $bs->Update($depSection['id'], $fields);
                if (!$res) {
                    okp($bs->LAST_ERROR);
                }
            }
        } else {
            continue;
        }
    }
    echo "<pre>";
    foreach ($userList as $user) {
        $sectionId = $sections[$user['section']]['id'];
        $userId = getUserIdByEmail($user['email'], true);
        if ($userId > 0 && $sectionId > 0) {
            $deps = [$sectionId];
            if ($sections[$user['parentSection']]['id']) {
                $deps[] = $sections[$user['parentSection']]['id'];
            }
            $userDepartments = \Bitrix\Main\UserTable::getList(array(
                'filter' => array(
                    '=ID' => $userId
                ),
                'select' => array('UF_DEPARTMENT')
            ))->fetch()['UF_DEPARTMENT'];
            if (!$deps) {
                $deps = [];
            }
            if (!$userDepartments) {
                $userDepartments = [];
            }
            $newDepartments = array_merge($deps, $userDepartments);
            sort($newDepartments);
            $newDepartments = array_unique($newDepartments);
            $res = $USER->Update($userId, ['UF_DEPARTMENT' => $newDepartments]);
            if (!$res) {
                echo $USER->LAST_ERROR . "\n";
            } else {
//                echo $userId . " добавлен в подразделения " . implode(', ', $newDepartments) . "\n";
            }
        } else {
            if (!$sectionId) {
                echo "Не задано подразделение для " . $user['email'] . " (строка " . $user['row'] . ")\n";
            }
            if (!$userId) {
                echo "Пользователь " . $user['email'] . " (строка " . $user['row'] . ") не найден в системе или неактивен\n";
            }
        }
    }
    echo "</pre>";
}