]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
Добавление в представления
authorfomichev <vladimir.fomichev@erp-flowers.ru>
Thu, 5 Jun 2025 07:50:06 +0000 (10:50 +0300)
committerfomichev <vladimir.fomichev@erp-flowers.ru>
Thu, 5 Jun 2025 07:50:06 +0000 (10:50 +0300)
erp24/controllers/crud/MarketplaceOrder1cStatusesController.php
erp24/records/MarketplaceOrder1cStatuses.php
erp24/views/crud/marketplace-order-1c-statuses/_form.php
erp24/views/crud/marketplace-order-1c-statuses/create.php
erp24/views/crud/marketplace-order-1c-statuses/index.php
erp24/views/crud/marketplace-order-1c-statuses/update.php
erp24/views/crud/marketplace-order-1c-statuses/view.php

index a39ca83a99abcc18a414da2c230e9a4b1407e449..8696b4b08f92dea85d7539dcdb5591d394231b88 100644 (file)
@@ -3,12 +3,14 @@
 namespace yii_app\controllers\crud;
 
 use Yii;
+use yii\db\Transaction;
 use yii\helpers\ArrayHelper;
 use yii_app\records\MarketplaceOrder1cStatuses;
 use yii\data\ActiveDataProvider;
 use yii\web\Controller;
 use yii\web\NotFoundHttpException;
 use yii\filters\VerbFilter;
