complete document service

This commit is contained in:
iIronside
2022-11-16 14:24:52 +03:00
parent 5c0badaf92
commit c52dd918db
20 changed files with 649 additions and 177 deletions

View File

@ -2,7 +2,6 @@
namespace common\models;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\Expression;
@ -28,8 +27,8 @@ use yii\db\Expression;
*/
class Document extends \yii\db\ActiveRecord
{
const SCENARIO_GENERATE_DOCUMENT_BODY = 'generate_document_body';
const SCENARIO_UPDATE_DOCUMENT_BODY = 'update_document_body';
const SCENARIO_DOWNLOAD_DOCUMENT = 'download_document';
/**
* {@inheritdoc}
@ -67,9 +66,14 @@ class Document extends \yii\db\ActiveRecord
[['contractor_manager_id'], 'exist', 'skipOnError' => true, 'targetClass' => Manager::className(), 'targetAttribute' => ['contractor_manager_id' => 'id']],
[['template_id'], 'exist', 'skipOnError' => true, 'targetClass' => DocumentTemplate::className(), 'targetAttribute' => ['template_id' => 'id']],
[['manager_id'], 'exist', 'skipOnError' => true, 'targetClass' => Manager::className(), 'targetAttribute' => ['manager_id' => 'id']],
// ['resumeTemplateId', 'required', 'on' => self::SCENARIO_GENERATE_RESUME_TEXT],
// ['resumeTemplateId', 'integer', 'on' => self::SCENARIO_GENERATE_RESUME_TEXT],
['body', 'required', 'on' => self::SCENARIO_UPDATE_DOCUMENT_BODY],
['body', function ($attribute, $params) {
preg_match_all('/(\${\w+})/', $this->$attribute,$out);
if (!empty($out[0])) {
$this->addError('body', 'В теле документа все переменные должны бвть заменены!');
}
}, 'on' => self::SCENARIO_DOWNLOAD_DOCUMENT
],
];
}

View File

@ -0,0 +1,51 @@
<?php
namespace common\models;
use Yii;
use yii\helpers\ArrayHelper;
/**
* This is the model class for table "document_field".
*
* @property int $id
* @property string $title
* @property string $field_template
*/
class DocumentField extends \yii\db\ActiveRecord
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'document_field';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['title', 'field_template'], 'string', 'max' => 255],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'title' => 'Название',
'field_template' => 'Шаблон поля',
];
}
public static function getTitleFieldTemplateArr(): array
{
return ArrayHelper::map(self::find()->all(), 'title', 'field_template');
}
}

View File

@ -3,6 +3,9 @@
namespace common\services;
use common\models\Document;
use common\models\DocumentTemplate;
use DateTime;
use kartik\mpdf\Pdf;
class DocumentService
{
@ -25,4 +28,94 @@ class DocumentService
->asArray()->all();
}
public static function getDocumentNumber(): string
{
$documents = Document::find()->where(['DATE(`created_at`)' => date('Y-m-d')])->orderBy('id DESC')->all();
$date = new DateTime();
foreach ($documents as $document) {
preg_match_all('/\b\d{2}\.\d{2}\.\d{4}\/\d{3}\b/', $document->body,$out);
if (!empty($out[0])) {
$num = substr($out[0][0], -3);
$num++;
$num = str_pad($num, 3, "0", STR_PAD_LEFT);
return $date->format('d.m.Y') . '/' . $num;
}
}
return $date->format('d.m.Y') . '/001';
}
public static function downloadPdf($id)
{
$model = Document::findOne($id);
$pdf = new Pdf(); // or new Pdf();
$mpdf = $pdf->api; // fetches mpdf api
$mpdf->SetFooter('{PAGENO}');
$mpdf->WriteHtml($model->body); // call mpdf write html
echo $mpdf->Output("{$model->title}", 'D'); // call the mpdf api output as needed
}
public static function downloadDocx($id)
{
$model = Document::findOne($id);
$pw = new \PhpOffice\PhpWord\PhpWord();
// (B) ADD HTML CONTENT
$section = $pw->addSection();
$documentText = str_replace(array('<br/>', '<br>', '</br>'), ' ', $model->body);
\PhpOffice\PhpWord\Shared\Html::addHtml($section, $documentText, false, false);
// (C) SAVE TO DOCX ON SERVER
// $pw->save("convert.docx", "Word2007");
// (D) OR FORCE DOWNLOAD
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment;filename=\"$model->title.docx\"");
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($pw, "Word2007");
$objWriter->save("php://output");
exit();
}
public static function generateDocumentBody(Document $model)
{
$templateModel = DocumentTemplate::findOne($model->template_id);
preg_match_all('/(\${\w+})/', $templateModel->template_body,$out);
$document = $templateModel->template_body;;
foreach ($out[0] as $field) {
if (str_contains($document, $field)) {
switch ($field)
{
case '${contract_number}':
$fieldValue = DocumentService::getDocumentNumber();
break;
case '${title}':
$fieldValue = $model->title;
break;
case '${company}':
$fieldValue = $model->company->name;
break;
case '${manager}':
$fieldValue = $model->manager->userCard->fio;
break;
case '${contractor_company}':
$fieldValue = $model->contractorCompany->name;
break;
case '${contractor_manager}':
$fieldValue = $model->contractorManager->userCard->fio;
break;
default:
$fieldValue = $field;
break;
}
$document = str_replace($field, $fieldValue, $document);
}
}
$model->body = $document;
}
}