Ver Fonte

refactor(query): replace withoutGlobalScopes with specific scope bypass

Replace all instances of `withoutGlobalScopes()` with `withoutGlobalScope(\\App\\Models\\Scopes\\YearScope::class)` to explicitly bypass only the YearScope. This improves code clarity and prevents unintended side effects from disabling all global scopes.

Additionally, fix export filter handling in ProductSKUController to properly validate and pass search parameters.
Alexander Musikhin há 1 mês atrás
pai
commit
b9f18d8fa0

+ 15 - 15
app/Console/Commands/ClearYearData.php

@@ -65,10 +65,10 @@ class ClearYearData extends Command
 
 
     private function collectStats(int $year): array
     private function collectStats(int $year): array
     {
     {
-        $orderIds = Order::withoutGlobalScopes()->withTrashed()->where('year', $year)->pluck('id');
-        $productIds = Product::withoutGlobalScopes()->withTrashed()->where('year', $year)->pluck('id');
-        $mafOrderIds = MafOrder::withoutGlobalScopes()->withTrashed()->where('year', $year)->pluck('id');
-        $productSkuIds = ProductSKU::withoutGlobalScopes()->withTrashed()->where('year', $year)->pluck('id');
+        $orderIds = Order::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()->where('year', $year)->pluck('id');
+        $productIds = Product::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()->where('year', $year)->pluck('id');
+        $mafOrderIds = MafOrder::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()->where('year', $year)->pluck('id');
+        $productSkuIds = ProductSKU::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()->where('year', $year)->pluck('id');
 
 
         $reclamationCount = Reclamation::whereIn('order_id', $orderIds)->count();
         $reclamationCount = Reclamation::whereIn('order_id', $orderIds)->count();
 
 
@@ -121,7 +121,7 @@ class ClearYearData extends Command
 
 
         // Сертификаты продуктов
         // Сертификаты продуктов
         $fileIds = $fileIds->merge(
         $fileIds = $fileIds->merge(
-            Product::withoutGlobalScopes()->withTrashed()
+            Product::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()
                 ->whereIn('id', $productIds)
                 ->whereIn('id', $productIds)
                 ->whereNotNull('certificate_id')
                 ->whereNotNull('certificate_id')
                 ->pluck('certificate_id')
                 ->pluck('certificate_id')
@@ -129,7 +129,7 @@ class ClearYearData extends Command
 
 
         // Паспорта SKU
         // Паспорта SKU
         $fileIds = $fileIds->merge(
         $fileIds = $fileIds->merge(
-            ProductSKU::withoutGlobalScopes()->withTrashed()
+            ProductSKU::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()
                 ->whereIn('id', $productSkuIds)
                 ->whereIn('id', $productSkuIds)
                 ->whereNotNull('passport_id')
                 ->whereNotNull('passport_id')
                 ->pluck('passport_id')
                 ->pluck('passport_id')
@@ -145,10 +145,10 @@ class ClearYearData extends Command
 
 
     private function clearData(int $year): void
     private function clearData(int $year): void
     {
     {
-        $orderIds = Order::withoutGlobalScopes()->withTrashed()->where('year', $year)->pluck('id');
-        $productIds = Product::withoutGlobalScopes()->withTrashed()->where('year', $year)->pluck('id');
-        $mafOrderIds = MafOrder::withoutGlobalScopes()->withTrashed()->where('year', $year)->pluck('id');
-        $productSkuIds = ProductSKU::withoutGlobalScopes()->withTrashed()->where('year', $year)->pluck('id');
+        $orderIds = Order::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()->where('year', $year)->pluck('id');
+        $productIds = Product::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()->where('year', $year)->pluck('id');
+        $mafOrderIds = MafOrder::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()->where('year', $year)->pluck('id');
+        $productSkuIds = ProductSKU::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()->where('year', $year)->pluck('id');
         $reclamationIds = Reclamation::whereIn('order_id', $orderIds)->pluck('id');
         $reclamationIds = Reclamation::whereIn('order_id', $orderIds)->pluck('id');
 
 
         // Собираем файлы до удаления связей
         // Собираем файлы до удаления связей
@@ -173,20 +173,20 @@ class ClearYearData extends Command
         Schedule::whereIn('order_id', $orderIds)->delete();
         Schedule::whereIn('order_id', $orderIds)->delete();
 
 
         $this->info('Удаление SKU продуктов...');
         $this->info('Удаление SKU продуктов...');
-        ProductSKU::withoutGlobalScopes()->withTrashed()->where('year', $year)->forceDelete();
+        ProductSKU::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()->where('year', $year)->forceDelete();
 
 
         $this->info('Удаление заказов...');
         $this->info('Удаление заказов...');
-        Order::withoutGlobalScopes()->withTrashed()->where('year', $year)->forceDelete();
+        Order::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()->where('year', $year)->forceDelete();
 
 
         $this->info('Удаление заказов МАФ...');
         $this->info('Удаление заказов МАФ...');
-        MafOrder::withoutGlobalScopes()->withTrashed()->where('year', $year)->forceDelete();
+        MafOrder::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()->where('year', $year)->forceDelete();
 
 
         $this->info('Удаление продуктов...');
         $this->info('Удаление продуктов...');
         // Сначала обнуляем certificate_id чтобы избежать проблем с FK
         // Сначала обнуляем certificate_id чтобы избежать проблем с FK
-        Product::withoutGlobalScopes()->withTrashed()
+        Product::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()
             ->whereIn('id', $productIds)
             ->whereIn('id', $productIds)
             ->update(['certificate_id' => null]);
             ->update(['certificate_id' => null]);
-        Product::withoutGlobalScopes()->withTrashed()->where('year', $year)->forceDelete();
+        Product::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()->where('year', $year)->forceDelete();
 
 
         $this->info('Удаление ТТН...');
         $this->info('Удаление ТТН...');
         // Обнуляем file_id перед удалением
         // Обнуляем file_id перед удалением

+ 9 - 9
app/Http/Controllers/ClearDataController.php

@@ -60,17 +60,17 @@ class ClearDataController extends Controller
     {
     {
         $years = [];
         $years = [];
 
 
-        $orderYears = Order::withoutGlobalScopes()->withTrashed()
+        $orderYears = Order::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()
             ->selectRaw('DISTINCT year')
             ->selectRaw('DISTINCT year')
             ->pluck('year')
             ->pluck('year')
             ->toArray();
             ->toArray();
 
 
-        $productYears = Product::withoutGlobalScopes()->withTrashed()
+        $productYears = Product::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()
             ->selectRaw('DISTINCT year')
             ->selectRaw('DISTINCT year')
             ->pluck('year')
             ->pluck('year')
             ->toArray();
             ->toArray();
 
 
-        $mafOrderYears = MafOrder::withoutGlobalScopes()->withTrashed()
+        $mafOrderYears = MafOrder::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()
             ->selectRaw('DISTINCT year')
             ->selectRaw('DISTINCT year')
             ->pluck('year')
             ->pluck('year')
             ->toArray();
             ->toArray();
@@ -91,10 +91,10 @@ class ClearDataController extends Controller
 
 
     private function collectStats(int $year): array
     private function collectStats(int $year): array
     {
     {
-        $orderIds = Order::withoutGlobalScopes()->withTrashed()->where('year', $year)->pluck('id');
-        $productIds = Product::withoutGlobalScopes()->withTrashed()->where('year', $year)->pluck('id');
-        $mafOrderIds = MafOrder::withoutGlobalScopes()->withTrashed()->where('year', $year)->pluck('id');
-        $productSkuIds = ProductSKU::withoutGlobalScopes()->withTrashed()->where('year', $year)->pluck('id');
+        $orderIds = Order::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()->where('year', $year)->pluck('id');
+        $productIds = Product::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()->where('year', $year)->pluck('id');
+        $mafOrderIds = MafOrder::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()->where('year', $year)->pluck('id');
+        $productSkuIds = ProductSKU::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()->where('year', $year)->pluck('id');
 
 
         $reclamationCount = Reclamation::whereIn('order_id', $orderIds)->count();
         $reclamationCount = Reclamation::whereIn('order_id', $orderIds)->count();
         $fileIds = $this->collectFileIds($year, $orderIds, $productIds, $productSkuIds);
         $fileIds = $this->collectFileIds($year, $orderIds, $productIds, $productSkuIds);
@@ -142,14 +142,14 @@ class ClearDataController extends Controller
         );
         );
 
 
         $fileIds = $fileIds->merge(
         $fileIds = $fileIds->merge(
-            Product::withoutGlobalScopes()->withTrashed()
+            Product::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()
                 ->whereIn('id', $productIds)
                 ->whereIn('id', $productIds)
                 ->whereNotNull('certificate_id')
                 ->whereNotNull('certificate_id')
                 ->pluck('certificate_id')
                 ->pluck('certificate_id')
         );
         );
 
 
         $fileIds = $fileIds->merge(
         $fileIds = $fileIds->merge(
-            ProductSKU::withoutGlobalScopes()->withTrashed()
+            ProductSKU::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()
                 ->whereIn('id', $productSkuIds)
                 ->whereIn('id', $productSkuIds)
                 ->whereNotNull('passport_id')
                 ->whereNotNull('passport_id')
                 ->pluck('passport_id')
                 ->pluck('passport_id')

+ 1 - 1
app/Http/Controllers/ImportController.php

@@ -40,7 +40,7 @@ class ImportController extends Controller
         $this->createDateFilters($model, 'created_at', 'updated_at');
         $this->createDateFilters($model, 'created_at', 'updated_at');
 
 
         $q = $model::query();
         $q = $model::query();
-        $q->withoutGlobalScopes();
+        $q->withoutGlobalScope(\App\Models\Scopes\YearScope::class);
 
 
         $this->acceptFilters($q, $request);
         $this->acceptFilters($q, $request);
         $this->acceptSearch($q, $request);
         $this->acceptSearch($q, $request);

+ 1 - 1
app/Http/Controllers/MafOrderController.php

@@ -61,7 +61,7 @@ class MafOrderController extends Controller
 
 
     public function show(Request $request, int $maf_order)
     public function show(Request $request, int $maf_order)
     {
     {
-        $this->data['maf_order'] = MafOrder::query()->withoutGlobalScopes()->find($maf_order);
+        $this->data['maf_order'] = MafOrder::query()->withoutGlobalScope(\App\Models\Scopes\YearScope::class)->find($maf_order);
         $this->data['previous_url'] = $this->resolvePreviousUrl(
         $this->data['previous_url'] = $this->resolvePreviousUrl(
             $request,
             $request,
             'previous_url_maf_order',
             'previous_url_maf_order',

+ 1 - 1
app/Http/Controllers/OrderController.php

@@ -255,7 +255,7 @@ class OrderController extends Controller
      */
      */
     public function show(Request $request, int $order)
     public function show(Request $request, int $order)
     {
     {
-        $this->data['order'] = Order::query()->withoutGlobalScopes()->find($order);
+        $this->data['order'] = Order::query()->withoutGlobalScope(\App\Models\Scopes\YearScope::class)->find($order);
 
 
         if ($request->boolean('sync_year') && $this->data['order']) {
         if ($request->boolean('sync_year') && $this->data['order']) {
             $previousYear = year();
             $previousYear = year();

+ 1 - 1
app/Http/Controllers/ProductController.php

@@ -86,7 +86,7 @@ class ProductController extends Controller
             'previous_url_products',
             'previous_url_products',
             route('catalog.index', session('gp_products'))
             route('catalog.index', session('gp_products'))
         );
         );
-        $this->data['product'] = Product::query()->withoutGlobalScopes()->find($product);
+        $this->data['product'] = Product::query()->withoutGlobalScope(\App\Models\Scopes\YearScope::class)->find($product);
         return view('catalog.edit', $this->data);
         return view('catalog.edit', $this->data);
     }
     }
 
 

+ 16 - 2
app/Http/Controllers/ProductSKUController.php

@@ -92,7 +92,7 @@ class ProductSKUController extends Controller
 
 
     public function show(Request $request, int $product_sku)
     public function show(Request $request, int $product_sku)
     {
     {
-        $this->data['product_sku'] = ProductSKU::query()->withoutGlobalScopes()->find($product_sku);
+        $this->data['product_sku'] = ProductSKU::query()->withoutGlobalScope(\App\Models\Scopes\YearScope::class)->find($product_sku);
         $this->data['previous_url'] = $this->resolvePreviousUrl(
         $this->data['previous_url'] = $this->resolvePreviousUrl(
             $request,
             $request,
             'previous_url_product_sku',
             'previous_url_product_sku',
@@ -145,7 +145,21 @@ class ProductSKUController extends Controller
 
 
     public function exportMaf(Request $request)
     public function exportMaf(Request $request)
     {
     {
-        $filters['year'] = year();
+        $request->validate([
+            'withFilter' => 'nullable',
+            'filters' => 'nullable|array',
+            's' => 'nullable|string',
+        ]);
+
+        $filters = [];
+        if ($request->boolean('withFilter')) {
+            $filters = $request->filters ?? [];
+            if ($request->filled('s')) {
+                $filters['s'] = $request->string('s')->toString();
+            }
+        }
+
+        $filters['year'] = (int) $request->session()->get('year', date('Y'));
         ExportMafJob::dispatch($request->user()->id, $filters);
         ExportMafJob::dispatch($request->user()->id, $filters);
         return redirect()->route('product_sku.index', session('gp_product_sku'))->with(['success' => 'Задача экспорта успешно создана!']);
         return redirect()->route('product_sku.index', session('gp_product_sku'))->with(['success' => 'Задача экспорта успешно создана!']);
     }
     }

+ 2 - 2
app/Http/Controllers/ScheduleController.php

@@ -374,7 +374,7 @@ class ScheduleController extends Controller
 
 
         if ($orderIds) {
         if ($orderIds) {
             $orderStatuses = Order::query()
             $orderStatuses = Order::query()
-                ->withoutGlobalScopes()
+                ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
                 ->whereIn('id', array_unique($orderIds))
                 ->whereIn('id', array_unique($orderIds))
                 ->pluck('order_status_id', 'id')
                 ->pluck('order_status_id', 'id')
                 ->all();
                 ->all();
@@ -396,7 +396,7 @@ class ScheduleController extends Controller
 
 
         if ($reclamationScheduleIds) {
         if ($reclamationScheduleIds) {
             $reclamationStatuses = Reclamation::query()
             $reclamationStatuses = Reclamation::query()
-                ->withoutGlobalScopes()
+                ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
                 ->whereIn('id', array_keys($reclamationScheduleIds))
                 ->whereIn('id', array_keys($reclamationScheduleIds))
                 ->pluck('status_id', 'id')
                 ->pluck('status_id', 'id')
                 ->all();
                 ->all();

+ 9 - 9
app/Http/Controllers/YearDataController.php

@@ -104,17 +104,17 @@ class YearDataController extends Controller
     {
     {
         $years = [];
         $years = [];
 
 
-        $orderYears = Order::withoutGlobalScopes()->withTrashed()
+        $orderYears = Order::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()
             ->selectRaw('DISTINCT year')
             ->selectRaw('DISTINCT year')
             ->pluck('year')
             ->pluck('year')
             ->toArray();
             ->toArray();
 
 
-        $productYears = Product::withoutGlobalScopes()->withTrashed()
+        $productYears = Product::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()
             ->selectRaw('DISTINCT year')
             ->selectRaw('DISTINCT year')
             ->pluck('year')
             ->pluck('year')
             ->toArray();
             ->toArray();
 
 
-        $mafOrderYears = MafOrder::withoutGlobalScopes()->withTrashed()
+        $mafOrderYears = MafOrder::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()
             ->selectRaw('DISTINCT year')
             ->selectRaw('DISTINCT year')
             ->pluck('year')
             ->pluck('year')
             ->toArray();
             ->toArray();
@@ -144,10 +144,10 @@ class YearDataController extends Controller
 
 
     private function collectStats(int $year): array
     private function collectStats(int $year): array
     {
     {
-        $orderIds = Order::withoutGlobalScopes()->withTrashed()->where('year', $year)->pluck('id');
-        $productIds = Product::withoutGlobalScopes()->withTrashed()->where('year', $year)->pluck('id');
-        $mafOrderIds = MafOrder::withoutGlobalScopes()->withTrashed()->where('year', $year)->pluck('id');
-        $productSkuIds = ProductSKU::withoutGlobalScopes()->withTrashed()->where('year', $year)->pluck('id');
+        $orderIds = Order::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()->where('year', $year)->pluck('id');
+        $productIds = Product::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()->where('year', $year)->pluck('id');
+        $mafOrderIds = MafOrder::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()->where('year', $year)->pluck('id');
+        $productSkuIds = ProductSKU::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()->where('year', $year)->pluck('id');
 
 
         $reclamationCount = Reclamation::whereIn('order_id', $orderIds)->count();
         $reclamationCount = Reclamation::whereIn('order_id', $orderIds)->count();
         $fileIds = $this->collectFileIds($year, $orderIds, $productIds, $productSkuIds);
         $fileIds = $this->collectFileIds($year, $orderIds, $productIds, $productSkuIds);
@@ -195,14 +195,14 @@ class YearDataController extends Controller
         );
         );
 
 
         $fileIds = $fileIds->merge(
         $fileIds = $fileIds->merge(
-            Product::withoutGlobalScopes()->withTrashed()
+            Product::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()
                 ->whereIn('id', $productIds)
                 ->whereIn('id', $productIds)
                 ->whereNotNull('certificate_id')
                 ->whereNotNull('certificate_id')
                 ->pluck('certificate_id')
                 ->pluck('certificate_id')
         );
         );
 
 
         $fileIds = $fileIds->merge(
         $fileIds = $fileIds->merge(
-            ProductSKU::withoutGlobalScopes()->withTrashed()
+            ProductSKU::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()
                 ->whereIn('id', $productSkuIds)
                 ->whereIn('id', $productSkuIds)
                 ->whereNotNull('passport_id')
                 ->whereNotNull('passport_id')
                 ->pluck('passport_id')
                 ->pluck('passport_id')

+ 10 - 10
app/Jobs/ClearYearDataJob.php

@@ -59,9 +59,9 @@ class ClearYearDataJob implements ShouldQueue
 
 
     private function clearData(): void
     private function clearData(): void
     {
     {
-        $orderIds = Order::withoutGlobalScopes()->withTrashed()->where('year', $this->year)->pluck('id');
-        $productIds = Product::withoutGlobalScopes()->withTrashed()->where('year', $this->year)->pluck('id');
-        $productSkuIds = ProductSKU::withoutGlobalScopes()->withTrashed()->where('year', $this->year)->pluck('id');
+        $orderIds = Order::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()->where('year', $this->year)->pluck('id');
+        $productIds = Product::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()->where('year', $this->year)->pluck('id');
+        $productSkuIds = ProductSKU::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()->where('year', $this->year)->pluck('id');
         $reclamationIds = Reclamation::whereIn('order_id', $orderIds)->pluck('id');
         $reclamationIds = Reclamation::whereIn('order_id', $orderIds)->pluck('id');
 
 
         $fileIds = $this->collectFileIds($orderIds, $productIds, $productSkuIds);
         $fileIds = $this->collectFileIds($orderIds, $productIds, $productSkuIds);
@@ -84,19 +84,19 @@ class ClearYearDataJob implements ShouldQueue
         Schedule::whereIn('order_id', $orderIds)->delete();
         Schedule::whereIn('order_id', $orderIds)->delete();
 
 
         // SKU продуктов
         // SKU продуктов
-        ProductSKU::withoutGlobalScopes()->withTrashed()->where('year', $this->year)->forceDelete();
+        ProductSKU::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()->where('year', $this->year)->forceDelete();
 
 
         // Заказы
         // Заказы
-        Order::withoutGlobalScopes()->withTrashed()->where('year', $this->year)->forceDelete();
+        Order::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()->where('year', $this->year)->forceDelete();
 
 
         // Заказы МАФ
         // Заказы МАФ
-        MafOrder::withoutGlobalScopes()->withTrashed()->where('year', $this->year)->forceDelete();
+        MafOrder::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()->where('year', $this->year)->forceDelete();
 
 
         // Продукты
         // Продукты
-        Product::withoutGlobalScopes()->withTrashed()
+        Product::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()
             ->whereIn('id', $productIds)
             ->whereIn('id', $productIds)
             ->update(['certificate_id' => null]);
             ->update(['certificate_id' => null]);
-        Product::withoutGlobalScopes()->withTrashed()->where('year', $this->year)->forceDelete();
+        Product::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()->where('year', $this->year)->forceDelete();
 
 
         // ТТН
         // ТТН
         Ttn::where('year', $this->year)->update(['file_id' => null]);
         Ttn::where('year', $this->year)->update(['file_id' => null]);
@@ -139,14 +139,14 @@ class ClearYearDataJob implements ShouldQueue
         );
         );
 
 
         $fileIds = $fileIds->merge(
         $fileIds = $fileIds->merge(
-            Product::withoutGlobalScopes()->withTrashed()
+            Product::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()
                 ->whereIn('id', $productIds)
                 ->whereIn('id', $productIds)
                 ->whereNotNull('certificate_id')
                 ->whereNotNull('certificate_id')
                 ->pluck('certificate_id')
                 ->pluck('certificate_id')
         );
         );
 
 
         $fileIds = $fileIds->merge(
         $fileIds = $fileIds->merge(
-            ProductSKU::withoutGlobalScopes()->withTrashed()
+            ProductSKU::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()
                 ->whereIn('id', $productSkuIds)
                 ->whereIn('id', $productSkuIds)
                 ->whereNotNull('passport_id')
                 ->whereNotNull('passport_id')
                 ->pluck('passport_id')
                 ->pluck('passport_id')

+ 1 - 1
app/Jobs/ExportMafJob.php

@@ -29,7 +29,7 @@ class ExportMafJob implements ShouldQueue
     public function handle(): void
     public function handle(): void
     {
     {
         try {
         try {
-            $file = (new ExportMafService())->handle($this->userId, $this->filters['year'] ?? null);
+            $file = (new ExportMafService())->handle($this->userId, $this->filters);
             Log::info('ExportMaf job done!');
             Log::info('ExportMaf job done!');
             Log::info($file);
             Log::info($file);
             event(new SendWebSocketMessageEvent('Экспорт завершён!', $this->userId, ['download' => $file]));
             event(new SendWebSocketMessageEvent('Экспорт завершён!', $this->userId, ['download' => $file]));

+ 1 - 1
app/Jobs/NotifyOrderInScheduleJob.php

@@ -34,7 +34,7 @@ class NotifyOrderInScheduleJob implements ShouldQueue
         }
         }
 
 
         if(!is_null($this->schedule->order_id)) {
         if(!is_null($this->schedule->order_id)) {
-            $order = Order::query()->withoutGlobalScopes()->where('id', $this->schedule->order_id)->first();
+            $order = Order::query()->withoutGlobalScope(\App\Models\Scopes\YearScope::class)->where('id', $this->schedule->order_id)->first();
             if(!is_null($order?->user?->token_fcm)) {
             if(!is_null($order?->user?->token_fcm)) {
                 $order->user->notify(new FireBaseNotification($title, $body));
                 $order->user->notify(new FireBaseNotification($title, $body));
             }
             }

+ 2 - 2
app/Models/MafOrder.php

@@ -43,12 +43,12 @@ class MafOrder extends Model
 
 
     public function product(): BelongsTo
     public function product(): BelongsTo
     {
     {
-        return $this->belongsTo(Product::class)->withoutGlobalScopes();
+        return $this->belongsTo(Product::class)->withoutGlobalScope(\App\Models\Scopes\YearScope::class);
     }
     }
 
 
     public function products_sku(): HasMany
     public function products_sku(): HasMany
     {
     {
-        return $this->hasMany(ProductSKU::class)->withoutGlobalScopes();
+        return $this->hasMany(ProductSKU::class)->withoutGlobalScope(\App\Models\Scopes\YearScope::class);
     }
     }
 
 
 }
 }

+ 1 - 1
app/Models/MafView.php

@@ -46,6 +46,6 @@ class MafView extends Model
      */
      */
     public function product(): BelongsTo
     public function product(): BelongsTo
     {
     {
-        return $this->belongsTo(Product::class, 'product_id', 'id')->withoutGlobalScopes();
+        return $this->belongsTo(Product::class, 'product_id', 'id')->withoutGlobalScope(\App\Models\Scopes\YearScope::class);
     }
     }
 }
 }

+ 3 - 3
app/Models/ProductSKU.php

@@ -48,7 +48,7 @@ class ProductSKU extends Model
      */
      */
     public function product(): BelongsTo
     public function product(): BelongsTo
     {
     {
-        return $this->belongsTo(Product::class, 'product_id', 'id')->withoutGlobalScopes();
+        return $this->belongsTo(Product::class, 'product_id', 'id')->withoutGlobalScope(\App\Models\Scopes\YearScope::class);
     }
     }
 
 
     /**
     /**
@@ -56,7 +56,7 @@ class ProductSKU extends Model
      */
      */
     public function order(): BelongsTo
     public function order(): BelongsTo
     {
     {
-        return $this->belongsTo(Order::class, 'order_id', 'id')->withoutGlobalScopes();
+        return $this->belongsTo(Order::class, 'order_id', 'id')->withoutGlobalScope(\App\Models\Scopes\YearScope::class);
     }
     }
 
 
     /**
     /**
@@ -72,6 +72,6 @@ class ProductSKU extends Model
      */
      */
     public function maf_order(): BelongsTo
     public function maf_order(): BelongsTo
     {
     {
-        return $this->belongsTo(MafOrder::class, 'maf_order_id', 'id')->withoutGlobalScopes();
+        return $this->belongsTo(MafOrder::class, 'maf_order_id', 'id')->withoutGlobalScope(\App\Models\Scopes\YearScope::class);
     }
     }
 }
 }

+ 2 - 2
app/Models/Reclamation.php

@@ -57,7 +57,7 @@ class Reclamation extends Model
 
 
     public function order(): BelongsTo
     public function order(): BelongsTo
     {
     {
-        return $this->belongsTo(Order::class)->withoutGlobalScopes();
+        return $this->belongsTo(Order::class)->withoutGlobalScope(\App\Models\Scopes\YearScope::class);
     }
     }
 
 
     public function status(): BelongsTo
     public function status(): BelongsTo
@@ -72,7 +72,7 @@ class Reclamation extends Model
             'reclamation_product_sku',
             'reclamation_product_sku',
             'reclamation_id',
             'reclamation_id',
             'product_sku_id')
             'product_sku_id')
-            ->withoutGlobalScopes();
+            ->withoutGlobalScope(\App\Models\Scopes\YearScope::class);
     }
     }
 
 
     public function user(): BelongsTo
     public function user(): BelongsTo

+ 7 - 7
app/Services/Export/ExportYearDataService.php

@@ -97,7 +97,7 @@ class ExportYearDataService
 
 
     private function exportProducts(): void
     private function exportProducts(): void
     {
     {
-        $products = Product::withoutGlobalScopes()
+        $products = Product::withoutGlobalScope(\App\Models\Scopes\YearScope::class)
             ->withTrashed()
             ->withTrashed()
             ->where('year', $this->year)
             ->where('year', $this->year)
             ->with('certificate')
             ->with('certificate')
@@ -169,7 +169,7 @@ class ExportYearDataService
 
 
     private function exportMafOrders(): void
     private function exportMafOrders(): void
     {
     {
-        $mafOrders = MafOrder::withoutGlobalScopes()
+        $mafOrders = MafOrder::withoutGlobalScope(\App\Models\Scopes\YearScope::class)
             ->withTrashed()
             ->withTrashed()
             ->where('year', $this->year)
             ->where('year', $this->year)
             ->with(['user', 'product'])
             ->with(['user', 'product'])
@@ -215,7 +215,7 @@ class ExportYearDataService
 
 
     private function exportOrders(): void
     private function exportOrders(): void
     {
     {
-        $orders = Order::withoutGlobalScopes()
+        $orders = Order::withoutGlobalScope(\App\Models\Scopes\YearScope::class)
             ->withTrashed()
             ->withTrashed()
             ->where('year', $this->year)
             ->where('year', $this->year)
             ->with(['user', 'district', 'area', 'objectType', 'brigadier', 'orderStatus'])
             ->with(['user', 'district', 'area', 'objectType', 'brigadier', 'orderStatus'])
@@ -277,7 +277,7 @@ class ExportYearDataService
 
 
     private function exportProductsSku(): void
     private function exportProductsSku(): void
     {
     {
-        $skus = ProductSKU::withoutGlobalScopes()
+        $skus = ProductSKU::withoutGlobalScope(\App\Models\Scopes\YearScope::class)
             ->withTrashed()
             ->withTrashed()
             ->where('year', $this->year)
             ->where('year', $this->year)
             ->with(['product', 'order', 'maf_order', 'passport'])
             ->with(['product', 'order', 'maf_order', 'passport'])
@@ -337,7 +337,7 @@ class ExportYearDataService
 
 
     private function exportReclamations(): void
     private function exportReclamations(): void
     {
     {
-        $orderIds = Order::withoutGlobalScopes()
+        $orderIds = Order::withoutGlobalScope(\App\Models\Scopes\YearScope::class)
             ->withTrashed()
             ->withTrashed()
             ->where('year', $this->year)
             ->where('year', $this->year)
             ->pluck('id');
             ->pluck('id');
@@ -440,7 +440,7 @@ class ExportYearDataService
 
 
     private function exportSchedules(): void
     private function exportSchedules(): void
     {
     {
-        $orderIds = Order::withoutGlobalScopes()
+        $orderIds = Order::withoutGlobalScope(\App\Models\Scopes\YearScope::class)
             ->withTrashed()
             ->withTrashed()
             ->where('year', $this->year)
             ->where('year', $this->year)
             ->pluck('id');
             ->pluck('id');
@@ -566,7 +566,7 @@ class ExportYearDataService
 
 
     private function copyFilesAndExportPivots(): void
     private function copyFilesAndExportPivots(): void
     {
     {
-        $orderIds = Order::withoutGlobalScopes()
+        $orderIds = Order::withoutGlobalScope(\App\Models\Scopes\YearScope::class)
             ->withTrashed()
             ->withTrashed()
             ->where('year', $this->year)
             ->where('year', $this->year)
             ->pluck('id');
             ->pluck('id');

+ 77 - 6
app/Services/ExportMafService.php

@@ -5,7 +5,10 @@ namespace App\Services;
 use App\Helpers\DateHelper;
 use App\Helpers\DateHelper;
 use App\Models\File;
 use App\Models\File;
 use App\Models\MafView;
 use App\Models\MafView;
+use App\Models\Scopes\YearScope;
+use Illuminate\Database\Eloquent\Builder;
 use Illuminate\Support\Facades\Storage;
 use Illuminate\Support\Facades\Storage;
+use Illuminate\Support\Str;
 use PhpOffice\PhpSpreadsheet\IOFactory;
 use PhpOffice\PhpSpreadsheet\IOFactory;
 use PhpOffice\PhpSpreadsheet\Style\Border;
 use PhpOffice\PhpSpreadsheet\Style\Border;
 use PhpOffice\PhpSpreadsheet\Style\Color;
 use PhpOffice\PhpSpreadsheet\Style\Color;
@@ -15,7 +18,7 @@ use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
 
 
 class ExportMafService
 class ExportMafService
 {
 {
-    public function handle(int $userId, ?int $year = null): string
+    public function handle(int $userId, array $filters = []): string
     {
     {
 
 
         $inputFileType = 'Xlsx'; // Xlsx - Xml - Ods - Slk - Gnumeric - Csv
         $inputFileType = 'Xlsx'; // Xlsx - Xml - Ods - Slk - Gnumeric - Csv
@@ -26,12 +29,13 @@ class ExportMafService
         $sheet = $spreadsheet->getActiveSheet();
         $sheet = $spreadsheet->getActiveSheet();
         $sheet->getPageSetup()->setOrientation(PageSetup::ORIENTATION_LANDSCAPE);
         $sheet->getPageSetup()->setOrientation(PageSetup::ORIENTATION_LANDSCAPE);
 
 
+        $year = (int) ($filters['year'] ?? date('Y'));
+        $query = MafView::query()
+            ->withoutGlobalScope(YearScope::class)
+            ->where('year', $year);
 
 
-        $targetYear = $year ?? year();
-        $mafs = MafView::query()
-            ->withoutGlobalScopes()
-            ->where('year', $targetYear)
-            ->get();
+        $this->applyFilters($query, $filters);
+        $mafs = $query->get();
         $i = 2;
         $i = 2;
         foreach ($mafs as $maf) {
         foreach ($mafs as $maf) {
             $sheet->setCellValue('A' . $i, $maf->id);
             $sheet->setCellValue('A' . $i, $maf->id);
@@ -86,4 +90,71 @@ class ExportMafService
         return $fileName;
         return $fileName;
 
 
     }
     }
+
+    private function applyFilters(Builder $query, array $filters): void
+    {
+        $allowedColumns = array_flip((new MafView())->getFillable());
+
+        foreach ($filters as $filterName => $filterValue) {
+            if ($filterName === 'year' || $filterValue === null || $filterValue === '') {
+                continue;
+            }
+
+            if ($filterName === 's') {
+                $searchFields = [
+                    'rfid',
+                    'factory_number',
+                    'statement_number',
+                    'upd_number',
+                    'object_address',
+                    'nomenclature_number',
+                    'article',
+                ];
+                $query->where(function ($subQuery) use ($searchFields, $filterValue) {
+                    foreach ($searchFields as $searchField) {
+                        $subQuery->orWhere($searchField, 'LIKE', '%' . $filterValue . '%');
+                    }
+                });
+                continue;
+            }
+
+            if (Str::endsWith($filterName, '_from') || Str::endsWith($filterName, '_to')) {
+                $operator = Str::endsWith($filterName, '_from') ? '>=' : '<=';
+                $column = Str::replace(['_from', '_to'], '', $filterName);
+                if (!isset($allowedColumns[$column])) {
+                    continue;
+                }
+                $query->where($column, $operator, $filterValue);
+                continue;
+            }
+
+            if (!isset($allowedColumns[$filterName])) {
+                continue;
+            }
+
+            if (is_string($filterValue) && Str::contains($filterValue, '||')) {
+                $values = explode('||', $filterValue);
+                $query->where(function ($subQuery) use ($filterName, $values) {
+                    $nonNullValues = [];
+                    foreach ($values as $value) {
+                        if ($value === '-пусто-') {
+                            $subQuery->orWhereNull($filterName);
+                        } else {
+                            $nonNullValues[] = $value;
+                        }
+                    }
+                    if (!empty($nonNullValues)) {
+                        $subQuery->orWhereIn($filterName, $nonNullValues);
+                    }
+                });
+                continue;
+            }
+
+            if ($filterValue === '-пусто-') {
+                $query->whereNull($filterName);
+            } else {
+                $query->where($filterName, $filterValue);
+            }
+        }
+    }
 }
 }

+ 2 - 1
app/Services/ExportOneOrderService.php

@@ -5,6 +5,7 @@ namespace App\Services;
 use App\Helpers\DateHelper;
 use App\Helpers\DateHelper;
 use App\Models\Order;
 use App\Models\Order;
 use App\Models\Product;
 use App\Models\Product;
+use App\Models\Scopes\YearScope;
 use Illuminate\Support\Collection;
 use Illuminate\Support\Collection;
 use Illuminate\Support\Facades\Log;
 use Illuminate\Support\Facades\Log;
 use Illuminate\Support\Facades\Storage;
 use Illuminate\Support\Facades\Storage;
@@ -27,7 +28,7 @@ class ExportOneOrderService
     public function handle(Order $order, int $userId): string
     public function handle(Order $order, int $userId): string
     {
     {
         $productsSku = $order->products_sku()
         $productsSku = $order->products_sku()
-            ->withoutGlobalScopes()
+            ->withoutGlobalScope(YearScope::class)
             ->where('year', $order->year)
             ->where('year', $order->year)
             ->get();
             ->get();
         $order->setRelation('products_sku', $productsSku);
         $order->setRelation('products_sku', $productsSku);

+ 1 - 1
app/Services/ExportOrdersService.php

@@ -32,7 +32,7 @@ class ExportOrdersService
         $productsSkuByOrder = collect();
         $productsSkuByOrder = collect();
         if ($orderIds->isNotEmpty() && $orderYears->isNotEmpty()) {
         if ($orderIds->isNotEmpty() && $orderYears->isNotEmpty()) {
             $productsSkuByOrder = ProductSKU::query()
             $productsSkuByOrder = ProductSKU::query()
-                ->withoutGlobalScopes()
+                ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
                 ->whereIn('order_id', $orderIds)
                 ->whereIn('order_id', $orderIds)
                 ->whereIn('year', $orderYears)
                 ->whereIn('year', $orderYears)
                 ->get()
                 ->get()

+ 2 - 2
app/Services/ExportReclamationsService.php

@@ -36,7 +36,7 @@ class ExportReclamationsService
             ->with([
             ->with([
                 'order.district',
                 'order.district',
                 'order.area',
                 'order.area',
-                'skus.product' => fn($q) => $q->withoutGlobalScopes(),
+                'skus.product' => fn($q) => $q->withoutGlobalScope(\App\Models\Scopes\YearScope::class),
                 'spareParts.pricingCodes',
                 'spareParts.pricingCodes',
             ])
             ])
             ->get()
             ->get()
@@ -163,7 +163,7 @@ class ExportReclamationsService
 
 
         $passportName = null;
         $passportName = null;
         if ($product->article && $year) {
         if ($product->article && $year) {
-            $productForYear = Product::withoutGlobalScopes()
+            $productForYear = Product::withoutGlobalScope(\App\Models\Scopes\YearScope::class)
                 ->where('year', $year)
                 ->where('year', $year)
                 ->where('article', $product->article)
                 ->where('article', $product->article)
                 ->first();
                 ->first();

+ 4 - 4
app/Services/GenerateDocumentsService.php

@@ -37,14 +37,14 @@ class GenerateDocumentsService
     {
     {
         $techDocsPath = base_path('/tech-docs/');
         $techDocsPath = base_path('/tech-docs/');
         $order = Order::query()
         $order = Order::query()
-            ->withoutGlobalScopes()
+            ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
             ->whereKey($order->id)
             ->whereKey($order->id)
             ->where('year', $order->year)
             ->where('year', $order->year)
             ->with('documents')
             ->with('documents')
             ->firstOrFail();
             ->firstOrFail();
 
 
         $products_sku = $order->products_sku()
         $products_sku = $order->products_sku()
-            ->withoutGlobalScopes()
+            ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
             ->where('year', $order->year)
             ->where('year', $order->year)
             ->get();
             ->get();
         $order->setRelation('products_sku', $products_sku);
         $order->setRelation('products_sku', $products_sku);
@@ -137,7 +137,7 @@ class GenerateDocumentsService
     public function generateHandoverPack(Order $order, int $userId): string
     public function generateHandoverPack(Order $order, int $userId): string
     {
     {
         $productsSku = $order->products_sku()
         $productsSku = $order->products_sku()
-            ->withoutGlobalScopes()
+            ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
             ->where('year', $order->year)
             ->where('year', $order->year)
             ->get();
             ->get();
         $order->setRelation('products_sku', $productsSku);
         $order->setRelation('products_sku', $productsSku);
@@ -699,7 +699,7 @@ class GenerateDocumentsService
 
 
     public function generateTtnPack(Ttn $ttn, int $userId): string
     public function generateTtnPack(Ttn $ttn, int $userId): string
     {
     {
-        $skus = ProductSKU::query()->withoutGlobalScopes()->whereIn('id', json_decode($ttn->skus))->get();
+        $skus = ProductSKU::query()->withoutGlobalScope(\App\Models\Scopes\YearScope::class)->whereIn('id', json_decode($ttn->skus))->get();
         $volume = $weight = $places = 0;
         $volume = $weight = $places = 0;
         foreach ($skus as $sku) {
         foreach ($skus as $sku) {
             if(!isset($order)) {
             if(!isset($order)) {

+ 1 - 1
app/Services/Import/ImportMafOrdersService.php

@@ -122,7 +122,7 @@ class ImportMafOrdersService
 
 
     private function loadProductCache(): void
     private function loadProductCache(): void
     {
     {
-        $this->productCache = Product::withoutGlobalScopes()
+        $this->productCache = Product::withoutGlobalScope(\App\Models\Scopes\YearScope::class)
             ->where('year', $this->year)
             ->where('year', $this->year)
             ->pluck('id', 'article')
             ->pluck('id', 'article')
             ->toArray();
             ->toArray();

+ 22 - 22
app/Services/Import/ImportYearDataService.php

@@ -207,9 +207,9 @@ class ImportYearDataService
     private function clearExistingData(): void
     private function clearExistingData(): void
     {
     {
         // Используем логику из ClearYearDataJob
         // Используем логику из ClearYearDataJob
-        $orderIds = Order::withoutGlobalScopes()->withTrashed()->where('year', $this->year)->pluck('id');
-        $productIds = Product::withoutGlobalScopes()->withTrashed()->where('year', $this->year)->pluck('id');
-        $productSkuIds = ProductSKU::withoutGlobalScopes()->withTrashed()->where('year', $this->year)->pluck('id');
+        $orderIds = Order::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()->where('year', $this->year)->pluck('id');
+        $productIds = Product::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()->where('year', $this->year)->pluck('id');
+        $productSkuIds = ProductSKU::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()->where('year', $this->year)->pluck('id');
         $reclamationIds = Reclamation::whereIn('order_id', $orderIds)->pluck('id');
         $reclamationIds = Reclamation::whereIn('order_id', $orderIds)->pluck('id');
 
 
         // Собираем файлы до удаления связей
         // Собираем файлы до удаления связей
@@ -233,19 +233,19 @@ class ImportYearDataService
         Schedule::whereIn('order_id', $orderIds)->delete();
         Schedule::whereIn('order_id', $orderIds)->delete();
 
 
         // SKU
         // SKU
-        ProductSKU::withoutGlobalScopes()->withTrashed()->where('year', $this->year)->forceDelete();
+        ProductSKU::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()->where('year', $this->year)->forceDelete();
 
 
         // Заказы
         // Заказы
-        Order::withoutGlobalScopes()->withTrashed()->where('year', $this->year)->forceDelete();
+        Order::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()->where('year', $this->year)->forceDelete();
 
 
         // МАФ заказы
         // МАФ заказы
-        MafOrder::withoutGlobalScopes()->withTrashed()->where('year', $this->year)->forceDelete();
+        MafOrder::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()->where('year', $this->year)->forceDelete();
 
 
         // Продукты
         // Продукты
-        Product::withoutGlobalScopes()->withTrashed()
+        Product::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()
             ->whereIn('id', $productIds)
             ->whereIn('id', $productIds)
             ->update(['certificate_id' => null]);
             ->update(['certificate_id' => null]);
-        Product::withoutGlobalScopes()->withTrashed()->where('year', $this->year)->forceDelete();
+        Product::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()->where('year', $this->year)->forceDelete();
 
 
         // ТТН
         // ТТН
         Ttn::where('year', $this->year)->update(['file_id' => null]);
         Ttn::where('year', $this->year)->update(['file_id' => null]);
@@ -276,14 +276,14 @@ class ImportYearDataService
         $fileIds = $fileIds->merge(DB::table('reclamation_act')->whereIn('reclamation_id', $reclamationIds)->pluck('file_id'));
         $fileIds = $fileIds->merge(DB::table('reclamation_act')->whereIn('reclamation_id', $reclamationIds)->pluck('file_id'));
 
 
         $fileIds = $fileIds->merge(
         $fileIds = $fileIds->merge(
-            Product::withoutGlobalScopes()->withTrashed()
+            Product::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()
                 ->whereIn('id', $productIds)
                 ->whereIn('id', $productIds)
                 ->whereNotNull('certificate_id')
                 ->whereNotNull('certificate_id')
                 ->pluck('certificate_id')
                 ->pluck('certificate_id')
         );
         );
 
 
         $fileIds = $fileIds->merge(
         $fileIds = $fileIds->merge(
-            ProductSKU::withoutGlobalScopes()->withTrashed()
+            ProductSKU::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->withTrashed()
                 ->whereIn('id', $productSkuIds)
                 ->whereIn('id', $productSkuIds)
                 ->whereNotNull('passport_id')
                 ->whereNotNull('passport_id')
                 ->pluck('passport_id')
                 ->pluck('passport_id')
@@ -373,7 +373,7 @@ class ImportYearDataService
             $nomenclatureNumber = $this->getStringValue($row, $headerMap, 'nomenclature_number', '');
             $nomenclatureNumber = $this->getStringValue($row, $headerMap, 'nomenclature_number', '');
 
 
             // Проверяем существует ли продукт
             // Проверяем существует ли продукт
-            $existing = Product::withoutGlobalScopes()
+            $existing = Product::withoutGlobalScope(\App\Models\Scopes\YearScope::class)
                 ->where('year', $this->year)
                 ->where('year', $this->year)
                 ->where('nomenclature_number', $nomenclatureNumber)
                 ->where('nomenclature_number', $nomenclatureNumber)
                 ->first();
                 ->first();
@@ -417,7 +417,7 @@ class ImportYearDataService
                 $existing->update($productData);
                 $existing->update($productData);
                 $this->productIdMapping[$oldId] = $existing->id;
                 $this->productIdMapping[$oldId] = $existing->id;
             } else {
             } else {
-                $product = Product::withoutGlobalScopes()->create($productData);
+                $product = Product::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->create($productData);
                 $this->productIdMapping[$oldId] = $product->id;
                 $this->productIdMapping[$oldId] = $product->id;
             }
             }
 
 
@@ -460,7 +460,7 @@ class ImportYearDataService
                 // Пробуем найти по номенклатуре
                 // Пробуем найти по номенклатуре
                 $nomenclature = $this->getValue($row, $headerMap, 'product_nomenclature');
                 $nomenclature = $this->getValue($row, $headerMap, 'product_nomenclature');
                 if ($nomenclature) {
                 if ($nomenclature) {
-                    $product = Product::withoutGlobalScopes()
+                    $product = Product::withoutGlobalScope(\App\Models\Scopes\YearScope::class)
                         ->where('year', $this->year)
                         ->where('year', $this->year)
                         ->where('nomenclature_number', $nomenclature)
                         ->where('nomenclature_number', $nomenclature)
                         ->first();
                         ->first();
@@ -474,7 +474,7 @@ class ImportYearDataService
             }
             }
 
 
             // Проверяем существует ли
             // Проверяем существует ли
-            $existing = MafOrder::withoutGlobalScopes()
+            $existing = MafOrder::withoutGlobalScope(\App\Models\Scopes\YearScope::class)
                 ->where('year', $this->year)
                 ->where('year', $this->year)
                 ->where('product_id', $newProductId)
                 ->where('product_id', $newProductId)
                 ->where('order_number', $orderNumber)
                 ->where('order_number', $orderNumber)
@@ -498,7 +498,7 @@ class ImportYearDataService
                 $existing->update($mafOrderData);
                 $existing->update($mafOrderData);
                 $this->mafOrderIdMapping[$oldId] = $existing->id;
                 $this->mafOrderIdMapping[$oldId] = $existing->id;
             } else {
             } else {
-                $mafOrder = MafOrder::withoutGlobalScopes()->create($mafOrderData);
+                $mafOrder = MafOrder::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->create($mafOrderData);
                 $this->mafOrderIdMapping[$oldId] = $mafOrder->id;
                 $this->mafOrderIdMapping[$oldId] = $mafOrder->id;
             }
             }
 
 
@@ -535,7 +535,7 @@ class ImportYearDataService
             $objectAddress = $this->getStringValue($row, $headerMap, 'object_address', '');
             $objectAddress = $this->getStringValue($row, $headerMap, 'object_address', '');
 
 
             // Проверяем существует ли
             // Проверяем существует ли
-            $existing = Order::withoutGlobalScopes()
+            $existing = Order::withoutGlobalScope(\App\Models\Scopes\YearScope::class)
                 ->where('year', $this->year)
                 ->where('year', $this->year)
                 ->where('object_address', $objectAddress)
                 ->where('object_address', $objectAddress)
                 ->first();
                 ->first();
@@ -582,7 +582,7 @@ class ImportYearDataService
                 $existing->update($orderData);
                 $existing->update($orderData);
                 $this->orderIdMapping[$oldId] = $existing->id;
                 $this->orderIdMapping[$oldId] = $existing->id;
             } else {
             } else {
-                $order = Order::withoutGlobalScopes()->create($orderData);
+                $order = Order::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->create($orderData);
                 $this->orderIdMapping[$oldId] = $order->id;
                 $this->orderIdMapping[$oldId] = $order->id;
             }
             }
 
 
@@ -625,7 +625,7 @@ class ImportYearDataService
                 // Пробуем найти по номенклатуре
                 // Пробуем найти по номенклатуре
                 $nomenclature = $this->getValue($row, $headerMap, 'product_nomenclature');
                 $nomenclature = $this->getValue($row, $headerMap, 'product_nomenclature');
                 if ($nomenclature) {
                 if ($nomenclature) {
-                    $product = Product::withoutGlobalScopes()
+                    $product = Product::withoutGlobalScope(\App\Models\Scopes\YearScope::class)
                         ->where('year', $this->year)
                         ->where('year', $this->year)
                         ->where('nomenclature_number', $nomenclature)
                         ->where('nomenclature_number', $nomenclature)
                         ->first();
                         ->first();
@@ -646,7 +646,7 @@ class ImportYearDataService
                 // Пробуем найти по адресу
                 // Пробуем найти по адресу
                 $orderAddress = $this->getValue($row, $headerMap, 'order_address');
                 $orderAddress = $this->getValue($row, $headerMap, 'order_address');
                 if ($orderAddress) {
                 if ($orderAddress) {
-                    $order = Order::withoutGlobalScopes()
+                    $order = Order::withoutGlobalScope(\App\Models\Scopes\YearScope::class)
                         ->where('year', $this->year)
                         ->where('year', $this->year)
                         ->where('object_address', $orderAddress)
                         ->where('object_address', $orderAddress)
                         ->first();
                         ->first();
@@ -669,7 +669,7 @@ class ImportYearDataService
                     // Пробуем найти по номеру заказа
                     // Пробуем найти по номеру заказа
                     $mafOrderNumber = $this->getValue($row, $headerMap, 'maf_order_number');
                     $mafOrderNumber = $this->getValue($row, $headerMap, 'maf_order_number');
                     if ($mafOrderNumber) {
                     if ($mafOrderNumber) {
-                        $mafOrder = MafOrder::withoutGlobalScopes()
+                        $mafOrder = MafOrder::withoutGlobalScope(\App\Models\Scopes\YearScope::class)
                             ->where('year', $this->year)
                             ->where('year', $this->year)
                             ->where('product_id', $newProductId)
                             ->where('product_id', $newProductId)
                             ->where('order_number', $mafOrderNumber)
                             ->where('order_number', $mafOrderNumber)
@@ -702,7 +702,7 @@ class ImportYearDataService
                 'passport_id' => $passportId,
                 'passport_id' => $passportId,
             ];
             ];
 
 
-            $sku = ProductSKU::withoutGlobalScopes()->create($skuData);
+            $sku = ProductSKU::withoutGlobalScope(\App\Models\Scopes\YearScope::class)->create($skuData);
             $this->productSkuIdMapping[$oldId] = $sku->id;
             $this->productSkuIdMapping[$oldId] = $sku->id;
 
 
             $count++;
             $count++;
@@ -750,7 +750,7 @@ class ImportYearDataService
                 // Пробуем найти по адресу
                 // Пробуем найти по адресу
                 $orderAddress = $this->getValue($row, $headerMap, 'order_address');
                 $orderAddress = $this->getValue($row, $headerMap, 'order_address');
                 if ($orderAddress) {
                 if ($orderAddress) {
-                    $order = Order::withoutGlobalScopes()
+                    $order = Order::withoutGlobalScope(\App\Models\Scopes\YearScope::class)
                         ->where('year', $this->year)
                         ->where('year', $this->year)
                         ->where('object_address', $orderAddress)
                         ->where('object_address', $orderAddress)
                         ->first();
                         ->first();

+ 1 - 1
app/Services/ImportCatalogService.php

@@ -76,7 +76,7 @@ class ImportCatalogService extends ImportBaseService
                 $certDate = (int) $r['certificate_date'];
                 $certDate = (int) $r['certificate_date'];
 
 
                 $existing = Product::query()
                 $existing = Product::query()
-                    ->withoutGlobalScopes()
+                    ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
                     ->where('year', $this->year)
                     ->where('year', $this->year)
                     ->where('nomenclature_number', $r['nomenclature_number'])
                     ->where('nomenclature_number', $r['nomenclature_number'])
                     ->first();
                     ->first();

+ 1 - 1
app/Services/ImportMafsService.php

@@ -80,7 +80,7 @@ class ImportMafsService extends ImportBaseService
                 $logMessage .= $r['products_sku.statement_date'] . ' ' . $r['products_sku.manufacture_date'] .' ';
                 $logMessage .= $r['products_sku.statement_date'] . ' ' . $r['products_sku.manufacture_date'] .' ';
 
 
                 $productSKU = ProductSKU::query()
                 $productSKU = ProductSKU::query()
-                    ->withoutGlobalScopes()
+                    ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
                     ->where('id', $id)
                     ->where('id', $id)
                     ->when($this->year, fn ($q) => $q->where('year', $this->year))
                     ->when($this->year, fn ($q) => $q->where('year', $this->year))
                     ->first();
                     ->first();

+ 42 - 37
app/Services/ImportOrdersService.php

@@ -123,7 +123,7 @@ class ImportOrdersService extends ImportBaseService
 
 
                 // product
                 // product
                 $product = Product::query()
                 $product = Product::query()
-                    ->withoutGlobalScopes()
+                    ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
                     ->where('year', $year)
                     ->where('year', $year)
                     ->where('nomenclature_number', $r['products.nomenclature_number'])
                     ->where('nomenclature_number', $r['products.nomenclature_number'])
                     ->first();
                     ->first();
@@ -160,7 +160,7 @@ class ImportOrdersService extends ImportBaseService
 
 
                 // order
                 // order
                 $order = Order::query()
                 $order = Order::query()
-                    ->withoutGlobalScopes()
+                    ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
                     ->where('year', $year)
                     ->where('year', $year)
                     ->where('object_address', $r['orders.object_address'])
                     ->where('object_address', $r['orders.object_address'])
                     ->first();
                     ->first();
@@ -168,7 +168,7 @@ class ImportOrdersService extends ImportBaseService
                     $order = Order::query()
                     $order = Order::query()
                         ->create([
                         ->create([
                             'year' => $year,
                             'year' => $year,
-                            'name' => $r['orders.object_address'],
+                            'name' => $r['orders.name'],
                             'user_id' => $userId,
                             'user_id' => $userId,
                             'district_id' => $districtId,
                             'district_id' => $districtId,
                             'area_id' => $areaId,
                             'area_id' => $areaId,
@@ -188,7 +188,7 @@ class ImportOrdersService extends ImportBaseService
                 // maf order
                 // maf order
                 if ($r['maf_orders.order_number'] != '') {
                 if ($r['maf_orders.order_number'] != '') {
                     $mafOrder = MafOrder::query()
                     $mafOrder = MafOrder::query()
-                        ->withoutGlobalScopes()
+                        ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
                         ->where('year', $year)
                         ->where('year', $year)
                         ->where('product_id', $product->id)
                         ->where('product_id', $product->id)
                         ->where('order_number', $r['maf_orders.order_number'])
                         ->where('order_number', $r['maf_orders.order_number'])
@@ -219,42 +219,47 @@ class ImportOrdersService extends ImportBaseService
                 // search rfid in products_sku
                 // search rfid in products_sku
                 $manufacture_date = is_int($r['products_sku.manufacture_date']) ? DateHelper::excelDateToISODate($r['products_sku.manufacture_date']) : null;
                 $manufacture_date = is_int($r['products_sku.manufacture_date']) ? DateHelper::excelDateToISODate($r['products_sku.manufacture_date']) : null;
                 $statement_date = is_int($r['products_sku.statement_date']) ? DateHelper::excelDateToISODate($r['products_sku.statement_date']) : null;
                 $statement_date = is_int($r['products_sku.statement_date']) ? DateHelper::excelDateToISODate($r['products_sku.statement_date']) : null;
+                $rfid = trim((string) $r['products_sku.rfid']) ?: null;
 
 
-                $productSKU = ProductSKU::query()
-                    ->withoutGlobalScopes()
-                    ->where('year', $year)
-                    ->where('rfid', $r['products_sku.rfid'])
-                    ->where('product_id', $product->id)
-                    ->where('order_id', $order->id)
-                    ->where('maf_order_id', $mafOrder?->id)
-                    ->where('factory_number', $r['products_sku.factory_number'])
-                    ->where('statement_number', $r['products_sku.statement_number'])
-                    ->where('upd_number', $r['products_sku.upd_number'])
-                    ->where('statement_date', $statement_date)
-                    ->where('manufacture_date', $manufacture_date)
-                    ->first();
-//            dd($productSKU->toRawSql());
-                if ($productSKU) {
-                    echo $this->import->log($logMessage . 'Found product with rfid: ' . $productSKU->rfid . ' Skip.' . '. ');
-                    continue;
-                } else {
-                    $productSKU = ProductSKU::query()->create([
-                        'year' => $year,
-                        'product_id' => $product->id,
-                        'order_id' => $order->id,
-                        'maf_order_id' => $mafOrder?->id,
-                        'status' => ($mafOrder?->id) ? 'отгружен' : 'требуется',
-                        'rfid' => $r['products_sku.rfid'],
-                        'factory_number' => $r['products_sku.factory_number'],
-                        'manufacture_date' => $manufacture_date,
-                        'statement_number' => $r['products_sku.statement_number'],
-                        'statement_date' => $statement_date,
-                        'upd_number' => $r['products_sku.upd_number'],
-                    ]);
-                    $result['productsSkuCreated'] += 1;
-                    $logMessage .= 'Created product sku: ' . $productSKU->id . '. ';
+                // Дедупликация возможна только при заполненном RFID.
+                // Если RFID пустой, нужно создавать новую позицию, чтобы поддержать несколько одинаковых товаров на одной площадке.
+                if ($rfid) {
+                    $productSKU = ProductSKU::query()
+                        ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
+                        ->where('year', $year)
+                        ->where('rfid', $rfid)
+                        ->where('product_id', $product->id)
+                        ->where('order_id', $order->id)
+                        ->where('maf_order_id', $mafOrder?->id)
+                        ->where('factory_number', $r['products_sku.factory_number'])
+                        ->where('statement_number', $r['products_sku.statement_number'])
+                        ->where('upd_number', $r['products_sku.upd_number'])
+                        ->where('statement_date', $statement_date)
+                        ->where('manufacture_date', $manufacture_date)
+                        ->first();
+
+                    if ($productSKU) {
+                        echo $this->import->log($logMessage . 'Found product with rfid: ' . $productSKU->rfid . ' Skip.' . '. ');
+                        continue;
+                    }
                 }
                 }
 
 
+                $productSKU = ProductSKU::query()->create([
+                    'year' => $year,
+                    'product_id' => $product->id,
+                    'order_id' => $order->id,
+                    'maf_order_id' => $mafOrder?->id,
+                    'status' => ($mafOrder?->id) ? 'отгружен' : 'требуется',
+                    'rfid' => $rfid,
+                    'factory_number' => $r['products_sku.factory_number'],
+                    'manufacture_date' => $manufacture_date,
+                    'statement_number' => $r['products_sku.statement_number'],
+                    'statement_date' => $statement_date,
+                    'upd_number' => $r['products_sku.upd_number'],
+                ]);
+                $result['productsSkuCreated'] += 1;
+                $logMessage .= 'Created product sku: ' . $productSKU->id . '. ';
+
                 echo $this->import->log($logMessage);
                 echo $this->import->log($logMessage);
             } catch (\Exception $e) {
             } catch (\Exception $e) {
                 $this->errorRows[$strNumber] = $e->getMessage();
                 $this->errorRows[$strNumber] = $e->getMessage();

+ 4 - 4
app/Services/ImportReclamationsService.php

@@ -99,7 +99,7 @@ class ImportReclamationsService extends ImportBaseService
 
 
                 // order
                 // order
 //                $order = Order::query()
 //                $order = Order::query()
-//                    ->withoutGlobalScopes()
+//                    ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
 //                    ->where('year', $year)
 //                    ->where('year', $year)
 //                    ->where('object_address', $r['orders.object_address'])
 //                    ->where('object_address', $r['orders.object_address'])
 //                    ->first();
 //                    ->first();
@@ -113,7 +113,7 @@ class ImportReclamationsService extends ImportBaseService
 
 
                 // product
                 // product
 //                $product = Product::query()
 //                $product = Product::query()
-//                    ->withoutGlobalScopes()
+//                    ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
 //                    ->where('year', $year)
 //                    ->where('year', $year)
 //                    ->where('nomenclature_number', $r['products.nomenclature_number'])
 //                    ->where('nomenclature_number', $r['products.nomenclature_number'])
 //                    ->first();
 //                    ->first();
@@ -127,7 +127,7 @@ class ImportReclamationsService extends ImportBaseService
 
 
                 // check maf with this nomenclature number in order
                 // check maf with this nomenclature number in order
                 $productSKU = ProductSKU::query()
                 $productSKU = ProductSKU::query()
-                    ->withoutGlobalScopes()
+                    ->withoutGlobalScope(\App\Models\Scopes\YearScope::class)
 //                    ->where('year', $year)
 //                    ->where('year', $year)
 //                    ->where('product_id', $product->id)
 //                    ->where('product_id', $product->id)
 //                    ->where('order_id', $order->id)
 //                    ->where('order_id', $order->id)
@@ -140,7 +140,7 @@ class ImportReclamationsService extends ImportBaseService
                     continue;
                     continue;
                 }
                 }
 
 
-                $order = Order::query()->withoutGlobalScopes()->where('id', $productSKU->order_id)->first();
+                $order = Order::query()->withoutGlobalScope(\App\Models\Scopes\YearScope::class)->where('id', $productSKU->order_id)->first();
 
 
                 $createDate = ($r['reclamations.create_date']) ? DateHelper::excelDateToISODate($r['reclamations.create_date']) : null;
                 $createDate = ($r['reclamations.create_date']) ? DateHelper::excelDateToISODate($r['reclamations.create_date']) : null;
                 $finishDate = ($r['reclamations.finish_date']) ? DateHelper::excelDateToISODate($r['reclamations.finish_date']) : null;
                 $finishDate = ($r['reclamations.finish_date']) ? DateHelper::excelDateToISODate($r['reclamations.finish_date']) : null;

+ 9 - 8
resources/views/products_sku/index.blade.php

@@ -60,15 +60,16 @@
                 <div class="modal-body">
                 <div class="modal-body">
                     <form action="{{ route('mafs.export') }}" method="post" enctype="multipart/form-data">
                     <form action="{{ route('mafs.export') }}" method="post" enctype="multipart/form-data">
                         @csrf
                         @csrf
+                        @include('partials.checkbox', ['title' => 'С учётом текущего фильтра и поиска', 'name' => 'withFilter', 'type' => 'checkbox', 'value' => 'yes', 'checked' => false])
                         <div class="d-none">
                         <div class="d-none">
-{{--                            @if(request()->s)--}}
-{{--                                @include('partials.input', ['name' => 'filters[s]', 'title' => 'поиск', 'value' => request()->s])--}}
-{{--                            @endif--}}
-{{--                            @if(request()->filters)--}}
-{{--                                @foreach(request()->filters as $filterName => $filterValue)--}}
-{{--                                    @include('partials.input', ['name' => 'filters[' . $filterName .']', 'title' => $filterName, 'value' => $filterValue])--}}
-{{--                                @endforeach--}}
-{{--                            @endif--}}
+                            @if(request()->s)
+                                @include('partials.input', ['name' => 's', 'title' => 'поиск', 'value' => request()->s])
+                            @endif
+                            @if(request()->filters)
+                                @foreach(request()->filters as $filterName => $filterValue)
+                                    @include('partials.input', ['name' => 'filters[' . $filterName .']', 'title' => $filterName, 'value' => $filterValue])
+                                @endforeach
+                            @endif
                         </div>
                         </div>
                         @include('partials.submit', ['name' => 'Экспорт'])
                         @include('partials.submit', ['name' => 'Экспорт'])
                     </form>
                     </form>