%PDF- %PDF-
Mini Shell

Mini Shell

Direktori : /www/loslex/production/app/Workers/
Upload File :
Create Path :
Current File : /www/loslex/production/app/Workers/RegistrationExporter.php

<?php

namespace App\Workers;

use App\Enums\ContestLevelEnum;
use App\Models\Contest;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use ZipArchive;

class RegistrationExporter
{
    public string $filename;

    public function __construct(Contest $contest, string $type, public bool $all) {
        $now = Carbon::now();
        $replacechars = array(".", "/");
        $this->filename = $contest->id . "/" . $now->isoFormat("YYYY-MM-DD") . "_" . str_replace($replacechars, "-", Str::ucfirst(Str::camel(Str::ascii($contest->contestname))));

        switch ($type) {
            case "csv":
                $this->filename .= ".csv";
                $content = $this->buildSVList($contest);
                break;

            case "tsv":
                $this->filename .= ".csv";
                $content = $this->buildSVList($contest, "\t");
                break;

            case "excel":
                $this->filename .= ".xlsx";
                $content = $this->buildExcel($contest);
                break;

            case "psc":
            default:
                $this->filename .= ".psc";
                $content = $this->buildPractiscore($contest);
                break;
        }

        Storage::disk('contests')->put($this->filename, $content, 'public');
    }

    private function buildHeaderLine()
    {
        return [
            __('exportheader.firstname'),
            __('exportheader.lastname'),
            __('exportheader.licence'),
            __('exportheader.email'),
            __('exportheader.losalias'),
            __('exportheader.division'),
            __('exportheader.squad'),
            __('exportheader.region'),
            __('exportheader.notcompete'),
        ];
    }

    protected function buildSVList(Contest $contest, $separator = ',')
    {
        $data = "\xEF\xBB\xBF"; //BOM
        $data .= join($separator, $this->buildHeaderLine()) . "\n";

        $regs = $this->all ? $contest->registrations : $contest->registrations->where('present', 1);
        $regs = $regs->sortBy([['squad'], ['lastname']]);
        foreach ($regs as $reg) {
            $data .= join($separator, [
                $reg->user->firstname,
                $reg->user->lastname . ($reg->user->namesuffix ? " " . $reg->user->namesuffix : ""),
                $reg->licence_number,
                $reg->user->email,
                strtoupper($reg->user->username),
                $reg->division->bgdivision,
                $reg->squad == 0 ? 'R' : $reg->squad,
                "CZE",
                $reg->notcomp ? "YES" : ""
            ]) . "\n";
        }

        return $data;
    }