+use yii_app\records\MarketplaceOrder1cStatusesRelations;
 use yii_app\services\LessonService;
 
 /**
@@ -57,18 +59,12 @@ class MarketplaceOrder1cStatusesController extends Controller
             }
         }
 
+
+
         $dataProvider = new ActiveDataProvider([
-            'query' => MarketplaceOrder1cStatuses::find()->orderBy(["posit" => SORT_ASC]),
-            /*
-            'pagination' => [
-                'pageSize' => 50
-            ],
-            'sort' => [
-                'defaultOrder' => [
-                    'id' => SORT_DESC,
-                ]
-            ],
-            */
+            'query' => MarketplaceOrder1cStatuses::find()
+                ->with(['relationsFrom', 'nextStatuses'])
+                ->orderBy(['posit' => SORT_ASC]),
         ]);
 
         return $this->render('index', [
@@ -98,16 +94,54 @@ class MarketplaceOrder1cStatusesController extends Controller
     {
         $model = new MarketplaceOrder1cStatuses();
 
-        if ($this->request->isPost) {
-            if ($model->load($this->request->post()) && $model->save()) {
-                return $this->redirect(['view', 'id' => $model->id]);
+        $relationModels = [new MarketplaceOrder1cStatusesRelations()];
+
+        $statusOptions = MarketplaceOrder1cStatuses::find()
+            ->select(['status'])
+            ->indexBy('id')
+            ->column();
+
+        if (Yii::$app->request->isPost) {
+            if ($model->load(Yii::$app->request->post())) {
+                $transaction = Yii::$app->db->beginTransaction(Transaction::SERIALIZABLE);
+                try {
+                    if (!$model->save()) {
+                        throw new \Exception('Не удалось сохранить MarketplaceOrder1cStatuses');
+                    }
+
+                    $postRelations = Yii::$app->request->post('Relations', []);
+
+                    foreach ($postRelations as $i => $relData) {
+                        if (empty($relData['status_id_to'])) {
+                            continue;
+                        }
+
+                        $rel = new MarketplaceOrder1cStatusesRelations();
+                        $rel->status_id_from = $model->id;
+                        $rel->status_id_to = $relData['status_id_to'];
+                        $rel->description   = $relData['description'];
+                        $rel->button_text   = $relData['button_text'];
+
+                        if (!$rel->save()) {
+                            throw new \Exception('Не удалось сохранить Relation #' . $i);
+                        }
+                    }
+
+                    $transaction->commit();
+                    return $this->redirect(['view', 'id' => $model->id]);
+
+                } catch (\Exception $e) {
+                    $transaction->rollBack();
+                    Yii::$app->session->setFlash('error', 'Ошибка при сохранении: ' . $e->getMessage());
+                }
             }
-        } else {
-            $model->loadDefaultValues();
         }
 
+
         return $this->render('create', [
-            'model' => $model,
+            'model'           => $model,
+            'relationModels'  => $relationModels,
+            'statusOptions'   => $statusOptions,
         ]);
     }
 
@@ -122,12 +156,52 @@ class MarketplaceOrder1cStatusesController extends Controller
     {
         $model = $this->findModel($id);
 
-        if ($this->request->isPost && $model->load($this->request->post()) && $model->save()) {
-            return $this->redirect(['view', 'id' => $model->id]);
+        $existingRelations = $model->getRelationsFrom()->all();
+        $relationModels = count($existingRelations) ? $existingRelations : [new MarketplaceOrder1cStatusesRelations()];
+
+        $statusOptions = MarketplaceOrder1cStatuses::find()
+            ->select(['status'])
+            ->indexBy('id')
+            ->column();
+
+        if (Yii::$app->request->isPost) {
+            if ($model->load(Yii::$app->request->post())) {
+                $transaction = Yii::$app->db->beginTransaction(Transaction::SERIALIZABLE);
+                try {
+                    if (!$model->save()) {
+                        throw new \Exception('Не удалось сохранить основной статус');
+                    }
+
+                    MarketplaceOrder1cStatusesRelations::deleteAll(['status_id_from' => $model->id]);
+
+                    $postRelations = Yii::$app->request->post('Relations', []);
+                    foreach ($postRelations as $i => $relData) {
+                        if (empty($relData['status_id_to'])) {
+                            continue;
+                        }
+                        $rel = new MarketplaceOrder1cStatusesRelations();
+                        $rel->status_id_from = $model->id;
+                        $rel->status_id_to   = $relData['status_id_to'];
+                        $rel->description    = $relData['description'];
+                        $rel->button_text    = $relData['button_text'];
+                        if (!$rel->save()) {
+                            throw new \Exception('Не удалось сохранить Relation #' . $i);
+                        }
+                    }
+
+                    $transaction->commit();
+                    return $this->redirect(['view', 'id' => $model->id]);
+                } catch (\Exception $e) {
+                    $transaction->rollBack();
+                    Yii::$app->session->setFlash('error', 'Ошибка при сохранении отношений: ' . $e->getMessage());
+                }
+            }
         }
 
         return $this->render('update', [
-            'model' => $model,
+            'model'           => $model,
+            'relationModels'  => $relationModels,
+            'statusOptions'   => $statusOptions,
         ]);
     }
 
@@ -154,10 +228,15 @@ class MarketplaceOrder1cStatusesController extends Controller
      */
     protected function findModel($id)
     {
-        if (($model = MarketplaceOrder1cStatuses::findOne(['id' => $id])) !== null) {
-            return $model;
+        $model = MarketplaceOrder1cStatuses::find()
+            ->with(['relationsFrom', 'nextStatuses'])
+            ->andWhere(['id' => $id])
+            ->one();
+
+        if ($model === null) {
+            throw new \yii\web\NotFoundHttpException('Запрошенная страница не найдена.');
         }
 
-        throw new NotFoundHttpException('The requested page does not exist.');
+        return $model;
     }
 }
index 3261641dc5c024991e20d45808dd49cce136f89c..4a396ebb72d6a8628004205e729d8e4c7b16fb18 100644 (file)
@@ -3,6 +3,7 @@
 namespace yii_app\records;
 
 use Yii;
+use yii\db\ActiveQuery;
 
 /**
  * This is the model class for table "marketplace_order_1c_statuses".
@@ -70,4 +71,37 @@ class MarketplaceOrder1cStatuses extends \yii\db\ActiveRecord
             'posit' => 'Порядок статусов',
         ];
     }
+
+    public function getRelationsFrom(): ActiveQuery
+    {
+        return $this->hasMany(
+            MarketplaceOrder1cStatusesRelations::class,
+            ['status_id_from' => 'id']
+        );
+    }
+
+
+    public function getRelationsTo(): ActiveQuery
+    {
+        return $this->hasMany(
+            MarketplaceOrder1cStatusesRelations::class,
+            ['status_id_to' => 'id']
+        );
+    }
+
+    public function getNextStatuses(): ActiveQuery
+    {
+        return $this->hasMany(
+            MarketplaceOrder1cStatuses::class,
+            ['id' => 'status_id_to']
+        )->via('relationsFrom');
+    }
+
+    public function getPrevStatuses(): ActiveQuery
+    {
+        return $this->hasMany(
+            MarketplaceOrder1cStatuses::class,
+            ['id' => 'status_id_from']
+        )->via('relationsTo');
+    }
 }
index cea0b9273b54c6c20aa78a52761b8e626c201dcb..ed00551790915e958289ff5ddb93bae94362040f 100644 (file)
@@ -1,22 +1,86 @@
 <?php
-
 use yii\helpers\Html;
 use yii\widgets\ActiveForm;
 
 /** @var yii\web\View $this */
 /** @var yii_app\records\MarketplaceOrder1cStatuses $model */
-/** @var yii\widgets\ActiveForm $form */
+/** @var yii_app\records\MarketplaceOrder1cStatusesRelations[] $relationModels */
+/** @var array $statusOptions  (ключ = id, значение = статус) */
+
+$js = <<<JS
+$(document).ready(function() {
+
+    $('#add-relation-btn').on('click', function() {
+        var template = $('#relation-template .relation-item.template');
+        var clone = template.clone().removeClass('template');
+        $('#relations-container').append(clone);
+    });
+
+    $('#relations-container').on('click', '.remove-relation-btn', function() {
+        $(this).closest('.relation-item').remove();
+    });
+});
+JS;
+$this->registerJs($js);
+
 ?>
 
 <div class="marketplace-order1c-statuses-form">
 
     <?php $form = ActiveForm::begin(); ?>
 
-    <?= $form->field($model, 'marketplace_id')->dropDownList([1 => 'ФлауВау', 2 => 'ЯндексМаркет']) ?>
+    <!-- Поля самого статуса -->
+    <?= $form->field($model, 'marketplace_id')
+        ->dropDownList([1 => 'ФлауВау', 2 => 'ЯндексМаркет'], ['prompt' => 'Выберите маркетплейс']) ?>
 
     <?= $form->field($model, 'status')->textInput(['maxlength' => true]) ?>
 
-    <?= $form->field($model, 'status_instruction')->textarea(['rows' => 6]) ?>
+    <?= $form->field($model, 'status_instruction')->textarea(['rows' => 4]) ?>
+
+    <hr>
+
+
+    <h4>Связанные статусы (relations)</h4>
+    <div id="relations-container">
+        <?php foreach ($relationModels as $i => $rel): ?>
+            <div class="relation-item" style="border:1px solid #ddd; padding:10px; margin-bottom:10px; position: relative;">
+                <!-- Поле «Статус-назначения» -->
+                <?= Html::label('Статус-назначения', null, ['class' => 'control-label']) ?>
+                <?= Html::dropDownList(
+                    "Relations[{$i}][status_id_to]",
+                    $rel->status_id_to,
+                    $statusOptions,
+                    ['prompt' => '— выберите статус —', 'class' => 'form-control']
+                ); ?>
+
+
+                <?= Html::label('Описание (description)', null, ['class' => 'control-label', 'style' => 'margin-top:8px;']) ?>
+                <?= Html::textInput(
+                    "Relations[{$i}][description]",
+                    $rel->description,
+                    ['class' => 'form-control']
+                ); ?>
+
+
+                <?= Html::label('Текст кнопки (button_text)', null, ['class' => 'control-label', 'style' => 'margin-top:8px;']) ?>
+                <?= Html::textInput(
+                    "Relations[{$i}][button_text]",
+                    $rel->button_text,
+                    ['class' => 'form-control']
+                ); ?>
+
+
+                <button type="button" class="btn btn-danger btn-sm remove-relation-btn"
+                        style="position:absolute; top:10px; right:10px;">
+                    &minus; Удалить
+                </button>
+            </div>
+        <?php endforeach; ?>
+    </div>
+
+    <button type="button" id="add-relation-btn" class="btn btn-primary btn-sm" style="margin-bottom:15px;">
+        &plus; Добавить ещё одну связь
+    </button>
 
     <div class="form-group">
         <?= Html::submitButton('Сохранить', ['class' => 'btn btn-success']) ?>
@@ -24,4 +88,28 @@ use yii\widgets\ActiveForm;
 
     <?php ActiveForm::end(); ?>
 
-</div>
+
+
+    <div id="relation-template" style="display:none;">
+        <div class="relation-item template" style="border:1px solid #ddd; padding:10px; margin-bottom:10px; position: relative;">
+            <?= Html::label('Статус-назначения', null, ['class' => 'control-label']) ?>
+            <?= Html::dropDownList(
+                "Relations[__index__][status_id_to]",
+                null,
+                $statusOptions,
+                ['prompt' => '— выберите статус —', 'class' => 'form-control']
+            ); ?>
+
+            <?= Html::label('Описание (description)', null, ['class' => 'control-label', 'style' => 'margin-top:8px;']) ?>
+            <?= Html::textInput("Relations[__index__][description]", null, ['class' => 'form-control']) ?>
+
+            <?= Html::label('Текст кнопки (button_text)', null, ['class' => 'control-label', 'style' => 'margin-top:8px;']) ?>
+            <?= Html::textInput("Relations[__index__][button_text]", null, ['class' => 'form-control']) ?>
+
+            <button type="button" class="btn btn-danger btn-sm remove-relation-btn"
+                    style="position:absolute; top:10px; right:10px;">
+                &minus; Удалить
+            </button>
+        </div>
+    </div>
+</div>
\ No newline at end of file
index 59eaeedda3e1466bf689bcfdd4b0a60bf66f79bb..e3140d6b5e497d563480428a7ca0c21217db3812 100644 (file)
@@ -14,7 +14,9 @@ $this->params['breadcrumbs'][] = $this->title;
     <h1><?= Html::encode($this->title) ?></h1>
 
     <?= $this->render('_form', [
-        'model' => $model,
+        'model'           => $model,
+        'relationModels'  => $relationModels,
+        'statusOptions'   => $statusOptions,
     ]) ?>
 
 </div>
index 153340db4211a1def513dffdc8b377ae152f5cda..628305f273917bfc948908069e38ba8aaed456ad 100644 (file)
@@ -53,6 +53,22 @@ $this->params['breadcrumbs'][] = $this->title;
                     return Url::toRoute([$action, 'id' => $model->id]);
                 }
             ],
+            [
+                'label' => 'Связанные статусы',
+                'format' => 'raw',
+                'value' => function (MarketplaceOrder1cStatuses $model) {
+                    $links = [];
+                    foreach ($model->nextStatuses as $nextStatus) {
+                         $links[] = Html::a(
+                            Html::encode($nextStatus->status),
+                            ['/crud/marketplace-order-1c-statuses/view', 'id' => $nextStatus->id]
+                        );
+                    }
+                    return empty($links)
+                        ? '<span class="text-muted">— нет связи —</span>'
+                        : implode('<br>', $links);
+                },
+            ],
         ],
     ]); ?>
 
