]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
Добавление баланса
authorVladimir Fomichev <vladimir.fomichev@erp-flowers.ru>
Tue, 19 Aug 2025 15:49:41 +0000 (18:49 +0300)
committerVladimir Fomichev <vladimir.fomichev@erp-flowers.ru>
Tue, 19 Aug 2025 15:49:41 +0000 (18:49 +0300)
erp24/controllers/WriteOffsErpController.php
erp24/records/WriteOffsProductsErp.php
erp24/views/write_offs_erp/_form.php
erp24/views/write_offs_erp/create.php
erp24/views/write_offs_erp/update.php
erp24/web/js/write-offs-erp/_form.js [new file with mode: 0644]

index b698189b465b109e959700544fc267ebd31dc646..c9b63b6549f13bdca59d87fa7e81c7d84879cb12 100644 (file)
@@ -4,6 +4,7 @@ namespace app\controllers;
 
 use Exception;
 use Yii;
+use yii\db\Query;
 use yii\helpers\ArrayHelper;
 use yii\web\Response;
 use yii\widgets\ActiveForm;
@@ -394,6 +395,24 @@ class WriteOffsErpController extends Controller
         }
 
         $listProductsDict = Products1c::getProducts1cByTypeWithPrice();
+        $listProductsID = array_keys($listProductsDict);
+        $storeIds = CityStore::find()->select('id')->where(['visible' => 1])->column();
+
+        $balanceArr = (new Query())
+            ->select([
+                'b.product_id',
+                'store_id' => 'ex.entity_id',
+                'b.quantity'
+            ])
+            ->from('balances as b')
+            ->leftJoin('export_import_table ex', 'ex.export_val = b.store_id')
+            ->where(['b.product_id' => $listProductsID])
+            ->andWhere(['ex.entity_id' => $storeIds])
+            ->all();
+        $balanceDict = [];
+        foreach ($balanceArr as $row) {
+            $balanceDict[$row['product_id']][$row['store_id']]= $row['quantity'];
+        }
 
         $listCityStoreNames = CityStore::getNames($storeIds);
         $listCauseDict = WriteOffsProductsErp::getCauseDict($groupId);
@@ -525,6 +544,7 @@ class WriteOffsErpController extends Controller
                         'listCityStoreNames' => $listCityStoreNames,
                         'listCauseDict' => $listCauseDict,
                         'listProductsDict' => $listProductsDict,
+                        'balanceDict' => $balanceDict,
                         'errors' => $errors
                     ]);
                 }
@@ -598,6 +618,7 @@ class WriteOffsErpController extends Controller
                             'listCityStoreNames' => $listCityStoreNames,
                             'listCauseDict' => $listCauseDict,
                             'listProductsDict' => $listProductsDict,
+                            'balanceDict' => $balanceDict,
                             'errors' => $errors
                         ]);
                     }
@@ -614,6 +635,7 @@ class WriteOffsErpController extends Controller
             'listCityStoreNames' => $listCityStoreNames,
             'listCauseDict' => $listCauseDict,
             'listProductsDict' => $listProductsDict,
+            'balanceDict' => $balanceDict,
         ];
 
         return $this->render('/write_offs_erp/create', $params);
@@ -705,6 +727,25 @@ class WriteOffsErpController extends Controller
 
         $listProductsDict = Products1c::getProducts1cByTypeWithPrice();
 
+        $listProductsID = array_keys($listProductsDict);
+        $storeIds = CityStore::find()->select('id')->where(['visible' => 1])->column();
+
+        $balanceArr = (new Query())
+            ->select([
+                'b.product_id',
+                'store_id' => 'ex.entity_id',
+                'b.quantity'
+            ])
+            ->from('balances as b')
+            ->leftJoin('export_import_table ex', 'ex.export_val = b.store_id')
+            ->where(['b.product_id' => $listProductsID])
+            ->andWhere(['ex.entity_id' => $storeIds])
+            ->all();
+        $balanceDict = [];
+        foreach ($balanceArr as $row) {
+            $balanceDict[$row['product_id']][$row['store_id']]= $row['quantity'];
+        }
+
         $modelWriteOffsProductsErps = ArrayHelper::getValue($model->getRelatedRecords(), 'writeOffsProductsErps');
 
         $listCityStoreNames = CityStore::getNames($storeIds);