    protected function buildPractiscore(Contest $contest)
    {
        $txt = Storage::disk('templates')->get($this->getPsTemplateFile("match_def.json", $contest->contest_level_id));
        $def = json_decode($txt);
        $def->match_id = $contest->psmatchguid;
        $def->match_name = $contest->contestname;
        $def->match_date = $contest->date->format("Y-m-d");
        $def->match_modifieddate = date("Y-m-d H:i:s.v");

        $regs = $this->all ? $contest->registrations : $contest->registrations->where('present', 1);
        foreach ($regs as $reg)
        {
            $date = $reg->updated_at->format("Y-m-d H:i:s.v");
            $chkins = array();
            if($reg->present) { $chkins[] = "CheckIN"; }
            if($reg->notcomp) { $chkins[] = "MZ"; }
            if($reg->lexmember && ($reg->user->is_valid_member($reg->contest->date) > 0)) { $chkins[] = "LEX"; }
            if($reg->paid) { $chkins[] = "Zaplaceno"; }
            $def->match_shooters[] = (object) array(
                "sh_uuid" => $reg->canceltoken,
                "sh_uid" => $reg->canceltoken,
                "sh_ln" => $reg->user->lastname . ($reg->user->namesuffix ? " " . $reg->user->namesuffix : ""),
                "sh_fn" => $reg->user->firstname,
                "sh_id" => strtoupper($reg->user->username),
                "sh_num" => $reg->id,
                "sh_random" => $this->shooterRandom($reg->id),
                "sh_sqd" => $reg->squad == 0 ? 99 : $reg->squad,
                "sh_del" => false,
                "sh_eml" => $reg->user->email,
                "sh_dvp" => $reg->division?->bgdivision,
                "sh_pf" => "MINOR",
                "sh_grd" => "",
                "mod_ctgs" => $date,
                "mod_chkins" => $date,
                "sh_chkins" => $chkins,
                "sh_wlk" => false,
                "sh_mod" => $date,
                "mod_pr" => $date,
                "mod_dv" => $date,
                "mod_pf" => $date,
                "mod_sq" => $date,
                "mod_dl" => $date,
                "mod_dq" => $date,
                "sh_dq" => false,
                "sh_cc" => "CZE"
            );
        }

        $txt = Storage::disk('templates')->get($this->getPsTemplateFile("match_scores.json", $contest->contest_level_id));
        $scores = json_decode($txt);
        $scores->match_id = $contest->psmatchguid;

        $tmpName = tempnam(sys_get_temp_dir(), 'practiscore.zip');
        $zip = new ZipArchive;
        $zip->open($tmpName, ZipArchive::CREATE);
        $zip->addFromString("match_def.json", json_encode($def, JSON_PRETTY_PRINT));
        $zip->addFromString("match_scores.json", json_encode($scores, JSON_PRETTY_PRINT));
        $zip->close();

        $contents = file_get_contents($tmpName);
        unlink($tmpName);
        return $contents;
    }

    protected function getPsTemplateFile(string $basename, int $contest_level_id = null)
    {
        $prefix = match ($contest_level_id) {
            ContestLevelEnum::LOSIK->value => "losik.",
            ContestLevelEnum::SZSCLASSIFICATION->value => "hs.",
            default => ""
        };

        return $prefix.$basename;
    }

    protected function buildExcel(Contest $contest)
    {
        $fp = Storage::disk('templates')->readStream($contest->isLosik() ? "LOSik_2017-template.xls" : "los-tabulka-" . $contest->stages . ".xls");
        $templateFile = stream_get_meta_data($fp)["uri"];
        $regs = $this->all ? $contest->registrations : $contest->registrations->where('present', 1);
        $reader = new Xls();
        $spreadsheet = $reader->load($templateFile);
        $ss = $spreadsheet->setActiveSheetIndex(0);

        $pos = 3;
        $date = date("d. m. Y");
        $ss->setCellValue("A1", $contest->contestname);
        if ($contest->isLosik()) {
            foreach ($regs as $reg) {
                if($reg->notcomp) { $ss->setCellValue("A" . $pos, "MZ"); }
                $ss->setCellValue("B" . $pos, $reg->user->email . "/" . strtoupper($reg->user->username) . "/" . $reg->canceltoken);
                $ss->setCellValue("C" . $pos, $reg->user->listedname);
                $ss->setCellValue("D" . $pos++, $date);
            }
        } else {
            $pos = array();
            foreach ($regs as $reg) {
                $div = strtoupper($reg->division->bgdivision);
                if (!isset($pos[$div])) {
                    $pos[$div] = ExcelHelper::getDefaultPosForDivision($div, $contest->stages);
                }
                if($reg->notcomp) { $ss->setCellValue("A" . $pos[$div], "MZ"); }
                $ss->setCellValue("B" . $pos[$div], $reg->user->email . "/" . strtoupper($reg->user->username). "/" . $reg->canceltoken);
                $ss->setCellValue("C" . $pos[$div]++, $reg->user->listedname);
            }
        }

        $tmpName = tempnam(sys_get_temp_dir(), 'export.xlsx');
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
        $writer->save($tmpName);
        $excel = file_get_contents($tmpName);
        unlink($tmpName);
        return $excel;
    }

    private function shooterRandom(int $shooterId)
    {
        srand($shooterId);
        return rand();
    }
}

Zerion Mini Shell 1.0