index 3ed565357d5a114890fa51278e05170fe976b85f..2bdf182b13a8e422e0935c988f7659f8641b65db 100644 (file)
@@ -18,7 +18,9 @@ $this->params['breadcrumbs'][] = 'Update';
     </h1>
 
     <?= $this->render('_form', [
-        'model' => $model,
+        'model'           => $model,
+        'relationModels'  => $relationModels,
+        'statusOptions'   => $statusOptions,
     ]) ?>
 
 </div>
index 103faefa9098cc0fb569fa7e377246cd7ec461c0..18c6ac3f9bfe8a6921e35d21496199132830dfd8 100644 (file)
@@ -2,6 +2,7 @@
 
 use yii\helpers\Html;
 use yii\widgets\DetailView;
+use yii_app\records\MarketplaceOrder1cStatuses;
 
 /** @var yii\web\View $this */
 /** @var yii_app\records\MarketplaceOrder1cStatuses $model */
@@ -41,6 +42,22 @@ $this->params['breadcrumbs'][] = $this->title;
             ],
             'status',
             'status_instruction:ntext',
+            [
+                'label' => 'Связанные статусы',
+                'format' => 'raw',
+                'value' => function (MarketplaceOrder1cStatuses $model) {
+                    $links = [];
+                    foreach ($model->nextStatuses as $nextStatus) {
+                        $links[] = Html::a(
+                            Html::encode($nextStatus->status),
+                            ['marketplace-order1c-statuses/view', 'id' => $nextStatus->id]
+                        );
+                    }
+                    return empty($links)
+                        ? '<span class="text-muted">— нет связи —</span>'
+                        : implode('<br>', $links);
+                },
+            ],
         ],
     ]) ?>