@@ -872,6 +913,7 @@ class WriteOffsErpController extends Controller
                     'listCityStoreNames' => $listCityStoreNames,
                     'listCauseDict' => $listCauseDict,
                     'listProductsDict' => $listProductsDict,
+                    'balanceDict' => $balanceDict,
                     'errors' => $errors
                 ]);
             }
@@ -960,6 +1002,7 @@ class WriteOffsErpController extends Controller
                     'listCityStoreNames' => $listCityStoreNames,
                     'listCauseDict' => $listCauseDict,
                     'listProductsDict' => $listProductsDict,
+                    'balanceDict' => $balanceDict,
                     'errors' => $e->getMessage()
                 ]);
             }
@@ -977,6 +1020,7 @@ class WriteOffsErpController extends Controller
             'listCityStoreNames' => $listCityStoreNames,
             'listCauseDict' => $listCauseDict,
             'listProductsDict' => $listProductsDict,
+            'balanceDict' => $balanceDict,
         ];
 
         return $this->render('/write_offs_erp/update', $params);
index 7df6bb64e87e12c74da00614d3a78bb1c7db8eff..9fbf1d8494938c304f139a27d170f2aafe3e8707 100644 (file)
@@ -303,7 +303,7 @@ class WriteOffsProductsErp extends \yii\db\ActiveRecord
      */
     public function getQuantity(): float
     {
-        return $this->quantity;
+        return (float)($this->quantity ?? 0);
     }
 
     /**
@@ -312,7 +312,7 @@ class WriteOffsProductsErp extends \yii\db\ActiveRecord
      */
     public function setQuantity(float $quantity): object
     {
-        $this->quantity = $quantity;
+        $this->quantity = $quantity === null ? 0.0 : (float)$quantity;
         return $this;
     }
 
index dba747d1e32c19304a7446db5a977ddf756f41e3..3afabcb7e0ec690ddd2bf2198e090f508f72401c 100644 (file)
@@ -7,6 +7,7 @@ use unclead\multipleinput\MultipleInput;
 use unclead\multipleinput\MultipleInputColumn;
 use yii\helpers\Html;
 use yii\helpers\Url;
+use yii\web\JsExpression;
 use yii\widgets\ActiveForm;
 
 
@@ -25,15 +26,28 @@ use yii_app\records\WriteOffsProductsErp;
 /** @var array $listCityStoreNames */
 /** @var array $listCauseDict */
 /** @var array $listProductsDict */
+/** @var array $balanceDict */
+/** @var bool $isUpdate */
 
 
 /** @var yii_app\records\WriteOffsProductsErp $modelsProducts */
 /** @var yii_app\forms\MultipleUploadForm $multipleUploadForm */
 
-
+$this->registerJs(
+    'window.balanceDict = ' . json_encode($balanceDict, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) . ';',
+    \yii\web\View::POS_HEAD
+);
 $this->registerJsFile('/js/validate/validateForm.js', ['position' => \yii\web\View::POS_END]);
 $this->registerJsFile('/js/heic2any.min.js', ['position' => \yii\web\View::POS_END]);
 $this->registerJsFile('/js/heic_to_jpg_replace.js', ['position' => \yii\web\View::POS_END]);
+$this->registerJsFile('/js/write-offs-erp/_form.js', [
+    'depends'  => [
+        \yii\web\JqueryAsset::class,
+        \kartik\select2\Select2Asset::class,
+    ],
+    'position' => \yii\web\View::POS_END,
+]);
+
 ?>
 
 <style>
