- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
/* Групповые операции с обращениями */
public function issuegroupopsAction() {
    $this->_helper->layout()->disableLayout();
    $this->_helper->viewRenderer->setNoRender(true);
    $operation = $this->_request->getPost('operation');
    define('RTF_SYMBOL_PAGE_BREAK', '\page');
    try {
        // Валидация
        if(!in_array($operation, array('print-letters', 'print-work-order'))) {
            throw new Exception('Неверная операция');
        }
        $issue_numbers = explode(';', (string)$_POST['issues']);
        if(!count($issue_numbers)) {
            throw new Exception('Не выбрано ни одного обращения.');
        }
        // Вычитка указанных обращений
        $filter = new Type_Issue_Filter(array('issue_number' => $issue_numbers));
        $paginator = new Type_Paginator;
        $paginator->items_per_page = 40;
        $issues = services::Issue()->records($this->user->sessionId, $filter, array('executant', 'address'), 'number', $paginator);
        if(!count($issues->items)) {
            throw new Exception('Выбранные обращения не найдены.');
        }
        $templateMaker = new Prodom_Rtf_TemplateMaker;
        $templatesDir = dirname(__FILE__).'/templates/';
        $outputFiles = array();
        // Вид операции с группой обращений
        switch($operation) {
            case 'print-letters': {
                // Сформирвать письма
                $templateMaker->readTemplatesFromRtfFile($templatesDir.'templates.rtf');
                $outputFiles = array('executants_%u.rtf' => array('issue2', 'letter1'), 'declarant_%u.rtf' => array('letter2'));
                break;
            }
            case 'print-work-order': {
                // Печать заказ-нарядов
                if(!is_null($this->user->organization->issue_form_template)) {
                    // Если для организации определен свой собственный шаблон
                    $templateMaker->readTemplatesFromRtfFile($templatesDir.$this->user->organization->issue_form_template);
                } else {
                    // Если шаблон явно не определен
                    $templateMaker->readTemplatesFromRtfFile($templatesDir.'templates.rtf');
                }
                $outputFiles = array('issue_%u.rtf' => array('issue1'));
                break;
            }
        }
        $toworkIssueIds = array();
        $outputs = array_fill_keys(array_keys($outputFiles), null);
        // Перебор выбранных пользователем обращений
        foreach($issues->items as $issue) {
            // Переводим все новые обращения в статус "В работе"
            $issue_new_statuses = array(ISSUE_STATUS_NEW, ISSUE_STATUS_CONFIRMED);
            if(($operation == 'print-work-order') && in_array($issue->status_id, $issue_new_statuses) && ($issue->org_executor_id == $this->user->organization->id)) {
                $toworkIssueIds[] = $issue->id;
            }
            // Подготовка полей обращения для печати на формах
            $fields = $this->getIssuePrintFields($issue);
            foreach($outputFiles as $fileName => $needTemplates) {
                foreach($needTemplates as $template_code) {
                    $out = $templateMaker->getAppliedTemplate($template_code, $fields);
                    $outputs[$fileName] .= ($outputs[$fileName] ? RTF_SYMBOL_PAGE_BREAK : null) . $out;
                }
            }
        }
        if(count($toworkIssueIds)) {
            $resp = services::Issue()->changeStatusMultiple($this->user->sessionId, $toworkIssueIds, ISSUE_STATUS_INWORK, null, null, null);
        }
        // Если на выходе только один файл, отправляем rtf
        if(count($outputs) == 1) {
            foreach($outputs as $fileName => $fileBody) {
                // Генерация случайного имени файла
                $fileName = str_replace('%u', substr(md5(implode('_', $issue_numbers)), 0, 7), $fileName);
                // Вывод файла пользователю
                header('Content-type: application/rtf');
                header("Content-Disposition: attachment; filename={$fileName}");
                echo $templateMaker->getHeader().$fileBody.$templateMaker->getFooter();
            }
        } else {
            // Eсли на выходе больше одного файла, пакуем их архивом
            header("Content-type: application/octet-stream");
            header("Content-Disposition: attachment; filename=issues.zip");
            header("Content-Description: Files of an applicant");
            // Создаем ZIP архив
            $zip = new ZipFile();
            foreach($outputs as $fileName => $fileBody) {
                // Генерация случайного имени файла
                $fileName = str_replace('%u', substr(md5(implode('_', $issue_numbers)), 0, 7), $fileName);
                // Вывод файла пользователю в браузер
                $fileBody = $templateMaker->getHeader().$fileBody.$templateMaker->getFooter();
                $zip->addFile($fileBody, $fileName);
            }
            echo $zip->file();
        }
    }
    catch(Exception $ex) {
        die($ex->getMessage());
    }
}
                                     
        
            Функция распечатки документов с отчетами по выбранным обращениям