Compare commits
No commits in common. "feature/maryKerApi" and "main" have entirely different histories.
feature/ma
...
main
@ -1,11 +0,0 @@
|
||||
{
|
||||
"version": "0.0.1",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "t2t-dev",
|
||||
"runtimeExecutable": "php",
|
||||
"runtimeArgs": ["artisan", "serve", "--port=8123"],
|
||||
"port": 8123
|
||||
}
|
||||
]
|
||||
}
|
||||
5
.gitignore
vendored
5
.gitignore
vendored
@ -73,8 +73,3 @@ Homestead.yaml
|
||||
/public/images/supplierLogo/*
|
||||
/public/attachments/*
|
||||
/database/csv/*
|
||||
/.gitea/workflows/deploy.yml
|
||||
/.claude/settings.local.json
|
||||
/public/js/
|
||||
/public/css/
|
||||
/public/mix-manifest.json
|
||||
|
||||
239
AGENTS.md
239
AGENTS.md
@ -1,56 +1,13 @@
|
||||
<laravel-boost-guidelines>
|
||||
=== projekt szabályok ===
|
||||
=== foundation rules ===
|
||||
|
||||
# Hibrid architektúra: Legacy vs. Modern
|
||||
# Laravel Boost Guidelines
|
||||
|
||||
A projekt jelenleg átmeneti fázisban van a régi Laravel 8-as architektúráról a modern Laravel 12-es felépítésre. KRITIKUS fontosságú a két "világ" megkülönböztetése:
|
||||
The Laravel Boost guidelines are specifically curated by Laravel maintainers for this application. These guidelines should be followed closely to ensure the best experience when building Laravel applications.
|
||||
|
||||
### 1. Legacy Világ (Csak karbantartás)
|
||||
- **Technológiai stekk**: jQuery, Bootstrap, Laravel Mix (`webpack.mix.js`), DataTables, Mustache.js.
|
||||
- **Belépési pont**: `resources/views/layout/core.blade.php`, `/legacy` útvonalak, és a hagyományos Blade nézeteket használó kontrollerek.
|
||||
- **Assetek**: A `mix()` függvénnyel kezelve. A fájlok a `resources/js/` mappában találhatók (kivéve a `modern` almappát).
|
||||
- **Szabály**: Ezekhez CSAK hibajavítás vagy kisebb módosítás esetén nyúlj. NE implementálj ide új funkciókat, hacsak nincs rá kifejezett kérés.
|
||||
## Foundational Context
|
||||
|
||||
### 2. Modern Világ (Elsődleges fejlesztés)
|
||||
- **Technológiai stekk**: Laravel 12, Filament v4 (TALL stekk: Tailwind, Alpine.js, Laravel, Livewire), Vite (`vite.config.js`).
|
||||
- **Belépési pont**: `/admin` (Filament Dashboard), `resources/modern/` mappa.
|
||||
- **Assetek**: A `vite()` függvénnyel kezelve. A stílusokhoz Tailwind CSS v4-et használunk.
|
||||
- **Szabály**: MINDEN új funkciót Filament resource-ok/oldalak vagy modern Livewire komponensek használatával kell megvalósítani.
|
||||
|
||||
### 3. Átállás és Modernizáció
|
||||
- **"Clean Cut" megközelítés**: Szisztematikusan váltjuk ki a régi jQuery megoldásokat modern Laravel 12-es megfelelőkre.
|
||||
- **Auditálás**: Használd a `BaseAuditable` osztályt minden új modellnél a konzisztens követhetőség érdekében.
|
||||
- **Refaktorálás**: Ha egy legacy kontroller/nézet jelentős átalakítást igényel, javasold annak áthelyezését egy Filament Resource-ba.
|
||||
|
||||
# Feature flag rendszer (Laravel Pennant)
|
||||
|
||||
Az alkalmazásban deploy nélkül, admin felületről (`/admin/feature-flags`) ki/bekapcsolható funkciókhoz a `laravel/pennant` csomagra épülő, saját `feature_flags`/`feature_flag_overrides` táblákkal kiegészített rendszer van. Új feature flag bevezetésekor vagy a rendszer módosításakor:
|
||||
|
||||
- **NE** írj kézzel új `Feature::define()` hívást — a `FeatureFlagRegistrar::registerAll()` (hívva: `AppServiceProvider::boot()`) automatikusan regisztrálja az admin felületen létrehozott flageket.
|
||||
- **NE** használd a Pennant saját tárolóját (`Feature::for($user)->activate()`) tartós, admin felületről törölhetetlen felhasználói döntésekhez — a `Feature::purge()` egy adott flag nevére **minden** scope-ot (minden felhasználó feloldását) töröl. Az explicit egyéni felülbírálásokat ezért a saját `feature_flag_overrides` tábla (`FeatureFlagOverride` modell) tárolja, amit a resolver néz meg elsőként, mielőtt a szabály-alapú (enabled/stage/role) logikára térne.
|
||||
- `FeatureFlagOverride` (vagy bármi, ami Pennant-cache-invalidáló Observerrel rendelkezik) módosítása mindig **model-instance-on keresztül** történjen (`$model->save()`/`$model->delete()`), soha ne query builder `->update()`/`->delete()`-tel — csak az előbbi váltja ki az Eloquent modell-eseményeket, amikre az Observerek épülnek.
|
||||
- A `FeatureFlagAdmin` nevű flag saját magát a feature flag admin felületet védi (`FeatureFlagPolicy`/`FeatureFlagOverridePolicy` → `Feature::for($user)->active('FeatureFlagAdmin')`) — jelenleg kizárólag `developer` szerepkör éri el, minden stage-en.
|
||||
- Teljes technikai leírás (architektúra, talált hibák, tesztelési minták): `storage/app/private/docs/feature-flag-rendszer.md`.
|
||||
|
||||
# Projekt-specifikus szabályok
|
||||
|
||||
- **API válaszok**: Használd a `flugger/laravel-responder` csomagot (`responder()` helper) minden API válaszhoz. Kövesd az `OrderController.php`-ban látható mintát.
|
||||
- **API verziózás**: Az API verziókat a névterekből kell kinyerni a `parseAPIVersionFromNamespace(__NAMESPACE__)` helper segítségével.
|
||||
- **Dokumentáció**: Használd a Scribe-ot az API dokumentációhoz. Használj `@group`, `@authenticated`, `@bodyParam`, és `@responseField` annotációkat a kontrollerekben.
|
||||
- **Modellek**: Az új modelleknek jellemzően a `BaseAuditable` osztályból kell származniuk a sima Eloquent `Model` helyett, ha auditálás szükséges.
|
||||
- **Helperek**: Használd az `app/helpers.php` fájlban definiált projekt-specifikus helpereket (pl. `formatterPhoneNumber`, `formatterDateTime`, `getSql`).
|
||||
- **Fordítások**: Használd a `laravel-lang/lang` csomagot a többnyelvű támogatáshoz.
|
||||
- **Enumok**: Használd a `bensampo/laravel-enum` csomagot a típusbiztos felsorolásokhoz (pl. `OrderStatusEnum`, `OrderType`).
|
||||
|
||||
=== alapvető szabályok ===
|
||||
|
||||
# Laravel Boost Irányelvek
|
||||
|
||||
A Laravel Boost irányelveket kifejezetten a Laravel karbantartói állították össze ehhez az alkalmazáshoz. Ezeket az irányelveket szigorúan be kell tartani a legjobb Laravel fejlesztési élmény biztosítása érdekében.
|
||||
|
||||
## Alapvető kontextus
|
||||
|
||||
Ez egy Laravel alkalmazás, a fő ökoszisztéma csomagok és verziók alább láthatók. Te ezeknek a szakértője vagy. Gondoskodj róla, hogy tartsd magad ezekhez a specifikus csomagokhoz és verziókhoz.
|
||||
This application is a Laravel application and its main Laravel ecosystems package & versions are below. You are an expert with them all. Ensure you abide by these specific packages & versions.
|
||||
|
||||
- php - 8.4
|
||||
- filament/filament (FILAMENT) - v4
|
||||
@ -66,162 +23,162 @@ ## Alapvető kontextus
|
||||
- phpunit/phpunit (PHPUNIT) - v11
|
||||
- tailwindcss (TAILWINDCSS) - v4
|
||||
|
||||
## Képességek aktiválása
|
||||
## Skills Activation
|
||||
|
||||
Ez a projekt tartomány-specifikus képességekkel rendelkezik. Kötelező aktiválnod a releváns képességet, amikor abban a tartományban dolgozol — ne várd meg, amíg elakadsz.
|
||||
This project has domain-specific skills available. You MUST activate the relevant skill whenever you work in that domain—don't wait until you're stuck.
|
||||
|
||||
- `laravel-best-practices` — Használd ezt a képességet Laravel PHP kód írásakor, átnézésekor vagy refaktorálásakor. Ez magában foglalja kontrollerek, modellek, migrációk, form requestek, policy-k, jobok, ütemezett parancsok, service osztályok és Eloquent lekérdezések készítését vagy módosítását. Aktiváld N+1 és lekérdezési teljesítményproblémák, gyorsítótárazási stratégiák, autorizációs és biztonsági minták, validáció, hibakezelés, sor- és job konfiguráció, útvonal definíciók és architektúrális döntések esetén. Használd továbbá Laravel kód áttekintéséhez és meglévő kódok refaktorálásához a legjobb gyakorlatok szerint. Minden Laravel háttér PHP kódmintát érintő feladathoz.
|
||||
- `livewire-development` — Használd minden olyan feladathoz vagy kérdéshez, amely a Livewire-t érinti. Aktiváld, ha a felhasználó említi a Livewire-t, a wire: direktívákat, vagy Livewire-specifikus koncepciókat, mint a wire:model, wire:click. Lefedi az új komponensek építését, reaktivitási hibák keresését, valós idejű form validációt, betöltési állapotokat, a Livewire 2-ről 3-ra való migrációt, komponens formátumok konvertálását és teljesítményoptimalizálást. Ne használd nem-Livewire reaktív UI-hoz (React, Vue, csak Alpine, Inertia.js) vagy standard Laravel formokhoz Livewire nélkül.
|
||||
- `pest-testing` — Ezt a képességet kizárólag Pest PHP teszteléshez használd Laravel projektekben. Aktiváld, amikor tesztet írsz, szerkesztesz, javítasz vagy refaktorálsz — beleértve a kódmódosítás után eltört tesztek javítását, asszerciók hozzáadását, PHPUnit tesztek Pest-re konvertálását, datasetek hozzáadását és TDD munkafolyamatokat. Mindig aktiváld, ha a felhasználó Pest-ben való írásról kérdez, teszt fájlokat vagy könyvtárakat említ (tests/Feature, tests/Unit), vagy architektúra teszteket. Lefedi az it()/expect() szintaxist, dataseteket, mockolást, böngésző tesztelést, arch()-ot, Livewire komponens teszteket, RefreshDatabase-t és minden Pest 4 funkciót. Ne használd factory-k, seeder-ek, migrációk, kontrollerek, modellek vagy nem teszt jellegű PHP kódok szerkesztéséhez.
|
||||
- `tailwindcss-development` — Mindig aktiváld, ha a felhasználó üzenete bármilyen formában tartalmazza a 'tailwind' szót. Továbbá használd: responzív rács elrendezések (többoszlopos kártya rácsok, termék rácsok), flex/grid oldalstruktúrák (oldalsávos dashboardok, fix fejlécek, mobil-navigáció), UI komponensek stílusozása (kártyák, táblázatok, navigációs sávok, árazási szakaszok, formok, inputok, jelvények), sötét mód variánsok hozzáadása, térköz vagy tipográfia javítása, valamint Tailwind v3/v4 munkák esetén. Fő felhasználási eset: Tailwind utility osztályok írása vagy javítása HTML sablonokban (Blade, JSX, Vue). Hagyd ki háttér PHP logika, adatbázis lekérdezések, API útvonalak, HTML/CSS komponens nélküli JavaScript, CSS fájl auditok, build eszköz konfiguráció és vanilla CSS esetén.
|
||||
- `laravel-best-practices` — Apply this skill whenever writing, reviewing, or refactoring Laravel PHP code. This includes creating or modifying controllers, models, migrations, form requests, policies, jobs, scheduled commands, service classes, and Eloquent queries. Triggers for N+1 and query performance issues, caching strategies, authorization and security patterns, validation, error handling, queue and job configuration, route definitions, and architectural decisions. Also use for Laravel code reviews and refactoring existing Laravel code to follow best practices. Covers any task involving Laravel backend PHP code patterns.
|
||||
- `livewire-development` — Use for any task or question involving Livewire. Activate if user mentions Livewire, wire: directives, or Livewire-specific concepts like wire:model, wire:click, invoke this skill. Covers building new components, debugging reactivity issues, real-time form validation, loading states, migrating from Livewire 2 to 3, converting component formats (SFC/MFC/class-based), and performance optimization. Do not use for non-Livewire reactive UI (React, Vue, Alpine-only, Inertia.js) or standard Laravel forms without Livewire.
|
||||
- `pest-testing` — Use this skill for Pest PHP testing in Laravel projects only. Trigger whenever any test is being written, edited, fixed, or refactored — including fixing tests that broke after a code change, adding assertions, converting PHPUnit to Pest, adding datasets, and TDD workflows. Always activate when the user asks how to write something in Pest, mentions test files or directories (tests/Feature, tests/Unit) or architecture tests. Covers: it()/expect() syntax, datasets, mocking, browser testing, arch(), Livewire component tests, RefreshDatabase, and all Pest 4 features. Do not use for editing factories, seeders, migrations, controllers, models, or non-test PHP code.
|
||||
- `tailwindcss-development` — Always invoke when the user's message includes 'tailwind' in any form. Also invoke for: building responsive grid layouts (multi-column card grids, product grids), flex/grid page structures (dashboards with sidebars, fixed topbars, mobile-toggle navs), styling UI components (cards, tables, navbars, pricing sections, forms, inputs, badges), adding dark mode variants, fixing spacing or typography, and Tailwind v3/v4 work. The core use case: writing or fixing Tailwind utility classes in HTML templates (Blade, JSX, Vue). Skip for backend PHP logic, database queries, API routes, JavaScript with no HTML/CSS component, CSS file audits, build tool configuration, and vanilla CSS.
|
||||
|
||||
## Konvenciók
|
||||
## Conventions
|
||||
|
||||
- Követned kell az alkalmazásban használt összes meglévő kódkonvenciót. Fájl létrehozásakor vagy szerkesztésekor ellenőrizd a szomszédos fájlokat a helyes struktúra, megközelítés és elnevezés érdekében.
|
||||
- Használj leíró neveket a változókhoz és metódusokhoz. Például: `isRegisteredForDiscounts`, nem pedig `discount()`.
|
||||
- Új komponens írása előtt ellenőrizd a meglévő komponenseket az újrahasznosíthatóság érdekében.
|
||||
- You must follow all existing code conventions used in this application. When creating or editing a file, check sibling files for the correct structure, approach, and naming.
|
||||
- Use descriptive names for variables and methods. For example, `isRegisteredForDiscounts`, not `discount()`.
|
||||
- Check for existing components to reuse before writing a new one.
|
||||
|
||||
## Ellenőrző szkriptek
|
||||
## Verification Scripts
|
||||
|
||||
- Ne készíts ellenőrző szkripteket vagy kísérletezz, ha a tesztek lefedik az adott funkciót és bizonyítják a működését. Az egység- és funkcionális tesztek fontosabbak.
|
||||
- Do not create verification scripts or tinker when tests cover that functionality and prove they work. Unit and feature tests are more important.
|
||||
|
||||
## Alkalmazás struktúra és architektúra
|
||||
## Application Structure & Architecture
|
||||
|
||||
- Tartsd magad a meglévő könyvtárstruktúrához; ne hozz létre új alapkatalógusokat jóváhagyás nélkül.
|
||||
- Ne változtasd meg az alkalmazás függőségeit jóváhagyás nélkül.
|
||||
- Stick to existing directory structure; don't create new base folders without approval.
|
||||
- Do not change the application's dependencies without approval.
|
||||
|
||||
## Frontend csomagolás
|
||||
## Frontend Bundling
|
||||
|
||||
- Ha a felhasználó nem látja a frontend változást a felületen, az jelentheti azt, hogy futtatnia kell az `npm run build`, `npm run dev` vagy `composer run dev` parancsot. Kérdezz rá.
|
||||
- If the user doesn't see a frontend change reflected in the UI, it could mean they need to run `npm run build`, `npm run dev`, or `composer run dev`. Ask them.
|
||||
|
||||
## Dokumentációs fájlok
|
||||
## Documentation Files
|
||||
|
||||
- Dokumentációs fájlokat csak akkor hozz létre, ha a felhasználó kifejezetten kéri.
|
||||
- You must only create documentation files if explicitly requested by the user.
|
||||
|
||||
## Válaszok
|
||||
## Replies
|
||||
|
||||
- Légy tömör a magyarázatokban - fókuszálj a fontos dolgokra, ahelyett, hogy nyilvánvaló részleteket magyaráznál.
|
||||
- Be concise in your explanations - focus on what's important rather than explaining obvious details.
|
||||
|
||||
=== boost szabályok ===
|
||||
=== boost rules ===
|
||||
|
||||
# Laravel Boost
|
||||
|
||||
## Eszközök
|
||||
## Tools
|
||||
|
||||
- A Laravel Boost egy kifejezetten ehhez az alkalmazáshoz tervezett eszközökkel rendelkező MCP szerver. Preferáld a Boost eszközöket a manuális alternatívákkal szemben, mint a shell parancsok vagy fájlbeolvasások.
|
||||
- Használd a `database-query` eszközt csak olvasható lekérdezések futtatásához az adatbázison, ahelyett, hogy nyers SQL-t írnál a tinkerbe.
|
||||
- Használd a `database-schema` eszközt a táblák szerkezetének vizsgálatához migrációk vagy modellek írása előtt.
|
||||
- Használd a `get-absolute-url` eszközt a projekt URL-jeinek helyes sémájának, domainjének és portjának feloldásához. Mindig használd ezt, mielőtt URL-t osztanál meg a felhasználóval.
|
||||
- Használd a `browser-logs` eszközt a böngésző naplók, hibák és kivételek beolvasásához. Csak a friss naplók hasznosak, hagyd figyelmen kívül a régi bejegyzéseket.
|
||||
- Laravel Boost is an MCP server with tools designed specifically for this application. Prefer Boost tools over manual alternatives like shell commands or file reads.
|
||||
- Use `database-query` to run read-only queries against the database instead of writing raw SQL in tinker.
|
||||
- Use `database-schema` to inspect table structure before writing migrations or models.
|
||||
- Use `get-absolute-url` to resolve the correct scheme, domain, and port for project URLs. Always use this before sharing a URL with the user.
|
||||
- Use `browser-logs` to read browser logs, errors, and exceptions. Only recent logs are useful, ignore old entries.
|
||||
|
||||
## Dokumentáció keresése (FONTOS)
|
||||
## Searching Documentation (IMPORTANT)
|
||||
|
||||
- Kódmódosítás előtt mindig használd a `search-docs` eszközt. Ne hagyd ki ezt a lépést. Ez automatikusan a telepített csomagok alapján ad verzióspecifikus dokumentációt.
|
||||
- Adj át egy `packages` tömböt az eredmények szűkítéséhez, ha tudod, mely csomagok relevánsak.
|
||||
- Használj több széles, téma alapú keresést: `['rate limiting', 'routing rate limiting', 'routing']`. Számíts rá, hogy a legrelevánsabb eredmények lesznek elöl.
|
||||
- Ne adj csomagneveket a kereséshez, mert a csomaginformáció már meg van osztva. Használd a `test resource table` kifejezést, ne a `filament 4 test resource table`-t.
|
||||
- Always use `search-docs` before making code changes. Do not skip this step. It returns version-specific docs based on installed packages automatically.
|
||||
- Pass a `packages` array to scope results when you know which packages are relevant.
|
||||
- Use multiple broad, topic-based queries: `['rate limiting', 'routing rate limiting', 'routing']`. Expect the most relevant results first.
|
||||
- Do not add package names to queries because package info is already shared. Use `test resource table`, not `filament 4 test resource table`.
|
||||
|
||||
### Keresési szintaxis
|
||||
### Search Syntax
|
||||
|
||||
1. Használj szavakat az automatikusan csonkolt ÉS logikához: a `rate limit` találatot ad a "rate" ÉS "limit" szavakra is.
|
||||
2. Használj `"idézőjeles kifejezéseket"` a pontos pozícióillesztéshez: az `"infinite scroll"` megköveteli az egymás melletti szavakat a megadott sorrendben.
|
||||
3. Kombináld a szavakat és kifejezéseket a vegyes kereséshez: `middleware "rate limit"`.
|
||||
4. Használj több keresést a VAGY logikához: `queries=["authentication", "middleware"]`.
|
||||
1. Use words for auto-stemmed AND logic: `rate limit` matches both "rate" AND "limit".
|
||||
2. Use `"quoted phrases"` for exact position matching: `"infinite scroll"` requires adjacent words in order.
|
||||
3. Combine words and phrases for mixed queries: `middleware "rate limit"`.
|
||||
4. Use multiple queries for OR logic: `queries=["authentication", "middleware"]`.
|
||||
|
||||
## Artisan
|
||||
|
||||
- Futtasd az Artisan parancsokat közvetlenül a parancssorból (pl. `php artisan route:list`). Használd a `php artisan list` parancsot az elérhető parancsok felfedezéséhez, és a `php artisan [command] --help` parancsot a paraméterek ellenőrzéséhez.
|
||||
- Vizsgáld meg az útvonalakat a `php artisan route:list` paranccsal. Szűrj: `--method=GET`, `--name=users`, `--path=api`, `--except-vendor`, `--only-vendor`.
|
||||
- Olvass be konfigurációs értékeket pont jelöléssel: `php artisan config:show app.name`, `php artisan config:show database.default`. Vagy olvasd a konfigurációs fájlokat közvetlenül a `config/` könyvtárból.
|
||||
- A környezeti változók ellenőrzéséhez olvasd közvetlenül a `.env` fájlt.
|
||||
- Run Artisan commands directly via the command line (e.g., `php artisan route:list`). Use `php artisan list` to discover available commands and `php artisan [command] --help` to check parameters.
|
||||
- Inspect routes with `php artisan route:list`. Filter with: `--method=GET`, `--name=users`, `--path=api`, `--except-vendor`, `--only-vendor`.
|
||||
- Read configuration values using dot notation: `php artisan config:show app.name`, `php artisan config:show database.default`. Or read config files directly from the `config/` directory.
|
||||
- To check environment variables, read the `.env` file directly.
|
||||
|
||||
## Tinker
|
||||
|
||||
- Futtass PHP kódot az alkalmazás környezetében hibakereséshez és teszteléshez. Ne hozz létre modelleket felhasználói jóváhagyás nélkül, preferáld a factory-kkal ellátott teszteket. Preferáld a meglévő Artisan parancsokat az egyedi tinker kódok helyett.
|
||||
- Mindig használj szimpla idézőjeleket a shell kifejtés megakadályozására: `php artisan tinker --execute 'Your::code();'`
|
||||
- Használj dupla idézőjelet a PHP stringekhez belül: `php artisan tinker --execute 'User::where("active", true)->count();'`
|
||||
- Execute PHP in app context for debugging and testing code. Do not create models without user approval, prefer tests with factories instead. Prefer existing Artisan commands over custom tinker code.
|
||||
- Always use single quotes to prevent shell expansion: `php artisan tinker --execute 'Your::code();'`
|
||||
- Double quotes for PHP strings inside: `php artisan tinker --execute 'User::where("active", true)->count();'`
|
||||
|
||||
=== php szabályok ===
|
||||
=== php rules ===
|
||||
|
||||
# PHP
|
||||
|
||||
- Mindig használj kapcsos zárójeleket a vezérlési szerkezeteknél, még az egysoros törzseknél is.
|
||||
- Használd a PHP 8 konstruktor property promotion-t: `public function __construct(public GitHub $github) { }`. Ne hagyj üres, nulla paraméteres `__construct()` metódusokat, hacsak a konstruktor nem privát.
|
||||
- Használj explicit visszatérési típus deklarációkat és típusjelzéseket minden metódus paraméternél: `function isAccessible(User $user, ?string $path = null): bool`
|
||||
- Használj TitleCase-t az Enum kulcsokhoz: `FavoritePerson`, `BestLake`, `Monthly`.
|
||||
- Preferáld a PHPDoc blokkokat az inline kommentekkel szemben. Csak kivételesen összetett logika esetén adj hozzá inline kommenteket.
|
||||
- Használj array shape típusdefiníciókat a PHPDoc blokkokban.
|
||||
- Always use curly braces for control structures, even for single-line bodies.
|
||||
- Use PHP 8 constructor property promotion: `public function __construct(public GitHub $github) { }`. Do not leave empty zero-parameter `__construct()` methods unless the constructor is private.
|
||||
- Use explicit return type declarations and type hints for all method parameters: `function isAccessible(User $user, ?string $path = null): bool`
|
||||
- Use TitleCase for Enum keys: `FavoritePerson`, `BestLake`, `Monthly`.
|
||||
- Prefer PHPDoc blocks over inline comments. Only add inline comments for exceptionally complex logic.
|
||||
- Use array shape type definitions in PHPDoc blocks.
|
||||
|
||||
=== laravel/core szabályok ===
|
||||
=== laravel/core rules ===
|
||||
|
||||
# Csináld a Laravel Útján
|
||||
# Do Things the Laravel Way
|
||||
|
||||
- Használd a `php artisan make:` parancsokat új fájlok (pl. migrációk, kontrollerek, modellek stb.) létrehozásához. Az elérhető Artisan parancsokat a `php artisan list` paranccsal listázhatod, és a paramétereiket a `php artisan [command] --help` paranccsal ellenőrizheted.
|
||||
- Ha generikus PHP osztályt hozol létre, használd a `php artisan make:class` parancsot.
|
||||
- Minden Artisan parancsnak add át a `--no-interaction` jelzőt a felhasználói beavatkozás nélküli működés érdekében. A helyes működéshez a megfelelő `--options` opciókat is meg kell adnod.
|
||||
- Use `php artisan make:` commands to create new files (i.e. migrations, controllers, models, etc.). You can list available Artisan commands using `php artisan list` and check their parameters with `php artisan [command] --help`.
|
||||
- If you're creating a generic PHP class, use `php artisan make:class`.
|
||||
- Pass `--no-interaction` to all Artisan commands to ensure they work without user input. You should also pass the correct `--options` to ensure correct behavior.
|
||||
|
||||
### Modell létrehozás
|
||||
### Model Creation
|
||||
|
||||
- Új modellek létrehozásakor készíts hozzájuk hasznos factory-kat és seedereket is. Kérdezz rá a felhasználónál, ha másra is szükség van, a `php artisan make:model --help` segítségével ellenőrizve az elérhető opciókat.
|
||||
- When creating new models, create useful factories and seeders for them too. Ask the user if they need any other things, using `php artisan make:model --help` to check the available options.
|
||||
|
||||
## API-k és Eloquent Resource-ok
|
||||
## APIs & Eloquent Resources
|
||||
|
||||
- API-k esetén alapértelmezés szerint használj Eloquent API Resource-okat és API verziózást, hacsak a meglévő API útvonalak nem másképp teszik, ekkor kövesd a meglévő alkalmazáskonvenciót.
|
||||
- For APIs, default to using Eloquent API Resources and API versioning unless existing API routes do not, then you should follow existing application convention.
|
||||
|
||||
## URL generálás
|
||||
## URL Generation
|
||||
|
||||
- Más oldalakra mutató linkek generálásakor preferáld a nevesített útvonalakat és a `route()` függvényt.
|
||||
- When generating links to other pages, prefer named routes and the `route()` function.
|
||||
|
||||
## Tesztelés
|
||||
## Testing
|
||||
|
||||
- Modellek létrehozásakor a tesztekhez használd a modellek factory-jait. Ellenőrizd, hogy a factory rendelkezik-e egyedi állapotokkal (states), amelyeket használni lehet, mielőtt manuálisan állítanád be a modellt.
|
||||
- Faker: Használj olyan metódusokat, mint a `$this->faker->word()` vagy a `fake()->randomDigit()`. Kövesd a meglévő konvenciókat, hogy a `$this->faker`-t vagy a `fake()`-et használd.
|
||||
- Tesztek létrehozásakor használd a `php artisan make:test [opciók] {név}` parancsot funkcionális teszt létrehozásához, és add át a `--unit` jelzőt egységteszt készítéséhez. A legtöbb tesztnek funkcionális tesztnek kell lennie.
|
||||
- When creating models for tests, use the factories for the models. Check if the factory has custom states that can be used before manually setting up the model.
|
||||
- Faker: Use methods such as `$this->faker->word()` or `fake()->randomDigit()`. Follow existing conventions whether to use `$this->faker` or `fake()`.
|
||||
- When creating tests, make use of `php artisan make:test [options] {name}` to create a feature test, and pass `--unit` to create a unit test. Most tests should be feature tests.
|
||||
|
||||
## Vite hiba
|
||||
## Vite Error
|
||||
|
||||
- Ha "Illuminate\Foundation\ViteException: Unable to locate file in Vite manifest" hibát kapsz, futtathatod az `npm run build` parancsot, vagy kérd meg a felhasználót, hogy futtassa az `npm run dev` vagy a `composer run dev` parancsot.
|
||||
- If you receive an "Illuminate\Foundation\ViteException: Unable to locate file in Vite manifest" error, you can run `npm run build` or ask the user to run `npm run dev` or `composer run dev`.
|
||||
|
||||
=== laravel/v12 szabályok ===
|
||||
=== laravel/v12 rules ===
|
||||
|
||||
# Laravel 12
|
||||
|
||||
- KRITIKUS: MINDIG használd a `search-docs` eszközt a verzióspecifikus Laravel dokumentációhoz és frissített kódpéldákhoz.
|
||||
- Ez a projekt a Laravel 10-ről lett frissítve az új, áramvonalasított Laravel fájlstruktúrára való áttérés nélkül.
|
||||
- Ez teljesen rendben van és a Laravel által ajánlott. Kövesd a Laravel 10-ből származó meglévő struktúrát. Nem kell áttérnünk az új Laravel struktúrára, hacsak a felhasználó kifejezetten nem kéri.
|
||||
- CRITICAL: ALWAYS use `search-docs` tool for version-specific Laravel documentation and updated code examples.
|
||||
- This project upgraded from Laravel 10 without migrating to the new streamlined Laravel file structure.
|
||||
- This is perfectly fine and recommended by Laravel. Follow the existing structure from Laravel 10. We do not need to migrate to the new Laravel structure unless the user explicitly requests it.
|
||||
|
||||
## Laravel 10 struktúra
|
||||
## Laravel 10 Structure
|
||||
|
||||
- A middleware-ek jellemzően az `app\Http/Middleware/` mappában, a service providerek pedig az `app\Providers/` mappában találhatók.
|
||||
- Nincs `bootstrap/app.php` alkalmazáskonfiguráció a Laravel 10 struktúrában:
|
||||
- A middleware regisztráció az `app\Http/Kernel.php` fájlban történik.
|
||||
- A kivételkezelés az `app\Exceptions/Handler.php` fájlban található.
|
||||
- A konzol parancsok és az ütemezés az `app\Console/Kernel.php` fájlban vannak regisztrálva.
|
||||
- A sebességkorlátok (rate limits) valószínűleg a `RouteServiceProvider`-ben vagy az `app\Http/Kernel.php`-ban találhatók.
|
||||
- Middleware typically lives in `app\Http/Middleware/` and service providers in `app\Providers/`.
|
||||
- There is no `bootstrap/app.php` application configuration in a Laravel 10 structure:
|
||||
- Middleware registration happens in `app\Http/Kernel.php`
|
||||
- Exception handling is in `app\Exceptions/Handler.php`
|
||||
- Console commands and schedule register in `app\Console/Kernel.php`
|
||||
- Rate limits likely exist in `RouteServiceProvider` or `app\Http/Kernel.php`
|
||||
|
||||
## Adatbázis
|
||||
## Database
|
||||
|
||||
- Oszlop módosításakor a migrációnak tartalmaznia kell az oszlophoz korábban definiált összes attribútumot. Ellenkező esetben azok elvesznek.
|
||||
- A Laravel 12 natívan lehetővé teszi az eager loaded rekordok korlátozását külső csomagok nélkül: `$query->latest()->limit(10);`.
|
||||
- When modifying a column, the migration must include all of the attributes that were previously defined on the column. Otherwise, they will be dropped and lost.
|
||||
- Laravel 12 allows limiting eagerly loaded records natively, without external packages: `$query->latest()->limit(10);`.
|
||||
|
||||
### Modellek
|
||||
### Models
|
||||
|
||||
- A castok beállíthatók és célszerű is beállítani a modell `casts()` metódusában a `$casts` tulajdonság helyett. Kövesd a többi modell meglévő konvencióit.
|
||||
- Casts can and likely should be set in a `casts()` method on a model rather than the `$casts` property. Follow existing conventions from other models.
|
||||
|
||||
=== livewire/core szabályok ===
|
||||
=== livewire/core rules ===
|
||||
|
||||
# Livewire
|
||||
|
||||
- A Livewire lehetővé teszi dinamikus, reaktív felületek építését PHP-ben, JavaScript írása nélkül.
|
||||
- Az Alpine.js-t használhatod kliensoldali interakciókhoz JavaScript keretrendszerek helyett.
|
||||
- Tartsd az állapotot a szerver oldalon, hogy a UI azt tükrözze. Validálj és autorizálj az action-ökben, ahogy a HTTP kéréseknél tennéd.
|
||||
- Livewire allow to build dynamic, reactive interfaces in PHP without writing JavaScript.
|
||||
- You can use Alpine.js for client-side interactions instead of JavaScript frameworks.
|
||||
- Keep state server-side so the UI reflects it. Validate and authorize in actions as you would in HTTP requests.
|
||||
|
||||
=== pest/core szabályok ===
|
||||
=== pest/core rules ===
|
||||
|
||||
## Pest
|
||||
|
||||
- Ez a projekt a Pest-et használja teszteléshez. Hozz létre teszteket: `php artisan make:test --pest {név}`.
|
||||
- Futtasd a teszteket: `php artisan test --compact` vagy szűrj: `php artisan test --compact --filter=tesztNeve`.
|
||||
- NE törölj teszteket jóváhagyás nélkül.
|
||||
- This project uses Pest for testing. Create tests: `php artisan make:test --pest {name}`.
|
||||
- Run tests: `php artisan test --compact` or filter: `php artisan test --compact --filter=testName`.
|
||||
- Do NOT delete tests without approval.
|
||||
|
||||
</laravel-boost-guidelines>
|
||||
|
||||
105
CLAUDE.md
105
CLAUDE.md
@ -1,105 +0,0 @@
|
||||
# CLAUDE.md
|
||||
|
||||
Laravel 12 (PHP 8.4) + Filament 4 + Livewire 3, Pest 3 tesztekkel, MariaDB adatbázison.
|
||||
Fejlesztés Windowson, egyetlen gépen — nincs csapat és nincs CI.
|
||||
|
||||
## Tesztek futtatása
|
||||
|
||||
Teljes suite (~77 mp, 6 processzen):
|
||||
|
||||
```bash
|
||||
php artisan test --parallel
|
||||
```
|
||||
|
||||
Egy tesztre vagy egy fájlra **`--parallel` nélkül** — ott a hat processz bootja tiszta
|
||||
veszteség, a párhuzamos futás lassabb:
|
||||
|
||||
```bash
|
||||
php artisan test --filter="részlet"
|
||||
```
|
||||
|
||||
Hasznos még: `--retry` (előbb a bukott teszteket futtatja, első hibánál megáll) és
|
||||
`--profile` (a 10 leglassabb teszt). A Pest 3.8-ban **nincs** `--dirty` kapcsoló.
|
||||
|
||||
A `tests/Feature/ExampleTest.php` (`GET /` → 302) **régóta bukik**, függetlenül minden
|
||||
más munkától. Egy bukó teszt a teljes suite-on ez, nem regresszió.
|
||||
|
||||
### Adatbázis-védelem
|
||||
|
||||
A `tests/TestCase.php` `setUp()`-ja a `RefreshDatabase` **előtt** ellenőrzi a
|
||||
konfigurált adatbázisnevet, mert a `RefreshDatabase` feltétel nélkül eldobja a
|
||||
táblákat. Az éles `d2d` név azonnali `exit(1)`-et vált ki.
|
||||
|
||||
Elfogadott név: `/^d2dtest(_test_\d+)?$/`. A `_test_N` alak a `--parallel`
|
||||
processzenkénti adatbázisa (a nevet a Laravel `TestDatabases::testDatabase()` adja).
|
||||
**Ezt a mintát ne lazítsd `str_starts_with($db, 'd2d')`-re** — az átengedné az éles
|
||||
adatbázist is.
|
||||
|
||||
A `setUp()` szándékosan hívja meg maga a `ParallelTesting::callSetUpTestCaseCallbacks()`-ot:
|
||||
a Laravel ezt csak akkor futtatná, ha ő hozta létre az alkalmazást, mi viszont előbb
|
||||
bootolunk az ellenőrzés miatt. Enélkül a processzenkénti adatbázis sosem jönne létre,
|
||||
és minden processz ugyanazt az adatbázist migrálná.
|
||||
|
||||
## Gépfüggő beállítások
|
||||
|
||||
**A `mysql` kliensnek a PATH-on kell lennie**, különben az egész teszt-suite elszáll
|
||||
(`MySqlSchemaState.php`). Binárisok: `C:\www\envkit\services\mysql\11.8.2\bin`.
|
||||
|
||||
**`bootstrap/cache/blade-icons.php`** — ez adja az app boot idejének a felét
|
||||
(nélküle 8,2 mp, vele 3,8 mp minden `php artisan` hívás). Gitignore-olt, tehát
|
||||
gépenként kell egyszer:
|
||||
|
||||
```bash
|
||||
php artisan icons:cache
|
||||
```
|
||||
|
||||
Új ikonkészlet vagy ikonokat szállító csomag után újra kell generálni. A
|
||||
`php artisan filament:optimize` **nem** hoz további nyereséget (mérve), viszont
|
||||
elrejtené az újonnan létrehozott Filament resource-okat — ne használd fejlesztés közben.
|
||||
|
||||
## Migrációk és séma dump
|
||||
|
||||
`database/schema/mysql-schema.sql` váltja ki a 103 migráció lefuttatását a teszteknél.
|
||||
**Minden új migráció után újra kell generálni:**
|
||||
|
||||
```bash
|
||||
php artisan schema:dump
|
||||
```
|
||||
|
||||
Ha elmarad, az nem törik el semmit — a Laravel betölti a dumpot, majd a dump utáni
|
||||
migrációkat egyenként lefuttatja rá.
|
||||
|
||||
A dumpot a Laravel csak akkor tölti be, ha a `migrations` tábla **üres**. Az e2e/d2d
|
||||
környezetek, ahol már vannak lefutott migrációk, változatlanul inkrementálisan
|
||||
migrálnak. A `--prune` kapcsolót **ne** használd: az törölné a migrációs fájlokat.
|
||||
|
||||
## A deployment tesztek szerkezete
|
||||
|
||||
`tests/Feature/Deployment/` hat fájlból áll, mert a paratest **fájlonként** osztja szét
|
||||
a munkát — egyetlen nagy fájlból nem tud párhuzamosítani. A felosztás mért időkre van
|
||||
kalibrálva, a leghosszabb fájl ~35 mp.
|
||||
|
||||
Ha új tesztet írsz, a téma szerinti fájlba tedd — de **ha az a fájl 35 mp fölé nőne,
|
||||
bontsd tovább**: a párhuzamos futás faliórája a leghosszabb fájlhoz van kötve.
|
||||
|
||||
A közös segédfüggvények a `DeploymentTestHelpers.php`-ban vannak (nem `*Test.php`, ezért
|
||||
a phpunit nem szedi fel). A temp git repó **processzenként egyszer** épül fel, a tesztek
|
||||
`File::copyDirectory`-val kapnak róla saját másolatot. A takarítás
|
||||
`register_shutdown_function`-ben van, **nem `afterAll()`-ban**: az fájlonként futna le, és
|
||||
a következő teszt-fájl alól húzná ki a mintát.
|
||||
|
||||
## Deploy
|
||||
|
||||
A deploy **kézi fájlmásolással** történik, nem gittel. Emiatt egy „benne van-e már élesben
|
||||
ez a javítás" kérdés **nem válaszolható meg a git állapotából** — a deployolt fájl
|
||||
tartalmát kell megnézni.
|
||||
|
||||
Queue-alapú funkcióknál a fájlmásolás önmagában nem elég: a `queue:work` hosszan futó
|
||||
folyamat, a memóriájában tartja a régi kódot. A sorrend:
|
||||
|
||||
```bash
|
||||
php artisan config:clear && php artisan cache:clear
|
||||
```
|
||||
|
||||
majd a workert futtató service force-restartja (d2d-n `d2d-environment_queue`). A restart
|
||||
a cache ürítés **után** jön, különben a frissen induló worker a régi konfigot töltené be.
|
||||
@ -1,336 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\ProfitCenter;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Monolog\Formatter\LineFormatter;
|
||||
|
||||
class CheckApiLog extends Command
|
||||
{
|
||||
protected $signature = 'app:check-api-log {file? : A storage/logs alatti API log fájl neve (pl. api-2026-07-21.log). Ha nincs megadva, a fájlnév szerint legutolsó api-*.log fájlt választja.}';
|
||||
|
||||
protected $description = 'A storage/logs/api-*.log fájlban szereplő /api/v1/order/unprocessed válaszok ellenőrzése: profit center hooreycaDataActive állapota és a HooreycaVolumen/HooreycaUnitPrice számított mezők helyessége.';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$filePath = $this->resolveLogFile($this->argument('file'));
|
||||
|
||||
if (! $filePath) {
|
||||
$this->error($this->argument('file')
|
||||
? 'A megadott log fájl nem található: storage/logs/'.$this->argument('file')
|
||||
: 'Nem található api-*.log fájl a storage/logs könyvtárban.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$this->info('Elemzett fájl: '.$filePath);
|
||||
|
||||
[$totalQueries, $totalOrders] = $this->preprocess($filePath);
|
||||
|
||||
if ($totalQueries === 0) {
|
||||
$this->warn('Nem található "unprocessed" API válasz (pagination mezővel) ebben a fájlban.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$this->info("Talált lekérdezések (API hívások): {$totalQueries}, összesen {$totalOrders} megrendeléssel.");
|
||||
|
||||
$errorLogPath = $this->errorLogPathFor($filePath);
|
||||
$errorLogger = Log::build([
|
||||
'driver' => 'single',
|
||||
'path' => $errorLogPath,
|
||||
]);
|
||||
|
||||
$formatter = new LineFormatter(null, null, true, true);
|
||||
$formatter->setJsonPrettyPrint(true);
|
||||
foreach ($errorLogger->getLogger()->getHandlers() as $handler) {
|
||||
$handler->setFormatter($formatter);
|
||||
}
|
||||
|
||||
$bar = $this->output->createProgressBar($totalOrders);
|
||||
$bar->start();
|
||||
|
||||
$queryIndex = 0;
|
||||
$queriesWithErrors = 0;
|
||||
$ordersWithErrors = 0;
|
||||
$itemErrorCount = 0;
|
||||
$profitCenterErrorCount = 0;
|
||||
|
||||
$handle = fopen($filePath, 'r');
|
||||
while (($line = fgets($handle)) !== false) {
|
||||
$responseBody = $this->extractUnprocessedResponse($line);
|
||||
if ($responseBody === null) {
|
||||
continue;
|
||||
}
|
||||
$queryIndex++;
|
||||
$queryHasError = false;
|
||||
|
||||
foreach ($responseBody['data'] ?? [] as $order) {
|
||||
$orderErrors = $this->checkProfitCenter($order);
|
||||
if ($orderErrors) {
|
||||
$profitCenterErrorCount++;
|
||||
}
|
||||
|
||||
foreach ($order['items'] ?? [] as $item) {
|
||||
$itemErrors = $this->checkItemCalculations($item);
|
||||
if ($itemErrors) {
|
||||
$itemErrorCount++;
|
||||
foreach ($itemErrors as $err) {
|
||||
$orderErrors[] = 'item id='.($item['id'] ?? '?').': '.$err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($orderErrors) {
|
||||
$ordersWithErrors++;
|
||||
$queryHasError = true;
|
||||
$errorLogger->error('Hibás megrendelés találat', [
|
||||
'sourceQueryIndex' => $queryIndex,
|
||||
'orderId' => $order['id'] ?? null,
|
||||
'errors' => $orderErrors,
|
||||
'order' => $order,
|
||||
]);
|
||||
}
|
||||
|
||||
$bar->advance();
|
||||
}
|
||||
|
||||
if ($queryHasError) {
|
||||
$queriesWithErrors++;
|
||||
}
|
||||
}
|
||||
fclose($handle);
|
||||
|
||||
$bar->finish();
|
||||
$this->newLine(2);
|
||||
|
||||
$this->table(['Metrika', 'Érték'], [
|
||||
['Vizsgált lekérdezések (API hívások) száma', $queryIndex],
|
||||
['Hibát tartalmazó lekérdezések száma', $queriesWithErrors],
|
||||
['Vizsgált megrendelések száma', $totalOrders],
|
||||
['Hibás megrendelések száma', $ordersWithErrors],
|
||||
['Hibás tétel(item) számítás találatok száma', $itemErrorCount],
|
||||
['Profit center hiba találatok száma', $profitCenterErrorCount],
|
||||
]);
|
||||
|
||||
if ($ordersWithErrors > 0) {
|
||||
$this->warn('Hibás rendelések naplózva ide: '.$errorLogPath);
|
||||
} else {
|
||||
$this->info('Nem található hiba.');
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
private function resolveLogFile(?string $file): ?string
|
||||
{
|
||||
$logsDir = storage_path('logs');
|
||||
|
||||
if ($file) {
|
||||
$path = $logsDir.DIRECTORY_SEPARATOR.$file;
|
||||
|
||||
return is_file($path) ? $path : null;
|
||||
}
|
||||
|
||||
$dated = [];
|
||||
foreach (glob($logsDir.DIRECTORY_SEPARATOR.'api-*.log') ?: [] as $path) {
|
||||
if (preg_match('/api-(\d{4}-\d{2}-\d{2})\.log$/', basename($path), $m)) {
|
||||
$dated[$m[1]] = $path;
|
||||
}
|
||||
}
|
||||
|
||||
if (! $dated) {
|
||||
return null;
|
||||
}
|
||||
|
||||
krsort($dated);
|
||||
|
||||
return reset($dated);
|
||||
}
|
||||
|
||||
private function errorLogPathFor(string $filePath): string
|
||||
{
|
||||
$suffix = preg_match('/api-(\d{4}-\d{2}-\d{2})\.log$/', basename($filePath), $m)
|
||||
? $m[1]
|
||||
: now()->format('Y-m-d');
|
||||
|
||||
return storage_path("logs/api-check-errors-{$suffix}.log");
|
||||
}
|
||||
|
||||
private function preprocess(string $filePath): array
|
||||
{
|
||||
$totalQueries = 0;
|
||||
$totalOrders = 0;
|
||||
|
||||
$handle = fopen($filePath, 'r');
|
||||
while (($line = fgets($handle)) !== false) {
|
||||
$responseBody = $this->extractUnprocessedResponse($line);
|
||||
if ($responseBody === null) {
|
||||
continue;
|
||||
}
|
||||
$totalQueries++;
|
||||
$totalOrders += count($responseBody['data'] ?? []);
|
||||
}
|
||||
fclose($handle);
|
||||
|
||||
return [$totalQueries, $totalOrders];
|
||||
}
|
||||
|
||||
/**
|
||||
* Csak a /api/v1/order/unprocessed válaszokat ismeri fel (a "pagination" kulcs csak ott van jelen,
|
||||
* a setProcessed/status válaszokban nincs).
|
||||
*/
|
||||
private function extractUnprocessedResponse(string $line): ?array
|
||||
{
|
||||
if (! str_contains($line, 'API response')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$context = $this->extractBalancedJson($line, 'API response');
|
||||
if ($context === null || ! isset($context['responseBody']) || ! is_array($context['responseBody'])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$body = $context['responseBody'];
|
||||
if (! isset($body['pagination'], $body['data']) || ! is_array($body['data'])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $body;
|
||||
}
|
||||
|
||||
/**
|
||||
* A Monolog sorvégi %context%/%extra% JSON-jából kiszedi az első kapcsos zárójel-pártól
|
||||
* a hozzá tartozó záró zárójelig terjedő, kiegyensúlyozott JSON-t (idézőjelen belüli
|
||||
* kapcsos zárójeleket figyelmen kívül hagyva), hogy a sor végén álló extra tartalom
|
||||
* (pl. üres %extra% tömb) ne zavarja a dekódolást.
|
||||
*/
|
||||
private function extractBalancedJson(string $line, string $marker): ?array
|
||||
{
|
||||
$pos = strpos($line, $marker);
|
||||
if ($pos === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$jsonStart = strpos($line, '{', $pos);
|
||||
if ($jsonStart === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$depth = 0;
|
||||
$inString = false;
|
||||
$escape = false;
|
||||
$end = null;
|
||||
$len = strlen($line);
|
||||
|
||||
for ($i = $jsonStart; $i < $len; $i++) {
|
||||
$ch = $line[$i];
|
||||
if ($escape) {
|
||||
$escape = false;
|
||||
continue;
|
||||
}
|
||||
if ($ch === '\\') {
|
||||
$escape = true;
|
||||
continue;
|
||||
}
|
||||
if ($ch === '"') {
|
||||
$inString = ! $inString;
|
||||
continue;
|
||||
}
|
||||
if ($inString) {
|
||||
continue;
|
||||
}
|
||||
if ($ch === '{') {
|
||||
$depth++;
|
||||
} elseif ($ch === '}') {
|
||||
$depth--;
|
||||
if ($depth === 0) {
|
||||
$end = $i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($end === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$decoded = json_decode(substr($line, $jsonStart, $end - $jsonStart + 1), true);
|
||||
|
||||
return json_last_error() === JSON_ERROR_NONE ? $decoded : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A profit center hooreycaDataActive állapotát a JELENLEGI DB-állapot alapján ellenőrzi
|
||||
* (a log maga nem tartalmazza a nyers flag értékét), és jelzi, ha a válasz tartalma
|
||||
* (profitCenterHooreycaId/profitCenterName jelenléte) nem egyezik a DB jelenlegi állapotával.
|
||||
*/
|
||||
private function checkProfitCenter(array $order): array
|
||||
{
|
||||
$errors = [];
|
||||
$profitCenterId = $order['profit_center_id'] ?? null;
|
||||
$profitCenter = $profitCenterId ? ProfitCenter::withTrashed()->find($profitCenterId) : null;
|
||||
$dbActive = $profitCenter?->hooreycaDataActive;
|
||||
$hasResponseData = ! empty($order['profitCenterHooreycaId']) || ! empty($order['profitCenterName']);
|
||||
|
||||
if (! $profitCenter) {
|
||||
$errors[] = "profit_center_id={$profitCenterId} nem található a DB-ben (törölve vagy soha nem létezett)";
|
||||
} elseif ($profitCenter->trashed()) {
|
||||
$errors[] = "profit_center_id={$profitCenterId} soft-deleted a DB-ben, mégis szerepelt a válaszban";
|
||||
} elseif (! $dbActive) {
|
||||
$errors[] = "profit_center_id={$profitCenterId} hooreycaDataActive JELENLEG nem aktív a DB-ben, mégis szerepelt a válaszban";
|
||||
}
|
||||
|
||||
if ($profitCenter && ! $profitCenter->trashed() && $dbActive && ! $hasResponseData) {
|
||||
$errors[] = "profit_center_id={$profitCenterId} a DB-ben aktív, de a válaszból hiányzik a profitCenterHooreycaId/profitCenterName";
|
||||
}
|
||||
|
||||
return $errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* A HooreycaVolumen/HooreycaUnitPrice mezőket a jelenleg érvényes (OrderController::
|
||||
* convertItemCollectionToHooreycaAPIItems-ben lévő) képlettel újraszámolja a naplózott
|
||||
* nyers mezőkből, és összeveti a naplózott számított értékkel.
|
||||
*/
|
||||
private function checkItemCalculations(array $item): array
|
||||
{
|
||||
$errors = [];
|
||||
$quantity = $item['quantity'] ?? null;
|
||||
$unitMultiplier = $item['unitMultiplier'] ?? null;
|
||||
$hooreycaMultiplier = $item['HooreycaMultiplier'] ?? null;
|
||||
$price = $item['price'] ?? null;
|
||||
$loggedVolumen = $item['HooreycaVolumen'] ?? null;
|
||||
$loggedUnitPrice = $item['HooreycaUnitPrice'] ?? null;
|
||||
|
||||
if ($hooreycaMultiplier === null) {
|
||||
$expectedVolumen = null;
|
||||
$expectedUnitPrice = null;
|
||||
} else {
|
||||
$expectedVolumen = $quantity * $hooreycaMultiplier;
|
||||
$expectedUnitPrice = $expectedVolumen != 0
|
||||
? ($quantity * $unitMultiplier * $price) / $expectedVolumen
|
||||
: null;
|
||||
}
|
||||
|
||||
if (! $this->numbersMatch($expectedVolumen, $loggedVolumen)) {
|
||||
$errors[] = sprintf('HooreycaVolumen eltér: várt=%s, naplózott=%s', json_encode($expectedVolumen), json_encode($loggedVolumen));
|
||||
}
|
||||
if (! $this->numbersMatch($expectedUnitPrice, $loggedUnitPrice)) {
|
||||
$errors[] = sprintf('HooreycaUnitPrice eltér: várt=%s, naplózott=%s', json_encode($expectedUnitPrice), json_encode($loggedUnitPrice));
|
||||
}
|
||||
|
||||
return $errors;
|
||||
}
|
||||
|
||||
private function numbersMatch($expected, $actual, float $epsilon = 0.0001): bool
|
||||
{
|
||||
if ($expected === null || $actual === null) {
|
||||
return $expected === $actual;
|
||||
}
|
||||
|
||||
return abs((float) $expected - (float) $actual) < $epsilon;
|
||||
}
|
||||
}
|
||||
@ -1,59 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Supplier;
|
||||
use App\Models\User;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class MaryKerApiToken extends Command
|
||||
{
|
||||
protected $signature = 'maryker:api-token
|
||||
{--rotate : a korábbi tokenek visszavonása az új kiadása előtt}
|
||||
{--name=maryker-api : a token neve}';
|
||||
|
||||
protected $description = 'Sanctum tokent ad ki a Mary-Ker API-hoz (EV3-461): szerepkör nélküli, a beszállítóhoz kötött felhasználóhoz';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$nameId = config('maryker.supplier_name_id');
|
||||
$supplier = Supplier::where('nameId', $nameId)->first();
|
||||
if (! $supplier) {
|
||||
$this->error("Nincs ilyen betűkódú beszállító: {$nameId}");
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$user = User::where('email', config('maryker.api_user_email'))->first();
|
||||
if ($user && $user->supplier_id !== $supplier->id) {
|
||||
$this->error("A(z) {$user->email} felhasználó nem a(z) {$nameId} beszállítóhoz van kötve (supplier_id: " . var_export($user->supplier_id, true) . '). Nem adok ki tokent.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
// Szerepkört szándékosan nem kap: így a Filament-panelekbe (canAccessPanel) sem léphet be.
|
||||
$user ??= User::create([
|
||||
'name' => "{$supplier->name} API",
|
||||
'email' => config('maryker.api_user_email'),
|
||||
'password' => Hash::make(Str::random(64)),
|
||||
'supplier_id' => $supplier->id,
|
||||
]);
|
||||
|
||||
if ($this->option('rotate')) {
|
||||
$revoked = $user->tokens()->delete();
|
||||
$this->line(" {$revoked} korábbi token visszavonva.");
|
||||
} elseif (($existing = $user->tokens()->count()) > 0) {
|
||||
$this->warn(" Már van {$existing} érvényes token; az újjal együtt mind él (visszavonás: --rotate).");
|
||||
}
|
||||
|
||||
$token = $user->createToken($this->option('name'), [config('maryker.ability')]);
|
||||
|
||||
$this->info("Token kiadva: {$supplier->name} ({$nameId}), felhasználó: {$user->email}");
|
||||
$this->line('A token csak most látható, nem kérhető le újra:');
|
||||
$this->line($token->plainTextToken);
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@ -1,182 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\ProfitCenter;
|
||||
use App\Models\Supplier;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use PhpOffice\PhpSpreadsheet\Cell\DataType;
|
||||
use PhpOffice\PhpSpreadsheet\Spreadsheet;
|
||||
use PhpOffice\PhpSpreadsheet\Style\Alignment;
|
||||
use PhpOffice\PhpSpreadsheet\Style\Fill;
|
||||
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
|
||||
|
||||
class MaryKerDeliveryAddressReport extends Command
|
||||
{
|
||||
protected $signature = 'maryker:delivery-addresses
|
||||
{--supplier=MARY : a beszállító betűkódja (nameId)}
|
||||
{--path= : a kimeneti xlsx útvonala}';
|
||||
|
||||
protected $description = 'Excelt készít a beszállító telephelyeiről és szállítási címeiről (EV3-461, szállítási alegység-azonosító egyeztetéséhez)';
|
||||
|
||||
public const TYPE_BASE = 'alap cím';
|
||||
|
||||
public const TYPE_DELIVERY = 'szállítási cím';
|
||||
|
||||
private const HEADERS = [
|
||||
'Profitcenter ID', 'Név', 'Hooreyca azonosító', 'Betűkód (nameId)', 'Beszállítói vevőkód',
|
||||
'Cím típusa', 'Cím', 'Cím azonosító', 'Cím megnevezése', 'Apolló-kód (kitöltendő)', 'Megjegyzés',
|
||||
];
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$supplier = Supplier::where('nameId', $this->option('supplier'))->first();
|
||||
if (! $supplier) {
|
||||
$this->error('Nincs ilyen betűkódú beszállító: ' . $this->option('supplier'));
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$rows = $this->rows($supplier);
|
||||
|
||||
$path = $this->option('path') ?: storage_path(
|
||||
'app/private/' . strtolower($supplier->nameId) . '_szallitasi_cimek_' . now()->format('Y-m-d') . '.xlsx'
|
||||
);
|
||||
if (! is_dir(dirname($path))) {
|
||||
mkdir(dirname($path), 0775, true);
|
||||
}
|
||||
|
||||
(new Xlsx($this->spreadsheet($supplier, $rows)))->save($path);
|
||||
|
||||
$profitCenters = count(array_unique(array_column($rows, 0)));
|
||||
$deliveryRows = count(array_filter($rows, fn ($row) => $row[5] === self::TYPE_DELIVERY));
|
||||
$warnings = count(array_filter($rows, fn ($row) => $row[10] !== ''));
|
||||
|
||||
$this->info('Elkészült: ' . $path);
|
||||
$this->line(" {$profitCenters} profitcenter, " . count($rows) . " sor, ebből {$deliveryRows} szállítási cím");
|
||||
if ($warnings > 0) {
|
||||
$this->warn(" {$warnings} sorban van megjegyzés (adatrögzítési eltérés), nézd át.");
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Egy sor / profitcenter, vagy ha a profitcenter több szállítási címes, egy sor / cím.
|
||||
* Ugyanazt a szabályt követi, mint a megrendelő felület (OrderController::createParameter):
|
||||
* a "multiAddress" jelző dönt, nem a címrekordok száma.
|
||||
*
|
||||
* @return array<int, array<int, mixed>>
|
||||
*/
|
||||
public function rows(Supplier $supplier): array
|
||||
{
|
||||
$profitCenters = $supplier->profitCenter()
|
||||
->with(['address' => fn ($query) => $query->orderBy('id'), 'supplierCustomerCodes'])
|
||||
->orderBy('name')
|
||||
->get();
|
||||
|
||||
$rows = [];
|
||||
foreach ($profitCenters as $profitCenter) {
|
||||
$head = [
|
||||
$profitCenter->id,
|
||||
$profitCenter->name,
|
||||
(string) $profitCenter->hooreycaId,
|
||||
(string) $profitCenter->nameId,
|
||||
(string) $profitCenter->supplierCustomerCodes->firstWhere('supplier_id', $supplier->id)?->customerCode,
|
||||
];
|
||||
foreach ($this->addressRows($profitCenter) as $addressRow) {
|
||||
$rows[] = array_merge($head, $addressRow);
|
||||
}
|
||||
}
|
||||
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, array{0: string, 1: string, 2: string, 3: string, 4: string, 5: string}>
|
||||
* [típus, cím, cím azonosító, cím megnevezése, Apolló-kód, megjegyzés]
|
||||
*/
|
||||
private function addressRows(ProfitCenter $profitCenter): array
|
||||
{
|
||||
$addresses = $profitCenter->address;
|
||||
|
||||
if ((bool) $profitCenter->multiAddress) {
|
||||
if ($addresses->isEmpty()) {
|
||||
return [[self::TYPE_DELIVERY, '', '', '', '', 'A több szállítási cím be van kapcsolva, de nincs szállítási cím rögzítve.']];
|
||||
}
|
||||
|
||||
return $addresses->map(fn ($address) => [
|
||||
self::TYPE_DELIVERY, $address->fullAddress, (string) $address->id, (string) $address->name, '', '',
|
||||
])->all();
|
||||
}
|
||||
|
||||
if ((bool) $profitCenter->addressEqual) {
|
||||
$extra = $addresses->count();
|
||||
|
||||
return [[self::TYPE_BASE, $profitCenter->fullAddress, '', '', '', $extra > 0
|
||||
? "A telephely címe az alap cím, de {$extra} további címrekord is van rögzítve - ezek a megrendelő felületen nem jelennek meg."
|
||||
: '']];
|
||||
}
|
||||
|
||||
$first = $addresses->first();
|
||||
if (! $first) {
|
||||
return [[self::TYPE_BASE, '', '', '', '', 'Az alap cím nem egyezik a telephely címével, de nincs címrekord rögzítve.']];
|
||||
}
|
||||
|
||||
return [[self::TYPE_BASE, $first->fullAddress, (string) $first->id, (string) $first->name, '', $addresses->count() > 1
|
||||
? 'Több címrekord van rögzítve, de a megrendelő felületen csak az első jelenik meg.'
|
||||
: '']];
|
||||
}
|
||||
|
||||
private function spreadsheet(Supplier $supplier, array $rows): Spreadsheet
|
||||
{
|
||||
$spreadsheet = new Spreadsheet();
|
||||
$sheet = $spreadsheet->getActiveSheet();
|
||||
$sheet->setTitle('Szállítási címek');
|
||||
|
||||
$sheet->setCellValue('A1', $supplier->name . ' - telephelyek és szállítási címek');
|
||||
$sheet->getStyle('A1')->getFont()->setBold(true)->setSize(16);
|
||||
$sheet->setCellValue('A2', 'EV3-461 · Adatforrás: ' . DB::connection()->getDatabaseName()
|
||||
. ' adatbázis · Készült: ' . now()->format('Y-m-d H:i'));
|
||||
$sheet->setCellValue('A3', 'Ahol a telephelynek több szállítási címe van, címenként egy sor szerepel. '
|
||||
. 'A sárga "Apolló-kód" oszlopot a Multi.hu tölti ki a cím azonosítója mellé.');
|
||||
|
||||
$headerRow = 5;
|
||||
foreach (self::HEADERS as $index => $text) {
|
||||
$sheet->setCellValueByColumnAndRow($index + 1, $headerRow, $text);
|
||||
}
|
||||
$range = 'A' . $headerRow . ':K' . $headerRow;
|
||||
$sheet->getStyle($range)->getFont()->setBold(true)->getColor()->setARGB('FFFFFFFF');
|
||||
$sheet->getStyle($range)->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB('FF44546A');
|
||||
$sheet->getStyle($range)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_CENTER);
|
||||
|
||||
$row = $headerRow;
|
||||
foreach ($rows as $values) {
|
||||
$row++;
|
||||
foreach ($values as $index => $value) {
|
||||
// Szövegként írjuk (vevőkód, betűkód): az Excel ne vágja le a vezető nullákat.
|
||||
$sheet->setCellValueExplicitByColumnAndRow(
|
||||
$index + 1,
|
||||
$row,
|
||||
$value,
|
||||
is_int($value) ? DataType::TYPE_NUMERIC : DataType::TYPE_STRING
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if ($row > $headerRow) {
|
||||
$sheet->getStyle('J' . ($headerRow + 1) . ':J' . $row)->getFill()
|
||||
->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB('FFFFF2CC');
|
||||
$sheet->getStyle('K' . ($headerRow + 1) . ':K' . $row)->getFont()->getColor()->setARGB('FF9C5700');
|
||||
}
|
||||
|
||||
foreach (['A' => 12, 'B' => 38, 'C' => 18, 'D' => 16, 'E' => 18, 'F' => 15, 'G' => 44, 'H' => 14, 'I' => 30, 'J' => 22, 'K' => 60] as $column => $width) {
|
||||
$sheet->getColumnDimension($column)->setWidth($width);
|
||||
}
|
||||
$sheet->freezePane('A' . ($headerRow + 1));
|
||||
$sheet->setAutoFilter($range);
|
||||
|
||||
return $spreadsheet;
|
||||
}
|
||||
}
|
||||
@ -35,16 +35,6 @@ public function handle(PricelistFileProcessService $service): int
|
||||
return 1;
|
||||
}
|
||||
|
||||
// A konzolos indítás ugyanúgy a termékadatokat érinti, mint a felületi - a
|
||||
// beszállítói blokkolás itt sem kerülhető meg.
|
||||
$guard = app(\App\Services\PricelistGuard::class);
|
||||
|
||||
if ($blockingFile = $guard->blockingFileFor($pricelistFile->supplier_id, $pricelistFile->id)) {
|
||||
$this->error($guard->blockingMessage($blockingFile));
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
$this->info("Folyamat elindítása: {$pricelistFile->filename} (ID: {$id})");
|
||||
$this->info("Workflow állapotok alaphelyzetbe állítása...");
|
||||
|
||||
|
||||
@ -1,269 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Enums\DbStatusFieldEnum;
|
||||
use App\Models\Producer;
|
||||
use App\Models\ProducerAlias;
|
||||
use App\Support\NameNormalizer;
|
||||
use App\Support\ProducerAliasResolver;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Visszamenőleges alias-feltöltés a már lezajlott EV3-357 gyártó-összevonásokból.
|
||||
*
|
||||
* Két forrásból dolgozik:
|
||||
*
|
||||
* 1. Az archivált gyártók `note` mezője ("Összevonva ide: #<id> (...)") - ez MINDIG
|
||||
* a jelenlegi adatbázis saját, konzisztens ID-ire mutat, láncolást igényelhet
|
||||
* (egy 1. körös célrekord a 2. körben maga is beolvadhatott).
|
||||
* 2. A producers:dedupe --report kimeneteként keletkezett JSON jelentések (a döntési
|
||||
* lapok, EV3-357 ticket-mappa). FONTOS: ezekben az ID-k környezetenként (fejlesztői/
|
||||
* d2d/éles) eltérnek, ezért a feloldás NÉVALAPÚ - a jelentés `final_name` mezőjét
|
||||
* a jelenlegi adatbázis aktív gyártói között normalizált egyezéssel keressük meg.
|
||||
*/
|
||||
class ProducersAliasBackfill extends Command
|
||||
{
|
||||
protected $signature = 'producers:alias-backfill
|
||||
{reports?* : dedupe-jelentés JSON fájl(ok) útvonala (producers:dedupe --report kimenete)}
|
||||
{--skip-archives : az archivált gyártók note mezejének feldolgozásának kihagyása}
|
||||
{--apply : ténylegesen beszúrja az aliasokat (alapértelmezés: csak kimutatás)}';
|
||||
|
||||
protected $description = 'Alias rekordok visszamenőleges feltöltése a korábbi gyártó-összevonásokból';
|
||||
|
||||
public function handle(ProducerAliasResolver $resolver): int
|
||||
{
|
||||
$candidates = [];
|
||||
|
||||
if (! $this->option('skip-archives')) {
|
||||
$candidates = array_merge($candidates, $this->collectFromArchivedProducers());
|
||||
}
|
||||
|
||||
foreach ($this->argument('reports') as $path) {
|
||||
$candidates = array_merge($candidates, $this->collectFromReport($path));
|
||||
}
|
||||
|
||||
if ($candidates === []) {
|
||||
$this->info('Nincs feldolgozandó jelölt.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
[$toInsert, $alreadyExists, $conflicts] = $this->classify($resolver, $candidates);
|
||||
|
||||
$this->summarize($toInsert, $alreadyExists, $conflicts);
|
||||
|
||||
if (! $this->option('apply')) {
|
||||
$this->newLine();
|
||||
$this->info('Ez csak kimutatás volt. A végrehajtáshoz: --apply');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
DB::transaction(function () use ($toInsert) {
|
||||
foreach ($toInsert as $row) {
|
||||
ProducerAlias::create([
|
||||
'producer_id' => $row['producer_id'],
|
||||
'name' => $row['name'],
|
||||
'normalized_name' => NameNormalizer::normalize($row['name']),
|
||||
'source' => 'backfill',
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
$this->newLine();
|
||||
$this->info(count($toInsert) . ' alias létrehozva.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, array{producer_id: int, name: string, origin: string}>
|
||||
*/
|
||||
private function collectFromArchivedProducers(): array
|
||||
{
|
||||
$candidates = [];
|
||||
|
||||
$archived = Producer::query()->where('status', DbStatusFieldEnum::archive)->get(['id', 'name', 'note']);
|
||||
|
||||
foreach ($archived as $producer) {
|
||||
$visited = [];
|
||||
$keeperId = $this->resolveActiveKeeperId($producer->id, $visited);
|
||||
|
||||
if ($keeperId === null) {
|
||||
$this->warn(" ! #{$producer->id} (\"{$producer->name}\") note-ja nem oldható fel aktív gyártóra.");
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$candidates[] = [
|
||||
'producer_id' => $keeperId,
|
||||
'name' => (string) $producer->name,
|
||||
'origin' => "archív #{$producer->id}",
|
||||
];
|
||||
}
|
||||
|
||||
return $candidates;
|
||||
}
|
||||
|
||||
/**
|
||||
* Egy archivált rekord note-jából kiolvassa a célrekordot, és ha az maga is
|
||||
* archivált (2. körben tovább olvadt), a láncot az aktuális aktív rekordig követi.
|
||||
*/
|
||||
private function resolveActiveKeeperId(int $id, array &$visited): ?int
|
||||
{
|
||||
if (isset($visited[$id])) {
|
||||
return null; // ciklusvédelem
|
||||
}
|
||||
$visited[$id] = true;
|
||||
|
||||
$producer = Producer::find($id);
|
||||
|
||||
if (! $producer) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (! in_array($producer->status, [DbStatusFieldEnum::archive, DbStatusFieldEnum::deleted], true)) {
|
||||
return $producer->id;
|
||||
}
|
||||
|
||||
if (! preg_match('/Összevonva ide:\s*#(\d+)/u', (string) $producer->note, $matches)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->resolveActiveKeeperId((int) $matches[1], $visited);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, array{producer_id: int, name: string, origin: string}>
|
||||
*/
|
||||
private function collectFromReport(string $path): array
|
||||
{
|
||||
if (! is_file($path)) {
|
||||
$this->error("A jelentésfájl nem található: {$path}");
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
$report = json_decode((string) file_get_contents($path), true);
|
||||
|
||||
if (! is_array($report) || ! isset($report['merges'])) {
|
||||
$this->error("A fájl nem érvényes producers:dedupe jelentés: {$path}");
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
$activeByNormalized = $this->activeProducersByNormalizedName();
|
||||
$restoreProducers = $report['restore']['producers'] ?? [];
|
||||
$candidates = [];
|
||||
|
||||
foreach ($report['merges'] as $merge) {
|
||||
$finalName = (string) ($merge['final_name'] ?? '');
|
||||
$targetId = $activeByNormalized[NameNormalizer::normalize($finalName)] ?? null;
|
||||
|
||||
if ($targetId === null) {
|
||||
$this->warn(" ! \"{$finalName}\" ({$path}) nem található aktív gyártóként ebben a környezetben.");
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$names = array_column($merge['from'] ?? [], 'name');
|
||||
|
||||
// A jelentésben a keeper eredeti (átnevezés előtti) neve csak a
|
||||
// restore.producers pillanatképben maradt meg - a merges tömb nem
|
||||
// tartalmazza.
|
||||
$keeperOriginalName = $restoreProducers[$merge['keeper_id']]['name'] ?? null;
|
||||
if ($keeperOriginalName !== null) {
|
||||
$names[] = (string) $keeperOriginalName;
|
||||
}
|
||||
|
||||
foreach (array_unique($names) as $name) {
|
||||
if (NameNormalizer::normalize($name) === NameNormalizer::normalize($finalName)) {
|
||||
continue; // ugyanaz, mint az élő név - felesleges alias lenne
|
||||
}
|
||||
|
||||
$candidates[] = [
|
||||
'producer_id' => $targetId,
|
||||
'name' => $name,
|
||||
'origin' => basename($path),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $candidates;
|
||||
}
|
||||
|
||||
private function activeProducersByNormalizedName(): array
|
||||
{
|
||||
return Producer::query()
|
||||
->whereNotIn('status', [DbStatusFieldEnum::archive, DbStatusFieldEnum::deleted])
|
||||
->get(['id', 'name'])
|
||||
->keyBy(fn ($p) => NameNormalizer::normalize($p->name))
|
||||
->map->id
|
||||
->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Szétválogatja a jelölteket: mit kell beszúrni, mi van már fent (idempotencia -
|
||||
* a parancs többször is lefuttatható ugyanazokkal a bemenetekkel), és mi ütközik.
|
||||
*
|
||||
* @return array{0: array, 1: array, 2: array}
|
||||
*/
|
||||
private function classify(ProducerAliasResolver $resolver, array $candidates): array
|
||||
{
|
||||
$toInsert = [];
|
||||
$alreadyExists = [];
|
||||
$conflicts = [];
|
||||
$seen = []; // normalized_name => true, hogy egy futáson belül ne duplázzunk
|
||||
|
||||
foreach ($candidates as $candidate) {
|
||||
$normalized = NameNormalizer::normalize($candidate['name']);
|
||||
|
||||
if (isset($seen[$normalized])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$existing = ProducerAlias::where('normalized_name', $normalized)
|
||||
->where('producer_id', $candidate['producer_id'])
|
||||
->exists();
|
||||
|
||||
if ($existing) {
|
||||
$alreadyExists[] = $candidate;
|
||||
$seen[$normalized] = true;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$resolver->assertNameAvailable($candidate['name'], $candidate['producer_id']);
|
||||
$toInsert[] = $candidate;
|
||||
} catch (RuntimeException $e) {
|
||||
$conflicts[] = $candidate + ['reason' => $e->getMessage()];
|
||||
}
|
||||
|
||||
$seen[$normalized] = true;
|
||||
}
|
||||
|
||||
return [$toInsert, $alreadyExists, $conflicts];
|
||||
}
|
||||
|
||||
private function summarize(array $toInsert, array $alreadyExists, array $conflicts): void
|
||||
{
|
||||
if ($toInsert !== []) {
|
||||
$this->table(
|
||||
['Forrás', 'Név', 'Célrekord'],
|
||||
array_map(fn ($c) => [$c['origin'], $c['name'], '#' . $c['producer_id']], $toInsert)
|
||||
);
|
||||
}
|
||||
|
||||
$this->line('Beszúrandó: ' . count($toInsert)
|
||||
. ' | már megvan: ' . count($alreadyExists)
|
||||
. ' | ütközés: ' . count($conflicts));
|
||||
|
||||
foreach ($conflicts as $conflict) {
|
||||
$this->warn(" ! \"{$conflict['name']}\" ({$conflict['origin']}): {$conflict['reason']}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,268 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Services\ProducerDeduplicator;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use PhpOffice\PhpSpreadsheet\IOFactory;
|
||||
|
||||
class ProducersDedupe extends Command
|
||||
{
|
||||
protected $signature = 'producers:dedupe
|
||||
{file? : a kitöltött döntési lap (producers:dedupe-report kimenete)}
|
||||
{--apply : ténylegesen végrehajtja az összevonást (alapértelmezés: csak kimutatás)}
|
||||
{--report= : hova írja a jelentést (ez a visszagörgetés bemenete)}
|
||||
{--rollback= : egy korábbi jelentés visszagörgetése}
|
||||
{--force : megerősítő kérdések nélkül fut (szkriptelt futtatáshoz)}';
|
||||
|
||||
protected $description = 'Duplikált gyártó rekordok összevonása a kitöltött döntési lap alapján';
|
||||
|
||||
public function handle(ProducerDeduplicator $deduplicator): int
|
||||
{
|
||||
if ($rollbackPath = $this->option('rollback')) {
|
||||
return $this->rollback($deduplicator, $rollbackPath);
|
||||
}
|
||||
|
||||
$file = $this->argument('file');
|
||||
|
||||
if (! $file || ! is_file($file)) {
|
||||
$this->error('Add meg a kitöltött döntési lapot. Ha még nincs: php artisan producers:dedupe-report');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$decisions = $this->readDecisions($file);
|
||||
|
||||
if ($decisions === []) {
|
||||
$this->error('A lapon nem találtam feldolgozható sort. Megvan az "'
|
||||
. ProducersDedupeReport::COLUMN_ID . '" oszlop a fejlécben?');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$plan = $deduplicator->buildPlan($decisions);
|
||||
$merges = $plan['merges'];
|
||||
$errors = $plan['errors'];
|
||||
|
||||
foreach ($errors as $error) {
|
||||
$this->warn(' ! ' . $error);
|
||||
}
|
||||
|
||||
// Az üres végleges név a bizonytalan javaslatok elutasításának módja - nem hiba,
|
||||
// de kiírjuk, hogy egy véletlen kihagyás se maradjon észrevétlen.
|
||||
foreach ($plan['skipped'] ?? [] as $skip) {
|
||||
$this->line(' - kimarad a(z) ' . $skip['group'] . '. csoport (nincs végleges név): '
|
||||
. implode(' / ', array_map(fn ($n) => '"' . $n . '"', $skip['names'])));
|
||||
}
|
||||
|
||||
if ($merges === []) {
|
||||
$this->error('Nincs végrehajtható összevonás.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$this->summarize($merges);
|
||||
|
||||
// A névütközés blokkoló: a végrehajtás duplikátumot állítana elő. A --force sem
|
||||
// kerüli meg - a lapot kell javítani.
|
||||
if (($plan['blocking'] ?? []) !== []) {
|
||||
$this->newLine();
|
||||
foreach ($plan['blocking'] as $blocking) {
|
||||
$this->error(' BLOKKOLÓ: ' . $blocking);
|
||||
}
|
||||
$this->error('A végrehajtás blokkolva, amíg a döntési lap nincs javítva.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
if (! $this->option('apply')) {
|
||||
$this->newLine();
|
||||
$this->info('Ez csak kimutatás volt. A végrehajtáshoz: --apply');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
if ($errors !== [] && ! $this->confirmed('Voltak figyelmeztetések. Biztosan folytatod?')) {
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$database = DB::connection()->getDatabaseName();
|
||||
if (! $this->confirmed("Végrehajtás a(z) '{$database}' adatbázison. Folytatod?")) {
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$report = $deduplicator->apply($merges);
|
||||
$reportPath = $this->writeReport($report);
|
||||
|
||||
$this->newLine();
|
||||
$this->info('Az összevonás megtörtént.');
|
||||
foreach ($report['totals'] as $table => $count) {
|
||||
$this->line(' ' . str_pad($table, 24) . number_format($count) . ' sor átírva');
|
||||
}
|
||||
$this->line(' ' . str_pad('alias', 24) . count($report['restore']['created_alias_ids'] ?? []) . ' létrehozva');
|
||||
foreach ($report['alias_warnings'] ?? [] as $warning) {
|
||||
$this->warn(' ! alias kihagyva: ' . $warning);
|
||||
}
|
||||
$this->line(' Jelentés: ' . $reportPath);
|
||||
$this->newLine();
|
||||
$this->comment('Visszagörgetés: php artisan producers:dedupe --rollback="' . $reportPath . '"');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Megerősítés, --force esetén kérdés nélkül.
|
||||
*/
|
||||
private function confirmed(string $question): bool
|
||||
{
|
||||
return $this->option('force') || $this->confirm($question, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* A lap fejlécnév alapján olvasódik, nem oszlopbetű szerint: a megrendelő
|
||||
* beszúrhat oszlopot vagy átrendezheti a lapot anélkül, hogy ez eltörne.
|
||||
*
|
||||
* @return array<int, array{group: mixed, id: int, final_name: ?string}>
|
||||
*/
|
||||
private function readDecisions(string $file): array
|
||||
{
|
||||
$sheet = IOFactory::load($file)->getActiveSheet();
|
||||
$highestRow = $sheet->getHighestDataRow();
|
||||
$highestColumn = $sheet->getHighestDataColumn();
|
||||
$columnCount = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);
|
||||
|
||||
$headerRow = null;
|
||||
$columns = [];
|
||||
|
||||
for ($row = 1; $row <= min($highestRow, 30); $row++) {
|
||||
for ($column = 1; $column <= $columnCount; $column++) {
|
||||
$value = trim((string) $sheet->getCellByColumnAndRow($column, $row)->getValue());
|
||||
|
||||
if ($value === ProducersDedupeReport::COLUMN_ID) {
|
||||
$headerRow = $row;
|
||||
}
|
||||
}
|
||||
|
||||
if ($headerRow !== null) {
|
||||
for ($column = 1; $column <= $columnCount; $column++) {
|
||||
$value = trim((string) $sheet->getCellByColumnAndRow($column, $headerRow)->getValue());
|
||||
if ($value !== '') {
|
||||
$columns[$value] = $column;
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if ($headerRow === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$idColumn = $columns[ProducersDedupeReport::COLUMN_ID] ?? null;
|
||||
$groupColumn = $columns[ProducersDedupeReport::COLUMN_GROUP] ?? null;
|
||||
$nameColumn = $columns[ProducersDedupeReport::COLUMN_FINAL_NAME] ?? null;
|
||||
|
||||
if (! $idColumn || ! $nameColumn) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$decisions = [];
|
||||
|
||||
for ($row = $headerRow + 1; $row <= $highestRow; $row++) {
|
||||
$id = (int) $sheet->getCellByColumnAndRow($idColumn, $row)->getValue();
|
||||
|
||||
if ($id <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$decisions[] = [
|
||||
'group' => $groupColumn ? $sheet->getCellByColumnAndRow($groupColumn, $row)->getValue() : null,
|
||||
'id' => $id,
|
||||
'final_name' => trim((string) $sheet->getCellByColumnAndRow($nameColumn, $row)->getValue()),
|
||||
];
|
||||
}
|
||||
|
||||
return $decisions;
|
||||
}
|
||||
|
||||
private function summarize(array $merges): void
|
||||
{
|
||||
$rows = [];
|
||||
$totals = ['products' => 0, 'order_archives_items' => 0, 'pricelist_file_lines' => 0];
|
||||
|
||||
foreach ($merges as $merge) {
|
||||
foreach ($merge['from'] as $from) {
|
||||
foreach ($totals as $key => $value) {
|
||||
$totals[$key] += $from['counts'][$key];
|
||||
}
|
||||
|
||||
$rows[] = [
|
||||
'"' . $from['name'] . '"',
|
||||
'→ #' . $merge['keeper_id'] . ' "' . $merge['final_name'] . '"'
|
||||
. ($merge['rename'] ? ' (átnevezés)' : ''),
|
||||
number_format($from['counts']['products']),
|
||||
number_format($from['counts']['order_archives_items']),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
$this->table(['Beolvasztandó', 'Célrekord', 'Termék', 'Rendelési tétel'], $rows);
|
||||
|
||||
$this->line('Csoport: ' . count($merges)
|
||||
. ' | beolvasztandó rekord: ' . array_sum(array_map(fn ($m) => count($m['from']), $merges)));
|
||||
$this->line('Átírandó sorok: products ' . number_format($totals['products'])
|
||||
. ' · order_archives_items ' . number_format($totals['order_archives_items'])
|
||||
. ' · pricelist_file_lines ' . number_format($totals['pricelist_file_lines']));
|
||||
}
|
||||
|
||||
private function writeReport(array $report): string
|
||||
{
|
||||
return app(ProducerDeduplicator::class)->writeReport($report, $this->option('report') ?: null);
|
||||
}
|
||||
|
||||
private function rollback(ProducerDeduplicator $deduplicator, string $path): int
|
||||
{
|
||||
if (! is_file($path)) {
|
||||
$this->error('A jelentésfájl nem található: ' . $path);
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$report = json_decode((string) file_get_contents($path), true);
|
||||
|
||||
if (! is_array($report) || ! isset($report['restore'])) {
|
||||
$this->error('A fájl nem érvényes producers:dedupe jelentés.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$database = DB::connection()->getDatabaseName();
|
||||
|
||||
if (($report['database'] ?? null) !== $database) {
|
||||
$this->warn('A jelentés a(z) "' . ($report['database'] ?? '?')
|
||||
. '" adatbázisról készült, most viszont "' . $database . '" az aktív.');
|
||||
|
||||
if (! $this->confirmed('Biztosan folytatod?')) {
|
||||
return self::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
$this->line('Visszagörgetés: ' . count($report['merges'] ?? []) . ' összevonás ('
|
||||
. ($report['created_at'] ?? '?') . ')');
|
||||
|
||||
if (! $this->confirmed("Visszagörgetés a(z) '{$database}' adatbázison. Folytatod?")) {
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$restored = $deduplicator->rollback($report);
|
||||
|
||||
$this->info('Visszagörgetve.');
|
||||
foreach ($restored as $table => $count) {
|
||||
$this->line(' ' . str_pad($table, 24) . number_format($count) . ' sor visszaállítva');
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@ -1,291 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Services\ProducerDeduplicator;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use PhpOffice\PhpSpreadsheet\Cell\DataType;
|
||||
use PhpOffice\PhpSpreadsheet\Spreadsheet;
|
||||
use PhpOffice\PhpSpreadsheet\Style\Alignment;
|
||||
use PhpOffice\PhpSpreadsheet\Style\Border;
|
||||
use PhpOffice\PhpSpreadsheet\Style\Fill;
|
||||
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
|
||||
|
||||
class ProducersDedupeReport extends Command
|
||||
{
|
||||
protected $signature = 'producers:dedupe-report
|
||||
{--path= : a kimeneti xlsx útvonala}
|
||||
{--loose : a bizonytalan jelöltek is kerüljenek a lapra (elírás, kötőjel, egybeírás, ékezet)}';
|
||||
|
||||
protected $description = 'Döntési lapot készít a duplikált gyártónevekről (a producers:dedupe bemenete)';
|
||||
|
||||
/**
|
||||
* A lap oszlopai. A producers:dedupe FEJLÉCNÉV alapján olvassa vissza, nem
|
||||
* oszlopbetű szerint - így a megrendelő beszúrhat oszlopot vagy átrendezheti a
|
||||
* lapot anélkül, hogy a beolvasás eltörne.
|
||||
*/
|
||||
public const COLUMN_GROUP = 'Csoport';
|
||||
|
||||
public const COLUMN_ID = 'Azonosító';
|
||||
|
||||
public const COLUMN_FINAL_NAME = 'VÉGLEGES NÉV (kitöltendő)';
|
||||
|
||||
private const TYPE_CERTAIN = 'biztos';
|
||||
|
||||
public function handle(ProducerDeduplicator $deduplicator): int
|
||||
{
|
||||
$certain = $deduplicator->duplicateGroups();
|
||||
$loose = $this->option('loose') ? $deduplicator->looseCandidateGroups() : [];
|
||||
|
||||
if ($certain === [] && $loose === []) {
|
||||
$this->info('Nincs duplikált gyártónév ebben az adatbázisban.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$path = $this->option('path') ?: storage_path(
|
||||
'app/private/gyarto_duplikaciok_' . now()->format('Y-m-d') . '.xlsx'
|
||||
);
|
||||
|
||||
$spreadsheet = new Spreadsheet();
|
||||
$sheet = $spreadsheet->getActiveSheet();
|
||||
$sheet->setTitle('Gyártó duplikációk');
|
||||
|
||||
$this->writeIntro($sheet, $loose !== []);
|
||||
$headerRow = 9;
|
||||
$this->writeHeader($sheet, $headerRow);
|
||||
$lastRow = $this->writeGroups($sheet, $headerRow, $certain, $loose);
|
||||
$this->finishLayout($sheet, $headerRow, $lastRow, $certain, $loose);
|
||||
|
||||
$directory = dirname($path);
|
||||
if (! is_dir($directory)) {
|
||||
mkdir($directory, 0775, true);
|
||||
}
|
||||
|
||||
(new Xlsx($spreadsheet))->save($path);
|
||||
|
||||
$this->info('Döntési lap elkészült: ' . $path);
|
||||
$this->line(' Biztos duplikáció: ' . count($certain) . ' csoport, '
|
||||
. array_sum(array_map('count', $certain)) . ' rekord');
|
||||
|
||||
if ($this->option('loose')) {
|
||||
$this->line(' Ellenőrizendő javaslat: ' . count($loose) . ' csoport, '
|
||||
. array_sum(array_map('count', $loose)) . ' rekord');
|
||||
} else {
|
||||
$this->comment(' A bizonytalan jelöltekhez (elírás, kötőjel, egybeírás, ékezet): --loose');
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
private function writeIntro($sheet, bool $hasLoose): void
|
||||
{
|
||||
$sheet->setCellValue('A1', 'Gyártó nevek összevonása – döntési lap');
|
||||
$sheet->getStyle('A1')->getFont()->setBold(true)->setSize(16);
|
||||
$sheet->setCellValue('A2', 'EV3-357 · Árlista feltöltés és feldolgozás újragondolása');
|
||||
$sheet->setCellValue('A3', 'Adatforrás: ' . DB::connection()->getDatabaseName()
|
||||
. ' adatbázis · Készült: ' . now()->format('Y-m-d H:i'));
|
||||
|
||||
$sheet->setCellValue('A5', 'A rendszerben ugyanaz a gyártó több néven is szerepel – például '
|
||||
. '"Danone" és "Danone " egy záró szóközzel, "Békás Kft." és "Békás Kft", vagy '
|
||||
. '"Gast Food" és "Gast-Food". Ez két gondot okoz: az árlista feldolgozó valódi változás '
|
||||
. 'nélkül is módosulást jelez, a statisztikában pedig egy gyártóra szűrve a másik név alá '
|
||||
. 'könyvelt tételek kimaradnak a riportból.');
|
||||
$sheet->mergeCells('A5:J5');
|
||||
$sheet->getStyle('A5')->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
|
||||
$sheet->getRowDimension(5)->setRowHeight(46);
|
||||
|
||||
$sheet->setCellValue('A6', 'TEENDŐ: minden csoportnál töltsd ki a sárga "VÉGLEGES NÉV" mezőt – ez lesz '
|
||||
. 'a megmaradó, egységes név. A többi név nem vész el: összevonjuk őket a véglegesbe, a '
|
||||
. 'termékek és a rendelési előzmények megmaradnak. Az "Azonosító" oszlopot kérjük ne módosítsd.');
|
||||
$sheet->mergeCells('A6:J6');
|
||||
$sheet->getStyle('A6')->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
|
||||
$sheet->getStyle('A6')->getFont()->setBold(true);
|
||||
$sheet->getRowDimension(6)->setRowHeight(46);
|
||||
|
||||
if ($hasLoose) {
|
||||
$sheet->setCellValue('A7', 'A "Típus" oszlop megmutatja, miben térnek el a nevek – így kötegelve '
|
||||
. 'tudsz haladni. A "' . ProducerDeduplicator::DIFF_PUNCTUATION . '" csoportoknál csak pont, '
|
||||
. 'kötőjel vagy vessző a különbség ("Békás Kft." és "Békás Kft"), ott már beírtuk a '
|
||||
. 'javaslatot. A többinél ("' . ProducerDeduplicator::DIFF_SPACING . '", "'
|
||||
. ProducerDeduplicator::DIFF_ACCENT . '", "' . ProducerDeduplicator::DIFF_COMPANY_FORM
|
||||
. '") NEM töltöttük ki a végleges nevet, mert ott valódi döntés kell: '
|
||||
. 'ha ugyanaz a cég, írd be a nevet (a javaslat a "Megjegyzés" oszlopban van); '
|
||||
. 'HA NEM UGYANAZ A CÉG, HAGYD ÜRESEN – akkor nem nyúlunk hozzájuk.');
|
||||
$sheet->mergeCells('A7:J7');
|
||||
$sheet->getStyle('A7')->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
|
||||
$sheet->getStyle('A7')->getFont()->setBold(true)->getColor()->setARGB('FF9C5700');
|
||||
$sheet->getRowDimension(7)->setRowHeight(62);
|
||||
}
|
||||
}
|
||||
|
||||
private function writeHeader($sheet, int $headerRow): void
|
||||
{
|
||||
$headers = [self::COLUMN_GROUP, self::COLUMN_ID, 'Típus', 'Gyártó neve a rendszerben', 'Eltérés',
|
||||
'Termékek', 'Rendelési tételek', 'Létrehozva', self::COLUMN_FINAL_NAME, 'Megjegyzés'];
|
||||
|
||||
foreach ($headers as $i => $text) {
|
||||
$sheet->setCellValueByColumnAndRow($i + 1, $headerRow, $text);
|
||||
}
|
||||
|
||||
$range = 'A' . $headerRow . ':J' . $headerRow;
|
||||
$sheet->getStyle($range)->getFont()->setBold(true)->getColor()->setARGB('FFFFFFFF');
|
||||
$sheet->getStyle($range)->getFill()->setFillType(Fill::FILL_SOLID)
|
||||
->getStartColor()->setARGB('FF44546A');
|
||||
$sheet->getStyle($range)->getAlignment()->setWrapText(true)
|
||||
->setVertical(Alignment::VERTICAL_CENTER);
|
||||
$sheet->getRowDimension($headerRow)->setRowHeight(32);
|
||||
}
|
||||
|
||||
/**
|
||||
* A laza javaslatok sorrendje: elöl a gyakorlatilag eldöntött esetek, hátul azok,
|
||||
* amik valódi cégismeretet igényelnek. Így a megrendelő kötegelve tud haladni.
|
||||
*/
|
||||
private const CATEGORY_ORDER = [
|
||||
ProducerDeduplicator::DIFF_PUNCTUATION,
|
||||
ProducerDeduplicator::DIFF_SPACING,
|
||||
ProducerDeduplicator::DIFF_ACCENT,
|
||||
ProducerDeduplicator::DIFF_COMPANY_FORM,
|
||||
ProducerDeduplicator::DIFF_MIXED,
|
||||
];
|
||||
|
||||
private function writeGroups($sheet, int $headerRow, array $certain, array $loose): int
|
||||
{
|
||||
$row = $headerRow + 1;
|
||||
$groupIndex = 0;
|
||||
|
||||
foreach ($certain as $members) {
|
||||
$groupIndex++;
|
||||
$row = $this->writeGroup($sheet, $row, $groupIndex, self::TYPE_CERTAIN, $members, false);
|
||||
}
|
||||
|
||||
$deduplicator = app(ProducerDeduplicator::class);
|
||||
$byCategory = [];
|
||||
foreach ($loose as $key => $members) {
|
||||
$byCategory[$deduplicator->differenceCategory($members)][$key] = $members;
|
||||
}
|
||||
|
||||
foreach (self::CATEGORY_ORDER as $category) {
|
||||
foreach ($byCategory[$category] ?? [] as $members) {
|
||||
$groupIndex++;
|
||||
// Az írásjel-eltérésnél nincs mérlegelnivaló (a "Kft." és a "Kft" ugyanaz),
|
||||
// ezért ott előre beírjuk a javaslatot - a megrendelő így csak a valóban
|
||||
// kérdéses eseteket nézi át tételesen.
|
||||
$prefill = $category === ProducerDeduplicator::DIFF_PUNCTUATION;
|
||||
$row = $this->writeGroup($sheet, $row, $groupIndex, $category, $members, ! $prefill);
|
||||
}
|
||||
}
|
||||
|
||||
return $row - 1;
|
||||
}
|
||||
|
||||
private function writeGroup($sheet, int $row, int $groupIndex, string $type, array $members, bool $isReview): int
|
||||
{
|
||||
$proposed = trim((string) $members[0]['producer']->name);
|
||||
$shade = $isReview ? 'FFFDF2E9' : ($groupIndex % 2 === 0 ? 'FFF2F2F2' : 'FFFFFFFF');
|
||||
$groupFirstRow = $row;
|
||||
|
||||
foreach ($members as $index => $member) {
|
||||
$producer = $member['producer'];
|
||||
$name = (string) $producer->name;
|
||||
|
||||
// A csoport sorszáma MINDEN soron szerepel: így a lap szűrhető és
|
||||
// rendezhető anélkül, hogy a csoportok összekeverednének.
|
||||
$sheet->setCellValue('A' . $row, $groupIndex);
|
||||
$sheet->setCellValue('B' . $row, $producer->id);
|
||||
$sheet->setCellValue('C' . $row, $type);
|
||||
$sheet->setCellValueExplicit('D' . $row, '"' . $name . '"', DataType::TYPE_STRING);
|
||||
$sheet->setCellValue('E' . $row, $index === 0
|
||||
? ($isReview ? 'legtöbb termék' : 'javasolt megtartani')
|
||||
: implode(', ', $this->describeDifference($name, $proposed)));
|
||||
$sheet->setCellValue('F' . $row, $member['counts']['products']);
|
||||
$sheet->setCellValue('G' . $row, $member['counts']['order_archives_items']);
|
||||
$sheet->setCellValue('H' . $row, substr((string) $producer->created_at, 0, 10));
|
||||
|
||||
$sheet->getStyle('A' . $row . ':J' . $row)->getFill()
|
||||
->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB($shade);
|
||||
|
||||
if ($index === 0) {
|
||||
$sheet->getStyle('D' . $row)->getFont()->setBold(true);
|
||||
|
||||
if ($isReview) {
|
||||
// Bizonytalan javaslatnál a végleges név ÜRESEN marad: az alapértelmezett
|
||||
// viselkedés a "nem nyúlunk hozzá", a döntés pedig tudatos kitöltés.
|
||||
$sheet->setCellValue('J' . $row, 'ha ugyanaz a cég: ' . $proposed);
|
||||
$sheet->getStyle('J' . $row)->getFont()->setItalic(true);
|
||||
} else {
|
||||
$sheet->setCellValueExplicit('I' . $row, $proposed, DataType::TYPE_STRING);
|
||||
$sheet->getStyle('I' . $row)->getFont()->setBold(true);
|
||||
}
|
||||
|
||||
$sheet->getStyle('I' . $row)->getFill()->setFillType(Fill::FILL_SOLID)
|
||||
->getStartColor()->setARGB($isReview ? 'FFFFE0B2' : 'FFFFF2CC');
|
||||
}
|
||||
|
||||
$row++;
|
||||
}
|
||||
|
||||
$sheet->getStyle('A' . $groupFirstRow . ':J' . ($row - 1))->getBorders()->getTop()
|
||||
->setBorderStyle(Border::BORDER_THIN)->getColor()->setARGB('FFBFBFBF');
|
||||
|
||||
return $row;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function describeDifference(string $name, string $proposed): array
|
||||
{
|
||||
$differences = [];
|
||||
|
||||
if ($name !== trim($name)) {
|
||||
$differences[] = 'szóköz a név szélén';
|
||||
}
|
||||
if (trim($name) !== $proposed && mb_strtoupper(trim($name)) === mb_strtoupper($proposed)) {
|
||||
$differences[] = 'eltérő kis/nagybetű';
|
||||
}
|
||||
if (str_contains($name, '/') || str_contains($name, '_')) {
|
||||
$differences[] = 'eltérő elválasztó';
|
||||
}
|
||||
if (preg_match('/\s{2,}/', $name)) {
|
||||
$differences[] = 'dupla szóköz';
|
||||
}
|
||||
|
||||
return $differences === [] ? ['eltérő írásmód'] : $differences;
|
||||
}
|
||||
|
||||
private function finishLayout($sheet, int $headerRow, int $lastRow, array $certain, array $loose): void
|
||||
{
|
||||
$first = $headerRow + 1;
|
||||
|
||||
$sheet->getStyle('F' . $first . ':G' . $lastRow)->getNumberFormat()->setFormatCode('# ##0');
|
||||
$sheet->getStyle('A' . $first . ':C' . $lastRow)->getAlignment()
|
||||
->setHorizontal(Alignment::HORIZONTAL_CENTER);
|
||||
$sheet->getStyle('I' . $first . ':I' . $lastRow)->getBorders()->getAllBorders()
|
||||
->setBorderStyle(Border::BORDER_THIN)->getColor()->setARGB('FFBF8F00');
|
||||
|
||||
$widths = ['A' => 9, 'B' => 11, 'C' => 15, 'D' => 34, 'E' => 20,
|
||||
'F' => 11, 'G' => 17, 'H' => 13, 'I' => 34, 'J' => 34];
|
||||
foreach ($widths as $column => $width) {
|
||||
$sheet->getColumnDimension($column)->setWidth($width);
|
||||
}
|
||||
|
||||
$sheet->freezePane('A' . $first);
|
||||
$sheet->setAutoFilter('A' . $headerRow . ':J' . $lastRow);
|
||||
|
||||
$summaryRow = $lastRow + 2;
|
||||
$summary = 'Biztos duplikáció: ' . count($certain) . ' csoport, '
|
||||
. array_sum(array_map('count', $certain)) . ' rekord.';
|
||||
|
||||
if ($loose !== []) {
|
||||
$summary .= ' Ellenőrizendő javaslat: ' . count($loose) . ' csoport, '
|
||||
. array_sum(array_map('count', $loose)) . ' rekord – ezeknél az üresen hagyott '
|
||||
. 'végleges név azt jelenti, hogy nem vonjuk össze őket.';
|
||||
}
|
||||
|
||||
$sheet->setCellValue('A' . $summaryRow, $summary);
|
||||
$sheet->mergeCells('A' . $summaryRow . ':J' . $summaryRow);
|
||||
$sheet->getStyle('A' . $summaryRow)->getFont()->setItalic(true);
|
||||
}
|
||||
}
|
||||
@ -158,7 +158,7 @@ private function sendNotification(int $orderArchiveId)
|
||||
$to[] = $orderData['customNotificationEmail'];
|
||||
}
|
||||
|
||||
if (config('app.stage', 'DEV') == 'PROD') {
|
||||
if (env('APP_STAGE', 'DEV') == 'PROD') {
|
||||
$to[] = $orderData['supplier']['orderEmail'];
|
||||
if ($orderData['supplier']['orderEmail2']) {
|
||||
$to[] = $orderData['supplier']['orderEmail2'];
|
||||
|
||||
@ -43,8 +43,9 @@ public function severity(): string
|
||||
self::NO_WORKSHEET,
|
||||
self::COLUMN_COUNT_MISMATCH,
|
||||
self::HEADER_MISMATCH,
|
||||
self::COLUMN_MISSING,
|
||||
self::NO_DATA_ROWS => 'blocker',
|
||||
|
||||
self::COLUMN_MISSING => 'error',
|
||||
self::COLUMN_EXTRA,
|
||||
self::FILE_TOO_LARGE => 'warning',
|
||||
};
|
||||
|
||||
@ -10,13 +10,6 @@ enum PricelistFileStatusEnum: string
|
||||
case done = 'done';
|
||||
case waiting_for_approval = 'waiting_for_approval';
|
||||
case closed = 'closed';
|
||||
/**
|
||||
* A Végrehajtás (Execution) lépés futott hibára. Szándékosan külön áll a `fail`-től:
|
||||
* a `fail` a validálásig tartó szakasz hibája, ahonnan a fájl újratöltésével (Edit)
|
||||
* biztonságosan újraindítható a lánc - itt viszont már történhettek termék- és
|
||||
* árírások, ezért csak a Folytatás vagy a Visszavonás akció indítható.
|
||||
*/
|
||||
case execution_failed = 'execution_failed';
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
@ -27,24 +20,6 @@ public function label(): string
|
||||
self::done => 'elkészült',
|
||||
self::waiting_for_approval => 'jóváhagyásra vár',
|
||||
self::closed => 'lezárva',
|
||||
self::execution_failed => 'végrehajtási hiba',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Badge szín a felülethez (a PricelistFileLineStatusEnum mintáját követve, hogy a
|
||||
* színek egy helyen legyenek, és egy új státusz ne törjön el minden match-et).
|
||||
*/
|
||||
public function color(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::todo => 'gray',
|
||||
self::inprogress => 'info',
|
||||
self::done => 'success',
|
||||
self::fail => 'danger',
|
||||
self::waiting_for_approval => 'primary',
|
||||
self::closed => 'warning',
|
||||
self::execution_failed => 'danger',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@ -15,7 +15,6 @@ enum PricelistSellerUnitEnum: string
|
||||
case liter = 'liter';
|
||||
case pár = 'pár';
|
||||
case tekercs = 'tekercs';
|
||||
case m = 'm';
|
||||
|
||||
/**
|
||||
* Visszaadja az összes értéket tömbként
|
||||
|
||||
@ -58,8 +58,6 @@ public function color(string $status): string
|
||||
'inprogress' => 'primary',
|
||||
'completed' => 'success',
|
||||
'failed' => 'danger',
|
||||
'rejected' => 'warning', // manuális elutasítás - nem hiba, hanem szabályos lezárás
|
||||
'reverted' => 'warning', // a végrehajtás kompenzáló visszaállítással visszavonva
|
||||
default => 'gray',
|
||||
};
|
||||
}
|
||||
|
||||
@ -24,6 +24,4 @@ class ProductUnitEnum extends BasicUnitEnum
|
||||
const pár = 'pár';
|
||||
|
||||
const zsák = 'zsák';
|
||||
|
||||
const m = 'm';
|
||||
}
|
||||
|
||||
@ -1,48 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Exports;
|
||||
|
||||
use Illuminate\Support\Collection;
|
||||
use Maatwebsite\Excel\Concerns\FromCollection;
|
||||
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
|
||||
use Maatwebsite\Excel\Concerns\WithHeadings;
|
||||
use Maatwebsite\Excel\Concerns\WithMapping;
|
||||
|
||||
class CurrentPriceExport implements FromCollection, ShouldAutoSize, WithHeadings, WithMapping
|
||||
{
|
||||
/**
|
||||
* @param Collection<int, array{supplier: ?string, producer: ?string, mainGroup: string, subGroup1: string, subGroup2: string, name: string, price: ?float}> $rows
|
||||
*/
|
||||
public function __construct(private Collection $rows) {}
|
||||
|
||||
public function collection(): Collection
|
||||
{
|
||||
return $this->rows;
|
||||
}
|
||||
|
||||
public function headings(): array
|
||||
{
|
||||
return [
|
||||
'Beszállító',
|
||||
'Gyártó',
|
||||
'Termék Főcsoport',
|
||||
'Termék alcsoport 1',
|
||||
'Termék alcsoport 2',
|
||||
'Termék megnevezése',
|
||||
'Aktuális ár',
|
||||
];
|
||||
}
|
||||
|
||||
public function map($row): array
|
||||
{
|
||||
return [
|
||||
$row['supplier'] ?? '',
|
||||
$row['producer'] ?? '',
|
||||
$row['mainGroup'] ?? '',
|
||||
$row['subGroup1'] ?? '',
|
||||
$row['subGroup2'] ?? '',
|
||||
$row['name'],
|
||||
$row['price'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -1,366 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Pages;
|
||||
|
||||
use App\Exports\CurrentPriceExport;
|
||||
use App\Models\Producer;
|
||||
use App\Models\Product;
|
||||
use App\Models\ProductGroup;
|
||||
use App\Models\Supplier;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Concerns\InteractsWithForms;
|
||||
use Filament\Forms\Contracts\HasForms;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Pages\Page;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Maatwebsite\Excel\Facades\Excel;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
|
||||
class CurrentPrice extends Page implements HasForms
|
||||
{
|
||||
use InteractsWithForms;
|
||||
|
||||
/** @var int[] */
|
||||
public const PER_PAGE_OPTIONS = [10, 25, 50, 100];
|
||||
|
||||
protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-currency-dollar';
|
||||
|
||||
protected static ?string $title = 'Aktuális ár';
|
||||
|
||||
protected static ?string $navigationLabel = 'Aktuális ár';
|
||||
|
||||
protected static string | \UnitEnum | null $navigationGroup = 'Statisztika';
|
||||
|
||||
public function getHeading(): string|\Illuminate\Contracts\Support\Htmlable
|
||||
{
|
||||
return '';
|
||||
}
|
||||
|
||||
public function getBreadcrumbs(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
protected string $view = 'filament.pages.current-price';
|
||||
|
||||
public ?array $data = [];
|
||||
|
||||
public bool $hasSearched = false;
|
||||
|
||||
public int $perPage = 10;
|
||||
|
||||
public int $page = 1;
|
||||
|
||||
public int $totalResults = 0;
|
||||
|
||||
/** @var array<int, array{supplier: ?string, producer: ?string, mainGroup: string, subGroup1: string, subGroup2: string, name: string, price: ?float}> */
|
||||
public array $results = [];
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->form->fill();
|
||||
}
|
||||
|
||||
public function form(Schema $form): Schema
|
||||
{
|
||||
return $form
|
||||
->schema([
|
||||
Select::make('supplier')
|
||||
->label('Beszállító:')
|
||||
->options(function (Get $get) {
|
||||
$selectedIds = $this->data['supplier'] ?? [];
|
||||
$query = Supplier::query();
|
||||
|
||||
$productQuery = $this->buildProductQuery($get, exclude: 'supplier');
|
||||
if ($productQuery) {
|
||||
$query->where(function ($q) use ($productQuery, $selectedIds) {
|
||||
$q->whereIn('id', (clone $productQuery)->whereNotNull('supplier_id')->distinct()->pluck('supplier_id'))
|
||||
->orWhereIn('id', $selectedIds);
|
||||
});
|
||||
}
|
||||
|
||||
return $query->orderBy('name')->pluck('name', 'id');
|
||||
})
|
||||
->multiple()
|
||||
->searchable()
|
||||
->live()
|
||||
->placeholder('Válasszon beszállítót...'),
|
||||
Select::make('productGroup')
|
||||
->label('Termékcsoport:')
|
||||
->options(function (Get $get) {
|
||||
$selectedIds = $this->data['productGroup'] ?? [];
|
||||
$query = ProductGroup::query();
|
||||
|
||||
$productQuery = $this->buildProductQuery($get, exclude: 'productGroup');
|
||||
if ($productQuery) {
|
||||
$query->where(function ($q) use ($productQuery, $selectedIds) {
|
||||
$q->whereIn('id', (clone $productQuery)->whereNotNull('product_group_id')->distinct()->pluck('product_group_id'))
|
||||
->orWhereIn('id', $selectedIds);
|
||||
});
|
||||
}
|
||||
|
||||
return $query->orderBy('name')->pluck('name', 'id');
|
||||
})
|
||||
->multiple()
|
||||
->searchable()
|
||||
->live()
|
||||
->placeholder('Válasszon termékcsoportot...'),
|
||||
Select::make('product')
|
||||
->label('Termék:')
|
||||
->multiple()
|
||||
->searchable()
|
||||
->live()
|
||||
->getSearchResultsUsing(function (string $search, Get $get) {
|
||||
$query = $this->buildProductQuery($get, exclude: 'product') ?? Product::query();
|
||||
$query->where('name', 'like', "%{$search}%");
|
||||
|
||||
return $query->limit(50)->pluck('name', 'name')->toArray();
|
||||
})
|
||||
->getOptionLabelsUsing(fn (array $values): array => Product::whereIn('name', $values)
|
||||
->pluck('name', 'name')
|
||||
->toArray())
|
||||
->placeholder('Válasszon terméket...'),
|
||||
Select::make('hooreycaName')
|
||||
->label('Hooreyca megnevezés :')
|
||||
->options(function (Get $get) {
|
||||
$selected = $this->data['hooreycaName'] ?? [];
|
||||
|
||||
DB::statement("SET sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));");
|
||||
$query = ($this->buildProductQuery($get, exclude: 'hooreycaName') ?? Product::query())
|
||||
->where('buyerProductName', '!=', '');
|
||||
$options = $query->orderBy('buyerProductName')
|
||||
->groupBy('buyerProductName')
|
||||
->pluck('buyerProductName', 'buyerProductName')
|
||||
->toArray();
|
||||
DB::statement("SET sql_mode=(SELECT CONCAT(@@sql_mode, ',ONLY_FULL_GROUP_BY'));");
|
||||
|
||||
foreach ($selected as $name) {
|
||||
if (filled($name) && ! array_key_exists($name, $options)) {
|
||||
$options[$name] = $name;
|
||||
}
|
||||
}
|
||||
|
||||
return $options;
|
||||
})
|
||||
->multiple()
|
||||
->searchable()
|
||||
->live()
|
||||
->placeholder('Válasszon megnevezést...'),
|
||||
Select::make('producer')
|
||||
->label('Gyártó :')
|
||||
->options(function (Get $get) {
|
||||
$selectedIds = $this->data['producer'] ?? [];
|
||||
$query = Producer::query();
|
||||
|
||||
$productQuery = $this->buildProductQuery($get, exclude: 'producer');
|
||||
if ($productQuery) {
|
||||
$query->where(function ($q) use ($productQuery, $selectedIds) {
|
||||
$q->whereIn('id', (clone $productQuery)->whereNotNull('producer_id')->distinct()->pluck('producer_id'))
|
||||
->orWhereIn('id', $selectedIds);
|
||||
});
|
||||
}
|
||||
|
||||
return $query->orderBy('name')->pluck('name', 'id');
|
||||
})
|
||||
->multiple()
|
||||
->searchable()
|
||||
->live()
|
||||
->placeholder('Válasszon gyártót...'),
|
||||
])
|
||||
->statePath('data');
|
||||
}
|
||||
|
||||
public function submit(): void
|
||||
{
|
||||
$this->data = $this->form->getState();
|
||||
$this->page = 1;
|
||||
$this->runSearch();
|
||||
}
|
||||
|
||||
public function updatedPerPage(): void
|
||||
{
|
||||
$this->page = 1;
|
||||
|
||||
if ($this->hasSearched) {
|
||||
$this->runSearch();
|
||||
}
|
||||
}
|
||||
|
||||
public function goToPage(int $page): void
|
||||
{
|
||||
$this->page = max(1, min($page, $this->lastPage()));
|
||||
$this->runSearch();
|
||||
}
|
||||
|
||||
public function lastPage(): int
|
||||
{
|
||||
return max(1, (int) ceil($this->totalResults / $this->perPage));
|
||||
}
|
||||
|
||||
public function exportExcel(): BinaryFileResponse
|
||||
{
|
||||
$products = $this->filteredResultsQuery()->orderBy('name')->get();
|
||||
$rows = $this->mapProductsToRows($products);
|
||||
|
||||
return Excel::download(new CurrentPriceExport($rows), 'aktualis-ar-'.now()->format('Y-m-d_His').'.xlsx');
|
||||
}
|
||||
|
||||
private function runSearch(): void
|
||||
{
|
||||
$query = $this->filteredResultsQuery();
|
||||
|
||||
$this->totalResults = (clone $query)->count();
|
||||
$this->page = min($this->page, $this->lastPage());
|
||||
|
||||
$products = $query->orderBy('name')
|
||||
->skip(($this->page - 1) * $this->perPage)
|
||||
->take($this->perPage)
|
||||
->get();
|
||||
|
||||
$this->results = $this->mapProductsToRows($products)->toArray();
|
||||
|
||||
$this->hasSearched = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* A szűrő űrlap aktuális állapota alapján felépített, még nem lapozott/rendezett Product query.
|
||||
*/
|
||||
private function filteredResultsQuery(): Builder
|
||||
{
|
||||
$data = $this->data;
|
||||
|
||||
$query = Product::query()->with(['Supplier', 'Producer']);
|
||||
|
||||
if (filled($data['supplier'] ?? [])) {
|
||||
$query->whereIn('supplier_id', $data['supplier']);
|
||||
}
|
||||
|
||||
if (filled($data['productGroup'] ?? [])) {
|
||||
$query->whereIn('product_group_id', $data['productGroup']);
|
||||
}
|
||||
|
||||
if (filled($data['producer'] ?? [])) {
|
||||
$query->whereIn('producer_id', $data['producer']);
|
||||
}
|
||||
|
||||
if (filled($data['product'] ?? [])) {
|
||||
$query->whereIn('name', $data['product']);
|
||||
}
|
||||
|
||||
if (filled($data['hooreycaName'] ?? [])) {
|
||||
$query->whereIn('buyerProductName', $data['hooreycaName']);
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
/**
|
||||
* Termékekhez tartozó aktuális ár és termékcsoport-hierarchia feloldása, és a táblázat/export
|
||||
* soraivá alakítása. Egyetlen extra lekérdezéssel dolgozza fel a kapott terméklistát (nincs N+1).
|
||||
*
|
||||
* @return Collection<int, array{supplier: ?string, producer: ?string, mainGroup: string, subGroup1: string, subGroup2: string, name: string, price: ?float}>
|
||||
*/
|
||||
private function mapProductsToRows(Collection $products): Collection
|
||||
{
|
||||
$today = now()->toDateString();
|
||||
|
||||
$currentPrices = DB::table('price_list_prices as plp')
|
||||
->join('price_lists as pl', 'pl.id', '=', 'plp.price_list_id')
|
||||
->whereIn('plp.product_id', $products->pluck('id'))
|
||||
->where('pl.available', '<=', $today)
|
||||
->orderBy('pl.available', 'desc')
|
||||
->orderBy('pl.id', 'desc')
|
||||
->get(['plp.product_id', 'plp.price'])
|
||||
->groupBy('product_id')
|
||||
->map(fn ($rows) => (float) $rows->first()->price);
|
||||
|
||||
$groupPaths = $this->getProductGroupPaths($products->pluck('product_group_id'));
|
||||
|
||||
return $products->map(function (Product $product) use ($currentPrices, $groupPaths) {
|
||||
$path = $groupPaths->get($product->product_group_id, []);
|
||||
|
||||
return [
|
||||
'supplier' => $product->Supplier?->name,
|
||||
'producer' => $product->Producer?->name,
|
||||
'mainGroup' => $path[0] ?? '',
|
||||
'subGroup1' => $path[1] ?? '',
|
||||
'subGroup2' => $path[2] ?? '',
|
||||
'name' => $product->name,
|
||||
'price' => $currentPrices->get($product->id),
|
||||
];
|
||||
})->values();
|
||||
}
|
||||
|
||||
/**
|
||||
* A termékcsoport-hierarchia első 3 szintje (Termék Főcsoport / alcsoport 1 / alcsoport 2)
|
||||
* termékcsoport id-nként, ugyanaz a logika, mint a legacy Árváltozás statisztikában
|
||||
* (ProductGroup::allWithPath() — a technikai gyökér csomópont nélkül).
|
||||
*
|
||||
* @param \Illuminate\Support\Collection<int, int|null> $productGroupIds
|
||||
* @return \Illuminate\Support\Collection<int, array<int, string>>
|
||||
*/
|
||||
private function getProductGroupPaths($productGroupIds): \Illuminate\Support\Collection
|
||||
{
|
||||
$ids = $productGroupIds->filter()->unique()->values();
|
||||
|
||||
if ($ids->isEmpty()) {
|
||||
return collect();
|
||||
}
|
||||
|
||||
return ProductGroup::whereIn('id', $ids)
|
||||
->with('ancestors')
|
||||
->get()
|
||||
->mapWithKeys(function (ProductGroup $group) {
|
||||
$names = $group->ancestors->pluck('name')->all();
|
||||
array_shift($names); // technikai gyökér ("Főcsoportok") elhagyása
|
||||
$names[] = $group->name;
|
||||
|
||||
return [$group->id => $names];
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Product query szűrve a szűrő űrlap összes mezőjének aktuális állapota alapján,
|
||||
* a $exclude-ban megadott mező kihagyásával (kölcsönös/kereszt-szűréshez).
|
||||
* Null-t ad vissza, ha egyik mező sincs kitöltve (nincs mit szűrni).
|
||||
*/
|
||||
private function buildProductQuery(Get $get, string $exclude): ?Builder
|
||||
{
|
||||
$supplierIds = $exclude === 'supplier' ? [] : ($get('supplier') ?? []);
|
||||
$productGroupIds = $exclude === 'productGroup' ? [] : ($get('productGroup') ?? []);
|
||||
$producerIds = $exclude === 'producer' ? [] : ($get('producer') ?? []);
|
||||
$productNames = $exclude === 'product' ? [] : ($get('product') ?? []);
|
||||
$hooreycaNames = $exclude === 'hooreycaName' ? [] : ($get('hooreycaName') ?? []);
|
||||
|
||||
if (blank($supplierIds) && blank($productGroupIds) && blank($producerIds) && blank($productNames) && blank($hooreycaNames)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$query = Product::query();
|
||||
|
||||
if (filled($supplierIds)) {
|
||||
$query->whereIn('supplier_id', $supplierIds);
|
||||
}
|
||||
|
||||
if (filled($productGroupIds)) {
|
||||
$query->whereIn('product_group_id', $productGroupIds);
|
||||
}
|
||||
|
||||
if (filled($producerIds)) {
|
||||
$query->whereIn('producer_id', $producerIds);
|
||||
}
|
||||
|
||||
if (filled($productNames)) {
|
||||
$query->whereIn('name', $productNames);
|
||||
}
|
||||
|
||||
if (filled($hooreycaNames)) {
|
||||
$query->whereIn('buyerProductName', $hooreycaNames);
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
}
|
||||
@ -1,609 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Pages;
|
||||
|
||||
use App\Models\DeploymentPackage as DeploymentPackageRecord;
|
||||
use App\Services\Deployment\ChangeSetAnalyzer;
|
||||
use App\Services\Deployment\DeploymentGuard;
|
||||
use App\Services\Deployment\DeploymentPackageBuilder;
|
||||
use App\Services\Deployment\DeploymentTargets;
|
||||
use App\Services\Deployment\GitRepository;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Concerns\InteractsWithForms;
|
||||
use Filament\Forms\Contracts\HasForms;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Schemas\Components\Grid;
|
||||
use Filament\Schemas\Schema;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Livewire\Attributes\Computed;
|
||||
use RuntimeException;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Deployment csomagoló: célkörnyezet, commit-tartomány, diff-előnézet és csomagolás.
|
||||
*
|
||||
* Az oldal a git történetet olvassa, és a kijelölt tartományból egy időbélyeges mappát
|
||||
* állít elő a config('deployment.output_path') alatt - a repón kívülre nem ír.
|
||||
*
|
||||
* A hozzáférést a DeploymentGuard dönti el (env kapcsoló + stage whitelist +
|
||||
* developer szerep + feature flag), és a mount()-on kívül minden akció elején
|
||||
* újra lefut - a felület elrejtése önmagában nem védelem.
|
||||
*/
|
||||
class DeploymentPackage extends Page implements HasForms
|
||||
{
|
||||
use InteractsWithForms;
|
||||
|
||||
protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-rocket-launch';
|
||||
|
||||
protected string $view = 'filament.pages.deployment-package';
|
||||
|
||||
protected static ?string $title = 'Deployment csomagoló';
|
||||
|
||||
protected static ?string $navigationLabel = 'Deployment csomagoló';
|
||||
|
||||
protected static bool $shouldRegisterNavigation = false;
|
||||
|
||||
/** @var array<string, mixed>|null */
|
||||
public ?array $data = [];
|
||||
|
||||
public ?string $fromCommit = null;
|
||||
|
||||
public ?string $toCommit = null;
|
||||
|
||||
public ?string $gitError = null;
|
||||
|
||||
/** @var array<int, string> a felületen kézzel kivett fájlok */
|
||||
public array $skippedPaths = [];
|
||||
|
||||
/** @var array<string, mixed>|null az utoljára elkészített csomag adatai */
|
||||
public ?array $lastPackage = null;
|
||||
|
||||
/** @var array<string, array<string, mixed>> targetenként a szerverről lekérdezett élő verzió */
|
||||
public array $liveVersions = [];
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
return app(DeploymentGuard::class)->isAllowed(auth()->user());
|
||||
}
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
app(DeploymentGuard::class)->ensureAllowed(auth()->user());
|
||||
|
||||
/** @var array<int, int> $limits */
|
||||
$limits = (array) config('deployment.commit_limits', [50]);
|
||||
|
||||
$target = app(DeploymentTargets::class)->defaultKey();
|
||||
|
||||
$this->form->fill([
|
||||
'target' => $target,
|
||||
'branch' => $this->defaultBranch(),
|
||||
'limit' => $limits[0] ?? 50,
|
||||
'search' => null,
|
||||
]);
|
||||
|
||||
$this->preloadFromCommit($target);
|
||||
$this->fetchAllLiveVersions();
|
||||
}
|
||||
|
||||
/**
|
||||
* A kezdő commit előtöltése az adott környezetre utoljára kirakott csomagból.
|
||||
*
|
||||
* Ez a funkció lényegi része: a "hol tart ez a környezet" kérdésre nem emlékezetből
|
||||
* kell válaszolni, így nem marad ki fájl a következő csomagból.
|
||||
*/
|
||||
private function preloadFromCommit(?string $targetKey): void
|
||||
{
|
||||
if (! $targetKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
$lastDeployed = DeploymentPackageRecord::lastDeployedFor($targetKey);
|
||||
|
||||
// Rebase/force push után a korábban rögzített hash már nem létezik - ilyenkor
|
||||
// inkább nem töltünk elő semmit, mint hogy hamis tartományt mutassunk.
|
||||
$this->fromCommit = $lastDeployed
|
||||
? app(GitRepository::class)->resolveCommit($lastDeployed->to_commit)
|
||||
: null;
|
||||
}
|
||||
|
||||
public function form(Schema $form): Schema
|
||||
{
|
||||
/** @var array<int, int> $limits */
|
||||
$limits = (array) config('deployment.commit_limits', [50]);
|
||||
|
||||
return $form
|
||||
->schema([
|
||||
Grid::make(4)
|
||||
->schema([
|
||||
Select::make('target')
|
||||
->label('Célkörnyezet')
|
||||
->options(app(DeploymentTargets::class)->options())
|
||||
->required()
|
||||
->live()
|
||||
->afterStateUpdated(fn (?string $state) => $this->preloadFromCommit($state))
|
||||
->helperText(fn (): ?string => $this->target()['remote_path'] ?? null),
|
||||
Select::make('branch')
|
||||
->label('Branch')
|
||||
->options($this->branchOptions())
|
||||
->required()
|
||||
->searchable()
|
||||
->live()
|
||||
->afterStateUpdated(fn () => $this->clearRange()),
|
||||
Select::make('limit')
|
||||
->label('Commitok száma')
|
||||
->options(array_combine($limits, $limits))
|
||||
->required()
|
||||
->live(),
|
||||
TextInput::make('search')
|
||||
->label('Keresés')
|
||||
->placeholder('pl. árlista, migráció, szerző')
|
||||
->helperText('A commit üzenetében (a törzsben is), a szerzőben és a hashben keres, a betöltött listán belül.')
|
||||
->live(debounce: 400),
|
||||
]),
|
||||
])
|
||||
->statePath('data');
|
||||
}
|
||||
|
||||
public function selectFrom(string $hash): void
|
||||
{
|
||||
app(DeploymentGuard::class)->ensureAllowed(auth()->user());
|
||||
|
||||
$this->fromCommit = $this->resolveOrWarn($hash);
|
||||
}
|
||||
|
||||
public function selectTo(string $hash): void
|
||||
{
|
||||
app(DeploymentGuard::class)->ensureAllowed(auth()->user());
|
||||
|
||||
$this->toCommit = $this->resolveOrWarn($hash);
|
||||
}
|
||||
|
||||
public function swapRange(): void
|
||||
{
|
||||
app(DeploymentGuard::class)->ensureAllowed(auth()->user());
|
||||
|
||||
[$this->fromCommit, $this->toCommit] = [$this->toCommit, $this->fromCommit];
|
||||
}
|
||||
|
||||
public function clearRange(): void
|
||||
{
|
||||
$this->fromCommit = null;
|
||||
$this->toCommit = null;
|
||||
$this->skippedPaths = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Egy fájl kézi ki-/visszavétele a csomagból.
|
||||
*/
|
||||
public function toggleFile(string $path): void
|
||||
{
|
||||
app(DeploymentGuard::class)->ensureAllowed(auth()->user());
|
||||
|
||||
$this->skippedPaths = in_array($path, $this->skippedPaths, true)
|
||||
? array_values(array_diff($this->skippedPaths, [$path]))
|
||||
: array_merge($this->skippedPaths, [$path]);
|
||||
}
|
||||
|
||||
/**
|
||||
* A csomag előállítása a kijelölt tartományból.
|
||||
*/
|
||||
public function createPackage(): void
|
||||
{
|
||||
app(DeploymentGuard::class)->ensureAllowed(auth()->user());
|
||||
|
||||
if (! $this->fromCommit || ! $this->toCommit) {
|
||||
Notification::make()
|
||||
->title('Nincs kijelölt tartomány')
|
||||
->body('Válassz egy kezdő és egy záró commitot.')
|
||||
->danger()
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$this->lastPackage = app(DeploymentPackageBuilder::class)->build(
|
||||
(string) ($this->data['target'] ?? ''),
|
||||
(string) ($this->data['branch'] ?? ''),
|
||||
$this->fromCommit,
|
||||
$this->toCommit,
|
||||
$this->skippedPaths,
|
||||
auth()->user()?->email,
|
||||
);
|
||||
} catch (RuntimeException $exception) {
|
||||
Notification::make()
|
||||
->title('A csomag nem készült el')
|
||||
->body($exception->getMessage())
|
||||
->danger()
|
||||
->persistent()
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
DeploymentPackageRecord::create([
|
||||
'name' => $this->lastPackage['name'],
|
||||
'target' => $this->lastPackage['target'],
|
||||
'branch' => $this->lastPackage['branch'],
|
||||
'from_commit' => $this->lastPackage['from'],
|
||||
'to_commit' => $this->lastPackage['to'],
|
||||
'folder' => $this->lastPackage['path'],
|
||||
'zip_path' => $this->lastPackage['zip'],
|
||||
'copied_count' => $this->lastPackage['counts']['copied'],
|
||||
'deleted_count' => $this->lastPackage['counts']['deleted'],
|
||||
'skipped_count' => $this->lastPackage['counts']['skipped'],
|
||||
'missing_count' => $this->lastPackage['counts']['missing'],
|
||||
]);
|
||||
|
||||
Notification::make()
|
||||
->title('A csomag elkészült')
|
||||
->body(sprintf(
|
||||
'%d fájl a(z) %s mappában.',
|
||||
$this->lastPackage['counts']['copied'],
|
||||
$this->lastPackage['name'],
|
||||
))
|
||||
->success()
|
||||
->send();
|
||||
}
|
||||
|
||||
/**
|
||||
* A csomag ZIP-jének letöltése.
|
||||
*/
|
||||
public function downloadPackage(int $id): ?BinaryFileResponse
|
||||
{
|
||||
app(DeploymentGuard::class)->ensureAllowed(auth()->user());
|
||||
|
||||
$package = DeploymentPackageRecord::find($id);
|
||||
$zipPath = $package?->zip_path;
|
||||
|
||||
// Az útvonal adatbázisból jön, ezért kiírás előtt ellenőrizzük, hogy a csomagoló
|
||||
// saját kimeneti mappáján belül van - egy elrontott vagy módosított rekord így sem
|
||||
// tud tetszőleges fájlt letölthetővé tenni.
|
||||
if (! $zipPath || ! is_file($zipPath) || ! $this->isInsideOutputPath($zipPath)) {
|
||||
Notification::make()
|
||||
->title('A ZIP nem érhető el')
|
||||
->body('A csomag ZIP fájlja már nincs a lemezen.')
|
||||
->danger()
|
||||
->send();
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return response()->download($zipPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* A csomag megjelölése kirakottként - innentől ez lesz a következő tartomány kezdete.
|
||||
*/
|
||||
public function markDeployed(int $id): void
|
||||
{
|
||||
app(DeploymentGuard::class)->ensureAllowed(auth()->user());
|
||||
|
||||
$package = DeploymentPackageRecord::find($id);
|
||||
|
||||
if (! $package) {
|
||||
return;
|
||||
}
|
||||
|
||||
$package->deployed_at = now();
|
||||
$package->save();
|
||||
|
||||
$this->preloadFromCommit($package->target);
|
||||
|
||||
Notification::make()
|
||||
->title('Megjelölve kirakottként')
|
||||
->body(sprintf('A(z) %s környezet innentől a %s commiton áll.', $package->target, substr((string) $package->to_commit, 0, 7)))
|
||||
->success()
|
||||
->send();
|
||||
}
|
||||
|
||||
/**
|
||||
* Az élő állapot lekérdezése a célkörnyezetről (deploy-version.json).
|
||||
*
|
||||
* Szándékosan gombra fut és nem minden rendereléskor: így nem indul kimenő kérés
|
||||
* magától, és nem lassítja az oldalt, ha egy környezet nem válaszol.
|
||||
*/
|
||||
public function fetchLiveVersion(string $targetKey, bool $force = false): void
|
||||
{
|
||||
app(DeploymentGuard::class)->ensureAllowed(auth()->user());
|
||||
|
||||
$target = app(DeploymentTargets::class)->find($targetKey);
|
||||
|
||||
if (! $target || ! $target['domain']) {
|
||||
return;
|
||||
}
|
||||
|
||||
$cacheKey = 'deployment.live-version.'.$targetKey;
|
||||
|
||||
if ($force) {
|
||||
Cache::forget($cacheKey);
|
||||
}
|
||||
|
||||
// Rövid cache: az oldal minden Livewire körben újrarenderel, kérésenkénti
|
||||
// HTTP hívás nélkül. A hibás választ is cache-eljük, hogy egy nem válaszoló
|
||||
// környezet ne lassítsa minden kattintásnál a felületet.
|
||||
$this->liveVersions[$targetKey] = Cache::remember($cacheKey, now()->addMinute(), function () use ($target): array {
|
||||
try {
|
||||
$response = Http::connectTimeout(2)->timeout(3)->get('https://'.$target['domain'].'/deploy-version.json');
|
||||
|
||||
return $response->successful()
|
||||
? ['ok' => true, 'data' => $response->json()]
|
||||
: ['ok' => false, 'error' => 'HTTP '.$response->status()];
|
||||
} catch (Throwable $exception) {
|
||||
return ['ok' => false, 'error' => $exception->getMessage()];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Minden környezet állapotának lekérése (oldalbetöltéskor fut).
|
||||
*/
|
||||
public function fetchAllLiveVersions(bool $force = false): void
|
||||
{
|
||||
foreach (array_keys(app(DeploymentTargets::class)->all()) as $targetKey) {
|
||||
$this->fetchLiveVersion($targetKey, $force);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Melyik commiton áll melyik környezet - a commitlista megjelöléséhez.
|
||||
*
|
||||
* Elsődlegesen a szerverről lekérdezett élő állapotot használjuk; ha az nem
|
||||
* elérhető, a naplóban kirakottként megjelölt csomagot.
|
||||
*
|
||||
* @return array<string, array<int, array{key:string, label:string, live:bool}>>
|
||||
*/
|
||||
#[Computed]
|
||||
public function commitMarkers(): array
|
||||
{
|
||||
$markers = [];
|
||||
|
||||
foreach ($this->environmentStatuses() as $status) {
|
||||
$liveCommit = ($status['live']['ok'] ?? false) ? ($status['live']['data']['commit'] ?? null) : null;
|
||||
$commit = $liveCommit ?: $status['package']?->to_commit;
|
||||
|
||||
if (! $commit) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$markers[$commit][] = [
|
||||
'key' => $status['target']['key'],
|
||||
'label' => $status['target']['label'],
|
||||
'live' => (bool) $liveCommit,
|
||||
];
|
||||
}
|
||||
|
||||
return $markers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Környezetenkénti állapot: mi van kirakva és mennyi a lemaradás.
|
||||
*
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
#[Computed]
|
||||
public function environmentStatuses(): array
|
||||
{
|
||||
$branch = $this->data['branch'] ?? null;
|
||||
$statuses = [];
|
||||
|
||||
foreach (app(DeploymentTargets::class)->all() as $key => $target) {
|
||||
$lastDeployed = DeploymentPackageRecord::lastDeployedFor($key);
|
||||
$live = $this->liveVersions[$key] ?? null;
|
||||
$liveCommit = $live['ok'] ?? false ? ($live['data']['commit'] ?? null) : null;
|
||||
|
||||
$statuses[] = [
|
||||
'target' => $target,
|
||||
'package' => $lastDeployed,
|
||||
'behind' => $lastDeployed && $branch
|
||||
? app(GitRepository::class)->countCommitsBetween($lastDeployed->to_commit, $branch)
|
||||
: null,
|
||||
'live' => $live,
|
||||
// A napló azt mondja meg, mit jelöltünk kirakottnak; a szerver azt, mi fut
|
||||
// valójában. Ha a kettő eltér, az elmaradt vagy félbemaradt feltöltés jele.
|
||||
'mismatch' => $liveCommit && $lastDeployed && $liveCommit !== $lastDeployed->to_commit,
|
||||
];
|
||||
}
|
||||
|
||||
return $statuses;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \Illuminate\Support\Collection<int, DeploymentPackageRecord>
|
||||
*/
|
||||
#[Computed]
|
||||
public function recentPackages(): Collection
|
||||
{
|
||||
return DeploymentPackageRecord::query()
|
||||
->when($this->data['target'] ?? null, fn ($query, $target) => $query->forTarget($target))
|
||||
->latest('id')
|
||||
->limit(10)
|
||||
->get();
|
||||
}
|
||||
|
||||
private function isInsideOutputPath(string $path): bool
|
||||
{
|
||||
$base = realpath((string) config('deployment.output_path'));
|
||||
$real = realpath($path);
|
||||
|
||||
return $base !== false && $real !== false && str_starts_with($real, $base);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{key:string, label:string, domain:string, remote_path:string, expected_branch:?string}|null
|
||||
*/
|
||||
public function target(): ?array
|
||||
{
|
||||
return app(DeploymentTargets::class)->find($this->data['target'] ?? null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, array{hash:string, short:string, author:string, date:string, subject:string, body:string, file_count:?int}>
|
||||
*/
|
||||
#[Computed]
|
||||
public function commits(): array
|
||||
{
|
||||
$branch = $this->data['branch'] ?? null;
|
||||
|
||||
if (! $branch) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
$commits = app(GitRepository::class)->commits($branch, (int) ($this->data['limit'] ?? 50));
|
||||
} catch (RuntimeException $exception) {
|
||||
$this->gitError = $exception->getMessage();
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
$search = trim((string) ($this->data['search'] ?? ''));
|
||||
|
||||
if ($search === '') {
|
||||
return $commits;
|
||||
}
|
||||
|
||||
$needle = mb_strtolower($search);
|
||||
|
||||
return array_values(array_filter(
|
||||
$commits,
|
||||
fn (array $commit): bool => str_contains(
|
||||
mb_strtolower(implode(' ', [$commit['subject'], $commit['body'], $commit['author'], $commit['hash']])),
|
||||
$needle,
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* A kijelölt tartomány elemzése, vagy null, ha még nincs két commit kiválasztva.
|
||||
*
|
||||
* @return array{
|
||||
* files: array<int, array{status:string, path:string, old_path:?string, excluded:bool, action:string}>,
|
||||
* copied: array<int, string>,
|
||||
* deleted: array<int, string>,
|
||||
* counts: array{total:int, copied:int, deleted:int, excluded:int},
|
||||
* warnings: array<int, array{level:string, title:string, body:string}>
|
||||
* }|null
|
||||
*/
|
||||
#[Computed]
|
||||
public function changeSet(): ?array
|
||||
{
|
||||
if (! $this->fromCommit || ! $this->toCommit) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$repository = app(GitRepository::class);
|
||||
|
||||
try {
|
||||
$changedFiles = $repository->changedFiles($this->fromCommit, $this->toCommit);
|
||||
} catch (RuntimeException $exception) {
|
||||
$this->gitError = $exception->getMessage();
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
$changeSet = app(ChangeSetAnalyzer::class)->analyze(
|
||||
$changedFiles,
|
||||
$this->target(),
|
||||
$this->data['branch'] ?? null,
|
||||
);
|
||||
|
||||
if ($this->fromCommit === $this->toCommit) {
|
||||
array_unshift($changeSet['warnings'], [
|
||||
'level' => 'warning',
|
||||
'title' => 'Azonos commitok',
|
||||
'body' => 'A kezdő és a záró commit ugyanaz, így a tartomány üres.',
|
||||
]);
|
||||
} elseif (! $repository->isAncestor($this->fromCommit, $this->toCommit)) {
|
||||
array_unshift($changeSet['warnings'], [
|
||||
'level' => 'danger',
|
||||
'title' => 'Fordított vagy szétágazó tartomány',
|
||||
'body' => 'A kezdő commit nem őse a zárónak, ezért a lista nem a "mi került bele azóta" kérdésre válaszol. Ellenőrizd a sorrendet (Csere gomb), vagy azt, hogy ugyanazon az ágon vagy-e.',
|
||||
]);
|
||||
}
|
||||
|
||||
return $changeSet;
|
||||
}
|
||||
|
||||
/**
|
||||
* A kijelölt tartományba eső commitok - csak a lista kiemeléséhez.
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
#[Computed]
|
||||
public function highlightedHashes(): array
|
||||
{
|
||||
if (! $this->fromCommit || ! $this->toCommit) {
|
||||
return array_values(array_filter([$this->fromCommit, $this->toCommit]));
|
||||
}
|
||||
|
||||
$hashes = array_column($this->commits(), 'hash');
|
||||
$fromIndex = array_search($this->fromCommit, $hashes, true);
|
||||
$toIndex = array_search($this->toCommit, $hashes, true);
|
||||
|
||||
if ($fromIndex === false || $toIndex === false) {
|
||||
return array_values(array_filter([$this->fromCommit, $this->toCommit]));
|
||||
}
|
||||
|
||||
// A lista fentről lefelé a legfrissebbtől halad, tehát a záró commit van előrébb.
|
||||
[$start, $end] = $fromIndex <= $toIndex ? [$fromIndex, $toIndex] : [$toIndex, $fromIndex];
|
||||
|
||||
return array_slice($hashes, $start, $end - $start + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function branchOptions(): array
|
||||
{
|
||||
try {
|
||||
$branches = app(GitRepository::class)->branches();
|
||||
} catch (RuntimeException $exception) {
|
||||
$this->gitError = $exception->getMessage();
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
return array_combine($branches, $branches) ?: [];
|
||||
}
|
||||
|
||||
public function isRepositoryAvailable(): bool
|
||||
{
|
||||
return app(GitRepository::class)->isAvailable();
|
||||
}
|
||||
|
||||
private function defaultBranch(): ?string
|
||||
{
|
||||
$repository = app(GitRepository::class);
|
||||
$current = $repository->currentBranch();
|
||||
|
||||
if ($current) {
|
||||
return $current;
|
||||
}
|
||||
|
||||
return $this->branchOptions() === [] ? null : array_key_first($this->branchOptions());
|
||||
}
|
||||
|
||||
private function resolveOrWarn(string $hash): ?string
|
||||
{
|
||||
$resolved = app(GitRepository::class)->resolveCommit($hash);
|
||||
|
||||
if (! $resolved) {
|
||||
Notification::make()
|
||||
->title('Ismeretlen commit')
|
||||
->body('A kiválasztott commit nem található a repóban.')
|
||||
->danger()
|
||||
->send();
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return $resolved;
|
||||
}
|
||||
}
|
||||
@ -82,19 +82,6 @@ public function save()
|
||||
{
|
||||
$data = $this->form->getState();
|
||||
|
||||
// Ugyanaz a védelem, mint a modern felületen: enélkül ez az oldal megkerülné a
|
||||
// beszállítói blokkolást, hiszen ugyanúgy PricelistFile-t hoz létre és láncot indít.
|
||||
if ($blockingFile = app(\App\Services\PricelistGuard::class)->blockingFileFor($data['supplier_id'] ?? null)) {
|
||||
Notification::make()
|
||||
->title('A beszállítóhoz jelenleg nem vihető fel árlista')
|
||||
->body(app(\App\Services\PricelistGuard::class)->blockingMessage($blockingFile))
|
||||
->danger()
|
||||
->persistent()
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$pricelistFile = PricelistFile::create([
|
||||
'filename' => $data['filename'],
|
||||
'supplier_id' => $data['supplier_id'],
|
||||
|
||||
@ -1,172 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Pages;
|
||||
|
||||
use App\Models\ProfitCenter;
|
||||
use App\Models\ProfitCenterSupplierCode;
|
||||
use App\Models\Supplier;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Forms\Concerns\InteractsWithForms;
|
||||
use Filament\Forms\Contracts\HasForms;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Schemas\Components\Grid;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Schemas\Components\Utilities\Set;
|
||||
use Filament\Schemas\Schema;
|
||||
use Laravel\Pennant\Feature;
|
||||
|
||||
class SupplierCustomerCodes extends Page implements HasForms
|
||||
{
|
||||
use InteractsWithForms;
|
||||
|
||||
protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-identification';
|
||||
|
||||
protected string $view = 'filament.pages.supplier-customer-codes';
|
||||
|
||||
protected static ?string $title = 'Beszállítói vevőkódok';
|
||||
|
||||
protected static ?string $navigationLabel = 'Beszállítói vevőkódok';
|
||||
|
||||
protected static bool $shouldRegisterNavigation = false;
|
||||
|
||||
public ?array $data = [];
|
||||
|
||||
/**
|
||||
* Rollout-védelem: a SupplierCustomerCode Pennant flag alapján dől el, ki éri el ezt
|
||||
* az oldalt - a topbar menüpont is ezt hívja (ld. speed-button-nav-bar.blade.php).
|
||||
*/
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
if (! $user = auth()->user()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return Feature::for($user)->active('SupplierCustomerCode');
|
||||
}
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
abort_unless(static::canAccess(), 403);
|
||||
|
||||
$this->form->fill();
|
||||
}
|
||||
|
||||
public function form(Schema $form): Schema
|
||||
{
|
||||
return $form
|
||||
->schema([
|
||||
Grid::make(2)
|
||||
->schema([
|
||||
Select::make('supplier_id')
|
||||
->label('Beszállító')
|
||||
->options(Supplier::query()->orderBy('name')->pluck('name', 'id'))
|
||||
->required()
|
||||
->searchable()
|
||||
->live()
|
||||
->afterStateUpdated(fn (?string $state, Set $set) => $this->loadSupplierData($state, $set)),
|
||||
TextInput::make('search')
|
||||
->label('Profitcenter keresése')
|
||||
->placeholder('Kezdjen el gépelni a szűküléshez...')
|
||||
->live(debounce: 300)
|
||||
->visible(fn (Get $get) => filled($get('supplier_id'))),
|
||||
]),
|
||||
Toggle::make('hasCustomerCode')
|
||||
->label('Vevőkód funkció aktív ennél a beszállítónál')
|
||||
->visible(fn (Get $get) => filled($get('supplier_id'))),
|
||||
Section::make('Profitcenterenkénti vevőkód')
|
||||
->visible(fn (Get $get) => filled($get('supplier_id')))
|
||||
->columns(3)
|
||||
->schema(fn (Get $get) => $this->profitCenterCodeFields($get('search'))),
|
||||
])
|
||||
->statePath('data');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, TextInput>
|
||||
*/
|
||||
private function profitCenterCodeFields(?string $search = null): array
|
||||
{
|
||||
return ProfitCenter::query()
|
||||
->when(filled($search), fn ($query) => $query->where('name', 'like', '%'.$search.'%'))
|
||||
->orderBy('name')
|
||||
->get()
|
||||
->map(fn (ProfitCenter $profitCenter) => TextInput::make("codes.{$profitCenter->id}")
|
||||
->label($profitCenter->name)
|
||||
->inlineLabel()
|
||||
->maxLength(255))
|
||||
->all();
|
||||
}
|
||||
|
||||
private function loadSupplierData(?string $supplierId, Set $set): void
|
||||
{
|
||||
$codes = [];
|
||||
|
||||
if ($supplierId) {
|
||||
$supplier = Supplier::find($supplierId);
|
||||
$set('hasCustomerCode', (bool) $supplier?->hasCustomerCode);
|
||||
|
||||
$codes = ProfitCenterSupplierCode::query()
|
||||
->where('supplier_id', $supplierId)
|
||||
->pluck('customerCode', 'profit_center_id')
|
||||
->all();
|
||||
} else {
|
||||
$set('hasCustomerCode', false);
|
||||
}
|
||||
|
||||
foreach (ProfitCenter::query()->pluck('id') as $profitCenterId) {
|
||||
$set("codes.{$profitCenterId}", $codes[$profitCenterId] ?? null);
|
||||
}
|
||||
}
|
||||
|
||||
protected function getFormActions(): array
|
||||
{
|
||||
return [
|
||||
Action::make('save')
|
||||
->label('Mentés')
|
||||
->submit('save')
|
||||
->color('primary'),
|
||||
];
|
||||
}
|
||||
|
||||
public function save(): void
|
||||
{
|
||||
$state = $this->form->getState();
|
||||
$supplierId = $state['supplier_id'];
|
||||
|
||||
Supplier::whereKey($supplierId)->update([
|
||||
'hasCustomerCode' => (bool) ($state['hasCustomerCode'] ?? false),
|
||||
]);
|
||||
|
||||
// A form aktuális szűrés (keresés) miatt csak a látható mezőket adná vissza a getState() -
|
||||
// a $this->data-ban viszont minden profitcenter kódja benne marad, mert a loadSupplierData()
|
||||
// mindegyiket explicit beállítja, függetlenül attól, hogy éppen renderelve van-e.
|
||||
foreach ($this->data['codes'] ?? [] as $profitCenterId => $customerCode) {
|
||||
$customerCode = is_string($customerCode) ? trim($customerCode) : $customerCode;
|
||||
|
||||
if (blank($customerCode)) {
|
||||
ProfitCenterSupplierCode::query()
|
||||
->where('supplier_id', $supplierId)
|
||||
->where('profit_center_id', $profitCenterId)
|
||||
->delete();
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
ProfitCenterSupplierCode::updateOrCreate(
|
||||
['supplier_id' => $supplierId, 'profit_center_id' => $profitCenterId],
|
||||
['customerCode' => $customerCode],
|
||||
);
|
||||
}
|
||||
|
||||
Notification::make()
|
||||
->title('Mentve')
|
||||
->body('A beszállító vevőkód adatai elmentve.')
|
||||
->success()
|
||||
->send();
|
||||
}
|
||||
}
|
||||
@ -1,51 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\FeatureFlagOverrides;
|
||||
|
||||
use App\Filament\Resources\FeatureFlagOverrides\Pages\CreateFeatureFlagOverride;
|
||||
use App\Filament\Resources\FeatureFlagOverrides\Pages\EditFeatureFlagOverride;
|
||||
use App\Filament\Resources\FeatureFlagOverrides\Pages\ListFeatureFlagOverrides;
|
||||
use App\Filament\Resources\FeatureFlagOverrides\Schemas\FeatureFlagOverrideForm;
|
||||
use App\Filament\Resources\FeatureFlagOverrides\Tables\FeatureFlagOverridesTable;
|
||||
use App\Models\FeatureFlagOverride;
|
||||
use BackedEnum;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
class FeatureFlagOverrideResource extends Resource
|
||||
{
|
||||
protected static ?string $model = FeatureFlagOverride::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-user-circle';
|
||||
|
||||
protected static string|\UnitEnum|null $navigationGroup = 'Rendszer';
|
||||
|
||||
protected static ?string $navigationLabel = 'Egyéni felülbírálások';
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return FeatureFlagOverrideForm::configure($schema);
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return FeatureFlagOverridesTable::configure($table);
|
||||
}
|
||||
|
||||
public static function getRelations(): array
|
||||
{
|
||||
return [
|
||||
//
|
||||
];
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ListFeatureFlagOverrides::route('/'),
|
||||
'create' => CreateFeatureFlagOverride::route('/create'),
|
||||
'edit' => EditFeatureFlagOverride::route('/{record}/edit'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -1,11 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\FeatureFlagOverrides\Pages;
|
||||
|
||||
use App\Filament\Resources\FeatureFlagOverrides\FeatureFlagOverrideResource;
|
||||
use Filament\Resources\Pages\CreateRecord;
|
||||
|
||||
class CreateFeatureFlagOverride extends CreateRecord
|
||||
{
|
||||
protected static string $resource = FeatureFlagOverrideResource::class;
|
||||
}
|
||||
@ -1,19 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\FeatureFlagOverrides\Pages;
|
||||
|
||||
use App\Filament\Resources\FeatureFlagOverrides\FeatureFlagOverrideResource;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
|
||||
class EditFeatureFlagOverride extends EditRecord
|
||||
{
|
||||
protected static string $resource = FeatureFlagOverrideResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
DeleteAction::make(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -1,19 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\FeatureFlagOverrides\Pages;
|
||||
|
||||
use App\Filament\Resources\FeatureFlagOverrides\FeatureFlagOverrideResource;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
|
||||
class ListFeatureFlagOverrides extends ListRecords
|
||||
{
|
||||
protected static string $resource = FeatureFlagOverrideResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
CreateAction::make(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -1,34 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\FeatureFlagOverrides\Schemas;
|
||||
|
||||
use App\Models\FeatureFlag;
|
||||
use App\Models\User;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Schemas\Schema;
|
||||
|
||||
class FeatureFlagOverrideForm
|
||||
{
|
||||
public static function configure(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->components([
|
||||
Select::make('feature_flag_id')
|
||||
->label('Feature flag')
|
||||
->searchable()
|
||||
->options(fn () => FeatureFlag::pluck('label', 'id'))
|
||||
->disabledOn('edit')
|
||||
->required(),
|
||||
Select::make('user_id')
|
||||
->label('Felhasználó')
|
||||
->searchable()
|
||||
->options(fn () => User::pluck('name', 'id'))
|
||||
->disabledOn('edit')
|
||||
->required(),
|
||||
Toggle::make('active')
|
||||
->label('Bekapcsolva')
|
||||
->required(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@ -1,55 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\FeatureFlagOverrides\Tables;
|
||||
|
||||
use App\Models\FeatureFlag;
|
||||
use App\Models\User;
|
||||
use Filament\Actions\BulkActionGroup;
|
||||
use Filament\Actions\DeleteBulkAction;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Tables\Columns\IconColumn;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Filters\SelectFilter;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
class FeatureFlagOverridesTable
|
||||
{
|
||||
public static function configure(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->columns([
|
||||
TextColumn::make('featureFlag.label')
|
||||
->label('Feature flag')
|
||||
->searchable()
|
||||
->sortable(),
|
||||
TextColumn::make('user.name')
|
||||
->label('Felhasználó')
|
||||
->searchable()
|
||||
->sortable(),
|
||||
IconColumn::make('active')
|
||||
->label('Állapot')
|
||||
->boolean(),
|
||||
TextColumn::make('updated_at')
|
||||
->label('Módosítva')
|
||||
->dateTime()
|
||||
->sortable(),
|
||||
])
|
||||
->filters([
|
||||
SelectFilter::make('feature_flag_id')
|
||||
->label('Feature flag')
|
||||
->options(fn () => FeatureFlag::pluck('label', 'id')),
|
||||
SelectFilter::make('user_id')
|
||||
->label('Felhasználó')
|
||||
->options(fn () => User::pluck('name', 'id'))
|
||||
->searchable(),
|
||||
])
|
||||
->recordActions([
|
||||
EditAction::make(),
|
||||
])
|
||||
->toolbarActions([
|
||||
BulkActionGroup::make([
|
||||
DeleteBulkAction::make(),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@ -1,52 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\FeatureFlags;
|
||||
|
||||
use App\Filament\Resources\FeatureFlags\Pages\CreateFeatureFlag;
|
||||
use App\Filament\Resources\FeatureFlags\Pages\EditFeatureFlag;
|
||||
use App\Filament\Resources\FeatureFlags\Pages\ListFeatureFlags;
|
||||
use App\Filament\Resources\FeatureFlags\RelationManagers\OverridesRelationManager;
|
||||
use App\Filament\Resources\FeatureFlags\Schemas\FeatureFlagForm;
|
||||
use App\Filament\Resources\FeatureFlags\Tables\FeatureFlagsTable;
|
||||
use App\Models\FeatureFlag;
|
||||
use BackedEnum;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
class FeatureFlagResource extends Resource
|
||||
{
|
||||
protected static ?string $model = FeatureFlag::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-flag';
|
||||
|
||||
protected static string|\UnitEnum|null $navigationGroup = 'Rendszer';
|
||||
|
||||
protected static ?string $navigationLabel = 'Feature flagek';
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return FeatureFlagForm::configure($schema);
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return FeatureFlagsTable::configure($table);
|
||||
}
|
||||
|
||||
public static function getRelations(): array
|
||||
{
|
||||
return [
|
||||
OverridesRelationManager::class,
|
||||
];
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ListFeatureFlags::route('/'),
|
||||
'create' => CreateFeatureFlag::route('/create'),
|
||||
'edit' => EditFeatureFlag::route('/{record}/edit'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -1,11 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\FeatureFlags\Pages;
|
||||
|
||||
use App\Filament\Resources\FeatureFlags\FeatureFlagResource;
|
||||
use Filament\Resources\Pages\CreateRecord;
|
||||
|
||||
class CreateFeatureFlag extends CreateRecord
|
||||
{
|
||||
protected static string $resource = FeatureFlagResource::class;
|
||||
}
|
||||
@ -1,19 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\FeatureFlags\Pages;
|
||||
|
||||
use App\Filament\Resources\FeatureFlags\FeatureFlagResource;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
|
||||
class EditFeatureFlag extends EditRecord
|
||||
{
|
||||
protected static string $resource = FeatureFlagResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
DeleteAction::make(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -1,19 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\FeatureFlags\Pages;
|
||||
|
||||
use App\Filament\Resources\FeatureFlags\FeatureFlagResource;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
|
||||
class ListFeatureFlags extends ListRecords
|
||||
{
|
||||
protected static string $resource = FeatureFlagResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
CreateAction::make(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -1,63 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\FeatureFlags\RelationManagers;
|
||||
|
||||
use App\Models\User;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Resources\RelationManagers\RelationManager;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Tables\Columns\IconColumn;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
class OverridesRelationManager extends RelationManager
|
||||
{
|
||||
protected static string $relationship = 'overrides';
|
||||
|
||||
protected static ?string $title = 'Egyéni felülbírálások';
|
||||
|
||||
public function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->components([
|
||||
Select::make('user_id')
|
||||
->label('Felhasználó')
|
||||
->searchable()
|
||||
->options(fn () => User::pluck('name', 'id'))
|
||||
->disabledOn('edit')
|
||||
->required(),
|
||||
Toggle::make('active')
|
||||
->label('Bekapcsolva')
|
||||
->required(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->recordTitleAttribute('user.name')
|
||||
->columns([
|
||||
TextColumn::make('user.name')
|
||||
->label('Felhasználó')
|
||||
->searchable(),
|
||||
IconColumn::make('active')
|
||||
->label('Állapot')
|
||||
->boolean(),
|
||||
TextColumn::make('updated_at')
|
||||
->label('Módosítva')
|
||||
->dateTime()
|
||||
->sortable(),
|
||||
])
|
||||
->headerActions([
|
||||
CreateAction::make(),
|
||||
])
|
||||
->recordActions([
|
||||
EditAction::make(),
|
||||
DeleteAction::make(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@ -1,55 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\FeatureFlags\Schemas;
|
||||
|
||||
use App\Models\Role;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TagsInput;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Schema;
|
||||
|
||||
class FeatureFlagForm
|
||||
{
|
||||
public static function configure(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->components([
|
||||
Section::make('Alapadatok')
|
||||
->columnSpanFull()
|
||||
->schema([
|
||||
TextInput::make('name')
|
||||
->label('Kulcs')
|
||||
->helperText('Ezt a kulcsot kell használni a kódban: Feature::active(\'kulcs\')')
|
||||
->required()
|
||||
->unique(ignoreRecord: true)
|
||||
->maxLength(255),
|
||||
TextInput::make('label')
|
||||
->label('Megnevezés')
|
||||
->required()
|
||||
->maxLength(255),
|
||||
Textarea::make('description')
|
||||
->label('Leírás')
|
||||
->columnSpanFull(),
|
||||
Toggle::make('enabled')
|
||||
->label('Bekapcsolva (rendszer szintű kapcsoló)')
|
||||
->default(true),
|
||||
]),
|
||||
Section::make('Célzás')
|
||||
->columnSpanFull()
|
||||
->schema([
|
||||
TagsInput::make('stages')
|
||||
->label('Stage-ek')
|
||||
->helperText('Üresen hagyva minden környezeten aktív. Ismert értékek: DEV, TEST, PROD, d2dtst, e2etst.')
|
||||
->placeholder('pl. TEST'),
|
||||
Select::make('roles')
|
||||
->label('Szerepkörök')
|
||||
->helperText('Üresen hagyva minden szerepkörnek aktív.')
|
||||
->multiple()
|
||||
->options(fn () => Role::pluck('display_name', 'name')->filter()->all()),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@ -1,92 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\FeatureFlags\Tables;
|
||||
|
||||
use App\Models\FeatureFlag;
|
||||
use App\Models\FeatureFlagOverride;
|
||||
use App\Models\User;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\BulkActionGroup;
|
||||
use Filament\Actions\DeleteBulkAction;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Forms\Components\Radio;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Columns\ToggleColumn;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
class FeatureFlagsTable
|
||||
{
|
||||
public static function configure(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->columns([
|
||||
TextColumn::make('name')
|
||||
->label('Kulcs')
|
||||
->searchable()
|
||||
->sortable(),
|
||||
TextColumn::make('label')
|
||||
->label('Megnevezés')
|
||||
->searchable(),
|
||||
ToggleColumn::make('enabled')
|
||||
->label('Bekapcsolva'),
|
||||
TextColumn::make('stages')
|
||||
->label('Stage-ek')
|
||||
->badge()
|
||||
->placeholder('mind'),
|
||||
TextColumn::make('roles')
|
||||
->label('Szerepkörök')
|
||||
->badge()
|
||||
->placeholder('mind'),
|
||||
TextColumn::make('updated_at')
|
||||
->label('Módosítva')
|
||||
->dateTime()
|
||||
->sortable(),
|
||||
])
|
||||
->recordActions([
|
||||
EditAction::make(),
|
||||
Action::make('userOverride')
|
||||
->label('Egyéni felülbírálás')
|
||||
->icon('heroicon-o-user')
|
||||
->form([
|
||||
Select::make('user_id')
|
||||
->label('Felhasználó')
|
||||
->searchable()
|
||||
->options(fn () => User::pluck('name', 'id'))
|
||||
->required(),
|
||||
Radio::make('override')
|
||||
->label('Állapot')
|
||||
->options([
|
||||
'inherit' => 'Örökölt (alapértelmezett szabály érvényes)',
|
||||
'on' => 'Bekapcsolva',
|
||||
'off' => 'Kikapcsolva',
|
||||
])
|
||||
->default('inherit')
|
||||
->required(),
|
||||
])
|
||||
->action(function (array $data, FeatureFlag $record) {
|
||||
$user = User::findOrFail($data['user_id']);
|
||||
|
||||
if ($data['override'] === 'inherit') {
|
||||
// model-instance delete() kell, hogy a FeatureFlagOverrideObserver
|
||||
// (Pennant purge) ténylegesen kiváltódjon - a query builder delete()
|
||||
// nem hívja meg a modell eseményeit
|
||||
FeatureFlagOverride::where('feature_flag_id', $record->id)
|
||||
->where('user_id', $user->id)
|
||||
->first()
|
||||
?->delete();
|
||||
} else {
|
||||
FeatureFlagOverride::updateOrCreate(
|
||||
['feature_flag_id' => $record->id, 'user_id' => $user->id],
|
||||
['active' => $data['override'] === 'on'],
|
||||
);
|
||||
}
|
||||
}),
|
||||
])
|
||||
->toolbarActions([
|
||||
BulkActionGroup::make([
|
||||
DeleteBulkAction::make(),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@ -3,40 +3,12 @@
|
||||
namespace App\Filament\Resources\PricelistFiles\Pages;
|
||||
|
||||
use App\Filament\Resources\PricelistFiles\PricelistFileResource;
|
||||
use App\Services\PricelistGuard;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Pages\CreateRecord;
|
||||
use Filament\Support\Exceptions\Halt;
|
||||
|
||||
class CreatePricelistFile extends CreateRecord
|
||||
{
|
||||
protected static string $resource = PricelistFileResource::class;
|
||||
|
||||
/**
|
||||
* A beszállító nem blokkolt-e egy befejezetlen végrehajtás miatt.
|
||||
*
|
||||
* A beszállító szándékosan választható marad az űrlapon: ha egyszerűen kivennénk a
|
||||
* listából, a felhasználó csak annyit látna, hogy "eltűnt a beszállító", és keresné
|
||||
* az okát. Így viszont konkrét magyarázatot kap arról, melyik fájl blokkol.
|
||||
*/
|
||||
protected function beforeCreate(): void
|
||||
{
|
||||
$blockingFile = app(PricelistGuard::class)->blockingFileFor($this->data['supplier_id'] ?? null);
|
||||
|
||||
if (! $blockingFile) {
|
||||
return;
|
||||
}
|
||||
|
||||
Notification::make()
|
||||
->title('A beszállítóhoz jelenleg nem vihető fel árlista')
|
||||
->body(app(PricelistGuard::class)->blockingMessage($blockingFile))
|
||||
->danger()
|
||||
->persistent()
|
||||
->send();
|
||||
|
||||
throw new Halt;
|
||||
}
|
||||
|
||||
protected function afterCreate(): void
|
||||
{
|
||||
app(\App\Services\PricelistFileProcessService::class)->dispatchInitialChain($this->record);
|
||||
|
||||
@ -27,10 +27,7 @@ protected function getHeaderActions(): array
|
||||
|
||||
protected function afterSave(): void
|
||||
{
|
||||
// A hasExecutionStarted() védelem itt a lényegi: ez a metódus indítja újra a
|
||||
// TELJES feldolgozási láncot. Ha a végrehajtás egyszer már futott, egy
|
||||
// nulláról induló újrafuttatás duplikált termékeket és árakat hozna létre.
|
||||
if ($this->record->status === PricelistFileStatusEnum::fail && ! $this->record->hasExecutionStarted()) {
|
||||
if ($this->record->status === PricelistFileStatusEnum::fail) {
|
||||
app(PricelistFileProcessService::class)->dispatchInitialChain($this->record);
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,18 +2,10 @@
|
||||
|
||||
namespace App\Filament\Resources\PricelistFiles\Pages;
|
||||
|
||||
use App\Enums\PricelistFileLineStatusEnum;
|
||||
use App\Enums\PricelistFileStatusEnum;
|
||||
use App\Filament\Resources\PricelistFiles\PricelistFileResource;
|
||||
use App\Models\PricelistFile;
|
||||
use App\Services\PricelistFileProcessService;
|
||||
use App\Services\PricelistGuard;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Pages\ViewRecord;
|
||||
use Laravel\Pennant\Feature;
|
||||
use App\Enums\PricelistFileStatusEnum;
|
||||
|
||||
class ViewPricelistFile extends ViewRecord
|
||||
{
|
||||
@ -22,246 +14,11 @@ class ViewPricelistFile extends ViewRecord
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
$this->approveAction(),
|
||||
$this->rejectAction(),
|
||||
// A visszavonás az elsődleges (primary) akció: egy megszakadt végrehajtás
|
||||
// után a gyakoribb helyes válasz a visszavonás + új árlista, a folytatás
|
||||
// jellemzően csak átmeneti hibánál (deadlock, kapcsolatvesztés) segít.
|
||||
$this->revertAction(),
|
||||
$this->continueExecutionAction(),
|
||||
$this->forceCloseAction(),
|
||||
EditAction::make()
|
||||
// A `fail` a validálásig tartó szakasz hibája, onnan a fájl újratöltése
|
||||
// biztonságosan újraindítja a láncot. A hasExecutionStarted() extra
|
||||
// feltétel a maradék kockázatot zárja ki: ha a végrehajtás egyszer már
|
||||
// elindult, a nulláról induló újrafuttatás duplikált termékeket és
|
||||
// árakat hozna létre.
|
||||
->visible(fn (PricelistFile $record) => $record->status === PricelistFileStatusEnum::fail
|
||||
&& ! $record->hasExecutionStarted()),
|
||||
->visible(fn ($record) => $record->status === PricelistFileStatusEnum::fail),
|
||||
];
|
||||
}
|
||||
|
||||
protected function approveAction(): Action
|
||||
{
|
||||
return Action::make('approve')
|
||||
->label('Jóváhagyás')
|
||||
->icon('heroicon-o-check-circle')
|
||||
->color('success')
|
||||
->visible(fn (PricelistFile $record) => $this->canDecide($record))
|
||||
->requiresConfirmation()
|
||||
->modalHeading('Árlista jóváhagyása')
|
||||
->modalDescription(fn (PricelistFile $record) => 'A jóváhagyás elindítja a tényleges importot: '
|
||||
. $this->summarizeLines($record)
|
||||
. ' A művelet a termékadatokat is módosítja.')
|
||||
->modalSubmitActionLabel('Jóváhagyás és végrehajtás')
|
||||
->action(function (PricelistFile $record) {
|
||||
if (! app(PricelistFileProcessService::class)->approve($record)) {
|
||||
$this->notifyStateChanged();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
Notification::make()
|
||||
->title('Végrehajtás elindítva')
|
||||
->body('Az árlista importja elindult, a haladás ezen az oldalon követhető.')
|
||||
->success()
|
||||
->send();
|
||||
});
|
||||
}
|
||||
|
||||
protected function rejectAction(): Action
|
||||
{
|
||||
return Action::make('reject')
|
||||
->label('Elutasítás')
|
||||
->icon('heroicon-o-x-circle')
|
||||
->color('danger')
|
||||
->visible(fn (PricelistFile $record) => $this->canDecide($record))
|
||||
->requiresConfirmation()
|
||||
->modalHeading('Árlista elutasítása')
|
||||
->modalDescription('A fájl lezárva státuszba kerül, import nem indul. A művelet nem vonható vissza.')
|
||||
->modalSubmitActionLabel('Elutasítás')
|
||||
->schema([
|
||||
Textarea::make('reason')
|
||||
->label('Elutasítás indoka')
|
||||
->rows(3)
|
||||
->maxLength(1000),
|
||||
])
|
||||
->action(function (PricelistFile $record, array $data) {
|
||||
if (! app(PricelistFileProcessService::class)->reject($record, $data['reason'] ?? null)) {
|
||||
$this->notifyStateChanged();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
Notification::make()
|
||||
->title('Árlista elutasítva')
|
||||
->body('A fájl lezárva státuszba került.')
|
||||
->success()
|
||||
->send();
|
||||
});
|
||||
}
|
||||
|
||||
protected function revertAction(): Action
|
||||
{
|
||||
return Action::make('revert')
|
||||
->label('Végrehajtás visszavonása')
|
||||
->icon('heroicon-o-arrow-uturn-left')
|
||||
->color('primary')
|
||||
->visible(fn (PricelistFile $record) => $this->canDecideOnExecution($record))
|
||||
->requiresConfirmation()
|
||||
->modalHeading('Végrehajtás visszavonása')
|
||||
->modalDescription(fn (PricelistFile $record) => $this->summarizeExecution($record)
|
||||
. ' A visszavonás visszaállítja a frissített termékeket a mentett állapotukra, a létrehozott termékeket kivonja a forgalomból, és törli a rögzített árakat.'
|
||||
. ' Ha egy terméket a végrehajtás óta kézzel módosítottak, azt a sort kihagyjuk, és a végén jelentjük.')
|
||||
->modalSubmitActionLabel('Visszavonás indítása')
|
||||
->action(function (PricelistFile $record) {
|
||||
app(PricelistFileProcessService::class)->dispatchRevertJob($record);
|
||||
|
||||
Notification::make()
|
||||
->title('Visszavonás elindítva')
|
||||
->body('A visszaállítás fut, a haladás ezen az oldalon követhető.')
|
||||
->success()
|
||||
->send();
|
||||
});
|
||||
}
|
||||
|
||||
protected function continueExecutionAction(): Action
|
||||
{
|
||||
return Action::make('continueExecution')
|
||||
->label('Végrehajtás folytatása')
|
||||
->icon('heroicon-o-play')
|
||||
->color('gray')
|
||||
->visible(fn (PricelistFile $record) => $this->canDecideOnExecution($record))
|
||||
->requiresConfirmation()
|
||||
->modalHeading('Végrehajtás folytatása')
|
||||
->modalDescription(fn (PricelistFile $record) => $this->summarizeExecution($record)
|
||||
. ' A folytatás onnan viszi tovább a feldolgozást, ahol megszakadt - a már feldolgozott sorok kimaradnak, tehát nem keletkezik duplikátum.')
|
||||
->modalSubmitActionLabel('Folytatás')
|
||||
->action(function (PricelistFile $record) {
|
||||
app(PricelistFileProcessService::class)->dispatchExecutionJob($record);
|
||||
|
||||
Notification::make()
|
||||
->title('Végrehajtás folytatása elindítva')
|
||||
->success()
|
||||
->send();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Felügyelt kényszerlezárás. Két külön kapu védi: a rollout flag ÉS a developer
|
||||
* szerepkör. Utóbbi a flag eltávolítása után is megmarad - a "lezárom anélkül, hogy
|
||||
* rendbe tenném az adatokat" művelet tartósan nem való minden árlistakezelőnek.
|
||||
*/
|
||||
protected function forceCloseAction(): Action
|
||||
{
|
||||
return Action::make('forceClose')
|
||||
->label('Kényszerlezárás')
|
||||
->icon('heroicon-o-lock-closed')
|
||||
->color('danger')
|
||||
->visible(fn (PricelistFile $record) => Feature::for(auth()->user())->active('PricelistExecution')
|
||||
&& auth()->user()?->hasRole('developer')
|
||||
&& $record->canBeForceClosed())
|
||||
->requiresConfirmation()
|
||||
->modalHeading('Kényszerlezárás')
|
||||
->modalDescription('A fájl lezárva státuszba kerül anélkül, hogy bármit visszaállítanánk. A végrehajtás által írt termék- és áradatok az adatbázisban maradnak, rendezetlenül. Csak akkor használd, ha a visszaállítás nem tud lefutni.')
|
||||
->modalSubmitActionLabel('Kényszerlezárás')
|
||||
->schema([
|
||||
Textarea::make('reason')
|
||||
->label('Indoklás')
|
||||
->helperText('Rögzítjük, ki, mikor és miért oldotta fel a fájlt visszaállítás nélkül.')
|
||||
->required()
|
||||
->rows(3)
|
||||
->maxLength(1000)
|
||||
->default(fn (PricelistFile $record) => $record->file_meta['revert']['last_error'] ?? null),
|
||||
])
|
||||
->action(function (PricelistFile $record, array $data) {
|
||||
if (! app(PricelistFileProcessService::class)->forceClose($record, $data['reason'])) {
|
||||
$this->notifyStateChanged();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
Notification::make()
|
||||
->title('A fájl kényszerlezárva')
|
||||
->body('A beszállító árlista-felvitele újra engedélyezett. Az adatok rendezése kézi feladat maradt.')
|
||||
->warning()
|
||||
->send();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* A megszakadt végrehajtás utáni döntési gombok közös feltétele.
|
||||
*/
|
||||
protected function canDecideOnExecution(PricelistFile $record): bool
|
||||
{
|
||||
return Feature::for(auth()->user())->active('PricelistExecution')
|
||||
&& $record->needsExecutionDecision();
|
||||
}
|
||||
|
||||
protected function summarizeExecution(PricelistFile $record): string
|
||||
{
|
||||
$summary = $record->executionSummary();
|
||||
|
||||
return sprintf(
|
||||
'A megszakadt végrehajtásból eddig: %d létrehozott termék, %d frissített termék, %d rögzített ár, %d hátralévő sor.',
|
||||
$summary['created_products'],
|
||||
$summary['updated_products'],
|
||||
$summary['priced_lines'],
|
||||
$summary['pending_lines'],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A döntési gombok közös feltétele: a rollout flag és a fájl jóváhagyhatósága.
|
||||
* A canBeApproved() a modellben él, mert ugyanezt a service is ellenőrzi a
|
||||
* művelet végrehajtásakor - a felület csak elrejti a gombot, a védelmet a
|
||||
* service adja.
|
||||
*/
|
||||
protected function canDecide(PricelistFile $record): bool
|
||||
{
|
||||
return Feature::for(auth()->user())->active('PricelistExecution')
|
||||
&& $record->canBeApproved()
|
||||
// Ugyanahhoz a beszállítóhoz nem lehet két nyitott végrehajtás.
|
||||
&& ! app(PricelistGuard::class)->isBlocked($record->supplier_id, $record->id);
|
||||
}
|
||||
|
||||
/**
|
||||
* A jóváhagyás előtti összegzés: mit fog csinálni az import.
|
||||
*/
|
||||
protected function summarizeLines(PricelistFile $record): string
|
||||
{
|
||||
$counts = $record->lineStatusCounts();
|
||||
|
||||
$parts = [];
|
||||
foreach ([
|
||||
PricelistFileLineStatusEnum::new_product,
|
||||
PricelistFileLineStatusEnum::updated,
|
||||
PricelistFileLineStatusEnum::ok,
|
||||
PricelistFileLineStatusEnum::warning,
|
||||
] as $status) {
|
||||
$count = (int) ($counts[$status->value] ?? 0);
|
||||
if ($count > 0) {
|
||||
$parts[] = $count . ' ' . $status->label();
|
||||
}
|
||||
}
|
||||
|
||||
return $parts === [] ? 'nincs feldolgozandó sor.' : implode(', ', $parts) . '.';
|
||||
}
|
||||
|
||||
/**
|
||||
* A felület 5 mp-enként pollozik, így a gomb megjelenítése és a kattintás között
|
||||
* változhat az állapot (pl. más felhasználó közben jóváhagyta). Ilyenkor a service
|
||||
* elutasítja a műveletet, a felhasználónak pedig ezt meg kell mondani.
|
||||
*/
|
||||
protected function notifyStateChanged(): void
|
||||
{
|
||||
Notification::make()
|
||||
->title('A művelet nem hajtható végre')
|
||||
->body('A fájl állapota időközben megváltozott. Frissítsd az oldalt a jelenlegi állapotért.')
|
||||
->warning()
|
||||
->send();
|
||||
}
|
||||
|
||||
protected function getHeaderWidgets(): array
|
||||
{
|
||||
return [
|
||||
|
||||
@ -162,30 +162,6 @@ public function form(Schema $schema): Schema
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Egy payload mező szövegként, a nézet eltörése nélkül.
|
||||
*
|
||||
* A régebbi rekordokban a rich text cellák ÜRES TÖMBKÉNT landoltak a payloadban
|
||||
* (a `json_encode` a RichText objektumot `{}`-ra serializálta). A TextColumn
|
||||
* `description()`-je viszont csak stringet vagy Htmlable-t fogad el, tömbre
|
||||
* TypeError-ral elszáll, és ilyenkor a teljes sorok-blokk nem jelenik meg.
|
||||
* A beolvasás azóta normalizál (PricelistFileProcessService::normalizeCellValue),
|
||||
* de a MÁR ELMENTETT sorok csak így maradnak megjeleníthetők.
|
||||
*/
|
||||
protected static function payloadText($record, int $headerIndex): string
|
||||
{
|
||||
$value = $record->payload[PriceListService::EXPECTED_HEADERS[$headerIndex]] ?? null;
|
||||
|
||||
if (is_array($value)) {
|
||||
$value = implode(' ', array_filter(
|
||||
\Illuminate\Support\Arr::flatten($value),
|
||||
fn ($item) => is_scalar($item),
|
||||
));
|
||||
}
|
||||
|
||||
return is_scalar($value) ? trim((string) $value) : '';
|
||||
}
|
||||
|
||||
public function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
@ -206,8 +182,8 @@ public function table(Table $table): Table
|
||||
|
||||
TextColumn::make('product_info')
|
||||
->label('Termék')
|
||||
->description(fn ($record) => self::payloadText($record, 4))
|
||||
->getStateUsing(fn ($record) => self::payloadText($record, 0) ?: 'N/A')
|
||||
->description(fn ($record) => $record->payload[PriceListService::EXPECTED_HEADERS[4]] ?? '')
|
||||
->getStateUsing(fn ($record) => $record->payload[PriceListService::EXPECTED_HEADERS[0]] ?? 'N/A')
|
||||
->color(fn ($record) => !empty($record->diff) ? 'info' : null)
|
||||
->wrap()
|
||||
->searchable(query: function ($query, string $search) {
|
||||
|
||||
@ -3,8 +3,6 @@
|
||||
namespace App\Filament\Resources\PricelistFiles\Schemas;
|
||||
|
||||
use App\Enums\PricelistFileStatusEnum;
|
||||
use App\Models\PricelistFile;
|
||||
use App\Services\PricelistGuard;
|
||||
use Filament\Schemas\Components\Grid;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Text;
|
||||
@ -21,71 +19,6 @@ public static function configure(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->components([
|
||||
// Döntéstámogató panel: megszakadt végrehajtás után a felhasználónak a
|
||||
// Folytatás és a Visszavonás között kell választania. Enélkül vakon
|
||||
// döntene - itt látja, mi történt már meg az importból.
|
||||
Section::make('Megszakadt végrehajtás')
|
||||
->description('A végrehajtás nem fejeződött be. Az árlista nem élesedett, tehát a felhasználók felé nem került ki ár. Döntsd el, folytatod-e, vagy visszavonod a már végrehajtott részt.')
|
||||
->icon('heroicon-o-exclamation-triangle')
|
||||
->columnSpanFull()
|
||||
->maxWidth(Width::Full)
|
||||
->visible(fn ($record) => $record->needsExecutionDecision())
|
||||
->schema([
|
||||
TextEntry::make('execution_error')
|
||||
->label('Hiba')
|
||||
->color('danger')
|
||||
->weight(FontWeight::Bold)
|
||||
->columnSpanFull()
|
||||
->getStateUsing(fn ($record) => $record->isExecutionStuck()
|
||||
? 'A végrehajtás ' . PricelistFile::STUCK_AFTER_MINUTES . ' percnél régebben nem jelzett haladást (elakadt folyamat).'
|
||||
: ($record->processing_current_step ?: 'Ismeretlen hiba.')),
|
||||
Grid::make(4)->schema([
|
||||
TextEntry::make('created_products')
|
||||
->label('Létrehozott termék')
|
||||
->icon('heroicon-o-plus-circle')
|
||||
->getStateUsing(fn ($record) => $record->executionSummary()['created_products']),
|
||||
TextEntry::make('updated_products')
|
||||
->label('Frissített termék')
|
||||
->icon('heroicon-o-pencil-square')
|
||||
->getStateUsing(fn ($record) => $record->executionSummary()['updated_products']),
|
||||
TextEntry::make('priced_lines')
|
||||
->label('Rögzített ár')
|
||||
->icon('heroicon-o-currency-dollar')
|
||||
->getStateUsing(fn ($record) => $record->executionSummary()['priced_lines']),
|
||||
TextEntry::make('pending_lines')
|
||||
->label('Hátralévő sor')
|
||||
->icon('heroicon-o-clock')
|
||||
->getStateUsing(fn ($record) => $record->executionSummary()['pending_lines']),
|
||||
]),
|
||||
TextEntry::make('revert_error')
|
||||
->label('Utolsó visszaállítási kísérlet hibája')
|
||||
->color('danger')
|
||||
->columnSpanFull()
|
||||
->visible(fn ($record) => ($record->file_meta['revert']['last_status'] ?? null) === 'failed')
|
||||
->getStateUsing(fn ($record) => $record->file_meta['revert']['last_error'] ?? null),
|
||||
]),
|
||||
|
||||
// A jóváhagyás gombjai némán tűnnének el, ha ugyanahhoz a beszállítóhoz
|
||||
// egy másik fájl végrehajtása van nyitva - ez megmondja, miért.
|
||||
Section::make('Blokkolt beszállító')
|
||||
->icon('heroicon-o-no-symbol')
|
||||
->columnSpanFull()
|
||||
->maxWidth(Width::Full)
|
||||
->visible(fn ($record) => $record->status === PricelistFileStatusEnum::waiting_for_approval
|
||||
&& app(PricelistGuard::class)->isBlocked($record->supplier_id, $record->id))
|
||||
->schema([
|
||||
TextEntry::make('blocking_file')
|
||||
->hiddenLabel()
|
||||
->color('danger')
|
||||
->columnSpanFull()
|
||||
->getStateUsing(function ($record) {
|
||||
$guard = app(PricelistGuard::class);
|
||||
$blockingFile = $guard->blockingFileFor($record->supplier_id, $record->id);
|
||||
|
||||
return $blockingFile ? $guard->blockingMessage($blockingFile) : null;
|
||||
}),
|
||||
]),
|
||||
|
||||
Section::make(null)
|
||||
->poll('5s')
|
||||
->columnSpanFull()
|
||||
@ -114,7 +47,14 @@ public static function configure(Schema $schema): Schema
|
||||
->label('Státusz')
|
||||
->badge()
|
||||
->formatStateUsing(fn (PricelistFileStatusEnum $state): string => $state->label())
|
||||
->color(fn (PricelistFileStatusEnum $state): string => $state->color()),
|
||||
->color(fn (PricelistFileStatusEnum $state): string => match ($state) {
|
||||
PricelistFileStatusEnum::todo => 'gray',
|
||||
PricelistFileStatusEnum::inprogress => 'info',
|
||||
PricelistFileStatusEnum::done => 'success',
|
||||
PricelistFileStatusEnum::fail => 'danger',
|
||||
PricelistFileStatusEnum::waiting_for_approval => 'primary',
|
||||
PricelistFileStatusEnum::closed => 'warning',
|
||||
}),
|
||||
]),
|
||||
Grid::make(3)
|
||||
->schema([
|
||||
|
||||
@ -32,7 +32,14 @@ public static function configure(Table $table): Table
|
||||
->label('Státusz')
|
||||
->badge()
|
||||
->formatStateUsing(fn (PricelistFileStatusEnum $state): string => $state->label())
|
||||
->color(fn (PricelistFileStatusEnum $state): string => $state->color())
|
||||
->color(fn (PricelistFileStatusEnum $state): string => match ($state) {
|
||||
PricelistFileStatusEnum::todo => 'gray',
|
||||
PricelistFileStatusEnum::inprogress => 'info',
|
||||
PricelistFileStatusEnum::done => 'success',
|
||||
PricelistFileStatusEnum::fail => 'danger',
|
||||
PricelistFileStatusEnum::waiting_for_approval => 'primary',
|
||||
PricelistFileStatusEnum::closed => 'warning',
|
||||
})
|
||||
->sortable(),
|
||||
TextColumn::make('processing_current_step')
|
||||
->label('Aktuális lépés')
|
||||
@ -52,10 +59,7 @@ public static function configure(Table $table): Table
|
||||
->recordActions([
|
||||
ViewAction::make(),
|
||||
EditAction::make()
|
||||
// Ha a végrehajtás már elindult, az újratöltés (és a vele járó
|
||||
// teljes lánc-újraindítás) duplikált termékeket/árakat okozna.
|
||||
->visible(fn ($record) => $record->status === PricelistFileStatusEnum::fail
|
||||
&& ! $record->hasExecutionStarted()),
|
||||
->visible(fn ($record) => $record->status === PricelistFileStatusEnum::fail),
|
||||
])
|
||||
->toolbarActions([
|
||||
BulkActionGroup::make([
|
||||
|
||||
@ -1,34 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Producers\Pages;
|
||||
|
||||
use App\Enums\DbStatusFieldEnum;
|
||||
use App\Filament\Resources\Producers\ProducerResource;
|
||||
use Filament\Resources\Pages\CreateRecord;
|
||||
|
||||
class CreateProducer extends CreateRecord
|
||||
{
|
||||
protected static string $resource = ProducerResource::class;
|
||||
|
||||
/**
|
||||
* Ugyanaz az alapállapot, mint amikor az árlista-feldolgozó hoz létre új gyártót
|
||||
* (PricelistFileProcessService::createMissingProducers()) - a kézi felvételnek nem
|
||||
* kell külön mezőt adni ehhez, mindig aktív és látható.
|
||||
*/
|
||||
protected function mutateFormDataBeforeCreate(array $data): array
|
||||
{
|
||||
$data['status'] = DbStatusFieldEnum::active;
|
||||
$data['canSee'] = 1;
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* A megtekintő oldalra irányít vissza, nem a listára - onnan tud rögtön aliast is
|
||||
* felvenni az újonnan létrehozott gyártóhoz.
|
||||
*/
|
||||
protected function getRedirectUrl(): string
|
||||
{
|
||||
return static::getResource()::getUrl('view', ['record' => $this->getRecord()]);
|
||||
}
|
||||
}
|
||||
@ -1,19 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Producers\Pages;
|
||||
|
||||
use App\Filament\Resources\Producers\ProducerResource;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
|
||||
class ListProducers extends ListRecords
|
||||
{
|
||||
protected static string $resource = ProducerResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
CreateAction::make(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -1,109 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Producers\Pages;
|
||||
|
||||
use App\Enums\DbStatusFieldEnum;
|
||||
use App\Filament\Resources\Producers\ProducerResource;
|
||||
use App\Models\Producer;
|
||||
use App\Models\Product;
|
||||
use App\Services\ProducerDeduplicator;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\Placeholder;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Pages\ViewRecord;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class ViewProducer extends ViewRecord
|
||||
{
|
||||
protected static string $resource = ProducerResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
$this->mergeProducerAction(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Két aktív gyártó összevonása felületről, Excel/CLI nélkül - EV3-473, 7. lépés.
|
||||
* Valódi tesztelés közben előkerült eset: az admin a felületen böngészve veszi
|
||||
* észre, hogy két aktív gyártó ugyanaz a cég, de az alias-felvétel elutasítja az
|
||||
* ütközést, és korábban nem volt mód a tényleges összevonásra máshogy, csak a
|
||||
* producers:dedupe-report -> Excel -> producers:dedupe --apply láncon, ami
|
||||
* fejlesztői hozzáférést igényel.
|
||||
*
|
||||
* A megtekintett gyártó MINDIG a keeper marad (nincs átnevezés) - ez a felhasználói
|
||||
* szándék, hiszen már ezen az oldalon áll. A ProducerDeduplicator::apply() egyetlen,
|
||||
* kézzel épített merge-bejegyzéssel hívva (buildPlan()/Excel nélkül) - ez már
|
||||
* automatikusan aliast is ír a beolvasztott névből (lásd 4. fázis).
|
||||
*/
|
||||
protected function mergeProducerAction(): Action
|
||||
{
|
||||
return Action::make('mergeProducer')
|
||||
->label('Gyártó összevonása')
|
||||
->icon('heroicon-o-arrows-pointing-in')
|
||||
->color('warning')
|
||||
->visible(fn (Producer $record) => $record->status === DbStatusFieldEnum::active)
|
||||
->schema([
|
||||
Select::make('loser_id')
|
||||
->label('Melyik aktív gyártót olvasszuk be ide?')
|
||||
->options(fn (Producer $record) => Producer::query()
|
||||
->whereNotIn('status', [DbStatusFieldEnum::archive, DbStatusFieldEnum::deleted])
|
||||
->where('id', '!=', $record->id)
|
||||
->orderBy('name')
|
||||
->pluck('name', 'id'))
|
||||
->searchable()
|
||||
->required()
|
||||
->live(),
|
||||
Placeholder::make('impact')
|
||||
->label('Hatás')
|
||||
->content(function (Get $get) {
|
||||
$loserId = $get('loser_id');
|
||||
|
||||
if (blank($loserId)) {
|
||||
return 'Válassz gyártót a hatás megtekintéséhez.';
|
||||
}
|
||||
|
||||
$products = Product::where('producer_id', $loserId)->count();
|
||||
$orderItems = DB::table('order_archives_items')->where('producer_id', $loserId)->count();
|
||||
$pricelistLines = DB::table('pricelist_file_lines')->where('producer_id', $loserId)->count();
|
||||
|
||||
return "Átírandó: {$products} termék, {$orderItems} rendelési tétel, "
|
||||
. "{$pricelistLines} árlista-sor. A kiválasztott gyártó archiválódik, "
|
||||
. 'a neve automatikusan alias lesz a jelenlegi gyártó alatt.';
|
||||
}),
|
||||
])
|
||||
->modalHeading('Gyártó összevonása')
|
||||
->modalSubmitActionLabel('Összevonás')
|
||||
->requiresConfirmation()
|
||||
->action(function (array $data, Producer $record) {
|
||||
$loser = Producer::findOrFail($data['loser_id']);
|
||||
|
||||
$deduplicator = app(ProducerDeduplicator::class);
|
||||
$report = $deduplicator->apply([[
|
||||
'keeper_id' => $record->id,
|
||||
'keeper_name' => $record->name,
|
||||
'final_name' => $record->name,
|
||||
'rename' => false,
|
||||
'from' => [['id' => $loser->id, 'name' => $loser->name]],
|
||||
]]);
|
||||
$reportPath = $deduplicator->writeReport($report);
|
||||
|
||||
Notification::make()
|
||||
->title('Gyártók összevonva')
|
||||
->body(sprintf(
|
||||
'"%s" beolvadt "%s" alá. %d termék, %d rendelési tétel, %d árlista-sor átírva. Jelentés: %s',
|
||||
$loser->name,
|
||||
$record->name,
|
||||
$report['totals']['products'] ?? 0,
|
||||
$report['totals']['order_archives_items'] ?? 0,
|
||||
$report['totals']['pricelist_file_lines'] ?? 0,
|
||||
basename($reportPath),
|
||||
))
|
||||
->success()
|
||||
->send();
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -1,68 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Producers;
|
||||
|
||||
use App\Filament\Resources\Producers\Pages\CreateProducer;
|
||||
use App\Filament\Resources\Producers\Pages\ListProducers;
|
||||
use App\Filament\Resources\Producers\Pages\ViewProducer;
|
||||
use App\Filament\Resources\Producers\RelationManagers\AliasesRelationManager;
|
||||
use App\Filament\Resources\Producers\Schemas\ProducerForm;
|
||||
use App\Filament\Resources\Producers\Schemas\ProducerInfolist;
|
||||
use App\Filament\Resources\Producers\Tables\ProducersTable;
|
||||
use App\Models\Producer;
|
||||
use BackedEnum;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
/**
|
||||
* Lista + megtekintés + kézi felvétel: gyártó eddig kizárólag árlista importból
|
||||
* keletkezett, EV3-473 8. lépése ad hozzá kézi létrehozást (pl. ha egy gyártót
|
||||
* előre fel akarnak venni, mielőtt bármelyik árlistán megjelenne). Szerkesztés/törlés
|
||||
* továbbra sincs - a név utólagos módosítása az árlista-alapú párosítást zavarná meg.
|
||||
*/
|
||||
class ProducerResource extends Resource
|
||||
{
|
||||
protected static ?string $model = Producer::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-building-storefront';
|
||||
|
||||
protected static ?string $navigationLabel = 'Gyártók';
|
||||
|
||||
protected static ?string $modelLabel = 'Gyártó';
|
||||
|
||||
protected static ?string $pluralLabel = 'Gyártók';
|
||||
|
||||
protected static ?string $breadcrumb = 'Gyártók';
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return ProducerForm::configure($schema);
|
||||
}
|
||||
|
||||
public static function infolist(Schema $schema): Schema
|
||||
{
|
||||
return ProducerInfolist::configure($schema);
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return ProducersTable::configure($table);
|
||||
}
|
||||
|
||||
public static function getRelations(): array
|
||||
{
|
||||
return [
|
||||
AliasesRelationManager::class,
|
||||
];
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ListProducers::route('/'),
|
||||
'create' => CreateProducer::route('/create'),
|
||||
'view' => ViewProducer::route('/{record}'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -1,102 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Producers\RelationManagers;
|
||||
|
||||
use App\Support\Exceptions\ActiveProducerNameCollisionException;
|
||||
use App\Support\NameNormalizer;
|
||||
use App\Support\ProducerAliasResolver;
|
||||
use Closure;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Resources\RelationManagers\RelationManager;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Teljes CRUD az aliasokon (nem a gyártó törzsén) - EV3-473. A gyártónak ma sincs
|
||||
* admin felülete, ez az első; a cél kizárólag az, hogy a régi gyártóneveket kézzel is
|
||||
* fel lehessen venni/törölni, ne csak a producers:dedupe és a backfill parancson át.
|
||||
*/
|
||||
class AliasesRelationManager extends RelationManager
|
||||
{
|
||||
protected static string $relationship = 'aliases';
|
||||
|
||||
protected static ?string $title = 'Aliasok';
|
||||
|
||||
/**
|
||||
* A panel alapértelmezése szerint minden ViewRecord oldalra kerülő relation manager
|
||||
* csak olvasható (Panel::hasReadOnlyRelationManagersOnResourceViewPagesByDefault()).
|
||||
* A ProducerResource szándékosan csak View oldalt ad a gyártóhoz (nincs Edit), de az
|
||||
* aliasokon MUST legyen teljes CRUD - ezért ez a manager kivétel a globális alapérték
|
||||
* alól, nem a panel-szintű beállítást lazítjuk (ami minden más View-relation managert
|
||||
* is érintene).
|
||||
*/
|
||||
public function isReadOnly(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema->components([
|
||||
TextInput::make('name')
|
||||
->label('Régi / alternatív gyártónév')
|
||||
->required()
|
||||
->maxLength(255)
|
||||
->rules([
|
||||
fn (): Closure => function (string $attribute, $value, Closure $fail) {
|
||||
try {
|
||||
app(ProducerAliasResolver::class)
|
||||
->assertNameAvailable($value, $this->getOwnerRecord()->id);
|
||||
} catch (ActiveProducerNameCollisionException $e) {
|
||||
// Ez nem feltétlenül hiba: lehet, hogy a két gyártó
|
||||
// valóban ugyanaz a cég. A "Gyártó összevonása" gomb
|
||||
// (ViewProducer fejléc) pont erre a helyzetre való.
|
||||
$fail($e->getMessage() . ' Ha ugyanaz a cég, használd a '
|
||||
. '"Gyártó összevonása" gombot az oldal tetején.');
|
||||
} catch (RuntimeException $e) {
|
||||
$fail($e->getMessage());
|
||||
}
|
||||
},
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
public function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->recordTitleAttribute('name')
|
||||
->columns([
|
||||
TextColumn::make('name')
|
||||
->label('Név')
|
||||
->searchable(),
|
||||
TextColumn::make('source')
|
||||
->label('Forrás')
|
||||
->badge(),
|
||||
TextColumn::make('created_at')
|
||||
->label('Létrehozva')
|
||||
->dateTime('Y-m-d H:i'),
|
||||
])
|
||||
->defaultSort('created_at', 'desc')
|
||||
// A "Gyártó összevonása" gomb (ViewProducer fejléc) a producer_aliases táblát
|
||||
// egy MÁSIK Livewire-komponensből (page-szintű action) írja - a relation
|
||||
// manager erről magától nem értesül. Poll-lal frissül, ugyanaz a minta, mint
|
||||
// a PricelistFiles LinesRelationManager-jén (háttérfolyamat frissíti a sorokat).
|
||||
->poll('5s')
|
||||
->headerActions([
|
||||
CreateAction::make()
|
||||
->mutateDataUsing(function (array $data): array {
|
||||
$data['normalized_name'] = NameNormalizer::normalize($data['name']);
|
||||
$data['source'] = 'manual';
|
||||
|
||||
return $data;
|
||||
}),
|
||||
])
|
||||
->recordActions([
|
||||
DeleteAction::make(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@ -1,39 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Producers\Schemas;
|
||||
|
||||
use App\Support\Exceptions\ActiveProducerNameCollisionException;
|
||||
use App\Support\ProducerAliasResolver;
|
||||
use Closure;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Schemas\Schema;
|
||||
use RuntimeException;
|
||||
|
||||
class ProducerForm
|
||||
{
|
||||
public static function configure(Schema $schema): Schema
|
||||
{
|
||||
return $schema->components([
|
||||
TextInput::make('name')
|
||||
->label('Név')
|
||||
->required()
|
||||
->maxLength(255)
|
||||
->rules([
|
||||
// Ugyanaz az ütközés-védelem, mint az alias-felvételnél: az új gyártó
|
||||
// neve se ütközhessen élő gyártóval vagy már létező aliasszal -
|
||||
// különben pont azt a duplikációt hoznánk létre kézzel, amit az
|
||||
// alias-rendszer megelőzni hivatott.
|
||||
fn (): Closure => function (string $attribute, $value, Closure $fail) {
|
||||
try {
|
||||
app(ProducerAliasResolver::class)->assertNameAvailable($value);
|
||||
} catch (ActiveProducerNameCollisionException $e) {
|
||||
$fail($e->getMessage() . ' Ha ugyanaz a cég, ne hozz létre új gyártót - '
|
||||
. 'vedd fel inkább aliasként a meglévőhöz.');
|
||||
} catch (RuntimeException $e) {
|
||||
$fail($e->getMessage());
|
||||
}
|
||||
},
|
||||
]),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@ -1,27 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Producers\Schemas;
|
||||
|
||||
use Filament\Infolists\Components\TextEntry;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Schema;
|
||||
|
||||
class ProducerInfolist
|
||||
{
|
||||
public static function configure(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->components([
|
||||
Section::make()
|
||||
->columns(2)
|
||||
->schema([
|
||||
TextEntry::make('name')->label('Név'),
|
||||
TextEntry::make('status')->label('Státusz')->badge(),
|
||||
TextEntry::make('note')
|
||||
->label('Megjegyzés')
|
||||
->placeholder('—')
|
||||
->columnSpanFull(),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@ -1,51 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Producers\Tables;
|
||||
|
||||
use App\Enums\DbStatusFieldEnum;
|
||||
use Filament\Actions\ViewAction;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Filters\SelectFilter;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
class ProducersTable
|
||||
{
|
||||
public static function configure(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->modifyQueryUsing(fn ($query) => $query->withCount('aliases'))
|
||||
->columns([
|
||||
TextColumn::make('name')
|
||||
->label('Név')
|
||||
->searchable()
|
||||
->sortable(),
|
||||
TextColumn::make('status')
|
||||
->label('Státusz')
|
||||
->badge()
|
||||
->color(fn (string $state) => match ($state) {
|
||||
DbStatusFieldEnum::active => 'success',
|
||||
DbStatusFieldEnum::archive => 'gray',
|
||||
DbStatusFieldEnum::deleted => 'danger',
|
||||
default => 'gray',
|
||||
})
|
||||
->sortable(),
|
||||
TextColumn::make('aliases_count')
|
||||
->label('Aliasok')
|
||||
->sortable(),
|
||||
TextColumn::make('note')
|
||||
->label('Megjegyzés')
|
||||
->limit(40)
|
||||
->placeholder('—')
|
||||
->toggleable(isToggledHiddenByDefault: true),
|
||||
])
|
||||
->defaultSort('name')
|
||||
->filters([
|
||||
SelectFilter::make('status')
|
||||
->label('Státusz')
|
||||
->options(collect(DbStatusFieldEnum::getValues())->mapWithKeys(fn ($v) => [$v => $v])),
|
||||
])
|
||||
->recordActions([
|
||||
ViewAction::make(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@ -1,11 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Products\Pages;
|
||||
|
||||
use App\Filament\Resources\Products\ProductResource;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
|
||||
class ListProducts extends ListRecords
|
||||
{
|
||||
protected static string $resource = ProductResource::class;
|
||||
}
|
||||
@ -1,11 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Products\Pages;
|
||||
|
||||
use App\Filament\Resources\Products\ProductResource;
|
||||
use Filament\Resources\Pages\ViewRecord;
|
||||
|
||||
class ViewProduct extends ViewRecord
|
||||
{
|
||||
protected static string $resource = ProductResource::class;
|
||||
}
|
||||
@ -1,140 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Products;
|
||||
|
||||
use App\Filament\Resources\Products\Pages\ListProducts;
|
||||
use App\Filament\Resources\Products\Pages\ViewProduct;
|
||||
use App\Filament\Resources\Products\Schemas\ProductInfolist;
|
||||
use App\Filament\Resources\Products\Tables\ProductsTable;
|
||||
use App\Models\Product;
|
||||
use App\Models\User;
|
||||
use BackedEnum;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Laravel\Pennant\Feature;
|
||||
|
||||
/**
|
||||
* EV3-464: egyszerűsített, csak olvasható termékkereső a profitcenternek ("melyik
|
||||
* beszállítónál kapható a csemege szalámi?"). Szándékosan nincs create/edit oldal.
|
||||
*
|
||||
* A láthatóság szerver oldalon szűkül (getEloquentQuery), nem csak a menüből:
|
||||
* - profitcenter szerepkörnél csak a saját profitcenter beszállítóinak termékei, akiktől
|
||||
* rendelni is lehet (suppliers.canSeeInOrder, mint az új rendelés beszállító-listáján);
|
||||
* - mindenkinél csak a beszállító jelenleg érvényes árlistáján szereplő termékek (fix).
|
||||
*
|
||||
* Az admin használat később jön; addig a ProfitCenterProductSearch flag + a szerepkör-lista
|
||||
* (root/developer a rollout-teszteléshez) szabja meg, ki éri el.
|
||||
*/
|
||||
class ProductResource extends Resource
|
||||
{
|
||||
public const FEATURE = 'ProfitCenterProductSearch';
|
||||
|
||||
protected static ?string $model = Product::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-magnifying-glass';
|
||||
|
||||
protected static ?string $navigationLabel = 'Termékkereső';
|
||||
|
||||
protected static ?string $modelLabel = 'Termék';
|
||||
|
||||
protected static ?string $pluralLabel = 'Termékkereső';
|
||||
|
||||
protected static ?string $breadcrumb = 'Termékkereső';
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
return static::canViewAny();
|
||||
}
|
||||
|
||||
public static function canViewAny(): bool
|
||||
{
|
||||
/** @var User|null $user */
|
||||
$user = auth()->user();
|
||||
|
||||
return $user
|
||||
&& $user->hasRole(['profit-center', 'root', 'developer'])
|
||||
&& Feature::for($user)->active(self::FEATURE);
|
||||
}
|
||||
|
||||
/**
|
||||
* A Product modellre a Laravel automatikusan a ProductPolicy-t köti, az viszont a
|
||||
* (beszállítói/admin) szerkesztésre készült és a profit-center szerepkört nem ismeri.
|
||||
* A rekord-szintű szűrést a getEloquentQuery() végzi (idegen termék 404), ezért itt
|
||||
* a resource-szintű jogosultság dönt.
|
||||
*/
|
||||
public static function canView($record): bool
|
||||
{
|
||||
return static::canViewAny();
|
||||
}
|
||||
|
||||
public static function canCreate(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public static function canEdit($record): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public static function canDelete($record): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public static function canDeleteAny(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public static function getEloquentQuery(): Builder
|
||||
{
|
||||
$query = parent::getEloquentQuery()
|
||||
->with(['Supplier', 'Producer', 'ProductGroup'])
|
||||
->inActivePriceList()
|
||||
->withActivePrice();
|
||||
|
||||
/** @var User|null $user */
|
||||
$user = auth()->user();
|
||||
if ($user?->hasRole('profit-center')) {
|
||||
$query->whereIn('products.supplier_id', static::profitCenterSupplierIds($user));
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
/**
|
||||
* A profitcenter beszállítói: a felhasználó első profitcentere (1:1 használat), csak
|
||||
* a rendelésnél is látható beszállítók. Profitcenter nélküli felhasználó nem lát semmit.
|
||||
*
|
||||
* @return array<int, int>
|
||||
*/
|
||||
public static function profitCenterSupplierIds(User $user): array
|
||||
{
|
||||
return $user->profitCenters()->first()
|
||||
?->suppliers()
|
||||
->where('suppliers.canSeeInOrder', 1)
|
||||
->pluck('suppliers.id')
|
||||
->all() ?? [];
|
||||
}
|
||||
|
||||
public static function infolist(Schema $schema): Schema
|
||||
{
|
||||
return ProductInfolist::configure($schema);
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return ProductsTable::configure($table);
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ListProducts::route('/'),
|
||||
'view' => ViewProduct::route('/{record}'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -1,50 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Products\Schemas;
|
||||
|
||||
use Filament\Infolists\Components\IconEntry;
|
||||
use Filament\Infolists\Components\TextEntry;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Schema;
|
||||
|
||||
class ProductInfolist
|
||||
{
|
||||
public static function configure(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->components([
|
||||
Section::make('Termék')
|
||||
->columns(2)
|
||||
->schema([
|
||||
TextEntry::make('name')->label('Megnevezés'),
|
||||
TextEntry::make('buyerProductName')->label('Horeca megnevezés')->placeholder('—'),
|
||||
TextEntry::make('Supplier.name')->label('Beszállító'),
|
||||
TextEntry::make('Producer.name')->label('Gyártó')->placeholder('—'),
|
||||
TextEntry::make('ProductGroup.name')->label('Termékcsoport')->placeholder('—'),
|
||||
TextEntry::make('supplierProductNumber')->label('Beszállítói cikkszám')->placeholder('—'),
|
||||
]),
|
||||
Section::make('Kiszerelés és ár')
|
||||
->columns(2)
|
||||
->schema([
|
||||
TextEntry::make('current_price')
|
||||
->label('Aktuális ár')
|
||||
->formatStateUsing(fn ($state) => $state === null ? '—' : number_format((float) $state, 2, ',', ' ').' Ft'),
|
||||
TextEntry::make('vat')->label('ÁFA (%)')->placeholder('—'),
|
||||
TextEntry::make('packing')->label('Kiszerelés (db)')->placeholder('—'),
|
||||
TextEntry::make('unitValue')
|
||||
->label('Egységérték')
|
||||
->formatStateUsing(fn ($state, $record) => trim($state.' '.$record->productUnit)),
|
||||
TextEntry::make('sellerUnit')->label('Eladási egység')->placeholder('—'),
|
||||
TextEntry::make('unitMultiplier')
|
||||
->label('Mennyiségi szorzó')
|
||||
->formatStateUsing(fn ($state, $record) => trim($state.' '.$record->amountUnit)),
|
||||
IconEntry::make('krel')->label('KREL')->boolean(),
|
||||
IconEntry::make('specialOffer')->label('Akciós')->boolean(),
|
||||
]),
|
||||
Section::make('Megjegyzés')
|
||||
->schema([
|
||||
TextEntry::make('note')->hiddenLabel()->placeholder('—')->columnSpanFull(),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@ -1,94 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Products\Tables;
|
||||
|
||||
use App\Filament\Resources\Products\ProductResource;
|
||||
use App\Models\Producer;
|
||||
use App\Models\ProductGroup;
|
||||
use App\Models\Supplier;
|
||||
use Filament\Actions\ViewAction;
|
||||
use Filament\Tables\Columns\IconColumn;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Filters\SelectFilter;
|
||||
use Filament\Tables\Filters\TernaryFilter;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
class ProductsTable
|
||||
{
|
||||
public static function configure(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->columns([
|
||||
TextColumn::make('name')
|
||||
->label('Termék')
|
||||
->searchable()
|
||||
->sortable(),
|
||||
TextColumn::make('Supplier.name')
|
||||
->label('Beszállító')
|
||||
->searchable()
|
||||
->sortable(),
|
||||
TextColumn::make('Producer.name')
|
||||
->label('Gyártó')
|
||||
->placeholder('—')
|
||||
->searchable(),
|
||||
TextColumn::make('ProductGroup.name')
|
||||
->label('Termékcsoport')
|
||||
->placeholder('—'),
|
||||
TextColumn::make('packing')
|
||||
->label('Kiszerelés')
|
||||
->formatStateUsing(fn ($record) => trim(
|
||||
($record->packing ? $record->packing.' × ' : '').$record->unitValue.' '.$record->productUnit
|
||||
)),
|
||||
TextColumn::make('current_price')
|
||||
->label('Ár')
|
||||
->formatStateUsing(fn ($state) => $state === null ? '—' : number_format((float) $state, 2, ',', ' ').' Ft')
|
||||
->alignEnd()
|
||||
->sortable(),
|
||||
IconColumn::make('specialOffer')
|
||||
->label('Akciós')
|
||||
->boolean()
|
||||
->trueColor('warning')
|
||||
->falseIcon('')
|
||||
->toggleable(),
|
||||
TextColumn::make('buyerProductName')
|
||||
->label('Horeca megnevezés')
|
||||
->searchable()
|
||||
->toggleable(isToggledHiddenByDefault: true),
|
||||
TextColumn::make('supplierProductNumber')
|
||||
->label('Beszállítói cikkszám')
|
||||
->searchable()
|
||||
->toggleable(isToggledHiddenByDefault: true),
|
||||
])
|
||||
->defaultSort('name')
|
||||
->filters([
|
||||
SelectFilter::make('supplier_id')
|
||||
->label('Beszállító')
|
||||
->multiple()
|
||||
->options(function () {
|
||||
// Ugyanaz a keret, mint a találati listáé: profitcenternek csak a saját beszállítói.
|
||||
$ids = ProductResource::getEloquentQuery()->reorder()->select('products.supplier_id')->distinct();
|
||||
|
||||
return Supplier::query()->whereIn('id', $ids)->orderBy('name')->pluck('name', 'id');
|
||||
}),
|
||||
SelectFilter::make('product_group_id')
|
||||
->label('Termékcsoport')
|
||||
->multiple()
|
||||
->searchable()
|
||||
->options(fn () => ProductGroup::query()->orderBy('name')->pluck('name', 'id')),
|
||||
SelectFilter::make('producer_id')
|
||||
->label('Gyártó')
|
||||
->multiple()
|
||||
->searchable()
|
||||
->options(fn () => Producer::query()->orderBy('name')->pluck('name', 'id')),
|
||||
TernaryFilter::make('specialOffer')
|
||||
->label('Akciós'),
|
||||
])
|
||||
->recordActions([
|
||||
ViewAction::make(),
|
||||
])
|
||||
->recordUrl(fn ($record) => ProductResource::getUrl('view', ['record' => $record]))
|
||||
->searchPlaceholder('Keresés: termék, beszállító, gyártó…')
|
||||
->paginated([25, 50, 100])
|
||||
->defaultPaginationPageOption(25);
|
||||
}
|
||||
}
|
||||
@ -3,44 +3,9 @@
|
||||
namespace App\Filament\Resources\ProfitCenterSupplierSchedules\Pages;
|
||||
|
||||
use App\Filament\Resources\ProfitCenterSupplierSchedules\ProfitCenterSupplierScheduleResource;
|
||||
use App\Models\ProfitCenterSupplierSchedule;
|
||||
use Filament\Resources\Pages\CreateRecord;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class CreateProfitCenterSupplierSchedule extends CreateRecord
|
||||
{
|
||||
protected static string $resource = ProfitCenterSupplierScheduleResource::class;
|
||||
|
||||
/**
|
||||
* Több profit center esetén minden egyes profit centerhez külön rekordot hoz létre.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
protected function handleRecordCreation(array $data): Model
|
||||
{
|
||||
$profitCenterIds = (array) $data['profit_center_id'];
|
||||
|
||||
$lastRecord = null;
|
||||
|
||||
foreach ($profitCenterIds as $profitCenterId) {
|
||||
$lastRecord = ProfitCenterSupplierSchedule::create([
|
||||
'profit_center_id' => $profitCenterId,
|
||||
'supplier_id' => $data['supplier_id'],
|
||||
'delivery_schedule_id' => $data['delivery_schedule_id'],
|
||||
]);
|
||||
}
|
||||
|
||||
return $lastRecord;
|
||||
}
|
||||
|
||||
/**
|
||||
* "Mentés és új létrehozása" esetén a Beszállító mezőt megtartja, a többit üríti (EV3-432).
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function preserveFormDataWhenCreatingAnother(array $data): array
|
||||
{
|
||||
return ['supplier_id' => $data['supplier_id'] ?? null];
|
||||
}
|
||||
}
|
||||
|
||||
@ -6,38 +6,12 @@
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Actions\ForceDeleteAction;
|
||||
use Filament\Actions\RestoreAction;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
use Filament\Schemas\Schema;
|
||||
|
||||
class EditProfitCenterSupplierSchedule extends EditRecord
|
||||
{
|
||||
protected static string $resource = ProfitCenterSupplierScheduleResource::class;
|
||||
|
||||
public function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->components([
|
||||
Select::make('profit_center_id')
|
||||
->label('Profit Center')
|
||||
->relationship('profitCenter', 'name')
|
||||
->searchable()
|
||||
->required(),
|
||||
Select::make('supplier_id')
|
||||
->label('Beszállító')
|
||||
->relationship('supplier', 'name')
|
||||
->searchable()
|
||||
->required(),
|
||||
Select::make('delivery_schedule_id')
|
||||
->label('Szállítási sablon')
|
||||
->relationship('deliverySchedule', 'name')
|
||||
->searchable()
|
||||
->live()
|
||||
->afterStateUpdated(fn ($state, $livewire) => $livewire->dispatch('delivery-schedule-changed', deliveryScheduleId: $state))
|
||||
->required(),
|
||||
]);
|
||||
}
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
|
||||
@ -2,7 +2,6 @@
|
||||
|
||||
namespace App\Filament\Resources\ProfitCenterSupplierSchedules\Schemas;
|
||||
|
||||
use App\Models\ProfitCenter;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Schemas\Schema;
|
||||
|
||||
@ -14,9 +13,8 @@ public static function configure(Schema $schema): Schema
|
||||
->components([
|
||||
Select::make('profit_center_id')
|
||||
->label('Profit Center')
|
||||
->options(ProfitCenter::orderBy('name')->pluck('name', 'id'))
|
||||
->relationship('profitCenter', 'name')
|
||||
->searchable()
|
||||
->multiple()
|
||||
->required(),
|
||||
Select::make('supplier_id')
|
||||
->label('Beszállító')
|
||||
|
||||
@ -33,9 +33,6 @@ class DeliveryCalendarWidget extends FullCalendarWidget
|
||||
/** Következő szállítási nap dátuma (YYYY-MM-DD formátum), kék kiemeléshez. */
|
||||
public ?string $nextDeliveryDate = null;
|
||||
|
||||
/** Előnézeti szállítási sablon ID (edit oldalon, mentés előtti változás). */
|
||||
public ?int $previewDeliveryScheduleId = null;
|
||||
|
||||
/**
|
||||
* Inaktív (nem választható) napok listája.
|
||||
*
|
||||
@ -77,13 +74,6 @@ public function onNextDeliveryDateChanged(?string $date): void
|
||||
$this->refreshRecords();
|
||||
}
|
||||
|
||||
#[On('delivery-schedule-changed')]
|
||||
public function onDeliveryScheduleChanged(?int $deliveryScheduleId): void
|
||||
{
|
||||
$this->previewDeliveryScheduleId = $deliveryScheduleId;
|
||||
$this->refreshRecords();
|
||||
}
|
||||
|
||||
protected function loadRecordFromFilter(): void
|
||||
{
|
||||
if ($this->record instanceof ProfitCenterSupplierSchedule) {
|
||||
@ -124,24 +114,11 @@ public function fetchEvents(array $info): array
|
||||
$events = [];
|
||||
|
||||
// 1. Szállítási napok – zöld háttér
|
||||
$assignment = $this->record;
|
||||
if ($this->previewDeliveryScheduleId && $this->previewDeliveryScheduleId !== $this->record->delivery_schedule_id) {
|
||||
$assignment = clone $this->record;
|
||||
$assignment->delivery_schedule_id = $this->previewDeliveryScheduleId;
|
||||
$assignment->setRelation('deliverySchedule', \App\Models\DeliverySchedule::find($this->previewDeliveryScheduleId));
|
||||
}
|
||||
|
||||
$deliveryDates = $service->getAvailableDeliveryDates(
|
||||
$this->record->profitCenter,
|
||||
$this->record->supplier,
|
||||
$start,
|
||||
$end,
|
||||
$assignment
|
||||
);
|
||||
|
||||
// A szállítási napok halmaza a hétvége-festéshez (4. pont) is kell.
|
||||
$deliveryDayLookup = array_flip(
|
||||
$deliveryDates->map(fn (Carbon $date) => $date->format('Y-m-d'))->all()
|
||||
$end
|
||||
);
|
||||
|
||||
foreach ($deliveryDates as $date) {
|
||||
@ -149,7 +126,7 @@ public function fetchEvents(array $info): array
|
||||
'id' => 'delivery-' . $date->format('Y-m-d'),
|
||||
'title' => '',
|
||||
'start' => $date->format('Y-m-d'),
|
||||
'end' => $date->copy()->addDay()->format('Y-m-d'),
|
||||
'end' => $date->addDay()->format('Y-m-d'),
|
||||
'allDay' => true,
|
||||
'display' => 'background',
|
||||
'backgroundColor' => '#4CAF50',
|
||||
@ -187,11 +164,9 @@ public function fetchEvents(array $info): array
|
||||
}
|
||||
|
||||
// 4. Hétvégék – szürke háttér (inaktív napok)
|
||||
// Csak azok a hétvégi napok, amelyek nem szállítási napok: a heti sablon
|
||||
// tartalmazhatja a szombatot/vasárnapot is (EV3-466).
|
||||
$current = $start->copy();
|
||||
while ($current->lte($end)) {
|
||||
if ($current->isWeekend() && ! isset($deliveryDayLookup[$current->format('Y-m-d')])) {
|
||||
if ($current->isWeekend()) {
|
||||
$events[] = [
|
||||
'id' => 'weekend-' . $current->format('Y-m-d'),
|
||||
'title' => '',
|
||||
|
||||
@ -90,13 +90,13 @@ public function index(): View|Response|JsonResponse
|
||||
$m->subject('Árlista változás ');
|
||||
$m->to($emailAddress);
|
||||
/*
|
||||
if(config('app.stage')=='PROD'){
|
||||
if(env('APP_STAGE')=='PROD'){
|
||||
$m->to($emailAddress);
|
||||
}else{
|
||||
if(config('app.stage')=='TEST'){
|
||||
if(env('APP_STAGE')=='TEST'){
|
||||
$m->to('beszerzes@delirest.hu');
|
||||
}
|
||||
if(config('app.stage')=='DEV'){
|
||||
if(env('APP_STAGE')=='DEV'){
|
||||
$m->to('city@e98.hu');
|
||||
}
|
||||
|
||||
@ -303,13 +303,13 @@ private function notificationNewPriceList($priceListId)
|
||||
$destEmail->each(function ($emailAddress) use ($emailData) {
|
||||
\Mail::send('email.priceListChangeNotify', $emailData, function ($m) use ($emailAddress) {
|
||||
$m->subject('Árlista változás ');
|
||||
if (config('app.stage') == 'PROD') {
|
||||
if (env('APP_STAGE') == 'PROD') {
|
||||
$m->to($emailAddress);
|
||||
} else {
|
||||
if (config('app.stage') == 'TEST') {
|
||||
if (env('APP_STAGE') == 'TEST') {
|
||||
$m->to('beszerzes@delirest.hu');
|
||||
}
|
||||
if (config('app.stage') == 'DEV') {
|
||||
if (env('APP_STAGE') == 'DEV') {
|
||||
$m->to('city@e98.hu');
|
||||
}
|
||||
}
|
||||
@ -338,19 +338,6 @@ private function importPriceList(Request $request): JsonResponse
|
||||
$supplierId = $request->input('supplier');
|
||||
$availableDate = $request->input('availableDate');
|
||||
|
||||
// Ez a legacy import közvetlenül ír a products táblába, teljesen megkerülve az
|
||||
// árlista feldolgozó modult - ezért itt a legfontosabb a beszállítói blokkolás.
|
||||
// Enélkül egy félig frissített termékhalmazra rétegződne rá egy újabb import.
|
||||
$guard = app(\App\Services\PricelistGuard::class);
|
||||
|
||||
if ($blockingFile = $guard->blockingFileFor((int) $supplierId)) {
|
||||
return \response()->json([
|
||||
'success' => false,
|
||||
'error' => $guard->blockingMessage($blockingFile),
|
||||
'res' => false,
|
||||
]);
|
||||
}
|
||||
|
||||
$otherField = [];
|
||||
$otherField['note'] = $request->input('note');
|
||||
$res = $this->service->importPriceList($supplierId, $availableDate, $collection->slice($importStartLine, $importLength)->toArray(), $otherField);
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
namespace App\Http\Controllers\admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\ProductGroup;
|
||||
|
||||
@ -269,7 +269,7 @@ protected function productValidationRules(): array
|
||||
return [
|
||||
'name' => 'required|string|max:255',
|
||||
'supplierId' => 'required|integer|exists:suppliers,id',
|
||||
'producer' => 'nullable|exists:producers,id',
|
||||
'producer' => 'required|exists:producers,id',
|
||||
'packaging' => 'required|numeric|min:0',
|
||||
'unitValue' => 'required|numeric|min:0',
|
||||
'productUnit' => 'required|string|in:'.implode(',', BasicUnitEnum::getValues()),
|
||||
@ -297,7 +297,7 @@ protected function productValidationRules(): array
|
||||
*/
|
||||
protected function transformValidated(array $validated): array
|
||||
{
|
||||
$validated['producer_id'] = isset($validated['producer']) ? $validated['producer'][0] : null;
|
||||
$validated['producer_id'] = $validated['producer'][0];
|
||||
$validated['product_group_id'] = $validated['productGroup'][0];
|
||||
$validated['supplier_id'] = $validated['supplierId'];
|
||||
$validated['packing'] = $validated['packaging'];
|
||||
|
||||
@ -149,31 +149,6 @@ private function getStatPriceChange(Request $request): JsonResponse
|
||||
return \response()->json(['function' => __FUNCTION__, 'parameters' => $this->Service->getStatisticsParameters(), 'ret' => $ret, 'success' => true], 200);
|
||||
}
|
||||
|
||||
public function getProductGroupSearch(Request $request): JsonResponse
|
||||
{
|
||||
$query = ProductGroup::query()
|
||||
->where('name', 'LIKE', '%' . $request->get('term') . '%');
|
||||
|
||||
if ($request->get('supplierId')) {
|
||||
$supplierIds = $request->get('supplierId');
|
||||
$query->whereHas('products', function ($q) use ($supplierIds) {
|
||||
$q->whereIn('supplier_id', $supplierIds);
|
||||
});
|
||||
}
|
||||
|
||||
$items = $query->orderBy('name')->get(['id', 'name'])->map(function ($group) {
|
||||
return [
|
||||
'id' => $group->id,
|
||||
'text' => $group->name,
|
||||
];
|
||||
});
|
||||
|
||||
return response()->json([
|
||||
'results' => $items,
|
||||
'pagination' => ['more' => false],
|
||||
]);
|
||||
}
|
||||
|
||||
public function getProductSearch(Request $request): JsonResponse
|
||||
{
|
||||
$page = $request->get('page');
|
||||
|
||||
@ -102,12 +102,6 @@ private function getSupplierDataFromRequest(Request $request)
|
||||
$data[$key] = $request->get($key);
|
||||
}
|
||||
$data['status'] = DbStatusFieldEnum::active;
|
||||
|
||||
// A hasCustomerCode mező csak akkor jelenik meg a formon, ha a SupplierCustomerCode
|
||||
// feature flag aktív - ilyenkor nem szabad null-t írni a NOT NULL boolean oszlopba.
|
||||
if ($request->has('hasCustomerCode')) {
|
||||
$data['hasCustomerCode'] = $request->boolean('hasCustomerCode');
|
||||
}
|
||||
if ($contactId = $request->get('contactId')) {
|
||||
$data['contactId'] = $contactId;
|
||||
} else {
|
||||
|
||||
@ -105,6 +105,7 @@ public function index(): View|Response|JsonResponse
|
||||
if (\request()->input('w') == 1) {
|
||||
$testOrderId = 16497; // heti
|
||||
$testOrderId = 16467; // heti
|
||||
|
||||
$testOrderId = 16507; // heti
|
||||
// $testOrderId=16512; //heti
|
||||
|
||||
@ -112,13 +113,8 @@ public function index(): View|Response|JsonResponse
|
||||
$testOrderId = 12140; // napi
|
||||
$testOrderId = 16506; // napi
|
||||
$testOrderId = 16571; // napi
|
||||
//$testOrderId = 308676; // napi
|
||||
$testOrderId = 307975; // napi
|
||||
}
|
||||
|
||||
/******** create Pdf from oder ***********/
|
||||
return $this->testPdfCreate($testOrderId);
|
||||
|
||||
/******** create Excel ***********/
|
||||
return $this->testExcelCreate($testOrderId);
|
||||
|
||||
@ -1759,7 +1755,7 @@ private function updateSend(Request $request, int $orderId): JsonResponse
|
||||
}
|
||||
|
||||
if (config('mail.MailToOrderAddress') != 'city99@e98.hu') {
|
||||
$m->bcc('city99@e98.hu');
|
||||
$m->bcc('city@e98.hu');
|
||||
}
|
||||
// $m->attach($attach,['as'=>$fileNameWithExt]);
|
||||
if ($fileType !== 'none') {
|
||||
@ -1893,9 +1889,6 @@ public function getDataTableContent(): JsonResponse
|
||||
} else {
|
||||
if (\request()->get('groupId')) {
|
||||
$groupId = \request()->get('groupId');
|
||||
if ($groupId === 'all') {
|
||||
$groupId = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -1,164 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\api\v1;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\OrderArchive;
|
||||
use App\Services\MaryKerLogger;
|
||||
use App\Services\MaryKerOrderEligibility;
|
||||
use App\Services\MaryKerOrderMapper;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* Mary-Ker (Apolló) rendeléslekérő és visszaigazoló API (EV3-461).
|
||||
*
|
||||
* A Hooreyca-mintától (OrderController) szándékosan elkülönített: saját útvonal, saját token. A szűrés
|
||||
* a token tulajdonosának supplier_id-jából jön, így a token más beszállító rendeléséhez nem fér hozzá.
|
||||
*
|
||||
* Az order_archives írásai szándékosan toBase()-en mennek: nincs modell-esemény, így nem íródik át
|
||||
* az updated_by / updated_at az API-felhasználóra, és nincs mit kiszivárogtatni a válaszba.
|
||||
*/
|
||||
class MaryKerOrderController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly MaryKerOrderMapper $mapper,
|
||||
private readonly MaryKerOrderEligibility $eligibility,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Feldolgozatlan rendelések (confirmed nem null, APIConfirmed null), régi elöl, lapozva.
|
||||
*
|
||||
* Idempotens a találati halmaz szempontjából: a lista csak az APIConfirmed-től és az adatok hiánytalanságától
|
||||
* függ, ezért ugyanazt adja, amíg a setProcessed meg nem történik. Az APICallBackId-t csak az első lekérésnél
|
||||
* generálja, utána stabil. Az egyetlen mellékhatás az APILastGetting bélyeg.
|
||||
*
|
||||
* Ami Apollónak hiányos (azonosító, vevőkód, cikkszám), az a rendelés kimarad a listából, és hibaként
|
||||
* bekerül a maryker naplóba, amíg az adatot rögzítik (ld. MaryKerOrderEligibility).
|
||||
*/
|
||||
public function unProcessed(Request $request): JsonResponse
|
||||
{
|
||||
$updateDate = Carbon::now();
|
||||
$header = $this->header($updateDate);
|
||||
|
||||
$supplierId = $request->user()?->supplier_id;
|
||||
if (! $supplierId) {
|
||||
return $this->forbidden($header);
|
||||
}
|
||||
|
||||
$page = OrderArchive::query()
|
||||
->whereIn('id', $this->eligibility->eligibleOrderIds($supplierId))
|
||||
->select([
|
||||
'id', 'humanId', 'confirmed', 'sumPrice', 'deliveryDate', 'note', 'profit_center_id', 'contactName',
|
||||
'profit_center_name', 'deliveryAddressId', 'deliveryAddressName', 'deliveryAddress',
|
||||
])
|
||||
->orderBy('id')
|
||||
->paginate(max(1, (int) config('maryker.per_page')));
|
||||
|
||||
$ids = $page->getCollection()->pluck('id');
|
||||
$callbackIds = $this->ensureCallbackIds($ids->all());
|
||||
$profitCenters = $this->mapper->profitCenterBlocks($page->getCollection(), $supplierId);
|
||||
$items = $this->mapper->itemBlocks($page->getCollection());
|
||||
|
||||
OrderArchive::query()->toBase()->whereIn('id', $ids)->update(['APILastGetting' => $updateDate]);
|
||||
|
||||
$page->setCollection($page->getCollection()->map(fn (OrderArchive $order) => [
|
||||
'orderId' => $order->humanId,
|
||||
'APICallBackId' => $callbackIds[$order->id],
|
||||
'confirmedAt' => $order->confirmed,
|
||||
'orderSum' => $this->mapper->number($order->sumPrice),
|
||||
'orderDeliveryDate' => $order->deliveryDate,
|
||||
'orderDescription' => (string) $order->note,
|
||||
'profitCenter' => $profitCenters[$order->id],
|
||||
'items' => $items[$order->id],
|
||||
]));
|
||||
|
||||
MaryKerLogger::channel()->info('MaryKer unprocessed', [
|
||||
'userId' => $request->user()->id, 'page' => $page->currentPage(), 'orderIds' => $ids->all(),
|
||||
]);
|
||||
|
||||
return responder()->success($page)->respond(null, $header);
|
||||
}
|
||||
|
||||
/**
|
||||
* Visszaigazolás: az APICallBackId-k alapján beállítja az APIConfirmed-et.
|
||||
* Kötelezően nem üres tömb; egy elem csak akkor "updated", ha a token beszállítójáé, lekért és még
|
||||
* nem visszaigazolt rendeléshez tartozik.
|
||||
*/
|
||||
public function setProcessed(Request $request): JsonResponse
|
||||
{
|
||||
$updateDate = Carbon::now();
|
||||
$header = $this->header($updateDate);
|
||||
|
||||
$supplierId = $request->user()?->supplier_id;
|
||||
if (! $supplierId) {
|
||||
return $this->forbidden($header);
|
||||
}
|
||||
|
||||
// A kliens nem biztos, hogy JSON Content-Type-ot küld (a Hooreyca sem teszi), ezért a nyers törzset olvassuk.
|
||||
$body = json_decode($request->getContent(), true);
|
||||
$validator = Validator::make(is_array($body) ? $body : [], [
|
||||
'APICallBackId' => ['required', 'array', 'min:1', 'max:' . (int) config('maryker.set_processed_max')],
|
||||
'APICallBackId.*' => ['required', 'string', 'max:36', 'distinct'],
|
||||
]);
|
||||
if (! is_array($body) || $validator->fails()) {
|
||||
$message = is_array($body) ? $validator->errors()->first() : 'A kérés törzse nem érvényes JSON objektum.';
|
||||
MaryKerLogger::channel()->warning('MaryKer setProcessed invalid data', ['userId' => $request->user()->id, 'message' => $message]);
|
||||
|
||||
return responder()->error('invalid data', $message)->respond(422, $header);
|
||||
}
|
||||
|
||||
$result = [];
|
||||
foreach ($body['APICallBackId'] as $callbackId) {
|
||||
$updated = OrderArchive::query()->toBase()
|
||||
->where('supplier_id', $supplierId)
|
||||
->where('APICallBackId', $callbackId)
|
||||
->whereNotNull('confirmed')
|
||||
->whereNotNull('APILastGetting')
|
||||
->whereNull('APIConfirmed')
|
||||
->update(['APIConfirmed' => $updateDate]);
|
||||
|
||||
$result[$callbackId] = $updated ? 'updated' : 'invalid Id';
|
||||
}
|
||||
|
||||
MaryKerLogger::channel()->info('MaryKer setProcessed', ['userId' => $request->user()->id, 'result' => $result]);
|
||||
|
||||
return responder()->success($result)->respond(null, $header);
|
||||
}
|
||||
|
||||
/**
|
||||
* Az üres APICallBackId-kat feltölti (versenyhelyzet-biztosan: csak null-t ír felül), majd visszaadja
|
||||
* az összes megadott rendelés azonosítóját id => uuid alakban.
|
||||
*
|
||||
* @param array<int, int> $orderIds
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function ensureCallbackIds(array $orderIds): array
|
||||
{
|
||||
$missing = OrderArchive::query()->toBase()->whereIn('id', $orderIds)->whereNull('APICallBackId')->pluck('id');
|
||||
|
||||
foreach ($missing as $id) {
|
||||
OrderArchive::query()->toBase()->where('id', $id)->whereNull('APICallBackId')
|
||||
->update(['APICallBackId' => (string) Str::orderedUuid()]);
|
||||
}
|
||||
|
||||
return OrderArchive::query()->toBase()->whereIn('id', $orderIds)->pluck('APICallBackId', 'id')->all();
|
||||
}
|
||||
|
||||
/** @return array{apiVersion: string, processedTime: string} */
|
||||
private function header(Carbon $time): array
|
||||
{
|
||||
$header = parseAPIVersionFromNamespace(__NAMESPACE__);
|
||||
$header['processedTime'] = $time->format('Y.m.d. H:i:s.u');
|
||||
|
||||
return $header;
|
||||
}
|
||||
|
||||
private function forbidden(array $header): JsonResponse
|
||||
{
|
||||
return responder()->error('forbidden', 'A tokenhez nem tartozik beszállító.')->respond(403, $header);
|
||||
}
|
||||
}
|
||||
@ -153,12 +153,14 @@ public function unProcessed(Request $request,Responder $responder)
|
||||
//->whereNulll('APIConfirmed')
|
||||
->whereNotNull('confirmed')
|
||||
->whereNull('APIConfirmed')
|
||||
->whereHas('profitCenter', function ($query) {
|
||||
$query->where('hooreycaDataActive', 1);
|
||||
})
|
||||
->orderBy('id','desc')->paginate(3)
|
||||
;
|
||||
|
||||
$filteredProfitCentersOrder=$OrderCollection->filter(function ($v) {
|
||||
return $v->profitCenter!=null;
|
||||
});
|
||||
$OrderCollection->setCollection($filteredProfitCentersOrder);
|
||||
|
||||
/* where condition not working on paginated eloquent collection
|
||||
dd($OrderCollection->toArray());
|
||||
$OrderCollection=$OrderCollection->whereNotNull('profit_center');
|
||||
|
||||
@ -2,53 +2,29 @@
|
||||
|
||||
namespace App\Jobs;
|
||||
|
||||
use App\Enums\PricelistWorkflowStep;
|
||||
use App\Models\PricelistFile;
|
||||
use App\Services\PricelistFileProcessService;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Queue\Queueable;
|
||||
use Throwable;
|
||||
|
||||
class PricelistExecutionJob implements ShouldQueue
|
||||
{
|
||||
use Queueable;
|
||||
|
||||
/**
|
||||
* Nincs automatikus újrapróbálkozás: egy félbeszakadt végrehajtás után már
|
||||
* létrejöhettek termékek és árak, egy vak újrafuttatás pedig félreérthető
|
||||
* állapotot okozna. A folytatásról a felhasználó dönt a felületen.
|
||||
* Create a new job instance.
|
||||
*/
|
||||
public int $tries = 1;
|
||||
|
||||
/**
|
||||
* Nagy árlistáknál a végrehajtás sokáig futhat, de nem korlátlanul: a timeout
|
||||
* garantálja, hogy a job terminális állapotba jut, és a failed() lefut.
|
||||
*/
|
||||
public int $timeout = 3600;
|
||||
|
||||
public function __construct(
|
||||
public PricelistFile $pricelistFile
|
||||
) {
|
||||
)
|
||||
{
|
||||
//
|
||||
}
|
||||
|
||||
public function handle(PricelistFileProcessService $service): void
|
||||
/**
|
||||
* Execute the job.
|
||||
*/
|
||||
public function handle(\App\Services\PricelistFileProcessService $service): void
|
||||
{
|
||||
$service->execute($this->pricelistFile);
|
||||
}
|
||||
|
||||
/**
|
||||
* A service catch ága csak PHP exceptionöket fogja el. Worker timeout, memórialimit
|
||||
* vagy worker-újraindítás esetén a catch soha nem fut le, és a fájl inprogress-ben
|
||||
* ragadna - egyik döntési gomb nélkül. Ez a hook zárja be ezt a rést.
|
||||
*/
|
||||
public function failed(?Throwable $exception): void
|
||||
{
|
||||
app(PricelistFileProcessService::class)->updateStepStatus(
|
||||
$this->pricelistFile,
|
||||
PricelistWorkflowStep::Execution,
|
||||
'failed',
|
||||
$exception?->getMessage() ?? 'A végrehajtás váratlanul megszakadt.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,43 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Jobs;
|
||||
|
||||
use App\Models\PricelistFile;
|
||||
use App\Services\PricelistFileProcessService;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Queue\Queueable;
|
||||
use Throwable;
|
||||
|
||||
class PricelistRevertJob implements ShouldQueue
|
||||
{
|
||||
use Queueable;
|
||||
|
||||
public int $tries = 1;
|
||||
|
||||
public int $timeout = 3600;
|
||||
|
||||
public function __construct(
|
||||
public PricelistFile $pricelistFile
|
||||
) {
|
||||
//
|
||||
}
|
||||
|
||||
public function handle(PricelistFileProcessService $service): void
|
||||
{
|
||||
$service->revert($this->pricelistFile);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ugyanaz a rés, mint a végrehajtásnál - de itt nagyobb a tétje: a kényszerlezárás
|
||||
* csak akkor érhető el, ha volt legalább egy TERMINÁLIS hibába futott visszaállítási
|
||||
* kísérlet. Ha egy megszakadt visszaállítás inprogress-ben ragadna, a beszállító
|
||||
* véglegesen blokkolva maradna, mindenféle kiút nélkül.
|
||||
*/
|
||||
public function failed(?Throwable $exception): void
|
||||
{
|
||||
app(PricelistFileProcessService::class)->failRevert(
|
||||
$this->pricelistFile,
|
||||
$exception?->getMessage() ?? 'A visszaállítás váratlanul megszakadt.',
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -1,48 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
|
||||
/**
|
||||
* Egy elkészített deployment csomag naplóbejegyzése.
|
||||
*
|
||||
* Nem csak audit: a legutóbb kirakott csomag `to_commit`-je adja a következő csomag
|
||||
* alapértelmezett kezdő commitját, környezetenként külön - ez az, ami a "mi maradt ki
|
||||
* a másolásból" hibát megelőzi.
|
||||
*/
|
||||
class DeploymentPackage extends BaseAuditable
|
||||
{
|
||||
use SoftDeletes;
|
||||
|
||||
protected $casts = [
|
||||
'deployed_at' => 'datetime',
|
||||
'copied_count' => 'integer',
|
||||
'deleted_count' => 'integer',
|
||||
'skipped_count' => 'integer',
|
||||
'missing_count' => 'integer',
|
||||
];
|
||||
|
||||
public function scopeForTarget(Builder $query, string $target): Builder
|
||||
{
|
||||
return $query->where('target', $target);
|
||||
}
|
||||
|
||||
/**
|
||||
* Az adott környezetre utoljára kirakottként megjelölt csomag.
|
||||
*/
|
||||
public static function lastDeployedFor(string $target): ?self
|
||||
{
|
||||
return static::query()
|
||||
->forTarget($target)
|
||||
->whereNotNull('deployed_at')
|
||||
->latest('deployed_at')
|
||||
->first();
|
||||
}
|
||||
|
||||
public function isDeployed(): bool
|
||||
{
|
||||
return $this->deployed_at !== null;
|
||||
}
|
||||
}
|
||||
@ -1,19 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
class FeatureFlag extends BaseAuditable
|
||||
{
|
||||
protected $casts = [
|
||||
'enabled' => 'boolean',
|
||||
'stages' => 'array',
|
||||
'roles' => 'array',
|
||||
];
|
||||
|
||||
public function overrides(): HasMany
|
||||
{
|
||||
return $this->hasMany(FeatureFlagOverride::class);
|
||||
}
|
||||
}
|
||||
@ -1,22 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class FeatureFlagOverride extends BaseAuditable
|
||||
{
|
||||
protected $casts = [
|
||||
'active' => 'boolean',
|
||||
];
|
||||
|
||||
public function featureFlag(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(FeatureFlag::class);
|
||||
}
|
||||
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
}
|
||||
@ -2,9 +2,7 @@
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Enums\PricelistFileLineStatusEnum;
|
||||
use App\Enums\PricelistFileStatusEnum;
|
||||
use App\Enums\PricelistWorkflowStep;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
@ -44,132 +42,4 @@ public function lines(): HasMany
|
||||
{
|
||||
return $this->hasMany(PricelistFileLine::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Egy workflow lépés aktuális státusza a `workflow_steps` tömbből
|
||||
* ('pending' / 'inprogress' / 'completed' / 'failed'), vagy null, ha a lépés
|
||||
* nem szerepel a rekordban (régi fájloknál előfordulhat).
|
||||
*/
|
||||
public function stepStatus(PricelistWorkflowStep $step): ?string
|
||||
{
|
||||
foreach ($this->workflow_steps ?? [] as $workflowStep) {
|
||||
if (($workflowStep['name'] ?? null) === $step->value) {
|
||||
return $workflowStep['status'] ?? null;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Van-e a fájlban blokkoló (hibás) sor. Ez a jóváhagyás egyik feltétele:
|
||||
* hibás sorral nem indítható végrehajtás.
|
||||
*/
|
||||
public function hasErrorLines(): bool
|
||||
{
|
||||
return $this->lines()
|
||||
->where('status', PricelistFileLineStatusEnum::error->value)
|
||||
->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* Jóváhagyható-e a fájl. Egyetlen igazságforrás: ezt nézi a felületi gomb
|
||||
* láthatósága ÉS a végrehajtási job is induláskor - a felület 5 mp-enként
|
||||
* pollozik, így a gomb megjelenítése és a kattintás között változhat az állapot.
|
||||
*/
|
||||
public function canBeApproved(): bool
|
||||
{
|
||||
return $this->status === PricelistFileStatusEnum::waiting_for_approval
|
||||
&& $this->stepStatus(PricelistWorkflowStep::Validation) === 'completed'
|
||||
&& ! $this->hasErrorLines();
|
||||
}
|
||||
|
||||
/**
|
||||
* Elindult-e már a végrehajtás. Ha igen, a fájl újratöltése (Edit -> a teljes
|
||||
* lánc újraindítása) TILOS: addigra már létrejöhettek termékek és árak, egy
|
||||
* nulláról induló újrafuttatás duplikálna. Helyette a Folytatás vagy a
|
||||
* Visszavonás akció használható.
|
||||
*/
|
||||
public function hasExecutionStarted(): bool
|
||||
{
|
||||
return ! in_array($this->stepStatus(PricelistWorkflowStep::Execution), ['pending', null], true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ennyi tétlenség után tekintjük elakadtnak a futó végrehajtást/visszaállítást.
|
||||
* A job failed() hookja a hibák többségét lefedi, de egy `kill -9`-elt worker után
|
||||
* az sem fut le - ilyenkor a fájl inprogress-ben ragadna, egyetlen elérhető döntési
|
||||
* gomb nélkül. Minden chunk ír a rekordba, tehát az updated_at a heartbeat.
|
||||
*/
|
||||
public const STUCK_AFTER_MINUTES = 15;
|
||||
|
||||
public function isExecutionStuck(?int $minutes = null): bool
|
||||
{
|
||||
if ($this->status !== PricelistFileStatusEnum::inprogress || ! $this->hasExecutionStarted()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (bool) $this->updated_at?->lt(now()->subMinutes($minutes ?? self::STUCK_AFTER_MINUTES));
|
||||
}
|
||||
|
||||
public function isRevertRunning(): bool
|
||||
{
|
||||
return $this->status === PricelistFileStatusEnum::inprogress
|
||||
&& ($this->file_meta['revert']['last_status'] ?? null) === 'inprogress';
|
||||
}
|
||||
|
||||
/**
|
||||
* Vár-e a fájl felhasználói döntésre (folytatás vagy visszaállítás).
|
||||
*/
|
||||
public function needsExecutionDecision(): bool
|
||||
{
|
||||
return $this->status === PricelistFileStatusEnum::execution_failed || $this->isExecutionStuck();
|
||||
}
|
||||
|
||||
/**
|
||||
* Kényszerlezárható-e. Feltétel: volt legalább egy visszaállítási kísérlet, amely
|
||||
* TERMINÁLIS hibaállapotba jutott. Így a kényszerlezárás nem alternatív útvonal a
|
||||
* visszaállítás mellett, hanem csak annak kudarca után elérhető vészkijárat.
|
||||
*/
|
||||
public function canBeForceClosed(): bool
|
||||
{
|
||||
$revert = $this->file_meta['revert'] ?? [];
|
||||
|
||||
return $this->needsExecutionDecision()
|
||||
&& (int) ($revert['attempts'] ?? 0) >= 1
|
||||
&& ($revert['last_status'] ?? null) === 'failed';
|
||||
}
|
||||
|
||||
/**
|
||||
* Mi történt már a végrehajtásból. A felhasználó ez alapján tud dönteni a folytatás
|
||||
* és a visszaállítás között - enélkül vakon választana a két gomb közül.
|
||||
*/
|
||||
public function executionSummary(): array
|
||||
{
|
||||
return [
|
||||
'created_products' => $this->lines()
|
||||
->where('status', PricelistFileLineStatusEnum::new_product->value)
|
||||
->whereNotNull('product_id')
|
||||
->count(),
|
||||
'updated_products' => $this->lines()->whereNotNull('applied_snapshot')->count(),
|
||||
'priced_lines' => $this->lines()->whereNotNull('executed_at')->count(),
|
||||
'pending_lines' => $this->lines()
|
||||
->where('status', '!=', PricelistFileLineStatusEnum::error->value)
|
||||
->whereNull('executed_at')
|
||||
->count(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Soronkénti státuszok darabszáma (státusz => darab), a jóváhagyás előtti
|
||||
* összegző modalhoz.
|
||||
*/
|
||||
public function lineStatusCounts(): array
|
||||
{
|
||||
return $this->lines()
|
||||
->selectRaw('status, COUNT(*) as total')
|
||||
->groupBy('status')
|
||||
->pluck('total', 'status')
|
||||
->all();
|
||||
}
|
||||
}
|
||||
|
||||
@ -16,8 +16,6 @@ class PricelistFileLine extends BaseAuditable
|
||||
'payload' => 'array',
|
||||
'validation_messages' => 'array',
|
||||
'diff' => 'array',
|
||||
'applied_snapshot' => 'array',
|
||||
'executed_at' => 'datetime',
|
||||
];
|
||||
|
||||
public function pricelistFile(): BelongsTo
|
||||
|
||||
@ -2,10 +2,4 @@
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
class Producer extends BaseAuditable
|
||||
{
|
||||
public function aliases()
|
||||
{
|
||||
return $this->hasMany(ProducerAlias::class);
|
||||
}
|
||||
}
|
||||
class Producer extends BaseAuditable {}
|
||||
|
||||
@ -1,11 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
class ProducerAlias extends BaseAuditable
|
||||
{
|
||||
public function producer()
|
||||
{
|
||||
return $this->belongsTo(Producer::class);
|
||||
}
|
||||
}
|
||||
@ -4,12 +4,10 @@
|
||||
|
||||
use App\Enums\StockStatusEnum;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\MorphOne;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class Product extends BaseAuditable
|
||||
{
|
||||
@ -25,49 +23,6 @@ protected function casts(): array
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Beszállítónként az érvényes árlista: a legfrissebb, a megadott napig már hatályos
|
||||
* (available <= dátum), törlés nélküli lista; azonos dátumnál a kisebb id - ugyanaz a
|
||||
* sorrend, mint a Price()-ban. A termék akkor "érvényes árlistás", ha ebben szerepel.
|
||||
*/
|
||||
public function scopeInActivePriceList(Builder $query, ?string $date = null): Builder
|
||||
{
|
||||
$date ??= Carbon::today()->format('Y-m-d');
|
||||
|
||||
return $query->whereExists(function ($sub) use ($date) {
|
||||
$sub->from('price_list_prices as plp')
|
||||
->join('price_lists as pl', 'pl.id', '=', 'plp.price_list_id')
|
||||
->whereColumn('plp.product_id', 'products.id')
|
||||
->whereRaw('pl.id = ('.self::activePriceListIdSql().')', [$date])
|
||||
->select(DB::raw(1));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Hozzáadja a current_price oszlopot: a termék ára az érvényes árlistán
|
||||
* (lásd scopeInActivePriceList), NULL ha nem szerepel rajta.
|
||||
*/
|
||||
public function scopeWithActivePrice(Builder $query, ?string $date = null): Builder
|
||||
{
|
||||
$date ??= Carbon::today()->format('Y-m-d');
|
||||
|
||||
return $query->addSelect([
|
||||
'products.*',
|
||||
'current_price' => DB::table('price_list_prices as plp')
|
||||
->join('price_lists as pl', 'pl.id', '=', 'plp.price_list_id')
|
||||
->whereColumn('plp.product_id', 'products.id')
|
||||
->whereRaw('pl.id = ('.self::activePriceListIdSql().')', [$date])
|
||||
->select('plp.price')
|
||||
->limit(1),
|
||||
]);
|
||||
}
|
||||
|
||||
private static function activePriceListIdSql(): string
|
||||
{
|
||||
return 'select pl2.id from price_lists pl2 where pl2.supplier_id = pl.supplier_id '
|
||||
.'and pl2.deleted_at is null and pl2.available <= ? order by pl2.available desc, pl2.id asc limit 1';
|
||||
}
|
||||
|
||||
public function ProductGroup(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(ProductGroup::class);
|
||||
|
||||
@ -4,7 +4,6 @@
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Kalnoy\Nestedset\NodeTrait;
|
||||
|
||||
@ -33,11 +32,6 @@ class ProductGroup extends Model
|
||||
|
||||
protected ?array $needsId = null;
|
||||
|
||||
public function products(): HasMany
|
||||
{
|
||||
return $this->hasMany(Product::class, 'product_group_id');
|
||||
}
|
||||
|
||||
private function getNodeToArray($node, $needChild, $maxDepth = 999)
|
||||
{
|
||||
if ($this->needsId) {
|
||||
|
||||
@ -3,7 +3,6 @@
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\Relations\MorphMany;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
|
||||
@ -34,11 +33,6 @@ public function suppliers(): BelongsToMany
|
||||
return $this->belongsToMany(Supplier::class)->withTimestamps();
|
||||
}
|
||||
|
||||
public function supplierCustomerCodes(): HasMany
|
||||
{
|
||||
return $this->hasMany(ProfitCenterSupplierCode::class);
|
||||
}
|
||||
|
||||
public function contact(): MorphMany
|
||||
{
|
||||
return $this->morphMany(Contact::class, 'contactable');
|
||||
|
||||
@ -1,23 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
|
||||
class ProfitCenterSupplierCode extends BaseAuditable
|
||||
{
|
||||
use SoftDeletes;
|
||||
|
||||
protected $guarded = ['id', 'created_at', 'updated_at'];
|
||||
|
||||
public function profitCenter(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(ProfitCenter::class);
|
||||
}
|
||||
|
||||
public function supplier(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Supplier::class);
|
||||
}
|
||||
}
|
||||
@ -44,11 +44,6 @@ public function profitCenter(): BelongsToMany
|
||||
return $this->belongsToMany(ProfitCenter::class)->withTimestamps();
|
||||
}
|
||||
|
||||
public function customerCodes(): HasMany
|
||||
{
|
||||
return $this->hasMany(ProfitCenterSupplierCode::class);
|
||||
}
|
||||
|
||||
public function users(): HasMany
|
||||
{
|
||||
return $this->hasMany(User::class);
|
||||
|
||||
@ -1,23 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Observers;
|
||||
|
||||
use App\Models\FeatureFlag;
|
||||
use Laravel\Pennant\Feature;
|
||||
|
||||
class FeatureFlagObserver
|
||||
{
|
||||
/**
|
||||
* A Pennant lazy módon, scope-onként gyorsítótárazza a feloldott értékeket -
|
||||
* mentés/törlés után purge-elni kell, hogy a módosítás azonnal érvényesüljön.
|
||||
*/
|
||||
public function saved(FeatureFlag $flag): void
|
||||
{
|
||||
Feature::purge($flag->name);
|
||||
}
|
||||
|
||||
public function deleted(FeatureFlag $flag): void
|
||||
{
|
||||
Feature::purge($flag->name);
|
||||
}
|
||||
}
|
||||
@ -1,33 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Observers;
|
||||
|
||||
use App\Models\FeatureFlagOverride;
|
||||
use Laravel\Pennant\Feature;
|
||||
|
||||
class FeatureFlagOverrideObserver
|
||||
{
|
||||
/**
|
||||
* Létrehozás/módosítás/törlés után csak az érintett usernek a gyorsítótárazott
|
||||
* Pennant-feloldását érvénytelenítjük, a többi felhasználót nem érinti.
|
||||
*/
|
||||
public function saved(FeatureFlagOverride $override): void
|
||||
{
|
||||
$this->forget($override);
|
||||
}
|
||||
|
||||
public function deleted(FeatureFlagOverride $override): void
|
||||
{
|
||||
$this->forget($override);
|
||||
}
|
||||
|
||||
private function forget(FeatureFlagOverride $override): void
|
||||
{
|
||||
$user = $override->user;
|
||||
$flag = $override->featureFlag;
|
||||
|
||||
if ($user && $flag) {
|
||||
Feature::for($user)->forget($flag->name);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,50 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Policies;
|
||||
|
||||
use App\Models\FeatureFlagOverride;
|
||||
use App\Models\User;
|
||||
use Laravel\Pennant\Feature;
|
||||
|
||||
class FeatureFlagOverridePolicy
|
||||
{
|
||||
/**
|
||||
* Ugyanaz a "FeatureFlagAdmin" flag szabályozza a hozzáférést, mint a
|
||||
* FeatureFlagPolicy-nál - a felülbírálások ugyanannak a jogosultsági
|
||||
* körnek a részei, mint maguk a flagek.
|
||||
*/
|
||||
protected function hasAccess(User $user): bool
|
||||
{
|
||||
return Feature::for($user)->active('FeatureFlagAdmin');
|
||||
}
|
||||
|
||||
public function viewAny(User $user): bool
|
||||
{
|
||||
return $this->hasAccess($user);
|
||||
}
|
||||
|
||||
public function view(User $user, FeatureFlagOverride $featureFlagOverride): bool
|
||||
{
|
||||
return $this->hasAccess($user);
|
||||
}
|
||||
|
||||
public function create(User $user): bool
|
||||
{
|
||||
return $this->hasAccess($user);
|
||||
}
|
||||
|
||||
public function update(User $user, FeatureFlagOverride $featureFlagOverride): bool
|
||||
{
|
||||
return $this->hasAccess($user);
|
||||
}
|
||||
|
||||
public function delete(User $user, FeatureFlagOverride $featureFlagOverride): bool
|
||||
{
|
||||
return $this->hasAccess($user);
|
||||
}
|
||||
|
||||
public function deleteAny(User $user): bool
|
||||
{
|
||||
return $this->hasAccess($user);
|
||||
}
|
||||
}
|
||||
@ -1,50 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Policies;
|
||||
|
||||
use App\Models\FeatureFlag;
|
||||
use App\Models\User;
|
||||
use Laravel\Pennant\Feature;
|
||||
|
||||
class FeatureFlagPolicy
|
||||
{
|
||||
/**
|
||||
* A feature flag admin felület elérését magára a "FeatureFlagAdmin" flagre bízzuk,
|
||||
* hogy a hozzáférés szabályozása (stage/szerepkör/felhasználó szinten) deploy
|
||||
* nélkül, az admin felületről állítható legyen.
|
||||
*/
|
||||
protected function hasAccess(User $user): bool
|
||||
{
|
||||
return Feature::for($user)->active('FeatureFlagAdmin');
|
||||
}
|
||||
|
||||
public function viewAny(User $user): bool
|
||||
{
|
||||
return $this->hasAccess($user);
|
||||
}
|
||||
|
||||
public function view(User $user, FeatureFlag $featureFlag): bool
|
||||
{
|
||||
return $this->hasAccess($user);
|
||||
}
|
||||
|
||||
public function create(User $user): bool
|
||||
{
|
||||
return $this->hasAccess($user);
|
||||
}
|
||||
|
||||
public function update(User $user, FeatureFlag $featureFlag): bool
|
||||
{
|
||||
return $this->hasAccess($user);
|
||||
}
|
||||
|
||||
public function delete(User $user, FeatureFlag $featureFlag): bool
|
||||
{
|
||||
return $this->hasAccess($user);
|
||||
}
|
||||
|
||||
public function deleteAny(User $user): bool
|
||||
{
|
||||
return $this->hasAccess($user);
|
||||
}
|
||||
}
|
||||
@ -2,10 +2,6 @@
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use App\Models\FeatureFlag;
|
||||
use App\Models\FeatureFlagOverride;
|
||||
use App\Observers\FeatureFlagObserver;
|
||||
use App\Observers\FeatureFlagOverrideObserver;
|
||||
use App\Repositories\AddressRepository;
|
||||
use App\Repositories\AddressRepositoryInterface;
|
||||
use App\Repositories\ContactRepository;
|
||||
@ -24,8 +20,6 @@
|
||||
use App\Repositories\ProfitCenterRepositoryInterface;
|
||||
use App\Repositories\SupplierRepository;
|
||||
use App\Repositories\SupplierRepositoryInterface;
|
||||
use App\Services\FeatureFlagRegistrar;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
|
||||
@ -59,15 +53,6 @@ public function boot(): void
|
||||
{
|
||||
URL::forceScheme('https');
|
||||
|
||||
FeatureFlag::observe(FeatureFlagObserver::class);
|
||||
FeatureFlagOverride::observe(FeatureFlagOverrideObserver::class);
|
||||
|
||||
// Schema::hasTable védi a friss telepítést / migrate-et megelőző state-et,
|
||||
// amikor a feature_flags tábla még nem létezik.
|
||||
if (Schema::hasTable('feature_flags')) {
|
||||
app(FeatureFlagRegistrar::class)->registerAll();
|
||||
}
|
||||
|
||||
\Illuminate\Database\Schema\Blueprint::macro('userIdFields', function () {
|
||||
$this->unsignedInteger('created_by')->nullable();
|
||||
$this->unsignedInteger('updated_by')->nullable();
|
||||
@ -77,7 +62,6 @@ public function boot(): void
|
||||
\Livewire\Livewire::component('app.filament.pages.price-list-processor', \App\Filament\Pages\PriceListProcessor::class);
|
||||
\Livewire\Livewire::component('app.filament.auth.login', \App\Filament\Auth\Login::class);
|
||||
\Livewire\Livewire::component('app.filament.pages.calendar-test', \App\Filament\Pages\CalendarTest::class);
|
||||
\Livewire\Livewire::component('app.filament.pages.supplier-customer-codes', \App\Filament\Pages\SupplierCustomerCodes::class);
|
||||
\Livewire\Livewire::component('app.filament.widgets.delivery-calendar-widget', \App\Filament\Widgets\DeliveryCalendarWidget::class);
|
||||
|
||||
\Livewire\Livewire::component('app.filament.supplier-portal.resources.product-stocks.pages.list-product-stocks', \App\Filament\SupplierPortal\Resources\ProductStocks\Pages\ListProductStocks::class);
|
||||
@ -104,15 +88,6 @@ public function boot(): void
|
||||
\Livewire\Livewire::component('app.filament.resources.profit-center-supplier-schedules.pages.create-profit-center-supplier-schedule', \App\Filament\Resources\ProfitCenterSupplierSchedules\Pages\CreateProfitCenterSupplierSchedule::class);
|
||||
\Livewire\Livewire::component('app.filament.resources.profit-center-supplier-schedules.pages.edit-profit-center-supplier-schedule', \App\Filament\Resources\ProfitCenterSupplierSchedules\Pages\EditProfitCenterSupplierSchedule::class);
|
||||
|
||||
\Livewire\Livewire::component('app.filament.resources.feature-flags.pages.list-feature-flags', \App\Filament\Resources\FeatureFlags\Pages\ListFeatureFlags::class);
|
||||
\Livewire\Livewire::component('app.filament.resources.feature-flags.pages.create-feature-flag', \App\Filament\Resources\FeatureFlags\Pages\CreateFeatureFlag::class);
|
||||
\Livewire\Livewire::component('app.filament.resources.feature-flags.pages.edit-feature-flag', \App\Filament\Resources\FeatureFlags\Pages\EditFeatureFlag::class);
|
||||
\Livewire\Livewire::component('app.filament.resources.feature-flags.relation-managers.overrides-relation-manager', \App\Filament\Resources\FeatureFlags\RelationManagers\OverridesRelationManager::class);
|
||||
|
||||
\Livewire\Livewire::component('app.filament.resources.feature-flag-overrides.pages.list-feature-flag-overrides', \App\Filament\Resources\FeatureFlagOverrides\Pages\ListFeatureFlagOverrides::class);
|
||||
\Livewire\Livewire::component('app.filament.resources.feature-flag-overrides.pages.create-feature-flag-override', \App\Filament\Resources\FeatureFlagOverrides\Pages\CreateFeatureFlagOverride::class);
|
||||
\Livewire\Livewire::component('app.filament.resources.feature-flag-overrides.pages.edit-feature-flag-override', \App\Filament\Resources\FeatureFlagOverrides\Pages\EditFeatureFlagOverride::class);
|
||||
|
||||
\Livewire\Livewire::component('filament.livewire.notifications', \Filament\Livewire\Notifications::class);
|
||||
\Livewire\Livewire::component('filament.livewire.database-notifications', \Filament\Livewire\DatabaseNotifications::class);
|
||||
\Livewire\Livewire::component('filament.livewire.sidebar', \Filament\Livewire\Sidebar::class);
|
||||
|
||||
@ -13,8 +13,7 @@ class AuthServiceProvider extends ServiceProvider
|
||||
* @var array<class-string, class-string>
|
||||
*/
|
||||
protected $policies = [
|
||||
\App\Models\FeatureFlag::class => \App\Policies\FeatureFlagPolicy::class,
|
||||
\App\Models\FeatureFlagOverride::class => \App\Policies\FeatureFlagOverridePolicy::class,
|
||||
// 'App\Models\Model' => 'App\Policies\ModelPolicy',
|
||||
];
|
||||
|
||||
/**
|
||||
|
||||
@ -26,7 +26,7 @@ public function __construct(
|
||||
* 3. Általános override (az összes PC-re vonatkozó)
|
||||
* Ha egyetlen szinten sem található override, folytatódik a normál kiértékelés.
|
||||
*/
|
||||
public function isDeliveryDay(ProfitCenter $pc, Supplier $supplier, Carbon $date, ?ProfitCenterSupplierSchedule $assignment = null): bool
|
||||
public function isDeliveryDay(ProfitCenter $pc, Supplier $supplier, Carbon $date): bool
|
||||
{
|
||||
$date = $date->startOfDay();
|
||||
|
||||
@ -42,12 +42,10 @@ public function isDeliveryDay(ProfitCenter $pc, Supplier $supplier, Carbon $date
|
||||
}
|
||||
|
||||
// PC-hez rendelt szállítási sablon lekérése (2. és 5. prioritáshoz egyaránt szükséges)
|
||||
if ($assignment === null) {
|
||||
$assignment = ProfitCenterSupplierSchedule::where('profit_center_id', $pc->id)
|
||||
->where('supplier_id', $supplier->id)
|
||||
->with('deliverySchedule')
|
||||
->first();
|
||||
}
|
||||
$assignment = ProfitCenterSupplierSchedule::where('profit_center_id', $pc->id)
|
||||
->where('supplier_id', $supplier->id)
|
||||
->with('deliverySchedule')
|
||||
->first();
|
||||
|
||||
// 2. Prioritás: DeliverySchedule-specifikus felülbírálás (a PC-hez rendelt szállítási sablon alapján)
|
||||
if ($assignment && $assignment->delivery_schedule_id) {
|
||||
@ -72,11 +70,9 @@ public function isDeliveryDay(ProfitCenter $pc, Supplier $supplier, Carbon $date
|
||||
return $override->is_delivery_day;
|
||||
}
|
||||
|
||||
// 4. Prioritás: Hivatalos munkaszüneti nap (WorkCalendar)
|
||||
// Csak a naptárban ünnepnapként rögzített dátum tilt. A naptári hétvége önmagában
|
||||
// NEM: azt az 5. pont heti sablonja dönti el, különben egy hétvégét is tartalmazó
|
||||
// sablon napjai elérhetetlenek maradnának (EV3-466).
|
||||
if ($this->workCalendarService->isHoliday($date)) {
|
||||
// 4. Prioritás: Hivatalos ünnepnap (WorkCalendar)
|
||||
// Ha aznap nem hivatalos munkanap van, akkor nincs szállítás (kivéve ha az 1-3. pont felülbírálta).
|
||||
if (! $this->workCalendarService->isWorkDay($date)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@ -95,14 +91,14 @@ public function isDeliveryDay(ProfitCenter $pc, Supplier $supplier, Carbon $date
|
||||
*
|
||||
* @return Collection<Carbon>
|
||||
*/
|
||||
public function getAvailableDeliveryDates(ProfitCenter $pc, Supplier $supplier, Carbon $start, Carbon $end, ?ProfitCenterSupplierSchedule $assignment = null): Collection
|
||||
public function getAvailableDeliveryDates(ProfitCenter $pc, Supplier $supplier, Carbon $start, Carbon $end): Collection
|
||||
{
|
||||
$dates = collect();
|
||||
$current = $start->copy()->startOfDay();
|
||||
$end = $end->copy()->startOfDay();
|
||||
|
||||
while ($current <= $end) {
|
||||
if ($this->isDeliveryDay($pc, $supplier, $current, $assignment)) {
|
||||
if ($this->isDeliveryDay($pc, $supplier, $current)) {
|
||||
$dates->push($current->copy());
|
||||
}
|
||||
$current->addDay();
|
||||
|
||||
@ -1,205 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Deployment;
|
||||
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* A git diff nyers kimenetéből állítja elő a csomagolható halmazt és a figyelmeztetéseket.
|
||||
*
|
||||
* Szándékosan nem hív gitet és nem ír fájlt: tisztán a listát és a szabályokat kezeli,
|
||||
* így a fázis 2 csomagolója ugyanezt az eredményt tudja majd felhasználni.
|
||||
*/
|
||||
class ChangeSetAnalyzer
|
||||
{
|
||||
/**
|
||||
* @param array<int, array{status:string, path:string, old_path:?string}> $changedFiles
|
||||
* @param array{key:string, label:string, domain:string, remote_path:string, expected_branch:?string}|null $target
|
||||
* @return array{
|
||||
* files: array<int, array{status:string, path:string, old_path:?string, excluded:bool, action:string}>,
|
||||
* copied: array<int, string>,
|
||||
* deleted: array<int, string>,
|
||||
* counts: array{total:int, copied:int, deleted:int, excluded:int},
|
||||
* warnings: array<int, array{level:string, title:string, body:string}>
|
||||
* }
|
||||
*/
|
||||
public function analyze(array $changedFiles, ?array $target = null, ?string $branch = null): array
|
||||
{
|
||||
/** @var array<int, string> $excludePatterns */
|
||||
$excludePatterns = (array) config('deployment.exclude', []);
|
||||
|
||||
$files = [];
|
||||
$copied = [];
|
||||
$deleted = [];
|
||||
$excludedCount = 0;
|
||||
|
||||
foreach ($changedFiles as $file) {
|
||||
$excluded = Str::is($excludePatterns, $file['path']);
|
||||
|
||||
// Törlés esetén nincs mit másolni: a fájl a célgépen létezik, itt már nem.
|
||||
// Átnevezésnél mindkettő kell - az új útvonal másolandó, a régi törlendő.
|
||||
$action = $excluded
|
||||
? 'skip'
|
||||
: ($file['status'] === 'D' ? 'delete' : 'copy');
|
||||
|
||||
if ($excluded) {
|
||||
$excludedCount++;
|
||||
} elseif ($action === 'delete') {
|
||||
$deleted[] = $file['path'];
|
||||
} else {
|
||||
$copied[] = $file['path'];
|
||||
|
||||
if ($file['old_path'] !== null && ! Str::is($excludePatterns, $file['old_path'])) {
|
||||
$deleted[] = $file['old_path'];
|
||||
}
|
||||
}
|
||||
|
||||
$files[] = array_merge($file, ['excluded' => $excluded, 'action' => $action]);
|
||||
}
|
||||
|
||||
return [
|
||||
'files' => $files,
|
||||
'copied' => $copied,
|
||||
'deleted' => $deleted,
|
||||
'counts' => [
|
||||
'total' => count($files),
|
||||
'copied' => count($copied),
|
||||
'deleted' => count($deleted),
|
||||
'excluded' => $excludedCount,
|
||||
],
|
||||
'warnings' => $this->warnings($copied, $deleted, $excludedCount, $target, $branch),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $copied
|
||||
* @param array<int, string> $deleted
|
||||
* @param array{key:string, label:string, domain:string, remote_path:string, expected_branch:?string}|null $target
|
||||
* @return array<int, array{level:string, title:string, body:string}>
|
||||
*/
|
||||
private function warnings(array $copied, array $deleted, int $excludedCount, ?array $target, ?string $branch): array
|
||||
{
|
||||
$warnings = [];
|
||||
$maxFiles = (int) config('deployment.max_files', 500);
|
||||
|
||||
if ($copied === [] && $deleted === []) {
|
||||
$warnings[] = [
|
||||
'level' => 'info',
|
||||
'title' => 'Nincs csomagolható változás',
|
||||
'body' => 'A két commit között nincs olyan fájl, ami a célgépre kerülne.',
|
||||
];
|
||||
}
|
||||
|
||||
if (count($copied) > $maxFiles) {
|
||||
$warnings[] = [
|
||||
'level' => 'danger',
|
||||
'title' => sprintf('Túl sok fájl (%d db, limit %d)', count($copied), $maxFiles),
|
||||
'body' => 'Ekkora tartomány kézi másolással már nehezen ellenőrizhető. Szűkítsd a commit-tartományt, vagy bontsd több csomagra.',
|
||||
];
|
||||
}
|
||||
|
||||
$migrations = $this->matching($copied, 'migration');
|
||||
|
||||
if ($migrations !== []) {
|
||||
$warnings[] = [
|
||||
'level' => 'warning',
|
||||
'title' => sprintf('Migráció a csomagban (%d db)', count($migrations)),
|
||||
'body' => 'A fájlok felmásolása után a célgépen le kell futtatni: php artisan migrate',
|
||||
];
|
||||
}
|
||||
|
||||
$seeders = $this->matching($copied, 'seeder');
|
||||
|
||||
if ($seeders !== []) {
|
||||
$warnings[] = [
|
||||
'level' => 'warning',
|
||||
'title' => sprintf('Seeder a csomagban (%d db)', count($seeders)),
|
||||
'body' => 'A seeder felmásolása önmagában nem csinál semmit - el kell dönteni, hogy le kell-e futtatni a célgépen. '
|
||||
.'Ha feature flageket ír, a lefutása után azok azonnal hatnak.',
|
||||
];
|
||||
}
|
||||
|
||||
if ($this->matching($copied, 'composer') !== []) {
|
||||
$warnings[] = [
|
||||
'level' => 'warning',
|
||||
'title' => 'Függőség változott (composer)',
|
||||
'body' => 'A vendor/ nincs verziókövetve, ezért nem kerül a csomagba - a célgépen composer install szükséges.',
|
||||
];
|
||||
}
|
||||
|
||||
if ($this->matching($copied, 'asset') !== []) {
|
||||
$warnings[] = [
|
||||
'level' => 'warning',
|
||||
'title' => 'Frontend forrás változott',
|
||||
'body' => 'A fordított assetek (public/build, public/js, public/css, mix-manifest.json) a .gitignore miatt NEM kerülnek a csomagba. Futtass npm run build-ot, és a fázis 4-től külön csatolhatók lesznek.',
|
||||
];
|
||||
}
|
||||
|
||||
if ($this->matching($copied, 'runtime') !== []) {
|
||||
$jobs = count($this->matching($copied, 'job'));
|
||||
$consoles = count($this->matching($copied, 'console'));
|
||||
|
||||
$detail = [];
|
||||
|
||||
if ($jobs > 0) {
|
||||
$detail[] = $jobs.' job';
|
||||
}
|
||||
|
||||
if ($consoles > 0) {
|
||||
$detail[] = $consoles.' konzol parancs';
|
||||
}
|
||||
|
||||
$warnings[] = [
|
||||
'level' => 'warning',
|
||||
'title' => 'Hosszan futó konténerek érintve'.($detail === [] ? '' : ' ('.implode(', ', $detail).')'),
|
||||
'body' => 'A queue worker és a scheduler külön konténerben fut, és a betöltött osztályokat a memóriájában '
|
||||
.'tartja - a fájlok felmásolása után is a RÉGI kóddal dolgozik, amíg újra nem indul. Ez némán rossz '
|
||||
.'viselkedést okoz (a job "elkészül", de nem azt csinálja, amit az új kód). A konkrét restart parancsok '
|
||||
.'a csomag _TEENDOK.md fájljában lesznek.',
|
||||
];
|
||||
}
|
||||
|
||||
if ($deleted !== []) {
|
||||
$warnings[] = [
|
||||
'level' => 'warning',
|
||||
'title' => sprintf('Törlendő fájl a célgépen (%d db)', count($deleted)),
|
||||
'body' => 'Ezeket a másolás nem intézi el, kézzel kell törölni - a csomag _TORLENDO.txt fájlja fogja tartalmazni őket.',
|
||||
];
|
||||
}
|
||||
|
||||
if ($excludedCount > 0) {
|
||||
$warnings[] = [
|
||||
'level' => 'info',
|
||||
'title' => sprintf('Kihagyott fájl (%d db)', $excludedCount),
|
||||
'body' => 'A kizárási lista (.env, storage/, vendor/, node_modules/, .git*) alapján ezek soha nem kerülnek csomagba.',
|
||||
];
|
||||
}
|
||||
|
||||
if ($target && $target['expected_branch'] && $branch && $branch !== $target['expected_branch']) {
|
||||
$warnings[] = [
|
||||
'level' => 'warning',
|
||||
'title' => 'Nem a szokásos branch',
|
||||
'body' => sprintf(
|
||||
'A(z) "%s" környezetre általában a %s branchről megy csomag, most viszont a %s van kiválasztva.',
|
||||
$target['label'],
|
||||
$target['expected_branch'],
|
||||
$branch,
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
return $warnings;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $paths
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function matching(array $paths, string $group): array
|
||||
{
|
||||
/** @var array<int, string> $patterns */
|
||||
$patterns = (array) config('deployment.attention.'.$group, []);
|
||||
|
||||
return array_values(array_filter($paths, fn (string $path): bool => Str::is($patterns, $path)));
|
||||
}
|
||||
}
|
||||
@ -1,92 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Deployment;
|
||||
|
||||
use App\Models\User;
|
||||
use Laravel\Pennant\Feature;
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* A deployment csomagoló hozzáférés-ellenőrzése egy helyen.
|
||||
*
|
||||
* Az alkalmazás kódja manuális fájlmásolással kerül a szerverekre, tehát ez az oldal
|
||||
* fizikailag ott lesz az éles környezetben is. Ezért négy, egymástól független feltétel
|
||||
* van, és mindet MINDEN belépési ponton ellenőrizni kell (oldal mount, akciók, később a
|
||||
* csomagoló service) - ha csak a felületet védjük, az látszatvédelem.
|
||||
*
|
||||
* A négyből a tényleges védelmet az .env kapcsoló és a stage whitelist adja, a
|
||||
* jogosultságot a szerepkör. A feature flag NEM biztonsági réteg: a menü-láthatóságot
|
||||
* vezérli, és lehetővé teszi a deploy nélküli kikapcsolást, illetve a név szerinti
|
||||
* átadást (feature_flag_overrides) developer szerep osztogatása nélkül.
|
||||
*/
|
||||
class DeploymentGuard
|
||||
{
|
||||
public function isAllowed(?User $user = null): bool
|
||||
{
|
||||
return $this->denialReason($user) === null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Csak a környezeti feltételek (1-2. réteg), felhasználó nélkül.
|
||||
*
|
||||
* Ezt hívja a csomagoló service is: így akkor sem fut le, ha valaki a felületet
|
||||
* megkerülve (konzolról, jobból) indítaná el egy szerveren.
|
||||
*/
|
||||
public function environmentDenialReason(): ?string
|
||||
{
|
||||
if (! config('deployment.enabled')) {
|
||||
return 'A deployment csomagoló ki van kapcsolva (DEPLOYMENT_PACKAGE_ENABLED).';
|
||||
}
|
||||
|
||||
/** @var array<int, string> $stages */
|
||||
$stages = (array) config('deployment.stages', []);
|
||||
|
||||
if (! in_array((string) config('app.stage'), $stages, true)) {
|
||||
return sprintf(
|
||||
'A deployment csomagoló csak fejlesztői környezetben használható (engedélyezett stage: %s, jelenlegi: %s).',
|
||||
implode(', ', $stages),
|
||||
(string) config('app.stage'),
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Az első nem teljesülő feltétel magyarázata, vagy null, ha minden rendben.
|
||||
*/
|
||||
public function denialReason(?User $user = null): ?string
|
||||
{
|
||||
if ($reason = $this->environmentDenialReason()) {
|
||||
return $reason;
|
||||
}
|
||||
|
||||
if (! $user) {
|
||||
return 'Bejelentkezés szükséges.';
|
||||
}
|
||||
|
||||
if (! $user->hasRole((string) config('deployment.role'))) {
|
||||
return 'A deployment csomagoló csak fejlesztői szerepkörrel érhető el.';
|
||||
}
|
||||
|
||||
if (! Feature::for($user)->active((string) config('deployment.feature_flag'))) {
|
||||
return 'A deployment csomagoló feature flag nincs bekapcsolva erre a felhasználóra.';
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function ensureAllowed(?User $user = null): void
|
||||
{
|
||||
if ($reason = $this->denialReason($user)) {
|
||||
abort(403, $reason);
|
||||
}
|
||||
}
|
||||
|
||||
public function ensureEnvironmentAllowed(): void
|
||||
{
|
||||
if ($reason = $this->environmentDenialReason()) {
|
||||
throw new RuntimeException($reason);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,510 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Deployment;
|
||||
|
||||
use Illuminate\Filesystem\Filesystem;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Str;
|
||||
use RuntimeException;
|
||||
use ZipArchive;
|
||||
|
||||
/**
|
||||
* A kijelölt commit-tartományból állítja elő a feltölthető csomagot.
|
||||
*
|
||||
* A kimenet egy mappa, amiben a fájlok EREDETI relatív útvonalon ülnek - így a
|
||||
* feltöltés a célgépen sima mappa-összeolvasztás. A tartalom mindig a záró commitból
|
||||
* jön (ld. GitRepository::archiveTo), nem a working tree-ből.
|
||||
*
|
||||
* A törölt fájlokat a másolás nem tudja elintézni, ezért azok külön listába kerülnek
|
||||
* (_TORLENDO.txt) - ez szándékosan kézi lépés marad.
|
||||
*/
|
||||
class DeploymentPackageBuilder
|
||||
{
|
||||
public function __construct(
|
||||
private readonly GitRepository $repository,
|
||||
private readonly ChangeSetAnalyzer $analyzer,
|
||||
private readonly DeploymentTargets $targets,
|
||||
private readonly DeploymentGuard $guard,
|
||||
private readonly Filesystem $files,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $skippedPaths a felületen kézzel kivett fájlok
|
||||
* @return array{
|
||||
* name:string, path:string, zip:?string, target:string, branch:string,
|
||||
* from:string, to:string, created_at:string, created_by:string,
|
||||
* counts:array{copied:int, deleted:int, excluded:int, skipped:int, missing:int},
|
||||
* files:array<int, array{path:string, status:string, size:int, sha1:string}>,
|
||||
* deleted:array<int, string>, skipped:array<int, string>, missing:array<int, string>,
|
||||
* warnings:array<int, array{level:string, title:string, body:string}>
|
||||
* }
|
||||
*/
|
||||
public function build(
|
||||
string $targetKey,
|
||||
string $branch,
|
||||
string $fromCommit,
|
||||
string $toCommit,
|
||||
array $skippedPaths = [],
|
||||
?string $createdBy = null,
|
||||
): array {
|
||||
$this->guard->ensureEnvironmentAllowed();
|
||||
|
||||
$target = $this->targets->find($targetKey);
|
||||
|
||||
if (! $target) {
|
||||
throw new RuntimeException('Ismeretlen célkörnyezet.');
|
||||
}
|
||||
|
||||
$from = $this->repository->resolveCommit($fromCommit);
|
||||
$to = $this->repository->resolveCommit($toCommit);
|
||||
|
||||
if (! $from || ! $to) {
|
||||
throw new RuntimeException('Ismeretlen commit azonosító.');
|
||||
}
|
||||
|
||||
$changeSet = $this->analyzer->analyze(
|
||||
$this->repository->changedFiles($from, $to),
|
||||
$target,
|
||||
$branch,
|
||||
);
|
||||
|
||||
$statuses = [];
|
||||
|
||||
foreach ($changeSet['files'] as $file) {
|
||||
$statuses[$file['path']] = $file['status'];
|
||||
}
|
||||
|
||||
$skipped = array_values(array_intersect($changeSet['copied'], $skippedPaths));
|
||||
$copy = array_values(array_diff($changeSet['copied'], $skippedPaths));
|
||||
$maxFiles = (int) config('deployment.max_files', 500);
|
||||
|
||||
if (count($copy) > $maxFiles) {
|
||||
throw new RuntimeException(sprintf(
|
||||
'A csomag %d fájlt tartalmazna, a limit %d. Szűkítsd a commit-tartományt.',
|
||||
count($copy),
|
||||
$maxFiles,
|
||||
));
|
||||
}
|
||||
|
||||
if ($copy === [] && $changeSet['deleted'] === []) {
|
||||
throw new RuntimeException('Nincs mit csomagolni: a tartományban nincs a célgépre kerülő változás.');
|
||||
}
|
||||
|
||||
$createdAt = Carbon::now();
|
||||
$path = $this->createDirectory($targetKey, $createdAt);
|
||||
$written = $this->repository->archiveTo($to, $copy, $path);
|
||||
|
||||
// Ha a git archive kihagyott valamit (pl. .gitattributes export-ignore), az itt
|
||||
// derül ki - csendben hiányzó fájl a manuális deploynál pont a legrosszabb hiba.
|
||||
$missing = array_values(array_diff($copy, $written));
|
||||
|
||||
$manifest = [
|
||||
'name' => basename($path),
|
||||
'path' => $path,
|
||||
'target' => $targetKey,
|
||||
'branch' => $branch,
|
||||
'from' => $from,
|
||||
'to' => $to,
|
||||
'created_at' => $createdAt->toIso8601String(),
|
||||
'created_by' => $createdBy ?? 'ismeretlen',
|
||||
'counts' => [
|
||||
'copied' => count($written),
|
||||
'deleted' => count($changeSet['deleted']),
|
||||
'excluded' => $changeSet['counts']['excluded'],
|
||||
'skipped' => count($skipped),
|
||||
'missing' => count($missing),
|
||||
],
|
||||
'files' => $this->describeFiles($path, $written, $statuses),
|
||||
'deleted' => $changeSet['deleted'],
|
||||
'skipped' => $skipped,
|
||||
'missing' => $missing,
|
||||
'warnings' => $changeSet['warnings'],
|
||||
];
|
||||
|
||||
$this->writeVersionMarker($path, $manifest, $target);
|
||||
$this->writeManifest($path, $manifest, $target);
|
||||
$this->writeDeleteList($path, $manifest, $target);
|
||||
$this->writeDeleteScript($path, $manifest, $target);
|
||||
$this->writeInstructions($path, $manifest, $target);
|
||||
|
||||
// A ZIP készül utoljára, hogy a kísérő fájlokat is tartalmazza. A fájllistát
|
||||
// előbb gyűjtjük össze, mint ahogy a zip létrejön, így nem tudja magát becsomagolni.
|
||||
$manifest['zip'] = $this->createZip($path, $manifest['name']);
|
||||
|
||||
return $manifest;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $written
|
||||
* @param array<string, string> $statuses
|
||||
* @return array<int, array{path:string, status:string, size:int, sha1:string}>
|
||||
*/
|
||||
private function describeFiles(string $path, array $written, array $statuses): array
|
||||
{
|
||||
sort($written);
|
||||
|
||||
return array_map(function (string $relative) use ($path, $statuses): array {
|
||||
$absolute = $path.DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $relative);
|
||||
|
||||
return [
|
||||
'path' => $relative,
|
||||
'status' => $statuses[$relative] ?? '?',
|
||||
'size' => $this->files->exists($absolute) ? $this->files->size($absolute) : 0,
|
||||
'sha1' => $this->files->exists($absolute) ? (string) sha1_file($absolute) : '',
|
||||
];
|
||||
}, $written);
|
||||
}
|
||||
|
||||
private function createDirectory(string $targetKey, Carbon $createdAt): string
|
||||
{
|
||||
$base = rtrim((string) config('deployment.output_path'), '/\\');
|
||||
$name = sprintf('deploy_%s_%s', $targetKey, $createdAt->format('Ymd_His'));
|
||||
$path = $base.DIRECTORY_SEPARATOR.$name;
|
||||
|
||||
// Ugyanabban a másodpercben indított második csomag ne írja felül az elsőt.
|
||||
$suffix = 2;
|
||||
|
||||
while ($this->files->exists($path)) {
|
||||
$path = $base.DIRECTORY_SEPARATOR.$name.'-'.$suffix++;
|
||||
}
|
||||
|
||||
$this->files->makeDirectory($path, 0775, true);
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
/**
|
||||
* A kirakott verzió azonosítója - ettől kezdve a "melyik commit fut a szerveren?"
|
||||
* kérdés egy HTTP kéréssel megválaszolható, nem kézi fájldiffel.
|
||||
*
|
||||
* @param array<string, mixed> $manifest
|
||||
* @param array<string, mixed> $target
|
||||
*/
|
||||
private function writeVersionMarker(string $path, array $manifest, array $target): void
|
||||
{
|
||||
$this->put($path.'/public/deploy-version.json', json_encode([
|
||||
'target' => $target['key'],
|
||||
'commit' => $manifest['to'],
|
||||
'short' => substr((string) $manifest['to'], 0, 7),
|
||||
'branch' => $manifest['branch'],
|
||||
'packaged_at' => $manifest['created_at'],
|
||||
'by' => $manifest['created_by'],
|
||||
], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)."\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $manifest
|
||||
* @param array<string, mixed> $target
|
||||
*/
|
||||
private function writeManifest(string $path, array $manifest, array $target): void
|
||||
{
|
||||
$this->put(
|
||||
$path.'/_MANIFEST.json',
|
||||
json_encode($manifest, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)."\n",
|
||||
);
|
||||
|
||||
$lines = [
|
||||
'DEPLOYMENT CSOMAG',
|
||||
str_repeat('=', 60),
|
||||
'Csomag: '.$manifest['name'],
|
||||
'Célkörnyezet: '.$target['label'],
|
||||
'Cél útvonal: '.$target['remote_path'],
|
||||
'Branch: '.$manifest['branch'],
|
||||
'Tartomány: '.substr((string) $manifest['from'], 0, 7).' (kizárva) -> '.substr((string) $manifest['to'], 0, 7).' (beleértve)',
|
||||
'Készítette: '.$manifest['created_by'],
|
||||
'Készült: '.$manifest['created_at'],
|
||||
'',
|
||||
sprintf('MÁSOLANDÓ FÁJLOK (%d)', $manifest['counts']['copied']),
|
||||
str_repeat('-', 60),
|
||||
];
|
||||
|
||||
foreach ($manifest['files'] as $file) {
|
||||
// mb_str_pad, mert a sprintf %-70s bájtban számol - egy ékezetes fájlnév
|
||||
// elcsúsztatná az oszlopot.
|
||||
$lines[] = sprintf(
|
||||
'%-2s %s %8d %s',
|
||||
$file['status'],
|
||||
mb_str_pad($file['path'], 70),
|
||||
$file['size'],
|
||||
$file['sha1'],
|
||||
);
|
||||
}
|
||||
|
||||
if ($manifest['deleted'] !== []) {
|
||||
$lines[] = '';
|
||||
$lines[] = sprintf('TÖRLENDŐ A CÉLGÉPEN (%d) - ld. _TORLENDO.txt', $manifest['counts']['deleted']);
|
||||
$lines[] = str_repeat('-', 60);
|
||||
|
||||
foreach ($manifest['deleted'] as $deleted) {
|
||||
$lines[] = ' '.$deleted;
|
||||
}
|
||||
}
|
||||
|
||||
if ($manifest['skipped'] !== []) {
|
||||
$lines[] = '';
|
||||
$lines[] = sprintf('KÉZZEL KIVÉVE A CSOMAGBÓL (%d)', $manifest['counts']['skipped']);
|
||||
$lines[] = str_repeat('-', 60);
|
||||
|
||||
foreach ($manifest['skipped'] as $skipped) {
|
||||
$lines[] = ' '.$skipped;
|
||||
}
|
||||
}
|
||||
|
||||
if ($manifest['missing'] !== []) {
|
||||
$lines[] = '';
|
||||
$lines[] = sprintf('FIGYELEM - NEM KERÜLT A CSOMAGBA (%d)', $manifest['counts']['missing']);
|
||||
$lines[] = str_repeat('-', 60);
|
||||
|
||||
foreach ($manifest['missing'] as $missing) {
|
||||
$lines[] = ' '.$missing;
|
||||
}
|
||||
}
|
||||
|
||||
$this->put($path.'/_MANIFEST.txt', implode("\n", $lines)."\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $manifest
|
||||
* @param array<string, mixed> $target
|
||||
*/
|
||||
private function writeDeleteList(string $path, array $manifest, array $target): void
|
||||
{
|
||||
$lines = [
|
||||
'# '.$manifest['name'].' - a célgépen TÖRLENDŐ fájlok',
|
||||
'# Cél: '.$target['label'].' - '.$target['remote_path'],
|
||||
'# A másolás ezeket nem intézi el, a törlés kézi lépés.',
|
||||
'',
|
||||
];
|
||||
|
||||
foreach ($manifest['deleted'] as $deleted) {
|
||||
$lines[] = $deleted;
|
||||
}
|
||||
|
||||
if ($manifest['deleted'] === []) {
|
||||
$lines[] = '# (nincs törlendő fájl ebben a csomagban)';
|
||||
}
|
||||
|
||||
$this->put($path.'/_TORLENDO.txt', implode("\n", $lines)."\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $manifest
|
||||
* @param array<string, mixed> $target
|
||||
*/
|
||||
private function writeInstructions(string $path, array $manifest, array $target): void
|
||||
{
|
||||
$steps = [
|
||||
'A csomag mappájának **tartalmát** másold fel ide: `'.$target['remote_path'].'`'
|
||||
.' — mappa-összeolvasztás, NEM a teljes app mappa cseréje. A `_` kezdetű fájlokat ne másold fel.',
|
||||
];
|
||||
|
||||
/** @var array<int, string> $restartSteps */
|
||||
$restartSteps = [];
|
||||
|
||||
if ($manifest['deleted'] !== []) {
|
||||
$steps[] = sprintf(
|
||||
'Töröld a `_TORLENDO.txt`-ben felsorolt %d fájlt a célgépen. Nagyobb mennyiségnél a mellékelt '
|
||||
.'szkript is használható **átnézés után**: `bash _torles.sh` kilistázza, `bash _torles.sh --confirm` törli.',
|
||||
$manifest['counts']['deleted'],
|
||||
);
|
||||
}
|
||||
|
||||
foreach ($manifest['warnings'] as $warning) {
|
||||
if (str_contains($warning['title'], 'Migráció')) {
|
||||
$steps[] = 'Futtasd a célgépen: `php artisan migrate`';
|
||||
}
|
||||
|
||||
if (str_contains($warning['title'], 'Seeder')) {
|
||||
$seeders = $this->seederClasses($manifest);
|
||||
|
||||
$steps[] = sprintf(
|
||||
'Seeder változott (%s). A felmásolás önmagában NEM futtatja le - ha idempotens '
|
||||
.'(`updateOrCreate`/`firstOrCreate`), futtasd: %s',
|
||||
implode(', ', $seeders),
|
||||
implode(' ', array_map(fn (string $class): string => '`php artisan db:seed --class='.$class.'`', $seeders)),
|
||||
);
|
||||
|
||||
// A projekt FeatureFlagObserver-e Eloquent mentéskor magától purge-öl, ezért
|
||||
// ezt nem kötelező lépésként, hanem feltételes ellenőrzésként írjuk ki.
|
||||
$steps[] = 'Ha a seeder feature flageket írt **Eloquent modellen keresztül**, a Pennant cache-t a '
|
||||
.'`FeatureFlagObserver` magától üríti. Query builderes írás (`->update()`) esetén viszont kell: '
|
||||
.'`php artisan pennant:purge`. Ha szerepkör/jogosultság **hozzárendelés** változott, a laratrust '
|
||||
.'cache-hez: `php artisan cache:clear`.';
|
||||
}
|
||||
|
||||
if (str_contains($warning['title'], 'composer')) {
|
||||
$steps[] = 'Futtasd a célgépen: `composer install --no-dev` (a vendor/ nincs a csomagban)';
|
||||
}
|
||||
|
||||
if (str_contains($warning['title'], 'Frontend')) {
|
||||
$steps[] = 'A fordított assetek NINCSENEK a csomagban (`.gitignore`) — `npm run build` után kézzel másold fel a `public/build` tartalmát.';
|
||||
}
|
||||
|
||||
// A restart lépéseket külön gyűjtjük: azoknak a cache ürítés UTÁN kell jönniük,
|
||||
// különben a frissen induló worker még a régi, cache-elt konfigot tölti be.
|
||||
if (str_contains($warning['title'], 'Hosszan futó')) {
|
||||
$commands = $this->targets->restartCommands($target['key']);
|
||||
|
||||
if ($commands !== []) {
|
||||
$restartSteps[] = 'Utolsó lépésként indítsd újra a hosszan futó konténereket. A queue worker és a '
|
||||
.'scheduler **a memóriájában tartja a betöltött kódot**, ezért a fájlmásolás önmagában NEM elég — '
|
||||
."enélkül a háttérfeladatok némán a régi viselkedést hozzák:\n\n"
|
||||
." ```bash\n ".implode("\n ", $commands)."\n ```";
|
||||
}
|
||||
|
||||
if ($target['services_note']) {
|
||||
$restartSteps[] = $target['services_note'];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$steps[] = 'Ürítsd a cache-t: `php artisan config:clear && php artisan view:clear && php artisan route:clear`';
|
||||
|
||||
foreach ($restartSteps as $restartStep) {
|
||||
$steps[] = $restartStep;
|
||||
}
|
||||
|
||||
$steps[] = 'Ellenőrizd a kirakott verziót: `curl https://'.$target['domain'].'/deploy-version.json`'
|
||||
.' — a commitnak `'.substr((string) $manifest['to'], 0, 7).'` kell lennie.';
|
||||
|
||||
$lines = [
|
||||
'# Teendők — '.$manifest['name'],
|
||||
'',
|
||||
'| | |',
|
||||
'|---|---|',
|
||||
'| Célkörnyezet | '.$target['label'].' |',
|
||||
'| Cél útvonal | `'.$target['remote_path'].'` |',
|
||||
'| Tartomány | `'.substr((string) $manifest['from'], 0, 7).'` → `'.substr((string) $manifest['to'], 0, 7).'` |',
|
||||
'| Fájlok | '.$manifest['counts']['copied'].' másolandó, '.$manifest['counts']['deleted'].' törlendő |',
|
||||
'',
|
||||
];
|
||||
|
||||
foreach ($steps as $index => $step) {
|
||||
$lines[] = ($index + 1).'. '.$step;
|
||||
}
|
||||
|
||||
if ($manifest['missing'] !== []) {
|
||||
$lines[] = '';
|
||||
$lines[] = '> **Figyelem:** '.$manifest['counts']['missing'].' fájl nem került a csomagba, '
|
||||
.'a listájuk a `_MANIFEST.txt` végén van. Ezeket ellenőrizd, mielőtt feltöltesz.';
|
||||
}
|
||||
|
||||
$this->put($path.'/_TEENDOK.md', implode("\n", $lines)."\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Törlő szkript nagyobb mennyiséghez - a kézi törlés (_TORLENDO.txt) marad az alapeset.
|
||||
*
|
||||
* Ezért alapból csak kilistáz, a tényleges törléshez explicit --confirm kell; és mivel
|
||||
* Windowson generáljuk Linux célgépre, LF sorvéggel és BOM nélkül kell kiírni, különben
|
||||
* a shebang sor törik el.
|
||||
*
|
||||
* @param array<string, mixed> $manifest
|
||||
* @param array<string, mixed> $target
|
||||
*/
|
||||
private function writeDeleteScript(string $path, array $manifest, array $target): void
|
||||
{
|
||||
$lines = [
|
||||
'#!/usr/bin/env bash',
|
||||
'# '.$manifest['name'].' - a célgépen törlendő fájlok ('.$target['label'].')',
|
||||
'# Futtatás az app gyökeréből:',
|
||||
'# bash _torles.sh -> csak kilistázza (dry run)',
|
||||
'# bash _torles.sh --confirm -> ténylegesen töröl',
|
||||
'set -euo pipefail',
|
||||
'',
|
||||
'[[ -f artisan && -d app ]] || { echo "HIBA: nem az app gyökerében futsz"; exit 1; }',
|
||||
'',
|
||||
'CONFIRM=0',
|
||||
'[[ "${1:-}" == "--confirm" ]] && CONFIRM=1',
|
||||
'',
|
||||
'FILES=(',
|
||||
];
|
||||
|
||||
foreach ($manifest['deleted'] as $deleted) {
|
||||
$lines[] = ' "'.$deleted.'"';
|
||||
}
|
||||
|
||||
$lines = array_merge($lines, [
|
||||
')',
|
||||
'',
|
||||
'if (( ${#FILES[@]} == 0 )); then echo "Nincs törlendő fájl."; exit 0; fi',
|
||||
'',
|
||||
'for f in "${FILES[@]}"; do',
|
||||
' case "$f" in /*|*..*) echo "KIHAGYVA (gyanús útvonal): $f"; continue ;; esac',
|
||||
' [[ -f "$f" ]] || { echo "NINCS MEG: $f"; continue; }',
|
||||
' if (( CONFIRM )); then rm -f -- "$f"; echo "TÖRÖLVE: $f"; else echo "TÖRÖLNÉ: $f"; fi',
|
||||
'done',
|
||||
'',
|
||||
'if (( ! CONFIRM )); then echo; echo "Ez csak lista volt. Tényleges törlés: bash _torles.sh --confirm"; fi',
|
||||
]);
|
||||
|
||||
$this->put($path.'/_torles.sh', implode("\n", $lines)."\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* A kész mappa ZIP-be csomagolása letöltéshez és archiváláshoz.
|
||||
*/
|
||||
private function createZip(string $path, string $name): ?string
|
||||
{
|
||||
$entries = [];
|
||||
|
||||
foreach ($this->files->allFiles($path, true) as $file) {
|
||||
$entries[str_replace('\\', '/', $file->getRelativePathname())] = $file->getPathname();
|
||||
}
|
||||
|
||||
if ($entries === []) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$zipPath = $path.DIRECTORY_SEPARATOR.$name.'.zip';
|
||||
$zip = new ZipArchive;
|
||||
|
||||
if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
|
||||
throw new RuntimeException('A ZIP fájl nem hozható létre.');
|
||||
}
|
||||
|
||||
foreach ($entries as $relative => $absolute) {
|
||||
$zip->addFile($absolute, $relative);
|
||||
}
|
||||
|
||||
$zip->close();
|
||||
|
||||
return $zipPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* A csomagban lévő seeder fájlok osztálynevei.
|
||||
*
|
||||
* @param array<string, mixed> $manifest
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function seederClasses(array $manifest): array
|
||||
{
|
||||
/** @var array<int, string> $patterns */
|
||||
$patterns = (array) config('deployment.attention.seeder', []);
|
||||
|
||||
$classes = [];
|
||||
|
||||
foreach ($manifest['files'] as $file) {
|
||||
if (Str::is($patterns, $file['path'])) {
|
||||
$classes[] = pathinfo($file['path'], PATHINFO_FILENAME);
|
||||
}
|
||||
}
|
||||
|
||||
return $classes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mindig LF sorvéggel írunk: a csomag Windowson készül, de Linux célgépre megy.
|
||||
*/
|
||||
private function put(string $path, string $contents): void
|
||||
{
|
||||
$directory = dirname($path);
|
||||
|
||||
if (! $this->files->isDirectory($directory)) {
|
||||
$this->files->makeDirectory($directory, 0775, true);
|
||||
}
|
||||
|
||||
$this->files->put($path, str_replace("\r\n", "\n", $contents));
|
||||
}
|
||||
}
|
||||
@ -1,88 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Deployment;
|
||||
|
||||
/**
|
||||
* A célkörnyezetek (e2e, d2d) feloldása a config/deployment.php-ból.
|
||||
*
|
||||
* A target nem utólagos címke: már a csomagoláskor rögzül, mert befolyásolja a
|
||||
* mappanevet, a teendők listáját, a kezdő commit előtöltését és a naplót is.
|
||||
*/
|
||||
class DeploymentTargets
|
||||
{
|
||||
/**
|
||||
* @return array<string, array{key:string, label:string, domain:string, remote_path:string, expected_branch:?string, services:array<string, string>, services_note:?string}>
|
||||
*/
|
||||
public function all(): array
|
||||
{
|
||||
/** @var array<string, array<string, mixed>> $targets */
|
||||
$targets = (array) config('deployment.targets', []);
|
||||
|
||||
$resolved = [];
|
||||
|
||||
foreach ($targets as $key => $target) {
|
||||
$resolved[$key] = array_merge(
|
||||
[
|
||||
'label' => $key,
|
||||
'domain' => '',
|
||||
'remote_path' => '',
|
||||
'expected_branch' => null,
|
||||
'services' => [],
|
||||
'services_note' => null,
|
||||
],
|
||||
$target,
|
||||
['key' => $key],
|
||||
);
|
||||
}
|
||||
|
||||
return $resolved;
|
||||
}
|
||||
|
||||
/**
|
||||
* A célkörnyezet hosszan futó service-einek újraindító parancsai.
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public function restartCommands(?string $key): array
|
||||
{
|
||||
$target = $this->find($key);
|
||||
|
||||
if (! $target || $target['services'] === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$user = (string) config('deployment.swarm.user', 'root');
|
||||
$host = (string) config('deployment.swarm.host');
|
||||
|
||||
return array_values(array_map(
|
||||
fn (string $service): string => sprintf(
|
||||
'ssh %s@%s "docker service update --force %s"',
|
||||
$user,
|
||||
$host,
|
||||
$service,
|
||||
),
|
||||
$target['services'],
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{key:string, label:string, domain:string, remote_path:string, expected_branch:?string, services:array<string, string>, services_note:?string}|null
|
||||
*/
|
||||
public function find(?string $key): ?array
|
||||
{
|
||||
return $key ? ($this->all()[$key] ?? null) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function options(): array
|
||||
{
|
||||
return array_map(fn (array $target): string => $target['label'], $this->all());
|
||||
}
|
||||
|
||||
public function defaultKey(): ?string
|
||||
{
|
||||
return array_key_first($this->all());
|
||||
}
|
||||
}
|
||||
@ -1,400 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Deployment;
|
||||
|
||||
use RuntimeException;
|
||||
use Symfony\Component\Process\Process;
|
||||
use ZipArchive;
|
||||
|
||||
/**
|
||||
* Csak olvasó git wrapper a deployment csomagolóhoz.
|
||||
*
|
||||
* Minden hívás argumentum-tömbbel megy a Symfony Process-nek, soha nem shell-stringgel,
|
||||
* így a felületről érkező érték nem tud parancsot injektálni. Ettől függetlenül minden
|
||||
* bemenetet külön is validálunk: a git a kötőjellel kezdődő értéket kapcsolóként
|
||||
* értelmezné, a `..` pedig commit-tartományt jelent, nem fájlnevet.
|
||||
*/
|
||||
class GitRepository
|
||||
{
|
||||
/** Mezőelválasztó a git log formátumban (ASCII unit separator). */
|
||||
private const FIELD_SEPARATOR = "\x1f";
|
||||
|
||||
/** Rekordelválasztó a git log formátumban (ASCII record separator). */
|
||||
private const RECORD_SEPARATOR = "\x1e";
|
||||
|
||||
private const COMMIT_PATTERN = '/^[0-9a-f]{7,40}$/';
|
||||
|
||||
private const REFERENCE_PATTERN = '#^[A-Za-z0-9][A-Za-z0-9._/-]*$#';
|
||||
|
||||
public function isAvailable(): bool
|
||||
{
|
||||
try {
|
||||
$this->run(['rev-parse', '--git-dir']);
|
||||
|
||||
return true;
|
||||
} catch (RuntimeException) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public function currentBranch(): ?string
|
||||
{
|
||||
try {
|
||||
$branch = trim($this->run(['rev-parse', '--abbrev-ref', 'HEAD']));
|
||||
} catch (RuntimeException) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return ($branch === '' || $branch === 'HEAD') ? null : $branch;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public function branches(): array
|
||||
{
|
||||
$output = $this->run([
|
||||
'for-each-ref',
|
||||
'--format=%(refname:short)',
|
||||
'--sort=-committerdate',
|
||||
'refs/heads',
|
||||
'refs/remotes',
|
||||
]);
|
||||
|
||||
return collect(explode("\n", $output))
|
||||
->map(fn (string $line): string => trim($line))
|
||||
->filter()
|
||||
// Az "origin/HEAD" csak egy mutató az alapértelmezett branchre, nem önálló ág.
|
||||
->reject(fn (string $branch): bool => str_ends_with($branch, '/HEAD'))
|
||||
->unique()
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* Commitlista egy referenciáról, legfrissebbtől visszafelé.
|
||||
*
|
||||
* A törzset (%b) is elkérjük, mert a felületen erre is lehet keresni - a commit
|
||||
* üzenet érdemi része nálunk gyakran a törzsben van, nem a tárgysorban.
|
||||
*
|
||||
* A --shortstat miatt minden commit után megjelenik a "N files changed" sor is,
|
||||
* ezt az utolsó mezőből bányásszuk ki - így nem kell commitonként külön git hívás
|
||||
* a fájlszámhoz.
|
||||
*
|
||||
* @return array<int, array{hash:string, short:string, author:string, date:string, subject:string, body:string, file_count:?int}>
|
||||
*/
|
||||
public function commits(string $reference, int $limit): array
|
||||
{
|
||||
$this->assertReference($reference);
|
||||
|
||||
$format = self::RECORD_SEPARATOR.implode(self::FIELD_SEPARATOR, ['%H', '%h', '%an', '%aI', '%s', '%b']);
|
||||
|
||||
$output = $this->run([
|
||||
'log',
|
||||
'--max-count='.max(1, min($limit, 500)),
|
||||
'--no-merges',
|
||||
'--shortstat',
|
||||
'--pretty=format:'.$format,
|
||||
$reference,
|
||||
'--',
|
||||
]);
|
||||
|
||||
$commits = [];
|
||||
|
||||
foreach (explode(self::RECORD_SEPARATOR, $output) as $record) {
|
||||
if (trim($record) === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$fields = explode(self::FIELD_SEPARATOR, $record, 6);
|
||||
|
||||
if (count($fields) < 6) {
|
||||
continue;
|
||||
}
|
||||
|
||||
[$hash, $short, $author, $date, $subject, $tail] = $fields;
|
||||
|
||||
// A --shortstat sora a törzs UTÁN érkezik, ezért előbb leválasztjuk róla:
|
||||
// enélkül a "3 files changed" szöveg a keresésbe és a törzsbe is beszivárogna.
|
||||
$fileCount = null;
|
||||
|
||||
if (preg_match('/\n\s*(\d+)\s+files?\s+changed[^\n]*\n?$/', $tail, $matches) === 1) {
|
||||
$fileCount = (int) $matches[1];
|
||||
$tail = substr($tail, 0, -strlen($matches[0]));
|
||||
}
|
||||
|
||||
$commits[] = [
|
||||
'hash' => $hash,
|
||||
'short' => $short,
|
||||
'author' => $author,
|
||||
'date' => $date,
|
||||
'subject' => trim($subject),
|
||||
'body' => trim($tail),
|
||||
'file_count' => $fileCount,
|
||||
];
|
||||
}
|
||||
|
||||
return $commits;
|
||||
}
|
||||
|
||||
/**
|
||||
* Teljes hash, ha a megadott érték létező commitra mutat - különben null.
|
||||
*/
|
||||
public function resolveCommit(string $hash): ?string
|
||||
{
|
||||
if (preg_match(self::COMMIT_PATTERN, $hash) !== 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
$resolved = trim($this->run(['rev-parse', '--verify', '--quiet', $hash.'^{commit}']));
|
||||
} catch (RuntimeException) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $resolved === '' ? null : $resolved;
|
||||
}
|
||||
|
||||
/**
|
||||
* Őse-e az első commit a másodiknak? (Fordított tartomány felismeréséhez.)
|
||||
*/
|
||||
public function isAncestor(string $ancestor, string $descendant): bool
|
||||
{
|
||||
if (! $this->resolveCommit($ancestor) || ! $this->resolveCommit($descendant)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// A merge-base 1-es kilépési kóddal jelzi a "nem őse" esetet, ez nem hiba,
|
||||
// ezért itt nem a run() dobó változatát használjuk.
|
||||
return $this->process(['merge-base', '--is-ancestor', $ancestor, $descendant])->run() === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* A két commit között változott fájlok (from kizárva, to beleértve).
|
||||
*
|
||||
* @return array<int, array{status:string, path:string, old_path:?string}>
|
||||
*/
|
||||
public function changedFiles(string $from, string $to): array
|
||||
{
|
||||
$fromHash = $this->resolveCommit($from);
|
||||
$toHash = $this->resolveCommit($to);
|
||||
|
||||
if (! $fromHash || ! $toHash) {
|
||||
throw new RuntimeException('Ismeretlen commit azonosító.');
|
||||
}
|
||||
|
||||
// A core.quotePath=false nélkül a git a nem-ASCII fájlneveket idézőjelbe teszi
|
||||
// és oktálisan escape-eli ("app/\303\251kezet.php") - ékezetes útvonalaknál ez
|
||||
// használhatatlan lenne.
|
||||
$output = $this->run([
|
||||
'-c', 'core.quotePath=false',
|
||||
'diff',
|
||||
'--name-status',
|
||||
'--find-renames',
|
||||
$fromHash.'..'.$toHash,
|
||||
'--',
|
||||
]);
|
||||
|
||||
$files = [];
|
||||
|
||||
foreach (explode("\n", $output) as $line) {
|
||||
$line = rtrim($line, "\r\n");
|
||||
|
||||
if ($line === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$parts = explode("\t", $line);
|
||||
$status = strtoupper(substr($parts[0], 0, 1));
|
||||
|
||||
// Átnevezés (R) és másolás (C) esetén két útvonal jön: régi és új.
|
||||
$isTwoPath = in_array($status, ['R', 'C'], true) && count($parts) >= 3;
|
||||
$path = $isTwoPath ? $parts[2] : ($parts[1] ?? '');
|
||||
$oldPath = $isTwoPath ? $parts[1] : null;
|
||||
|
||||
if (! $this->isSafePath($path) || ($oldPath !== null && ! $this->isSafePath($oldPath))) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$files[] = [
|
||||
'status' => $status,
|
||||
'path' => $path,
|
||||
'old_path' => $oldPath,
|
||||
];
|
||||
}
|
||||
|
||||
usort($files, fn (array $a, array $b): int => strcmp($a['path'], $b['path']));
|
||||
|
||||
return $files;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hány commit van a kettő között (from kizárva, to beleértve).
|
||||
*
|
||||
* A környezetek lemaradásának kimutatásához: "az e2e 7 committal van elmaradva".
|
||||
*/
|
||||
public function countCommitsBetween(string $from, string $to): ?int
|
||||
{
|
||||
$fromHash = $this->resolveCommit($from);
|
||||
|
||||
if (! $fromHash) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
$this->assertReference($to);
|
||||
$count = trim($this->run(['rev-list', '--count', $fromHash.'..'.$to, '--']));
|
||||
} catch (RuntimeException) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return is_numeric($count) ? (int) $count : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A megadott commit szerinti fájltartalmat írja ki a célmappába, relatív útvonalakat megőrizve.
|
||||
*
|
||||
* Szándékosan a git objektumtárból dolgozunk (git archive) és nem a working tree-ből:
|
||||
* így garantáltan a commitolt állapot kerül a csomagba (nem szivárog ki félkész
|
||||
* módosítás), és a .gitattributes `text=auto eol=lf` miatt LF sorvégekkel, ami a
|
||||
* Linux célgépeknek kell - a working tree másolása ezt egyik esetben sem garantálná.
|
||||
*
|
||||
* @param array<int, string> $paths
|
||||
* @return array<int, string> a ténylegesen kiírt útvonalak
|
||||
*/
|
||||
public function archiveTo(string $commit, array $paths, string $targetDirectory): array
|
||||
{
|
||||
// Pathspec nélkül a git archive a TELJES fát csomagolná - üres listánál ezért
|
||||
// nem hívhatjuk meg egyáltalán.
|
||||
if ($paths === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$resolved = $this->resolveCommit($commit);
|
||||
|
||||
if (! $resolved) {
|
||||
throw new RuntimeException('Ismeretlen commit azonosító.');
|
||||
}
|
||||
|
||||
$written = [];
|
||||
|
||||
// Az útvonalak argumentumként mennek: Windowson a CreateProcess parancssora
|
||||
// ~32 000 karakter, ezért darabolunk.
|
||||
foreach (array_chunk($paths, 100) as $chunk) {
|
||||
$archivePath = tempnam(sys_get_temp_dir(), 'deployment-archive-');
|
||||
|
||||
if ($archivePath === false) {
|
||||
throw new RuntimeException('Nem hozható létre ideiglenes fájl a csomagoláshoz.');
|
||||
}
|
||||
|
||||
try {
|
||||
$this->run(array_merge(
|
||||
['archive', '--format=zip', '--output='.$archivePath, $resolved, '--'],
|
||||
$chunk,
|
||||
));
|
||||
|
||||
$written = array_merge($written, $this->extract($archivePath, $targetDirectory));
|
||||
} finally {
|
||||
@unlink($archivePath);
|
||||
}
|
||||
}
|
||||
|
||||
return $written;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function extract(string $archivePath, string $targetDirectory): array
|
||||
{
|
||||
$zip = new ZipArchive;
|
||||
|
||||
if ($zip->open($archivePath) !== true) {
|
||||
throw new RuntimeException('A git archive kimenete nem nyitható meg.');
|
||||
}
|
||||
|
||||
$entries = [];
|
||||
|
||||
try {
|
||||
for ($index = 0; $index < $zip->numFiles; $index++) {
|
||||
$name = $zip->getNameIndex($index);
|
||||
|
||||
if ($name === false || str_ends_with($name, '/')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// A célmappából kimutató bejegyzés nem fordulhat elő valódi git archive-ban,
|
||||
// de a kiírás előtti ellenőrzés olcsó - és ez az egyetlen pont, ahol az
|
||||
// alkalmazás a repón kívülre írhatna.
|
||||
if (! $this->isSafePath($name)) {
|
||||
throw new RuntimeException(sprintf('Gyanús útvonal a csomagban: %s', $name));
|
||||
}
|
||||
|
||||
$entries[] = $name;
|
||||
}
|
||||
|
||||
if ($entries !== [] && ! $zip->extractTo($targetDirectory, $entries)) {
|
||||
throw new RuntimeException('A fájlok kicsomagolása nem sikerült.');
|
||||
}
|
||||
} finally {
|
||||
$zip->close();
|
||||
}
|
||||
|
||||
return $entries;
|
||||
}
|
||||
|
||||
/**
|
||||
* A repo gyökeréből ki nem mutató, relatív útvonal-e.
|
||||
*/
|
||||
private function isSafePath(string $path): bool
|
||||
{
|
||||
if ($path === '' || str_starts_with($path, '/') || str_contains($path, "\0")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Windows meghajtó-előtag (C:/...) és szülőkönyvtár-hivatkozás sem fordulhat elő
|
||||
// valódi git útvonalban, viszont fájlkiírásnál kitörhetne a célmappából.
|
||||
return preg_match('#^[A-Za-z]:#', $path) !== 1
|
||||
&& preg_match('#(^|/)\.\.(/|$)#', $path) !== 1;
|
||||
}
|
||||
|
||||
private function assertReference(string $reference): void
|
||||
{
|
||||
if (preg_match(self::REFERENCE_PATTERN, $reference) !== 1 || str_contains($reference, '..')) {
|
||||
throw new RuntimeException(sprintf('Érvénytelen git referencia: %s', $reference));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $arguments
|
||||
*/
|
||||
private function process(array $arguments): Process
|
||||
{
|
||||
return new Process(
|
||||
array_merge([(string) config('deployment.git_binary') ?: 'git'], $arguments),
|
||||
(string) config('deployment.repo_path') ?: base_path(),
|
||||
null,
|
||||
null,
|
||||
(float) config('deployment.timeout', 60),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $arguments
|
||||
*/
|
||||
private function run(array $arguments): string
|
||||
{
|
||||
$process = $this->process($arguments);
|
||||
$process->run();
|
||||
|
||||
if (! $process->isSuccessful()) {
|
||||
throw new RuntimeException(sprintf(
|
||||
'A git parancs hibára futott (%s): %s',
|
||||
implode(' ', $arguments),
|
||||
trim($process->getErrorOutput()) ?: trim($process->getOutput()),
|
||||
));
|
||||
}
|
||||
|
||||
return $process->getOutput();
|
||||
}
|
||||
}
|
||||
@ -1,53 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\FeatureFlag;
|
||||
use App\Models\FeatureFlagOverride;
|
||||
use App\Models\User;
|
||||
use Laravel\Pennant\Feature;
|
||||
|
||||
class FeatureFlagRegistrar
|
||||
{
|
||||
/**
|
||||
* Regisztrálja az összes adatbázisban tárolt feature flaget a Pennant-ban.
|
||||
*
|
||||
* Az egyéni felhasználói felülbírálásokat szándékosan NEM a Pennant saját
|
||||
* tárolóján (Feature::for($user)->activate()) keresztül kezeljük, mert a
|
||||
* Pennant purge() minden scope-ra töröl egy adott flag névre - egy admin
|
||||
* mentés (pl. enabled kikapcsolása) így törölné az explicit felülbírálásokat
|
||||
* is. Ezért az override-okat saját táblában tároljuk, a resolver pedig ezt
|
||||
* nézi meg elsőként; a Pennant tárolója így csak a szabály-alapú
|
||||
* alapértelmezett feloldást cache-eli, amit bármikor biztonságos purge-elni.
|
||||
*/
|
||||
public function registerAll(): void
|
||||
{
|
||||
FeatureFlag::all()->each(function (FeatureFlag $flag) {
|
||||
Feature::define($flag->name, function (?User $user) use ($flag) {
|
||||
if ($user) {
|
||||
$override = FeatureFlagOverride::where('feature_flag_id', $flag->id)
|
||||
->where('user_id', $user->id)
|
||||
->first();
|
||||
|
||||
if ($override) {
|
||||
return $override->active;
|
||||
}
|
||||
}
|
||||
|
||||
if (! $flag->enabled) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($flag->stages && ! in_array(config('app.stage'), $flag->stages, true)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($flag->roles && (! $user || ! $user->hasRole($flag->roles))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -1,33 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
/**
|
||||
* A Mary-Ker API (EV3-461) naplója: storage/logs/maryker-*.log (a `maryker` csatorna).
|
||||
*/
|
||||
class MaryKerLogger
|
||||
{
|
||||
/** Egy ismétlődő eseményt (pl. egy rendelés, ami minden lekérésnél kimarad) legfeljebb ennyi másodpercenként naplózunk újra. */
|
||||
public const REPEAT_AFTER = 3600;
|
||||
|
||||
/** @return LoggerInterface */
|
||||
public static function channel()
|
||||
{
|
||||
return Log::channel('maryker');
|
||||
}
|
||||
|
||||
/**
|
||||
* Naplóz, de ugyanazt a kulcsú eseményt csak REPEAT_AFTER másodpercenként: az Apolló rendszeresen lekérdez,
|
||||
* és a hiba addig fennáll, amíg valaki ki nem javítja az adatot — így nem telik meg a napló, de nem is tűnik el.
|
||||
*/
|
||||
public static function once(string $level, string $key, string $message, array $context = []): void
|
||||
{
|
||||
if (Cache::add('maryker:log:' . $key, true, self::REPEAT_AFTER)) {
|
||||
self::channel()->{$level}($message, $context);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,124 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\OrderArchive;
|
||||
use App\Models\OrderArchivesItem;
|
||||
use App\Models\ProfitCenterSupplierCode;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* Eldönti, hogy a beszállító feldolgozatlan rendelései közül melyek adhatók ki a Mary-Ker API-n (EV3-461).
|
||||
*
|
||||
* Egy rendelés kimarad, ha Apolló nem tudná helyesen feldolgozni:
|
||||
* 1. a rendelésazonosítója (humanId) üres, vagy hosszabb a megengedettnél (specifikáció 5. pont);
|
||||
* 2. a telephelyéhez nincs beszállítói vevőkód (specifikáció 3.2 pont);
|
||||
* 3. van olyan tétele, aminek nincs beszállítói cikkszáma (specifikáció 3.3 pont): a tétel szó nélküli elhagyása
|
||||
* a fejléc összegével nem egyező rendelést adna.
|
||||
*
|
||||
* A kimaradást hibaként naplózzuk a maryker csatornán (rendelésenként óránként egyszer, ld. MaryKerLogger::once),
|
||||
* és csak az első találó okot: ha a hiba megszűnik, a rendelés a következő lekéréskor megjelenik.
|
||||
*
|
||||
* Szándékosan egyetlen "feldolgozatlan" lekérdezés és PHP-oldali szűrés, nem rendelésenkénti alkérdések: az
|
||||
* order_archives és az order_archives_items táblán nincs index (backlog B-03), így minden korrelált alkérdés
|
||||
* végigolvasná a több százezer / milliós táblát.
|
||||
*/
|
||||
class MaryKerOrderEligibility
|
||||
{
|
||||
/** Egy lekérésnél legfeljebb ennyi kihagyott rendelést naplózunk kategóriánként. */
|
||||
private const MAX_LOGGED = 500;
|
||||
|
||||
/**
|
||||
* @return array<int, int> a kiadható rendelések azonosítói, növekvő sorrendben
|
||||
*/
|
||||
public function eligibleOrderIds(int $supplierId): array
|
||||
{
|
||||
$pending = OrderArchive::query()
|
||||
->where('supplier_id', $supplierId)
|
||||
->whereNotNull('confirmed')
|
||||
->whereNull('APIConfirmed')
|
||||
->orderBy('id')
|
||||
->get(['id', 'humanId', 'profit_center_id']);
|
||||
|
||||
$pending = $this->withValidOrderId($pending);
|
||||
$pending = $this->withCustomerCode($pending, $supplierId);
|
||||
$pending = $this->withProductNumbers($pending);
|
||||
|
||||
return $pending->pluck('id')->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, OrderArchive> $orders
|
||||
* @return Collection<int, OrderArchive>
|
||||
*/
|
||||
private function withValidOrderId(Collection $orders): Collection
|
||||
{
|
||||
$max = (int) config('maryker.order_id_max_length');
|
||||
[$valid, $invalid] = $orders->partition(
|
||||
fn (OrderArchive $order) => $order->humanId !== null && $order->humanId !== '' && mb_strlen($order->humanId) <= $max
|
||||
);
|
||||
|
||||
$invalid->take(self::MAX_LOGGED)->each(fn (OrderArchive $order) => MaryKerLogger::once(
|
||||
'error',
|
||||
"order-id:{$order->id}",
|
||||
'MaryKer: a rendelés kimarad az unprocessed listából, a rendelésazonosító (humanId) üres vagy hosszabb a megengedettnél',
|
||||
['orderId' => $order->id, 'humanId' => $order->humanId, 'length' => mb_strlen((string) $order->humanId), 'max' => $max],
|
||||
));
|
||||
|
||||
return $valid;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, OrderArchive> $orders
|
||||
* @return Collection<int, OrderArchive>
|
||||
*/
|
||||
private function withCustomerCode(Collection $orders, int $supplierId): Collection
|
||||
{
|
||||
if ($orders->isEmpty()) {
|
||||
return $orders;
|
||||
}
|
||||
|
||||
$withCode = ProfitCenterSupplierCode::where('supplier_id', $supplierId)
|
||||
->whereIn('profit_center_id', $orders->pluck('profit_center_id')->filter()->unique())
|
||||
->whereNotNull('customerCode')->where('customerCode', '<>', '')
|
||||
->pluck('profit_center_id')->flip();
|
||||
|
||||
[$valid, $missing] = $orders->partition(fn (OrderArchive $order) => $withCode->has($order->profit_center_id));
|
||||
|
||||
$missing->take(self::MAX_LOGGED)->each(fn (OrderArchive $order) => MaryKerLogger::once(
|
||||
'error',
|
||||
"customer-code:{$order->id}",
|
||||
'MaryKer: a rendelés kimarad az unprocessed listából, a telephelyhez nincs beszállítói vevőkód',
|
||||
['orderId' => $order->id, 'humanId' => $order->humanId, 'profitCenterId' => $order->profit_center_id],
|
||||
));
|
||||
|
||||
return $valid;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, OrderArchive> $orders
|
||||
* @return Collection<int, OrderArchive>
|
||||
*/
|
||||
private function withProductNumbers(Collection $orders): Collection
|
||||
{
|
||||
if ($orders->isEmpty()) {
|
||||
return $orders;
|
||||
}
|
||||
|
||||
$badItems = OrderArchivesItem::whereIn('order_archive_id', $orders->pluck('id'))
|
||||
->where(fn ($query) => $query->whereNull('supplierProductNumber')->orWhere('supplierProductNumber', ''))
|
||||
->get(['id', 'order_archive_id'])
|
||||
->groupBy('order_archive_id');
|
||||
|
||||
[$valid, $invalid] = $orders->partition(fn (OrderArchive $order) => ! $badItems->has($order->id));
|
||||
|
||||
$invalid->take(self::MAX_LOGGED)->each(fn (OrderArchive $order) => MaryKerLogger::once(
|
||||
'error',
|
||||
"product-number:{$order->id}",
|
||||
'MaryKer: a rendelés kimarad az unprocessed listából, van olyan tétele, aminek nincs beszállítói cikkszáma',
|
||||
['orderId' => $order->id, 'humanId' => $order->humanId, 'itemIds' => $badItems[$order->id]->pluck('id')->all()],
|
||||
));
|
||||
|
||||
return $valid;
|
||||
}
|
||||
}
|
||||
@ -1,211 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Address;
|
||||
use App\Models\OrderArchive;
|
||||
use App\Models\OrderArchivesItem;
|
||||
use App\Models\ProfitCenter;
|
||||
use App\Models\ProfitCenterSupplierCode;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* Az OrderArchive sorokból a Mary-Ker API JSON-blokkjait állítja elő (EV3-461, specifikáció 3. pont).
|
||||
*/
|
||||
class MaryKerOrderMapper
|
||||
{
|
||||
/** A válaszban szereplő számok tizedesjegyeinek maximuma. */
|
||||
private const DECIMALS = 4;
|
||||
|
||||
/**
|
||||
* A "profitCenter" blokk rendelésenként. A cím a megrendeléskor rögzített pillanatkép
|
||||
* (order_archives.deliveryAddress / deliveryAddressName), nem az élő törzsadat.
|
||||
*
|
||||
* A pillanatkép egyetlen szöveg ("{irányítószám} {város} {utca}"), az API viszont külön postCode / city / address
|
||||
* mezőt ad. A szerkezetet az élő rekordból vesszük, de csak akkor, ha az pontosan ugyanazt a címet adja ki, mint
|
||||
* a pillanatkép (azaz a cím a rendelés óta nem változott) és az irányítószáma érvényes. Egyébként a szöveget
|
||||
* bontjuk, ami becslés, ezért figyelmeztetést naplózunk.
|
||||
*
|
||||
* TODO 2.4: sellerDeliveryLocationId (szállítási alegység-azonosító) — a 2. szakasz új táblájából; addig lásd
|
||||
* sellerProfitCenterId() ideiglenes összetett értékét.
|
||||
*
|
||||
* @param Collection<int, OrderArchive> $orders
|
||||
* @return array<int, array<string, string>> rendelés id => blokk
|
||||
*/
|
||||
public function profitCenterBlocks(Collection $orders, int $supplierId): array
|
||||
{
|
||||
$profitCenterIds = $orders->pluck('profit_center_id')->filter()->unique()->values();
|
||||
|
||||
$profitCenters = ProfitCenter::withTrashed()
|
||||
->whereIn('id', $profitCenterIds)
|
||||
->with(['address' => fn ($query) => $query->orderBy('id')])
|
||||
->get()->keyBy('id');
|
||||
$customerCodes = ProfitCenterSupplierCode::where('supplier_id', $supplierId)
|
||||
->whereIn('profit_center_id', $profitCenterIds)
|
||||
->pluck('customerCode', 'profit_center_id');
|
||||
$addresses = Address::whereIn('id', $orders->pluck('deliveryAddressId')->filter()->unique())
|
||||
->get()->keyBy('id');
|
||||
|
||||
$blocks = [];
|
||||
foreach ($orders as $order) {
|
||||
$profitCenter = $profitCenters->get($order->profit_center_id);
|
||||
$live = $order->deliveryAddressId
|
||||
? $addresses->get($order->deliveryAddressId)
|
||||
: $this->profitCenterAddress($profitCenter);
|
||||
[$postCode, $city, $street] = $this->splitAddress($order, $live);
|
||||
|
||||
$blocks[$order->id] = [
|
||||
// string marad, a vezető nullák megmaradnak
|
||||
'sellerProfitCenterId' => $this->sellerProfitCenterId(
|
||||
$order, $profitCenter, (string) $customerCodes->get($order->profit_center_id)
|
||||
),
|
||||
'name' => (string) ($order->deliveryAddressName ?: $order->profit_center_name ?: $profitCenter?->name),
|
||||
'postCode' => $postCode,
|
||||
'city' => $city,
|
||||
'address' => $street,
|
||||
'contactName' => (string) $order->contactName,
|
||||
'contactEmail' => (string) $profitCenter?->email,
|
||||
'contactPhone' => (string) $profitCenter?->phone,
|
||||
'contactMobil' => (string) $profitCenter?->mobil,
|
||||
];
|
||||
}
|
||||
|
||||
return $blocks;
|
||||
}
|
||||
|
||||
/**
|
||||
* Az "items" blokk rendelésenként (specifikáció 3.3 pont).
|
||||
*
|
||||
* A sumPrice a specifikáció szerint számított: quantity * unitMultiplier * price. Figyelem: az order_archives_items
|
||||
* price oszlopa double(8,2), ezért ahol a megrendeléskori egységár több tizedesjegyű volt, a tételösszegek
|
||||
* a fejléc összegétől (order_archives.sumPrice) centekkel eltérhetnek (backlog B-11).
|
||||
*
|
||||
* @param Collection<int, OrderArchive> $orders
|
||||
* @return array<int, array<int, array<string, mixed>>> rendelés id => tételek
|
||||
*/
|
||||
public function itemBlocks(Collection $orders): array
|
||||
{
|
||||
$items = OrderArchivesItem::whereIn('order_archive_id', $orders->pluck('id'))
|
||||
->orderBy('id')
|
||||
->get(['id', 'order_archive_id', 'name', 'supplierProductNumber', 'unitMultiplier', 'sellerUnit', 'producer_name', 'quantity', 'price'])
|
||||
->groupBy('order_archive_id');
|
||||
|
||||
$blocks = [];
|
||||
foreach ($orders as $order) {
|
||||
$blocks[$order->id] = $items->get($order->id, collect())->map(fn (OrderArchivesItem $item) => [
|
||||
// string marad, a vezető nullák megmaradnak
|
||||
'sellerItemNumber' => (string) $item->supplierProductNumber,
|
||||
'name' => (string) $item->name,
|
||||
'packMultiplier' => $this->number($item->unitMultiplier),
|
||||
'packName' => (string) $item->sellerUnit,
|
||||
'producerName' => (string) $item->producer_name,
|
||||
'orderNumber' => $this->number($item->quantity),
|
||||
'price' => $this->number($item->price),
|
||||
'sumPrice' => $this->itemSum($item),
|
||||
])->values()->all();
|
||||
}
|
||||
|
||||
return $blocks;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pénzösszeg / mennyiség a partnerrel egyeztetett formátumban: legfeljebb 4 tizedesjegy (specifikáció 2. pont).
|
||||
* A tárolt double lebegőpontos zajt hordoz (pl. 258817.12149533), ezért kerekítjük.
|
||||
*/
|
||||
public function number(float|int|string|null $value): ?float
|
||||
{
|
||||
return $value === null ? null : round((float) $value, self::DECIMALS);
|
||||
}
|
||||
|
||||
private function itemSum(OrderArchivesItem $item): ?float
|
||||
{
|
||||
if ($item->quantity === null || $item->unitMultiplier === null || $item->price === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->number($item->quantity * $item->unitMultiplier * $item->price);
|
||||
}
|
||||
|
||||
/**
|
||||
* IDEIGLENES (EV3-461, 2. szakasz előtt): több szállítási címes telephelynél, ha a rendelésen van kiválasztott cím,
|
||||
* a vevőkód után "_{Address.id}" kerül; egyébként a sima vevőkód. A több címes jelzőt a megrendelő felülethez
|
||||
* hasonlóan a telephely "multiAddress" mezője adja, nem a címrekordok száma.
|
||||
*
|
||||
* Apolló ezt az értéket nem ismeri: a 2. szakaszban az Apolló által kiadott szállítási alegység-kód
|
||||
* (sellerDeliveryLocationId) váltja ki, és a sellerProfitCenterId újra a sima vevőkód lesz (backlog B-10).
|
||||
*/
|
||||
private function sellerProfitCenterId(OrderArchive $order, ?ProfitCenter $profitCenter, string $customerCode): string
|
||||
{
|
||||
if (! $profitCenter || ! (int) $profitCenter->multiAddress) {
|
||||
return $customerCode;
|
||||
}
|
||||
|
||||
if (! $order->deliveryAddressId) {
|
||||
MaryKerLogger::once('warning', "multi-address:{$order->id}", 'MaryKer: több címes telephely, de a rendelésen nincs kiválasztott szállítási cím, a sima vevőkód megy ki', [
|
||||
'orderId' => $order->id, 'humanId' => $order->humanId, 'profitCenterId' => $order->profit_center_id,
|
||||
]);
|
||||
|
||||
return $customerCode;
|
||||
}
|
||||
|
||||
return $customerCode . '_' . $order->deliveryAddressId;
|
||||
}
|
||||
|
||||
/** Ugyanazt a szabályt követi, mint a megrendelő felület (OrderController::getProfitCenterAddress). */
|
||||
private function profitCenterAddress(?ProfitCenter $profitCenter): ProfitCenter|Address|null
|
||||
{
|
||||
if (! $profitCenter) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (int) $profitCenter->addressEqual ? $profitCenter : $profitCenter->address->first();
|
||||
}
|
||||
|
||||
/** @return array{0: string, 1: string, 2: string} [irányítószám, város, utca] */
|
||||
private function splitAddress(OrderArchive $order, ProfitCenter|Address|null $live): array
|
||||
{
|
||||
$snapshot = $this->normalize($order->deliveryAddress);
|
||||
|
||||
if ($live && $this->validPostCode($live->postCode)
|
||||
&& ($snapshot === '' || $this->normalize($live->fullAddress) === $snapshot)) {
|
||||
return [trim($live->postCode), trim((string) $live->city), trim((string) $live->street)];
|
||||
}
|
||||
|
||||
if ($snapshot === '') {
|
||||
$this->warn($order, 'nincs pillanatkép-cím, és az élő cím sem használható');
|
||||
|
||||
return ['', '', ''];
|
||||
}
|
||||
|
||||
if (preg_match('/^(\d{4})\s+(\S+)\s*(.*)$/u', $snapshot, $parts)) {
|
||||
$this->warn($order, 'a pillanatkép nem azonos az élő címmel (vagy az élő cím hibás), a bontás becslés', $snapshot);
|
||||
|
||||
return [$parts[1], rtrim($parts[2], ',;'), $parts[3]];
|
||||
}
|
||||
|
||||
$this->warn($order, 'a pillanatkép-cím nem bontható irányítószámra, városra és utcára', $snapshot);
|
||||
|
||||
return ['', '', $snapshot];
|
||||
}
|
||||
|
||||
private function warn(OrderArchive $order, string $reason, ?string $snapshot = null): void
|
||||
{
|
||||
MaryKerLogger::once('warning', "address:{$order->id}", 'MaryKer: címadat-eltérés a rendelésen: ' . $reason, [
|
||||
'orderId' => $order->id,
|
||||
'humanId' => $order->humanId,
|
||||
'profitCenterId' => $order->profit_center_id,
|
||||
'deliveryAddressId' => $order->deliveryAddressId,
|
||||
'snapshot' => $snapshot ?? $order->deliveryAddress,
|
||||
]);
|
||||
}
|
||||
|
||||
private function validPostCode(?string $postCode): bool
|
||||
{
|
||||
return (bool) preg_match('/^\d{4}$/', trim((string) $postCode));
|
||||
}
|
||||
|
||||
private function normalize(?string $text): string
|
||||
{
|
||||
return trim((string) preg_replace('/\s+/u', ' ', (string) $text));
|
||||
}
|
||||
}
|
||||
@ -62,65 +62,36 @@ public function calculate(
|
||||
}
|
||||
}
|
||||
|
||||
return $this->findNextDeliveryDay($startDay, $supplier, $pc, $leadDays, $assignment);
|
||||
return $this->findNextDeliveryDay($startDay, $supplier, $pc, $leadDays);
|
||||
}
|
||||
|
||||
/**
|
||||
* Előreszámol $leadDays darab átfutási napot, majd az első olyan napot adja vissza,
|
||||
* Munkanapokban számol előre ($leadDays darabot), majd az első olyan napot adja vissza,
|
||||
* amelyik szállítási nap is.
|
||||
*
|
||||
* A szállítási nap keresése NINCS munkanaphoz kötve: hétvégi szállítást a heti sablon
|
||||
* engedhet, ezt az isDeliveryDay() dönti el (EV3-466).
|
||||
*/
|
||||
private function findNextDeliveryDay(
|
||||
Carbon $candidate,
|
||||
Supplier $supplier,
|
||||
ProfitCenter $pc,
|
||||
int $leadDays,
|
||||
ProfitCenterSupplierSchedule $assignment,
|
||||
): ?Carbon {
|
||||
$leadDaysCounted = 0;
|
||||
$workingDaysCounted = 0;
|
||||
|
||||
// Max. 365 nap iteráció (végtelen ciklus-védelem)
|
||||
for ($i = 0; $i < 365; $i++) {
|
||||
if ($leadDaysCounted >= $leadDays) {
|
||||
// Átfutási idő letelt – az első szállítási napot keressük
|
||||
if ($this->deliveryCalendarService->isDeliveryDay($pc, $supplier, $candidate, $assignment)) {
|
||||
return $candidate->copy();
|
||||
if ($this->workCalendarService->isWorkDay($candidate)) {
|
||||
if ($workingDaysCounted >= $leadDays) {
|
||||
// Átfutási idő letelt – az első szállítási napot keressük
|
||||
if ($this->deliveryCalendarService->isDeliveryDay($pc, $supplier, $candidate)) {
|
||||
return $candidate->copy();
|
||||
}
|
||||
} else {
|
||||
$workingDaysCounted++;
|
||||
}
|
||||
} elseif ($this->countsTowardLeadTime($candidate, $assignment)) {
|
||||
$leadDaysCounted++;
|
||||
}
|
||||
$candidate->addDay();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Eldönti, hogy az adott nap beleszámít-e az átfutási idő visszaszámolásába.
|
||||
*
|
||||
* A hivatalos munkanapokon túl beleszámítanak azok a hétvégi napok is, amelyeket a
|
||||
* PC-hez rendelt heti sablon szállítási napként jelöl – egy 7 napos sablonnál tehát
|
||||
* minden nap telik, egy H–P sablonnál viszont a hétvége változatlanul nem (EV3-466).
|
||||
* Munkaszüneti napon sosem telik az átfutás.
|
||||
*/
|
||||
private function countsTowardLeadTime(Carbon $date, ProfitCenterSupplierSchedule $assignment): bool
|
||||
{
|
||||
if ($this->workCalendarService->isHoliday($date)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($this->workCalendarService->isWorkDay($date)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$schedule = $assignment->deliverySchedule;
|
||||
|
||||
if (! $schedule || ! $schedule->is_active) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (bool) $schedule->{strtolower($date->format('l'))};
|
||||
}
|
||||
}
|
||||
|
||||
@ -11,7 +11,6 @@
|
||||
use App\Repositories\ProducerRepository;
|
||||
use App\Repositories\ProductRepository;
|
||||
use App\Repositories\SupplierRepository;
|
||||
use App\Support\NameNormalizer;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\MessageBag;
|
||||
|
||||
@ -23,9 +22,6 @@ class PriceListService
|
||||
|
||||
protected ProducerRepository $producerRepository;
|
||||
|
||||
/** @var array<string, array>|null normalizált gyártónév => rekord (lusta index) */
|
||||
private ?array $producersByNormalizedName = null;
|
||||
|
||||
protected ProductRepository $productRepository;
|
||||
|
||||
protected MessageBag $error;
|
||||
@ -88,7 +84,7 @@ public function getExcelFieldPointer(): array
|
||||
}
|
||||
|
||||
public const EXPECTED_HEADERS = [
|
||||
0 => 'Szálltói cikkszám',
|
||||
0 => 'Szállítói cikkszám',
|
||||
1 => 'Fő termékcsoport',
|
||||
2 => 'Alcsoport 1',
|
||||
3 => 'Alcsoport 2',
|
||||
@ -96,7 +92,7 @@ public function getExcelFieldPointer(): array
|
||||
5 => 'Kiszerelés',
|
||||
6 => 'Súly/Űrtartalom (nettó)',
|
||||
7 => 'Mértékegység',
|
||||
8 => 'Gyártó/Forgalmazó',
|
||||
8 => 'Gyártó',
|
||||
9 => 'Legkisebb eladási egység',
|
||||
10 => 'Egységszorzó',
|
||||
11 => 'Mennyiségi egység',
|
||||
@ -110,7 +106,6 @@ public function getExcelFieldPointer(): array
|
||||
19 => 'Vevői megnevezés',
|
||||
20 => 'Megjegyzés',
|
||||
21 => 'KREL',
|
||||
22 => 'Akció',
|
||||
];
|
||||
|
||||
private array $excelFieldPointer = [
|
||||
@ -136,7 +131,6 @@ public function getExcelFieldPointer(): array
|
||||
'buyerProductName' => 19,
|
||||
'note' => 20,
|
||||
'krel' => 21,
|
||||
'specialOffer' => 22,
|
||||
|
||||
];
|
||||
|
||||
@ -163,7 +157,6 @@ public function getExcelFieldPointer(): array
|
||||
'buyerProductName' => ['string'], // 19
|
||||
'note' => ['string'], // 20
|
||||
'krel' => ['string'], // 21
|
||||
'specialOffer' => ['string'], // 22
|
||||
];
|
||||
|
||||
private array $excelFieldConverter = [
|
||||
@ -172,7 +165,6 @@ public function getExcelFieldPointer(): array
|
||||
'vat' => ['percentage'],
|
||||
'note' => ['null'],
|
||||
'krel' => ['booleanCustom'],
|
||||
'specialOffer' => ['booleanCustom'],
|
||||
'hooreycaId' => ['null'],
|
||||
'HooreycaUnit' => ['null'],
|
||||
'HooreycaMultiplier' => ['null'],
|
||||
@ -571,7 +563,6 @@ private function loadProducers(?string $index = null)
|
||||
$this->producerIndexedBy = $index;
|
||||
}
|
||||
$this->producers = $this->producerRepository->allByIndex($index);
|
||||
$this->producersByNormalizedName = null;
|
||||
|
||||
}
|
||||
|
||||
@ -582,32 +573,7 @@ private function getProducerByName($name)
|
||||
return $this->producers[$name];
|
||||
}
|
||||
|
||||
// Normalizált egyeztetés, ha a karakterre pontos találat elmarad.
|
||||
//
|
||||
// A beszállítói Excelekben a gyártó neve rendszeresen eltérő kis/nagybetűvel
|
||||
// vagy fölösleges szóközzel érkezik ("Danone " vs "Danone"). Korábban ilyenkor
|
||||
// ÚJ gyártó jött létre - így halmozódott fel a rendszerben 70 duplikált név,
|
||||
// ami az árlista feldolgozóban hamis módosulást, a statisztikában pedig hiányzó
|
||||
// tételeket okozott (egy névre szűrve a másik ID alá könyvelt sorok kimaradtak).
|
||||
$normalized = NameNormalizer::normalize((string) $name);
|
||||
|
||||
if ($normalized === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($this->producersByNormalizedName === null) {
|
||||
$this->producersByNormalizedName = [];
|
||||
|
||||
foreach ($this->producers as $producerName => $producer) {
|
||||
// Az ELSŐ előfordulás nyer: a Producer::all() id szerint jön, tehát a
|
||||
// legrégebbi rekord a kanonikus - jellemzően az, amelyikre a termékek
|
||||
// többsége mutat.
|
||||
$key = NameNormalizer::normalize((string) $producerName);
|
||||
$this->producersByNormalizedName[$key] ??= $producer;
|
||||
}
|
||||
}
|
||||
|
||||
return $this->producersByNormalizedName[$normalized] ?? false;
|
||||
return false;
|
||||
}
|
||||
|
||||
private function initProducerRepository()
|
||||
@ -620,9 +586,6 @@ private function initProducerRepository()
|
||||
private function addNewProducer($data)
|
||||
{
|
||||
$this->initProducerRepository();
|
||||
// Körülvágás mentés előtt: a nyers Excel-értékből származó záró szóköz miatt
|
||||
// keletkezett a duplikátumok egyharmada.
|
||||
$data['name'] = trim((string) ($data['name'] ?? ''));
|
||||
$data['canSee'] = 1;
|
||||
$data['status'] = \App\Enums\DbStatusFieldEnum::active;
|
||||
if ($id = $this->producerRepository->add($data)) {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,78 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Enums\PricelistFileStatusEnum;
|
||||
use App\Models\PricelistFile;
|
||||
|
||||
/**
|
||||
* Egy beszállítóhoz egyszerre legfeljebb egy "nyitott" végrehajtás tartozhat.
|
||||
*
|
||||
* Amíg egy fájl végrehajtása hibára futott (`execution_failed`), a beszállító
|
||||
* termékei félig frissített állapotban vannak: egy részük már az új árlista adatait
|
||||
* hordozza, más részük még a régit. Ha erre az állapotra új árlistát vinnénk fel, a
|
||||
* validálás ehhez a kevert állapothoz számolná a diffeket - egyes sorok tévesen
|
||||
* "rendben"-nek látszanának, mások fölöslegesen "módosítás"-nak -, az import pedig
|
||||
* egy inkonzisztens alapra rétegződne rá.
|
||||
*
|
||||
* A futó (`inprogress`) végrehajtás blokkolása még közvetlenebb: két párhuzamos
|
||||
* import ugyanarra a termékhalmazra nem determinisztikus végeredményt adna.
|
||||
*
|
||||
* FONTOS: ezt a védelmet MINDEN belépési ponton alkalmazni kell (modern Filament
|
||||
* felület, régebbi PriceListProcessor oldal, legacy admin import, konzol parancs) -
|
||||
* ha csak az űrlapot védjük, a blokkolás látszatvédelem marad, mert a beszállítókat
|
||||
* ma még nagyrészt a legacy felületen kezelik.
|
||||
*/
|
||||
class PricelistGuard
|
||||
{
|
||||
/**
|
||||
* A beszállítót blokkoló árlista fájl, ha van ilyen.
|
||||
*
|
||||
* @param int|null $exceptFileId ezt a fájlt hagyjuk figyelmen kívül (önmagát ne blokkolja)
|
||||
*/
|
||||
public function blockingFileFor(?int $supplierId, ?int $exceptFileId = null): ?PricelistFile
|
||||
{
|
||||
if (! $supplierId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return PricelistFile::query()
|
||||
->where('supplier_id', $supplierId)
|
||||
->when($exceptFileId, fn ($query) => $query->whereKeyNot($exceptFileId))
|
||||
->whereIn('status', [
|
||||
PricelistFileStatusEnum::execution_failed->value,
|
||||
PricelistFileStatusEnum::inprogress->value,
|
||||
])
|
||||
->latest('id')
|
||||
->get()
|
||||
// Az `inprogress` önmagában nem blokkol: az előfeldolgozás és a validálás
|
||||
// egyetlen terméket sem ír, ezért közben nyugodtan feltölthető másik fájl.
|
||||
// Csak az számít, ahol a végrehajtás már elindult - ezt a workflow_steps
|
||||
// JSON tartalma dönti el, amit SQL-ben nem szűrnénk tisztán, a beszállítónkénti
|
||||
// jelöltek száma viszont elenyésző.
|
||||
->first(fn (PricelistFile $file) => $file->status === PricelistFileStatusEnum::execution_failed
|
||||
|| $file->hasExecutionStarted());
|
||||
}
|
||||
|
||||
public function isBlocked(?int $supplierId, ?int $exceptFileId = null): bool
|
||||
{
|
||||
return $this->blockingFileFor($supplierId, $exceptFileId) !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Felhasználónak szóló magyarázat: melyik fájl blokkol és miért.
|
||||
*/
|
||||
public function blockingMessage(PricelistFile $blockingFile): string
|
||||
{
|
||||
$state = $blockingFile->status === PricelistFileStatusEnum::execution_failed
|
||||
? 'végrehajtása hibára futott'
|
||||
: 'végrehajtása jelenleg fut';
|
||||
|
||||
return sprintf(
|
||||
'A beszállítóhoz tartozó "%s" árlista (#%d) %s. Amíg ez nincs lezárva (folytatás vagy visszavonás), nem indítható újabb árlista-feldolgozás, mert a termékadatok félig frissített állapotban lehetnek.',
|
||||
$blockingFile->filename,
|
||||
$blockingFile->id,
|
||||
$state,
|
||||
);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user