@@ -116,194 +130,235 @@ $this->registerJsFile('/js/heic_to_jpg_replace.js', ['position' => \yii\web\View
     }
     ?>
     <div style="overflow-x: scroll;">
-        <?= $form->field($model, 'modelsProducts')->widget(MultipleInput::className(), [
-            'min' => 0,
-            'max' => 100,
-            'columns' => [
-                [
-                    'name' => 'id',
-                    'type' => BaseColumn::TYPE_HIDDEN_INPUT,
-                    'value' => function ($data) {
-                        return $data['id'] ?? '';
-                    },
-                    'headerOptions' => [
-                        'style' => 'width: 70px;',
-                    ]
-                ],
-                [
-                    'name' => 'num_row',
-                    'type' => BaseColumn::TYPE_HIDDEN_INPUT,
-                    'value' => function ($data) {
-                        return $data['num_row'] ?? '';
-                    },
-                    'headerOptions' => [
-                        'style' => 'width: 70px;',
-                    ]
-                ],
-                [
-                    'name' => 'product_id',
-                    'type' => Select2::classname(),
-                    'enableError' => true,
-                    'title' => 'Товар',
-                    'options' => [
-                        'data' => $listProductsDict
-                    ],
-                    'items' => $listProductsDict,
-                ],
-                [
-                    'name' => 'transfer',
-                    'type' => 'checkbox',
-                    'title' => 'Перенести',
-                    'options' => [
-                        'class' => 'transfer-checkbox',
-                    ],
-                ],
-                [
-                    'name' => 'quantity',
-                    'type' => 'textInput',
-                    'title' => 'Количество',
-                    'options' => [
-                        'type' => 'number',
-                        'class' => 'form-control',
-                        'placeholder' => 'Введите количество',
-                        'min' => 0.1,
-                        'step' => 0.1,
-                    ],
-                ],
-                [
-                    'name' => 'cause_id',
-                    'type' => 'dropDownList',
-                    'title' => 'Причина списания',
-                    'items' => $listCauseDict,
-                ],
-                [
-                    'name' => 'add_image',
-                    'type' => $checkBoxType,
-                    'title' => 'Добавить файлы',
-                    'options' => [
-                        'data' => [0, 1]
-                    ],
+      <?php
+      $columns = [
+          [
+              'name' => 'id',
+              'type' => BaseColumn::TYPE_HIDDEN_INPUT,
+              'value' => function ($data) {
+                  return $data['id'] ?? '';
+              },
+              'headerOptions' => [
+                  'style' => 'width: 70px;',
+              ]
+          ],
+          [
+              'name' => 'num_row',
+              'type' => BaseColumn::TYPE_HIDDEN_INPUT,
+              'value' => function ($data) {
+                  return $data['num_row'] ?? '';
+              },
+              'headerOptions' => [
+                  'style' => 'width: 70px;',
+              ]
+          ],
+          [
+              'name' => 'product_id',
+              'type' => Select2::class,
+              'title' => 'Товар',
+              'enableError' => true,
+              'options' => [
+                  'data' => $listProductsDict,
+                  'options' => [
+                      'placeholder' => 'Выберите товар',
+                      'class' => 'select-product',
+                  ],
+                  'pluginOptions' => [
+                      'allowClear' => true,
+                      'escapeMarkup' => new JsExpression('function (m) { return m; }'),
+
+
+                      'templateResult' => new JsExpression('function (state) {
+                if (!state.id) { return state.text || ""; }
+                var storeId = $("#writeoffserp-store_id").val();
+                var bal = 0;
+                if (window.balanceDict && window.balanceDict[state.id] && window.balanceDict[state.id][storeId] !== undefined) {
+                    bal = parseFloat(window.balanceDict[state.id][storeId]) || 0;
+                }
+                return (state.text || "") + " (" + bal + ")";
+            }'),
+                      'templateSelection' => new JsExpression('function (state) {
+                if (!state.id) { return state.text || ""; }
+                var storeId = $("#writeoffserp-store_id").val();
+                var bal = 0;
+                if (window.balanceDict && window.balanceDict[state.id] && window.balanceDict[state.id][storeId] !== undefined) {
+                    bal = parseFloat(window.balanceDict[state.id][storeId]) || 0;
+                }
+                return (state.text || "") + " (" + bal + ")";
+            }'),
+
+
+                      'matcher' => new JsExpression('function (params, data) {
+                if (!data.id) return data; 
+
+                var storeId = $("#writeoffserp-store_id").val();
+                if (!storeId) return null; 
+
+                var qty = 0;
+                if (window.balanceDict && window.balanceDict[data.id] && window.balanceDict[data.id][storeId] !== undefined) {
+                    qty = parseFloat(window.balanceDict[data.id][storeId]) || 0;
+                }
+                if (qty <= 0) {
+                    return null; 
+                }
+
+                // стандартное поведение поиска
+                var term = (params.term || "").toLowerCase();
+                if (!term) return data;
+                return (data.text || "").toLowerCase().indexOf(term) > -1 ? data : null;
+            }'),
+                  ],
+              ],
+              'items' => $listProductsDict,
+          ],
+
+
+          [
+              'name' => 'quantity',
+              'type' => 'textInput',
+              'title' => 'Количество',
+              'options' => [
+                  'type' => 'number',
+                  'class' => 'form-control',
+                  'placeholder' => 'Введите количество',
+                  'min' => 0.1,
+                  'step' => 0.1,
+              ],
+          ],
+          [
+              'name' => 'cause_id',
+              'type' => 'dropDownList',
+              'title' => 'Причина списания',
+              'items' => $listCauseDict,
+          ],
+          [
+              'name' => 'add_image',
+              'type' => $checkBoxType,
+              'title' => 'Добавить файлы',
+              'options' => [
+                  'data' => [0, 1]
+              ],
 //                'items' => [0,1],
-                ],
-                [
-                    'name' => 'images_row',
-                    'type' => BaseColumn::TYPE_STATIC,
-                    'value' => function ($data) {
-                        if (!empty($data['id'])) {
-                            $query = WriteOffsProductsErp::find()
-                                ->andWhere([
-                                    'write_offs_products_erp.id' => $data['id'],
-                                    'write_offs_products_erp.active_product' => 1,
-                                ]);
-
-
-                            $query->joinWith(['imagesWriteOffsErp']);
-
-                            $action = $query->createCommand()->getRawSql();
-
-                            $modelWriteOffsProductsErp = $query->All();
-                            $productImagesList = [];
-                            $forWidget = false;
-                            foreach ($modelWriteOffsProductsErp as $item) {
-                                $productImagesList = WriteOffsErp::getImagesList($item->imagesWriteOffsErp, $forWidget);
-                            }
-                            if (!empty($productImagesList)) {
-                                if ($forWidget) {
-                                    $dataTable = dosamigos\gallery\Gallery::widget(['items' => $productImagesList]);
-                                } else {
-                                    $dataTable = implode('', $productImagesList);
-                                }
-                            }
-                        }
-                        $test = 33;
-                        return $dataTable ?? '';
-                    },
-                    'headerOptions' => [
+          ],
+          [
+              'name' => 'images_row',
+              'type' => BaseColumn::TYPE_STATIC,
+              'value' => function ($data) {
+                  if (!empty($data['id'])) {
+                      $query = WriteOffsProductsErp::find()
+                          ->andWhere([
+                              'write_offs_products_erp.id' => $data['id'],
+                              'write_offs_products_erp.active_product' => 1,
+                          ]);
+
+
+                      $query->joinWith(['imagesWriteOffsErp']);
+
+                      $action = $query->createCommand()->getRawSql();
+
+                      $modelWriteOffsProductsErp = $query->All();
+                      $productImagesList = [];
+                      $forWidget = false;
+                      foreach ($modelWriteOffsProductsErp as $item) {
+                          $productImagesList = WriteOffsErp::getImagesList($item->imagesWriteOffsErp, $forWidget);
+                      }
+                      if (!empty($productImagesList)) {
+                          if ($forWidget) {
+                              $dataTable = dosamigos\gallery\Gallery::widget(['items' => $productImagesList]);
+                          } else {
+                              $dataTable = implode('', $productImagesList);
+                          }
+                      }
+                  }
+                  $test = 33;
+                  return $dataTable ?? '';
+              },
+              'headerOptions' => [
 //                    'style' => 'width: 70px;',
-                    ]
-                ],
-                [
-                    'name' => 'imageFiles',
-                    'title' => 'Фотографии: jpg и png',
-                    'type' => FileInput::className(),
-                    'options' => [
-                        'options' => [
-                            'multiple' => true,
-                            'accept' => 'image/*',
-                            'name' => 'image_name',
-                            'capture' => '',
-                            'class' => 'file'
-                        ],
-                        'pluginOptions' => [
-                            'showPreview' => false,
-                            'showCaption' => true,
-                            'showRemove' => true,
-                            'showUpload' => false,
-                            'overwriteInitial' => true,
-                            'browseIcon' => '+',
-                            'cancelIcon' => 'x',
-                            'removeIcon' => '-',
-                            'buttonLabelClass' => 'hidden',
-                            'fileActionSettings' => ['showUpload' => false],
-                            'maxFileCount' => 10,
-                            'multiple' => true
-                        ],
-                        'model' => $multipleUploadForm,
-                    ],
-                ],
-                [
-                    'name' => 'videoFiles',
-                    'title' => 'Видео: mp4, mov, avi',
-                    'type' => FileInput::className(),
-                    'options' => function ($data) {
-                        $videoUrl = null;
-                        $deleteUrl = '#';
-
-                        if (is_array($data) && !empty($data['id'])) {
-                            $videoUrl = Files::find()
-                                ->select('url')
-                                ->where([
-                                    'entity' => WriteOffsProductsErp::WRITE_OFFS_VIDEO,
-                                    'entity_id' => $data['id']
-                                ])
-                                ->scalar();
-
-                            $deleteUrl = Url::to(['write-offs-erp/delete-video', 'id' => $data['id']]);
-                        }
-
-                        return [
-                            'options' => [
-                                'multiple' => false,
-                                'accept' => 'video/*',
-                                'name' => 'video_name',
-                                'capture' => '',
-                                'class' => 'videos'
-                            ],
-                            'pluginOptions' => [
-                                'showPreview' => false,
-                                'showCaption' => true,
-                                'showRemove' => true,
-                                'showUpload' => false,
-                                'showCancel' => false,
-                                'overwriteInitial' => true,
-                                'browseIcon' => '+',
-                                'removeIcon' => '-',
-                                'buttonLabelClass' => 'hidden',
-                                'fileActionSettings' => ['showUpload' => false],
-                                'multiple' => false,
-                                'previewFileType' => 'video',
-                                'allowedFileExtensions' => ['mp4', 'mov', 'avi'],
-                                'initialPreview' => $videoUrl ? [$videoUrl] : [],
-                                'initialPreviewAsData' => true,
-                                'initialCaption' => $videoUrl ? basename($videoUrl) : '',
-                                'initialPreviewConfig' => $videoUrl ? [[
-                                    'type' => 'video',
-                                    'caption' => basename($videoUrl),
-                                    'url' => $deleteUrl,
-                                ]] : [],
-                            ],
-                            'pluginEvents' => [
-                                'fileclear' => new \yii\web\JsExpression("
+              ]
+          ],
+          [
+              'name' => 'imageFiles',
+              'title' => 'Фотографии: jpg и png',
+              'type' => FileInput::className(),
+              'options' => [
+                  'options' => [
+                      'multiple' => true,
+                      'accept' => 'image/*',
+                      'name' => 'image_name',
+                      'capture' => '',
+                      'class' => 'file'
+                  ],
+                  'pluginOptions' => [
+                      'showPreview' => false,
+                      'showCaption' => true,
+                      'showRemove' => true,
+                      'showUpload' => false,
+                      'overwriteInitial' => true,
+                      'browseIcon' => '+',
+                      'cancelIcon' => 'x',
+                      'removeIcon' => '-',
+                      'buttonLabelClass' => 'hidden',
+                      'fileActionSettings' => ['showUpload' => false],
+                      'maxFileCount' => 10,
+                      'multiple' => true
+                  ],
+                  'model' => $multipleUploadForm,
+              ],
+          ],
+          [
+              'name' => 'videoFiles',
+              'title' => 'Видео: mp4, mov, avi',
+              'type' => FileInput::className(),
+              'options' => function ($data) {
+                  $videoUrl = null;
+                  $deleteUrl = '#';
+
+                  if (is_array($data) && !empty($data['id'])) {
+                      $videoUrl = Files::find()
+                          ->select('url')
+                          ->where([
+                              'entity' => WriteOffsProductsErp::WRITE_OFFS_VIDEO,
+                              'entity_id' => $data['id']
+                          ])
+                          ->scalar();
+
+                      $deleteUrl = Url::to(['write-offs-erp/delete-video', 'id' => $data['id']]);
+                  }
+
+                  return [
+                      'options' => [
+                          'multiple' => false,
+                          'accept' => 'video/*',
+                          'name' => 'video_name',
+                          'capture' => '',
+                          'class' => 'videos'
+                      ],
+                      'pluginOptions' => [
+                          'showPreview' => false,
+                          'showCaption' => true,
+                          'showRemove' => true,
+                          'showUpload' => false,
+                          'showCancel' => false,
+                          'overwriteInitial' => true,
+                          'browseIcon' => '+',
+                          'removeIcon' => '-',
+                          'buttonLabelClass' => 'hidden',
+                          'fileActionSettings' => ['showUpload' => false],
+                          'multiple' => false,
+                          'previewFileType' => 'video',
+                          'allowedFileExtensions' => ['mp4', 'mov', 'avi'],
+                          'initialPreview' => $videoUrl ? [$videoUrl] : [],
+                          'initialPreviewAsData' => true,
+                          'initialCaption' => $videoUrl ? basename($videoUrl) : '',
+                          'initialPreviewConfig' => $videoUrl ? [[
+                              'type' => 'video',
+                              'caption' => basename($videoUrl),
+                              'url' => $deleteUrl,
+                          ]] : [],
+                      ],
+                      'pluginEvents' => [
+                          'fileclear' => new \yii\web\JsExpression("
                                     function(event) {
                                         var modelId = " . (isset($data['id']) ? (int)$data['id'] : 'null') . ";
                                         if (!modelId) {
@@ -322,18 +377,40 @@ $this->registerJsFile('/js/heic_to_jpg_replace.js', ['position' => \yii\web\View
                                         });
                                     }
     "),
-                            ],
-
-                        ];
-                    }
-                ],
-                [
-                    'name' => 'comment',
-                    'type' => 'textInput',
-                    'title' => 'Комментарий',
-
-                ],
-            ],
+                      ],
+
+                  ];
+              }
+          ],
+          [
+              'name' => 'comment',
+              'type' => 'textInput',
+              'title' => 'Комментарий',
+
+          ],
+      ];
+      $transferColumn = [
+          'name' => 'transfer',
+          'type' => 'checkbox',
+          'title' => 'Перенести',
+          'options' => [
+              'class' => 'transfer-checkbox',
+          ]
+      ];
+
+      if ($isUpdate) {
+          $columns = array_merge(
+              array_slice($columns, 0, 3),
+              [$transferColumn],
+              array_slice($columns, 3)
+          );
+      }
+
+      ?>
+        <?= $form->field($model, 'modelsProducts')->widget(MultipleInput::className(), [
+            'min' => 0,
+            'max' => 100,
+            'columns' => $columns,
             'addButtonPosition' => MultipleInput::POS_FOOTER, // show add button in the header
         ])->label(false); ?>
     </div>
@@ -355,10 +432,12 @@ $this->registerJsFile('/js/heic_to_jpg_replace.js', ['position' => \yii\web\View
 
     <?php ActiveForm::end(); ?>
     <div class="form-group">
+        <?php $classTransferButton = $isUpdate ? 'btn btn-warning ' : ' btn btn-warning d-none'; ?>
         <?= Html::button('Перенести выделенные', [
-            'class' => 'btn btn-warning',
+            'class' => $classTransferButton,
             'id' => 'btn-transfer',
             'type'  => 'button',
+
             'title' => 'Создать новый документ и переместить в него отмеченные позиции',
         ]) ?>
     </div>
index b9a3d50d8e930cbd2cae3047a13b6e7a1e636f89..0c3b586d08bab99b76fce29266a4258aba326ca0 100644 (file)
@@ -9,6 +9,7 @@ use yii\helpers\Html;
 /** @var array $listCityStoreNames */
 /** @var array $listCauseDict */
 /** @var array $listProductsDict */
+/** @var array $balanceDict */
 
 $this->title = 'Создание документа списания в ERP';
 $this->params['breadcrumbs'][] = ['label' => 'Write Offs Erps', 'url' => ['index']];
@@ -33,6 +34,8 @@ $this->params['breadcrumbs'][] = $this->title;
         'listCityStoreNames' => $listCityStoreNames,
         'listCauseDict' => $listCauseDict,
         'listProductsDict' => $listProductsDict,
+        'balanceDict' => $balanceDict,
+        'isUpdate' => false,
     ]) ?>
 
 
index 82bd4e50d4b743c2a51c5256f50ef8de3246f308..e2b4e396d348c4e033bccfbea5514b215e2e9599 100644 (file)
@@ -10,6 +10,7 @@ use yii\helpers\Url;
 /** @var array $listCityStoreNames */
 /** @var array $listCauseDict */
 /** @var array $listProductsDict */
+/** @var array $balanceDict */
 
 $this->title = 'Изменение документа списания номер ' . $model->number . ' от '. $model->date;
 $this->params['breadcrumbs'][] = ['label' => 'Write Offs Erps', 'url' => ['index']];
@@ -55,6 +56,8 @@ $this->registerJsFile('/js/write-offs-erp/update.js', ['position' => \yii\web\Vi
         'listCityStoreNames' => $listCityStoreNames,
         'listCauseDict' => $listCauseDict,
         'listProductsDict' => $listProductsDict,
+        'balanceDict' => $balanceDict,
+        'isUpdate' => true,
     ]) ?>
 
 </div>
diff --git a/erp24/web/js/write-offs-erp/_form.js b/erp24/web/js/write-offs-erp/_form.js
new file mode 100644 (file)
index 0000000..3ee7431
--- /dev/null
@@ -0,0 +1,40 @@
+(function ($) {
+    'use strict';
+
+    function getBalance(productId, storeId) {
+        if (!window.balanceDict || !productId || !storeId) return 0;
+        var map = window.balanceDict[productId];
+        if (!map) return 0;
+        var v = map[storeId];
+        var n = parseFloat(v);
+        return isNaN(n) ? 0 : n;
+    }
+
+    function setQtyForRow($sel) {
+        var productId = $sel.val();
+        var storeId = $('#writeoffserp-store_id').val();
+        var bal = getBalance(productId, storeId);
+
+        var $row = $sel.closest('.multiple-input-list__item');
+        if (!$row.length) $row = $sel.closest('tr');
+
+        $row.find('input[name$="[quantity]"]').val(bal || 0).trigger('change');
+    }
+
+    $(document).on(
+        'select2:select',
+        'select[name^="WriteOffsErp[modelsProducts]"][name$="[product_id]"]',
+        function () { setQtyForRow($(this)); }
+    );
+
+    // Смена магазина -> обновим подписи и количества
+    $(document).on('change', '#writeoffserp-store_id', function () {
+        $('select[name^="WriteOffsErp[modelsProducts]"][name$="[product_id]"]').each(function () {
+            var $sel = $(this);
+            $sel.trigger('change.select2');
+            // обновить qty под текущий магазин
+            if ($sel.val()) setQtyForRow($sel);
+        });
+    });
+
+})(jQuery);
\ No newline at end of file